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.
This commit is contained in:
parent
75f326bfdd
commit
a52ce6ef70
29 changed files with 1489 additions and 139 deletions
|
|
@ -109,6 +109,8 @@ internal static class TestServerInitializer
|
|||
World.Load();
|
||||
World.ExitSerializationThreads();
|
||||
DecayScheduler.Configure();
|
||||
// Without npc-speeds.json every BaseCreature constructor throws.
|
||||
Server.Mobiles.NPCSpeeds.Configure();
|
||||
Server.Engines.Spawners.SpawnerJsonSerializer.Configure();
|
||||
|
||||
if (TileDataLoaded)
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -11,12 +11,16 @@ public class SpawnerDiscoveryValidationTests
|
|||
[JsonDiscoverableType("dup")]
|
||||
private sealed record DupA : SpawnerDto
|
||||
{
|
||||
public override IReadOnlyList<SpawnerEntry> EntryView => null;
|
||||
|
||||
protected override BaseSpawner CreateEmpty() => new Spawner();
|
||||
}
|
||||
|
||||
[JsonDiscoverableType("dup")]
|
||||
private sealed record DupB : SpawnerDto
|
||||
{
|
||||
public override IReadOnlyList<SpawnerEntry> EntryView => null;
|
||||
|
||||
protected override BaseSpawner CreateEmpty() => new Spawner();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,57 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Server.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners.Json;
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class SpawnerDtoEntryTests
|
||||
{
|
||||
[Fact]
|
||||
public void Export_WritesEntriesAtSameJsonPosition_WithDisabledOnlyWhenSet()
|
||||
{
|
||||
var spawner = new Spawner(1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10), 0, default, "Rabbit", "Bird");
|
||||
spawner.Entries[1].Disabled = true;
|
||||
|
||||
var json = SpawnerJsonSerializer.SerializeCompact(new List<SpawnerDto> { spawner.ToDto() });
|
||||
|
||||
Assert.Contains("\"entries\": [\n { \"name\": \"Rabbit\"", json);
|
||||
Assert.Contains("{ \"name\": \"Bird\"", json);
|
||||
Assert.Equal(1, CountOccurrences(json, "\"disabled\": true"));
|
||||
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Import_AdoptsDeserializedEntryObjects()
|
||||
{
|
||||
var json = """
|
||||
[{"$type":"Spawner","guid":"11111111-1111-1111-1111-111111111111","location":[1500,1500,0],"map":"Felucca","count":1,"minDelay":"00:05:00","maxDelay":"00:10:00","homeRange":4,"entries":[{"name":"Rabbit","probability":100,"maxCount":1,"disabled":true}]}]
|
||||
""";
|
||||
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(json, SpawnerJsonSerializer.Options);
|
||||
var spawner = dtos![0].ToSpawner();
|
||||
|
||||
Assert.Single(spawner.Entries);
|
||||
Assert.True(spawner.Entries[0].Disabled);
|
||||
Assert.Same(dtos[0].EntryView[0], spawner.Entries[0]);
|
||||
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
private static int CountOccurrences(string source, string value)
|
||||
{
|
||||
var count = 0;
|
||||
var index = 0;
|
||||
while ((index = source.IndexOf(value, index, StringComparison.Ordinal)) >= 0)
|
||||
{
|
||||
count++;
|
||||
index += value.Length;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,243 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Server.Tests;
|
||||
using Server.Text;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners;
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class SpawnerEntryOwnershipTests
|
||||
{
|
||||
[Fact]
|
||||
public void Disabled_DefaultsFalse_AndRoundTripsBinary()
|
||||
{
|
||||
var spawner = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit", "Bird");
|
||||
Assert.False(spawner.Entries[0].Disabled);
|
||||
Assert.True(spawner.Entries[0].Enabled);
|
||||
|
||||
spawner.Entries[1].Disabled = true;
|
||||
|
||||
var bytes = SpawnerBlob.Write(spawner);
|
||||
var loaded = SpawnerBlob.Read<Spawner>(bytes, (Serial)0x40001234);
|
||||
|
||||
Assert.Equal(2, loaded.Entries.Count);
|
||||
Assert.False(loaded.Entries[0].Disabled);
|
||||
Assert.True(loaded.Entries[1].Disabled);
|
||||
|
||||
spawner.Delete();
|
||||
loaded.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Disabled_IsOmittedFromJsonWhenFalse_AndWrittenWhenTrue()
|
||||
{
|
||||
var entry = new SpawnerEntry("Rabbit");
|
||||
var json = JsonSerializer.Serialize(entry, SpawnerJsonSerializer.Options);
|
||||
Assert.DoesNotContain("disabled", json);
|
||||
|
||||
entry.Disabled = true;
|
||||
json = JsonSerializer.Serialize(entry, SpawnerJsonSerializer.Options);
|
||||
Assert.Contains("\"disabled\": true", json);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddRemoveClear_OperateOnOwnerList()
|
||||
{
|
||||
var spawner = new Spawner();
|
||||
Assert.Empty(spawner.Entries);
|
||||
|
||||
var a = spawner.AddEntry("Rabbit", 100, 2, false);
|
||||
var b = spawner.AddEntry("Bird", 50, 1, false, "Hue 33", null);
|
||||
Assert.Equal(2, spawner.Entries.Count);
|
||||
Assert.Same(a, spawner.Entries[0]);
|
||||
Assert.Equal("Hue 33", spawner.Entries[1].Properties);
|
||||
|
||||
spawner.RemoveEntry(a);
|
||||
Assert.Single(spawner.Entries);
|
||||
Assert.Same(b, spawner.Entries[0]);
|
||||
|
||||
spawner.RemoveAllEntries();
|
||||
Assert.Empty(spawner.Entries);
|
||||
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Start_WorksAfterStop_WhenOwnerHasEntries()
|
||||
{
|
||||
var spawner = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit");
|
||||
Assert.True(spawner.Running);
|
||||
spawner.Stop();
|
||||
Assert.False(spawner.Running);
|
||||
spawner.Start();
|
||||
Assert.True(spawner.Running);
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dupe_ClonesEntriesIntoIndependentList()
|
||||
{
|
||||
var source = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit", "Bird");
|
||||
source.Entries[1].Disabled = true;
|
||||
|
||||
var copy = new Spawner();
|
||||
source.Dupe(copy);
|
||||
|
||||
Assert.Equal(2, copy.Entries.Count);
|
||||
Assert.NotSame(source.Entries[0], copy.Entries[0]);
|
||||
Assert.Equal("Bird", copy.Entries[1].SpawnedName);
|
||||
Assert.True(copy.Entries[1].Disabled);
|
||||
Assert.NotEqual(source.Guid, copy.Guid);
|
||||
|
||||
source.AddEntry("Orc", 100, 1, false);
|
||||
Assert.Equal(2, copy.Entries.Count);
|
||||
|
||||
source.Delete();
|
||||
copy.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyEntriesTo_ReplacesTargetEntries()
|
||||
{
|
||||
var source = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit");
|
||||
var target = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Orc", "Troll");
|
||||
|
||||
source.CopyEntriesTo(target);
|
||||
|
||||
Assert.Single(target.Entries);
|
||||
Assert.Equal("Rabbit", target.Entries[0].SpawnedName);
|
||||
Assert.NotSame(source.Entries[0], target.Entries[0]);
|
||||
|
||||
source.Delete();
|
||||
target.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyEntriesTo_Self_IsNoOp()
|
||||
{
|
||||
var spawner = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit", "Bird");
|
||||
var first = spawner.Entries[0];
|
||||
var second = spawner.Entries[1];
|
||||
|
||||
spawner.CopyEntriesTo(spawner);
|
||||
|
||||
Assert.Equal(2, spawner.Entries.Count);
|
||||
Assert.Same(first, spawner.Entries[0]);
|
||||
Assert.Same(second, spawner.Entries[1]);
|
||||
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveEntry_ForeignEntry_IsIgnored()
|
||||
{
|
||||
var a = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit");
|
||||
var b = new Spawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Bird");
|
||||
|
||||
var foreign = b.Entries[0];
|
||||
var spawned = new Item(0x1f13);
|
||||
foreign.AddToSpawned(spawned);
|
||||
|
||||
a.RemoveEntry(foreign);
|
||||
|
||||
Assert.Single(a.Entries);
|
||||
Assert.Equal("Rabbit", a.Entries[0].SpawnedName);
|
||||
Assert.Single(b.Entries);
|
||||
Assert.Same(foreign, b.Entries[0]);
|
||||
|
||||
Assert.False(spawned.Deleted);
|
||||
Assert.Single(foreign.Spawned);
|
||||
|
||||
spawned.Delete();
|
||||
a.Delete();
|
||||
b.Delete();
|
||||
}
|
||||
|
||||
// Manual: remove the Skip, run, and read the numbers from the thrown assertion.
|
||||
[Fact(Skip = "manual benchmark")]
|
||||
public void Benchmark_SpawnPath_Manual()
|
||||
{
|
||||
const int iterations = 100_000;
|
||||
const int warmup = 1_000;
|
||||
|
||||
var report = new ValueStringBuilder(stackalloc char[512]);
|
||||
report.Append('\n', 1);
|
||||
|
||||
foreach (var entryCount in new[] { 1, 10, 50 })
|
||||
{
|
||||
var spawner = new Spawner(1000, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10));
|
||||
spawner.MoveToWorld(new Point3D(1500, 1500, 0), Map.Felucca);
|
||||
|
||||
// SpawnedMaxCount = 0 keeps every entry full, so Spawn() does selection only.
|
||||
for (var i = 0; i < entryCount; i++)
|
||||
{
|
||||
spawner.AddEntry("Rabbit", 100, 0, false);
|
||||
}
|
||||
|
||||
for (var i = 0; i < warmup; i++)
|
||||
{
|
||||
spawner.Spawn();
|
||||
}
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
for (var i = 0; i < iterations; i++)
|
||||
{
|
||||
spawner.Spawn();
|
||||
}
|
||||
|
||||
sw.Stop();
|
||||
|
||||
var nsPerCall = sw.Elapsed.TotalMilliseconds * 1_000_000.0 / iterations;
|
||||
report.Append(
|
||||
$"Spawn() entries={entryCount,2}: {nsPerCall,8:F1} ns/call ({iterations} iterations, {sw.ElapsedMilliseconds} ms total)\n"
|
||||
);
|
||||
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
{
|
||||
var spawner = new Spawner(1000, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10));
|
||||
spawner.MoveToWorld(new Point3D(1500, 1500, 0), Map.Felucca);
|
||||
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
spawner.AddEntry("Rabbit", 100, 1, false);
|
||||
}
|
||||
|
||||
spawner.Spawn();
|
||||
Assert.Single(spawner.Spawned);
|
||||
var rabbit = spawner.Spawned.Keys.First();
|
||||
|
||||
for (var i = 0; i < warmup; i++)
|
||||
{
|
||||
spawner.Remove(rabbit);
|
||||
}
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
for (var i = 0; i < iterations; i++)
|
||||
{
|
||||
spawner.Remove(rabbit);
|
||||
}
|
||||
|
||||
sw.Stop();
|
||||
|
||||
var nsPerCall = sw.Elapsed.TotalMilliseconds * 1_000_000.0 / iterations;
|
||||
report.Append(
|
||||
$"Remove(ISpawnable) entries=10: {nsPerCall,8:F1} ns/call ({iterations} iterations, {sw.ElapsedMilliseconds} ms total)\n"
|
||||
);
|
||||
|
||||
(rabbit as Mobile)?.Delete();
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
var summary = report.ToString();
|
||||
report.Dispose();
|
||||
|
||||
throw new Xunit.Sdk.XunitException(summary);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using Server.Engines.Spawners;
|
||||
using Server.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners;
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class SpawnerFixtureCapture
|
||||
{
|
||||
// Freezes the BaseSpawner v12 save layout as test input; refuses to run against newer code.
|
||||
[SkippableFact]
|
||||
public void CaptureLegacyBlobs()
|
||||
{
|
||||
Skip.If(Environment.GetEnvironmentVariable("MODERNUO_CAPTURE_SPAWNER_FIXTURES") != "1");
|
||||
|
||||
var version = (int)typeof(BaseSpawner)
|
||||
.GetField("SerializationVersion", BindingFlags.NonPublic | BindingFlags.Static)!
|
||||
.GetRawConstantValue()!;
|
||||
Assert.True(version == 12, $"Fixtures must be captured with BaseSpawner v12; current version is {version}.");
|
||||
|
||||
var dir = Path.Combine(AppContext.BaseDirectory, "Tests", "Engines", "Spawners", "Fixtures");
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
var spawner = new Spawner(2, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, "Rabbit", "Bird")
|
||||
{
|
||||
Name = "FixtureSpawner"
|
||||
};
|
||||
spawner.Entries[1].Properties = "Hue 33";
|
||||
File.WriteAllBytes(Path.Combine(dir, "spawner.v12-v1.bin"), SpawnerBlob.Write(spawner));
|
||||
|
||||
var proximity = new ProximitySpawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, default, 5, "boo", true, "Rat", "Bird")
|
||||
{
|
||||
Name = "FixtureProximity"
|
||||
};
|
||||
File.WriteAllBytes(Path.Combine(dir, "proximity.v12-v1-v0.bin"), SpawnerBlob.Write(proximity));
|
||||
|
||||
var region = new RegionSpawner(1, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), 0, "Orc", "Troll")
|
||||
{
|
||||
Name = "FixtureRegion"
|
||||
};
|
||||
File.WriteAllBytes(Path.Combine(dir, "region.v12-v1-v0.bin"), SpawnerBlob.Write(region));
|
||||
|
||||
spawner.Delete();
|
||||
proximity.Delete();
|
||||
region.Delete();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,305 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using ModernUO.Serialization;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Server.Mobiles;
|
||||
using Server.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners;
|
||||
|
||||
[SerializationGenerator(0)]
|
||||
public partial class TestEntry : SpawnerEntry
|
||||
{
|
||||
// Dirty tracking is resolved on the declared type, so a derived entry re-declares its owner.
|
||||
[DirtyTrackingEntity]
|
||||
private BaseSpawner Owner => Parent;
|
||||
|
||||
[SerializableField(0)]
|
||||
private string _tag;
|
||||
|
||||
public TestEntry(BaseSpawner parent) : base(parent)
|
||||
{
|
||||
}
|
||||
|
||||
public TestEntry(BaseSpawner parent, string name, int probability, int maxCount, string properties, string parameters)
|
||||
: base(parent, name, probability, maxCount, properties, parameters)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
[SerializationGenerator(0)]
|
||||
public partial class HookRecordingSpawner : Spawner
|
||||
{
|
||||
[SerializedIgnoreDupe]
|
||||
[SerializableField(0)]
|
||||
private List<TestEntry> _testEntries;
|
||||
|
||||
public List<string> Log { get; } = [];
|
||||
public bool VetoNext { get; set; }
|
||||
|
||||
public HookRecordingSpawner()
|
||||
{
|
||||
}
|
||||
|
||||
public HookRecordingSpawner(Serial serial) : base(serial)
|
||||
{
|
||||
}
|
||||
|
||||
public override IReadOnlyList<SpawnerEntry> Entries => _testEntries ?? (IReadOnlyList<SpawnerEntry>)Array.Empty<SpawnerEntry>();
|
||||
|
||||
protected override ReadOnlySpan<SpawnerEntry> EntrySpan =>
|
||||
ReadOnlySpan<SpawnerEntry>.CastUp(CollectionsMarshal.AsSpan(_testEntries));
|
||||
|
||||
protected override SpawnerEntry CreateEntry(string name, int probability, int maxCount, string properties, string parameters) =>
|
||||
new TestEntry(this, name, probability, maxCount, properties, parameters) { Tag = "made" };
|
||||
|
||||
protected override void AddEntryCore(SpawnerEntry entry)
|
||||
{
|
||||
TestEntries ??= [];
|
||||
AddToTestEntries((TestEntry)entry);
|
||||
}
|
||||
|
||||
protected override bool RemoveEntryCore(SpawnerEntry entry)
|
||||
{
|
||||
if (entry is not TestEntry te || _testEntries?.Contains(te) != true)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
RemoveFromTestEntries(te);
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override void ClearEntriesCore()
|
||||
{
|
||||
if (_testEntries?.Count > 0)
|
||||
{
|
||||
ClearTestEntries();
|
||||
}
|
||||
}
|
||||
|
||||
protected override void AdoptEntries(IReadOnlyList<SpawnerEntry> entries)
|
||||
{
|
||||
ClearEntriesCore();
|
||||
for (var i = 0; i < entries.Count; i++)
|
||||
{
|
||||
var e = entries[i];
|
||||
TestEntry te;
|
||||
if (e is TestEntry existing)
|
||||
{
|
||||
te = existing;
|
||||
}
|
||||
else
|
||||
{
|
||||
te = (TestEntry)CloneEntry(e);
|
||||
TransferSpawned(e, te);
|
||||
}
|
||||
|
||||
te.SetParent(this);
|
||||
AddEntryCore(te);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Test hook: adopt entries built elsewhere, exercising the conversion path.</summary>
|
||||
public void AdoptForTest(IReadOnlyList<SpawnerEntry> entries) => AdoptEntries(entries);
|
||||
|
||||
/// <summary>Test hook: rebuild the Spawned registry without a full save round trip.</summary>
|
||||
public void RebuildSpawnedForTest() => RebuildSpawned();
|
||||
|
||||
// Spawner's rebuild runs before _testEntries is read; rebuild again here.
|
||||
[AfterDeserialization]
|
||||
private void AfterDeserialization() => RebuildSpawned();
|
||||
|
||||
protected override SpawnerEntry CloneEntry(SpawnerEntry source)
|
||||
{
|
||||
var clone = (TestEntry)base.CloneEntry(source);
|
||||
clone.Tag = (source as TestEntry)?.Tag ?? clone.Tag;
|
||||
return clone;
|
||||
}
|
||||
|
||||
protected override void OnStarted() => Log.Add("started");
|
||||
protected override void OnStopped() => Log.Add("stopped");
|
||||
|
||||
protected override bool OnBeforeSpawn(SpawnerEntry entry)
|
||||
{
|
||||
Log.Add($"before:{entry.SpawnedName}");
|
||||
if (VetoNext)
|
||||
{
|
||||
VetoNext = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override void OnConfigureSpawned(SpawnerEntry entry, ISpawnable spawned) => Log.Add($"configure:{entry.SpawnedName}");
|
||||
|
||||
protected override Point3D GetSpawnPosition(SpawnerEntry entry, ISpawnable spawned, Map map)
|
||||
{
|
||||
Log.Add($"position:{entry.SpawnedName}");
|
||||
return Location;
|
||||
}
|
||||
|
||||
protected override void OnSpawned(SpawnerEntry entry, ISpawnable spawned) => Log.Add($"spawned:{entry.SpawnedName}");
|
||||
|
||||
protected override void OnSpawnedDeath(SpawnerEntry entry, ISpawnable spawned, Mobile killer) =>
|
||||
Log.Add($"death:{entry.SpawnedName}:{killer?.Name ?? "none"}");
|
||||
}
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class SpawnerHookTests
|
||||
{
|
||||
private static HookRecordingSpawner Place()
|
||||
{
|
||||
var spawner = new HookRecordingSpawner();
|
||||
spawner.InitSpawn(1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10));
|
||||
spawner.MoveToWorld(new Point3D(1500, 1500, 0), Map.Felucca);
|
||||
return spawner;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Hooks_FireInOrder_OnSpawnAndStartStop()
|
||||
{
|
||||
var spawner = Place();
|
||||
spawner.AddEntry("Rabbit", 100, 1, false);
|
||||
spawner.Log.Clear();
|
||||
|
||||
spawner.Stop();
|
||||
spawner.Start();
|
||||
spawner.Spawn();
|
||||
|
||||
Assert.Equal(
|
||||
["stopped", "started", "before:Rabbit", "configure:Rabbit", "position:Rabbit", "spawned:Rabbit"],
|
||||
spawner.Log
|
||||
);
|
||||
Assert.Single(spawner.Spawned);
|
||||
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Hooks_FireForItemEntries()
|
||||
{
|
||||
var spawner = Place();
|
||||
spawner.AddEntry("Gold", 100, 1, false);
|
||||
spawner.Log.Clear();
|
||||
|
||||
spawner.Spawn();
|
||||
|
||||
Assert.Equal(
|
||||
["before:Gold", "configure:Gold", "position:Gold", "spawned:Gold"],
|
||||
spawner.Log
|
||||
);
|
||||
Assert.IsAssignableFrom<Item>(Assert.Single(spawner.Spawned).Key);
|
||||
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NextSpawn_OnStoppedSpawner_FiresOnStarted()
|
||||
{
|
||||
var spawner = Place();
|
||||
spawner.AddEntry("Rabbit", 100, 1, false);
|
||||
spawner.Stop();
|
||||
spawner.Log.Clear();
|
||||
|
||||
spawner.NextSpawn = TimeSpan.FromSeconds(5);
|
||||
|
||||
Assert.True(spawner.Running);
|
||||
Assert.Equal(["started"], spawner.Log);
|
||||
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnBeforeSpawn_CanVeto()
|
||||
{
|
||||
var spawner = Place();
|
||||
spawner.AddEntry("Rabbit", 100, 1, false);
|
||||
spawner.VetoNext = true;
|
||||
|
||||
spawner.Spawn();
|
||||
|
||||
Assert.Empty(spawner.Spawned);
|
||||
Assert.Contains("before:Rabbit", spawner.Log);
|
||||
Assert.DoesNotContain("spawned:Rabbit", spawner.Log);
|
||||
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Death_NotifiesOwningSpawner_BeforeUnlink()
|
||||
{
|
||||
var spawner = Place();
|
||||
spawner.AddEntry("Rabbit", 100, 1, false);
|
||||
spawner.Spawn();
|
||||
var rabbit = Assert.Single(spawner.Spawned).Key as BaseCreature;
|
||||
Assert.NotNull(rabbit);
|
||||
|
||||
var killer = new PlayerMobile { Name = "Hunter" };
|
||||
rabbit.LastKiller = killer;
|
||||
rabbit.Kill();
|
||||
|
||||
Assert.Contains("death:Rabbit:Hunter", spawner.Log);
|
||||
|
||||
killer.Delete();
|
||||
spawner.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OwnEntryType_SurvivesBinaryRoundTripAndDupe()
|
||||
{
|
||||
var spawner = Place();
|
||||
spawner.AddEntry("Rabbit", 100, 1, false);
|
||||
((TestEntry)spawner.Entries[0]).Tag = "kept";
|
||||
spawner.Spawn();
|
||||
Assert.Single(spawner.Spawned);
|
||||
|
||||
var loaded = SpawnerBlob.Read<HookRecordingSpawner>(SpawnerBlob.Write(spawner), (Serial)0x40009999);
|
||||
Assert.Equal("kept", ((TestEntry)loaded.Entries[0]).Tag);
|
||||
|
||||
Assert.Single(loaded.Entries[0].Spawned);
|
||||
Assert.Single(loaded.Spawned);
|
||||
|
||||
var copy = new HookRecordingSpawner();
|
||||
spawner.Dupe(copy);
|
||||
Assert.Equal("kept", ((TestEntry)copy.Entries[0]).Tag);
|
||||
Assert.Empty(copy.Entries[0].Spawned);
|
||||
|
||||
spawner.Delete();
|
||||
loaded.Delete();
|
||||
copy.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AdoptEntries_ConvertsForeignEntries_KeepingLiveSpawns()
|
||||
{
|
||||
var source = new Spawner();
|
||||
source.InitSpawn(1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10));
|
||||
source.MoveToWorld(new Point3D(1502, 1502, 0), Map.Felucca);
|
||||
source.AddEntry("Rabbit", 100, 1, false);
|
||||
source.Spawn();
|
||||
var rabbit = Assert.Single(source.Spawned).Key;
|
||||
|
||||
var adopter = Place();
|
||||
adopter.AdoptForTest(source.Entries);
|
||||
|
||||
var adopted = Assert.Single(adopter.Entries);
|
||||
Assert.IsType<TestEntry>(adopted);
|
||||
Assert.Equal("Rabbit", adopted.SpawnedName);
|
||||
Assert.Same(rabbit, Assert.Single(adopted.Spawned));
|
||||
Assert.Empty(source.Entries[0].Spawned);
|
||||
|
||||
adopter.RebuildSpawnedForTest();
|
||||
Assert.Same(rabbit, Assert.Single(adopter.Spawned).Key);
|
||||
|
||||
source.Delete();
|
||||
Assert.False(rabbit.Deleted);
|
||||
|
||||
adopter.Delete();
|
||||
Assert.True(rabbit.Deleted);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Server.Items;
|
||||
using Server.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners;
|
||||
|
||||
internal static class SpawnerBlob
|
||||
{
|
||||
public static byte[] Write(Item item)
|
||||
{
|
||||
var writer = new BufferWriter(true);
|
||||
item.Serialize(writer);
|
||||
return writer.Buffer[..(int)writer.Position];
|
||||
}
|
||||
|
||||
public static T Read<T>(byte[] bytes, Serial serial) where T : Item
|
||||
{
|
||||
var item = (T)Activator.CreateInstance(typeof(T), serial)!;
|
||||
var reader = new BufferReader(bytes);
|
||||
item.Deserialize(reader);
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class SpawnerSaveMigrationTests
|
||||
{
|
||||
private static byte[] Fixture(string name) =>
|
||||
File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Tests", "Engines", "Spawners", "Fixtures", name));
|
||||
|
||||
[Fact]
|
||||
public void V12Spawner_EntriesAreAdoptedByOwner()
|
||||
{
|
||||
var loaded = SpawnerBlob.Read<Spawner>(Fixture("spawner.v12-v1.bin"), (Serial)0x40001001);
|
||||
|
||||
Assert.Equal("FixtureSpawner", loaded.Name);
|
||||
Assert.Equal(2, loaded.Entries.Count);
|
||||
Assert.Equal("Rabbit", loaded.Entries[0].SpawnedName);
|
||||
Assert.Equal("Hue 33", loaded.Entries[1].Properties);
|
||||
Assert.False(loaded.Entries[0].Disabled);
|
||||
Assert.NotNull(loaded.Spawned);
|
||||
Assert.Empty(loaded.Spawned);
|
||||
|
||||
loaded.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void V12ProximityAndRegion_EntriesAreAdoptedThroughSubclasses()
|
||||
{
|
||||
var prox = SpawnerBlob.Read<ProximitySpawner>(Fixture("proximity.v12-v1-v0.bin"), (Serial)0x40001002);
|
||||
Assert.Equal(2, prox.Entries.Count);
|
||||
Assert.Equal("Rat", prox.Entries[0].SpawnedName);
|
||||
Assert.Equal("Bird", prox.Entries[1].SpawnedName);
|
||||
Assert.Equal(5, prox.TriggerRange);
|
||||
Assert.True(prox.InstantFlag);
|
||||
|
||||
var region = SpawnerBlob.Read<RegionSpawner>(Fixture("region.v12-v1-v0.bin"), (Serial)0x40001003);
|
||||
Assert.Equal(2, region.Entries.Count);
|
||||
Assert.Equal("Orc", region.Entries[0].SpawnedName);
|
||||
Assert.Equal("Troll", region.Entries[1].SpawnedName);
|
||||
|
||||
prox.Delete();
|
||||
region.Delete();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NewFormat_RoundTripsByteIdentical_WithLiveSpawnReferences()
|
||||
{
|
||||
var spawner = new Spawner(1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10), 0, default, "Rabbit");
|
||||
spawner.MoveToWorld(new Point3D(1500, 1500, 0), Map.Felucca);
|
||||
spawner.Spawn();
|
||||
Assert.Single(spawner.Spawned);
|
||||
|
||||
var first = SpawnerBlob.Write(spawner);
|
||||
var loaded = SpawnerBlob.Read<Spawner>(first, (Serial)0x40001004);
|
||||
Assert.Single(loaded.Entries);
|
||||
Assert.Single(loaded.Entries[0].Spawned);
|
||||
Assert.Single(loaded.Spawned);
|
||||
|
||||
var second = SpawnerBlob.Write(loaded);
|
||||
Assert.Equal(first, second);
|
||||
|
||||
loaded.Delete();
|
||||
spawner.Delete();
|
||||
}
|
||||
}
|
||||
|
|
@ -11,11 +11,16 @@
|
|||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="xunit.SkippableFact" Version="1.5.61" />
|
||||
<PackageReference Include="ModernUO.Serialization.Generator" Version="4.1.0" PrivateAssets="all" />
|
||||
<ProjectReference Include="..\Server\Server.csproj" />
|
||||
<ProjectReference Include="..\UOContent\UOContent.csproj" />
|
||||
<ProjectReference Include="..\Server.Tests\Server.Tests.csproj" />
|
||||
<DataFiles Include="$(SolutionDir)\Distribution\Data\**" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="Tests/Engines/Spawners/Fixtures/*.bin" CopyToOutputDirectory="PreserveNewest" />
|
||||
<AdditionalFiles Include="Migrations/*.v*.json" />
|
||||
</ItemGroup>
|
||||
<Target Name="CopyData" AfterTargets="AfterBuild">
|
||||
<Copy SourceFiles="@(DataFiles)" DestinationFolder="$(OutDir)\Data\%(RecursiveDir)" />
|
||||
</Target>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue