Snapshot for release 2026.10.19.1 (internal f0bdcf8)

This commit is contained in:
Tom Bohar 2026-10-19 09:11:22 -04:00
commit 39de36d3af
131 changed files with 11266 additions and 520 deletions

View file

@ -0,0 +1,119 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
// ============================================================================
// Per-monster attack power (2026-10-12): MonsterRule.AttackPower.
//
// Default the DEFAULT line's choice; on the DEFAULT line, the global
// Melee/Missile Power settings (Auto = 100%, or 80% with Use
// Recklessness and the skill trained)
// High 100% every swing or shot
// Reckless 80%: inside the band where Recklessness adds damage (ACE:
// 10%-90% of the bar, retail wiki: 20%-80%, so 80% is in both)
// Variable a new random power each attack, Variable Power Min..Max
// Reckless + Variable random each attack, inside the Recklessness band (20%-80%)
// and the Variable range
//
// Recklessness only adds damage when the skill is trained or specialized; with it
// untrained a reckless choice falls back to High (or Variable), since a short bar
// would only cost damage. Magic doesn't use attack power.
// ============================================================================
/// <summary>Names and resolution of <see cref="MonsterRule.AttackPower"/>.</summary>
public static class AttackPowerModes
{
public const string Default = "Default";
public const string High = "High";
public const string Reckless = "Reckless";
public const string Variable = "Variable";
public const string RecklessVariable = "Reckless + Variable";
/// <summary>Every choice, in the order the editors list them.</summary>
public static readonly string[] All = { Default, High, Reckless, Variable, RecklessVariable };
/// <summary>The bar fraction a fixed reckless attack uses.</summary>
public const float RecklessPower = 0.8f;
/// <summary>The Recklessness band used for a varied reckless attack (retail wiki: 20%-80%).</summary>
public const int RecklessBandMinPct = 20;
public const int RecklessBandMaxPct = 80;
/// <summary>A saved value as one of <see cref="All"/>; blank or unknown is Default.</summary>
public static string Normalize(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return Default;
string v = value.Trim();
foreach (string m in All)
if (m.Equals(v, StringComparison.OrdinalIgnoreCase)) return m;
// Hand-typed and meta spellings: "RecklessVariable", "reckless+variable".
string squeezed = v.Replace(" ", "").Replace("+", "");
if (squeezed.Equals("RecklessVariable", StringComparison.OrdinalIgnoreCase)) return RecklessVariable;
return Default;
}
/// <summary>
/// The mode that applies to a monster: its own rule's, else the DEFAULT line's, else
/// Default (the global settings). <paramref name="defaultRule"/> may be the same object.
/// </summary>
public static string Effective(MonsterRule? rule, MonsterRule? defaultRule)
{
string own = Normalize(rule?.AttackPower);
if (own != Default) return own;
return Normalize(defaultRule?.AttackPower);
}
/// <summary>
/// The power bar fraction (0..1) for one attack.
/// <paramref name="globalPct"/> is the global Melee/Missile Power (-1 = Auto);
/// <paramref name="random01"/> returns a value in [0, 1).
/// </summary>
public static float Resolve(string mode, int globalPct, bool useRecklessness, bool recklessTrained,
int variableMinPct, int variableMaxPct, Func<double> random01)
{
switch (Normalize(mode))
{
case High:
return 1.0f;
case Reckless:
return recklessTrained ? RecklessPower : 1.0f;
case Variable:
{
var (lo, hi) = VariableRange(variableMinPct, variableMaxPct);
return Pick(lo, hi, random01);
}
case RecklessVariable:
{
var (lo, hi) = VariableRange(variableMinPct, variableMaxPct);
if (!recklessTrained) return Pick(lo, hi, random01);
int rlo = Math.Max(lo, RecklessBandMinPct);
int rhi = Math.Min(hi, RecklessBandMaxPct);
// The Variable range doesn't overlap the band (e.g. 85-100): the whole band.
if (rlo > rhi) { rlo = RecklessBandMinPct; rhi = RecklessBandMaxPct; }
return Pick(rlo, rhi, random01);
}
default:
if (globalPct < 0)
return useRecklessness && recklessTrained ? RecklessPower : 1.0f;
return Math.Clamp(globalPct, 0, 100) / 100f;
}
}
/// <summary>The Variable range in percent, clamped to 0..100 and put in order.</summary>
public static (int Lo, int Hi) VariableRange(int minPct, int maxPct)
{
int lo = Math.Clamp(minPct, 0, 100), hi = Math.Clamp(maxPct, 0, 100);
return lo <= hi ? (lo, hi) : (hi, lo);
}
private static float Pick(int loPct, int hiPct, Func<double> random01)
{
double r = Math.Clamp(random01(), 0.0, 1.0);
double pct = loPct + (hiPct - loPct) * r;
return (float)(Math.Round(pct) / 100.0);
}
}

View file

