refactor(spawners): replace DynamicJson with typed SpawnerDto records (#2505)

## Summary

Removes the dated `DynamicJson` JSON helper and migrates spawner JSON (de)serialization to a polymorphic `record SpawnerDto` hierarchy. `DynamicJson` was the last remaining consumer (regions moved off it in #1400).

The key correctness improvement: **System.Text.Json deserializes plain DTO records, never a live `Item`.** Previously, deserializing directly into an `Item` meant STJ constructed world-registered objects *before* the data was validated — a malformed/hand-edited spawn file could leave orphaned spawner Items in the world save. Now a parse failure is GC-only; `dto.ToSpawner()` constructs the spawner only from a fully-validated DTO and self-cleans on failure.

## What changed

- **New:** `SpawnerDto` (abstract) + `SpawnerDataDto` / `RegionSpawnerDto` / `ProximitySpawnerDto`, each marked with a reusable `[JsonDiscoverableType]` opt-in attribute. Auto-discovered at the `Configure` phase — no manual registration list (avoids the regions `Register<T>()` footgun), open to custom spawner subtypes.
- **Symmetric mapping:** `BaseSpawner.ToDto()` (export) ⇄ `SpawnerDto.ToSpawner()` (import). `ToSpawner()` deletes-and-rethrows on any failure, so the importer can never orphan an Item.
- **`SpawnerJsonSerializer`** wires `$type` polymorphism on the `SpawnerDto` root with loud collision/constructibility validation.
- **Import/export commands** rewired to the typed DTO path (reflection `FindTypeByName`/`CreateInstance` removed).
- **Data migration:** the 109 `Distribution/Data/Spawns/**` files moved from `"type"`→`"$type"` and legacy `homeRange`→`spawnBounds`. The runtime still *reads* legacy `homeRange` for external files. The `homeRange→spawnBounds` formula is proven equivalent to the runtime conversion (`BoundsEquivalenceTests`, hr=0/1/3/7).
- **Deleted:** `Projects/Server/Json/DynamicJson.cs`.

Sparse export output matches the legacy `ToJson` (nullable DTO properties + `WhenWritingNull`). Binary world-save serialization is untouched.

## Tests

- DTO round-trip per spawner type; sparse-default omission; legacy `homeRange` read; export/import file round-trip.
- `Import_MalformedFile_LeaksNoWorldItems` — proves a mid-array parse failure constructs zero world Items.
- `AllSpawnFilesLoadTests` — every migrated spawn file deserializes and builds.
- Duplicate-discriminator validation.
- UOContent.Tests 485/485, Server.Tests 710/710, build clean.

## Follow-up (not in this PR)

`Rectangle3DConverter.Write` (in `Projects/Server/`) omits `z1/z2` when `Start.Z == -128`, so a future server-side export of a `homeRange`-style spawner round-trips depth 256→255. Pre-existing and out of scope here (Server change); the migrated data reads correctly. Worth a separate small converter PR.
This commit is contained in:
Kamron Batman 2026-06-25 23:24:45 -07:00 • committed by GitHub
parent a26219c837
commit d8a64f3316
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
135 changed files with 7654 additions and 6079 deletions

View file

@ -0,0 +1,117 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: BaseSpawner.Dto.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.Engines.Spawners;
public abstract partial class BaseSpawner
{
/// <summary>Applies the common DTO fields to this freshly-created spawner (import path).</summary>
internal void ApplyDto(SpawnerDto dto)
{
_guid = dto.Guid == Guid.Empty ? Guid.NewGuid() : dto.Guid;
if (!string.IsNullOrEmpty(dto.Name))
{
Name = dto.Name;
}
// Compact homeRange -> spawnBounds (Map not available yet; use the DTO location).
if (dto.HomeRange >= 0)
{
SpawnBounds = BoundsFromHomeRange(dto.Location, dto.HomeRange);
}
InitSpawn(dto.Count, dto.MinDelay, dto.MaxDelay, dto.Team, SpawnBounds);
_walkingRange = dto.WalkingRange;
_spawnLocationIsHome = dto.SpawnLocationIsHome;
_spawnPositionMode = dto.SpawnPositionMode;
_maxSpawnAttempts = dto.MaxSpawnAttempts;
if (dto.Entries != null)
{
for (var i = 0; i < dto.Entries.Count; i++)
{
var entry = dto.Entries[i];
AddEntry(entry.SpawnedName, entry.SpawnedProbability, entry.SpawnedMaxCount, false, entry.Properties, entry.Parameters);
}
}
}
/// <summary>The square spawn bounds a homeRange radius represents (centered on the location).</summary>
private protected static Rectangle3D BoundsFromHomeRange(Point3D location, int homeRange)
{
int z;
int depth;
if (homeRange == 0)
{
z = location.Z;
depth = 0;
}
else
{
z = -128;
depth = 256;
}
return new Rectangle3D(
location.X - homeRange,
location.Y - homeRange,
z,
homeRange * 2 + 1,
homeRange * 2 + 1,
depth
);
}
private protected string DtoName
{
get
{
var name = Name;
return string.IsNullOrEmpty(name) || name == DefaultName ? null : name;
}
}
// ToDto helpers for values whose export form differs from the public property. (Guid/MinDelay/
// MaxDelay/Team/SpawnLocationIsHome match their property and are referenced directly in ToDto.)
// Raw field; the public WalkingRange is computed (falls back to HomeRange).
private protected int DtoWalkingRange => _walkingRange;
// Abandoned is a transient runtime state, not persisted -> map to Automatic (omitted).
private protected SpawnPositionMode DtoSpawnPositionMode =>
_spawnPositionMode == SpawnPositionMode.Abandoned ? SpawnPositionMode.Automatic : _spawnPositionMode;
// Runtime treats 0 as DefaultMaxSpawnAttempts -> map the default to 0 (omitted).
private protected int DtoMaxSpawnAttempts => _maxSpawnAttempts == DefaultMaxSpawnAttempts ? 0 : _maxSpawnAttempts;
// The radius if SpawnBounds is exactly what it reconstructs (lossless square); otherwise -1.
private protected int DtoHomeRange
{
get
{
if (SpawnBounds == default || !IsHomeRangeStyle)
{
return -1;
}
var homeRange = HomeRange;
return SpawnBounds == BoundsFromHomeRange(Location, homeRange) ? homeRange : -1;
}
}
}

View file

@ -1,12 +1,10 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.Json;
using ModernUO.Serialization;
using Server.Commands;
using Server.Gumps;
using Server.Items;
using Server.Json;
using Server.Logging;
using Server.Mobiles;
using static Server.Attributes;
@ -120,6 +118,9 @@ public abstract partial class BaseSpawner : Item, ISpawner
[CommandProperty(AccessLevel.Developer)]
public abstract Rectangle3D SpawnBounds { get; set; }
/// <summary>Builds the JSON DTO for this spawner (export path).</summary>
public abstract SpawnerDto ToDto();
/// <summary>
/// If true, the home location of the spawn is the location where it spawned
/// If false, the home location of the spawn is the location of the spawner
@ -294,67 +295,6 @@ public abstract partial class BaseSpawner : Item, ISpawner
}
}
public BaseSpawner(DynamicJson json, JsonSerializerOptions options) : base(0x1f13)
{
if (!json.GetProperty("guid", options, out _guid))
{
_guid = Guid.NewGuid();
}
if (json.GetProperty("name", options, out string name))
{
Name = name;
}
json.GetProperty("count", options, out int amount);
json.GetProperty("minDelay", options, DefaultMinDelay, out TimeSpan minDelay);
json.GetProperty("maxDelay", options, DefaultMaxDelay, out TimeSpan maxDelay);
json.GetProperty("team", options, out int team);
json.GetProperty("homeRange", options, -1, out int homeRange);
json.GetProperty("walkingRange", options, out _walkingRange);
// Handle legacy homeRange format (new spawnBounds format handled by derived classes)
if (homeRange >= 0 && json.GetProperty("location", options, out Point3D location))
{
int z;
int depth;
if (homeRange == 0)
{
z = location.Z;
depth = 0;
}
else
{
z = -128;
depth = 256;
}
// Fall back to homeRange with location for oldest format
// Note: Map not available during JSON loading, so use location.Z directly
SpawnBounds = new Rectangle3D(
location.X - homeRange,
location.Y - homeRange,
z,
homeRange * 2 + 1,
homeRange * 2 + 1,
depth
);
}
json.GetProperty("spawnLocationIsHome", options, out _spawnLocationIsHome);
json.GetProperty("spawnPositionMode", options, out _spawnPositionMode);
json.GetProperty("maxSpawnAttempts", options, DefaultMaxSpawnAttempts, out _maxSpawnAttempts);
InitSpawn(amount, minDelay, maxDelay, team, SpawnBounds);
json.GetProperty("entries", options, out List<SpawnerEntry> entries);
foreach (var entry in entries)
{
AddEntry(entry.SpawnedName, entry.SpawnedProbability, entry.SpawnedMaxCount, false, entry.Properties, entry.Parameters);
}
}
public override string DefaultName => "Spawner";
public bool IsFull => Spawned?.Count >= _count;
public bool IsEmpty => Spawned?.Count == 0;
@ -493,59 +433,6 @@ public abstract partial class BaseSpawner : Item, ISpawner
RemoveSpawns();
}
public virtual void ToJson(DynamicJson json, JsonSerializerOptions options)
{
json.Type = GetType().Name;
// Always required
json.SetProperty("guid", options, _guid);
json.SetProperty("location", options, Location);
json.SetProperty("map", options, Map);
json.SetProperty("count", options, Count);
json.SetProperty("entries", options, Entries);
// Only write if non-default
if (!string.IsNullOrEmpty(Name))
{
json.SetProperty("name", options, Name);
}
if (_minDelay != DefaultMinDelay)
{
json.SetProperty("minDelay", options, MinDelay);
}
if (_maxDelay != DefaultMaxDelay)
{
json.SetProperty("maxDelay", options, MaxDelay);
}
if (_team != 0)
{
json.SetProperty("team", options, Team);
}
if (_walkingRange != 0)
{
json.SetProperty("walkingRange", options, WalkingRange);
}
if (_spawnLocationIsHome)
{
json.SetProperty("spawnLocationIsHome", options, SpawnLocationIsHome);
}
if (_spawnPositionMode is not SpawnPositionMode.Automatic and not SpawnPositionMode.Abandoned)
{
json.SetProperty("spawnPositionMode", options, _spawnPositionMode);
}
if (_maxSpawnAttempts != DefaultMaxSpawnAttempts)
{
json.SetProperty("maxSpawnAttempts", options, _maxSpawnAttempts);
}
}
public virtual Point3D GetSpawnPosition(ISpawnable spawned, Map map)
{
// Abandoned spawners skip all work

View file

@ -17,7 +17,6 @@ using System;
using System.Collections.Generic;
using System.IO;
using Server.Commands.Generic;
using Server.Json;
using Server.Network;
namespace Server.Engines.Spawners;
@ -66,9 +65,7 @@ public class ExportSpawnersCommand : BaseCommand
NetState.FlushAll();
var options = JsonConfig.GetOptions(new TextDefinitionConverterFactory());
var spawnRecords = new List<DynamicJson>(list.Count);
var spawnRecords = new List<SpawnerDto>(list.Count);
for (var i = 0; i < list.Count; i++)
{
// Not a spawner, not on a valid map, or is in a container
@ -85,9 +82,7 @@ public class ExportSpawnersCommand : BaseCommand
continue;
}
var dynamicJson = DynamicJson.Create(spawner.GetType());
spawner.ToJson(dynamicJson, options);
spawnRecords.Add(dynamicJson);
spawnRecords.Add(spawner.ToDto());
}
if (spawnRecords.Count == 0)
@ -98,7 +93,9 @@ public class ExportSpawnersCommand : BaseCommand
e.Mobile.SendMessage("Exporting spawners...");
JsonConfig.Serialize(path, spawnRecords, options);
// Compact layout (UTF-8, no BOM, LF) keeps re-exports diff-friendly.
PathUtility.EnsureDirectory(Path.GetDirectoryName(path));
File.WriteAllText(path, SpawnerJsonSerializer.SerializeCompact(spawnRecords));
e.Mobile.SendMessage($"Spawners exported to {path}");
}

