ModernUO/Projects/UOContent/Mobiles/AI/BaseAI/AITimer.cs
Kamron Batman e7f85d404d
feat: Adds independent think/move clocks for creature AI to fix speed (#2591)
Splits creature speed into two clocks so movement pace can be tuned without touching reaction time:

- **Think clock** — `ActiveSpeed`/`PassiveSpeed`/`CurrentSpeed`: seconds per AI decision. Unchanged in meaning, storage, and cadence.
- **Move clock** — `ActiveMoveSpeed`/`PassiveMoveSpeed` (+ resolved `CurrentMoveSpeed`): seconds per step. `0` = inherit the matching think value.

### How

- Move speeds come from optional `activeMove`/`passiveMove` in `npc-speeds.json`, are `[props`-tunable per instance (set `0` to re-inherit), and serialize (BaseCreature v22).
- `SetSpeed()` keeps its legacy one-clock semantics — sets the think clock **and clears move overrides** — so existing callers cannot half-configure a creature. `SetMoveSpeed()`/`ClearMoveSpeed()` configure movement explicitly; `ScaleMoveSpeed()` scales overrides for buffs.
- `CurrentMoveSpeed` is derived by classifying `CurrentSpeed`: a verbatim active/passive think value maps to the matching move value; a bespoke pace written directly (mount boosts, follow sprint) stays fused to both clocks. External `CurrentSpeed` writers need no changes.
- `AITimer` schedules the earlier of the two deadlines. Decisions run at the think cadence exactly as before; while a pursuit/investigation is live, the timer also wakes when the movement budget elapses and advances one step with no decisions. Steps no longer snap to the think grid, so any step delay paces smoothly on the 8ms wheel. A blocked creature schedules no move wakes.
- The movement budget is RunUO's `m_NextMove` accumulate-and-clamp at a full step, so long-run pacing averages `CurrentMoveSpeed` exactly.

### Behavior changes

- **`npc-speeds.json` buckets get RunUO `TransformMoveDelay`-parity move values**: creatures step at RunUO pace while thinking/reacting at current speed. The situational +0.1/+0.2 offsets are deliberately omitted.
- **Existing saves migrate on load**: a pre-v22 creature whose think speeds still match its npc-speeds entry (never hand-tuned) adopts the table's move values — worlds and pets pick up the new pacing without a respawn. Tuned creatures keep movement inheriting their think clock.
- **Paragons scale movement by `SpeedBuff` (1.2x)**: RunUO had no deliberate policy here — dividing by 1.2 knocked most speeds off `TransformMoveDelay`'s exact-equality table (raw pass-through, 2x+ faster), while 0.3/0.6 creatures landed back on it for ~1.33x. This applies the uniform 1.2x the buff always claimed. UnConvert snaps speeds back to exact table values within 1e-4 — /1.2 then ×1.2 drifts 0.45 and 0.9 by an ulp, which would read as hand-tuned (and defeat a future skip-table-conformant-values serialization pass); tuned speeds keep.
- **Herding paces the movement clock**: the old `CurrentSpeed` getter hack is gone. A herded creature walks at a fixed 0.3s/step — RunUO's forced pace, without its `TransformMoveDelay` inflation to 0.6 — so herding is never penalized by a slow creature. Thinking is untouched, and `CheckHerding` walks through `MoveToPoint`, so herded creatures path around obstacles.
- **Badly-hurt slowdown now inflates the step delay only** (RunUO parity), computed from the base each step. Previously it wrote `CurrentSpeed = CurrentSpeed + 0.05..0.15` back on every successful step — compounding unboundedly while hurt and slowing decisions too.
- Removes the vestigial `MoveSpeedMod` (never read, written, or serialized).
- With no bucket or per-instance move values, both clocks carry identical values and creatures pace as before.

### Testing

- Full suite passes (1557, including 12 new `MoveSpeedTests`: resolution classes, `SetSpeed` clearing, `0`-re-inherit, v22 round-trip with exact-consumption check, save migration adopt/skip, buff scale/snap, herding).
- In-game verified via local diagnostics build (per-step budget tracing): steady 700ms step cadence on a 0.3s think grid with one-step catch-up after idle, think grid unperturbed by move wakes.
2026-08-23 10:19:59 -07:00

168 lines
5 KiB
C#

/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: AITimer.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
************************************************************************/
using System;
namespace Server.Mobiles;
/// <summary>
/// Drives an AI on two clocks: decisions at <see cref="BaseCreature.CurrentSpeed"/>, plus
/// move-only wakes at <see cref="BaseAI.NextMove"/> while a pursuit is live. Each tick
/// schedules the earlier of the two deadlines.
/// </summary>
public sealed class AITimer : Timer
{
private readonly BaseAI _owner;
private long _nextThink;
private int _detectHiddenMinDelay;
private int _detectHiddenMaxDelay;
public AITimer(BaseAI owner) : base(TimeSpan.FromMilliseconds(Utility.Random(3000)),
TimeSpan.FromSeconds(owner.Mobile.CurrentSpeed))
{
_owner = owner;
_owner._nextDetectHidden = Core.TickCount;
_nextThink = Core.TickCount;
}
public void Activate()
{
_nextThink = Core.TickCount;
Interval = TimeSpan.FromSeconds(_owner.Mobile.CurrentSpeed);
Start();
}
// A speed-up must not wait out a stale, longer think deadline.
public void OnSpeedChanged()
{
var candidate = Core.TickCount + (long)(_owner.Mobile.CurrentSpeed * 1000);
if (candidate - _nextThink < 0)
{
_nextThink = candidate;
}
Interval = TimeSpan.FromSeconds(_owner.Mobile.CurrentSpeed);
}
protected override void OnTick()
{
if (ShouldStop())
{
Stop();
return;
}
if (Core.TickCount - _nextThink >= 0)
{
_owner.Mobile.OnThink();
if (ShouldStop())
{
Stop();
return;
}
HandleBardEffects();
if (_owner.Mobile.Controlled ? _owner.Obey() : _owner.Think())
{
HandleDetectHidden();
}
// Cadence from the post-decision speed (decisions may flip active/passive).
_nextThink = Core.TickCount + (long)(_owner.Mobile.CurrentSpeed * 1000);
}
else
{
_owner.ContinueMove();
}
ScheduleNext();
}
private void ScheduleNext()
{
var now = Core.TickCount;
var delay = _nextThink - now;
if (_owner.TryGetMoveWake(out var nextMove))
{
var moveDelay = nextMove - now;
// Only a future budget is a wake — a blocked creature must not spin the timer.
if (moveDelay > 0 && moveDelay < delay)
{
delay = moveDelay;
}
}
// The wheel rounds up to its 8ms resolution; a non-positive delay becomes one turn.
Interval = TimeSpan.FromMilliseconds(delay);
}
private bool ShouldStop()
{
if (_owner.Mobile.Deleted)
{
return true;
}
if (_owner.Mobile.Map == null || _owner.Mobile.Map == Map.Internal || _owner.Mobile.PlayerRangeSensitive &&
!_owner.Mobile.Controlled && !_owner.Mobile.Map.GetSector(_owner.Mobile.Location).Active)
{
_owner.Deactivate();
return true;
}
return false;
}
private void HandleBardEffects()
{
if (_owner.Mobile.BardPacified)
{
_owner.DoBardPacified();
}
else if (_owner.Mobile.BardProvoked)
{
_owner.DoBardProvoked();
}
}
private void CacheDetectHiddenDelays()
{
var delay = Math.Min(30000 / _owner.Mobile.Int, 120);
_detectHiddenMinDelay = delay * 900; // 26s to 108s
_detectHiddenMaxDelay = delay * 1100; // 32s to 132s
}
private void HandleDetectHidden()
{
if (!_owner.CanDetectHidden || Core.TickCount - _owner._nextDetectHidden < 0)
{
return;
}
_owner.DetectHidden();
if (_detectHiddenMinDelay == 0 || _detectHiddenMaxDelay == 0)
{
CacheDetectHiddenDelays();
}
_owner._nextDetectHidden = Core.TickCount + Utility.RandomMinMax(_detectHiddenMinDelay, _detectHiddenMaxDelay);
}
}