@ -24,6 +24,9 @@
// yield (MayRestartMacro), and a death drops the pending recall (the player's
// Stop Macro On Death stands).
// Health back over the line (or 100%) ends the episode. Nothing counts in portal space.
// The failsafe (jump included) is for a character that can heal: it arms only with a heal that went
// out in the last minute, or a heal spell / kit / health potion at hand (HealCapableNow). A melee
// character with nothing to heal with is not jumped or recalled. HpFailsafeRecall defaults to off.
// ============================================================================
using System;
@ -92,6 +95,9 @@ public partial class BuffManager
ResetHpFailsafe();
return;
}
// Only a character that can heal at all: a melee character with no spell, kit or potion
// (resting, or out-healed) has nothing for the failsafe to retry, and a recall there is wrong.
if (!HealCapableNow(now)) { ResetHpFailsafe(); return; }
if (!_fsActive)
{
_fsActive = true;
@ -146,6 +152,59 @@ public partial class BuffManager
StartFailsafeRecall(now, hp, failedSec);
}
// A heal (spell, kit or potion) that actually went out: the failsafe's proof the character can heal.
private DateTime _lastHealSentAt = DateTime.MinValue;
private DateTime _healCapableCheckAt = DateTime.MinValue;
private bool _healCapableCached;
/// <summary>A heal sent this recently proves the character can heal (kit used up since, a script's drain).</summary>
internal const double HealSentProofMs = 60_000;
/// <summary>Every heal that goes out (cast, kit, potion) records itself here, then feeds the latency tracker.</summary>
private void NoteHealSent(string action)
{
_lastHealSentAt = Now;
_healLatency.HealSent(Now, action);
}
/// <summary>
/// Can this character heal at all? A heal went out in the last HealSentProofMs, or one could now: a known
/// Heal Self / Stamina to Health Self with Life Magic trained, a healing kit, or a health potion
/// (Use Potions on and one listed or in the pack). Read at most once a second (it walks the pack).
/// </summary>
private bool HealCapableNow(DateTime now)
{
if (_lastHealSentAt != DateTime.MinValue && (now - _lastHealSentAt).TotalMilliseconds < HealSentProofMs) return true;
if ((now - _healCapableCheckAt).TotalMilliseconds < 1000 && _healCapableCheckAt != DateTime.MinValue) return _healCapableCached;
_healCapableCheckAt = now;
bool capable = false;
try
{
if (IsSkillUsable(AcSkillType.LifeMagic))
{
foreach (string spell in new[] { "Heal Self", "Stamina to Health Self" })
{
if (_spellManager.GetDynamicSelfBuffId(spell, AcSkillType.LifeMagic) != 0
|| _spellManager.GetSelfSpellIdAboveAllowedTier(spell, AcSkillType.LifeMagic) != 0) { capable = true; break; }
}
}
if (!capable && _worldObjectCache != null)
{
if (BestPackHealingKit() != null) capable = true;
else
{
foreach (var r in _settings.ConsumableRules)
if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase)
&& !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase)
&& ConsumableLookup.Resolve(_worldObjectCache, r) != null) { capable = true; break; }
}
if (!capable && _settings.UsePotions && HasListedPotion("HealthPotion")) capable = true;
}
}
catch { capable = false; }
_healCapableCached = capable;
return capable;
}
private void ResetHpFailsafe()
{
_fsActive = false;

View file

@ -156,6 +156,20 @@ public partial class BuffManager : IDisposable
// like any cast.
private int _pendingUpgradeSpellId;
// Consecutive SILENT no-shows of an upgrade, per family (the registry never moved / no chat for an
// item spell). An upgrade's no-show is no strike on the family (see the no-show branches), so
// without a bound a cast the server silently drops loops forever: an item enchant whose lower
// record is still on the books after the armor was lost or the weapon swapped (nothing to bind
// to), or a self-buff the server ignores. In a force/batch run that holds _isForceRebuffing, and
// with it buffing's priority over fighting, for good. After UpgradeNoShowThreshold of them the
// UPGRADE alone is parked for UpgradeParkCooldown: the family is not blacklisted or put in
// _buffFailCooldownUntil, and the level it was cast over keeps refreshing as a normal cast.
// Cleared by any confirmed cast of the family (NoteBuffConfirmed) and by Force Rebuff.
private readonly Dictionary<int, int> _upgradeNoShowCounts = new();
private readonly Dictionary<int, DateTime> _upgradeParkedUntil = new();
private const int UpgradeNoShowThreshold = 3;
private static readonly TimeSpan UpgradeParkCooldown = TimeSpan.FromMinutes(5);
// Per-family diagnostic throttle — last reason string we logged. Suppresses
// dup spam when IsBuffActive is polled every tick by NeedsAnyBuff + CheckAndCastSelfBuffs.
private readonly Dictionary<int, string> _lastArmorRecastReason = new();
@ -974,6 +988,20 @@ public partial class BuffManager : IDisposable
public void RequestForceFullRebuff() => System.Threading.Interlocked.Exchange(ref _forceRebuffRequested, 1);
public void RequestCancelBuffing() => System.Threading.Interlocked.Exchange(ref _cancelBuffingRequested, 1);
// /ra buff skipped runs on AC's chat-command thread; building the list there would write the pump's
// kit and skip fields from a second thread. The command only sets this; the pump builds and reports.
private int _skipReportRequested;
public void RequestSkipReport() => System.Threading.Interlocked.Exchange(ref _skipReportRequested, 1);
private void ReportFilterSkips()
{
BuildDynamicBuffList(); // refreshes the skip list, even with buffing off
string summary = _filterSummary;
_host.WriteToChat(summary.Length == 0
? "[RynthAi] Buff filter: nothing is being skipped."
: $"[RynthAi] Buff filter skips: {summary}", 1);
}
public void ForceFullRebuff()
{
_isForceRebuffing = true;
@ -984,8 +1012,11 @@ public partial class BuffManager : IDisposable
_unsatisfiedStrikes.Clear(); // ditto for the post-batch satisfaction audit
_castIssuedAtByFamily.Clear();
_expiryAtCastByFamily.Clear();
_upgradeNoShowCounts.Clear(); // and a fresh try at parked upgrades
_upgradeParkedUntil.Clear();
_ramBuffTimers.Clear();
_itemSpellTimers.Clear();
EndPendingUpgrade(_pendingSpellId, "a new Force Rebuff");
_pendingSpellId = 0;
_lastCastAttempt = DateTime.MinValue;
SaveBuffTimers();
@ -1005,6 +1036,7 @@ public partial class BuffManager : IDisposable
_isRechargingMana = false;
_isRechargingStamina = false;
_isHealingSelf = false;
EndPendingUpgrade(_pendingSpellId, "buffing cancelled");
_pendingSpellId = 0;
_chain.PassEnd("cancelled", s => _host.Log(s));
_host.WriteToChat("[RynthAi] Sequence cancelled.", 5);
@ -1237,6 +1269,8 @@ public partial class BuffManager : IDisposable
ForceFullRebuff();
if (System.Threading.Interlocked.Exchange(ref _cancelBuffingRequested, 0) != 0)
CancelBuffing();
if (System.Threading.Interlocked.Exchange(ref _skipReportRequested, 0) != 0)
ReportFilterSkips();
// Post-cast diffs for the bufftest experiment run unconditionally — even if the
// user toggled the macro off mid-experiment, we still want to capture and log them.
@ -1347,6 +1381,7 @@ public partial class BuffManager : IDisposable
&& CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s)) && !BusyHoldsHeal())
{
_host.Log($"[BuffDiag] health {_vitals.HealthPct}% under a heal line: released pending buff id={_pendingSpellId} to heal first.");
EndPendingUpgrade(_pendingSpellId, "released to heal");
_pendingSpellId = 0;
_onCastResolved?.Invoke("released to heal");
}
@ -1444,6 +1479,7 @@ public partial class BuffManager : IDisposable
if (isUpgrade)
{
_host.Log($"[BuffDiag] upgrade '{pendingSpell.Name}' (id={_pendingSpellId}, fam={fam}) not in the live registry after {sinceCastMs:0}ms (the lower level is unchanged): no strike, tried again.");
NoteUpgradeNoShow(_pendingSpellId); // bounded: parks the upgrade (only) after UpgradeNoShowThreshold in a row
}
else
{
@ -1493,6 +1529,8 @@ public partial class BuffManager : IDisposable
bool confirmedKnown = _spellManager.IsKnownSnapshotWarm && _spellManager.IsKnownSpellId(stuckId);
if (!confirmedKnown && !isUpgrade)
_spellManager.MarkSpellUnresolvable(stuckId);
if (isUpgrade)
NoteUpgradeNoShow(stuckId); // bounded: parks the upgrade (only) after UpgradeNoShowThreshold in a row
// 2026-05-25 — per-family silent-no-show bookkeeping on the
// ARMOR path, mirroring the self-buff path above.
@ -2241,7 +2279,7 @@ public partial class BuffManager : IDisposable
if (_pendingVitalLabel == LabelHealing)
{
_healSpellIds.Add(spellId);
_healLatency.HealSent(Now, what);
NoteHealSent(what);
}
return true;
}
@ -2292,7 +2330,7 @@ public partial class BuffManager : IDisposable
_host.UseFor(unchecked((uint)potion.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list");
_lastPotionAt = DateTime.Now;
_lastCastAttempt = DateTime.Now;
if (IsHealthPotionType(types)) _healLatency.HealSent(Now, rule.Name);
if (IsHealthPotionType(types)) NoteHealSent(rule.Name);
return true;
}
if (listedOnly) return VitalNo("none listed in Consumables");
@ -2308,7 +2346,7 @@ public partial class BuffManager : IDisposable
_host.UseFor(unchecked((uint)wo.Id), "Buff", $"vitals: {kind} potion from the pack");
_lastPotionAt = DateTime.Now;
_lastCastAttempt = DateTime.Now;
if (IsHealthPotionType(types)) _healLatency.HealSent(Now, wo.Name ?? "health potion");
if (IsHealthPotionType(types)) NoteHealSent(wo.Name ?? "health potion");
return true;
}
return VitalNo("none in the Items list or the pack");
@ -2461,7 +2499,7 @@ public partial class BuffManager : IDisposable
_host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: healing kit on yourself");
_lastCastAttempt = DateTime.Now;
MarkKitUsed();
_healLatency.HealSent(Now, kit.Name ?? "healing kit");
NoteHealSent(kit.Name ?? "healing kit");
return true;
}
@ -3119,7 +3157,8 @@ public partial class BuffManager : IDisposable
// run cast (the priority buffs landed and raised the skill, or a higher spell was
// learned). Never lower: a skill that dropped leaves the run's cast alone.
if (_forceRebuffCastFamilies.Contains(targetSpell.Family))
return !(CastLevelThisRun(targetSpell.Family) is int ran && ran > 0 && GetSpellLevel(targetSpell) > ran);
return UpgradeParked(targetSpell.Family)
|| !(CastLevelThisRun(targetSpell.Family) is int ran && ran > 0 && GetSpellLevel(targetSpell) > ran);
if (!_isAutoBatchRebuff) return false;
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining);
}
@ -3142,7 +3181,7 @@ public partial class BuffManager : IDisposable
{
if (_itemSpellTimers.TryGetValue(targetSpell.Family, out ItemSpellRecord? itemTimer))
{
if (itemTimer.SpellLevel < targetLevel)
if (itemTimer.SpellLevel < targetLevel && !UpgradeParked(targetSpell.Family))
{
LogArmorRecast(targetSpell, $"tier-upgrade recordedLvl={itemTimer.SpellLevel} < targetLvl={targetLevel} (recorded='{itemTimer.SpellName}')");
return false;
@ -3184,7 +3223,7 @@ public partial class BuffManager : IDisposable
// login) keeps the cap, so a relog doesn't recast every capped Incantation.
int effectiveTarget = EffectiveTargetLevel(targetSpell);
if (timer.SpellLevel < effectiveTarget)
if (timer.SpellLevel < effectiveTarget && !UpgradeParked(targetSpell.Family))
{
LogPlayerRecast(targetSpell, $"tier-upgrade storedLvl={timer.SpellLevel} < effTarget={effectiveTarget} (nominal={targetLevel}, achievedCap={(_familyAchievedTier.TryGetValue(targetSpell.Family, out int a2) ? a2 : -1)}, stored='{timer.SpellName}')");
return false;
@ -3240,6 +3279,8 @@ public partial class BuffManager : IDisposable
int level = GetSpellLevel(spell);
if (!_familyAttemptedTier.TryGetValue(spell.Family, out int prev) || level > prev)
_familyAttemptedTier[spell.Family] = level;
// A cast of the family landed: the server takes it, so no upgrade no-show streak or park stands.
ClearUpgradeNoShows(spell.Family);
// The pending upgrade (or better) landed.
if (_pendingUpgradeSpellId != 0 && SpellTableStub.GetById(_pendingUpgradeSpellId) is { } up
&& up.Family == spell.Family && level >= GetSpellLevel(up))
@ -3253,8 +3294,9 @@ public partial class BuffManager : IDisposable
/// <summary>
/// The pending upgrade cast <paramref name="spellId"/> did not take (fizzle, refusal, no mana,
/// no-show): it is no longer pending, and it is cast again at the next opportunity. No try cap,
/// and no rest after a fizzle, a client refusal or a no-show; a server mana or component refusal
/// still rests the family as it does for any buff.
/// and no rest after a fizzle or a client refusal; a server mana or component refusal still rests
/// the family as it does for any buff. A SILENT no-show is the exception to "no cap": after
/// UpgradeNoShowThreshold in a row the upgrade (only) is parked (NoteUpgradeNoShow).
/// </summary>
private void EndPendingUpgrade(int spellId, string why)
{
@ -3262,6 +3304,41 @@ public partial class BuffManager : IDisposable
_pendingUpgradeSpellId = 0;
_host.Log($"[Buff] upgrade to {SpellTableStub.GetById(spellId)?.Name ?? spellId.ToString()} did not take ({why}); cast again at the next opportunity.");
}
/// <summary>True while upgrades of <paramref name="family"/> are parked after repeated silent no-shows.</summary>
private bool UpgradeParked(int family)
=> family != 0 && _upgradeParkedUntil.TryGetValue(family, out DateTime until) && DateTime.Now < until;
/// <summary>
/// The pending upgrade <paramref name="spellId"/> was a silent no-show (nothing showed in the
/// registry / no chat). Counts it; at UpgradeNoShowThreshold in a row the family's upgrades are
/// parked for UpgradeParkCooldown (and the count starts over for the next window). Nothing else
/// is touched: no strike, no family park, no blacklist.
/// </summary>
private void NoteUpgradeNoShow(int spellId)
{
int family = SpellTableStub.GetById(spellId)?.Family ?? 0;
if (family == 0) return;
int count = _upgradeNoShowCounts.TryGetValue(family, out int prev) ? prev + 1 : 1;
if (count >= UpgradeNoShowThreshold)
{
_upgradeNoShowCounts.Remove(family);
_upgradeParkedUntil[family] = DateTime.Now + UpgradeParkCooldown;
_host.Log($"[Buff] upgrade of family {family} ({SpellTableStub.GetById(spellId)?.Name}) never showed {count} times in a row: upgrades of it parked {UpgradeParkCooldown.TotalMinutes:0}min " +
"(the level it was cast over still refreshes as a normal cast; the family is not blacklisted).");
}
else
{
_upgradeNoShowCounts[family] = count;
_host.Log($"[Buff] upgrade of family {family} did not show ({count}/{UpgradeNoShowThreshold} before it is parked).");
}
}
private void ClearUpgradeNoShows(int family)
{
_upgradeNoShowCounts.Remove(family);
_upgradeParkedUntil.Remove(family);
}
/// <summary>
/// The level IsBuffActive holds a player buff to: the target spell's level, capped at the
/// highest level that family has landed at, once the target level has been confirmed and
@ -3283,6 +3360,9 @@ public partial class BuffManager : IDisposable
/// </summary>
private int ActiveLevelBelow(int family, int newLevel)
{
// Upgrades parked after repeated silent no-shows: a cast of the family now is the normal
// refresh of what is on (no upgrade line, and its no-show is judged like any other buff's).
if (UpgradeParked(family)) return 0;
int on = 0;
if (_isForceRebuffing && _forceRebuffCastFamilies.Contains(family)) on = CastLevelThisRun(family);
else if (_ramBuffTimers.TryGetValue(family, out RamTimerInfo? t)
@ -3902,6 +3982,14 @@ public partial class BuffManager : IDisposable
private DateTime _filterSkipLoggedAt = DateTime.MinValue;
private string _filterSkipLoggedSummary = "";
private const double FilterSkipLogMinSec = 30;
// "skill untrained" is true of nearly every character (an unspecialised melee skill has no mastery to cast),
// so it would make the chat line print at every buff run. It stays in the summary (/ra buff skipped, the
// Buffing page) and the log, and is left out of the chat line.
internal const string SkillUntrainedReason = "skill untrained";
private string _filterChatSummary = "";
private int _filterChatCount;
private DateTime _filterChatLoggedAt = DateTime.MinValue;
private string _filterChatLoggedSummary = "";
private const int SummaryNamesPerReason = 5;
private void SetFilterSkips(List<(string Buff, string Reason)> skips)
@ -3912,6 +4000,9 @@ public partial class BuffManager : IDisposable
if (same) return;
_filterSkips = skips.Count == 0 ? Array.Empty<(string, string)>() : skips;
_filterSummary = BuildSummary(skips);
var notable = skips.FindAll(s => s.Reason != SkillUntrainedReason);
_filterChatCount = notable.Count;
_filterChatSummary = notable.Count == skips.Count ? _filterSummary : BuildSummary(notable);
}
/// <summary>"skill untrained: A, B, C, D, E (+12 more); no melee or missile weapon listed: Blood Drinker, Heart Seeker".</summary>
@ -3946,19 +4037,27 @@ public partial class BuffManager : IDisposable
/// <summary>The skipped buffs grouped by reason, or "".</summary>
public string FilterSkipSummary() => _filterSummary;
// One line per buff run (Force Rebuff, or the automatic batch starting). Same content as the
// last line is held back for FilterSkipLogMinSec; different content prints at once. Reads the
// skips of the BuildDynamicBuffList pass the caller just made.
// One log line and (when something besides untrained skills is skipped) one chat line per buff run
// (Force Rebuff, or the automatic batch starting). Same content as the last line is held back for
// FilterSkipLogMinSec; different content prints at once. Reads the skips of the BuildDynamicBuffList
// pass the caller just made.
private void LogFilterSkips()
{
var now = DateTime.Now;
string summary = _filterSummary;
if (summary.Length == 0) return;
var now = DateTime.Now;
if (summary == _filterSkipLoggedSummary && (now - _filterSkipLoggedAt).TotalSeconds < FilterSkipLogMinSec) return;
_filterSkipLoggedAt = now;
_filterSkipLoggedSummary = summary;
_host.WriteToChat($"[RynthAi] Buff run skips {_filterSkips.Count} buff(s) this character can't use - {summary}", 1);
_host.Log($"[Buff] filter skips: {summary}");
if (summary != _filterSkipLoggedSummary || (now - _filterSkipLoggedAt).TotalSeconds >= FilterSkipLogMinSec)
{
_filterSkipLoggedAt = now;
_filterSkipLoggedSummary = summary;
_host.Log($"[Buff] filter skips: {summary}");
}
string chat = _filterChatSummary;
if (chat.Length == 0) return;
if (chat == _filterChatLoggedSummary && (now - _filterChatLoggedAt).TotalSeconds < FilterSkipLogMinSec) return;
_filterChatLoggedAt = now;
_filterChatLoggedSummary = chat;
_host.WriteToChat($"[RynthAi] Buff run skips {_filterChatCount} buff(s) this character can't use - {chat}", 1);
}
internal List<string> BuildDynamicBuffList()
{
@ -4009,7 +4108,7 @@ public partial class BuffManager : IDisposable
if (!IsSkillUsable(kvp.Key))
{
// Always left out (no skill, no mastery to cast); the setting only decides whether it is reported.
if (filter && !BaseCreatureBuffs.Contains(kvp.Value)) skips.Add((kvp.Value, "skill untrained"));
if (filter && !BaseCreatureBuffs.Contains(kvp.Value)) skips.Add((kvp.Value, SkillUntrainedReason));
continue;
}
if (kvp.Value.Contains("Creature Enchantment Mastery"))
@ -5387,9 +5486,13 @@ public partial class BuffManager : IDisposable
{
if ((DateTime.Now - asked.At).TotalSeconds >= WandIdRetrySec)
{
_host.RequestId(uid);
_wandIdAsked[wo.Id] = (asked.Count + 1, DateTime.Now);
_host.Log($"[WieldGate] identifying 0x{uid:X8} '{wo.Name}' before using it to buff (its wield requirement isn't known yet)");
// Counted only when the engine took it: a refused ask (a death or a portal) is not one of the
// WandIdMaxAsks, and the wand is held back and asked about again.
if (_host.RequestId(uid))
{
_wandIdAsked[wo.Id] = (asked.Count + 1, DateTime.Now);
_host.Log($"[WieldGate] identifying 0x{uid:X8} '{wo.Name}' before using it to buff (its wield requirement isn't known yet)");
}
}
return true;
}

View file

@ -0,0 +1,523 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Environment-impact throttle (2026-10-12). Rules and bookkeeping in EnvironmentImpact.cs.
///
/// missile "Your missile attack hit the environment." in Missile mode counts one hit on the
/// target the server's attack is bound to.
/// magic each single-target war/void cast is watched: our projectiles (named like the
/// shape, "Flame Bolt") are claimed as they appear next to the player, followed until
/// they stop or vanish, and the cast counts one hit when every projectile stopped
/// short of the target (ProjectileImpactJudge) and no hit, resist or evade line came
/// back for it. Rings and walls aren't watched: they don't fly at the target.
///
/// At EnvironmentImpactLimit hits within the window the throttle trips: the server's attack is
/// released (a magic cast in flight finishes first) and the chosen response runs: an approach
/// (autorun toward the target, at most EnvironmentApproachMeters, never nearer than
/// EnvironmentMinDistance, bounded in time and by progress), or a new target (this one skipped
/// for EnvironmentSkipSec). Off = no detection at all.
/// </summary>
public partial class CombatManager
{
/// <summary>Clock for the throttle and the projectile watch; tests replace it.</summary>
internal Func<DateTime> EnvClock { get; set; } = () => DateTime.Now;
internal EnvironmentImpactThrottle EnvThrottle { get; } = new();
/// <summary>The start of the chat line ACE sends the shooter (ProjectileCollisionHelper.OnCollideEnvironment,
/// a Broadcast line). Matched at the line's start only: a player's copy has their name in front.</summary>
internal const string MissileEnvironmentText = "Your missile attack hit the environment";
// A cast's projectiles appear once its windup ends (up to ~2.5 s for a high tier).
private const double CastClaimWindowMs = 4000;
// Our projectile spawns at the caster; farther than this at its first sight it isn't ours.
private const double ClaimRadiusMeters = 8.0;
// Still this long after flying counts as stopped (ACE zeroes its velocity on impact).
private const double StoppedForMs = 250;
private const double StillMeters = 0.05;
// A projectile still flying after this is dropped from the watch (no verdict).
private const double ProjectileMaxFlightMs = 8000;
// After the last projectile stops, a hit/resist/evade line still has this long to arrive.
private const double ImpactEvidenceGraceMs = 1000;
private const int MaxCastWatches = 4;
// An approach that hasn't gained this much ground in ApproachNoProgressMs is blocked.
private const double ApproachProgressMeters = 0.5;
private const double ApproachNoProgressMs = 2500;
private const double ApproachMaxMs = 8000;
private const double ApproachRunRefreshMs = 1000;
private const double ApproachTurnRefreshMs = 300;
private const double ApproachFaceToleranceDeg = 10;
// Think stopped driving the approach (buffing took over, out of range): let go of autorun.
private const double ApproachOrphanMs = 1500;
private enum EnvKind { Missile, Magic }
private sealed class TrackedProjectile
{
public uint Id;
public double StartX, StartY, StartZ;
public double LastX, LastY, LastZ;
public DateTime FirstSeen, LastMoved;
public double Travel;
public bool Resolved, Short;
}
private sealed class CastWatch
{
public int TargetId;
public string SpellName = "";
public DateTime CastAt;
public double CasterX, CasterY, CasterZ;
public bool HasCasterPos;
public readonly List<TrackedProjectile> Projectiles = new();
public DateTime LastImpactAt = DateTime.MinValue;
}
// Creates are queued and claimed by the heartbeat poll (the name lands a moment later).
private readonly ConcurrentQueue<(uint Id, DateTime At)> _envCreated = new();
private readonly List<(uint Id, DateTime At)> _envCandidates = new();
private readonly List<CastWatch> _castWatches = new();
private readonly Dictionary<int, DateTime> _envSkipUntil = new();
private DateTime _envLastEvidenceAt = DateTime.MinValue;
// The trip waiting for Think, and the approach in progress.
private int _envPendingTargetId;
private EnvKind _envPendingKind;
private int _envApproachTargetId;
private EnvKind _envApproachKind;
private double _envApproachGoal, _envApproachBestDist;
private DateTime _envApproachStartedAt, _envApproachProgressAt, _envApproachRunAt, _envApproachTurnAt, _envApproachTickAt;
private bool _envApproachUsedMotions;
/// <summary>True while combat is walking toward a target for its environment hits.</summary>
internal bool EnvironmentApproachActive => _envApproachTargetId != 0;
private EnvironmentResponse ResponseFor(EnvKind kind) => EnvironmentImpactPlanner.Parse(
kind == EnvKind.Missile ? _settings.MissileEnvironmentResponse : _settings.MagicEnvironmentResponse);
// ── Signals ────────────────────────────────────────────────────────────────
/// <summary>A new object. Only queued while the macro runs with magic detection on
/// (the heartbeat poll that drains the queue runs only then). Separate from OnObjectCreated,
/// which feeds the ghost tracker on every create.</summary>
public void OnEnvironmentObjectCreated(uint objectId)
{
if (objectId == 0 || _settings.MagicEnvironmentResponse == 0 || !_settings.IsMacroRunning) return;
_envCreated.Enqueue((objectId, EnvClock()));
}
/// <summary>From OnObjectDeleted: a projectile that vanished has hit something, and a
/// monster id that's gone forgets its hits, approaches and skip.</summary>
private void OnEnvironmentObjectDeleted(uint objectId)
{
int id = (int)objectId;
EnvThrottle.Forget(id);
_envSkipUntil.Remove(id);
if (_castWatches.Count == 0) return;
DateTime now = EnvClock();
foreach (var w in _castWatches)
foreach (var p in w.Projectiles)
if (p.Id == objectId && !p.Resolved) ResolveProjectile(w, p, now);
}
/// <summary>The missile line, from HandleChatForDamage. True when it was that line.</summary>
private bool NoteMissileEnvironmentChat(string text)
{
if (!ChatSource.StartsWithMarker(text, MissileEnvironmentText, StringComparison.OrdinalIgnoreCase)) return false;
if (ResponseFor(EnvKind.Missile) == EnvironmentResponse.Off) return true;
if (CurrentCombatMode != CombatMode.Missile) return true;
int target = _serverAttackTargetId != 0 ? _serverAttackTargetId : activeTargetId;
if (target != 0) RecordEnvironmentImpact(target, EnvKind.Missile, "missile hit the environment");
return true;
}
/// <summary>Any sign an attack reached a monster (hit, resist, evade, a health drop):
/// a cast with one of these after it didn't only hit the environment.</summary>
private void NoteEnvironmentEvidence() => _envLastEvidenceAt = EnvClock();
/// <summary>A single-target cast just went out (AttackWithMagic): watch its projectiles.</summary>
internal void RegisterCastWatch(int targetId, string spellName)
{
if (ResponseFor(EnvKind.Magic) == EnvironmentResponse.Off || targetId == 0) return;
DateTime now = EnvClock();
var w = new CastWatch { TargetId = targetId, SpellName = spellName, CastAt = now };
if (TryGetPlayerGlobal(out double px, out double py, out double pz))
{
w.CasterX = px; w.CasterY = py; w.CasterZ = pz; w.HasCasterPos = true;
}
if (_castWatches.Count >= MaxCastWatches) _castWatches.RemoveAt(0);
_castWatches.Add(w);
}
/// <summary>Counts one environment hit; at the limit, arms the response for Think.</summary>
private void RecordEnvironmentImpact(int targetId, EnvKind kind, string detail)
{
DateTime now = EnvClock();
int limit = Math.Max(1, _settings.EnvironmentImpactLimit);
int window = Math.Max(1, _settings.EnvironmentImpactWindowSec);
int n = EnvThrottle.Record(targetId, now, window);
string name = _worldFilter[targetId]?.Name ?? "";
_host.Log($"[EnvImpact] {kind.ToString().ToLowerInvariant()}: {detail} — 0x{(uint)targetId:X8} '{name}' {n}/{limit} in {window}s");
if (n < limit || targetId != activeTargetId) return;
if (_envApproachTargetId == targetId) return; // already moving closer to it
_envPendingTargetId = targetId;
_envPendingKind = kind;
}
// ── Heartbeat: projectile watch and the approach's safety net ─────────────
/// <summary>Every heartbeat while the macro runs (pump thread).</summary>
internal void PollEnvironmentImpact()
{
DateTime now = EnvClock();
if (_settings.MagicEnvironmentResponse == 0)
{
while (_envCreated.TryDequeue(out _)) { }
_envCandidates.Clear();
_castWatches.Clear();
}
else
{
while (_envCreated.TryDequeue(out var c)) _envCandidates.Add(c);
ClaimProjectiles(now);
TrackProjectiles(now);
JudgeCastWatches(now);
}
// Think drives the approach; when it stops (another activity, out of range, combat off)
// or the deadline passes, autorun must not be left on.
if (_envApproachTargetId != 0
&& ((now - _envApproachTickAt).TotalMilliseconds > ApproachOrphanMs
|| (now - _envApproachStartedAt).TotalMilliseconds > ApproachMaxMs + ApproachOrphanMs
|| !_settings.EnableCombat))
EndEnvironmentApproach("combat stopped driving it");
// Same for the re-sync sidestep's movement key: Think releases it after ResyncStepMs,
// but only while it keeps ticking in magic mode.
if (_resyncState == 2 && (TargetClock() - _resyncAt).TotalMilliseconds > ResyncStepMs + ApproachOrphanMs)
AbandonResync("combat stopped driving it");
}
private void ClaimProjectiles(DateTime now)
{
if (_envCandidates.Count == 0) return;
bool havePlayer = TryGetPlayerGlobal(out double px, out double py, out double pz);
for (int i = _envCandidates.Count - 1; i >= 0; i--)
{
var (id, at) = _envCandidates[i];
string name = _worldFilter[(int)id]?.Name ?? "";
if (name.Length == 0 && _host.TryGetObjectName(id, out string n2)) name = n2;
if (name.Length == 0)
{
// The name lands a moment after the create; give it a second.
if ((now - at).TotalMilliseconds > 1000) _envCandidates.RemoveAt(i);
continue;
}
_envCandidates.RemoveAt(i);
if (!IsWatchedProjectileName(name)) continue;
if (!havePlayer || !TryGetObjectGlobal(id, out double x, out double y, out double z)) continue;
if (Dist(px, py, pz, x, y, z) > ClaimRadiusMeters) continue;
// The newest cast still taking projectiles (a blast's several share one cast).
CastWatch? owner = null;
for (int w = _castWatches.Count - 1; w >= 0; w--)
{
double age = (at - _castWatches[w].CastAt).TotalMilliseconds;
if (age >= -50 && age <= CastClaimWindowMs) { owner = _castWatches[w]; break; }
}
if (owner == null) continue;
owner.Projectiles.Add(new TrackedProjectile
{
Id = id, StartX = x, StartY = y, StartZ = z, LastX = x, LastY = y, LastZ = z,
FirstSeen = now, LastMoved = now,
});
}
}
/// <summary>A war/void projectile: the shape names (SpellShapes/VoidSpellShapes), or any
/// name ending in a flying shape (lore-named projectiles of the same shapes).</summary>
internal static bool IsWatchedProjectileName(string name)
{
if (IsSpellProjectileName(name)) return !name.EndsWith(" Ring", StringComparison.OrdinalIgnoreCase);
return name.EndsWith(" Bolt", StringComparison.OrdinalIgnoreCase)
|| name.EndsWith(" Streak", StringComparison.OrdinalIgnoreCase)
|| name.EndsWith(" Arc", StringComparison.OrdinalIgnoreCase)
|| name.EndsWith(" Blast", StringComparison.OrdinalIgnoreCase);
}
private void TrackProjectiles(DateTime now)
{
foreach (var w in _castWatches)
{
foreach (var p in w.Projectiles)
{
if (p.Resolved) continue;
if ((now - p.FirstSeen).TotalMilliseconds > ProjectileMaxFlightMs)
{
p.Resolved = true; // no verdict: treated as not short
continue;
}
if (!TryGetObjectGlobal(p.Id, out double x, out double y, out double z)) continue;
if (Dist(x, y, z, p.LastX, p.LastY, p.LastZ) > StillMeters)
{
p.LastX = x; p.LastY = y; p.LastZ = z;
p.LastMoved = now;
p.Travel = Math.Max(p.Travel, Dist(x, y, z, p.StartX, p.StartY, p.StartZ));
continue;
}
if (p.Travel >= ProjectileImpactJudge.MinTravelMeters
&& (now - p.LastMoved).TotalMilliseconds >= StoppedForMs)
ResolveProjectile(w, p, now);
}
}
}
private void ResolveProjectile(CastWatch w, TrackedProjectile p, DateTime now)
{
p.Resolved = true;
w.LastImpactAt = now;
if (p.Travel < ProjectileImpactJudge.MinTravelMeters) return;
if (!TryGetObjectGlobal((uint)w.TargetId, out double tx, out double ty, out double tz)) return;
double cx = w.CasterX, cy = w.CasterY, cz = w.CasterZ;
if (!w.HasCasterPos) { cx = p.StartX; cy = p.StartY; cz = p.StartZ; }
p.Short = ProjectileImpactJudge.StoppedShort(
Dist(p.LastX, p.LastY, p.LastZ, tx, ty, tz),
Dist(cx, cy, cz, p.LastX, p.LastY, p.LastZ),
Dist(cx, cy, cz, tx, ty, tz));
}
private void JudgeCastWatches(DateTime now)
{
for (int i = _castWatches.Count - 1; i >= 0; i--)
{
var w = _castWatches[i];
double age = (now - w.CastAt).TotalMilliseconds;
if (w.Projectiles.Count == 0)
{
if (age > CastClaimWindowMs + 500) _castWatches.RemoveAt(i); // refused or never seen
continue;
}
// A blast's projectiles all appear together; wait out the claim window only briefly.
bool allResolved = w.Projectiles.TrueForAll(p => p.Resolved);
if (!allResolved) continue;
if ((now - w.LastImpactAt).TotalMilliseconds < ImpactEvidenceGraceMs) continue;
_castWatches.RemoveAt(i);
bool reached = _envLastEvidenceAt >= w.CastAt;
bool allShort = w.Projectiles.TrueForAll(p => p.Short);
if (!reached && allShort)
RecordEnvironmentImpact(w.TargetId, EnvKind.Magic,
$"'{w.SpellName}' stopped short of the target ({w.Projectiles.Count} projectile{(w.Projectiles.Count == 1 ? "" : "s")})");
}
}
// ── Think: the response ───────────────────────────────────────────────────
/// <summary>
/// In ThinkCore once the target is valid and in reach. True = this tick belongs to the
/// response (an approach under way, or the target just switched): no attack.
/// </summary>
internal bool RunEnvironmentImpact(WorldObject targetObj, double currentDist)
{
DateTime now = EnvClock();
if (_envApproachTargetId != 0)
{
if (_envApproachTargetId == activeTargetId)
return ContinueEnvironmentApproach(targetObj, currentDist, now);
EndEnvironmentApproach("the target changed");
}
if (_envPendingTargetId == 0) return false;
if (_envPendingTargetId != activeTargetId) { _envPendingTargetId = 0; return false; }
EnvKind kind = _envPendingKind;
// The cast in flight finishes first: turning or running now would cancel it.
if (kind == EnvKind.Magic && IsCastInFlight()) return true;
// A re-sync sidestep already holding a movement key finishes first: running or turning
// over it would send two movement states at once.
if (_resyncState == 2) return true;
int id = activeTargetId;
_envPendingTargetId = 0;
EnvThrottle.ResetHits(id);
EnvironmentResponse response = ResponseFor(kind);
int minDist = Math.Max(1, _settings.EnvironmentMinDistance);
EnvironmentAction action = EnvironmentImpactPlanner.Decide(response, EnvThrottle.Approaches(id),
currentDist, minDist, HasAlternateTarget(id));
string who = $"0x{(uint)id:X8} '{targetObj.Name}' at {currentDist:0.0}m";
string why = kind == EnvKind.Missile ? "missiles" : "spells";
switch (action)
{
case EnvironmentAction.NewTarget:
{
if (_serverAttackTargetId != 0) ReleaseServerAttack("environment hits", log: false);
int skip = Math.Max(1, _settings.EnvironmentSkipSec);
_envSkipUntil[id] = now.AddSeconds(skip);
_host.Log($"[EnvImpact] {why} keep hitting the environment: leaving {who}, skipping it {skip}s ({EnvironmentImpactPlanner.Name((int)response)})");
SupersedeResync("a new target");
ForgetScanned(id);
DropTarget("environment hits: new target");
return true;
}
case EnvironmentAction.Approach:
{
if (_serverAttackTargetId != 0) ReleaseServerAttack("environment hits", log: false);
double goal = EnvironmentImpactPlanner.ApproachGoal(currentDist, _settings.EnvironmentApproachMeters, minDist);
EnvThrottle.NoteApproach(id);
_envApproachTargetId = id;
_envApproachKind = kind;
_envApproachGoal = goal;
_envApproachBestDist = currentDist;
_envApproachStartedAt = _envApproachProgressAt = _envApproachTickAt = now;
_envApproachRunAt = _envApproachTurnAt = DateTime.MinValue;
_envApproachUsedMotions = false;
_host.Log($"[EnvImpact] {why} keep hitting the environment: moving closer to {who}, stopping at {goal:0.0}m ({EnvironmentImpactPlanner.Name((int)response)})");
SupersedeResync("moving closer");
return ContinueEnvironmentApproach(targetObj, currentDist, now);
}
default:
_host.Log($"[EnvImpact] {why} keep hitting the environment on {who}, but it's the only monster in reach and already close: attacking on");
return false;
}
}
/// <summary>
/// The throttle acted on misses the magic re-sync (TickResyncStep) was also counting. The
/// misses are explained (a wall in the way), so the re-sync's count starts over, and a
/// sidestep that is wanted but not yet started is dropped. Moving closer is itself real
/// movement, which re-syncs the server's copy of our position anyway.
/// </summary>
private void SupersedeResync(string by)
{
_magicMissesSinceHit = 0;
if (_resyncState != 1) return;
_resyncState = 0;
_host.Log($"[EnvImpact] re-sync sidestep dropped: {by} answers the misses");
}
/// <summary>Stops a re-sync sidestep where it is, letting go of its movement key if held.</summary>
private void AbandonResync(string why)
{
if (_resyncState == 0) return;
if (_resyncState == 2) _host.SetMotionBy("Combat/Resync", _resyncMotion, false);
_resyncState = 0;
_host.Log($"[CombatCast] re-sync sidestep stopped: {why}");
}
private bool ContinueEnvironmentApproach(WorldObject targetObj, double currentDist, DateTime now)
{
_envApproachTickAt = now;
if (currentDist <= _envApproachGoal)
{
EndEnvironmentApproach($"reached {currentDist:0.0}m");
return false;
}
if ((now - _envApproachStartedAt).TotalMilliseconds > ApproachMaxMs)
{
EndEnvironmentApproach($"timed out at {currentDist:0.0}m");
return false;
}
if (currentDist < _envApproachBestDist - ApproachProgressMeters)
{
_envApproachBestDist = currentDist;
_envApproachProgressAt = now;
}
else if ((now - _envApproachProgressAt).TotalMilliseconds > ApproachNoProgressMs)
{
EndEnvironmentApproach($"no progress (blocked?) at {currentDist:0.0}m");
return false;
}
// Face the target, then run. A held call (the pacer, a use) is simply tried next tick.
if ((now - _envApproachTurnAt).TotalMilliseconds >= ApproachTurnRefreshMs
&& TryGetHeadingTo(activeTargetId, out double desiredDeg, out double err)
&& err > ApproachFaceToleranceDeg)
{
if (_host.HasTurnToHeading)
{
if (_host.TurnToHeadingBy("Combat/Approach", (float)desiredDeg)) _envApproachTurnAt = now;
}
else
{
FaceTarget(activeTargetId);
_envApproachUsedMotions = true;
_envApproachTurnAt = now;
}
}
if ((now - _envApproachRunAt).TotalMilliseconds >= ApproachRunRefreshMs
&& _host.SetAutoRunBy("Combat/Approach", true))
_envApproachRunAt = now;
_stallWatch.Hold(now);
LastCombatSkipReason = "env-approach"; // D4 record-only
return true;
}
/// <summary>Stops an approach in progress (autorun off). Safe to call when none is.</summary>
private void EndEnvironmentApproach(string why)
{
if (_envApproachTargetId == 0) return;
int id = _envApproachTargetId;
_envApproachTargetId = 0;
if (_envApproachRunAt != DateTime.MinValue) _host.SetAutoRunBy("Combat/Approach", false);
if (_envApproachUsedMotions) ClearCombatTurnMotions();
_host.Log($"[EnvImpact] {_envApproachKind.ToString().ToLowerInvariant()} approach to 0x{(uint)id:X8} ended: {why}");
}
/// <summary>True while <paramref name="id"/> is being skipped for its environment hits.</summary>
private bool IsEnvironmentSkipped(int id)
{
if (_envSkipUntil.Count == 0 || !_envSkipUntil.TryGetValue(id, out DateTime until)) return false;
if (EnvClock() < until) return true;
_envSkipUntil.Remove(id);
return false;
}
/// <summary>Clears every environment-impact state (macro stop, new character).</summary>
private void ResetEnvironmentImpact(string why)
{
EndEnvironmentApproach(why);
AbandonResync(why);
_envPendingTargetId = 0;
_castWatches.Clear();
_envCandidates.Clear();
while (_envCreated.TryDequeue(out _)) { }
EnvThrottle.Clear();
_envSkipUntil.Clear();
}
// ── Positions (global metres: landblock x/y * 192 + the in-block offset) ──
private bool TryGetObjectGlobal(uint id, out double x, out double y, out double z)
{
x = y = z = 0;
if (!_host.TryGetObjectPosition(id, out uint cell, out float lx, out float ly, out float lz)) return false;
x = ((cell >> 24) & 0xFF) * 192.0 + lx;
y = ((cell >> 16) & 0xFF) * 192.0 + ly;
z = lz;
return true;
}
private bool TryGetPlayerGlobal(out double x, out double y, out double z)
{
x = y = z = 0;
if (!_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz,
out _, out _, out _, out _)) return false;
x = ((cell >> 24) & 0xFF) * 192.0 + lx;
y = ((cell >> 16) & 0xFF) * 192.0 + ly;
z = lz;
return true;
}
private static double Dist(double ax, double ay, double az, double bx, double by, double bz)
{
double dx = ax - bx, dy = ay - by, dz = az - bz;
return Math.Sqrt(dx * dx + dy * dy + dz * dz);
}
}

View file

@ -0,0 +1,244 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.Shared; // TurnToHeadingBy / SetAutoRunBy
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Kite / pull-away (2026-10-16). Rules in KiteModes.cs; distance in LegacyUiSettings.KitePullMeters.
///
/// When the effective monster rule is PullAway, combat tags the mob (one hit window), then
/// autoruns away from its lock-spot origin until the mob has been dragged that many metres
/// clear of where it stood, then stops and kills it. Default and per-mob via MonsterRule.Kite.
/// </summary>
public partial class CombatManager
{
/// <summary>Clock for the kite state machine; tests replace it.</summary>
internal Func<DateTime> KiteClock { get; set; } = () => DateTime.Now;
// Face-away + autorun cadence (mirrors EnvironmentApproach).
private const double KiteTurnRefreshMs = 300;
private const double KiteRunRefreshMs = 1000;
// Think stopped driving the kite (buffing took over): let go of autorun.
private const double KiteOrphanMs = 1500;
// Tag window: allow attacks so aggro sticks before we turn and run.
private const double KiteTagMaxMs = 2500;
// A pull that never gets far enough (blocked, mob leashed) gives up and fights in place.
private const double KiteMaxMs = 20000;
// Don't outrun the chase: stop autorun when farther than this from the mob.
private const double KiteCatchUpSlackMeters = 1.5;
// Progress toward the pull goal; no gain in this long ⇒ blocked / leashed.
private const double KiteProgressMeters = 0.75;
private const double KiteNoProgressMs = 4000;
private enum KitePhase { None, Tag, Flee, Done }
private int _kiteTargetId;
private KitePhase _kitePhase = KitePhase.None;
private double _kiteOriginX, _kiteOriginY, _kiteOriginZ;
private bool _kiteHasOrigin;
private double _kiteBestPull;
private DateTime _kiteStartedAt, _kiteProgressAt, _kiteRunAt, _kiteTurnAt, _kiteTickAt;
private bool _kiteUsedMotions;
// Targets already pulled this engagement (object id): do not re-kite mid-fight.
private readonly HashSet<int> _kiteDoneIds = new();
/// <summary>True while combat is tagging or running a pull-away for the locked target.</summary>
internal bool KiteActive => _kitePhase is KitePhase.Tag or KitePhase.Flee;
/// <summary>
/// In ThinkCore once the target is valid. True = this tick belongs to the kite (flee under
/// way): no attack. Tag phase returns false so the first hit(s) can land.
/// </summary>
internal bool RunKite(WorldObject targetObj, double currentDist)
{
DateTime now = KiteClock();
int id = activeTargetId;
if (id == 0) { EndKite("no target"); return false; }
// Already pulled this object id for this engagement: fight in place.
if (_kiteDoneIds.Contains(id))
{
if (_kiteTargetId == id) EndKite("already pulled");
return false;
}
var rule = GetRuleForTarget(targetObj);
if (!KiteModes.WantsPullAway(rule, DefaultMonsterRule()))
{
if (_kiteTargetId == id) EndKite("rule Off");
return false;
}
// Start (or retarget) a pull for this lock.
if (_kiteTargetId != id || _kitePhase == KitePhase.None)
{
if (_kiteTargetId != 0 && _kiteTargetId != id)
EndKite("the target changed");
BeginKite(id, targetObj, now);
}
_kiteTickAt = now;
double pullMeters = Math.Max(3.0, _settings.KitePullMeters);
if (_kitePhase == KitePhase.Tag)
{
bool tagged = _lastDamageDealtAt != DateTime.MinValue && _lastDamageDealtAt >= _kiteStartedAt;
bool tagTimedOut = (now - _kiteStartedAt).TotalMilliseconds >= KiteTagMaxMs;
if (!_settings.KiteTagFirst || tagged || tagTimedOut)
{
_kitePhase = KitePhase.Flee;
_kiteBestPull = PullDistance(id);
_kiteProgressAt = now;
_kiteRunAt = _kiteTurnAt = DateTime.MinValue;
string why = !_settings.KiteTagFirst ? "tag skipped"
: tagged ? "tagged"
: "tag timed out";
_host.Log($"[Kite] pull-away on 0x{(uint)id:X8} '{targetObj.Name}': fleeing ({why}), goal {pullMeters:0}m from origin");
EndEnvironmentApproach("kite pull-away");
}
else
{
LastCombatSkipReason = "kite-tag";
return false; // let Think attack once so aggro sticks
}
}
if (_kitePhase != KitePhase.Flee) return false;
double pulled = PullDistance(id);
if (pulled >= pullMeters)
{
FinishKite(id, $"pulled {pulled:0.0}m");
return false;
}
if ((now - _kiteStartedAt).TotalMilliseconds > KiteMaxMs)
{
FinishKite(id, $"timed out at {pulled:0.0}m");
return false;
}
if (pulled > _kiteBestPull + KiteProgressMeters)
{
_kiteBestPull = pulled;
_kiteProgressAt = now;
}
else if ((now - _kiteProgressAt).TotalMilliseconds > KiteNoProgressMs)
{
FinishKite(id, $"no progress (blocked/leashed?) at {pulled:0.0}m");
return false;
}
// Don't outrun the chase past disengage: wait for the mob to catch up.
double catchUp = Math.Max(1.0, DisengageDistance - KiteCatchUpSlackMeters);
bool waiting = currentDist > catchUp;
// Face away from the mob while fleeing; face it while waiting for catch-up.
if ((now - _kiteTurnAt).TotalMilliseconds >= KiteTurnRefreshMs
&& TryGetHeadingTo(id, out double towardDeg, out _))
{
double faceDeg = waiting ? towardDeg : (towardDeg + 180.0) % 360.0;
if (_host.HasTurnToHeading)
{
if (_host.TurnToHeadingBy("Combat/Kite", (float)faceDeg)) _kiteTurnAt = now;
}
else
{
// No heading snap: FaceTarget only faces toward the mob (useful while waiting).
if (waiting) { FaceTarget(id); _kiteUsedMotions = true; }
_kiteTurnAt = now;
}
}
if (waiting)
{
if (_kiteRunAt != DateTime.MinValue)
{
_host.SetAutoRunBy("Combat/Kite", false);
_kiteRunAt = DateTime.MinValue;
}
LastCombatSkipReason = "kite-wait";
_stallWatch.Hold(now);
return true;
}
if ((now - _kiteRunAt).TotalMilliseconds >= KiteRunRefreshMs
&& _host.SetAutoRunBy("Combat/Kite", true))
_kiteRunAt = now;
_stallWatch.Hold(now);
LastCombatSkipReason = "kite-flee";
return true;
}
private void BeginKite(int id, WorldObject targetObj, DateTime now)
{
_kiteTargetId = id;
_kitePhase = _settings.KiteTagFirst ? KitePhase.Tag : KitePhase.Flee;
_kiteHasOrigin = TryGetObjectGlobal((uint)id, out _kiteOriginX, out _kiteOriginY, out _kiteOriginZ);
if (!_kiteHasOrigin)
_kiteHasOrigin = TryGetPlayerGlobal(out _kiteOriginX, out _kiteOriginY, out _kiteOriginZ);
_kiteBestPull = 0;
_kiteStartedAt = _kiteProgressAt = _kiteTickAt = now;
_kiteRunAt = _kiteTurnAt = DateTime.MinValue;
_kiteUsedMotions = false;
string phase = _kitePhase == KitePhase.Tag ? "tag then flee" : "flee";
_host.Log($"[Kite] pull-away start 0x{(uint)id:X8} '{targetObj.Name}' ({phase}, {_settings.KitePullMeters}m)");
if (_kitePhase == KitePhase.Flee)
EndEnvironmentApproach("kite pull-away");
}
/// <summary>How far the mob has been dragged from its lock-spot origin (metres).</summary>
private double PullDistance(int id)
{
if (!_kiteHasOrigin) return 0;
if (!TryGetObjectGlobal((uint)id, out double x, out double y, out double z))
return _kiteBestPull;
return Dist(x, y, z, _kiteOriginX, _kiteOriginY, _kiteOriginZ);
}
/// <summary>Pull succeeded or gave up: remember the id and fight in place.</summary>
private void FinishKite(int id, string why)
{
_kiteDoneIds.Add(id);
if (_kiteDoneIds.Count > 64) _kiteDoneIds.Clear();
EndKite(why);
_host.Log($"[Kite] pull-away done 0x{(uint)id:X8}: {why} — attacking");
}
/// <summary>Stops a kite in progress (autorun off). Safe to call when none is.</summary>
private void EndKite(string why)
{
if (_kitePhase == KitePhase.None && _kiteTargetId == 0) return;
int id = _kiteTargetId;
bool wasRunning = _kiteRunAt != DateTime.MinValue;
_kiteTargetId = 0;
_kitePhase = KitePhase.None;
_kiteHasOrigin = false;
if (wasRunning) _host.SetAutoRunBy("Combat/Kite", false);
if (_kiteUsedMotions) ClearCombatTurnMotions();
_kiteRunAt = _kiteTurnAt = DateTime.MinValue;
if (id != 0)
_host.Log($"[Kite] ended 0x{(uint)id:X8}: {why}");
}
/// <summary>Clears kite state (macro stop, new character).</summary>
private void ResetKite(string why)
{
EndKite(why);
_kiteDoneIds.Clear();
}
/// <summary>
/// Pump-thread orphan watch: Think drives the flee; when it stops (another activity,
/// combat off) autorun must not be left on.
/// </summary>
internal void PollKite()
{
if (_kitePhase == KitePhase.None) return;
DateTime now = KiteClock();
if ((now - _kiteTickAt).TotalMilliseconds > KiteOrphanMs
|| !_settings.EnableCombat
|| !_settings.IsMacroRunning)
EndKite("combat stopped driving it");
}
}

View file

@ -1033,6 +1033,9 @@ public partial class CombatManager : IDisposable
// A ghost (the server doesn't have it for us): skipped until it shows it is real.
if (Ghosts.IsGhost(wo.Id)) { _ghostsSkippedInScan++; continue; }
// Left for hitting the environment (New target): skipped for EnvironmentSkipSec.
if (IsEnvironmentSkipped(wo.Id)) continue;
// Just killed (KillerNotification) but not yet a corpse — skip so we
// don't re-lock and cast at it during its death animation.
if (_recentlyKilled.ContainsKey(wo.Id)) continue;
@ -1135,6 +1138,7 @@ public partial class CombatManager : IDisposable
_hitAt.Remove(id);
_blacklistManager.ForgetTarget(id);
Ghosts.NoteDeleted(id);
OnEnvironmentObjectDeleted(objectId);
if (id == activeTargetId || id == _lockedTargetId || id == _lastAttackedTargetId)
_awaitingCastResolution = false;
@ -1436,13 +1440,15 @@ public partial class CombatManager : IDisposable
_damageStore!.RecordTaken(src, name, ElementFromWord(m.Groups["type"].Value), amount);
}
/// <summary>A chat line for the damage meter and the stall watchdog.
/// <summary>A chat line for the damage meter, the stall watchdog and the environment throttle.
/// <paramref name="chatType"/> is the line's eChatTypes (-1 = not known).</summary>
public void HandleChatForDamage(string text, int chatType = -1)
{
if (string.IsNullOrEmpty(text)) return;
// Combat lines come from the server; one in a player's chat type is someone's imitation.
if (RynthCore.Plugin.Shared.ChatSource.IsPlayerAuthored(chatType)) return;
// An arrow into a wall: the environment-impact throttle's missile signal.
if (NoteMissileEnvironmentChat(text)) return;
// A miss is a swing too (stall watchdog). "You evaded X!" is the monster's miss, not ours.
if (text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase) > 0)
NoteSwingEvidence("miss");
@ -1455,6 +1461,7 @@ public partial class CombatManager : IDisposable
if (critLine) _lastCritChatAt = now;
if (!CombatText.TryParseOutgoingHit(text, out string victim, out int amount)) return;
NoteEnvironmentEvidence(); // a cast that hit something didn't only hit the environment
bool crit = critLine || (now - _lastCritChatAt).TotalMilliseconds <= CRIT_WINDOW_MS;
// Which monster the line is about. One spell can hurt several (rings, walls, blasts,
@ -1878,12 +1885,214 @@ public partial class CombatManager : IDisposable
/// <summary>Test seam: one judged magic cast with no damage.</summary>
internal void MagicMissForTest(int tid) => NoteMagicMissForResync(tid);
// ── Empyrean Handler lethal-ring evade (chat-triggered back-jump) ─────────
// ACECustom Handler emote: "The handler briefly channels infused Empyrean hatred
// to release a lethal ring." The ring can't be melee-evaded — if the character is
// inside its cast radius they die. On that line, when still in range of a Handler,
// cancel the current swing/cast and back-jump away, then resume combat (target kept).
private const string HandlerRingChannelHint = "channels infused Empyrean hatred to release a lethal ring";
private const string HandlerRingChannelStart = "The handler briefly channels";
private const string HandlerNameHint = "Empyrean Handler";
/// <summary>Yards: Handler lethal ring is treated as at least this wide (RingRange when larger).</summary>
internal const double HandlerRingDangerYards = 12.0;
/// <summary>Back-jump charge (ms) — run-back + jump must clear ~ring radius.</summary>
private const int HandlerRingJumpHoldMs = 750;
private const double HandlerRingEvadeCooldownMs = 4_000;
private DateTime _handlerRingEvadeAt = DateTime.MinValue;
private DateTime _handlerRingEvadeUntil = DateTime.MinValue;
private int _handlerRingEvadeId;
private bool _handlerRingJumpStarted;
/// <summary>
/// Plugin wires this to <c>Jumper.Start("xs", faceHeading, ms)</c> — face the Handler
/// then run-back jump (x+s) so the body moves away. Returns false if the jumper refused.
/// </summary>
public Func<float, int, bool>? RequestBackJump { get; set; }
/// <summary>True while the wired jumper is mid-turn / charge / settle.</summary>
public Func<bool>? JumpBusy { get; set; }
/// <summary>True while a Handler-ring evade is holding combat (jump or settle).</summary>
public bool RingEvadeActive =>
_handlerRingEvadeUntil != DateTime.MinValue && DateTime.Now < _handlerRingEvadeUntil;
/// <summary>
/// Chat line from RynthAiPlugin.OnChatWindowText. Starts a back-jump evade when the
/// Handler channels its lethal ring and the character is still inside ring range.
/// </summary>
public void HandleChatForRingEvade(string? text, int chatType = -1)
{
if (string.IsNullOrEmpty(text)) return;
// Gate: only while the macro is running with combat on, and only if the setting allows it.
// Otherwise a Handler line heard while the character is idle or being driven by hand (or by a
// meta) would take over the keyboard for a back-jump.
if (!_settings.HandlerRingEvade || !_settings.IsMacroRunning || !_settings.EnableCombat) return;
// Handler channel is an Emote (0x0C). ChatSource.IsPlayerAuthored treats Emote as
// player speech, which would skip every real Handler line — anchor on the unique
// phrase starting the line instead (player copies are "Name says, \"...\").
bool anchored =
RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, HandlerRingChannelStart, StringComparison.OrdinalIgnoreCase)
|| (RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, "The handler", StringComparison.OrdinalIgnoreCase)
&& text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) >= 0);
if (!anchored)
{
// Mid-line only when the type is clearly not player speech (some clients strip "The ").
if (chatType is RynthCore.Plugin.Shared.ChatSource.Speech
or RynthCore.Plugin.Shared.ChatSource.Tell
or RynthCore.Plugin.Shared.ChatSource.OutgoingTell
or RynthCore.Plugin.Shared.ChatSource.Channel
or RynthCore.Plugin.Shared.ChatSource.ChannelSend
or RynthCore.Plugin.Shared.ChatSource.Allegiance
or RynthCore.Plugin.Shared.ChatSource.Fellowship)
return;
if (text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) < 0) return;
if (text.IndexOf(" says,", StringComparison.OrdinalIgnoreCase) >= 0
|| text.IndexOf(" tells you,", StringComparison.OrdinalIgnoreCase) >= 0)
return;
}
DateTime now = DateTime.Now;
if (_handlerRingEvadeAt != DateTime.MinValue
&& (now - _handlerRingEvadeAt).TotalMilliseconds < HandlerRingEvadeCooldownMs)
return;
if (!TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name))
{
_host.Log("[CombatEvade] Handler lethal-ring channel heard, but no Empyrean Handler is nearby — no jump.");
return;
}
double danger = Math.Max(HandlerRingDangerYards, Math.Max(1, _settings.RingRange));
if (dist > danger)
{
_host.Log($"[CombatEvade] Handler lethal-ring channel; '{name}' at {dist:0.0} m (outside {danger:0.#} m) — staying put.");
return;
}
// Face the Handler, then Jumper "xs" (back + run) moves the body away from it.
// Facing away + back-jump would leap into the ring.
float faceHandler = 0f;
if (TryGetHeadingTo(handlerId, out double toHandler, out _))
faceHandler = (float)(toHandler % 360.0);
else if (_host.TryGetPlayerHeading(out float curr))
faceHandler = curr;
_handlerRingEvadeAt = now;
_handlerRingEvadeId = handlerId;
_handlerRingJumpStarted = false;
// Hold combat long enough for turn + charge + land + one re-engage tick.
_handlerRingEvadeUntil = now.AddMilliseconds(HandlerRingJumpHoldMs + 2_200);
// Stop the bound melee/missile attack so the jump isn't eaten by the swing servo.
try
{
if (_host.HasCancelAttack) _host.CancelAttack();
ReleaseHeldTurn();
}
catch { }
bool started = RequestBackJump?.Invoke(faceHandler, HandlerRingJumpHoldMs) == true;
if (started)
{
_handlerRingJumpStarted = true;
_host.Log($"[CombatEvade] Empyrean Handler lethal ring — back-jump away from '{name}' " +
$"at {dist:0.0} m (danger {danger:0.#} m), face {faceHandler:0}° then xs.");
}
else
{
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_host.Log("[CombatEvade] Empyrean Handler lethal ring heard in range, but the back-jump did not start.");
}
}
/// <summary>
/// Holds Think from attacking while the Handler-ring back-jump runs. Keeps the target
/// so combat re-engages as soon as the jumper settles.
/// </summary>
private bool TickRingEvade()
{
if (_handlerRingEvadeUntil == DateTime.MinValue) return false;
DateTime now = DateTime.Now;
bool jumperBusy = JumpBusy?.Invoke() == true;
// Jump never started / failed: clear early.
if (_handlerRingJumpStarted && !jumperBusy && now >= _handlerRingEvadeUntil)
{
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_handlerRingJumpStarted = false;
_host.Log("[CombatEvade] Handler ring evade done — re-engaging.");
return false;
}
if (jumperBusy || now < _handlerRingEvadeUntil)
{
LastCombatSkipReason = "handler-ring-evade";
_tickWait = CombatLatencyTracker.Wait.Other;
return true;
}
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_handlerRingJumpStarted = false;
_host.Log("[CombatEvade] Handler ring evade done — re-engaging.");
return false;
}
/// <summary>Nearest Empyrean Handler (active target preferred when it is one).</summary>
private bool TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name)
{
handlerId = 0; dist = double.MaxValue; name = "";
int me = _host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId();
if (me == 0) return false;
int bestId = 0;
double bestDist = double.MaxValue;
string bestName = "";
void Consider(int id, string? nm)
{
if (id == 0 || string.IsNullOrEmpty(nm)) return;
if (nm.IndexOf(HandlerNameHint, StringComparison.OrdinalIgnoreCase) < 0) return;
double d = _worldFilter.Distance(me, id);
if (d < 0 || d >= bestDist) return;
bestDist = d; bestId = id; bestName = nm;
}
if (activeTargetId != 0)
Consider(activeTargetId, _worldFilter[activeTargetId]?.Name);
foreach (var s in _scannedTargets)
Consider(s.Id, s.Name);
// Landscape fallback when the scan hasn't listed it yet (channel can land mid-approach).
if (bestId == 0)
{
try
{
foreach (WorldObject wo in _worldFilter.GetLandscape())
{
if ((int)wo.ObjectClass != (int)AcObjectClass.Monster) continue;
Consider(wo.Id, wo.Name);
}
}
catch { }
}
if (bestId == 0) return false;
handlerId = bestId; dist = bestDist; name = bestName;
return true;
}
public void ReportDamageOnTarget(int targetId)
{
_magicMissesSinceHit = 0; // something we cast landed: the server's position is fine
// Damage / health change on the cast we're judging → that cast HIT.
if (targetId == _pendingJudgeTargetId)
_damageSincePendingCast = true;
NoteEnvironmentEvidence();
// Immediate positive feedback on the engaged target clears the streak.
if (targetId == _lastAttackedTargetId)
_consecutiveCastMisses = 0;
@ -1904,6 +2113,7 @@ public partial class CombatManager : IDisposable
int i = text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase);
if (i < 0) i = text.IndexOf(" resists your spell", StringComparison.OrdinalIgnoreCase);
if (i <= 0) return;
NoteEnvironmentEvidence(); // the spell or swing reached a monster
string who = text.Substring(0, i).Trim();
if (who.StartsWith("The ", StringComparison.Ordinal)) who = who.Substring(4);
if (who.Length == 0) return;
@ -2225,6 +2435,9 @@ public partial class CombatManager : IDisposable
_host.Log($"[RynthAi] DropTarget 0x{activeTargetId:X8}: {reason} [{DescribeTargetPos(activeTargetId)}]");
activeTargetId = 0;
_lockedTargetId = 0;
EndKite("target dropped");
EndEnvironmentApproach("target dropped");
_envPendingTargetId = 0;
// A turn held toward the dropped target must be let go, or the character keeps
// spinning until something else happens to release it.
if (_facingTarget) ClearCombatTurnMotions();
@ -2675,9 +2888,15 @@ public partial class CombatManager : IDisposable
// one busy-count tick; only the first encounter of a wcid pays it.
if (!_fightAppraiseRequested)
{
_fightAppraiseRequested = true;
try { if (_host.HasRequestId) _host.RequestId((uint)_fightTargetId); } catch { }
try { if (_host.HasQueryHealth) _host.QueryHealth((uint)_fightTargetId); } catch { }
// Done only once the engine took the request (it refuses around a death or a portal; a refused one
// is asked again next tick). No RequestId at all: nothing to wait for.
bool idTaken = true;
try { if (_host.HasRequestId) idTaken = _host.RequestId((uint)_fightTargetId); } catch { }
if (idTaken)
{
_fightAppraiseRequested = true;
try { if (_host.HasQueryHealth) _host.QueryHealth((uint)_fightTargetId); } catch { }
}
}
}
@ -2727,6 +2946,7 @@ public partial class CombatManager : IDisposable
int id = _scannedTargets[i].Id;
if (id == excludeId) continue;
if (_recentlyKilled.ContainsKey(id)) continue;
if (IsEnvironmentSkipped(id)) continue;
return true;
}
return false;
@ -2878,6 +3098,11 @@ public partial class CombatManager : IDisposable
return true;
}
// Empyrean Handler lethal-ring back-jump: hold casts/swings until the jump settles,
// then fall through and re-engage the same target.
if (TickRingEvade())
return true;
double acDistanceLimit = _settings.MonsterRange;
// Hysteresis: a locked target is retained (and kept under attack) out to
// the larger disengage distance, while new targets are still only
@ -2977,7 +3202,7 @@ public partial class CombatManager : IDisposable
ForgetScanned(activeTargetId);
DropTarget("hp=0");
}
else if (target != null &&
else if (target != null && !KiteActive &&
_worldFilter.Distance(_host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId) > disengageLimit)
DropTarget("out of range");
// If target == null here it's a transient world-filter miss — keep the lock,
@ -3098,9 +3323,18 @@ public partial class CombatManager : IDisposable
// step-back — instead of dropping to peace and restarting the approach.
double currentDist = _worldFilter.Distance(
_host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId);
// Pull-away kite runs before the disengage gate: fleeing intentionally stretches
// range, and the kite itself waits for catch-up rather than idling here.
if (RunKite(targetObj, currentDist))
return true;
if (currentDist > disengageLimit)
return true;
// Environment-impact throttle: too many missiles/spells into walls short of this target
// stop the attack and move closer or switch target (CombatManager.EnvironmentImpact.cs).
if (RunEnvironmentImpact(targetObj, currentDist))
return true;
// Melee/missile stall safety net (see CombatStallWatchdog). Holds the attack while
// one of its steps is settling.
if (RunStallWatchdog(targetObj, currentDist))
@ -3929,13 +4163,23 @@ public partial class CombatManager : IDisposable
{
_wasMacroRunning = false;
ClearCombatTurnMotions();
ResetEnvironmentImpact("macro stopped");
ResetKite("macro stopped");
}
return;
}
_wasMacroRunning = true;
NotePriorityZeroRules();
LogCombatStateIfChanged();
// Environment-impact throttle: follow our spell projectiles, judge finished casts, and
// let go of an approach Think stopped driving.
try { PollEnvironmentImpact(); }
catch (Exception ex) { _host.Log($"[EnvImpact] poll crashed: {ex.Message}"); }
try { PollKite(); }
catch (Exception ex) { _host.Log($"[Kite] poll crashed: {ex.Message}"); }
// A combat mode change ends the server's attack (HandleActionChangeCombatMode →
// HandleActionCancelAttack), so out of Melee/Missile there is nothing bound to release.
if (_serverAttackTargetId != 0)
@ -4016,6 +4260,8 @@ public partial class CombatManager : IDisposable
{
if (_scannedTargets.Count == 0) return;
if (TryLockForcedTarget()) return; // Target lock (/ra targetlock): CombatManager.TargetLock.cs
// Pull-away in progress: keep the incumbent until the kite ends (do not switch mid-flee).
if (KiteActive && _lockedTargetId != 0) return;
// Boost Loot Priority: the next target waits for the last kill's corpse. Without this the
// next lock went out a few ms after each kill, 1-3 s before ACE creates the corpse, so the
// arbiter always saw combat engaged and corpses were looted in batches (2026-10-14).
@ -4236,6 +4482,35 @@ public partial class CombatManager : IDisposable
return progress != DateTime.MinValue && (now - progress).TotalMilliseconds <= UndamagedCommitmentMaxMs;
}
private List<MonsterRule>? _priorityZeroNoticeRules;
private string _priorityZeroNoticeKey = "";
/// <summary>
/// Priority 0 on a monster rule now means "never attacked or tracked" (before, it was a lowest
/// priority that still fought back). A profile written under the old meaning would silently stop
/// fighting those monsters, so the first time a rule list holds any, one log line and one chat
/// notice say what it does now (again only if the set of Priority 0 rules changes, e.g. another
/// profile loads). Behavior is not changed.
/// </summary>
internal void NotePriorityZeroRules()
{
var rules = _settings.MonsterRules;
if (ReferenceEquals(rules, _priorityZeroNoticeRules)) return;
_priorityZeroNoticeRules = rules;
List<string>? zero = null;
foreach (var rule in rules)
if (rule.Priority <= 0) (zero ??= new List<string>()).Add(string.IsNullOrWhiteSpace(rule.Name) ? "(unnamed)" : rule.Name);
if (zero == null) { _priorityZeroNoticeKey = ""; return; }
string key = string.Join("|", zero).ToLowerInvariant();
if (key == _priorityZeroNoticeKey) return;
_priorityZeroNoticeKey = key;
string names = zero.Count <= 5 ? string.Join(", ", zero) : string.Join(", ", zero.GetRange(0, 5)) + $" and {zero.Count - 5} more";
string line = $"[RynthAi] Monsters: Priority 0 now means 'never attacked or tracked', even if the monster attacks you " +
$"(rows with Priority 0: {names}). Raise the row's Priority to fight it.";
_host.Log(line);
_host.WriteToChat(line, 2);
}
/// <summary>True when the monster rule for <paramref name="id"/> says Priority 0 (never attacked).</summary>
internal bool IsIgnored(int id) => id != ForcedTargetId && PriorityOf(id) <= 0;
@ -6101,17 +6376,26 @@ public partial class CombatManager : IDisposable
return false;
}
float power;
// Power: the monster rule's Attack Power (High / Reckless / Variable / Reckless +
// Variable), else the global Melee/Missile Power (AttackPowerPlanner.cs).
int powerPct = isMissile ? _settings.MissileAttackPower : _settings.MeleeAttackPower;
if (powerPct < 0)
bool recklessTrained = _charSkills == null || _charSkills[AcSkillType.Recklessness].Training >= 2;
// No rule asking for a power (every rule on Default, as saved before this existed):
// the rule lookup is skipped, the global setting applies exactly as it always did.
WorldObject? powerTarget = null;
string powerMode = AttackPowerModes.Default;
if (AnyAttackPowerRule())
{
power = 1.0f;
if (_settings.UseRecklessness && (_charSkills == null || _charSkills[AcSkillType.Recklessness].Training >= 2))
power = 0.8f;
powerTarget = _worldFilter[activeTargetId];
powerMode = AttackPowerModes.Effective(GetRuleForTarget(powerTarget), DefaultMonsterRule());
}
else
float power = AttackPowerModes.Resolve(powerMode, powerPct, _settings.UseRecklessness, recklessTrained,
_settings.VariablePowerMin, _settings.VariablePowerMax, PowerRandom);
if (powerMode != AttackPowerModes.Default && _powerLoggedTargetId != activeTargetId)
{
power = powerPct / 100f;
_powerLoggedTargetId = activeTargetId;
_host.Log($"[AttackPower] 0x{targetId:X8} '{powerTarget?.Name}': {powerMode}" +
(recklessTrained ? "" : " (Recklessness untrained: no reckless band)") + $", first attack at {power * 100:0}%");
}
int uiHeight = isMissile ? _settings.MissileAttackHeight : _settings.MeleeAttackHeight;
@ -6173,10 +6457,25 @@ public partial class CombatManager : IDisposable
if (matches) return r;
}
return _settings.MonsterRules.FirstOrDefault(
m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
return DefaultMonsterRule();
}
/// <summary>The Monsters tab's DEFAULT line (the catch-all rule), or null.</summary>
private MonsterRule? DefaultMonsterRule() => _settings.MonsterRules.FirstOrDefault(
m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
/// <summary>True when some monster rule has an Attack Power other than Default.</summary>
private bool AnyAttackPowerRule()
{
foreach (MonsterRule r in _settings.MonsterRules)
if (AttackPowerModes.Normalize(r.AttackPower) != AttackPowerModes.Default) return true;
return false;
}
/// <summary>Random source for Variable attack power, [0, 1); tests replace it.</summary>
internal Func<double> PowerRandom { get; set; } = Random.Shared.NextDouble;
private int _powerLoggedTargetId;
private void AttackWithMagic(WorldObject target)
{
_wallFaceHeld = false;
@ -6282,11 +6581,8 @@ public partial class CombatManager : IDisposable
}
}
// A script chooses this cast (RynthAi.Combat, CombatManager.ScriptHook.cs): ask it, wait for
// its answer (held, not an attack yet), cast what it chose; a decline, a bad answer or no
// answer in time falls through to RynthAi's own choice below, this same tick.
if (TryScriptAttack(target, element)) return;
// A rule with no attack shape on means no offensive cast at this monster: a script's choice
// is no exception (it used to be asked first, and cast at a monster the owner turned casting off for).
if (rule != null && PickBaseShape(rule) < 0)
{
_host.Log($"[CombatCast] rule '{rule.Name}' has no attack shapes enabled (UseArc/Ring/Streak/Bolt/Blast/Wall all false) — no offensive cast");
@ -6294,6 +6590,11 @@ public partial class CombatManager : IDisposable
return;
}
// A script chooses this cast (RynthAi.Combat, CombatManager.ScriptHook.cs): ask it, wait for
// its answer (held, not an attack yet), cast what it chose; a decline, a bad answer or no
// answer in time falls through to RynthAi's own choice below, this same tick.
if (TryScriptAttack(target, element)) return;
int warTier = _spellManager?.GetHighestSpellTier(AcSkillType.WarMagic) ?? 0;
int voidTier = _spellManager?.GetHighestSpellTier(AcSkillType.VoidMagic) ?? 0;
int offensiveSpellId = FindBestShapedSpell(element, rule, out bool isRing, out int castShape, arcTargetId: activeTargetId);
@ -6353,6 +6654,10 @@ public partial class CombatManager : IDisposable
_pendingOffensiveCastAt = DateTime.Now;
_pendingOffensiveTargetId = activeTargetId;
NoteOffensiveSeq();
// Environment-impact throttle: follow this cast's projectiles (rings and walls
// don't fly at the target, so they aren't judged).
if (!multiTarget)
RegisterCastWatch(activeTargetId, SpellTableStub.GetById(offensiveSpellId)?.Name ?? $"spell {offensiveSpellId}");
// Tag this cast's weapon + element + tier so the pushed damage event
// can be attributed to it, count it for casts-to-kill learning, then

