ModernUO/Projects/UOContent/Engines/ML Quests/Objectives/BaseObjective.cs
Kamron Batman 2935eafe24
feat: convert all delta-time serialization to anchored time (#2589)
## Summary

Phase 3 of the anchored-time work: **every actively-written delta-time value in the engine now stores an anchored timestamp** — absolute on the wire, shifted forward by the downtime at load. Remaining time survives restarts (as delta did), and unlike delta, the bytes do not change on every save, so an idle world serializes identically save after save.

The answer to "is it possible everywhere": **yes** — including the one case that looked impossible.

## The GenericPersistence problem, solved

`GenericPersistence` bins (`Virtues.bin`, `StealableArtifacts.bin`, …) are raw payloads with no idx header, so they have no anchor of their own — anchored reads there would silently apply zero shift. But the anchor is a property of the **save**, not the file: every file in one save shares one `World.SaveStartTime`, and `Persistence.Load` reads **all** entity indexes (phase 1) before **any** persistence payload (phase 2). So the idx v5 header stamps a save-wide `World.LoadTimeShift`, and generic persistence readers inherit it. No file-format change, no per-bin header, old bins unaffected.

## Converted

- **Item v10 → v11**: `LastMoved` — previously whole-minute delta, rewritten every save for every item, the single largest source of idle-save churn — and `DecayResetTime` (retiring the TODO from #2583). **Mobile v37 → v38**: the three stat-gain stamps. **BaseCreature v20 → v21**: `SummonEnd`.
- **17 code-generated classes** (`[DeltaDateTime]` → `[AnchoredDateTime]`, version bump + `MigrateFrom` each): the five field spells, TransientItem, VirtueContext (×7 fields), PuzzleChestSolutionAndTime, BaseCamp, BaseBoat, RentedVendor, PlayerVendor, Ethics Player, Sheep, StarRoomGate, ChampionSpawn (×3), Corpse (`TimeOfDeath`, v19). The `MigrateFrom` bodies were generated from each class's current migration schema and are compiler-verified; VirtueContext's save-flagged nullables fall back to the same defaults the old deserialize left in place. Corpse's six migrations moved to a new `Corpse.Migrations.cs`.
- **Hand-written sites**: StealableArtifacts (v2), VendorInventory (v1), ML quest objectives (persistence v3) — each gated on its own version.

**Not converted, deliberately**: the ~25 read-only `ReadDeltaTime` sites in legacy version fallbacks and migration replays — they decode existing old bytes and must never change. `[DeltaDateTime]`/`WriteDeltaTime` remain available for them.

## Verification

- Build 0 errors / 0 warnings; **837 + 708 tests green**.
- Schema regeneration produced exactly the 17 expected new `vN.json` files (all `AnchoredTime` rule args), nothing else touched.
- **New acceptance tests** pin the point of the whole effort: serializing the same item at two save times **5 hours apart produces byte-identical output**, and `LastMoved`/`DecayResetTime` round-trip **exactly** at sub-minute precision (the old minutes encoding destroyed both properties).

## Notes for review

- `LastMoved` grows from a 1–3 byte encoded minutes value to 8-byte ticks per item — the price of byte-stability; it repays itself in incremental-save behavior since unchanged items now produce unchanged bytes.
- BaseEscortable-style semantics are unchanged: anchored shift preserves *remaining* time exactly, the same contract delta provided, so no gameplay-visible behavior changes — deadlines simply stop being consumed by downtime that delta already protected against, now with stable bytes.

## Enforcement

`WriteDeltaTime` is now `[Obsolete]` (interface + implementation). With the repo's warnings-as-errors, any new delta-time write — hand-written or emitted by a still-unconverted `[DeltaDateTime]` field — fails the build, with the migration instructions in the message. That the full solution still builds with **zero warnings** is itself the proof no active delta writer survived the conversion. `ReadDeltaTime` deliberately stays un-attributed: its remaining callers decode existing old bytes and are correct forever; its XML docs now state the legacy-decode-only contract.
2026-08-22 19:34:43 -07:00

186 lines
5 KiB
C#

using System;
using Server.Gumps;
using Server.Mobiles;
namespace Server.Engines.MLQuests.Objectives
{
public abstract class BaseObjective
{
public virtual bool IsTimed => false;
public virtual TimeSpan Duration => TimeSpan.Zero;
public virtual bool CanOffer(IQuestGiver quester, PlayerMobile pm, bool message) => true;
public abstract void WriteToGump(ref DynamicGumpBuilder builder, ref int y);
public virtual BaseObjectiveInstance CreateInstance(MLQuestInstance instance) => null;
}
public abstract class BaseObjectiveInstance
{
public enum DataType : byte
{
None,
EscortObjective,
KillObjective,
DeliverObjective
}
public BaseObjectiveInstance(MLQuestInstance instance, BaseObjective obj)
{
Instance = instance;
if (obj.IsTimed)
{
EndTime = Core.Now + obj.Duration;
}
}
public MLQuestInstance Instance { get; }
public bool IsTimed => EndTime != DateTime.MinValue;
public DateTime EndTime { get; set; }
public bool Expired { get; set; }
public virtual DataType ExtraDataType => DataType.None;
public virtual void WriteToGump(ref DynamicGumpBuilder builder, ref int y)
{
if (IsTimed)
{
WriteTimeRemaining(ref builder, ref y, Utility.Max(EndTime - Core.Now, TimeSpan.Zero));
}
}
public static void WriteTimeRemaining(ref DynamicGumpBuilder builder, ref int y, TimeSpan timeRemaining)
{
builder.AddHtmlLocalized(103, y, 120, 16, 1062379, 0x5F90); // Est. time remaining:
builder.AddLabel(223, y, 0x481, $"{timeRemaining.TotalSeconds:F0}");
y += 16;
}
public virtual bool AllowsQuestItem(Item item, Type type) => false;
public virtual bool IsCompleted() => false;
public virtual void CheckComplete()
{
if (IsCompleted())
{
Instance.Player.PlaySound(0x5B6); // public sound
Instance.CheckComplete();
}
}
public virtual void OnQuestAccepted()
{
}
public virtual void OnQuestCancelled()
{
}
public virtual void OnQuestCompleted()
{
}
public virtual bool OnBeforeClaimReward() => true;
public virtual void OnClaimReward()
{
}
public virtual void OnAfterClaimReward()
{
}
public virtual void OnRewardClaimed()
{
}
public virtual void OnQuesterDeleted()
{
}
public virtual void OnPlayerDeath()
{
}
public virtual void OnExpire()
{
}
public virtual void Serialize(IGenericWriter writer)
{
// Version info is written in MLQuestPersistence.Serialize
if (IsTimed)
{
writer.Write(true);
writer.WriteAnchoredTime(EndTime);
}
else
{
writer.Write(false);
}
// For type checks on deserialization
// (This way quest objectives can be changed without breaking serialization)
writer.Write((byte)ExtraDataType);
}
public static void Deserialize(IGenericReader reader, int version, BaseObjectiveInstance objInstance)
{
if (reader.ReadBool())
{
var endTime = version >= 3 ? reader.ReadAnchoredTime() : reader.ReadDeltaTime();
if (objInstance != null)
{
objInstance.EndTime = endTime;
}
}
var extraDataType = (DataType)reader.ReadByte();
switch (extraDataType)
{
case DataType.EscortObjective:
{
var completed = reader.ReadBool();
if (objInstance is EscortObjectiveInstance instance)
{
instance.HasCompleted = completed;
}
break;
}
case DataType.KillObjective:
{
var slain = reader.ReadInt();
if (objInstance is KillObjectiveInstance instance)
{
instance.Slain = slain;
}
break;
}
case DataType.DeliverObjective:
{
var completed = reader.ReadBool();
if (objInstance is DeliverObjectiveInstance instance)
{
instance.HasCompleted = completed;
}
break;
}
}
}
}
}