Restore the combat stance after a scroll read

Using a scroll puts the character in Peace. ScrollLearner remembers the mode from
before the first read of a run (Melee/Missile/Magic, Peace Mode When Idle off) and
requests it once, 3.5 s after the last read ends, through ChangeCombatModeFor (pacing,
busy wait, 3 tries). Dropped when the tick is not safe (fight/buff), or another
subsystem already changed the mode.

Review fixes:
- A restore more than 15 s after the settle time is dropped (death/vendor/buff holds, a stuck busy).
- The main-hand weapon is recorded at the first read; a different one cancels the restore (ACE reverts
  a mode the weapon does not fit).
- Only a request that went out counts toward the 3-request cap; pacer holds are retried.
- Peace Mode When Idle is re-checked each tick; the macro-stop close logs only from Peace; logs name modes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-10-12 16:20:31 -07:00
commit bef9b2b1a3
2 changed files with 375 additions and 0 deletions

View file

@ -358,6 +358,12 @@ internal sealed class ScrollLearner
return safe;
}
if (_seriesOpen)
{
if (!_settings.IsMacroRunning) CloseSeries(CurrentMode() == CombatMode.NonCombat ? "the macro stopped" : "");
else TickRestore(now, safe, busyCount);
}
if (!_settings.IsMacroRunning) return false;
if (!_settings.ReadUnknownScrolls && _pending.Count == 0) return false;
@ -380,6 +386,103 @@ internal sealed class ScrollLearner
return TryStartRead(inv, now);
}
// ── Stance restore ────────────────────────────────────────────────────────
// Using a scroll puts the character in Peace. The mode it was in before the FIRST read of a
// run of reads is remembered, and requested once after the last one, when it was a combat
// mode and Peace Mode When Idle is off, so the next fight starts in stance. Nothing is sent
// when something else owns the moment (not safe: a fight or buff), when anything else already
// changed the mode, or while the client is busy.
/// <summary>Quiet time after a read before the stance goes back: a next scroll starts within ReadGapMs + StartCheckMs.</summary>
internal const long RestoreSettleMs = 3_500;
internal const long RestoreRetryMs = 1_000;
internal const int RestoreMaxRequests = 3;
/// <summary>
/// How long after the settle time a restore may still go out. The learner is not ticked during a
/// death hold, a buff hold, vendoring or crafting, and the client can stay busy: a restore that
/// late is a stance from before the interruption (a previous life's Melee after a respawn), so
/// the series is dropped instead.
/// </summary>
internal const long RestoreGiveUpMs = 15_000;
private bool _seriesOpen;
private int _restoreMode; // 0 = nothing to restore
private int _restoreWeapon; // the main-hand weapon at the first read; ACE reverts a mode its weapon doesn't fit
private long _restoreNextAt;
private int _restoreRequests;
private int CurrentMode()
{
try { return _host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : 0; }
catch { return 0; }
}
private static string ModeName(int mode) => mode switch
{
CombatMode.NonCombat => "Peace",
CombatMode.Melee => "Melee",
CombatMode.Missile => "Missile",
CombatMode.Magic => "Magic",
_ => mode.ToString(),
};
/// <summary>The melee/missile weapon or caster in the main hand (0 = none readable); CombatManager.InHandWeaponId's rules.</summary>
private int WieldedWeaponId()
{
try
{
foreach (var wo in _cache?.GetDirectInventory(forceRefresh: true) ?? Array.Empty<WorldObject>())
{
if (WorldObjectCache.IsAmmo(wo)) continue;
if ((wo.Values(LongValueKey.CurrentWieldedLocation, 0) & OffhandRules.ShieldSlot) != 0) continue; // the off hand
bool weapon = wo.ObjectClass == AcObjectClass.MeleeWeapon || wo.ObjectClass == AcObjectClass.MissileWeapon || WeaponList.IsWand(wo);
if (weapon && WorldObjectCache.IsWieldedByPlayer(_host, wo)) return wo.Id;
}
}
catch { }
return 0;
}
private void OpenSeries()
{
if (_seriesOpen) return; // a later scroll of the same run: the first read's mode stands
_seriesOpen = true;
_restoreRequests = 0;
_restoreNextAt = 0;
int m = CurrentMode();
_restoreMode = !_settings.PeaceModeWhenIdle && (m == CombatMode.Melee || m == CombatMode.Missile || m == CombatMode.Magic) ? m : 0;
_restoreWeapon = _restoreMode != 0 ? WieldedWeaponId() : 0;
}
private void CloseSeries(string why)
{
if (_restoreMode != 0 && why.Length > 0) LogLine($"[Learn] stance not restored ({why})");
_seriesOpen = false;
_restoreMode = 0;
}
private void TickRestore(long now, bool safe, int busyCount)
{
if (_settings.PeaceModeWhenIdle) { CloseSeries(""); return; } // switched on since: Peace is wanted
long age = now - _lastReadEndedAt;
if (_restoreMode == 0) { if (age >= RestoreSettleMs) CloseSeries(""); return; }
if (age < RestoreSettleMs) return; // the next scroll may be about to start
if (age > RestoreSettleMs + RestoreGiveUpMs) { CloseSeries("too late"); return; }
int cur = CurrentMode();
if (cur == _restoreMode) { CloseSeries(""); return; } // back in stance
if (cur != CombatMode.NonCombat) { CloseSeries("something else set the mode"); return; }
if (!safe) { CloseSeries("a fight or another task has the tick"); return; }
if (busyCount > 0 || now < _restoreNextAt) return;
if (_restoreRequests >= RestoreMaxRequests) { CloseSeries("the client did not change mode"); return; }
if (WieldedWeaponId() != _restoreWeapon) { CloseSeries("the weapon changed"); return; }
// Only a request that went out counts: a pacing hold (another action unanswered) is retried next tick.
if (_host.ChangeCombatModeFor(_restoreMode, "Learn", "back to the stance from before the scroll read"))
{
_restoreRequests++;
_restoreNextAt = now + RestoreRetryMs;
LogLine($"[Learn] restoring {ModeName(_restoreMode)} mode after reading");
}
}
/// <summary>How often a waiting scroll is looked for in the pack.</summary>
internal const long StartCheckMs = 1_000;
private long _lastStartCheckAt = long.MinValue / 2;
@ -479,6 +582,7 @@ internal sealed class ScrollLearner
return false;
}
OpenSeries();
pp.Attempts++;
_readItemId = pickId;
_readSpellId = j.SpellId;
@ -600,6 +704,8 @@ internal sealed class ScrollLearner
/// <summary>Logout: the session memory goes with the character.</summary>
public void Reset()
{
_seriesOpen = false;
_restoreMode = 0;
_failedSpells.Clear();
_approved.Clear();
_pending.Clear();

View file

@ -56,6 +56,16 @@ internal static class LearnSpellsTests
r.Add("learn: with the setting off nothing is looted or read", SettingOffDoesNothing);
r.Add("learn: a scroll already in the pack is read, only at a safe moment", PackScrollAtSafeMoment);
r.Add("learn: a read with no answer is retried once, then given up", ReadTimeoutBounded);
r.Add("learn: a combat stance from before a read is requested once after it", StanceRestoredAfterRead);
r.Add("learn: no restore from Peace, with Peace Mode When Idle, or once the mode changed", StanceNotRestoredWhenNotWanted);
r.Add("learn: scrolls back to back restore the stance once, after the last", StanceRestoredOnceAfterSeries);
r.Add("learn: a fight during the read window is not fought over", StanceNotRestoredIntoAFight);
r.Add("learn: a restore that would come minutes late (no ticks, or busy for ever) is dropped", StanceTooLate);
r.Add("learn: a changed weapon in hand cancels the restore", StanceWeaponChanged);
r.Add("learn: pacing holds do not use up the restore budget", StancePacerHold);
r.Add("learn: Peace Mode When Idle switched on mid-window cancels the restore", StancePeaceIdleToggled);
r.Add("learn: a restore that never lands is tried 3 times, then given up", StanceNeverLands);
r.Add("learn: Reset and the macro stopping close the series", StanceResetAndMacroStop);
r.Add("learn: settings - on by default, old files keep it on, /vt opt and metas reach ReadUnknownScrolls", Settings);
}
@ -225,6 +235,265 @@ internal static class LearnSpellsTests
}
}
// ── Stance restore ────────────────────────────────────────────────────────
private static ScrollLearner StanceRig(int modeBefore, bool peaceIdle, int scrolls, out Clock clock, out LegacyUiSettings s,
Action? setup = null, params uint[] extraIds)
{
BaseWorld();
setup?.Invoke();
FakeHost.CombatModeCalls = true;
FakeHost.CombatModeValue = modeBefore;
AddScroll(PackScroll, FlameBoltIII, "Scroll of Flame Bolt III", Player);
var ids = new List<uint> { PackScroll };
ids.AddRange(extraIds);
if (scrolls > 1) { AddScroll(Scroll2, FrostBoltI, "Scroll of Frost Bolt I", Player); ids.Add(Scroll2); }
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, ids);
clock = new Clock();
s = Settings0();
s.PeaceModeWhenIdle = peaceIdle;
return Learner(host, s, cache, clock);
}
/// <summary>The read starts (the server then puts us in Peace), and ends with the scroll destroyed.</summary>
private static void FinishARead(ScrollLearner l, Clock c)
{
TickUntilRead(l, c);
Check.True(l.IsReading, "a read started");
FakeHost.CombatModeValue = CombatMode.NonCombat;
Learned();
l.OnChat("The scroll is destroyed.");
c.Now += 100;
l.Tick(true, 0);
Check.False(l.IsReading, "the read is over");
}
/// <summary>The scroll taught its spell (the fake server never deletes it, so mark it known).</summary>
private static void Learned() =>
FakeHost.Spellbook.Add((uint)(FakeHost.Uses.Last() == PackScroll ? FlameBoltIII : FrostBoltI));
private static void Quiet(ScrollLearner l, Clock c, long ms, bool safe = true, int busy = 0)
{
for (long t = 0; t < ms; t += 250) { c.Now += 250; l.Tick(safe, busy); }
}
private static void StanceRestoredAfterRead()
{
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out _);
FinishARead(l, c);
Quiet(l, c, 1_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "not at once: a next scroll may follow");
Quiet(l, c, 3_000);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Magic.ToString(), "Magic requested once after the read");
FakeHost.CombatModeValue = CombatMode.Magic; // the client switched
Quiet(l, c, 6_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 1, "and not again");
// The client is busy: the request waits, then goes out.
var b = StanceRig(CombatMode.Melee, false, 1, out var cb, out _);
FinishARead(b, cb);
Quiet(b, cb, 5_000, busy: 2);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "busy: held");
Quiet(b, cb, 500);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Melee.ToString(), "free again: Melee requested");
Done();
}
private static void StanceNotRestoredWhenNotWanted()
{
var peace = StanceRig(CombatMode.NonCombat, false, 1, out var c1, out _);
FinishARead(peace, c1);
Quiet(peace, c1, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "Peace before the read: nothing");
var idle = StanceRig(CombatMode.Magic, true, 1, out var c2, out _);
FinishARead(idle, c2);
Quiet(idle, c2, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "Peace Mode When Idle on: nothing");
var moved = StanceRig(CombatMode.Magic, false, 1, out var c3, out _);
FinishARead(moved, c3);
FakeHost.CombatModeValue = CombatMode.Melee; // something else chose a mode
Quiet(moved, c3, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "another subsystem set a mode: left alone");
Done();
}
private static void StanceRestoredOnceAfterSeries()
{
var l = StanceRig(CombatMode.Magic, false, 2, out var c, out _);
FinishARead(l, c);
Quiet(l, c, 2_000); // the second scroll starts inside the settle time
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no restore between reads");
if (!l.IsReading) TickUntilRead(l, c);
Check.True(l.IsReading, "the second scroll is being read");
FakeHost.CombatModeValue = CombatMode.NonCombat;
Learned();
l.OnChat("The scroll is destroyed.");
c.Now += 100;
l.Tick(true, 0);
Check.False(l.IsReading, "second read over");
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "still none");
Quiet(l, c, 3_750);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Magic.ToString(), "one restore, after the last: ");
Done();
}
private static void StanceNotRestoredIntoAFight()
{
// The fight starts in the settle window and combat sets its own stance.
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out _);
FinishARead(l, c);
Quiet(l, c, 1_000, safe: false);
FakeHost.CombatModeValue = CombatMode.Missile;
Quiet(l, c, 8_000, safe: false);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "combat owns the mode: no restore");
// Still in Peace when the settle time ends but a fight holds the tick: dropped, not queued behind it.
var f = StanceRig(CombatMode.Magic, false, 1, out var c2, out _);
FinishARead(f, c2);
Quiet(f, c2, 4_000, safe: false);
Quiet(f, c2, 4_000, safe: true);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "not safe at restore time: dropped");
Check.True(Logged("stance not restored"), "and logged: " + LearnLogs());
Done();
}
private const uint SwordW = 0x80000601, DaggerW = 0x80000602;
private static void Weapons()
{
foreach (var (id, name) in new[] { (SwordW, "Long Sword"), (DaggerW, "Dagger") })
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = 0x1;
FakeHost.Ints[(id, 9)] = 0x00100000;
}
FakeHost.Ints[(SwordW, 10)] = 0x00100000; // the sword is in hand
}
private static void StanceTooLate()
{
// No learner tick for 20 minutes (a death hold, a vendor hold): not Melee from a past life.
var l = StanceRig(CombatMode.Melee, false, 1, out var c, out _);
FinishARead(l, c);
c.Now += 1_200_000;
l.Tick(true, 0);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "20 minutes later: no request");
Check.True(Logged("stance not restored (too late)"), "and logged: " + LearnLogs());
Quiet(l, c, 4_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "and the series is closed");
// The client stays busy for ten minutes: dropped at the limit, not sent when it frees up.
var b = StanceRig(CombatMode.Magic, false, 1, out var cb, out _);
FinishARead(b, cb);
Quiet(b, cb, 600_000, busy: 1);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "busy for 10 minutes: nothing sent");
Quiet(b, cb, 2_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "and not when it frees up");
Check.True(Logged("stance not restored (too late)"), "logged: " + LearnLogs());
Done();
}
private static void StanceWeaponChanged()
{
// ACE reverts a mode the wielded weapon doesn't fit: a different weapon in hand cancels the restore.
var l = StanceRig(CombatMode.Melee, false, 1, out var c, out _, Weapons, SwordW, DaggerW);
FinishARead(l, c);
FakeHost.Ints.Remove((SwordW, 10));
FakeHost.Ints[(DaggerW, 10)] = 0x00100000;
Quiet(l, c, 6_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "another weapon in hand: no request");
Check.True(Logged("stance not restored (the weapon changed)"), "logged: " + LearnLogs());
// Same weapon: restored.
var s = StanceRig(CombatMode.Melee, false, 1, out var c2, out _, Weapons, SwordW, DaggerW);
FinishARead(s, c2);
Quiet(s, c2, 4_000);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Melee.ToString(), "the same weapon: Melee requested");
Check.True(Logged("restoring Melee mode"), "the log names the mode: " + LearnLogs());
Done();
}
private static void StancePacerHold()
{
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out _);
long t = 50_000_000;
ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => t;
try
{
FinishARead(l, c);
var host = FakeHost.Create(Player);
// Another subsystem's action has no answer yet, so a mode change is held for the whole window.
for (long ms = 0; ms < 8_000; ms += 250)
{
c.Now += 250; t += 250;
if (ActionPacer.Current(host) == null) ActionPacer.Begin(host, PacedKind.ItemUse, 1, "x", "Other", 0);
l.Tick(true, 0);
}
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "held by the pacer: nothing sent");
Check.False(Logged("did not change mode"), "and no false give-up: " + LearnLogs());
// The action is answered: exactly one request.
ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => t;
Quiet(l, c, 500);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Magic.ToString(), "answered: exactly one request");
}
finally { ActionPacer.Enabled = false; ActionPacer.Reset(); ActionPacer.NowMs = () => Environment.TickCount64; Done(); }
}
private static void StancePeaceIdleToggled()
{
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out var s);
FinishARead(l, c);
Quiet(l, c, 1_000);
s.PeaceModeWhenIdle = true;
Quiet(l, c, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "switched on mid-window: no request");
Check.False(Logged("stance not restored"), "and silently: " + LearnLogs());
Done();
}
private static void StanceNeverLands()
{
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out _);
FinishARead(l, c);
Quiet(l, c, 12_000); // the client never reads Magic
Check.Eq(FakeHost.CombatModeRequests.Count, ScrollLearner.RestoreMaxRequests, "exactly the cap");
Check.True(Logged("stance not restored (the client did not change mode)"), "then the give-up line: " + LearnLogs());
Quiet(l, c, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, ScrollLearner.RestoreMaxRequests, "and no more");
Done();
}
private static void StanceResetAndMacroStop()
{
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out _);
FinishARead(l, c);
l.Reset();
Quiet(l, c, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "Reset closes the series");
// The macro stops while in Peace: no request, and it says why.
var m = StanceRig(CombatMode.Magic, false, 1, out var c2, out var s2);
FinishARead(m, c2);
s2.IsMacroRunning = false;
c2.Now += 500; m.Tick(true, 0);
Quiet(m, c2, 6_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "macro stopped: no request");
Check.True(Logged("stance not restored (the macro stopped)"), "logged when it was in Peace: " + LearnLogs());
// Still in stance (the read never took it out): closes without a log.
var n = StanceRig(CombatMode.Magic, false, 1, out var c3, out var s3);
FinishARead(n, c3);
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Logs.Clear();
s3.IsMacroRunning = false;
c3.Now += 500; n.Tick(true, 0);
Check.False(Logged("stance not restored"), "still in stance: closed silently: " + LearnLogs());
Done();
}
// ── Tests ─────────────────────────────────────────────────────────────────
private static void AceRule()