View file

@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
// ============================================================================
// Environment-impact throttle (2026-10-12): pure rules and bookkeeping.
//
// A missile or a war/void projectile that hits a wall, a pillar, the ceiling
// or another object short of the target does no damage, and before this the bot
// kept firing into it until the no-damage blacklist (several settle windows) or
// the no-progress timeout gave up. Now, once a target has taken
// EnvironmentImpactLimit such hits within EnvironmentImpactWindowSec, combat
// stops attacking it and does what the player chose for that kind of combat:
// move closer, pick another target, or move closer once and then pick another.
//
// The signals (CombatManager.EnvironmentImpact.cs):
// missile ACE ProjectileCollisionHelper.OnCollideEnvironment sends the shooter
// "Your missile attack hit the environment." (also when the arrow hits
// an object that isn't its target).
// magic ACE sends nothing (SpellProjectile.OnCollideEnvironment only
// explodes the projectile), so the bot follows its own projectiles and
// judges where they stopped (ProjectileImpactJudge).
//
// Everything here is pure (no host, no clock of its own) so the host tests can
// drive it directly.
// ============================================================================
/// <summary>What combat does once a target has taken too many environment hits.
/// Stored as an int in the settings (MissileEnvironmentResponse / MagicEnvironmentResponse).</summary>
public enum EnvironmentResponse
{
/// <summary>No detection; keep attacking (the behaviour before 2026-10-12).</summary>
Off = 0,
/// <summary>Move toward the target each time; once already close, pick another target.</summary>
MoveCloser = 1,
/// <summary>Skip the target for a while and pick another (moves closer when there is no other).</summary>
NewTarget = 2,
/// <summary>Move closer once; if the shots still hit the environment, pick another target.</summary>
CloserThenNewTarget = 3,
}
/// <summary>The step combat takes for one throttle trip.</summary>
public enum EnvironmentAction { None, Approach, NewTarget }
/// <summary>Choices and the decision for one throttle trip.</summary>
public static class EnvironmentImpactPlanner
{
/// <summary>Combo labels, in <see cref="EnvironmentResponse"/> order (plugin and engine settings panels).</summary>
public static readonly string[] ResponseNames =
{ "Off", "Move closer", "New target", "Move closer, then new target" };
/// <summary>Approaching is pointless within this much of the closest allowed distance.</summary>
public const double ApproachSlackMeters = 0.5;
/// <summary>A saved int as a response; anything out of range is Off.</summary>
public static EnvironmentResponse Parse(int value)
=> value is >= 0 and <= 3 ? (EnvironmentResponse)value : EnvironmentResponse.Off;
/// <summary>The label for a saved value (logs and the settings panels).</summary>
public static string Name(int value) => ResponseNames[(int)Parse(value)];
/// <summary>
/// The step for a throttle trip on a target <paramref name="distance"/> metres away that
/// has already been approached <paramref name="approachesDone"/> times for this reason.
/// Never approaches nearer than <paramref name="minDistance"/>. A new target needs another
/// monster in reach: skipping the only one would leave it free to hit the bot while combat
/// idles, so then the bot moves closer if it still can, or keeps attacking (None).
/// </summary>
public static EnvironmentAction Decide(EnvironmentResponse response, int approachesDone,
double distance, double minDistance, bool hasAlternateTarget)
{
bool canApproach = double.IsFinite(distance) && distance > minDistance + ApproachSlackMeters;
EnvironmentAction approachElseNone = canApproach ? EnvironmentAction.Approach : EnvironmentAction.None;
EnvironmentAction newTargetElse = hasAlternateTarget ? EnvironmentAction.NewTarget : approachElseNone;
return response switch
{
EnvironmentResponse.MoveCloser => canApproach ? EnvironmentAction.Approach : newTargetElse,
EnvironmentResponse.NewTarget => newTargetElse,
EnvironmentResponse.CloserThenNewTarget => approachesDone == 0 && canApproach
? EnvironmentAction.Approach : newTargetElse,
_ => EnvironmentAction.None,
};
}
/// <summary>
/// Where an approach stops: <paramref name="stepMeters"/> nearer than now, never nearer
/// than <paramref name="minDistance"/>.
/// </summary>
public static double ApproachGoal(double distance, double stepMeters, double minDistance)
=> Math.Max(Math.Max(0.5, minDistance), distance - Math.Max(1.0, stepMeters));
}
/// <summary>
/// Environment hits per target inside a sliding window, and how many times each target has
/// been approached for them. Pump thread only.
/// </summary>
public sealed class EnvironmentImpactThrottle
{
private readonly Dictionary<int, List<DateTime>> _hits = new();
private readonly Dictionary<int, int> _approaches = new();
// A long session meets thousands of monsters; ids are forgotten on delete, this is the backstop.
private const int MaxTracked = 256;
/// <summary>Records one hit on <paramref name="targetId"/> and returns the hits within the window.</summary>
public int Record(int targetId, DateTime now, double windowSec)
{
if (targetId == 0) return 0;
if (_hits.Count >= MaxTracked && !_hits.ContainsKey(targetId)) _hits.Clear();
if (!_hits.TryGetValue(targetId, out var list)) _hits[targetId] = list = new List<DateTime>(4);
list.Add(now);
Prune(list, now, windowSec);
return list.Count;
}
/// <summary>Hits on <paramref name="targetId"/> within the window (no new hit).</summary>
public int Count(int targetId, DateTime now, double windowSec)
{
if (!_hits.TryGetValue(targetId, out var list)) return 0;
Prune(list, now, windowSec);
return list.Count;
}
/// <summary>Starts the count again (after the bot acted on it).</summary>
public void ResetHits(int targetId) => _hits.Remove(targetId);
public int Approaches(int targetId) => _approaches.TryGetValue(targetId, out int n) ? n : 0;
public void NoteApproach(int targetId)
{
if (_approaches.Count >= MaxTracked && !_approaches.ContainsKey(targetId)) _approaches.Clear();
_approaches[targetId] = Approaches(targetId) + 1;
}
/// <summary>The object is gone (deleted): a respawn reusing the id starts clean.</summary>
public void Forget(int targetId)
{
_hits.Remove(targetId);
_approaches.Remove(targetId);
}
public void Clear()
{
_hits.Clear();
_approaches.Clear();
}
private static void Prune(List<DateTime> list, DateTime now, double windowSec)
{
double window = Math.Max(1.0, windowSec);
list.RemoveAll(t => (now - t).TotalSeconds > window);
}
}
/// <summary>
/// Where a spell projectile stopped, against where the target is. A projectile that reaches
/// the target stops at its surface; one that hits the environment stops short of it, toward
/// the caster. Both conditions must hold, so a large monster (its surface a few metres from its
/// centre) isn't read as a wall. The caller also requires that no hit, resist or evade line
/// arrived for the cast: that is the final word for a large monster or an odd stop.
/// </summary>
public static class ProjectileImpactJudge
{
/// <summary>A stop farther than this from the target's centre didn't touch it.</summary>
public const double MissRadiusMeters = 4.0;
/// <summary>A stop at least this much nearer to the caster than the target is "short".</summary>
public const double ShortByMeters = 2.0;
/// <summary>A projectile that flew less than this never really left (or was never ours).</summary>
public const double MinTravelMeters = 1.0;
/// <summary>True when the projectile stopped short of the target and away from it.</summary>
public static bool StoppedShort(double impactToTarget, double casterToImpact, double casterToTarget)
{
if (!double.IsFinite(impactToTarget) || !double.IsFinite(casterToImpact) || !double.IsFinite(casterToTarget))
return false;
return impactToTarget > MissRadiusMeters && casterToImpact + ShortByMeters < casterToTarget;
}
}

View file

@ -309,6 +309,9 @@ public class FellowshipTracker : IDisposable
return IsReadablePointer(fel) ? fel : IntPtr.Zero;
}
/// <summary>Drops the refresh throttle: the next read re-walks the client's member table (RynthOracle's Refresh button).</summary>
public void Invalidate() => _lastRefresh = DateTime.MinValue;
private void RefreshIfNeeded()
{
if ((DateTime.Now - _lastRefresh).TotalMilliseconds < REFRESH_INTERVAL_MS) return;

View file

@ -0,0 +1,79 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
// ============================================================================
// Per-monster kite / pull-away (2026-10-16): MonsterRule.Kite.
//
// Default the DEFAULT line's choice; on the DEFAULT line, Off (fight in place)
// Off engage and kill where the mob stands
// PullAway after a brief tag, run away until the mob has been pulled
// KitePullMeters from its lock-spot origin, then kill it alone
//
// Resolution matches AttackPowerModes: a rule's own value wins; "Default" falls
// through to the DEFAULT row; blank/unknown is Default (→ Off via the DEFAULT row).
// ============================================================================
/// <summary>Names and resolution of <see cref="MonsterRule.Kite"/>.</summary>
public static class KiteModes
{
public const string Default = "Default";
public const string Off = "Off";
public const string PullAway = "PullAway";
/// <summary>Every choice, in the order the editors list them.</summary>
public static readonly string[] All = { Default, Off, PullAway };
/// <summary>Combo labels (plugin Advanced + engine Monsters/Damage panels).</summary>
public static readonly string[] DisplayNames = { "Default", "Off", "Pull away" };
/// <summary>A saved value as one of <see cref="All"/>; blank or unknown is Default.</summary>
public static string Normalize(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return Default;
string v = value.Trim();
foreach (string m in All)
if (m.Equals(v, StringComparison.OrdinalIgnoreCase)) return m;
// Hand-typed / UI spellings: "Pull away", "pull-away", "Kite".
string squeezed = v.Replace(" ", "").Replace("-", "").Replace("_", "");
if (squeezed.Equals("PullAway", StringComparison.OrdinalIgnoreCase)
|| squeezed.Equals("Kite", StringComparison.OrdinalIgnoreCase)
|| squeezed.Equals("Pull", StringComparison.OrdinalIgnoreCase))
return PullAway;
if (squeezed.Equals("None", StringComparison.OrdinalIgnoreCase)
|| squeezed.Equals("Disabled", StringComparison.OrdinalIgnoreCase))
return Off;
return Default;
}
/// <summary>
/// The mode that applies to a monster: its own rule's, else the DEFAULT line's.
/// On the DEFAULT line, Default resolves to Off (safe: no pull until the player opts in).
/// </summary>
public static string Effective(MonsterRule? rule, MonsterRule? defaultRule)
{
string own = Normalize(rule?.Kite);
if (own != Default) return own;
// The DEFAULT row itself: Default means Off.
if (rule != null && defaultRule != null
&& ReferenceEquals(rule, defaultRule))
return Off;
if (rule != null && string.Equals(rule.Name, "Default", StringComparison.OrdinalIgnoreCase))
return Off;
string fromDefault = Normalize(defaultRule?.Kite);
return fromDefault == Default ? Off : fromDefault;
}
/// <summary>True when combat should pull this monster before finishing it.</summary>
public static bool WantsPullAway(MonsterRule? rule, MonsterRule? defaultRule)
=> Effective(rule, defaultRule) == PullAway;
/// <summary>Label for logs and tooltips.</summary>
public static string Name(string? value) => Normalize(value) switch
{
PullAway => "Pull away",
Off => "Off",
_ => "Default",
};
}

View file

@ -54,6 +54,17 @@ public class MissileCraftingManager
private const int EQUIP_DELAY_MS = 500;
private const int ERROR_BACKOFF_MS = 60000;
// An ammo wield the server ignores (ammo that doesn't fit the launcher really in hand) came
// round again every AMMO_CHECK_INTERVAL_MS, and each try stopped nav while it waited for the
// answer: Silentkelpie stood still ~3.5 s of every 5 on 2026-10-15. The same item sent more
// than MAX_EQUIP_REPEATS times inside EQUIP_REPEAT_WINDOW_MS backs off instead.
private const int EQUIP_REPEAT_WINDOW_MS = 30000;
private const int MAX_EQUIP_REPEATS = 2;
private const int EQUIP_IGNORED_BACKOFF_MS = 120000;
private int _lastEquipSentId;
private DateTime _lastEquipSentAt = DateTime.MinValue;
private int _equipRepeats;
private int _headBundleId = 0;
private int _shaftBundleId = 0;
private AmmoRecipe? _currentRecipe = null;
@ -145,13 +156,15 @@ public class MissileCraftingManager
_lastAmmoCheck = DateTime.Now;
var inv = GetInventory(forceRefresh: true);
if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category))
if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category, out WorldObject? launcher))
return;
_lastWeaponCategory = category;
if (HasWieldedAmmo(inv, category))
return;
_host.Log($"[RynthAi] MissileCraft: no {GetCategoryLabel(category)} wielded with launcher " +
$"0x{launcher!.Id:X8} '{launcher.Name}' (slot {launcher.WieldedLocation}); evaluating");
ChatLog($"No wielded {GetCategoryLabel(category)}s. Evaluating...");
SetState(CraftState.Evaluating);
}
@ -350,6 +363,18 @@ public class MissileCraftingManager
if (targetId != 0)
{
if (!NoteEquipSent(targetId))
{
string name = inv.FirstOrDefault(i => i.Id == targetId)?.Name ?? $"0x{targetId:X8}";
string why = $"The server didn't wield {name} after {MAX_EQUIP_REPEATS} tries; " +
$"leaving the ammo alone for {EQUIP_IGNORED_BACKOFF_MS / 60000} minutes";
_host.Log($"[RynthAi] MissileCraft: {why} (0x{targetId:X8})");
Reset(why);
_equipRepeats = 0;
_lastAmmoCheck = DateTime.Now.AddMilliseconds(EQUIP_IGNORED_BACKOFF_MS - AMMO_CHECK_INTERVAL_MS);
return;
}
_host.UseFor((uint)targetId, "Crafting", "missile crafting: wield the new ammo");
ChatLog($"Equipped ammo (id=0x{targetId:X8})");
Reset($"Done: {_currentRecipe?.OutputName ?? "ammo"}");
@ -382,9 +407,9 @@ public class MissileCraftingManager
private List<WorldObject> GetInventory(bool forceRefresh = false)
=> _objectCache?.GetDirectInventory(forceRefresh).ToList() ?? new();
private WeaponCategory ResolveWeaponCategory(IEnumerable<WorldObject> inventory)
private WeaponCategory ResolveWeaponCategory(List<WorldObject> inventory)
{
if (TryGetWieldedMissileCategory(inventory, out WeaponCategory category))
if (TryGetWieldedMissileCategory(inventory, out WeaponCategory category, out _))
{
_lastWeaponCategory = category;
return category;
@ -393,24 +418,29 @@ public class MissileCraftingManager
return _lastWeaponCategory;
}
private bool TryGetWieldedMissileCategory(IEnumerable<WorldObject> inventory, out WeaponCategory category)
private bool TryGetWieldedMissileCategory(List<WorldObject> inventory, out WeaponCategory category,
out WorldObject? launcher)
{
foreach (var item in inventory)
foreach (var item in WornCandidates(inventory))
{
if (!IsPlayerWielded(item) || !LooksLikeMissileWeapon(item))
// AC files ammo as a missile weapon: wielded quarrels must not pass for the launcher
// (no "crossbow" in the name reads as a bow, and arrows went on at the crossbow).
if (WorldObjectCache.IsAmmo(item) || !IsPlayerWielded(item) || !LooksLikeMissileWeapon(item))
continue;
category = GetWeaponCategory(item.Name);
launcher = item;
return true;
}
category = WeaponCategory.Bow;
launcher = null;
return false;
}
private bool HasWieldedAmmo(IEnumerable<WorldObject> inventory, WeaponCategory category)
private bool HasWieldedAmmo(List<WorldObject> inventory, WeaponCategory category)
{
foreach (var item in inventory)
foreach (var item in WornCandidates(inventory))
{
if (!IsPlayerWielded(item))
continue;
@ -422,16 +452,62 @@ public class MissileCraftingManager
return false;
}
/// <summary>
/// The direct scan plus the cache-known items it left out. The scan merges worn gear only when
/// its slot reads above 0, and the slot reads 0 for gear wielded after login (a launcher combat
/// swapped in, and its ammo), so the launcher really in hand was missing from the scan alone.
/// </summary>
private IEnumerable<WorldObject> WornCandidates(List<WorldObject> inventory)
{
foreach (var item in inventory)
yield return item;
if (_objectCache == null)
yield break;
var listed = new HashSet<int>(inventory.Select(i => i.Id));
foreach (var item in _objectCache.GetInventory())
if (listed.Add(item.Id))
yield return item;
}
private bool IsPlayerWielded(WorldObject item)
{
if (item.WieldedLocation <= 0)
// Found inside a pack by the direct scan: AC's container lists never hold worn gear. A
// launcher put away after a swap keeps its old wielder and slot in the client's object
// description, so the slot alone said a stowed bow was in hand while a crossbow was, and
// arrows were wielded at it every 5 s (Silentkelpie, 2026-10-15).
if (item.DirectContainerId != 0)
return false;
uint playerId = _host.GetPlayerId();
if (playerId == 0)
return false;
return item.Wielder == 0 || item.Wielder == unchecked((int)playerId);
if (item.WieldedLocation > 0)
return item.Wielder == 0 || item.Wielder == unchecked((int)playerId);
// The slot reads 0 for gear wielded after login; the wielder still names the player.
return _host.HasGetObjectWielderInfo
&& _host.TryGetObjectWielderInfo(unchecked((uint)item.Id), out uint wielder, out _)
&& wielder == playerId;
}
/// <summary>
/// Counts an ammo wield about to go out; false once the same item was already sent
/// <see cref="MAX_EQUIP_REPEATS"/> times inside <see cref="EQUIP_REPEAT_WINDOW_MS"/>.
/// </summary>
private bool NoteEquipSent(int targetId)
{
DateTime now = DateTime.Now;
if (targetId == _lastEquipSentId && (now - _lastEquipSentAt).TotalMilliseconds < EQUIP_REPEAT_WINDOW_MS)
_equipRepeats++;
else
_equipRepeats = 1;
_lastEquipSentId = targetId;
_lastEquipSentAt = now;
return _equipRepeats <= MAX_EQUIP_REPEATS;
}
private static bool LooksLikeMissileWeapon(WorldObject item)

View file

@ -22,7 +22,8 @@ namespace RynthCore.Plugin.RynthAi;
/// Behaviour (per user spec):
/// * Summon only when mobs are near — at least <c>PetMinMonsters</c> scanned,
/// attackable monsters within <c>CustomPetRange</c> — and no pet is currently
/// active. Re-summon when the pet despawns mid-fight.
/// active. Re-summon when the pet despawns mid-fight (lifespan / death), after
/// the essence's retail ~45 s use cooldown (Summoning wiki / ACE PetDevice).
/// * Auto-refill an empty essence from an Encapsulated Spirit in inventory
/// (gated on <c>PetAutoRefill</c>).
///
@ -30,6 +31,12 @@ namespace RynthCore.Plugin.RynthAi;
/// guarded, one in-flight action at a time. Entirely plugin-side; the only AC
/// actions issued are <c>Host.UseObject</c> (summon) and <c>Host.UseObjectOn</c>
/// (refill), both selection-free.
///
/// Stuck/fail (Kelpie 2026-10-16): a Use that the server refused (cooldown, incline,
/// busy) never drops Structure and never spawns a pet. The old path still assumed a
/// pet for 10 s and parked the essence only 30 s — short of the 45 s item cooldown —
/// so the next try timed out again. Failed summons no longer assume a pet; every
/// Use parks the essence for <see cref="DeviceUseCooldownMs"/>.
/// </summary>
internal sealed class PetManager
{
@ -55,6 +62,7 @@ internal sealed class PetManager
// pet is active for at least this long, so we don't re-issue before the new
// pet's CreateObject lands in the cache. Name-detection takes over once it does.
private long _assumePetActiveUntil;
private bool _petSeenSinceSummon; // the pet has shown up in the cache during this assume window
// Devices that just failed (skill too low, timed out, empty with no spirit)
// get parked so we advance to the next configured essence instead of looping.
@ -76,8 +84,14 @@ internal sealed class PetManager
private const long ThinkIntervalMs = 1000;
private const long ActionTimeoutMs = 8000;
/// <summary>Hold after a confirmed summon until the pet lands in the landscape cache (kept at the base's 10 s).</summary>
private const long AssumeActiveAfterSummonMs = 10_000;
private const long DeviceFailCooldownMs = 30_000;
/// <summary>
/// Retail / ACE PetDevice use cooldown (~45 s). Applies after every Use we fire — success
/// or fail — so we do not re-Use while the server still refuses the essence.
/// </summary>
private const long DeviceUseCooldownMs = 45_000;
private const long DeviceFailCooldownMs = 30_000; // a refill that timed out (a summon is parked from IssueSummon)
private const long DeviceNoSpiritCooldownMs = 15_000;
private const long ServerSaidFullTrustMs = 30 * 60_000;
private const long RefillWindowMs = 120_000; // two refills inside this and the
@ -140,7 +154,7 @@ internal sealed class PetManager
{
_summonElement = PetChoice.ElementOf(_host, unchecked((uint)_activeDeviceId),
_objectCache[_activeDeviceId]?.Name ?? "");
_assumePetActiveUntil = now + AssumeActiveAfterSummonMs;
AssumePetFor(now, AssumeActiveAfterSummonMs);
GoIdle();
}
}
@ -158,13 +172,27 @@ internal sealed class PetManager
// decrement that never lands), and waiting on it would wedge the subsystem.
if (_state != PetState.Idle && now - _actionIssuedAt > ActionTimeoutMs)
{
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8}); cooling down.");
if (_activeDeviceId != 0)
_deviceCooldownUntil[_activeDeviceId] = now + DeviceFailCooldownMs;
// A summon that we simply couldn't confirm very likely DID work — assume
// a pet for a bit so we don't immediately re-issue into "already active".
if (_state == PetState.Summoning)
_assumePetActiveUntil = now + AssumeActiveAfterSummonMs;
bool summonConfirmed = _state == PetState.Summoning
&& (SummonLanded() || IsPetActive());
// Host.Log so FakeHost / in-game logs see it; RynthLog for the Pets category file.
string timeoutMsg =
$"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8})"
+ (summonConfirmed
? "; summon confirmed late."
: "; no charge drop / no pet — treating as failed Use.");
_host.Log(timeoutMsg);
RynthLog.Write(LogCat.Pets, timeoutMsg);
// Do NOT restart DeviceUseCooldownMs here — IssueSummon already parked the essence
// from the Use instant. Re-arming from timeout would wait ~53 s and leave gaps
// after a refused Use (Kelpie stuck/fail).
// Only assume a pet when the Use clearly landed; a failed Use must not block
// resummon after the cooldown (false assume + short park left gaps).
if (_state != PetState.Summoning && _activeDeviceId != 0)
_deviceCooldownUntil[_activeDeviceId] = now + DeviceFailCooldownMs; // refill timeout: park as before
if (summonConfirmed)
AssumePetFor(now, AssumeActiveAfterSummonMs);
else if (_state == PetState.Summoning)
_assumePetActiveUntil = 0;
Reset();
return;
}
@ -186,7 +214,7 @@ internal sealed class PetManager
// "<pet> is already active" — a pet is up but our detection lagged. Back off.
if (text.Contains("is already active", StringComparison.OrdinalIgnoreCase))
{
_assumePetActiveUntil = NowMs + AssumeActiveAfterSummonMs;
AssumePetFor(NowMs, AssumeActiveAfterSummonMs);
GoIdle();
return;
}
@ -196,10 +224,15 @@ internal sealed class PetManager
{
_host.Log($"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
_serverSaidFullUntil.Remove(_activeDeviceId); // really empty: the read is right again
// The server-side pyreal refill didn't happen (charm off / no pyreals):
// park the essence so the empty-summon path can't spin on it.
if (AllowSummonOnEmpty?.Invoke() == true && _activeDeviceId != 0)
_deviceCooldownUntil[_activeDeviceId] = NowMs + DeviceNoSpiritCooldownMs;
// Empty Use does not burn the retail 45 s spawn cooldown the way a real summon
// does; drop the Use park so the next think can refill (or re-try pyreal path).
if (_activeDeviceId != 0)
{
if (AllowSummonOnEmpty?.Invoke() == true)
_deviceCooldownUntil[_activeDeviceId] = NowMs + DeviceNoSpiritCooldownMs;
else
_deviceCooldownUntil.Remove(_activeDeviceId);
}
GoIdle();
return;
}
@ -223,15 +256,32 @@ internal sealed class PetManager
// ── Decision ───────────────────────────────────────────────────────────────
/// <summary>Treat a pet as out until <paramref name="now"/> + <paramref name="ms"/> (it may not be in the cache yet).</summary>
private void AssumePetFor(long now, long ms)
{
_assumePetActiveUntil = now + ms;
_petSeenSinceSummon = false;
}
private void TryBeginAction(long now)
{
// A pet is already up (just summoned, or detected in the world) — done.
if (now < _assumePetActiveUntil) return;
if (IsPetActive())
// If the assume window is still open but the pet is gone (despawn / death), clear it
// so we can wait on the essence cooldown and resummon.
bool petOut = IsPetActive();
if (now < _assumePetActiveUntil)
{
if (petOut) { _petSeenSinceSummon = true; return; }
// The pet came and went (died / lifespan ended): don't wait out the window. A pet that has not
// landed in the cache yet keeps the window, or a second essence would be summoned beside it.
if (!_petSeenSinceSummon) return;
_assumePetActiveUntil = 0;
}
if (petOut)
{
// A cosmetic pet in the slot steps aside for the fight; wait for the dismiss to land.
if (YieldPetForCombat != null && MonstersNearby() && YieldPetForCombat())
_assumePetActiveUntil = now + 3000;
AssumePetFor(now, 3000);
return;
}
if (HoldSummons?.Invoke() == true) return;
@ -298,15 +348,18 @@ internal sealed class PetManager
private void IssueSummon(int deviceId, int charges)
{
// Don't fire the essence-use while a cast gesture is animating — AC
// refuses item use mid-gesture, which would burn the 8s timeout and a
// 30s device park for nothing. No state change; caller retries next tick.
// refuses item use mid-gesture, which would burn the 8s timeout and the
// 45 s essence cooldown for nothing. No state change; caller retries next tick.
if (!_host.CanCastNow) return;
long now = NowMs;
_state = PetState.Summoning;
_activeDeviceId = deviceId;
_activeSpiritId = 0;
_preActionCharges = charges;
_actionIssuedAt = NowMs;
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}).");
_actionIssuedAt = now;
// Server starts the PetDevice cooldown on Use, whether the pet spawns or not.
_deviceCooldownUntil[deviceId] = now + DeviceUseCooldownMs;
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}); essence cooldown {DeviceUseCooldownMs / 1000}s.");
_host.UseFor(unchecked((uint)deviceId), "Pet", "summon a pet from the essence");
}
@ -455,9 +508,12 @@ internal sealed class PetManager
foreach (var wo in _objectCache.GetLandscape())
{
if (wo == null) continue;
// Corpses keep the pet's name briefly; don't treat them as a live summon.
if (wo.ObjectClass == AcObjectClass.Corpse) continue;
string n = wo.Name;
if (!string.IsNullOrEmpty(n) && n.StartsWith(prefix, StringComparison.Ordinal))
return true;
if (string.IsNullOrEmpty(n) || !n.StartsWith(prefix, StringComparison.Ordinal)) continue;
if (n.Contains("Corpse", StringComparison.OrdinalIgnoreCase)) continue;
return true;
}
return false;
}

View file

@ -74,12 +74,14 @@ internal sealed class WeaponElementTracker
if (id == 0 || IsIdentified(id)) continue;
int n = _requests.TryGetValue(id, out int c) ? c : 0;
if (n >= MaxRequestsPerItem) continue;
bool taken = false;
try { taken = _host.RequestId(unchecked((uint)id)); } catch { }
_lastRequestAt = now; // paces a retry as it paces a request
if (!taken) return 0; // the engine refused (a death or a portal): not counted, asked again after the gap
_requests[id] = n + 1;
_inFlightId = id;
_inFlightAt = now;
_lastRequestAt = now;
RequestsSent++;
try { _host.RequestId(unchecked((uint)id)); } catch { }
return id;
}
return 0;

View file

@ -66,7 +66,7 @@ internal static class WieldRequirements
private static AcSkillType? SkillOf(uint stype)
{
if (stype == 0) return null;
foreach (AcSkillType k in Enum.GetValues(typeof(AcSkillType)))
foreach (AcSkillType k in Enum.GetValues<AcSkillType>())
if (CharacterSkills.AcSkillTypeToSTypeSkill(k) == stype) return k;
return null;
}

View file

@ -406,6 +406,7 @@ internal static unsafe class CombatHookInterface
_table = null;
if (t != null) NativeMemory.Free(t);
CombatHook.Reset();
CombatHook.LastUseDone = null; // the lambda captured the host: don't keep a shut-down instance's host alive
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]

View file

@ -48,6 +48,8 @@ public sealed partial class RynthAiPlugin
private int _corpseIdAcceptedThisTick;
private long _corpseIdBudgetAt; // when the budget last started over (a scan tick, or CorpseIdRefusedRetryMs without one)
private const long CorpseIdReaskMs = 3000; // no appraisal data this long after an accepted request: ask once more
private const int CorpseIdMaxReasks = 3; // ...at most this many times per corpse (each accepted ask raises the client's busy count and holds opens)
private readonly Dictionary<int, int> _corpseIdAskCount = new(); // accepted requests per corpse, the first included
private int _busyCount;
private long _busyCountLastIncrementAt;
private long _busyCountBecamePositiveAt; // when count first went 0→positive
@ -399,6 +401,7 @@ public sealed partial class RynthAiPlugin
_corpseIdRequested.Clear();
_corpseIdAskedAt.Clear();
_corpseIdRefusedAt.Clear();
_corpseIdAskCount.Clear();
}
if (_corpseSkipLogged.Count > 200)
_corpseSkipLogged.Clear();
@ -1017,8 +1020,11 @@ public sealed partial class RynthAiPlugin
/// requests, so a refused or dropped one is asked again. A refused one is retried every
/// CorpseIdRefusedRetryMs; an accepted one with no data is asked again every CorpseIdReaskMs, and only for
/// the corpse the bot is targeting or has open (any other corpse in range gets one accepted request, not a
/// stream). At most CorpseIdPerTick requests are accepted per scan tick, so a refusal window ending with
/// many uncached corpses in range does not burst. No give-up cap.
/// stream), at most CorpseIdMaxReasks times, and only while the loot mode needs the killer name (My Kills
/// Only, Fellowship Kills). All Corpses still gets the one first request (the radar colours own kills from
/// it) but never a stream of them; Recover My Corpse keeps its own 5 s ask (RequestOwnCorpseId). At most
/// CorpseIdPerTick requests are accepted per scan tick, so a refusal window ending with many uncached
/// corpses in range does not burst.
/// </summary>
private void TryRequestCorpseId(WorldObject corpse, string longDesc)
{
@ -1026,14 +1032,17 @@ public sealed partial class RynthAiPlugin
long idNow = ActionPacer.NowMs();
if (idNow - _corpseIdBudgetAt >= CorpseIdRefusedRetryMs) { _corpseIdAcceptedThisTick = 0; _corpseIdBudgetAt = idNow; } // evaluations outside a scan must not exhaust it for good
bool candidate = corpse.Id == _targetCorpseId || (_openedContainerId != 0 && corpse.Id == _openedContainerId);
int asks = _corpseIdAskCount.TryGetValue(corpse.Id, out int askCount) ? askCount : 0;
bool due = !_corpseIdRequested.Contains(corpse.Id)
|| (candidate && _corpseIdAskedAt.TryGetValue(corpse.Id, out long askedAt) && idNow - askedAt >= CorpseIdReaskMs);
|| (candidate && asks <= CorpseIdMaxReasks && CorpseNameNeeded()
&& _corpseIdAskedAt.TryGetValue(corpse.Id, out long askedAt) && idNow - askedAt >= CorpseIdReaskMs);
if (!due || _corpseIdAcceptedThisTick >= CorpseIdPerTick) return;
if (_corpseIdRefusedAt.TryGetValue(corpse.Id, out long refusedAt) && idNow - refusedAt < CorpseIdRefusedRetryMs) return;
if (Host.RequestId(unchecked((uint)corpse.Id)))
{
_corpseIdRequested.Add(corpse.Id);
_corpseIdAskedAt[corpse.Id] = idNow;
_corpseIdAskCount[corpse.Id] = asks + 1;
_corpseIdRefusedAt.Remove(corpse.Id);
_corpseIdAcceptedThisTick++;
}
@ -1043,6 +1052,9 @@ public sealed partial class RynthAiPlugin
}
}
/// <summary>The loot mode reads the killer name (My Kills Only, Fellowship Kills); All Corpses does not.</summary>
private bool CorpseNameNeeded() => (_dashboard?.Settings?.LootOwnership ?? 0) < 2;
private CorpseLootDecision EvaluateCorpseLootDecision(WorldObject? corpse)
{
var settings = _dashboard?.Settings;
@ -1915,6 +1927,10 @@ public sealed partial class RynthAiPlugin
}
private bool _pickupHeldLogged;
private long _pickupHoldTickAt; // CorpseNowMs of the previous held call; 0 = no hold running
/// <summary>A gap between two held calls longer than this was not one continuous hold (the corpse clock is not paid back for it).</summary>
internal const long PickupHoldMaxGapMs = 500;
/// <summary>
/// True while the server owes an answer to a cast or use (ActionPacer): ACE refuses a pickup
@ -1928,6 +1944,7 @@ public sealed partial class RynthAiPlugin
if (!ActionPacer.Outstanding(Host, out var pending) || pending == null)
{
_pickupHeldLogged = false;
_pickupHoldTickAt = 0;
return false;
}
if (!_pickupHeldLogged)
@ -1935,9 +1952,32 @@ public sealed partial class RynthAiPlugin
_pickupHeldLogged = true;
LootDiag($"[RynthAi] Corpse loot: pickup waits - the server still owes an answer to {ActionPacer.Describe(pending.Kind, pending.Label)} ({pending.Who}).");
}
PauseCorpseClockWhileHeld();
return true;
}
/// <summary>
/// The corpse's timeout clock does not run while a pickup is held for the server's answer to a
/// cast or use, as it does not for the buff / salvage-panel holds (FreezeCorpseTimeout). The hold
/// is bounded by the pacer: an action unanswered past its limit (ActionPacer.CastMaxMs for a
/// cast) stops being outstanding. FreezeCorpseTimeout itself cannot be used here: the
/// open-container branch of TickCorpseOpening resets its frozen age every tick, so this adds the
/// time since the previous held call to the claim time instead. Without it a corpse held for
/// 12 s timed out the moment the cast was answered, and AbandonCurrentCorpse gave the opened
/// corpse the 30-minute completed mark, which skipped its loot.
/// </summary>
private void PauseCorpseClockWhileHeld()
{
long now = CorpseNowMs;
long last = _pickupHoldTickAt;
_pickupHoldTickAt = now;
if (last == 0 || _targetCorpseId == 0 || _corpseTargetSince == 0)
return;
long gap = now - last;
if (gap > 0 && gap <= PickupHoldMaxGapMs)
_corpseTargetSince += gap;
}
private void TickPendingCorpsePickup(LegacyUiSettings settings)
{
if (_objectCache == null || _openedContainerId == 0 || _currentLootItemId == 0)
@ -3396,6 +3436,7 @@ public sealed partial class RynthAiPlugin
_corpseIdRequested.Remove(sid);
_corpseIdAskedAt.Remove(sid);
_corpseIdRefusedAt.Remove(sid);
_corpseIdAskCount.Remove(sid);
_corpseSkipLogged.Remove(sid);
_corpseWaitingSince.Remove(sid);
@ -3552,16 +3593,42 @@ public sealed partial class RynthAiPlugin
/// <summary>A held-back close is sent anyway when no other corpse has been opened this long.</summary>
internal const long DeferredCloseMaxMs = 3000;
/// <summary>Another corpse to loot is in range (the finished one is already marked completed).</summary>
/// <summary>
/// Another corpse to loot is in range (the finished one is already marked completed) and the
/// looter can go to it now: <see cref="CanClaimNextCorpse"/>. A corpse that combat, a full pack, a
/// refusing server or a buff / mana drain hold keeps from being claimed would leave the finished
/// one open for nothing (metas and Lua read the open container meanwhile).
/// </summary>
private bool OtherCorpseToLoot(int doneCorpseId)
{
var settings = _dashboard?.Settings;
if (settings == null || _objectCache == null) return false;
double maxMeters = GetCorpseApproachRangeMaxMeters(settings);
if (maxMeters <= 0.25) return false;
if (!CanClaimNextCorpse(settings, maxMeters)) return false;
return TryFindNearestCorpse(maxMeters, out WorldObject? next, out _) && next != null && next.Id != doneCorpseId;
}
/// <summary>
/// The holds TickCorpseOpening applies before it claims or opens a corpse, as one answer for
/// "would the next corpse be claimed now": looting blocked by a full pack (your own corpse
/// excepted), the use-refusal back-off, buffing, a mana drain, and combat's priority (the open
/// container no longer shields a claim once the finished corpse is released). What the activity
/// arbiter hands out later is not known here; the deferred close is sent after DeferredCloseMaxMs,
/// or as soon as one of these holds starts (TickDeferredClose). Distance is no reason to close
/// early: a far corpse is used at once and the server walks the character to it.
/// </summary>
private bool CanClaimNextCorpse(LegacyUiSettings settings, double maxMeters)
{
if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters)) return false;
if (_useRefusals.HoldsOpens(CorpseNowMs)) return false;
if (string.Equals(settings.BotAction, "Buffing", StringComparison.OrdinalIgnoreCase)) return false;
if (_manaStoneManager?.HoldsLootForDrain() == true) return false;
if (settings.EnableCombat && _combatManager?.HasTargets == true && !settings.BoostLootPriority && !_lootStarveTurn)
return false;
return true;
}
/// <summary>Holds the close of a finished corpse back. Only when the engine can close it later and
/// reports which container the client has open (so the hold can see the server close it).</summary>
private bool DeferClose(int corpseId)
@ -3591,10 +3658,13 @@ public sealed partial class RynthAiPlugin
return;
}
bool stopped = !settings.IsMacroRunning || !settings.EnableLooting || settings.BoostNavPriority;
if (!stopped && CorpseNowMs - _closeDeferredAt < DeferredCloseMaxMs)
// A hold that began after the close was deferred (a fight, a full pack) ends the wait too.
double maxMeters = GetCorpseApproachRangeMaxMeters(settings);
bool blocked = !stopped && maxMeters > 0.25 && !CanClaimNextCorpse(settings, maxMeters);
if (!stopped && !blocked && CorpseNowMs - _closeDeferredAt < DeferredCloseMaxMs)
return;
_closeDeferredFor = 0;
CloseCorpseContainer(id, stopped ? "completed; looting stopped" : "completed; no other corpse opened");
CloseCorpseContainer(id, stopped ? "completed; looting stopped" : blocked ? "completed; the next corpse can't be claimed now" : "completed; no other corpse opened");
}
private void CloseCorpseContainer(int corpseId, string why)

