ModernUO/Projects/UOContent/Engines/Spawners/Json/SpawnerDto.cs
Kamron Batman a52ce6ef70
refactor(spawners): subclass-owned entries, lifecycle hooks, per-entry Disabled flag (#2621)
## Summary

Moves spawner entry storage out of the abstract `BaseSpawner` into the concrete owner, so a spawner subclass can store its own entry type while every stock code path keeps working. Motivation: an out-of-tree spawner (ModernSpawner) needs `ModernSpawnerEntry : SpawnerEntry` with extra fields; today `BaseSpawner` owns `List<SpawnerEntry>` and a family of non-virtual members, and the serialization generator constructs list elements from the declared element type, so storage has to live in the class that declares the concrete list.

### What changed

- **`BaseSpawner` v13** no longer owns `_entries`. It reads entries through an abstract view and mutates them through an owner contract (`BaseSpawner.Entries.cs`):
  `Entries` (`IReadOnlyList<SpawnerEntry>`, `[IgnoreDupe]`), `EntrySpan` (`ReadOnlySpan<SpawnerEntry>` for hot loops), `CreateEntry`, `AddEntryCore`, `RemoveEntryCore`, `ClearEntriesCore`, `AdoptEntries`, `CloneEntry`, `TransferSpawned`, plus public `RemoveAllEntries()`, `CopyEntriesTo(target)` and protected `RebuildSpawned()`. Every loop inside `BaseSpawner` is an indexed `for` over `EntrySpan`.
- **`Spawner` v2** owns `[SerializedIgnoreDupe] List<SpawnerEntry> _entryList` (generated `EntryList`, protected). `ProximitySpawner`/`RegionSpawner` inherit it unchanged. The `Spawned` rebuild and timer re-arm moved from the base `[AfterDeserialization]` (which runs before derived fields are read) into `Spawner`'s.
- **Save migration**: `MigrateFrom(V12Content)` (and the v10/v11/legacy readers) hand the old list to the owner via `AdoptEntries`; `Spawner.MigrateFrom(V1Content)` restores its own fields and leaves the adopted list alone. Three v12/v1/v0 save blobs captured before the change are committed as fixtures and loaded by tests.
- **Lifecycle hooks** (`BaseSpawner.Hooks.cs`, all no-op by default): `OnStarted`, `OnStopped`, `OnBeforeSpawn(entry)` veto, `OnConfigureSpawned(entry, spawned)` before positioning, entry-aware `GetSpawnPosition(entry, spawned, map)`, `OnSpawned(entry, spawned)`, `OnSpawnedDeath(entry, spawned, killer)`. `BaseCreature.OnDeath` calls `NotifySpawnedDeath` before base death (which deletes the mobile and unlinks the spawner). `Start()` and the `NextSpawn` setter share one start core so `OnStarted` fires on both.
- **`SpawnerEntry` v2**: per-entry `Disabled` (XmlSpawner's entry "lock"), stored inverted so the common case writes nothing in binary or JSON; skipped by weighted selection, live spawns untouched; toggle button per row in `SpawnerGump`. `SetParent` is public and `Parent` is protected so an out-of-tree entry subclass can adopt and dirty-track.
- **DTO**: `SpawnerDto` loses `Entries`; each concrete record declares its own `entries` at the same JSON order, so `Distribution/Data/Spawns/**` is byte-identical. Import adopts the deserialized entry objects instead of recreating them through `AddEntry`, which is what preserves subtype fields (and `disabled`).

### Breaking changes and behaviour changes

- **API:** `BaseSpawner.Entries` is `IReadOnlyList<SpawnerEntry>` instead of `List<SpawnerEntry>`. The generated `AddToEntries`/`RemoveFromEntries`/`InsertIntoEntries`/`RemoveFromEntriesAt`/`ClearEntries` helpers on `BaseSpawner` are gone; use `AddEntry`/`RemoveEntry`/`RemoveAllEntries`/`CopyEntriesTo`. `RemoveAllEntries()` deletes the entries' live spawns as well as the entries (the old generated `ClearEntries()` only cleared the list), which is why it has a new name rather than the old one.
- `SpawnerControllerGump` "copy entries" now goes through `CopyEntriesTo`, which deletes the target's live spawns (previously it cleared the list and left the spawns orphaned) and is a no-op when source == target (previously that wiped the source).
- `RemoveEntry` with an entry the spawner does not own is now a no-op (previously it deleted that entry's spawns).
- `Respawn()` honours `Disabled` because it calls `Spawn()`; `Spawn(int index)`, `RemoveSpawn`, and `RemoveSpawns` ignore it.
- Copying entries between spawners no longer forces a 1-second first spawn; the target re-arms on its normal delay.
- Subclasses that own a different entry list than `Spawner`'s must call `RebuildSpawned()` from their own `[AfterDeserialization]` (`Spawner`'s call runs before their list is read) and, when converting adopted entries into their own type, carry live spawns across with `TransferSpawned`. The in-repo test subclass demonstrates both.

### Performance

Manual harness (`Benchmark_SpawnPath_Manual`, skipped by default): 100k calls, entries all full so `Spawn()` does selection only.

| Path | Before (4bad0cc9e) | After |
|---|---|---|
| `Spawn()` 1 entry | 48.7 ns | 53.2 ns (within run-to-run noise) |
| `Spawn()` 10 entries | 243.7 ns | 153.1 ns |
| `Spawn()` 50 entries | 1077.6 ns | 645.1 ns |
| `Remove()` 10 entries | 139.6 ns | 83.6 ns |

Hooks are no-ops for stock spawners; `OnMovement` is untouched.

### Tests

- `SpawnerEntryOwnershipTests` (add/remove/clear, start after stop, dupe, copy, self-copy, foreign-entry removal, Disabled binary/JSON)
- `SpawnerHookTests` (hook order for mobiles and items, veto, death notification, `NextSpawn` start, a subclass with its own `List<TestEntry>` round-tripping and duping)
- `SpawnerSaveMigrationTests` (v12 fixtures through `Spawner`, `ProximitySpawner`, `RegionSpawner`; new-format byte-identical round trip with a live spawn reference)
- `SpawnerDtoEntryTests` (compact JSON position of `entries`, `disabled` only when set, import adopts the deserialized objects)
- Existing DTO/JSON/spawn-data tests unchanged. UOContent.Tests 801 passed, Server.Tests 869 passed. Migration schemas regenerated (`BaseSpawner.v13`, `Spawner.v2`, `SpawnerEntry.v2`).

Coverage caveats, stated plainly: v10, v11 and the pre-codegen legacy reader could not be captured as fixtures by the current code; each changed only `_entries = …` → `AdoptEntries(…)` into the same sink the v12 fixtures exercise, and is covered by review. The captured v12 fixtures carry no live spawns, so re-linking live `ISpawnable` references is proven by the new-format round trip, not by a legacy blob. The `SpawnerGump` toggle layout could not be checked in a client; the delete button moved from x=38 to x=46 to make room.
2026-09-11 17:41:08 -07:00

240 lines
7.6 KiB
C#

/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SpawnerDto.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;
using System.Collections.Generic;
using System.Text.Json.Serialization;
using Server.Json;
using Server.Regions;
namespace Server.Engines.Spawners;
/// <summary>
/// Plain data carrier for spawner JSON. STJ deserializes into these records (never a live Item),
/// so a malformed file fails as GC only; <see cref="ToSpawner"/> builds the spawner from a
/// validated DTO. Options use <c>WhenWritingDefault</c>; mandatory fields force-write via
/// <c>[JsonIgnore(Condition = Never)]</c> and <c>[JsonPropertyOrder]</c> sets the on-disk order.
/// </summary>
public abstract record SpawnerDto
{
// Mandatory: always written.
[JsonPropertyName("guid")]
[JsonPropertyOrder(0)]
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public Guid Guid { get; init; }
[JsonPropertyName("name")]
[JsonPropertyOrder(1)]
public string Name { get; init; }
[JsonPropertyName("location")]
[JsonPropertyOrder(2)]
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
[JsonConverter(typeof(Point3DArrayConverter))]
public Point3D Location { get; init; }
[JsonPropertyName("map")]
[JsonPropertyOrder(3)]
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public Map Map { get; init; }
[JsonPropertyName("count")]
[JsonPropertyOrder(4)]
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public int Count { get; init; }
[JsonPropertyName("minDelay")]
[JsonPropertyOrder(5)]
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public TimeSpan MinDelay { get; init; }
[JsonPropertyName("maxDelay")]
[JsonPropertyOrder(6)]
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public TimeSpan MaxDelay { get; init; }
// Optional: omitted at default (spawnBounds/region live on the subtypes at order 8).
[JsonPropertyName("team")]
[JsonPropertyOrder(7)]
public int Team { get; init; }
[JsonPropertyName("walkingRange")]
[JsonPropertyOrder(9)]
public int WalkingRange { get; init; }
[JsonPropertyName("spawnLocationIsHome")]
[JsonPropertyOrder(11)]
public bool SpawnLocationIsHome { get; init; }
[JsonPropertyName("spawnPositionMode")]
[JsonPropertyOrder(12)]
public SpawnPositionMode SpawnPositionMode { get; init; }
[JsonPropertyName("maxSpawnAttempts")]
[JsonPropertyOrder(13)]
public int MaxSpawnAttempts { get; init; }
// Compact square-bounds form, -1 when absent. Written only when >= 0 (ShouldSerialize, since 0
// is a valid radius WhenWritingDefault cannot emit); reconstructs SpawnBounds in ApplyDto.
[JsonPropertyName("homeRange")]
[JsonPropertyOrder(8)]
public int HomeRange { get; init; } = -1;
/// <summary>The entries carried by the concrete record, in its own entry type. Never serialized directly.</summary>
[JsonIgnore]
public abstract IReadOnlyList<SpawnerEntry> EntryView { get; }
/// <summary>Constructs the empty concrete spawner Item for this DTO.</summary>
protected abstract BaseSpawner CreateEmpty();
/// <summary>Builds and populates the live spawner. Override to apply subtype fields after base.</summary>
public virtual BaseSpawner ToSpawner()
{
var spawner = CreateEmpty();
try
{
spawner.ApplyDto(this);
return spawner;
}
catch
{
// CreateEmpty registered the Item; delete it if population throws so no orphan escapes.
spawner.Delete();
throw;
}
}
}
[JsonDiscoverableType("Spawner")]
public sealed record SpawnerDataDto : SpawnerDto
{
[JsonPropertyName("spawnBounds")]
[JsonPropertyOrder(8)]
public Rectangle3D SpawnBounds { get; init; }
[JsonPropertyName("entries")]
[JsonPropertyOrder(10)]
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public List<SpawnerEntry> Entries { get; init; }
[JsonIgnore]
public override IReadOnlyList<SpawnerEntry> EntryView => Entries;
protected override BaseSpawner CreateEmpty() => new Spawner();
public override BaseSpawner ToSpawner()
{
var spawner = (Spawner)base.ToSpawner();
try
{
if (SpawnBounds != default)
{
spawner.SpawnBounds = SpawnBounds;
}
return spawner;
}
catch
{
spawner.Delete();
throw;
}
}
}
[JsonDiscoverableType("RegionSpawner")]
public sealed record RegionSpawnerDto : SpawnerDto
{
[JsonPropertyName("region")]
[JsonPropertyOrder(8)]
public string Region { get; init; }
[JsonPropertyName("entries")]
[JsonPropertyOrder(10)]
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public List<SpawnerEntry> Entries { get; init; }
[JsonIgnore]
public override IReadOnlyList<SpawnerEntry> EntryView => Entries;
protected override BaseSpawner CreateEmpty() => new RegionSpawner();
public override BaseSpawner ToSpawner()
{
var spawner = (RegionSpawner)base.ToSpawner();
try
{
spawner.SpawnRegion = Server.Region.Find(Region, Map) as BaseRegion;
return spawner;
}
catch
{
spawner.Delete();
throw;
}
}
}
[JsonDiscoverableType("ProximitySpawner")]
public sealed record ProximitySpawnerDto : SpawnerDto
{
[JsonPropertyName("spawnBounds")]
[JsonPropertyOrder(8)]
public Rectangle3D SpawnBounds { get; init; }
[JsonPropertyName("triggerRange")]
[JsonPropertyOrder(14)]
public int TriggerRange { get; init; }
[JsonPropertyName("spawnMessage")]
[JsonPropertyOrder(15)]
public TextDefinition SpawnMessage { get; init; }
[JsonPropertyName("instant")]
[JsonPropertyOrder(16)]
public bool Instant { get; init; }
[JsonPropertyName("entries")]
[JsonPropertyOrder(10)]
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public List<SpawnerEntry> Entries { get; init; }
[JsonIgnore]
public override IReadOnlyList<SpawnerEntry> EntryView => Entries;
protected override BaseSpawner CreateEmpty() => new ProximitySpawner();
public override BaseSpawner ToSpawner()
{
var spawner = (ProximitySpawner)base.ToSpawner();
try
{
if (SpawnBounds != default)
{
spawner.SpawnBounds = SpawnBounds;
}
spawner.TriggerRange = TriggerRange;
spawner.SpawnMessage = SpawnMessage;
spawner.InstantFlag = Instant;
return spawner;
}
catch
{
spawner.Delete();
throw;
}
}
}