ModernUO/Projects/UOContent/Skills/DetectHidden.cs
Kamron Batman 392c4e16d5
refactor: Changes BaseCreature to the SerializationGenerator (delta save requirement) (#2611)
The pure SerializationGenerator conversion of `BaseCreature`, split out of #2592 so it can serve as the reference for converting every other large hand-written class in the Delta Saves project (#7, phase 3). Two behaviour changes from #2592 are deliberately not here and follow in their own PRs on top of this one: `SpeedClass`, and the collapse of `ControlMaster`/`SummonMaster` into one reference (a creature can lose or keep either independently: Blade Spirits and Energy Vortexes are summoned but never controlled, EnragedCreature and talisman summons keep a summon master with neither flag set).

## What this is

- `BaseCreature` becomes `[SerializationGenerator(23, false)]` with a `[SerializableField]` per serialized slot and `[SaveFlag]` elision on nearly every field, so a stock creature serializes to its version plus flags. Field orders run 0..53 with no gaps (54 fields).
- The hand-written reader stays as `private void Deserialize(IGenericReader reader, int version)` for every pre-codegen version (0..22); post-codegen bumps use `MigrateFrom` from here on. `[AfterDeserialization]` carries the post-load fixups main did after reading (stat timers, AI type, followers, reacquire seeding).
- `ControlMaster` and `SummonMaster` stay two independent fields with main's semantics, each elided when null.
- `DamageMin`/`DamageMax`/`ActiveSpeed`/`PassiveSpeed` are no longer virtual (nothing in the tree overrode them); comments swept to the constraints that matter.
- Direct writes to serialized backing fields outside the generated setters (`SetDamage`, `SetResistance`, the move-speed helpers, the loot flag, feed loyalty, the delete timer) call `this.MarkDirty()`, matching the #2609 standard, so the class is ready for delta saves once `Mobile` is audited.
- Schema `Server.Mobiles.BaseCreature.v23.json` regenerated by the tool (a second run produces no diff).

## Deferred to follow-up PRs

SpeedClass: the serialized `_speedClass` field, `DefaultSpeedClass` replacing the type constant, `ApplySpeedClass`/`OnSpeedClassChange`, "None means custom", the four-speeds-as-one-block elision, `NPCSpeeds.FindEntry(SpeedLevel)`, the constructor fallback to Medium, and their tests.

Master references: serializing one `Master` with a `Controlled`/`Summoned` fan-out and the `SetControlMaster` lockstep.

## Tests

UOContent.Tests 776 / Server.Tests 855 green. `BaseCreatureSerializationTests` covers: a default creature elides to version + flags; a populated creature round-trips with exact byte consumption; back-to-back saves are byte-identical; an uncontrolled summon keeps its SummonMaster; byte-authentic v22 legacy streams (replicas of main's `Serialize`) load through the legacy reader for a wild tamable, a controlled pet, a controlled summon with an anchored `SummonEnd`, and a summon-master-only creature (the EnragedCreature shape); a running delete timer round-trips through `[DeserializeTimer]`; `Friends`, `CurrentWayPoint` and `HomeMap` round-trip; a `BaseVendor` stub round-trips the generated BaseVendor v2 → generated BaseCreature v23 chain.

## Behaviour notes for reviewers

- `ActiveMoveSpeed`/`PassiveMoveSpeed` getters return the raw override (0 = inherit); `CurrentMoveSpeed` is the resolved pace.
- Speeds elided as table defaults re-snap to the current `npc-speeds.json` on load, so table edits reach unmodified spawns on restart.
- `GetSpeeds` no longer throws on the save/load path when the table has no entry for the type: saves elide against the creature's own values and loads keep the stream. Construction still throws (`InvalidOperationException`, was `KeyNotFoundException`). An elided load with no table entry would otherwise resume at speed 0, so `[AfterDeserialization]` logs once and paces it at Medium.
- `virtual` removed from `ActiveSpeed`, `PassiveSpeed`, `DamageMin`, `DamageMax` (no overrides in the tree; forks may have some).
- `ControlMaster`, `SummonMaster`, `ControlOrder`, `Tamable`, `IsParagon` are `[SerializableProperty]` over hand-written setters because follower bookkeeping must run before the assignment, which a `fieldChanged` hook cannot express; the wire format is identical.

## Prerequisites for cherry-picking
#2609 (BaseVendor is already generated on top of BaseCreature) and SerializationGenerator 4.1.0.
2026-09-06 14:11:51 -07:00

268 lines
9.3 KiB
C#

using System;
using System.Collections.Generic;
using Server.Engines.PartySystem;
using Server.Factions;
using Server.Guilds;
using Server.Items;
using Server.Mobiles;
using Server.Multis;
using Server.Network;
using Server.Systems.FeatureFlags;
using Server.Targeting;
namespace Server.SkillHandlers;
public static class DetectHidden
{
// Debounce tracking: (stealther, detector) -> last detection time
private static readonly Dictionary<(Mobile, Mobile), long> PassiveDetectDebounce = [];
private const int PassiveDetectDebounceMs = 3000; // 3 seconds
private const int DebounceCleanupIntervalMs = 10000; // Run cleanup every 10 seconds
private const int DebounceExpiryMs = 10000; // Remove entries older than 10 seconds
private static long _lastCleanupTime;
public static void Initialize()
{
SkillInfo.Table[(int)SkillName.DetectHidden].Callback = OnUse;
}
public static TimeSpan OnUse(Mobile src)
{
src.SendLocalizedMessage(500819); // Where will you search?
src.Target = new InternalTarget();
return TimeSpan.FromSeconds(30.0);
}
// Clean up old debounce entries to prevent memory bloat
private static void CleanupDebounceCache(long now)
{
foreach (var entry in PassiveDetectDebounce)
{
if (now - entry.Value > DebounceExpiryMs)
{
PassiveDetectDebounce.Remove(entry.Key);
}
}
}
// For testing: clear the debounce cache to prevent cross-test contamination
internal static void ClearDebounceCache()
{
PassiveDetectDebounce.Clear();
}
// Passive detection: check if a detector can passively detect a stealther.
// Called via OnMovement when either party moves within range.
// Returns true if detection was successful (and the stealther was revealed).
// NOTE: OSI uncertain - The exact chance calculation and distance dropoff is unknown.
// We use a ±10 variance on both skills, matching active detection mechanics.
public static bool TryDetectStealther(Mobile detector, Mobile stealther)
{
if (!ContentFeatureFlags.PassiveDetectHidden || stealther == detector || !stealther.Hidden || !detector.Alive)
{
return false;
}
// Felucca PvP only
if (stealther.Map != Map.Felucca)
{
return false;
}
var detectSkill = detector.Skills.DetectHidden.Value;
if (detectSkill <= 0)
{
return false;
}
var now = Core.TickCount;
// Debounce: skip pairs already checked recently (cheap dictionary lookup before expensive checks)
var key = (stealther, detector);
if (PassiveDetectDebounce.TryGetValue(key, out var lastDetect) && now - lastDetect < PassiveDetectDebounceMs)
{
return false;
}
// Periodic cleanup (amortized, not every call)
if (now - _lastCleanupTime > DebounceCleanupIntervalMs)
{
_lastCleanupTime = now;
CleanupDebounceCache(now);
}
// Excludes blessed, dead, bonded pets, and region-based PvP rules
if (stealther.AccessLevel > AccessLevel.Player || !detector.CanBeHarmful(stealther, false))
{
return false;
}
// Exclude party members
var stealtherParty = Party.Get(stealther);
var detectorParty = Party.Get(detector);
if (stealtherParty != null && stealtherParty == detectorParty)
{
return false;
}
// Exclude guild members and allies
if (stealther.Guild is Guild sg && detector.Guild is Guild dg && (sg == dg || sg.IsAlly(dg)))
{
return false;
}
var ss = detectSkill + Utility.Random(21) - 10;
var ts = stealther.Skills.Hiding.Value + Utility.Random(21) - 10;
if (ss >= ts)
{
stealther.RevealingAction();
stealther.SendLocalizedMessage(500814); // You have been revealed!
PassiveDetectDebounce[key] = now;
return true;
}
return false;
}
private class InternalTarget : Target
{
public InternalTarget() : base(12, true, TargetFlags.None)
{
}
protected override void OnTargetCancel(Mobile from, TargetCancelType cancelType)
{
from.NextSkillTime = Core.TickCount;
}
protected override void OnTarget(Mobile src, object targ)
{
var foundAnyone = false;
var srcSkill = src.Skills.DetectHidden.Value;
var range = (int)(srcSkill / 10.0);
if (targ is TrappableContainer container && container.TrapType != TrapType.None)
{
// Direct container targeting: show [trapped] if within detection range and skill check passes
if (src.InRange(container.GetWorldLocation(), range) &&
src.CheckSkill(SkillName.DetectHidden, 0.0, 100.0))
{
src.NetState.SendMessageLocalized(
container.Serial,
container.ItemID,
MessageType.Regular,
0x3B2,
3,
500813 // [trapped]
);
foundAnyone = true;
}
}
else if (targ is not Item && (targ is not Mobile m || m == src))
{
// Area scan only when targeting self or the ground
var p = targ switch
{
Mobile mobile => mobile.Location,
IPoint3D d => new Point3D(d),
_ => src.Location
};
if (!src.CheckSkill(SkillName.DetectHidden, 0.0, 100.0))
{
range /= 2;
}
var house = BaseHouse.FindHouseAt(p, src.Map, 16);
var inHouse = house?.IsFriend(src) == true;
if (inHouse)
{
range = 22;
}
if (range > 0)
{
foreach (var trg in src.Map.GetMobilesInRange(p, range))
{
if (!trg.Hidden || src == trg)
{
continue;
}
var ss = srcSkill + Utility.Random(21) - 10;
var ts = trg.Skills.Hiding.Value + Utility.Random(21) - 10;
if (src.AccessLevel < trg.AccessLevel || ss < ts && (!inHouse || !house.IsInside(trg)))
{
continue;
}
if (trg is ShadowKnight && (trg.X != p.X || trg.Y != p.Y))
{
continue;
}
trg.RevealingAction();
trg.SendLocalizedMessage(500814); // You have been revealed!
foundAnyone = true;
}
foreach (var item in src.Map.GetItemsInRange(p, range))
{
if (item is BaseFactionTrap factionTrap)
{
if (Faction.Find(src) != null &&
src.CheckTargetSkill(SkillName.DetectHidden, factionTrap, 80.0, 100.0))
{
src.SendLocalizedMessage(
1042712, // You reveal a trap placed by a faction:
true,
$" {(factionTrap.Faction == null ? "" : factionTrap.Faction.Definition.FriendlyName)}"
);
factionTrap.Visible = true;
factionTrap.BeginConceal();
foundAnyone = true;
}
}
else if (item is BaseTrap { Visible: false } trap)
{
// High Seas (Publish 79): Requires 75 Detect Hidden to detect dungeon traps
if (Core.HS && srcSkill < 75.0)
{
continue;
}
trap.Visible = true;
Timer.StartTimer(TimeSpan.FromSeconds(10.0), () =>
{
if (!trap.Deleted)
{
trap.Visible = false;
}
});
foundAnyone = true;
}
}
}
}
if (!foundAnyone)
{
src.SendLocalizedMessage(500817); // You can see nothing hidden there.
}
// Calculate how much time has passed since the targeter was opened
var ticksSinceTargeter = (int)(Core.TickCount - (src.NextSkillTime - 30000));
var remainingCooldown = Math.Max(0, 10000 - ticksSinceTargeter);
src.NextSkillTime = Core.TickCount + remainingCooldown;
}
}
}