View file

@ -44,6 +44,7 @@ internal static unsafe class HubInterface
t->SessionStats = &SessionStats;
t->SessionReset = &SessionReset;
t->SessionStatsMore = &SessionStatsMore;
t->VaultedDungeonsEnabled = &VaultedDungeonsEnabled;
t->Version = RynthAiHubApiV1.InterfaceVersion;
_table = t;
}
@ -250,6 +251,14 @@ internal static unsafe class HubInterface
catch { return 0; }
}
/// <summary>RynthAi's Vaulted Dungeons setting: RynthILT's keeper runs only while it is on (off by default).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int VaultedDungeonsEnabled()
{
try { return Plugin?.VaultedDungeonsEnabledForIlt == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void SessionReset()
{

View file

@ -204,9 +204,10 @@ internal sealed class CombatHudTracker
if (_appraiseAttempts >= AppraiseMaxAttempts || !_host.HasRequestId) return;
if (_lastAppraiseAt != 0 && now - _lastAppraiseAt < AppraiseRetryMs) return;
// Counted only when the engine took it (it refuses around a death or a portal).
if (!_host.RequestId(uid)) return;
_appraiseAttempts++;
_lastAppraiseAt = now;
_host.RequestId(uid);
}
/// <summary>Polls the pet's health, then hands the server's health stream back to the fight target.</summary>

View file

@ -0,0 +1,27 @@
// MiniRemoteHeader.cs - the Mini Remote's [V/H] [Options] [gear] header row: what a click does, and the
// button widths. Pure, so the host tests check both offline.
//
// Options opens RynthAi Settings (Advanced Settings) through RynthCore's "/rc ui open Settings" when the
// host has a chat parser. The Mini Remote's own popup (sections, layout, slot size) opens from the small
// gear button next to it, from a right-click on Options, and from a left-click on Options when there is
// no chat parser to run the command.
namespace RynthCore.Plugin.RynthAi.Huds;
internal static class MiniRemoteHeader
{
/// <summary>[V/H]: one letter, so it doesn't need the width of the word buttons.</summary>
public const float LayoutButtonWidth = 56f;
public const float OptionsButtonWidth = 80f;
/// <summary>The gear button right of Options: square-ish and small.</summary>
public const float GearButtonWidth = 28f;
/// <summary>
/// The engine command a left-click on Options runs, or null when the host can't run chat commands
/// (then the click opens the Mini Remote popup instead).
/// </summary>
public static string? OptionsLeftClickCommand(bool hasChatParser) => hasChatParser ? MovedTabs.Settings : null;
/// <summary>Total width of the header row for the given spacing between its three buttons.</summary>
public static float RowWidth(float itemSpacing) =>
LayoutButtonWidth + OptionsButtonWidth + GearButtonWidth + 2f * itemSpacing;
}

View file

@ -12,7 +12,9 @@
// Quest Timers and Fellowship, Skills, Inventory, Item Count, Inventory HUDs: windows every server
// has), then "Server: <name>", i.e. the installed server plugins' windows for the world you're on,
// which RynthCore sends (ServerMenuModel), or a link to RynthCore's Options > Diagnostics (where a
// server is forced) when none matches. The Options button holds the Mini Remote's own settings.
// server is forced) when none matches. The Options button opens RynthAi Settings (/rc ui open
// Settings); the small gear next to it, or a right-click on Options, holds the Mini Remote's own
// settings (sections, layout, slot size), and so does a click on Options when there is no chat parser.
// The V/H button stacks the sections (vertical) or lays them out in three columns (horizontal).
//
// Remote sections (each can be hidden from the Options menu):
@ -59,8 +61,7 @@ internal sealed class MiniRemoteHud
/// <summary>Pixels per Ctrl+wheel notch over the slot grid.</summary>
private const float SlotSizeStep = 2f;
/// <summary>Narrowest horizontal-layout column (fits the stat lines and the translate row).</summary>
private const float MinColumnWidth = 190f;
private const float HeaderButtonWidth = 80f;
internal const float MinColumnWidth = 190f;
private static readonly Vector4 ColLabel = new(0.80f, 0.84f, 0.90f, 1f);
private static readonly Vector4 ColReady = new(0.40f, 0.95f, 0.45f, 1f);
@ -82,6 +83,8 @@ internal sealed class MiniRemoteHud
private bool _onRemoteTab = true;
// The Options button was clicked this frame (the popup opens at window level).
private bool _openOptions;
// The header's Options button was right-clicked this frame: its popup opens, not the remote's menu.
private bool _headerRightClick;
/// <summary>One tab after Remote: a universal one (drawn here) or RynthILT's.</summary>
private readonly record struct TabEntry(string Id, string Label, Vector2 Size, bool Ilt);
@ -125,7 +128,7 @@ internal sealed class MiniRemoteHud
// Right-click on the remote opens the Character / server menu, unless a slot's own menu is
// open (the ILT tabs have their own right-click menus).
if (_onRemoteTab && _slotMenuIndex < 0 && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
if (_onRemoteTab && _slotMenuIndex < 0 && !_headerRightClick && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
ImGui.OpenPopup(MenuPopup);
RenderOptions(s, embedded: false);
RenderMenu(s);
@ -152,7 +155,7 @@ internal sealed class MiniRemoteHud
// Without tabs (RynthCore's sections show them instead) the remote alone.
float width = RenderBody(s, _hud.Remote(), allowTabs: tabs && !InDrawer);
if (_onRemoteTab && _slotMenuIndex < 0 && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
if (_onRemoteTab && _slotMenuIndex < 0 && !_headerRightClick && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
ImGui.OpenPopup(MenuPopup);
RenderOptions(s, embedded: true);
RenderMenu(s);
@ -179,6 +182,7 @@ internal sealed class MiniRemoteHud
private float RenderBody(HudState s, MiniRemoteController? remote, bool allowTabs)
{
_onRemoteTab = true;
_headerRightClick = false;
_tabs.Clear();
if (allowTabs && remote != null)
{
@ -311,17 +315,54 @@ internal sealed class MiniRemoteHud
// ── Layout ──────────────────────────────────────────────────────────────
/// <summary>[V/H] and [Options] buttons. Fixed widths so the auto-resizing window can't grow from them.</summary>
/// <summary>
/// [V/H], [Options] and a small gear. Fixed widths (MiniRemoteHeader, sized to fit MinColumnWidth)
/// so the auto-resizing window can't grow from them.
/// </summary>
private void RenderHeaderRow(HudState s)
{
if (ImGui.Button((s.MiniRemoteHorizontal ? "H" : "V") + "##mrlayout", new Vector2(HeaderButtonWidth, 0)))
if (ImGui.Button((s.MiniRemoteHorizontal ? "H" : "V") + "##mrlayout", new Vector2(MiniRemoteHeader.LayoutButtonWidth, 0)))
s.MiniRemoteHorizontal = !s.MiniRemoteHorizontal;
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip(s.MiniRemoteHorizontal ? "Horizontal: sections in columns. Click to stack them." : "Vertical: sections stacked. Click to lay them out in columns.");
ImGui.SameLine();
// Opened by RenderOptions: this row sits inside the Remote tab, whose ID the popup must not get.
if (ImGui.Button("Options##mropts", new Vector2(HeaderButtonWidth, 0))) _openOptions = true;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Mini Remote settings: sections, layout, slot size.\nRight-click the remote for the Character and server windows.");
// Left-click: RynthAi Settings (the engine's "Settings" panel); without a chat parser, and on a
// right-click, the Mini Remote popup (RenderOptions: this row sits inside the Remote tab, whose
// ID the popup must not get, so the popup opens at window level through _openOptions).
if (ImGui.Button("Options##mropts", new Vector2(MiniRemoteHeader.OptionsButtonWidth, 0)))
{
string? command = MiniRemoteHeader.OptionsLeftClickCommand(_hud.Host.HasInvokeChatParser);
if (command != null) _hud.RunEngineCommand(command);
else _openOptions = true;
}
if (ImGui.IsItemHovered())
{
_headerRightClick = true; // the remote's right-click menu stays closed over this button
if (ImGui.IsMouseClicked(ImGuiMouseButton.Right)) _openOptions = true;
SafeImGui.SetTooltip(_hud.Host.HasInvokeChatParser
? "Open RynthAi Settings (Advanced Settings).\nRight-click: Mini Remote sections, layout, slot size."
: "Mini Remote settings: sections, layout, slot size.");
}
ImGui.SameLine();
if (ImGui.Button("##mrgear", new Vector2(MiniRemoteHeader.GearButtonWidth, 0))) _openOptions = true;
DrawGear(ImGui.GetItemRectMin(), ImGui.GetItemRectMax());
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Mini Remote sections, layout, slot size");
}
/// <summary>A small gear (ring and eight teeth) centred in the button's rectangle, in the text colour.</summary>
private static void DrawGear(Vector2 min, Vector2 max)
{
var draw = ImGui.GetWindowDrawList();
uint col = ImGui.GetColorU32(ImGuiCol.Text);
Vector2 c = (min + max) * 0.5f;
float r = MathF.Min(max.X - min.X, max.Y - min.Y) * 0.22f;
draw.AddCircle(c, r, col, 12, 1.6f);
for (int i = 0; i < 8; i++)
{
float a = i * MathF.PI / 4f;
var dir = new Vector2(MathF.Cos(a), MathF.Sin(a));
draw.AddLine(c + dir * (r + 0.5f), c + dir * (r + 3f), col, 2f);
}
}
private void RenderVertical(HudState s, MiniRemoteController? remote)

View file

@ -21,6 +21,12 @@ internal static class MovedTabs
/// <summary>RynthCore Options > Diagnostics (the server picker; RynthCore 2026.10.5.54+).</summary>
public const string Diagnostics = "/rc diagnostics";
/// <summary>
/// RynthAi Settings (Advanced Settings): RynthCore's "Settings" panel (SettingsFace.Title), opened
/// by name through "/rc ui open &lt;Panel&gt;" (RynthCoreChatCommands, the generic panel verb).
/// </summary>
public const string Settings = "/rc ui open Settings";
/// <summary>
/// The chat command that opens where tab <paramref name="tab"/> lives now, or null when it is
/// still a Mini Remote tab (or not a tab at all). Case and padding don't matter.
@ -36,6 +42,7 @@ internal static class MovedTabs
{
OracleCharacter => "RynthOracle's Character tab",
Diagnostics => "RynthCore Options > Diagnostics",
Settings => "RynthAi Settings (Advanced Settings)",
_ => command,
};
}

View file

@ -71,6 +71,10 @@ internal static class SectionsManifest
["charms"] = ("inventory", "Charms", 220, "ILT charms and Guardian Hands: acquired, status, tier, toggles (RynthILT)."),
["banking"] = ("inventory", "Banking", 230, "Your ILT bank: balances, deposits, withdrawals and transfers (RynthILT)."),
["games"] = ("games", "Games", 100, "ILT games (RynthILT)."),
// Listed only while RynthILT shows the tab: the Vaulted Dungeons master switch (RynthAi
// Settings > Navigation) is on, on an ILT world.
["vaulted"] = ("nav", "Vaulted Dungeons", 220,
"Keep the character in one Vaulted Dungeon (RynthILT; Settings > Navigation > Vaulted Dungeons)."),
};
/// <summary>The surface name of a tab's view ("section:gear").</summary>

View file

@ -15,6 +15,30 @@ internal sealed class LegacyAdvancedSettingsUi
// Server Features list being edited (committed on Enter / focus loss); null = show the saved list.
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
/// <summary>
/// The environment-impact throttle's shared numbers (one set for missiles and magic), drawn
/// under each response combo. <paramref name="id"/> keeps the two copies' ImGui ids apart.
/// </summary>
private void DrawEnvironmentThrottleKnobs(string id)
{
ImGui.Indent();
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Hits to trip##envlimit{id}", ref _settings.EnvironmentImpactLimit, 1, 10);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Environment hits on one target, within the window, before combat reacts.\nShared by missiles and magic.");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Window (s)##envwin{id}", ref _settings.EnvironmentImpactWindowSec, 5, 120);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Move closer by (m)##envstep{id}", ref _settings.EnvironmentApproachMeters, 1, 30);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Closest (m)##envmin{id}", ref _settings.EnvironmentMinDistance, 1, 30);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Never moves nearer than this. Already this close, a new target is picked instead.");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Skip target (s)##envskip{id}", ref _settings.EnvironmentSkipSec, 5, 300);
ImGui.Unindent();
}
private static readonly string[] NavLabelModeNames = { "Off", "Numbers", "Numbers and names" };
private const string NavResumeNearestTip =
"On: starting the macro, loading a Circular or Linear route, and carrying on after a fight, loot, buff or door\n" +
@ -436,9 +460,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Spacing();
ImGui.Text("Give Queue");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Give Interval (ms)", ref _settings.GiveQueueIntervalMs, 50, 2000);
ImGui.SliderInt("Give Interval (ms)", ref _settings.GiveQueueIntervalMs, 0, 2000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Minimum delay between each item sent by /ra givea commands.\nLower = faster but may drop items if the server can't keep up.");
ImGui.SetTooltip("Minimum gap between two gives sent by /ra givea commands.\n0 = send the next give the moment the server answers the last (fastest).\nThe queue always waits for the server's answer first.");
break;
case "Recharge":
@ -532,6 +556,45 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextItemWidth(120);
ImGui.Combo("Missile Attack Height", ref _settings.MissileAttackHeight, AttackHeights, AttackHeights.Length);
ImGui.Spacing();
ImGui.Text("Variable Power (monster rules)");
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("A monster rule's Power column picks per monster: Default (these settings),\n" +
"High (100%), Reckless (80%, needs Recklessness trained), Variable (a new\n" +
"random power each attack in this range), or Reckless + Variable (random,\n" +
"kept inside the Recklessness band 20-80%).");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Variable Min %", ref _settings.VariablePowerMin, 0, 100);
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Variable Max %", ref _settings.VariablePowerMax, 0, 100);
ImGui.Spacing();
ImGui.Text("Missiles Hitting the Environment");
ImGui.SetNextItemWidth(220);
ImGui.Combo("Missile Response", ref _settings.MissileEnvironmentResponse,
EnvironmentImpactPlanner.ResponseNames, EnvironmentImpactPlanner.ResponseNames.Length);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("When arrows or bolts keep hitting walls or objects instead of the target\n" +
"(\"Your missile attack hit the environment.\"), stop shooting and:\n" +
" Move closer - run toward the target for a clearer shot\n" +
" New target - skip this one for a while and fight another\n" +
" Move closer, then new target - one approach, then switch\n" +
"The only monster in reach is never skipped.");
DrawEnvironmentThrottleKnobs("missile");
ImGui.Spacing();
ImGui.Text("Pull Away (Kite)");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Pull Distance (m)", ref _settings.KitePullMeters, 3, 100);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("When a monster rule's Kite is Pull away (or Default follows the\n" +
"DEFAULT row set to Pull away), tag the mob then run until it has\n" +
"been dragged this many metres from where it stood, then kill it.\n" +
"Set per mob on the Monsters / Damage panels.");
ImGui.Checkbox("Tag Before Fleeing", ref _settings.KiteTagFirst);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Land a hit before running so aggro sticks. Off = flee as soon as locked.");
ImGui.Spacing();
ImGui.Text("Weapon Swaps");
ImGui.SetNextItemWidth(150);
@ -600,7 +663,8 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetTooltip(
"At or under Emergency Heal At with heals failing: break the\n" +
"stuck cast with a jump and heal again; if that fails too,\n" +
"recall to the lifestone.");
"recall to the lifestone. Off by default; only a character that\n" +
"can heal (a heal spell, kit or potion) is ever recalled.");
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 0, 5000);
@ -629,6 +693,20 @@ internal sealed class LegacyAdvancedSettingsUi
"The character turns to face the target first. 0 = no walls.");
ImGui.InputInt("Min Wall Targets", ref _settings.MinWallTargets);
ImGui.Spacing();
ImGui.Text("Spells Hitting the Environment");
ImGui.SetNextItemWidth(220);
ImGui.Combo("Magic Response", ref _settings.MagicEnvironmentResponse,
EnvironmentImpactPlanner.ResponseNames, EnvironmentImpactPlanner.ResponseNames.Length);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("When bolts, streaks, arcs or blasts keep stopping short of the target\n" +
"(a wall, a pillar, the ceiling) with no hit or resist, stop casting and:\n" +
" Move closer - run toward the target for a clearer line\n" +
" New target - skip this one for a while and fight another\n" +
" Move closer, then new target - one approach, then switch\n" +
"Rings and walls aren't judged. The only monster in reach is never skipped.");
DrawEnvironmentThrottleKnobs("magic");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Spell Difficulty (Min Buffed Skill)");
@ -663,6 +741,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetTooltip("Drop a locked target only past this distance (hysteresis).\n0 or <= Monster Range = auto (Monster Range + 3).");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Ring Range", ref _settings.RingRange);
ImGui.Checkbox("Evade Handler Ring", ref _settings.HandlerRingEvade);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Empyrean Handler: when it channels its lethal ring and you are within 12 yards (or Ring Range if larger),\nback-jump away and re-engage. Acts only while the macro is running with combat on.");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Approach Range", ref _settings.ApproachRange);

View file

@ -69,8 +69,9 @@ internal sealed partial class LegacyDashboardRenderer
// the server sends at login. Before 2026-09-28 every server shared
// SettingsProfiles\ACEmulator, so the same character name on two servers
// shared one profile; that folder is still used when no name is known.
private static readonly string ProfilesBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "SettingsProfiles");
private static readonly string MonstersBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MonsterProfiles");
// internal + settable only so the host tests can point LoadSettings at a scratch folder.
internal static string ProfilesBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "SettingsProfiles");
internal static string MonstersBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MonsterProfiles");
private const string LegacyServerFolder = "ACEmulator";
private string _serverFolder = LegacyServerFolder;
private string _settingsRoot => Path.Combine(ProfilesBase, _serverFolder);
@ -386,27 +387,43 @@ internal sealed partial class LegacyDashboardRenderer
// new character kept the previous character's weapons and consumables,
// and autosave then wrote them into its Default.json.
bool freshProfile = !File.Exists(_settingsFilePath);
bool holdUnreadable = false;
if (freshProfile)
{
CopySettings(new LegacyUiSettings(), _settings);
_lastSavedJson = string.Empty;
}
else if (TryReadProfile(_settingsFilePath, out LegacyUiSettings? loaded, out string loadedJson, out string readError))
{
CopySettings(loaded!, _settings);
_lastSavedJson = loadedJson;
}
else if (TryReadProfile(_settingsFilePath + BackupSuffix, out LegacyUiSettings? fromBak, out string bakJson, out _))
{
// The profile didn't read (cut off by a client that died mid-save, say): the copy
// kept by the last good save is used. The broken file is set aside and the backup put
// back as the profile, so the next save doesn't turn the broken file into the new .bak.
CopySettings(fromBak!, _settings);
_lastSavedJson = bakJson;
KeepUnreadableProfile(_settingsFilePath);
try { File.Copy(_settingsFilePath + BackupSuffix, _settingsFilePath, overwrite: true); }
catch (Exception ex) { _host.Log($"[RynthAi] Settings: putting the backup back as {_settingsFilePath} failed: {ex.Message}"); }
_host.Log($"[RynthAi] Settings: {_settingsFilePath} didn't read ({readError}); loaded the backup instead.");
_host.WriteToChat($"[RynthAi] Your settings file didn't read ({readError}); restored the backup copy.", 1);
}
else
{
try
{
string json = File.ReadAllText(_settingsFilePath);
var loaded = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings);
if (loaded != null)
{
CopySettings(loaded, _settings);
_lastSavedJson = json;
}
}
catch { }
// Neither reads. Before, the defaults kept here were autosaved over the profile at once,
// so one bad read reset the character for good. Now a copy is set aside and nothing is
// written until a setting is actually changed (the baseline is re-taken below).
CopySettings(new LegacyUiSettings(), _settings);
KeepUnreadableProfile(_settingsFilePath);
holdUnreadable = true;
_host.Log($"[RynthAi] Settings: {_settingsFilePath} didn't read ({readError}) and there's no good backup; using defaults without saving over it.");
_host.WriteToChat($"[RynthAi] Your settings file didn't read ({readError}). A copy was kept next to it (.unreadable); defaults are in use until you change something.", 1);
}
_packSetup = freshProfile ? PackSetup.FillNew
: _settings.ProfileItemsChecked ? PackSetup.None : PackSetup.CheckExisting;
: holdUnreadable || _settings.ProfileItemsChecked ? PackSetup.None : PackSetup.CheckExisting;
_packSetupStart = 0;
_packLastCount = -1;
@ -461,6 +478,15 @@ internal sealed partial class LegacyDashboardRenderer
// combat system has no fallback weapon/damage selection for unmatched mobs.
_settings.EnsureDefaultRule();
SetupMonsterWatcher();
if (holdUnreadable)
{
// The defaults now in memory (and the monster rules just loaded) are not a change: take
// them as the saved state, so the autosave leaves the unreadable file alone until the
// player changes something.
try { CaptureTransientUiState(); _lastSavedJson = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings); }
catch { _lastSavedJson = string.Empty; }
}
}
/// <summary>
@ -505,9 +531,58 @@ internal sealed partial class LegacyDashboardRenderer
DataWriteGuard.TrySave("the settings profile", path, () =>
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, json);
// Written beside it and swapped in, the previous file kept as .bak: File.WriteAllText
// empties the profile first, so a client closed or killed mid-save (relaunching for a
// DXVK change, the launcher's stuck-client kill) left a cut-off file that then loaded
// as defaults.
string tmp = path + "." + Environment.ProcessId + ".tmp";
try
{
File.WriteAllText(tmp, json);
if (File.Exists(path)) File.Replace(tmp, path, path + BackupSuffix, ignoreMetadataErrors: true);
else File.Move(tmp, path);
}
finally
{
try { if (File.Exists(tmp)) File.Delete(tmp); } catch { }
}
}, out reason, callerShows);
/// <summary>The last good profile kept by each save (profile path + this).</summary>
internal const string BackupSuffix = ".bak";
/// <summary>Reads and parses a settings profile; false (with the reason) when it's missing or doesn't parse.</summary>
private static bool TryReadProfile(string path, out LegacyUiSettings? settings, out string json, out string error)
{
settings = null; json = string.Empty; error = "";
try
{
if (!File.Exists(path)) { error = "missing"; return false; }
json = File.ReadAllText(path);
if (string.IsNullOrWhiteSpace(json)) { error = "the file is empty"; return false; }
settings = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings);
if (settings == null) { error = "the file holds no settings"; return false; }
return true;
}
catch (Exception ex)
{
error = ex.GetType().Name + ": " + ex.Message;
return false;
}
}
/// <summary>Copies a profile that didn't read to "&lt;name&gt;.unreadable-&lt;time&gt;" so its contents can be recovered.</summary>
private void KeepUnreadableProfile(string path)
{
try
{
if (!File.Exists(path)) return;
string copy = path + ".unreadable-" + DateTime.Now.ToString("yyyyMMdd-HHmmss");
File.Copy(path, copy, overwrite: false);
}
catch (Exception ex) { _host.Log($"[RynthAi] Settings: keeping a copy of {path} failed: {ex.Message}"); }
}
private static bool WriteSettingsFile(string path, string json) => WriteSettingsFile(path, json, out _);
/// <summary>After a failed autosave, when CheckAndSave may try again (not every tick).</summary>
@ -983,12 +1058,46 @@ internal sealed partial class LegacyDashboardRenderer
incoming.Insert(0, existingDefault ?? new MonsterRule { Name = "Default" });
}
// An engine without the Power column (before 2026-10-12) sends no AttackPower, which
// would reset every rule to Default: keep each rule's own (same name and expression).
if (json.IndexOf("\"AttackPower\"", StringComparison.OrdinalIgnoreCase) < 0)
CarryAttackPower(_settings.MonsterRules, incoming);
// Same for kite (2026-10-16): an older Monsters panel omits Kite and would wipe PullAway.
if (json.IndexOf("\"Kite\"", StringComparison.OrdinalIgnoreCase) < 0)
CarryKite(_settings.MonsterRules, incoming);
_settings.MonsterRules = incoming;
SaveMonstersFile();
}
catch { }
}
/// <summary>Copies AttackPower from <paramref name="current"/> onto the matching rules of
/// <paramref name="incoming"/> (same Name and MatchExpression, case-insensitive).</summary>
internal static void CarryAttackPower(List<MonsterRule> current, List<MonsterRule> incoming)
{
foreach (var r in incoming)
{
var old = current.FirstOrDefault(o =>
string.Equals(o.Name, r.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(o.MatchExpression ?? "", r.MatchExpression ?? "", StringComparison.OrdinalIgnoreCase));
if (old != null) r.AttackPower = old.AttackPower;
}
}
/// <summary>Copies Kite from <paramref name="current"/> onto the matching rules of
/// <paramref name="incoming"/> (same Name and MatchExpression, case-insensitive).</summary>
internal static void CarryKite(List<MonsterRule> current, List<MonsterRule> incoming)
{
foreach (var r in incoming)
{
var old = current.FirstOrDefault(o =>
string.Equals(o.Name, r.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(o.MatchExpression ?? "", r.MatchExpression ?? "", StringComparison.OrdinalIgnoreCase));
if (old != null) r.Kite = old.Kite;
}
}
// ── Settings bridge (engine-side Avalonia SettingsPanel) ─────────────────
public string BuildSettingsJson()
@ -1070,10 +1179,21 @@ internal sealed partial class LegacyDashboardRenderer
UseNativeAttack = s.UseNativeAttack,
SummonPets = s.SummonPets,
PetMinMonsters = s.PetMinMonsters,
// Spell Combat
VariablePowerMin = s.VariablePowerMin,
VariablePowerMax = s.VariablePowerMax,
MissileEnvironmentResponse = s.MissileEnvironmentResponse,
MagicEnvironmentResponse = s.MagicEnvironmentResponse,
EnvironmentImpactLimit = s.EnvironmentImpactLimit,
EnvironmentImpactWindowSec = s.EnvironmentImpactWindowSec,
EnvironmentApproachMeters = s.EnvironmentApproachMeters,
EnvironmentMinDistance = s.EnvironmentMinDistance,
EnvironmentSkipSec = s.EnvironmentSkipSec,
KitePullMeters = s.KitePullMeters,
KiteTagFirst = s.KiteTagFirst,
WeaponSwapSettleMs = s.WeaponSwapSettleMs,
WeaponSwapMinHealthPct = s.WeaponSwapMinHealthPct,
WeaponSwapMinGainPct = s.WeaponSwapMinGainPct,
// Spell Combat
SpellCastIntervalMs = s.SpellCastIntervalMs,
AttackSpellIntervalMs = s.AttackSpellIntervalMs,
CastDispelSelf = s.CastDispelSelf,
@ -1101,6 +1221,7 @@ internal sealed partial class LegacyDashboardRenderer
CorpseApproachRangeMin = s.CorpseApproachRangeMin,
// Navigation
BoostNavPriority = s.BoostNavPriority,
EnableVaultedDungeons = s.EnableVaultedDungeons,
FollowNavMin = s.FollowNavMin,
NavRingThickness = s.NavRingThickness,
NavLineThickness = s.NavLineThickness,
@ -1110,6 +1231,8 @@ internal sealed partial class LegacyDashboardRenderer
NavLabelMode = NavLabelModes.Clamp(s.NavLabelMode),
NavGuideLine = s.NavGuideLine,
NavResumeNearest = s.NavResumeNearest,
TrackBreadcrumbs = s.NavOverlay.TrackBreadcrumbs,
ShowRouteOverlay = s.NavOverlay.ShowRouteMarkers,
OpenDoors = s.OpenDoors,
OpenDoorRange = s.OpenDoorRange,
OpenDoorsOnPathOnly = s.OpenDoorsOnPathOnly,
@ -1311,10 +1434,22 @@ internal sealed partial class LegacyDashboardRenderer
s.UseNativeAttack = p.UseNativeAttack;
s.SummonPets = p.SummonPets;
s.PetMinMonsters = p.PetMinMonsters;
// Spell Combat
// Absent (an engine without these controls) = unchanged.
if (p.VariablePowerMin is int vpMin) s.VariablePowerMin = vpMin;
if (p.VariablePowerMax is int vpMax) s.VariablePowerMax = vpMax;
if (p.MissileEnvironmentResponse is int envMis) s.MissileEnvironmentResponse = envMis;
if (p.MagicEnvironmentResponse is int envMag) s.MagicEnvironmentResponse = envMag;
if (p.EnvironmentImpactLimit is int envLimit) s.EnvironmentImpactLimit = envLimit;
if (p.EnvironmentImpactWindowSec is int envWin) s.EnvironmentImpactWindowSec = envWin;
if (p.EnvironmentApproachMeters is int envStep) s.EnvironmentApproachMeters = envStep;
if (p.EnvironmentMinDistance is int envMinDist) s.EnvironmentMinDistance = envMinDist;
if (p.EnvironmentSkipSec is int envSkip) s.EnvironmentSkipSec = envSkip;
if (p.KitePullMeters is int kitePull) s.KitePullMeters = Math.Clamp(kitePull, 3, 100);
if (p.KiteTagFirst is bool kiteTag) s.KiteTagFirst = kiteTag;
if (p.WeaponSwapSettleMs is int wsSettle) s.WeaponSwapSettleMs = Math.Clamp(wsSettle, 0, 3000);
if (p.WeaponSwapMinHealthPct is int wsHealth) s.WeaponSwapMinHealthPct = Math.Clamp(wsHealth, 0, 100);
if (p.WeaponSwapMinGainPct is int wsGain) s.WeaponSwapMinGainPct = Math.Clamp(wsGain, 0, 200);
// Spell Combat
s.SpellCastIntervalMs = p.SpellCastIntervalMs;
if (p.AttackSpellIntervalMs is int attackDelay) s.AttackSpellIntervalMs = attackDelay; // absent = unchanged
s.CastDispelSelf = p.CastDispelSelf;
@ -1342,6 +1477,7 @@ internal sealed partial class LegacyDashboardRenderer
s.CorpseApproachRangeMin = p.CorpseApproachRangeMin;
// Navigation
s.BoostNavPriority = p.BoostNavPriority;
if (p.EnableVaultedDungeons is bool vaulted) s.EnableVaultedDungeons = vaulted; // absent = unchanged
s.FollowNavMin = p.FollowNavMin;
s.NavRingThickness = p.NavRingThickness;
s.NavLineThickness = p.NavLineThickness;
@ -1351,6 +1487,8 @@ internal sealed partial class LegacyDashboardRenderer
if (p.NavLabelMode >= 0) s.NavLabelMode = NavLabelModes.Clamp(p.NavLabelMode);
if (p.NavGuideLine is bool guideLine) s.NavGuideLine = guideLine;
if (p.NavResumeNearest is bool resumeNearest) s.NavResumeNearest = resumeNearest; // absent = unchanged
if (p.TrackBreadcrumbs is bool crumbs) s.NavOverlay.TrackBreadcrumbs = crumbs; // absent = unchanged
if (p.ShowRouteOverlay is bool routeOverlay) s.NavOverlay.ShowRouteMarkers = routeOverlay;
s.OpenDoors = p.OpenDoors;
s.OpenDoorRange = p.OpenDoorRange;
if (p.OpenDoorsOnPathOnly is bool doorsOnPath) s.OpenDoorsOnPathOnly = doorsOnPath; // absent = unchanged
@ -1640,18 +1778,30 @@ internal sealed partial class LegacyDashboardRenderer
// Load from new profile file if it exists
if (File.Exists(_settingsFilePath))
{
try
if (TryReadProfile(_settingsFilePath, out LegacyUiSettings? loaded, out string json, out string readError))
{
string json = File.ReadAllText(_settingsFilePath);
var loaded = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings);
if (loaded != null)
CopySettings(loaded!, _settings);
_settings.SelectedProfile = newProfile;
_lastSavedJson = json;
}
else
{
// Same as at login: the profile that didn't read is set aside (and the backup used
// when there is one) instead of being overwritten by the profile we just left.
KeepUnreadableProfile(_settingsFilePath);
if (TryReadProfile(_settingsFilePath + BackupSuffix, out LegacyUiSettings? fromBak, out string bakJson, out _))
{
CopySettings(loaded, _settings);
CopySettings(fromBak!, _settings);
_settings.SelectedProfile = newProfile;
_lastSavedJson = json;
_lastSavedJson = bakJson;
try { File.Copy(_settingsFilePath + BackupSuffix, _settingsFilePath, overwrite: true); } catch { }
_host.WriteToChat($"[RynthAi] Profile '{newProfile}' didn't read ({readError}); restored its backup copy.", 1);
}
else
{
_host.WriteToChat($"[RynthAi] Profile '{newProfile}' didn't read ({readError}); a copy was kept next to it (.unreadable). Your current settings are in use under that name.", 1);
}
}
catch { }
}
else
{
@ -1816,6 +1966,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.TargetSelection = Math.Clamp(tmp.TargetSelection, 0, 3);
dst.TargetLock = tmp.TargetLock;
dst.RingRange = tmp.RingRange;
dst.HandlerRingEvade = tmp.HandlerRingEvade; // a profile saved before this setting loads it as on
dst.ApproachRange = tmp.ApproachRange;
dst.MinRingTargets = tmp.MinRingTargets;
dst.BlastRange = tmp.BlastRange;
@ -1838,6 +1989,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.CorpseApproachRangeMax = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMax, 10.0);
dst.CorpseApproachRangeMin = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMin, 2.0);
dst.BoostNavPriority = tmp.BoostNavPriority;
dst.EnableVaultedDungeons = tmp.EnableVaultedDungeons;
dst.BoostLootPriority = tmp.BoostLootPriority;
dst.OpenDoors = tmp.OpenDoors;
dst.OpenDoorRange = tmp.OpenDoorRange;
@ -1867,6 +2019,17 @@ internal sealed partial class LegacyDashboardRenderer
dst.MeleeAttackPower = tmp.MeleeAttackPower;
dst.MissileAttackPower = tmp.MissileAttackPower;
dst.UseRecklessness = tmp.UseRecklessness;
dst.VariablePowerMin = tmp.VariablePowerMin;
dst.VariablePowerMax = tmp.VariablePowerMax;
dst.MissileEnvironmentResponse = tmp.MissileEnvironmentResponse;
dst.MagicEnvironmentResponse = tmp.MagicEnvironmentResponse;
dst.EnvironmentImpactLimit = tmp.EnvironmentImpactLimit;
dst.EnvironmentImpactWindowSec = tmp.EnvironmentImpactWindowSec;
dst.EnvironmentApproachMeters = tmp.EnvironmentApproachMeters;
dst.EnvironmentMinDistance = tmp.EnvironmentMinDistance;
dst.EnvironmentSkipSec = tmp.EnvironmentSkipSec;
dst.KitePullMeters = Math.Clamp(tmp.KitePullMeters, 3, 100);
dst.KiteTagFirst = tmp.KiteTagFirst;
dst.WeaponSwapSettleMs = Math.Clamp(tmp.WeaponSwapSettleMs, 0, 3000);
dst.WeaponSwapMinHealthPct = Math.Clamp(tmp.WeaponSwapMinHealthPct, 0, 100);
dst.WeaponSwapMinGainPct = Math.Clamp(tmp.WeaponSwapMinGainPct, 0, 200);