View file

@ -190,6 +190,15 @@ public static class ImportSpawnersCommand
}
}
// Test seam: wraps ImportJsonSpawners without requiring a live Mobile (from = null is safe
// because from is only used in the JsonException path, which won't be hit for valid files).
internal static void ImportFile(FileInfo file, Dictionary<Guid, ISpawner> allSpawners)
{
var generated = 0;
var failures = 0;
ImportJsonSpawners(null, file, allSpawners, ref generated, ref failures);
}
private static void ImportJsonSpawners(
Mobile from,
FileInfo file,
@ -198,78 +207,89 @@ public static class ImportSpawnersCommand
ref int totalFailures
)
{
var options = JsonConfig.GetOptions();
List<SpawnerDto> dtos;
try
{
var spawners = JsonConfig.Deserialize<List<DynamicJson>>(file.FullName);
if (spawners == null || spawners.Count == 0)
{
from.SendMessage($"GenerateSpawners: Skipping empty spawner file {file.Name}");
logger.Information("{User} is skipping empty spawner file {File}", from, file.FullName);
return;
}
using var queue = PooledRefQueue<Item>.Create();
for (var i = 0; i < spawners.Count; i++)
{
var json = spawners[i];
var type = AssemblyHandler.FindTypeByName(json.Type);
if (type == null || !typeof(BaseSpawner).IsAssignableFrom(type))
{
logger.Error($"Invalid spawner type {json.Type ?? "(-null-)"} ({i}).");
totalFailures++;
continue;
}
json.GetProperty("location", options, out Point3D location);
json.GetProperty("map", options, out Map map);
// Delete all spawners at this location.
// Probably shouldn't do this outside of migrations? Is there a better way to find/fix spawners?
foreach (var spawner in map.GetItemsAt<BaseSpawner>(location))
{
if (spawner.GetType() == type)
{
queue.Enqueue(spawner);
allSpawners.Remove(spawner.Guid);
}
}
while (queue.Count > 0)
{
queue.Dequeue().Delete();
}
try
{
var spawner = type.CreateInstance<ISpawner>(json, options);
spawner!.MoveToWorld(location, map);
spawner!.Respawn();
if (allSpawners.Remove(spawner.Guid, out var oldSpawner))
{
oldSpawner.Delete();
}
allSpawners.Add(spawner.Guid, spawner);
totalGenerated++;
}
catch (Exception ex)
{
json.GetProperty("guid", options, out Guid guid);
TraceException(ex, $"Failed to generate spawner {guid}.");
totalFailures++;
}
}
// DTO deserialization constructs NO world objects — a malformed file fails as GC only.
dtos = JsonConfig.Deserialize<List<SpawnerDto>>(file.FullName, SpawnerJsonSerializer.Options);
}
catch (JsonException)
{
from.SendMessage(
from?.SendMessage(
$"GenerateSpawners: Exception parsing {file.FullName}, file may not be in the correct format."
);
return;
}
if (dtos == null || dtos.Count == 0)
{
from?.SendMessage($"GenerateSpawners: Skipping empty spawner file {file.Name}");
logger.Information("{User} is skipping empty spawner file {File}", from, file.FullName);
return;
}
using var queue = PooledRefQueue<Item>.Create();
for (var i = 0; i < dtos.Count; i++)
{
var dto = dtos[i];
var location = dto.Location;
var map = dto.Map;
if (map == null || map == Map.Internal)
{
logger.Error("Spawner {Guid} ({Index}) has no valid map; skipping.", dto.Guid, i);
totalFailures++;
continue;
}
BaseSpawner spawner;
try
{
spawner = dto.ToSpawner(); // constructs the single Item, now referenced
}
catch (Exception ex)
{
TraceException(ex, $"Failed to build spawner {dto.Guid}.");
totalFailures++;
continue;
}
var type = spawner.GetType();
// Delete all existing spawners of the same concrete type at this location.
foreach (var existing in map.GetItemsAt<BaseSpawner>(location))
{
if (existing.GetType() == type && existing != spawner)
{
queue.Enqueue(existing);
allSpawners.Remove(existing.Guid);
}
}
while (queue.Count > 0)
{
queue.Dequeue().Delete();
}
try
{
spawner.MoveToWorld(location, map);
spawner.Respawn();
if (allSpawners.Remove(spawner.Guid, out var oldSpawner))
{
oldSpawner.Delete();
}
allSpawners.Add(spawner.Guid, spawner);
totalGenerated++;
}
catch (Exception ex)
{
TraceException(ex, $"Failed to generate spawner {spawner.Guid}.");
spawner.Delete();
totalFailures++;
}
}
}

View file

@ -0,0 +1,43 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Point3DArrayConverter.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.Text.Json;
using System.Text.Json.Serialization;
using Server.Json;
namespace Server.Engines.Spawners;
/// <summary>
/// Writes a <see cref="Point3D"/> as the compact array form <c>[x, y, z]</c> used by the spawn
/// files (the default <see cref="Point3DConverter"/> writes an object). Reading delegates to the
/// default converter, so array/object/string inputs all still load.
/// </summary>
public sealed class Point3DArrayConverter : JsonConverter<Point3D>
{
private static readonly Point3DConverter _inner = new();
public override Point3D Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
_inner.Read(ref reader, typeToConvert, options);
public override void Write(Utf8JsonWriter writer, Point3D value, JsonSerializerOptions options)
{
writer.WriteStartArray();
writer.WriteNumberValue(value.X);
writer.WriteNumberValue(value.Y);
writer.WriteNumberValue(value.Z);
writer.WriteEndArray();
}
}

View file

@ -0,0 +1,217 @@
/*************************************************************************
* 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("entries")]
[JsonPropertyOrder(10)]
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public List<SpawnerEntry> Entries { 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>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; }
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; }
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; }
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;
}
}
}

View file

@ -0,0 +1,45 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ProximitySpawner.Dto.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/>. *
*************************************************************************/
namespace Server.Engines.Spawners;
public partial class ProximitySpawner
{
public override SpawnerDto ToDto()
{
var homeRange = DtoHomeRange;
return new ProximitySpawnerDto
{
Guid = Guid,
Name = DtoName,
Location = Location,
Map = Map,
Count = Count,
MinDelay = MinDelay,
MaxDelay = MaxDelay,
Team = Team,
WalkingRange = DtoWalkingRange,
Entries = Entries,
SpawnLocationIsHome = SpawnLocationIsHome,
SpawnPositionMode = DtoSpawnPositionMode,
MaxSpawnAttempts = DtoMaxSpawnAttempts,
HomeRange = homeRange,
SpawnBounds = homeRange >= 0 ? default : SpawnBounds,
TriggerRange = TriggerRange,
SpawnMessage = SpawnMessage,
Instant = InstantFlag
};
}
}

View file

@ -14,9 +14,7 @@
*************************************************************************/
using System;
using System.Text.Json;
using ModernUO.Serialization;
using Server.Json;
using Server.Mobiles;
namespace Server.Engines.Spawners;
@ -64,29 +62,10 @@ public partial class ProximitySpawner : Spawner
InstantFlag = instantFlag;
}
public ProximitySpawner(DynamicJson json, JsonSerializerOptions options) : base(json, options)
{
json.GetProperty("triggerRange", options, out int triggerRange);
json.GetProperty("spawnMessage", options, out TextDefinition spawnMessage);
json.GetProperty("instant", options, out bool instant);
TriggerRange = triggerRange;
SpawnMessage = spawnMessage;
InstantFlag = instant;
}
public override string DefaultName => "Proximity Spawner";
public override bool HandlesOnMovement => Running;
public override void ToJson(DynamicJson json, JsonSerializerOptions options)
{
base.ToJson(json, options);
json.SetProperty("triggerRange", options, TriggerRange);
json.SetProperty("spawnMessage", options, SpawnMessage);
json.SetProperty("instant", options, InstantFlag);
}
public override void DoTimer(TimeSpan delay)
{
if (!Running)

View file

@ -0,0 +1,38 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: RegionSpawner.Dto.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/>. *
*************************************************************************/
namespace Server.Engines.Spawners;
public partial class RegionSpawner
{
// RegionSpawner spawns from region rectangles, so it writes neither homeRange nor spawnBounds.
public override SpawnerDto ToDto() => new RegionSpawnerDto
{
Guid = Guid,
Name = DtoName,
Location = Location,
Map = Map,
Count = Count,
MinDelay = MinDelay,
MaxDelay = MaxDelay,
Team = Team,
WalkingRange = DtoWalkingRange,
Entries = Entries,
SpawnLocationIsHome = SpawnLocationIsHome,
SpawnPositionMode = DtoSpawnPositionMode,
MaxSpawnAttempts = DtoMaxSpawnAttempts,
Region = SpawnRegion?.Name
};
}

View file

@ -14,9 +14,7 @@
*************************************************************************/
using System;
using System.Text.Json;
using ModernUO.Serialization;
using Server.Json;
using Server.Regions;
namespace Server.Engines.Spawners;
@ -52,15 +50,6 @@ public partial class RegionSpawner : Spawner
{
}
public RegionSpawner(DynamicJson json, JsonSerializerOptions options) : base(json, options)
{
json.GetProperty("map", options, out Map map);
json.GetProperty("region", options, out string spawnRegion);
_spawnRegion = Region.Find(spawnRegion, map) as BaseRegion;
_spawnRegion?.InitRectangles();
}
[CommandProperty(AccessLevel.Developer)]
public BaseRegion SpawnRegion
{
@ -116,12 +105,6 @@ public partial class RegionSpawner : Spawner
return base.GetSpawnPosition(spawned, map);
}
public override void ToJson(DynamicJson json, JsonSerializerOptions options)
{
base.ToJson(json, options);
json.SetProperty("region", options, SpawnRegion.Name);
}
public override void GetSpawnerProperties(IPropertyList list)
{
base.GetSpawnerProperties(list);

View file

@ -0,0 +1,42 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Spawner.Dto.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/>. *
*************************************************************************/
namespace Server.Engines.Spawners;
public partial class Spawner
{
public override SpawnerDto ToDto()
{
var homeRange = DtoHomeRange;
return new SpawnerDataDto
{
Guid = Guid,
Name = DtoName,
Location = Location,
Map = Map,
Count = Count,
MinDelay = MinDelay,
MaxDelay = MaxDelay,
Team = Team,
WalkingRange = DtoWalkingRange,
Entries = Entries,
SpawnLocationIsHome = SpawnLocationIsHome,
SpawnPositionMode = DtoSpawnPositionMode,
MaxSpawnAttempts = DtoMaxSpawnAttempts,
HomeRange = homeRange,
SpawnBounds = homeRange >= 0 ? default : SpawnBounds
};
}
}

View file

@ -1,7 +1,5 @@
using System;
using System.Text.Json;
using ModernUO.Serialization;
using Server.Json;
namespace Server.Engines.Spawners;
@ -57,25 +55,6 @@ public partial class Spawner : BaseSpawner
{
}
public Spawner(DynamicJson json, JsonSerializerOptions options) : base(json, options)
{
// Read spawnBounds (not in BaseSpawner to allow RegionSpawner to skip it)
if (json.GetProperty("spawnBounds", options, out Rectangle3D spawnBounds))
{
SpawnBounds = spawnBounds;
}
}
public override void ToJson(DynamicJson json, JsonSerializerOptions options)
{
base.ToJson(json, options);
if (SpawnBounds != default)
{
json.SetProperty("spawnBounds", options, SpawnBounds);
}
}
public override Region Region => Region.Find(Location, Map);
protected override bool SupportsSpiralScan => _useSpiralScan;

View file

@ -0,0 +1,346 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SpawnerJsonSerializer.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.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using Server.Json;
using Server.Logging;
using Server.Text;
namespace Server.Engines.Spawners;
public static class SpawnerJsonSerializer
{
private static readonly ILogger logger = LogFactory.GetLogger(typeof(SpawnerJsonSerializer));
private static JsonDerivedType[] _derivedTypes;
private static JsonSerializerOptions _options;
/// <summary>
/// Invoked automatically during the Configure bootstrap phase
/// (AssemblyHandler.Invoke("Configure")). Discovers every concrete SpawnerDto subclass
/// marked with [JsonDiscoverableType] and registers it for STJ polymorphism.
/// </summary>
public static void Configure()
{
var discovered = new List<JsonDerivedType>();
var byDiscriminator = new Dictionary<string, Type>();
foreach (var asm in AssemblyHandler.Assemblies)
{
Collect(AssemblyHandler.GetTypeCache(asm).Types, discovered, byDiscriminator);
}
Collect(AssemblyHandler.GetTypeCache(Core.Assembly).Types, discovered, byDiscriminator);
_derivedTypes = discovered.ToArray();
_options = null; // force rebuild with the discovered types
logger.Information("Discovered {Count} spawner JSON type(s)", _derivedTypes.Length);
}
private static void Collect(Type[] types, List<JsonDerivedType> discovered, Dictionary<string, Type> byDiscriminator)
{
for (var i = 0; i < types.Length; i++)
{
var type = types[i];
if (type.IsAbstract || !type.IsAssignableTo(typeof(SpawnerDto)))
{
continue;
}
var attr = (JsonDiscoverableTypeAttribute)Attribute.GetCustomAttribute(
type, typeof(JsonDiscoverableTypeAttribute), false);
if (attr == null)
{
continue;
}
var (discriminator, derived) = Validate(type, byDiscriminator);
byDiscriminator[discriminator] = type;
discovered.Add(derived);
}
}
internal static (string discriminator, JsonDerivedType derived) Validate(
Type type, Dictionary<string, Type> byDiscriminator)
{
if (!IsJsonConstructible(type))
{
throw new Exception(
$"SpawnerDto type '{type.FullName}' is marked [JsonDiscoverableType] but System.Text.Json cannot construct it. " +
"Add a public parameterless constructor or use a record with init-only properties."
);
}
var attr = (JsonDiscoverableTypeAttribute)Attribute.GetCustomAttribute(
type, typeof(JsonDiscoverableTypeAttribute), false);
var discriminator = attr?.Discriminator ?? type.Name;
if (byDiscriminator.TryGetValue(discriminator, out var existing))
{
throw new Exception(
$"Spawner JSON discriminator '{discriminator}' is claimed by both '{existing.FullName}' and " +
$"'{type.FullName}'. Set an explicit discriminator via [JsonDiscoverableType(\"...\")] on one."
);
}
return (discriminator, new JsonDerivedType(type, discriminator));
}
private static bool IsJsonConstructible(Type type)
{
foreach (var ctor in type.GetConstructors())
{
if (ctor.GetParameters().Length == 0)
{
return true;
}
if (Attribute.IsDefined(ctor, typeof(JsonConstructorAttribute)))
{
return true;
}
}
return false;
}
public static JsonSerializerOptions Options =>
_options ??= new JsonSerializerOptions(JsonConfig.GetOptions())
{
// Optional fields omit at default; mandatory ones force-write via [JsonIgnore(Never)].
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers =
{
AddPolymorphism,
ConfigureHomeRange
}
}
};
private static void AddPolymorphism(JsonTypeInfo typeInfo)
{
if (typeInfo.Type != typeof(SpawnerDto))
{
return;
}
typeInfo.PolymorphismOptions = new JsonPolymorphismOptions();
for (var i = 0; i < _derivedTypes.Length; i++)
{
typeInfo.PolymorphismOptions.DerivedTypes.Add(_derivedTypes[i]);
}
}
// homeRange writes only when >= 0 (0 is a valid radius WhenWritingDefault could not emit).
private static void ConfigureHomeRange(JsonTypeInfo typeInfo)
{
if (!typeInfo.Type.IsAssignableTo(typeof(SpawnerDto)))
{
return;
}
for (var i = 0; i < typeInfo.Properties.Count; i++)
{
if (typeInfo.Properties[i].Name == "homeRange")
{
typeInfo.Properties[i].ShouldSerialize = static (_, value) => value is int hr && hr >= 0;
}
}
}
// --- Compact writer (matches the on-disk spawn-file layout used by [ExportSpawners) ---
private const int CompactPrintWidth = 125;
private static readonly JsonSerializerOptions _scalarOptions = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
/// <summary>
/// Serializes to the compact spawn-file layout: a container is inline only when all its values
/// are scalars and the line fits within 125 characters; otherwise it expands (2-space indent).
/// UTF-8, LF. Admin/cold path.
/// </summary>
public static string SerializeCompact<T>(T value)
{
var node = JsonSerializer.SerializeToNode(value, Options);
var sb = ValueStringBuilder.Create();
try
{
WriteNode(node, ref sb, 0, 0);
sb.Append("\n");
return sb.ToString();
}
finally
{
sb.Dispose();
}
}
private static void WriteNode(JsonNode node, ref ValueStringBuilder sb, int indent, int column)
{
if (node is not JsonArray and not JsonObject)
{
sb.Append(node?.ToJsonString(_scalarOptions) ?? "null");
return;
}
if (AllScalarChildren(node))
{
var inline = Inline(node);
if (column + inline.Length <= CompactPrintWidth)
{
sb.Append(inline);
return;
}
}
var childIndent = indent + 1;
var childColumn = childIndent * 2;
if (node is JsonArray arr)
{
sb.Append("[\n");
for (var i = 0; i < arr.Count; i++)
{
sb.Append(' ', childColumn);
WriteNode(arr[i], ref sb, childIndent, childColumn);
sb.Append(i < arr.Count - 1 ? ",\n" : "\n");
}
sb.Append(' ', indent * 2);
sb.Append("]");
return;
}
var obj = (JsonObject)node;
sb.Append("{\n");
var index = 0;
var count = obj.Count;
foreach (var pair in obj)
{
sb.Append(' ', childColumn);
var prefix = $"\"{pair.Key}\": ";
sb.Append(prefix);
WriteNode(pair.Value, ref sb, childIndent, childColumn + prefix.Length);
sb.Append(++index < count ? ",\n" : "\n");
}
sb.Append(' ', indent * 2);
sb.Append("}");
}
private static bool AllScalarChildren(JsonNode node)
{
if (node is JsonArray arr)
{
foreach (var element in arr)
{
if (element is JsonArray or JsonObject)
{
return false;
}
}
return true;
}
foreach (var pair in (JsonObject)node)
{
if (pair.Value is JsonArray or JsonObject)
{
return false;
}
}
return true;
}
private static string Inline(JsonNode node)
{
var sb = ValueStringBuilder.Create();
try
{
AppendInline(node, ref sb);
return sb.ToString();
}
finally
{
sb.Dispose();
}
}
private static void AppendInline(JsonNode node, ref ValueStringBuilder sb)
{
switch (node)
{
case JsonArray arr:
{
sb.Append("[");
for (var i = 0; i < arr.Count; i++)
{
if (i > 0)
{
sb.Append(", ");
}
AppendInline(arr[i], ref sb);
}
sb.Append("]");
break;
}
case JsonObject obj:
{
if (obj.Count == 0)
{
sb.Append("{}");
break;
}
sb.Append("{ ");
var first = true;
foreach (var pair in obj)
{
if (!first)
{
sb.Append(", ");
}
first = false;
sb.Append("\"");
sb.Append(pair.Key);
sb.Append("\": ");
AppendInline(pair.Value, ref sb);
}
sb.Append(" }");
break;
}
default:
sb.Append(node?.ToJsonString(_scalarOptions) ?? "null");
break;
}
}
}