View file

@ -207,6 +207,10 @@ public sealed class LegacyUiSettings
// setting loads it as on.
public bool TargetLock = true;
public int RingRange = 5;
// Empyrean Handler lethal ring (CombatManager.HandleChatForRingEvade): when the Handler channels the
// ring and the character is inside its danger radius, back-jump away and re-engage. Only acts while
// the macro is running with combat on. On by default because it is gated that way.
public bool HandlerRingEvade = true;
public int ApproachRange = 4;
public int MinRingTargets = 4;
// Blast like a ring: with BlastRange > 0, a rule with Blast on casts a blast only when
@ -252,6 +256,13 @@ public sealed class LegacyUiSettings
public double CorpseApproachRangeMin = 2.0;
public bool BoostNavPriority;
/// <summary>
/// Options > Navigation > Vaulted Dungeons: the MASTER switch of RynthILT's Vaulted Dungeons
/// keeper (Infinite Leaftide / ACECustom only). Off by default. RynthILT reads it through
/// "RynthAi.Hub" VaultedDungeonsEnabled; while it is off the keeper does nothing (no recalls,
/// no /rc quit, no tab). This is the one place the switch lives.
/// </summary>
public bool EnableVaultedDungeons;
public bool BoostLootPriority;
public bool OpenDoors;
public float OpenDoorRange = 5.0f;
@ -400,7 +411,7 @@ public sealed class LegacyUiSettings
/// </summary>
public List<string> MonsterNameBlacklist { get; set; } = new();
public int GiveQueueIntervalMs = 150;
public int GiveQueueIntervalMs = 0;
/// <summary>
/// Item augmentation count used for T11 wield gates in loot rules ("T11: Can Wield").
@ -433,7 +444,7 @@ public sealed class LegacyUiSettings
/// breaker runs and the heal is tried again; when that fails too, recall to the lifestone.
/// Off: the breaker still runs, no recall.
/// </summary>
public bool HpFailsafeRecall = true;
public bool HpFailsafeRecall = false;
/// <summary>
/// Minimum delay between offensive (war/void) COMBAT spell casts, in ms.
@ -470,6 +481,41 @@ public sealed class LegacyUiSettings
public bool UseNativeAttack = false;
public bool UseRecklessness;
/// <summary>
/// The range a monster rule's "Variable" attack power picks from, in percent of the bar
/// (a new value every swing or shot). "Reckless + Variable" also stays inside the
/// Recklessness band (20-80%). See AttackPowerPlanner.
/// </summary>
public int VariablePowerMin = 50;
public int VariablePowerMax = 100;
// ── Environment hits (2026-10-12, Combat/EnvironmentImpact.cs) ─────────────
/// <summary>
/// What missile combat does once a target has taken EnvironmentImpactLimit "Your missile
/// attack hit the environment." within EnvironmentImpactWindowSec: an EnvironmentResponse
/// (0 Off, 1 Move closer, 2 New target, 3 Move closer then new target). Off by default.
/// </summary>
public int MissileEnvironmentResponse;
/// <summary>The same for war/void casts whose projectiles stop short of the target. Off by default.</summary>
public int MagicEnvironmentResponse;
/// <summary>Environment hits on one target, within the window, that trip the response.</summary>
public int EnvironmentImpactLimit = 2;
/// <summary>The window (seconds) the hits are counted in.</summary>
public int EnvironmentImpactWindowSec = 20;
/// <summary>How far (metres) each "move closer" goes toward the target.</summary>
public int EnvironmentApproachMeters = 6;
/// <summary>Never approaches nearer than this (metres); already this close, a new target is picked.</summary>
public int EnvironmentMinDistance = 3;
/// <summary>How long (seconds) a target left for its environment hits is skipped.</summary>
public int EnvironmentSkipSec = 30;
/// <summary>
/// Pull-away kite (2026-10-16, Combat/KiteModes.cs): how far (metres) to drag a PullAway
/// monster from its lock-spot origin before stopping to kill it. Per-mob on/off is
/// MonsterRule.Kite (Default follows the DEFAULT row).
/// </summary>
public int KitePullMeters = 20;
/// <summary>Land a hit before fleeing so aggro sticks (Off = run immediately).</summary>
public bool KiteTagFirst = true;
/// <summary>
/// Combat and buffing only ever wield weapons from the Items list. With this on (the
/// default), a character whose Items list has no wand at all may still buff and cast with a
/// caster from its pack (by object class, never by name). Any listed wand turns it off.
@ -819,6 +865,13 @@ public sealed class MonsterRule
/// <summary>Debuffs the player typed in (Damage panel), comma separated: a spell's base
/// name ("Corrosion Vulnerability Other") casts its best known tier; a full name casts as is.</summary>
public string CustomDebuffs { get; set; } = "";
/// <summary>Melee/missile attack power against the monsters this rule covers: one of
/// AttackPowerModes.All. "Default" = the DEFAULT line's choice (on the DEFAULT line: the global
/// Melee/Missile Power settings). Rules saved before 2026-10-12 load as Default.</summary>
public string AttackPower { get; set; } = AttackPowerModes.Default;
/// <summary>Combat pull-away for this rule: one of KiteModes.All. "Default" = the DEFAULT
/// line's choice (on the DEFAULT line: Off). Rules saved before 2026-10-16 load as Default.</summary>
public string Kite { get; set; } = "Default";
}
public sealed class BuffRule
@ -1061,7 +1114,20 @@ public sealed class SettingsBridgePayload
public bool UseNativeAttack { get; set; }
public bool SummonPets { get; set; }
public int PetMinMonsters { get; set; }
// Variable attack power and the environment-impact throttle (2026-10-12). Null = sent by an
// engine without these controls, which leaves the plugin's own values alone.
public int? VariablePowerMin { get; set; }
public int? VariablePowerMax { get; set; }
public int? MissileEnvironmentResponse { get; set; }
public int? MagicEnvironmentResponse { get; set; }
public int? EnvironmentImpactLimit { get; set; }
public int? EnvironmentImpactWindowSec { get; set; }
public int? EnvironmentApproachMeters { get; set; }
public int? EnvironmentMinDistance { get; set; }
public int? EnvironmentSkipSec { get; set; }
// Pull-away kite (2026-10-16). Null = sender without these controls; leave plugin values alone.
public int? KitePullMeters { get; set; }
public bool? KiteTagFirst { get; set; }
// Weapon swaps (only when the sender includes them).
public int? WeaponSwapSettleMs { get; set; }
public int? WeaponSwapMinHealthPct { get; set; }
@ -1101,6 +1167,11 @@ public sealed class SettingsBridgePayload
// Navigation
public bool BoostNavPriority { get; set; }
/// <summary>
/// Options > Navigation > Vaulted Dungeons: the keeper's master switch (off by default). Nullable:
/// an engine that predates the row omits it, and absent = unchanged (never switches it off or on).
/// </summary>
public bool? EnableVaultedDungeons { get; set; }
public float FollowNavMin { get; set; }
public float NavRingThickness { get; set; }
public float NavLineThickness { get; set; }
@ -1111,6 +1182,10 @@ public sealed class SettingsBridgePayload
public int NavLabelMode { get; set; } = -1;
public bool? NavGuideLine { get; set; }
public bool? NavResumeNearest { get; set; }
// NavOverlay.TrackBreadcrumbs / ShowRouteMarkers: the Nav panel's "Breadcrumbs" and "Route
// overlay" switches, also on Settings > Navigation. Null (an older engine) = unchanged.
public bool? TrackBreadcrumbs { get; set; }
public bool? ShowRouteOverlay { get; set; }
public bool OpenDoors { get; set; }
public float OpenDoorRange { get; set; }
public bool? OpenDoorsOnPathOnly { get; set; } // absent (an older profile or plugin) = unchanged

View file

@ -12,9 +12,11 @@ namespace RynthCore.Plugin.RynthAi.Loot;
/// AutoCram moves non-equipped loose items out of the player's main pack into
/// sub-packs so the main pack stays empty for new loot pickups.
///
/// AutoStack merges two partial stacks of the same item (arrows, components,
/// salvage, pyreals, etc.) by dropping the smaller one onto the larger one's
/// slot — the server auto-merges stackable same-type items at the same slot.
/// AutoStack merges two partial stacks of the same weenie (arrows, components,
/// pyreals, etc.) by dropping the smaller one onto the larger one's slot — the
/// server merges only same-WCID stackables. Groups by WCID (not display name). A
/// pair whose total is over MaxStackSize is still tried: the server fills the
/// target and leaves the rest in the source, which is progress, not a failure.
/// </summary>
public sealed class InventoryManager
{
@ -33,7 +35,7 @@ public sealed class InventoryManager
// engine return is enqueue-accepted, not moved-confirmed (AcMainThreadQueue
// gesture-defers a move up to ~250 ticks ≈ 4-8s), so success and failure are
// indistinguishable at the call site. We confirm on a LATER snapshot.
private sealed class Pending { public DateTime EnqueuedAt; public int FromContainer; }
private sealed class Pending { public DateTime EnqueuedAt; public int FromContainer; public int TargetCount; public int SourceCount; }
private sealed class Backoff { public DateTime NextRetry; public int Attempts; public DateTime LastTouched; }
private readonly Dictionary<int, Pending> _cramPending = new(); // item id -> in-flight move
private readonly Dictionary<int, Backoff> _cramBackoff = new(); // item id -> confirmed-fail backoff
@ -259,10 +261,12 @@ public sealed class InventoryManager
if (inPlayerScope) playerItems.Add(item);
}
// Group by name, keep only stackable items with >1 in the same group.
// Group by weenie class id (WCID), not display name. Same-name stacks that are
// different weenies (e.g. Coalesced Mana 42517 vs 42518) cannot merge — the server
// answers "not compatible for stacking" and AutoStack used to retry forever.
var groupList = playerItems
.Where(x => GetMaxStackSize(x) > 1)
.GroupBy(x => x.Name)
.GroupBy(StackGroupKey)
.Where(g => g.Count() > 1)
.ToList();
@ -308,7 +312,9 @@ public sealed class InventoryManager
if (_stackPending.TryGetValue(key, out var sp))
{
bool sourceGone = !inv.Any(x => x.Id == parts[si].Item.Id);
if (sourceGone)
// Past the max the server fills the target and the source survives smaller:
// that is a merge too, not a failure.
if (sourceGone || MergeProgressed(sp.TargetCount, sp.SourceCount, parts[ti].Count, parts[si].Count))
{
_stackPending.Remove(key);
_stackBackoff.Remove(key);
@ -350,7 +356,7 @@ public sealed class InventoryManager
// Enqueue accepted — record PENDING, confirm on a later snapshot. Do NOT
// add the pair-key on success (the old bug that poisoned good merges and
// starved multi-partial consolidation).
_stackPending[pairKey] = new Pending { EnqueuedAt = DateTime.Now, FromContainer = playerId };
_stackPending[pairKey] = new Pending { EnqueuedAt = DateTime.Now, FromContainer = playerId, TargetCount = target.Count, SourceCount = source.Count };
return true; // one action per tick
}
@ -400,7 +406,24 @@ public sealed class InventoryManager
foreach (var k in dead) map.Remove(k);
}
// ── Stack-size lookup ─────────────────────────────────────────────────
// ── Stack-size / group-key lookup ─────────────────────────────────────
/// <summary>
/// AutoStack group key: the WCID when known (Decal Type / TryGetObjectWcid), else the name.
/// Name-only is a cold-start fallback; once a WCID is known, same-name stacks of different
/// weenies stay in separate groups.
/// </summary>
internal static string StackGroupKey(int wcid, string? name) => wcid > 0 ? "w:" + wcid : "n:" + (name ?? "");
private static string StackGroupKey(WorldObject item)
=> StackGroupKey(item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0), item.Name);
/// <summary>
/// True when a merge we sent moved something: the target grew or the source shrank since it was
/// enqueued. Counts are read from the same snapshot, so a refused merge changes neither.
/// </summary>
internal static bool MergeProgressed(int targetBefore, int sourceBefore, int targetNow, int sourceNow)
=> targetBefore > 0 && sourceBefore > 0 && (targetNow > targetBefore || sourceNow < sourceBefore);
private static int GetMaxStackSize(WorldObject item)
{

View file

@ -184,7 +184,9 @@ internal sealed class LootEditorBridge
d.ItemId = id;
var match = (LootItemMatch)Math.Clamp(req.Match, 0, 2);
d.IncludeT11 = req.IncludeT11;
LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like, req.IncludeT11);
d.AttributesSupported = true;
// The checklist shows every attribute whatever the match, so the item is always read in full.
LootItemFacts? facts = Items.Facts(id, true, req.IncludeT11 || req.Choices != null);
if (facts == null) return Refuse(d, $"RynthAi doesn't know item 0x{id:X8} yet. Select it again in a moment.");
d.IsT11 = facts.T11?.IsT11 == true;
d.ItemName = facts.Name;
@ -211,9 +213,11 @@ internal sealed class LootEditorBridge
KeepCount = req.KeepCount < 0 ? null : req.KeepCount,
RuleName = req.RuleName,
IncludeT11 = req.IncludeT11,
Choices = req.Choices,
};
LootItemRuleDraft? draft = LootItemRules.Build(facts, options, out string error);
if (draft == null) return Refuse(d, error);
foreach (LootItemAttribute row in draft.Attributes) d.Attributes.Add(row.ToWire());
d.Match = (int)draft.Match;
d.Action = (int)draft.Action;
d.KeepCount = draft.KeepCount;

View file

@ -962,9 +962,9 @@ internal sealed class ManaStoneManager
if (!_host.HasRequestId) return false;
if (_host.HasHasAppraisalData && _host.HasAppraisalData(unchecked((uint)id))) return false;
if (_stoneIdRequestedAt.TryGetValue(id, out long at) && now - at < StoneIdRetryMs) return false;
if (!_host.RequestId(unchecked((uint)id))) return false; // refused (a death or a portal): asked again next pass, not in 5 minutes
_stoneIdRequestedAt[id] = now;
_host.Log($"[RynthAi] ManaStone: identifying stone 0x{(uint)id:X8} (its charge can't be read).");
_host.RequestId(unchecked((uint)id));
return true;
}
@ -1078,8 +1078,7 @@ internal sealed class ManaStoneManager
if (!requestedThisPass && _host.HasRequestId
&& (!_manaIdRequestedAt.TryGetValue(item.Id, out long at) || nowMs - at > 300_000))
{
_manaIdRequestedAt[item.Id] = nowMs;
_host.RequestId(unchecked((uint)item.Id));
if (_host.RequestId(unchecked((uint)item.Id))) _manaIdRequestedAt[item.Id] = nowMs; // a refused one is asked again next pass
requestedThisPass = true;
}
continue;
@ -1101,9 +1100,11 @@ internal sealed class ManaStoneManager
&& nowMs - _lastGearRefreshAt >= GearRefreshSpacingMs
&& (!_gearReadRefreshedAt.TryGetValue(item.Id, out long readAt) || nowMs - readAt >= GearRefreshMs))
{
_gearReadRefreshedAt[item.Id] = nowMs;
_lastGearRefreshAt = nowMs;
_host.RequestId(unchecked((uint)item.Id));
if (_host.RequestId(unchecked((uint)item.Id))) // a refused one is asked again next pass
{
_gearReadRefreshedAt[item.Id] = nowMs;
_lastGearRefreshAt = nowMs;
}
requestedThisPass = true;
}
}

View file

@ -3631,6 +3631,20 @@ internal sealed class ExpressionEngine
["CastDispelSelf"] = (() => B(s.CastDispelSelf), v => s.CastDispelSelf = ToDouble(v) != 0),
["AutoFellowMgmt"] = (() => B(s.AutoFellowMgmt), v => s.AutoFellowMgmt = ToDouble(v) != 0),
["UseRecklessness"] = (() => B(s.UseRecklessness), v => s.UseRecklessness = ToDouble(v) != 0),
// The range a monster rule's Variable attack power picks from (percent of the bar).
["VariablePowerMin"] = (() => I(s.VariablePowerMin), v => { if (int.TryParse(v, out int i)) s.VariablePowerMin = Math.Clamp(i, 0, 100); }),
["VariablePowerMax"] = (() => I(s.VariablePowerMax), v => { if (int.TryParse(v, out int i)) s.VariablePowerMax = Math.Clamp(i, 0, 100); }),
// Environment hits: 0 Off, 1 Move closer, 2 New target, 3 Move closer then new target.
["MissileEnvironmentResponse"] = (() => I(s.MissileEnvironmentResponse), v => { if (int.TryParse(v, out int i)) s.MissileEnvironmentResponse = Math.Clamp(i, 0, 3); }),
["MagicEnvironmentResponse"] = (() => I(s.MagicEnvironmentResponse), v => { if (int.TryParse(v, out int i)) s.MagicEnvironmentResponse = Math.Clamp(i, 0, 3); }),
["EnvironmentImpactLimit"] = (() => I(s.EnvironmentImpactLimit), v => { if (int.TryParse(v, out int i)) s.EnvironmentImpactLimit = Math.Clamp(i, 1, 10); }),
["EnvironmentImpactWindowSec"] = (() => I(s.EnvironmentImpactWindowSec), v => { if (int.TryParse(v, out int i)) s.EnvironmentImpactWindowSec = Math.Clamp(i, 5, 120); }),
["EnvironmentApproachMeters"] = (() => I(s.EnvironmentApproachMeters), v => { if (int.TryParse(v, out int i)) s.EnvironmentApproachMeters = Math.Clamp(i, 1, 30); }),
["EnvironmentMinDistance"] = (() => I(s.EnvironmentMinDistance), v => { if (int.TryParse(v, out int i)) s.EnvironmentMinDistance = Math.Clamp(i, 1, 30); }),
["EnvironmentSkipSec"] = (() => I(s.EnvironmentSkipSec), v => { if (int.TryParse(v, out int i)) s.EnvironmentSkipSec = Math.Clamp(i, 5, 300); }),
// Pull-away kite (Combat/KiteModes.cs).
["KitePullMeters"] = (() => I(s.KitePullMeters), v => { if (int.TryParse(v, out int i)) s.KitePullMeters = Math.Clamp(i, 3, 100); }),
["KiteTagFirst"] = (() => B(s.KiteTagFirst), v => s.KiteTagFirst = ToDouble(v) != 0),
["WeaponSwapSettleMs"] = (() => I(s.WeaponSwapSettleMs), v => { if (int.TryParse(v, out int i)) s.WeaponSwapSettleMs = Math.Clamp(i, 0, 3000); }),
["WeaponSwapMinHealthPct"] = (() => I(s.WeaponSwapMinHealthPct), v => { if (int.TryParse(v, out int i)) s.WeaponSwapMinHealthPct = Math.Clamp(i, 0, 100); }),
["WeaponSwapMinGainPct"] = (() => I(s.WeaponSwapMinGainPct), v => { if (int.TryParse(v, out int i)) s.WeaponSwapMinGainPct = Math.Clamp(i, 0, 200); }),

View file

@ -119,6 +119,12 @@ public sealed class PetTabState
public bool KeepCosmeticOut;
/// <summary>Seconds to wait before re-summoning the cosmetic pet after it despawns.</summary>
public int CosmeticRespawnSeconds = 15;
// Auto siphon-lens capture (ACECustom MonsterCapture; Mini Remote > Pets).
/// <summary>When on, use the selected siphon lens on a nearby creature once it is weak enough.</summary>
public bool AutoCaptureEnabled;
/// <summary>Index into <see cref="PetCaptureRules.Lenses"/> (Flawed to Asheron).</summary>
public int CaptureLensIndex;
}
/// <summary>A user's choice of summon type for one essence (matched by name, case-insensitive).</summary>
@ -250,6 +256,7 @@ internal sealed class MiniRemoteStore
s.Pet.RosterKind = Math.Clamp(s.Pet.RosterKind, 0, 2);
s.Pet.RosterSort = Math.Clamp(s.Pet.RosterSort, 0, 6);
s.Pet.CosmeticRespawnSeconds = Math.Clamp(s.Pet.CosmeticRespawnSeconds, 5, 600);
s.Pet.CaptureLensIndex = Math.Clamp(s.Pet.CaptureLensIndex, 0, PetCaptureRules.Lenses.Length - 1);
s.Quests ??= new QuestsTabState();
s.Quests.QuestFilter ??= string.Empty;
s.Quests.QuestFavorites ??= new();

View file

@ -0,0 +1,164 @@
// PetCaptureRules.cs — ACECustom MonsterCapture thresholds for siphon lenses (pure; no host).
//
// Copied from ACECustom Source/ACE.Server/Entity/MonsterCapture.cs so the client can tell when
// a creature is weak enough to siphon before using a lens. Keep these numbers in lockstep with
// the server: CaptureMaxHealthFraction / CaptureMaxHealthPoints / CaptureRangeM and the lens
// WCID table in PetGuideController.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.MiniRemote;
/// <summary>One siphon lens the Pets tab can auto-use (name, WCID, whether health is gated).</summary>
public readonly struct PetCaptureLens
{
public PetCaptureLens(string name, uint wcid, bool bypassesHealthGate)
{
Name = name;
Wcid = wcid;
BypassesHealthGate = bypassesHealthGate;
}
public string Name { get; }
public uint Wcid { get; }
/// <summary>Asheron's (and Debug) lenses skip the 20% / 20 HP gate.</summary>
public bool BypassesHealthGate { get; }
}
/// <summary>
/// When a siphon lens can be used, matching ACECustom MonsterCapture.UseCaptureCrystal.
/// A creature is weak enough when its health fraction is ≤ 20% OR its current HP is under 20
/// (whichever comes first). Asheron's Lens skips that check.
/// </summary>
public static class PetCaptureRules
{
/// <summary>A lens targets the nearest attackable creature within this many meters.</summary>
public const float CaptureRangeM = 5.0f;
/// <summary>Siphon once at or below this fraction of max health…</summary>
public const float CaptureMaxHealthFraction = 0.20f;
/// <summary>…or below this many hit points (the gate is OR with the fraction).</summary>
public const int CaptureMaxHealthPoints = 20;
/// <summary>
/// Lenses the player can pick for auto-capture. Order is the combo index.
/// Resonance needs a prior failed capture (server-side); Asheron's bypasses the health gate.
/// </summary>
public static readonly PetCaptureLens[] Lenses =
{
new("Flawed Siphon Lens", 78780001, bypassesHealthGate: false),
new("Pristine Siphon Lens", 78780002, bypassesHealthGate: false),
new("Perfect Siphon Lens", 78780003, bypassesHealthGate: false),
new("Resonance Lens", 78780010, bypassesHealthGate: false),
new("Asheron's Lens", 78780012, bypassesHealthGate: true),
};
/// <summary>Combo labels for the Pets tab (same order as <see cref="Lenses"/>).</summary>
public static readonly string[] LensNames =
{
"Flawed", "Pristine", "Perfect", "Resonance", "Asheron's",
};
public static PetCaptureLens LensAt(int index)
{
int i = Math.Clamp(index, 0, Lenses.Length - 1);
return Lenses[i];
}
/// <summary>
/// True when ACECustom would accept a siphon on this creature for a normal (non-bypass) lens.
/// Pass current/max when known; when only a 0–1 ratio is known, pass ratio as current and 1 as max
/// (then only the fraction half of the gate can fire).
/// </summary>
public static bool IsWeakEnough(uint currentHp, uint maxHp)
{
if (currentHp == 0) return false; // dead — server refuses
if (maxHp == 0) return false;
float pct = (float)currentHp / maxHp;
// Server: refuse when pct > 0.20 AND current >= 20. Allowed otherwise.
return pct <= CaptureMaxHealthFraction || currentHp < CaptureMaxHealthPoints;
}
/// <summary>Same gate from a 0–1 health ratio only (no absolute HP). Dead / unknown = false.</summary>
public static bool IsWeakEnoughRatio(float healthRatio)
{
if (healthRatio <= 0f || healthRatio > 1f) return false;
return healthRatio <= CaptureMaxHealthFraction;
}
/// <summary>True when this lens may be used given the creature's vitals (bypass lenses always, if alive).</summary>
public static bool CanAttempt(PetCaptureLens lens, uint currentHp, uint maxHp)
{
if (currentHp == 0) return false;
if (lens.BypassesHealthGate) return maxHp == 0 || currentHp > 0;
return IsWeakEnough(currentHp, maxHp);
}
/// <summary>Distance gate: ACECustom CaptureRangeM.</summary>
public static bool InRange(double distanceM) => distanceM >= 0 && distanceM <= CaptureRangeM;
}
/// <summary>
/// A brake on the auto-capture loop. The Pets tab fires a lens every couple of seconds and only stops
/// on reply strings it guesses at, so an unrecognized reply (or a creature the server never lets go of)
/// would burn lenses without end. This caps consecutive tries per target and, as a backstop, consecutive
/// tries over all targets; both reset on a recognized success. Pure: the tests drive it.
/// </summary>
public sealed class PetCaptureThrottle
{
/// <summary>Lens uses on one creature, with no success in between, before it is left alone.</summary>
public const int MaxTriesPerTarget = 5;
/// <summary>How long a creature that used up its tries is left alone (ms).</summary>
public const long TargetBlockMs = 120_000;
/// <summary>Lens uses over all creatures with no success before auto-capture switches itself off.</summary>
public const int MaxTriesWithoutSuccess = 15;
private readonly Dictionary<int, int> _tries = new();
private readonly Dictionary<int, long> _blockedUntil = new();
private int _sinceSuccess;
/// <summary>Consecutive lens uses with no recognized success (all targets).</summary>
public int TriesWithoutSuccess => _sinceSuccess;
/// <summary>True when the backstop was hit: the caller should switch auto-capture off.</summary>
public bool Exhausted => _sinceSuccess >= MaxTriesWithoutSuccess;
/// <summary>False while this target is blocked (it used its tries) or the backstop is hit.</summary>
public bool MayAttempt(int targetId, long nowMs)
{
if (Exhausted) return false;
if (_blockedUntil.TryGetValue(targetId, out long until))
{
if (nowMs < until) return false;
_blockedUntil.Remove(targetId); // block served: a fresh set of tries
_tries.Remove(targetId);
}
return true;
}
/// <summary>Seconds left on this target's block, 0 when it is not blocked.</summary>
public long BlockedSecondsLeft(int targetId, long nowMs)
=> _blockedUntil.TryGetValue(targetId, out long until) && nowMs < until ? (until - nowMs + 999) / 1000 : 0;
/// <summary>Count a lens use on this target; blocks it once it reaches <see cref="MaxTriesPerTarget"/>.</summary>
public void RecordAttempt(int targetId, long nowMs)
{
_sinceSuccess++;
int n = _tries.TryGetValue(targetId, out int t) ? t + 1 : 1;
_tries[targetId] = n;
if (n >= MaxTriesPerTarget) _blockedUntil[targetId] = nowMs + TargetBlockMs;
}
/// <summary>A recognized success reply: everything starts over.</summary>
public void RecordSuccess() => Reset();
public void Reset()
{
_tries.Clear();
_blockedUntil.Clear();
_sinceSuccess = 0;
}
}

View file

@ -23,6 +23,9 @@
// player bools the server stamps. Feeds PetManager.AllowSummonOnEmpty.
// * Healing pet (UB HealingBuddy subset): summons a heal pet when HP drops, dismisses it
// after the heal lands, holds PetManager's combat summons while it is out.
// * Auto siphon capture (ACECustom MonsterCapture): when enabled, uses the chosen lens on the
// nearest attackable creature within 5 m once it is <=20% health or under 20 HP (Asheron's
// Lens skips the health gate). Resonance still needs a prior failed capture on the server.
// * /pets and /shinies logs: RynthILT's (RynthILT.Hub section "pets-logs", ILT only).
// * Breeding sub-tab (Infinite Leaftide only): the tab becomes Roster | Breeding when RynthILT
// offers it (an ILT world whose server hasn't reported pet breeding off). Its whole body is
@ -57,6 +60,17 @@ internal sealed class PetsTab
private long _lastHealThink;
private string _healStatus = "idle";
// Auto siphon-lens capture (ACECustom MonsterCapture).
private long _lastCaptureThink;
private long _captureCooldownUntil;
private volatile string _captureStatus = "off";
private const long CaptureThinkMs = 250;
private const long CaptureCooldownMs = 2500;
private const long CaptureFailBackoffMs = 8000;
// Hard cap on lens uses: the loop stops on reply strings we only guess at, so it is also bounded
// per creature and over all creatures (PetCaptureThrottle).
private readonly PetCaptureThrottle _captureThrottle = new();
// Roster snapshot (rebuilt on the pump thread, read by the render thread).
private volatile PetStats[] _pets = Array.Empty<PetStats>();
private long _lastPetScan;
@ -289,6 +303,11 @@ internal sealed class PetsTab
_lastHealThink = nowMs;
TickHealing(nowMs);
}
if (nowMs - _lastCaptureThink >= CaptureThinkMs)
{
_lastCaptureThink = nowMs;
TickCapture(nowMs);
}
if (nowMs - _lastPresenceThink >= 1000)
{
_lastPresenceThink = nowMs;
@ -334,9 +353,51 @@ internal sealed class PetsTab
EndHealCycle(MiniRemoteContext.NowMs, "heal landed");
}
}
// ACECustom MonsterCapture replies — back off after a refuse so we don't burn lenses.
if (S.AutoCaptureEnabled && text.Length > 0)
{
long now = MiniRemoteContext.NowMs;
if (PetCaptureLines.IsSuccess(text))
{
_captureStatus = "captured";
_captureThrottle.RecordSuccess();
_captureCooldownUntil = now + CaptureCooldownMs;
}
else if (ContainsAny(text,
"too strong",
"blind rage",
"cannot be siphoned",
"cannot be captured",
"No creatures nearby",
"already dead",
"already being captured",
"hasn't failed a capture",
"echo has faded",
"Failed to consume"))
{
_captureStatus = "refused: " + Truncate(text, 48);
_captureCooldownUntil = now + CaptureFailBackoffMs;
}
else if (ContainsAny(text, "siphon failed", "lens shatters", "resisted your capture", "resonance fades"))
{
_captureStatus = "failed (creature may enrage)";
_captureCooldownUntil = now + CaptureFailBackoffMs;
}
}
return false;
}
private static bool ContainsAny(string text, params string[] parts)
{
foreach (string p in parts)
if (text.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
private static string Truncate(string s, int max)
=> s.Length <= max ? s : s[..(max - 3)] + "...";
public void OnLogout()
{
_heal = HealState.Idle;
@ -345,6 +406,9 @@ internal sealed class PetsTab
_lastSummonEssenceId = 0;
_cosmeticOutEssenceId = 0;
_cosmeticNextAt = 0;
_captureCooldownUntil = 0;
_captureStatus = "off";
_captureThrottle.Reset();
}
// ── Healing pet ─────────────────────────────────────────────────────────
@ -415,6 +479,154 @@ internal sealed class PetsTab
// ── Active pet ──────────────────────────────────────────────────────────
// ── Auto siphon capture (ACECustom MonsterCapture) ───────────────────────
/// <summary>
/// When Auto Capture is on, use the chosen siphon lens on the nearest attackable creature
/// within 5 m once ACECustom's health gate is met (≤20% or under 20 HP; Asheron's skips it).
/// The server picks the nearest creature itself — we only fire when that nearest candidate is
/// already weak enough, so a full-health neighbour closer than the wounded target won't waste a lens.
/// </summary>
private void TickCapture(long now)
{
if (!S.AutoCaptureEnabled)
{
_captureStatus = "off";
return;
}
if (_ctx.Ilt.Loaded && _ctx.Ilt.IsOff(RynthIltHub.FeatureMonsterCapture))
{
_captureStatus = "monster capture disabled on this server";
return;
}
if (now < _captureCooldownUntil)
{
long left = (_captureCooldownUntil - now + 999) / 1000;
if (!_captureStatus.StartsWith("waiting", StringComparison.Ordinal))
_captureStatus = $"waiting {left}s";
return;
}
if (_ctx.Inventory.IsBusy) { _captureStatus = "busy"; return; }
var lens = PetCaptureRules.LensAt(S.CaptureLensIndex);
var lensItem = _ctx.Inventory.FindByWcid(lens.Wcid);
if (lensItem == null)
{
_captureStatus = $"no {lens.Name} carried";
return;
}
if (!TryFindNearestCaptureTarget(out WorldObject? target, out double distM, out uint curHp, out uint maxHp))
{
_captureStatus = "no attackable creature within 5 m";
return;
}
if (!PetCaptureRules.InRange(distM))
{
_captureStatus = $"{target!.Name} at {distM:0.0} m (need <={PetCaptureRules.CaptureRangeM:0} m)";
return;
}
if (!PetCaptureRules.CanAttempt(lens, curHp, maxHp))
{
float pct = maxHp > 0 ? curHp * 100f / maxHp : -1f;
_captureStatus = pct >= 0
? $"{target!.Name} at {pct:0}% / {curHp} HP (need <={PetCaptureRules.CaptureMaxHealthFraction:P0} or <{PetCaptureRules.CaptureMaxHealthPoints} HP)"
: $"{target!.Name}: health unknown";
return;
}
if (!_captureThrottle.MayAttempt(target!.Id, now))
{
_captureStatus = $"{target.Name}: {PetCaptureThrottle.MaxTriesPerTarget} tries, no capture; left alone for {_captureThrottle.BlockedSecondsLeft(target.Id, now)}s";
return;
}
if (!_ctx.Inventory.Use(lensItem))
{
_captureStatus = "UseObject refused";
return;
}
_captureThrottle.RecordAttempt(target.Id, now);
if (_captureThrottle.Exhausted)
{
// Backstop: this many lenses with no recognized capture means something is off. Stop, don't keep burning them.
S.AutoCaptureEnabled = false;
RynthLog.Write(LogCat.Pets,
$"[Pets] auto-capture: {PetCaptureThrottle.MaxTriesWithoutSuccess} lens uses without a capture reply; auto-capture switched off");
}
float shown = maxHp > 0 ? curHp * 100f / maxHp : 0f;
_captureStatus = $"using {lens.Name} on {target!.Name} ({shown:0}% / {curHp} HP)";
_captureCooldownUntil = now + CaptureCooldownMs;
RynthLog.Write(LogCat.Pets,
$"[Pets] auto-capture: {lens.Name} -> 0x{target.Id:X8} '{target.Name}' d={distM:0.0}m hp={curHp}/{maxHp}");
}
/// <summary>
/// Nearest attackable landscape creature within capture range, with vitals from the host when
/// available else the cache health ratio (fraction-only gate).
/// </summary>
private bool TryFindNearestCaptureTarget(out WorldObject? best, out double bestDist, out uint curHp, out uint maxHp)
{
best = null;
bestDist = double.MaxValue;
curHp = maxHp = 0;
var cache = _ctx.Inventory.Cache;
if (cache == null) return false;
uint playerId = _ctx.Inventory.PlayerId;
if (playerId == 0) return false;
int pid = unchecked((int)playerId);
string ownPrefix = _ctx.CharName.Length > 0 ? _ctx.CharName + "'s " : string.Empty;
foreach (var wo in cache.GetLandscape())
{
if (wo == null || wo.Id == pid) continue;
if (wo.ObjectClass != AcObjectClass.Monster) continue;
if (ownPrefix.Length > 0 && wo.Name.StartsWith(ownPrefix, StringComparison.Ordinal)) continue;
// Skip corpses / non-attackable when the host can tell.
if (_ctx.Host.HasObjectIsAttackable && !_ctx.Host.ObjectIsAttackable(unchecked((uint)wo.Id)))
continue;
double d = cache.Distance(pid, wo.Id);
if (d < 0 || d > PetCaptureRules.CaptureRangeM || d >= bestDist) continue;
if (!TryReadCreatureVitals(wo.Id, cache, out uint c, out uint m))
continue;
if (c == 0) continue; // dead
best = wo;
bestDist = d;
curHp = c;
maxHp = m;
}
return best != null;
}
/// <summary>
/// Absolute vitals via TryGetTargetVitals when bound; else cache health ratio as a 0–1000 scale
/// so only the fraction half of ACECustom's gate can fire.
/// </summary>
private bool TryReadCreatureVitals(int id, WorldObjectCache cache, out uint cur, out uint max)
{
cur = max = 0;
if (_ctx.Host.HasGetTargetVitals
&& _ctx.Host.TryGetTargetVitals(unchecked((uint)id), out uint h, out uint mh, out _, out _, out _, out _)
&& mh > 0)
{
cur = h;
max = mh;
return true;
}
float ratio = cache.GetHealthRatio(id);
if (ratio < 0f) return false;
// Synthetic scale: ratio 0.20 → 200/1000 so IsWeakEnough's fraction half matches.
max = 1000;
cur = (uint)Math.Clamp((int)Math.Round(ratio * 1000f), 1, 1000);
return true;
}
/// <summary>The live "&lt;Me&gt;'s …" creature (server pet naming), or null.</summary>
private WorldObject? FindOwnPet()
{
@ -764,12 +976,49 @@ internal sealed class PetsTab
{
ImGui.Separator();
RenderCharms();
ImGui.Separator();
RenderCapture();
}
ImGui.Separator();
RenderHealing();
_ctx.Ilt.RenderSection(RynthIltHub.SectionPetLogs);
}
/// <summary>ACECustom siphon-lens auto-capture (ILT only): enable + which lens to use.</summary>
private void RenderCapture()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Monster capture");
bool captureOff = _ctx.Ilt.IsOff(RynthIltHub.FeatureMonsterCapture);
ImGui.BeginDisabled(captureOff);
bool en = S.AutoCaptureEnabled;
if (ImGui.Checkbox("Auto-capture when a creature is weak enough", ref en))
{
S.AutoCaptureEnabled = en;
_captureThrottle.Reset();
}
if (ImGui.IsItemHovered())
{
SafeImGui.SetTooltip(
"Uses the selected siphon lens on the nearest attackable creature within 5 m once it is\n" +
"at or below 20% health or under 20 HP (ACECustom MonsterCapture). Asheron's Lens skips\n" +
"the health gate. Resonance Lens still needs a prior failed capture on the server.\n" +
"Off by default. Stops on its own after 5 tries on one creature (it is left alone for 2 min)\n" +
"or 15 lens uses in a row with no capture.");
}
ImGui.SameLine();
ImGui.SetNextItemWidth(120);
int lens = Math.Clamp(S.CaptureLensIndex, 0, PetCaptureRules.LensNames.Length - 1);
if (ImGui.Combo("##petcapturelens", ref lens, PetCaptureRules.LensNames, PetCaptureRules.LensNames.Length))
S.CaptureLensIndex = lens;
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Which siphon lens to use. Must be carried in your pack.");
ImGui.EndDisabled();
if (captureOff)
SafeImGui.TextDisabled("Monster capture is disabled on this server.");
else
SafeImGui.TextDisabled("Status: " + _captureStatus);
}
/// <summary>Type / Sort combos, action buttons, the active-summon line and per-type options.</summary>
private void RenderRosterHeader(LegacyUiSettings settings)
{

View file

@ -1785,7 +1785,12 @@ internal sealed class NavigationEngine
return false;
}
_host.UseFor((uint)bestId, "Nav", $"portal/NPC waypoint '{target}'");
// A use the engine did not send (UseObject said no) is not a use: false lets the caller ask again.
if (!_host.UseFor((uint)bestId, "Nav", $"portal/NPC waypoint '{target}'"))
{
_host.Log($"Nav: UseObject portal '{target}' (0x{bestId:X8}) was not sent - will retry");
return false;
}
// Publish the resolved object so the marker renderer can draw a ring +
// line to the portal's real position (the waypoint coord is a placeholder).
_settings.ActivePortalObjId = (uint)bestId;

View file

@ -243,6 +243,8 @@ public static class VirindiTankProfileImporter
dst.OffhandId = src.OffhandId;
dst.PreferredAmmoItemId = src.PreferredAmmoItemId;
dst.PetDamage = src.PetDamage;
dst.AttackPower = src.AttackPower;
dst.Kite = src.Kite;
}
private static MonsterRule CloneMonsterRule(MonsterRule row) =>
@ -268,6 +270,8 @@ public static class VirindiTankProfileImporter
OffhandId = row.OffhandId,
PreferredAmmoItemId = row.PreferredAmmoItemId,
PetDamage = row.PetDamage,
AttackPower = row.AttackPower,
Kite = row.Kite,
PreferredDamage = row.PreferredDamage,
};

View file

@ -2246,11 +2246,7 @@ public sealed partial class RynthAiPlugin
case "cancel": HandleCancelForceBuff(); break;
case "skipped":
if (_buffManager == null) { ChatLine("[RynthAi] Buff manager not ready."); break; }
_buffManager.BuildDynamicBuffList(); // refresh the skip list
string summary = _buffManager.FilterSkipSummary();
ChatLine(summary.Length == 0
? "[RynthAi] Buff filter: nothing is being skipped."
: $"[RynthAi] Buff filter skips: {summary}");
_buffManager.RequestSkipReport(); // chat commands run on AC's thread; the pump builds the list and answers
break;
default:
ChatLine("[RynthAi] /ra buff force - recast every buff now, whatever time is left");
@ -2602,10 +2598,7 @@ public sealed partial class RynthAiPlugin
if (allItems)
{
foreach (var item in matches)
{
int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1));
EnqueueGive((uint)item.Id, (uint)target.Id, stackSize);
}
EnqueueGive((uint)item.Id, (uint)target.Id, 0); // 0 = the whole stack, whatever it reads at send time
ChatLine($"[RynthAi] Queued {matches.Count} stack(s) matching '{itemPart}' → {target.Name}");
}
else if (countGiven)
@ -2626,8 +2619,8 @@ public sealed partial class RynthAiPlugin
}
if (gives.Count == 1)
{
GiveItem((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount,
Math.Max(1, gives[0].Item.Values(LongValueKey.StackCount, 1)));
// Through the queue: an NPC that takes one item per give needs the repeat-until-met loop.
EnqueueGive((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount);
ChatLine($"[RynthAi] Giving {gives[0].Amount} x '{gives[0].Item.Name}' to {target.Name}");
}
else
@ -2707,8 +2700,7 @@ public sealed partial class RynthAiPlugin
if (IsGiveProfileExempt(item)) continue;
var (action, _) = Loot.LootEvaluator.Classify(nativeProfile, item, null);
if (action != RynthCore.Loot.LootAction.Keep) continue;
int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1));
EnqueueGive((uint)item.Id, (uint)target.Id, stackSize);
EnqueueGive((uint)item.Id, (uint)target.Id, 0); // 0 = the whole stack
queued++;
}
}
@ -2723,8 +2715,7 @@ public sealed partial class RynthAiPlugin
foreach (var rule in vtProfile.Rules)
if (VTankLootEvaluator.Match(rule, item, lootCtx)) { matched = rule; break; }
if (matched == null || (matched.Action != VTankLootAction.Keep && matched.Action != VTankLootAction.KeepUpTo)) continue;
int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1));
EnqueueGive((uint)item.Id, (uint)target.Id, stackSize);
EnqueueGive((uint)item.Id, (uint)target.Id, 0); // 0 = the whole stack
queued++;
}
}

View file

@ -159,6 +159,8 @@ public sealed partial class RynthAiPlugin
internal MiniRemote.MiniRemoteController? MiniRemoteForIlt => _miniRemote;
internal WorldObjectCache? ObjectCacheForIlt => _objectCache;
internal RynthCore.Plugin.Shared.SessionStatsTracker? SessionStatsForIlt => _sessionStats;
/// <summary>The Vaulted Dungeons master switch (Settings > Navigation); false before login.</summary>
internal bool VaultedDungeonsEnabledForIlt => _dashboard?.Settings.EnableVaultedDungeons == true;
/// <summary>Item Info window, created once settings exist.</summary>
private void EnsureItemInfoUi()

View file

@ -58,6 +58,19 @@ public sealed partial class RynthAiPlugin
/// </summary>
private bool _wasPortalingForPacer;
private bool _wasMacroForPacer;
/// <summary>
/// The macro is switched on (off to on, whoever did it): a UseDone that arrived while it was off, a
/// player's own refused action, is not news. Without this the pacer's observer took it for a fresh
/// 'too busy' answer at the first check and held every start for the probe wait (~1.5 s).
/// </summary>
private void NoteMacroForPacer(bool running)
{
if (running && !_wasMacroForPacer) RynthCore.Plugin.Shared.ActionPacer.NoteMacroStart();
_wasMacroForPacer = running;
}
/// <summary>Portal space starts: the server dropped what was open (no breaker on a teleport's gap).</summary>
private void NotePortalForPacer()
{

View file

@ -133,13 +133,54 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// Give queue — drained one item per tick with a cooldown (interval comes from settings)
private readonly Queue<(uint itemId, uint targetId, int stackSize)> _pendingGives = new();
private DateTime _lastGiveAt = DateTime.MinValue;
// The give the server hasn't answered yet (0 = none): the next one waits for it.
private uint _giveInFlightId, _giveInFlightTarget;
private int _giveInFlightAmount, _giveInFlightStack, _giveInFlightTries;
private int _giveInFlightStack, _giveInFlightTries;
private long _giveInFlightAt;
private const long GiveConfirmMs = 3000;
private const int GiveMaxTries = 2;
// Items still to hand over from the in-flight give (a whole stack = its size; each shrink lowers it).
private int _giveInFlightRemaining;
// The in-flight request is a genuine "give all" (amount 0 from the caller): the only kind that may go out as a plain,
// whole-object give when the stack count cannot be read. A re-send of it stays "all".
private bool _giveInFlightAll;
// True once the in-flight give has been sent more than once (a busy re-send or a no-answer re-send):
// an "Item not found!" then means an earlier send already landed.
private bool _giveInFlightResent;
private string _giveInFlightName = string.Empty;
private long _giveLastSendAt = long.MinValue;
// A busy refusal re-sends the same give after this long (up to GiveBusyGiveUpMs in total).
private const long GiveBusyRetryMs = 300;
private long _giveBusyRetryAt; // 0 = not waiting on a busy re-send
// Continuous busy waiting on one give: since when, how many busy answers, when the player was last told.
private long _giveBusySince, _giveBusyNoticeAt;
private int _giveBusyCount;
private const long GiveBusyNoticeMs = 10000;
// Busy waiting on one give is given up after this long in total: the item is skipped and counted.
private const long GiveBusyGiveUpMs = 60000;
// A stackable item whose stack count will not read: which item, since when. After GiveReadFailMs the
// give goes out anyway (an explicit amount, or a plain give for amount 1) so the queue always advances.
private uint _giveReadFailId;
private long _giveReadFailSince;
private const long GiveReadFailMs = 2000;
// Consecutive ticks the in-flight item read as unreadable (no cache entry, Container 0); 2 = gone.
private int _giveGoneStreak;
private int _giveUnclassified; // unclassified chat lines logged for this give (max 5)
// Chat verdict on the in-flight give, set by OnChatWindowText and read on the tick.
private enum GiveChat { None, Busy, Permanent, ItemNotFound }
private int _giveChatVerdict; // a GiveChat, handed from OnChatWindowText to the tick with Interlocked
private string _giveChatLine = string.Empty;
private bool _giveSawAcceptLine;
// A stack that shrank but is still carried goes again before anything else in the queue.
private (uint itemId, uint targetId, int remaining)? _giveRedo;
// Run summary (reset when the queue empties).
private bool _giveRunActive;
private long _giveRunStartAt, _giveRunLastAnswerAt;
private int _giveRunItems;
private readonly List<string> _giveRunSkips = new();
// Test seam: a fake millisecond clock.
private Func<long>? _giveClock;
private long GiveNow() => _giveClock?.Invoke() ?? Environment.TickCount64;
private RynthCore.Loot.LootProfile? _nativeLootProfile;
private string _nativeLootProfilePath = string.Empty;
private DateTime _nativeLootProfileTime = DateTime.MinValue;
@ -261,6 +302,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
RynthCore.Plugin.Shared.UseAudit.WorldUseHold = null;
RynthCore.Plugin.Shared.ActionPacer.Enabled = false;
RynthCore.Plugin.Shared.ActionPacer.Forget("shutdown");
CombatHook.LastUseDone = null; // captured this instance's host (set again at Init)
// Give the heap back. When a changed RynthAi is deployed, the engine loads
// it as a new copy and this one is abandoned for good (a NativeAOT DLL can't
@ -450,6 +492,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_playerId = 0;
_loginComplete = false;
_pendingGives.Clear();
ResetGiveState();
// A /ub delay armed before logout must not fire into the next character's session.
_delayedCommands.Clear();
ClearPropertyDump();
@ -699,6 +742,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve
_combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
// Empyrean Handler lethal-ring: face the Handler, run-back jump (Jumper "xs"), re-engage.
// Read _jumper at call time — it is constructed later in this session setup.
_combatManager.RequestBackJump = (faceHeading, ms) => _jumper != null && _jumper.Start("xs", faceHeading, ms);
_combatManager.JumpBusy = () => _jumper?.IsBusy == true;
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
if (_buffManager != null)
_buffManager.OffhandStowed = id => _combatManager?.NoteOffhandStowed(id);
@ -1015,7 +1062,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
["TargetFPSFocused"] = (10, 240), ["TargetFPSBackground"] = (5, 60),
["BlacklistAttempts"] = (1, 20), ["BlacklistTimeoutSec"] = (5, 120), ["BlacklistCastSettleMs"] = (500, 5000),
["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000),
["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (0, 2000),
["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60), ["MissileArcClearance"] = (0, 3),
["HealAt"] = (0, 100), ["EmergencyHealAt"] = (0, 100),
["StaminaToHealthAt"] = (0, 100), ["StaminaToHealthMinStamina"] = (0, 100), ["RestamAt"] = (0, 100), ["RestamTo"] = (0, 100), ["GetManaAt"] = (0, 100),
@ -1023,6 +1070,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100),
["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100),
["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2),
["VariablePowerMin"] = (0, 100), ["VariablePowerMax"] = (0, 100),
["MissileEnvironmentResponse"] = (0, 3), ["MagicEnvironmentResponse"] = (0, 3),
["EnvironmentImpactLimit"] = (1, 10), ["EnvironmentImpactWindowSec"] = (5, 120),
["EnvironmentApproachMeters"] = (1, 30), ["EnvironmentMinDistance"] = (1, 30), ["EnvironmentSkipSec"] = (5, 300),
["KitePullMeters"] = (3, 100),
["WeaponSwapSettleMs"] = (0, 3000), ["WeaponSwapMinHealthPct"] = (0, 100), ["WeaponSwapMinGainPct"] = (0, 200),
["PetMinMonsters"] = (1, 20),
["SpellCastIntervalMs"] = (100, 1500), ["StuckCastBreakMs"] = (0, 60000), ["RecoveryRetryMs"] = (200, 5000), ["AttackSpellIntervalMs"] = (0, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), ["MinWallTargets"] = (1, 20), ["WallRange"] = (0, 100),
@ -1126,9 +1178,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
int id = unchecked((int)e.Id);
if (Host.HasRequestId && idRequests < 3
&& (!Host.HasHasAppraisalData || !Host.HasAppraisalData(e.Id))
&& _equipIdRequested.Add(e.Id))
&& !_equipIdRequested.Contains(e.Id))
{
Host.RequestId(e.Id); // appraisal 0xC9 lands in the engine cache; read it next pass
// Remembered only when the engine took it: it refuses around a death or a portal, and a refused
// request marked as done would never be asked again. Appraisal 0xC9 lands in the engine cache;
// read it next pass.
if (Host.RequestId(e.Id)) _equipIdRequested.Add(e.Id);
idRequests++;
}
var a = new EquipAppraisal { Name = e.Name, Id = e.Id, Slot = e.Slot };
@ -1652,7 +1707,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
RynthCore.Plugin.Shared.ActionPacer.NoteFrame();
// Stuck Cast Break, once per tick: the breaker runs for every subsystem's casts.
if (_dashboard?.Settings is { } paceSettings)
{
RynthCore.Plugin.Shared.ActionPacer.StuckCastMs = Math.Max(0, paceSettings.StuckCastBreakMs);
NoteMacroForPacer(paceSettings.IsMacroRunning);
}
NotePortalForPacer();
if (HoldForDeath())
return;
@ -2305,6 +2363,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
else _dashboard?.PushChatLine(text, chatType);
OnChatLocalFeatures(text, chatType, ref eat);
try { NoteHotspotChat(text, chatType); } catch (Exception ex) { Host.Log($"[RynthAi] Hazard chat check failed: {ex.Message}"); }
try { NoteGiveChat(text, chatType); } catch (Exception ex) { Host.Log($"[RynthAi] Give chat check failed: {ex.Message}"); }
_buffManager?.OnChatWindowText(text, chatType);
_manaStoneManager?.OnChatWindowText(text);
_salvageManager?.OnChatWindowText(text);
@ -2312,6 +2371,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager?.TraceCastChat(text, chatType);
_combatManager?.HandleChatForDebuffs(text);
_combatManager?.HandleChatForDamage(text, chatType);
_combatManager?.HandleChatForRingEvade(text, chatType);
_missileCraftingManager?.HandleChat(text);
_scrollLearner?.OnChat(text);
_metaManager?.HandleChat(text, chatType);
@ -2354,7 +2414,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
try { _combatManager?.OnObjectCreated(objectId); } catch { }
_sessionStats?.OnCreateObject(objectId);
try { _objectCache?.OnCreateObject(objectId); }
try
{
_objectCache?.OnCreateObject(objectId);
_combatManager?.OnEnvironmentObjectCreated(objectId); // spell projectiles for the environment-impact throttle
}
catch (Exception ex)
{
Host.Log($"[RynthAi] OnCreateObject EXCEPTION on id=0x{objectId:X8}: {ex.GetType().Name}: {ex.Message}");
@ -3397,75 +3461,353 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
internal void CancelGiveQueue()
{
int count = _pendingGives.Count;
var redo = _giveRedo;
int count = _pendingGives.Count + (redo.HasValue ? 1 : 0);
_pendingGives.Clear();
_giveInFlightId = 0;
ResetGiveState();
ChatLine(count > 0
? $"[RynthAi] Give queue cancelled ({count} item(s) remaining)."
: "[RynthAi] Give queue is already empty.");
}
/// <summary>Drops the in-flight give, the redo slot and the run summary (cancel, logout).</summary>
private void ResetGiveState()
{
_giveInFlightId = 0;
_giveRedo = null;
_giveBusyRetryAt = 0;
_giveBusySince = 0;
_giveBusyCount = 0;
_giveGoneStreak = 0;
_giveReadFailId = 0;
Interlocked.Exchange(ref _giveChatVerdict, 0);
_giveRunActive = false;
_giveRunItems = 0;
_giveRunSkips.Clear();
}
/// <summary>
/// One give at a time, each after the server has taken the last: the item has left the
/// inventory (or its stack shrank, for part of a stack). The queue used to send a give
/// every 150 ms; the server takes one give at a time and answers the rest "too busy",
/// so /ub give handed over one item and dropped the rest (2026-10-08). A give with no
/// answer in GiveConfirmMs is sent once more, then skipped.
/// Classifies a chat line as an answer to the in-flight give. Lowercase substrings: the client
/// renders WeenieError text from its own string table, so only the server's custom strings
/// ("Item not found!", "Target not found!", "Give amount not valid!") are exact.
/// </summary>
private static GiveChat ClassifyGiveChat(string text)
{
string t = text.ToLowerInvariant();
// Busy class first: "<npc> is too busy to accept gifts" must not read as "not accepting gifts".
if (t.Contains("too busy") || t.Contains("is busy right now")) return GiveChat.Busy;
if (t.Contains("item not found")) return GiveChat.ItemNotFound;
if (t.Contains("give amount not valid") || t.Contains("target not found")
|| t.Contains("doesn't want") || t.Contains("does not want")
|| t.Contains("not accepting gifts") || t.Contains("cowers from you"))
return GiveChat.Permanent;
return GiveChat.None;
}
/// <summary>
/// Speech, tells and emotes are other players' words, never the server's answer to a give. The text
/// shape is the real guard. Chat type 17 is the client's Spellcasting type (spell words, ours and
/// other casters': "chat type=17 ... says, "Zojak Ves""), which is never an answer either, so it is
/// skipped too; system notices such as "You give ..." arrive as 0.
/// </summary>
private static bool IsGiveChatSpeech(string text, int chatType)
{
if (chatType == 17) return true;
string t = text.ToLowerInvariant();
return t.Contains(" says, \"") || t.Contains(" tells you, \"") || t.Contains(" asks, \"")
|| t.Contains(" exclaims, \"") || t.Contains(" yells, \"") || t.Contains(" whispers, \"")
|| t.StartsWith("you say, ", StringComparison.Ordinal) || t.StartsWith("you tell ", StringComparison.Ordinal)
|| t.StartsWith("you whisper", StringComparison.Ordinal) || t.StartsWith("you exclaim", StringComparison.Ordinal)
|| t.StartsWith("you yell", StringComparison.Ordinal) || t.StartsWith("you ask", StringComparison.Ordinal);
}
/// <summary>
/// OnChatWindowText: only records the verdict; every send happens in DrainGiveQueue. The engine
/// dispatches chat from ProcessPendingActions and the plugin tick from TickAll, back to back in
/// one driver (EntryPoint.cs:1120-1122, ImGui/EngineFrameController.cs:461-467 in RynthCore-autoid),
/// so this is one thread in practice; the verdict still goes through Interlocked.
/// </summary>
private void NoteGiveChat(string text, int chatType = 0)
{
if (_giveInFlightId == 0) return;
if (IsGiveChatSpeech(text, chatType)) return;
if (text.StartsWith("You give ", StringComparison.Ordinal)) { _giveSawAcceptLine = true; return; }
var kind = ClassifyGiveChat(text);
if (kind == GiveChat.None)
{
// Types 1 (RynthAi's own lines), 7 (magic) and 17 (spell words) are never worth a slot.
if (_giveUnclassified < 10 && chatType != 1 && chatType != 7 && !text.StartsWith("[", StringComparison.Ordinal))
{
_giveUnclassified++;
Host.Log($"[Give] unclassified chat: type={chatType} '{text}'");
}
return;
}
// The first verdict noted for this give stands until the tick takes it.
if (Interlocked.CompareExchange(ref _giveChatVerdict, (int)kind, 0) == 0) _giveChatLine = text;
}
/// <summary>
/// One give at a time, answered before the next goes out (ACE cancels a move chain when a second
/// give arrives, and answers extras "too busy"). An answer is the item leaving the pack or its
/// stack shrinking: an NPC with a Give emote takes ONE item per give, so a shrunk stack goes
/// again at once, in the same tick. Busy refusals re-send after GiveBusyRetryMs, for up to GiveBusyGiveUpMs in total;
/// permanent refusals skip the stack. No answer at all in GiveConfirmMs re-sends, up to
/// GiveMaxTries, then skips. GiveQueueIntervalMs is only a minimum gap between two sends.
/// </summary>
private void DrainGiveQueue()
{
long now = Environment.TickCount64;
long now = GiveNow();
if (_giveInFlightId != 0)
{
if (GiveLanded())
{
_giveInFlightId = 0;
_lastGiveAt = DateTime.UtcNow;
if (_pendingGives.Count == 0)
ChatLine("[RynthAi] Give queue complete.");
}
else if (now - _giveInFlightAt < GiveConfirmMs)
return;
else if (_giveInFlightTries < GiveMaxTries)
{
GiveItem(_giveInFlightId, _giveInFlightTarget, _giveInFlightAmount, _giveInFlightStack);
_giveInFlightTries++;
_giveInFlightAt = now;
return;
}
else
{
ChatLine($"[RynthAi] Give: the server didn't take 0x{_giveInFlightId:X8} - skipping it.");
_giveInFlightId = 0;
if (_pendingGives.Count == 0) return;
}
if (!ResolveGiveInFlight(now)) return;
}
if (_pendingGives.Count == 0) return;
int intervalMs = _dashboard?.Settings.GiveQueueIntervalMs ?? 150;
if ((DateTime.UtcNow - _lastGiveAt).TotalMilliseconds < intervalMs) return;
var redo = _giveRedo;
if (!redo.HasValue && _pendingGives.Count == 0)
{
FinishGiveRun(now);
return;
}
int intervalMs = Math.Max(0, _dashboard?.Settings.GiveQueueIntervalMs ?? 0);
if (intervalMs > 0 && _giveLastSendAt != long.MinValue && now - _giveLastSendAt < intervalMs) return;
var (itemId, targetId, stackSize) = _pendingGives.Dequeue();
// The queued amount is what to hand over; GiveItem gives the whole object when it is
// the whole stack (amount 0) and uses AC's real give action, which an NPC accepts.
int whole = _objectCache?[unchecked((int)itemId)] is WorldObject wo ? Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) : stackSize;
GiveItem(itemId, targetId, stackSize, whole);
_lastGiveAt = DateTime.UtcNow;
_giveInFlightId = itemId;
_giveInFlightTarget = targetId;
_giveInFlightAmount = stackSize;
_giveInFlightStack = whole;
_giveInFlightTries = 1;
_giveInFlightAt = now;
uint itemId, targetId;
int amount;
if (redo.HasValue)
{
(itemId, targetId, amount) = redo.Value;
_giveRedo = null;
}
else
(itemId, targetId, amount) = _pendingGives.Dequeue();
if (!_giveRunActive)
{
_giveRunActive = true;
_giveRunStartAt = now;
_giveRunLastAnswerAt = now;
_giveRunItems = 0;
_giveRunSkips.Clear();
}
if (!SendGive(itemId, targetId, amount, 1, resent: false, now))
_giveRedo = (itemId, targetId, amount); // unreadable stack: first in line again next tick
}
/// <summary>The in-flight give went through: the item left the inventory, or part of its stack did.</summary>
private bool GiveLanded()
/// <summary>
/// Settles the in-flight give. Returns true when it is done (landed or skipped) and the tick may
/// send the next give now; false when the tick must stop (still waiting, or a re-send just went out).
/// </summary>
private bool ResolveGiveInFlight(long now)
{
if (_objectCache?[unchecked((int)_giveInFlightId)] is not WorldObject wo) return true;
if (!InPlayerInventory(wo.Container)) return true;
return _giveInFlightAmount < _giveInFlightStack
&& Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) < _giveInFlightStack;
long sinceSend = now - _giveInFlightAt;
string tag = $"0x{_giveInFlightId:X8} '{_giveInFlightName}'";
// 1. Progress: the item left the pack, or its stack shrank. A failed read is "no information":
// the stack count reads -1 (never a clamped 1, which looked like a shrink of 99), and an
// unreadable object (no cache entry, Container 0) must read the same on two ticks in a row.
var wo = _objectCache?[unchecked((int)_giveInFlightId)];
// Where it is: in the pack (the player, or a pack the player carries), with the give target (gone),
// or somewhere we cannot place. A container that is neither the player nor the target and whose own
// container reads 0 is unreadable, not gone.
int cont = wo?.Container ?? 0;
bool readable = wo != null && cont != 0;
bool carried = false;
if (readable)
{
int playerInt = unchecked((int)_playerId);
if (cont == playerInt) carried = true;
else if (cont != unchecked((int)_giveInFlightTarget))
{
int outer = _objectCache?.GetContainerId(cont) ?? 0;
if (outer == 0) readable = false;
else carried = outer == playerInt;
}
}
int stackNow = wo != null ? wo.Values(LongValueKey.StackCount, -1) : -1;
bool gone;
if (readable && !carried) { gone = true; _giveGoneStreak = 0; }
else if (readable) { gone = false; _giveGoneStreak = 0; }
else
{
_giveGoneStreak++;
gone = _giveGoneStreak >= 2;
}
if (gone)
{
int given = Math.Max(1, Math.Min(_giveInFlightRemaining, _giveInFlightStack));
Host.Log($"[RynthAi] Give answer: gone {tag} +{given} item(s) after {sinceSend} ms (accept line seen: {_giveSawAcceptLine})");
CompleteGiveStack(given, now);
return true;
}
if (carried && stackNow >= 0 && stackNow < _giveInFlightStack)
{
int delta = _giveInFlightStack - stackNow;
int remaining = _giveInFlightRemaining - delta;
Host.Log($"[RynthAi] Give answer: shrink {tag} {_giveInFlightStack}->{stackNow} after {sinceSend} ms (accept line seen: {_giveSawAcceptLine})");
_giveRunItems += delta;
_giveRunLastAnswerAt = now;
uint shrunkId = _giveInFlightId;
_giveInFlightId = 0;
_giveBusyRetryAt = 0;
_giveBusySince = 0;
if (remaining > 0)
_giveRedo = (shrunkId, _giveInFlightTarget, remaining);
return true;
}
// 2. A chat verdict.
var chat = (GiveChat)Interlocked.Exchange(ref _giveChatVerdict, 0);
if (chat == GiveChat.ItemNotFound)
{
// "Item not found" after a re-send means the earlier send landed, but only if the pack agrees:
// gone (or unreadable) counts as given; still carried with the same stack is a plain skip.
if (_giveInFlightResent && !carried)
{
int given = Math.Max(1, _giveInFlightRemaining);
Host.Log($"[RynthAi] Give answer: item-not-found after a re-send, item gone, counted as given {tag} +{given} item(s) after {sinceSend} ms");
CompleteGiveStack(given, now);
return true;
}
Host.Log($"[RynthAi] Give answer: permanent {tag} '{_giveChatLine}' after {sinceSend} ms");
SkipGiveStack("item not found", tag, now);
return true;
}
if (chat == GiveChat.Permanent)
{
Host.Log($"[RynthAi] Give answer: permanent {tag} '{_giveChatLine}' after {sinceSend} ms");
SkipGiveStack("refused", tag, now);
return true;
}
if (chat == GiveChat.Busy)
{
_giveBusyCount++;
if (_giveBusySince == 0) { _giveBusySince = now; _giveBusyNoticeAt = now; }
if (now - _giveBusySince >= GiveBusyGiveUpMs)
{
// A target that stays busy (a player in a trade) would otherwise be re-sent, and answer
// "too busy" in the player's chat, every GiveBusyRetryMs for ever.
Host.Log($"[RynthAi] Give answer: busy #{_giveBusyCount} {tag} for {now - _giveBusySince} ms; giving up");
string? busyWho = _objectCache?[unchecked((int)_giveInFlightTarget)]?.Name;
ChatLine($"[RynthAi] Give: {(string.IsNullOrEmpty(busyWho) ? "the target" : busyWho)} stayed busy for {(now - _giveBusySince) / 1000} s - skipping 0x{_giveInFlightId:X8}.");
SkipGiveStack("busy too long", tag, now);
return true;
}
if (_giveBusyCount == 1 || _giveBusyCount % 10 == 0)
Host.Log($"[RynthAi] Give answer: busy #{_giveBusyCount} {tag} '{_giveChatLine}' after {sinceSend} ms; re-sending in {GiveBusyRetryMs} ms");
if (now - _giveBusyNoticeAt >= GiveBusyNoticeMs)
{
_giveBusyNoticeAt = now;
string? who = _objectCache?[unchecked((int)_giveInFlightTarget)]?.Name;
ChatLine($"[RynthAi] Give: {(string.IsNullOrEmpty(who) ? "the target" : who)} is busy - still retrying (/ra givea stop to cancel).");
}
_giveBusyRetryAt = now + GiveBusyRetryMs;
}
if (_giveBusyRetryAt != 0)
{
if (now < _giveBusyRetryAt) return false;
_giveBusyRetryAt = 0;
if (!SendGive(_giveInFlightId, _giveInFlightTarget, _giveInFlightAll ? 0 : _giveInFlightRemaining, _giveInFlightTries, resent: true, now))
_giveBusyRetryAt = now; // unreadable stack: try again next tick
return false;
}
// 3. No answer at all.
if (sinceSend < GiveConfirmMs) return false;
if (_giveInFlightTries < GiveMaxTries)
{
Host.Log($"[RynthAi] Give answer: no-answer {tag} after {sinceSend} ms; re-sending");
if (!SendGive(_giveInFlightId, _giveInFlightTarget, _giveInFlightAll ? 0 : _giveInFlightRemaining, _giveInFlightTries + 1, resent: true, now))
{
_giveInFlightTries++; // this was a try even though nothing went out: GiveMaxTries stays a cap on sends
_giveBusyRetryAt = now; // unreadable stack: try again next tick
}
return false;
}
Host.Log($"[RynthAi] Give answer: no-answer {tag} after {sinceSend} ms; giving up");
ChatLine($"[RynthAi] Give: the server didn't take 0x{_giveInFlightId:X8} - skipping it.");
SkipGiveStack("no answer", tag, now);
return true;
}
private void CompleteGiveStack(int items, long now)
{
_giveRunItems += items;
_giveRunLastAnswerAt = now;
_giveInFlightId = 0;
_giveReadFailId = 0;
_giveBusyRetryAt = 0;
_giveBusySince = 0;
}
private void SkipGiveStack(string why, string tag, long now)
{
_giveRunSkips.Add($"{tag}: {why}");
Host.Log($"[RynthAi] Give skip: {tag} ({why})");
_giveRunLastAnswerAt = now;
_giveInFlightId = 0;
_giveReadFailId = 0;
_giveBusyRetryAt = 0;
_giveBusySince = 0;
}
/// <summary>
/// Sends one give and records it as the in-flight one. <paramref name="amount"/> is the items still to hand over;
/// 0 (or less) is a genuine "give all", the only request that may go out as a whole-object give when the stack
/// count cannot be read. An explicit amount, 1 included, always goes out as that explicit amount.
/// </summary>
private bool SendGive(uint itemId, uint targetId, int amount, int tries, bool resent, long now)
{
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
int read = wo != null ? wo.Values(LongValueKey.StackCount, -1) : -1;
// A failed read on a stackable item (MaxStackSize above 1) is no information: nothing is sent this
// tick, and the caller tries again next tick. A read that keeps failing for GiveReadFailMs must not
// hold the queue for ever: then the give goes out anyway, as the explicit amount asked for (1 included:
// a "give 1" of a stack that is really 99 must not hand over all 99) or, for a genuine give-all, as a
// plain give, and says so in the log.
bool all = amount <= 0;
if (read < 0 && wo != null && wo.Values(LongValueKey.MaxStackSize, -1) > 1)
{
if (_giveReadFailId != itemId) { _giveReadFailId = itemId; _giveReadFailSince = now; }
if (now - _giveReadFailSince < GiveReadFailMs) return false;
Host.Log($"[RynthAi] Give: stack count of 0x{itemId:X8} '{wo.Name}' unreadable for {now - _giveReadFailSince} ms; sending anyway ({(all ? "plain give" : $"amount {amount}")})");
}
else _giveReadFailId = 0;
// Here a negative read means a non-stackable item, an unknown one, or a stackable whose count stayed
// unreadable: record max(1, amount) as its stack. An explicit amount is sent as that explicit amount
// (an explicit 1 is what the engine sends for a single item anyway); only a give-all goes out whole.
int whole = read >= 0 ? Math.Max(1, read) : Math.Max(1, amount);
string name = wo?.Name ?? string.Empty;
_giveInFlightId = itemId;
_giveInFlightTarget = targetId;
_giveInFlightRemaining = read < 0 ? Math.Max(1, amount) : (amount <= 0 || amount > whole ? whole : amount);
_giveInFlightStack = whole;
_giveInFlightAll = all;
_giveInFlightTries = tries;
_giveInFlightResent = resent;
_giveInFlightName = name;
_giveInFlightAt = now;
_giveLastSendAt = now;
Interlocked.Exchange(ref _giveChatVerdict, 0);
_giveSawAcceptLine = false;
_giveGoneStreak = 0;
if (!resent) { _giveBusyCount = 0; _giveBusySince = 0; _giveUnclassified = 0; }
GiveItem(itemId, targetId, amount, read >= 0 ? whole : (all ? 0 : amount + 1)); // amount + 1: GiveItem must not fold an explicit amount into a whole give
Host.Log($"[RynthAi] Give send: 0x{itemId:X8} '{name}' stack={(read >= 0 ? whole.ToString() : "?")} amount={amount} try={tries}{(resent ? " (re-send)" : string.Empty)}");
return true;
}
private void FinishGiveRun(long now)
{
if (!_giveRunActive) return;
_giveRunActive = false;
long elapsed = Math.Max(0, _giveRunLastAnswerAt - _giveRunStartAt);
string avg = _giveRunItems > 0 ? $"{elapsed / _giveRunItems} ms" : "n/a";
string why = _giveRunSkips.Count == 0 ? string.Empty : $" ({string.Join("; ", _giveRunSkips)})";
string line = $"[RynthAi] Give queue complete: {_giveRunItems} item(s) given, {_giveRunSkips.Count} stack(s) skipped{why}, {elapsed / 1000.0:0.0}s total, {avg} per give.";
Host.Log(line);
ChatLine(line);
_giveRunItems = 0;
_giveRunSkips.Clear();
}
/// <summary>

View file

@ -60,6 +60,8 @@
<Compile Include="..\Shared\ServerCommandPanel.cs" Link="Shared\ServerCommandPanel.cs" />
<!-- Mini Remote session stats: RynthTracker's code, so the two show the same numbers (2026-10-11). -->
<Compile Include="..\Shared\KillCounter.cs" Link="Shared\KillCounter.cs" />
<!-- The pet-capture success replies: the Pets tab's auto-capture and RynthILT's Vaulted Dungeons timer. -->
<Compile Include="..\Shared\PetCaptureLines.cs" Link="Shared\PetCaptureLines.cs" />
<Compile Include="..\Shared\TrackerSessionStore.cs" Link="Shared\TrackerSessionStore.cs" />
<Compile Include="..\Shared\SessionStats.cs" Link="Shared\SessionStats.cs" />
<Compile Include="..\Shared\SessionStatsTracker.cs" Link="Shared\SessionStatsTracker.cs" />

View file

@ -636,7 +636,7 @@ internal sealed class AutoTradeManager
{
_idState.TryGetValue(id, out var st);
if (st.Attempts > 0 && now - st.LastAt < IdResendMs) continue;
_host.RequestId(id);
if (!_host.RequestId(id)) break; // refused (a death or a portal): not an attempt, asked again next tick
_idState[id] = (st.Attempts + 1, now);
_lastIdSentAt = now;
break;

View file

@ -564,7 +564,7 @@ internal sealed class AutoVendorManager
{
_idState.TryGetValue(id, out var st);
if (st.Attempts > 0 && now - st.LastAt < IdResendMs) continue;
_host.RequestId(id);
if (!_host.RequestId(id)) break; // refused (a death or a portal): not an attempt, asked again next tick
_idState[id] = (st.Attempts + 1, now);
_lastIdSentAt = now;
break;