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:
parent
a26219c837
commit
d8a64f3316
135 changed files with 7654 additions and 6079 deletions
|
|
@ -0,0 +1,30 @@
|
|||
using Server.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace Server.Tests.Json;
|
||||
|
||||
public class JsonDiscoverableTypeAttributeTests
|
||||
{
|
||||
[JsonDiscoverableType]
|
||||
private sealed class DefaultName { }
|
||||
|
||||
[JsonDiscoverableType("custom")]
|
||||
private sealed class Overridden { }
|
||||
|
||||
[Fact]
|
||||
public void DefaultDiscriminator_IsNull()
|
||||
{
|
||||
var attr = (JsonDiscoverableTypeAttribute)System.Attribute.GetCustomAttribute(
|
||||
typeof(DefaultName), typeof(JsonDiscoverableTypeAttribute), false);
|
||||
Assert.NotNull(attr);
|
||||
Assert.Null(attr.Discriminator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OverrideDiscriminator_IsReturned()
|
||||
{
|
||||
var attr = (JsonDiscoverableTypeAttribute)System.Attribute.GetCustomAttribute(
|
||||
typeof(Overridden), typeof(JsonDiscoverableTypeAttribute), false);
|
||||
Assert.Equal("custom", attr.Discriminator);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
/*************************************************************************
|
||||
* ModernUO *
|
||||
* Copyright 2019-2026 - ModernUO Development Team *
|
||||
* Email: hi@modernuo.com *
|
||||
* File: DynamicJson.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.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Server.Json;
|
||||
|
||||
public class DynamicJson
|
||||
{
|
||||
public static DynamicJson Create(Type type) => new()
|
||||
{
|
||||
Type = type.Name,
|
||||
Data = new Dictionary<string, JsonElement>()
|
||||
};
|
||||
|
||||
[JsonPropertyName("type")]
|
||||
public string Type { get; set; }
|
||||
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement> Data { get; set; }
|
||||
|
||||
// TODO: Use JSON Node in .NET 6
|
||||
public void SetProperty<T>(string key, JsonSerializerOptions options, T value)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(JsonSerializer.SerializeToUtf8Bytes(value, options));
|
||||
Data[key] = doc.RootElement.Clone();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public bool GetProperty<T>(string key, JsonSerializerOptions options, out T t) =>
|
||||
GetProperty(key, options, default, out t);
|
||||
|
||||
public bool GetProperty<T>(string key, JsonSerializerOptions options, T defaultT, out T t)
|
||||
{
|
||||
if (Data.TryGetValue(key, out var el))
|
||||
{
|
||||
t = el.ToObject<T>(options);
|
||||
return true;
|
||||
}
|
||||
|
||||
t = defaultT;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool GetEnumProperty<T>(string key, JsonSerializerOptions options, out T t) where T : struct, Enum
|
||||
{
|
||||
if (Data.TryGetValue(key, out var el))
|
||||
{
|
||||
return Enum.TryParse(el.ToObject<string>(options), out t);
|
||||
}
|
||||
|
||||
t = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
32
Projects/Server/Json/JsonDiscoverableTypeAttribute.cs
Normal file
32
Projects/Server/Json/JsonDiscoverableTypeAttribute.cs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
/*************************************************************************
|
||||
* ModernUO *
|
||||
* Copyright 2019-2026 - ModernUO Development Team *
|
||||
* Email: hi@modernuo.com *
|
||||
* File: JsonDiscoverableTypeAttribute.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.Json;
|
||||
|
||||
/// <summary>
|
||||
/// Marks a concrete class as a discoverable polymorphic JSON derived type. A consumer
|
||||
/// (e.g. <c>SpawnerJsonSerializer</c>) scans assemblies for marked subclasses of a chosen
|
||||
/// base and registers them for System.Text.Json polymorphism. Optionally overrides the
|
||||
/// <c>$type</c> discriminator value (defaults to the type's <see cref="System.Type.Name"/>).
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
|
||||
public sealed class JsonDiscoverableTypeAttribute : Attribute
|
||||
{
|
||||
public JsonDiscoverableTypeAttribute(string discriminator = null) => Discriminator = discriminator;
|
||||
|
||||
public string Discriminator { get; }
|
||||
}
|
||||
|
|
@ -84,6 +84,7 @@ internal static class TestServerInitializer
|
|||
World.Load();
|
||||
World.ExitSerializationThreads();
|
||||
DecayScheduler.Configure();
|
||||
Server.Engines.Spawners.SpawnerJsonSerializer.Configure();
|
||||
|
||||
VerifyTrammelTileDataLoaded();
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,72 @@
|
|||
// Regression test: verifies that EVERY migrated spawn file deserializes and builds spawners.
|
||||
// This catches any migration defects where a spawn file is syntactically correct JSON
|
||||
// but fails to build spawners via DTO.ToSpawner(). Any failure names the offending file
|
||||
// and is a real migration defect, not a test weakness.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners.Json;
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class AllSpawnFilesLoadTests
|
||||
{
|
||||
[Fact]
|
||||
public void EverySpawnFile_DeserializesAndBuildsSpawners()
|
||||
{
|
||||
var root = Path.Combine(Core.BaseDirectory, "Data", "Spawns");
|
||||
if (!Directory.Exists(root))
|
||||
{
|
||||
return; // distribution data not present in this checkout
|
||||
}
|
||||
|
||||
var failures = new List<string>();
|
||||
var fileCount = 0;
|
||||
var spawnerCount = 0;
|
||||
|
||||
foreach (var file in Directory.EnumerateFiles(root, "*.json", SearchOption.AllDirectories))
|
||||
{
|
||||
fileCount++;
|
||||
try
|
||||
{
|
||||
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(
|
||||
File.ReadAllText(file), SpawnerJsonSerializer.Options);
|
||||
|
||||
if (dtos != null)
|
||||
{
|
||||
foreach (var dto in dtos)
|
||||
{
|
||||
try
|
||||
{
|
||||
var spawner = dto.ToSpawner();
|
||||
spawnerCount++;
|
||||
spawner?.Delete();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failures.Add($"{file}: ToSpawner failed: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
failures.Add($"{file}: JSON deserialization failed: {ex.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failures.Add($"{file}: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(
|
||||
failures.Count == 0,
|
||||
$"Loaded {fileCount} files, built {spawnerCount} spawners. Failures:\n{string.Join("\n", failures)}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
// Validates that the spawnBounds JSON emitted by tools/spawner-json-migrate/migrate.mjs
|
||||
// deserializes to the SAME Rectangle3D that the runtime homeRange path produces.
|
||||
// This test MUST pass before bulk-migrating the spawn data files.
|
||||
//
|
||||
// toBounds formula (from migrate.mjs):
|
||||
// hr == 0 -> { x1:x, y1:y, z1:z, x2:x+1, y2:y+1, z2:z }
|
||||
// hr > 0 -> { x1:x-hr, y1:y-hr, z1:-128, x2:x+hr+1, y2:y+hr+1, z2:128 }
|
||||
//
|
||||
// Rectangle3DConverter x1/y1/z1/x2/y2/z2 form creates Rectangle3D(Point3D(x1,y1,z1), Point3D(x2,y2,z2))
|
||||
// where _start==(x1,y1,z1) and _end==(x2,y2,z2). Rectangle3D.End is exclusive.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners.Json;
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class BoundsEquivalenceTests
|
||||
{
|
||||
private const int LocX = 100;
|
||||
private const int LocY = 200;
|
||||
private const int LocZ = 5;
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(1)]
|
||||
[InlineData(3)]
|
||||
[InlineData(7)]
|
||||
public void SpawnBoundsJson_EqualsHomeRangePath(int hr)
|
||||
{
|
||||
BaseSpawner fromHomeRange = null;
|
||||
BaseSpawner fromSpawnBounds = null;
|
||||
try
|
||||
{
|
||||
// Path A: legacy homeRange field -> ApplyDto sets SpawnBounds
|
||||
var homeRangeJson = BuildHomeRangeJson(hr);
|
||||
var dtosA = JsonSerializer.Deserialize<List<SpawnerDto>>(homeRangeJson, SpawnerJsonSerializer.Options);
|
||||
fromHomeRange = Assert.Single(dtosA).ToSpawner();
|
||||
var expected = Assert.IsType<Spawner>(fromHomeRange).SpawnBounds;
|
||||
|
||||
// Path B: migrated spawnBounds field -> SpawnerDataDto.ToSpawner sets SpawnBounds
|
||||
var spawnBoundsJson = BuildSpawnBoundsJson(hr);
|
||||
var dtosB = JsonSerializer.Deserialize<List<SpawnerDto>>(spawnBoundsJson, SpawnerJsonSerializer.Options);
|
||||
fromSpawnBounds = Assert.Single(dtosB).ToSpawner();
|
||||
var actual = Assert.IsType<Spawner>(fromSpawnBounds).SpawnBounds;
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
finally
|
||||
{
|
||||
fromHomeRange?.Delete();
|
||||
fromSpawnBounds?.Delete();
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildHomeRangeJson(int hr) => $$"""
|
||||
[
|
||||
{
|
||||
"$type": "Spawner",
|
||||
"location": [{{LocX}}, {{LocY}}, {{LocZ}}],
|
||||
"map": "Felucca",
|
||||
"count": 1,
|
||||
"homeRange": {{hr}},
|
||||
"entries": []
|
||||
}
|
||||
]
|
||||
""";
|
||||
|
||||
private static string BuildSpawnBoundsJson(int hr)
|
||||
{
|
||||
int x1, y1, z1, x2, y2, z2;
|
||||
if (hr == 0)
|
||||
{
|
||||
// hr==0: _start=(x,y,z), _end=(x+1,y+1,z) — single tile, depth 0
|
||||
(x1, y1, z1, x2, y2, z2) = (LocX, LocY, LocZ, LocX + 1, LocY + 1, LocZ);
|
||||
}
|
||||
else
|
||||
{
|
||||
// hr>0: _start=(x-hr,y-hr,-128), _end=(x+hr+1,y+hr+1,128) — hr*2+1 wide, depth 256
|
||||
(x1, y1, z1, x2, y2, z2) = (LocX - hr, LocY - hr, -128, LocX + hr + 1, LocY + hr + 1, 128);
|
||||
}
|
||||
|
||||
return $$"""
|
||||
[
|
||||
{
|
||||
"$type": "Spawner",
|
||||
"location": [{{LocX}}, {{LocY}}, {{LocZ}}],
|
||||
"map": "Felucca",
|
||||
"count": 1,
|
||||
"spawnBounds": { "x1": {{x1}}, "y1": {{y1}}, "z1": {{z1}}, "x2": {{x2}}, "y2": {{y2}}, "z2": {{z2}} },
|
||||
"entries": []
|
||||
}
|
||||
]
|
||||
""";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Server.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners.Json;
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class ExportImportFileTests
|
||||
{
|
||||
[Fact]
|
||||
public void Serialize_ThenDeserialize_File_PreservesSpawner()
|
||||
{
|
||||
Spawner original = null;
|
||||
BaseSpawner rebuilt = null;
|
||||
var path = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
original = new Spawner(3, TimeSpan.FromMinutes(4), TimeSpan.FromMinutes(8), 1,
|
||||
new Rectangle3D(200, 200, 0, 9, 9, 0), "Tanner");
|
||||
original.MoveToWorld(new Point3D(204, 204, 0), Map.Felucca);
|
||||
|
||||
JsonConfig.Serialize(path, new List<SpawnerDto> { original.ToDto() }, SpawnerJsonSerializer.Options);
|
||||
|
||||
var dtos = JsonConfig.Deserialize<List<SpawnerDto>>(path, SpawnerJsonSerializer.Options);
|
||||
rebuilt = Assert.Single(dtos).ToSpawner();
|
||||
var s = Assert.IsType<Spawner>(rebuilt);
|
||||
Assert.Equal(3, s.Count);
|
||||
Assert.Equal(1, s.Team);
|
||||
Assert.Equal(new Rectangle3D(200, 200, 0, 9, 9, 0), s.SpawnBounds);
|
||||
}
|
||||
finally
|
||||
{
|
||||
rebuilt?.Delete();
|
||||
original?.Delete();
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,200 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners.Json;
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class ImportCleanupTests
|
||||
{
|
||||
private const string SpawnerGuid = "11111111-1111-1111-1111-111111111111";
|
||||
|
||||
[Fact]
|
||||
public void Import_ValidFile_PlacesSpawner()
|
||||
{
|
||||
var dir = Path.Combine(Path.GetTempPath(), "muo-spawner-import-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(dir);
|
||||
var path = Path.Combine(dir, "test.json");
|
||||
File.WriteAllText(path, """
|
||||
[
|
||||
{
|
||||
"$type": "Spawner",
|
||||
"guid": "11111111-1111-1111-1111-111111111111",
|
||||
"location": [305, 305, 0],
|
||||
"map": "Felucca",
|
||||
"count": 1,
|
||||
"spawnBounds": { "x1": 300, "y1": 300, "x2": 310, "y2": 310 },
|
||||
"entries": []
|
||||
}
|
||||
]
|
||||
""");
|
||||
|
||||
BaseSpawner placedSpawner = null;
|
||||
try
|
||||
{
|
||||
var all = new Dictionary<Guid, ISpawner>();
|
||||
ImportSpawnersCommand.ImportFile(new FileInfo(path), all);
|
||||
|
||||
foreach (var s in Map.Felucca.GetItemsAt<BaseSpawner>(new Point3D(305, 305, 0)))
|
||||
{
|
||||
if (s.Guid == new Guid(SpawnerGuid))
|
||||
{
|
||||
placedSpawner = s;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.NotNull(placedSpawner);
|
||||
Assert.True(all.ContainsKey(new Guid(SpawnerGuid)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
placedSpawner?.Delete();
|
||||
if (Directory.Exists(dir))
|
||||
{
|
||||
Directory.Delete(dir, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Import_NoMap_DeletesOrphanedSpawner()
|
||||
{
|
||||
// A spawner with no map entry deserialized by STJ will have map == null (or Map.Internal).
|
||||
// Verify it does NOT end up on any live map.
|
||||
var dir = Path.Combine(Path.GetTempPath(), "muo-spawner-import-nomap-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(dir);
|
||||
var path = Path.Combine(dir, "test-nomap.json");
|
||||
File.WriteAllText(path, """
|
||||
[
|
||||
{
|
||||
"$type": "Spawner",
|
||||
"guid": "22222222-2222-2222-2222-222222222222",
|
||||
"location": [400, 400, 0],
|
||||
"count": 1,
|
||||
"spawnBounds": { "x1": 395, "y1": 395, "x2": 405, "y2": 405 },
|
||||
"entries": []
|
||||
}
|
||||
]
|
||||
""");
|
||||
|
||||
try
|
||||
{
|
||||
var all = new Dictionary<Guid, ISpawner>();
|
||||
ImportSpawnersCommand.ImportFile(new FileInfo(path), all);
|
||||
|
||||
// The spawner must NOT be in allSpawners (rejected due to missing map).
|
||||
Assert.DoesNotContain(new Guid("22222222-2222-2222-2222-222222222222"), all.Keys);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(dir))
|
||||
{
|
||||
Directory.Delete(dir, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Import_MalformedFile_LeaksNoWorldItems()
|
||||
{
|
||||
// First entry is syntactically valid JSON for a Spawner, second entry is truncated/garbage.
|
||||
// STJ throws a JsonException during array deserialization before any Items are created
|
||||
// (the DTO path is GC-only), so zero new spawners should appear at the valid entry's location.
|
||||
var dir = Path.Combine(Path.GetTempPath(), "muo-import-malformed-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(Path.Combine(dir, "bad.json"), """
|
||||
[ { "$type": "Spawner", "location": [320, 320, 0], "map": "Felucca", "count": 1,
|
||||
"entries": [ { "name": "Fisherman", "maxCount": 1, "probability": 100 } ] },
|
||||
{ "$type": "Spawner", "location": [ THIS IS NOT JSON
|
||||
""");
|
||||
try
|
||||
{
|
||||
var before = CountSpawnersNear(new Point3D(320, 320, 0));
|
||||
ImportSpawnersCommand.ImportFile(new FileInfo(Path.Combine(dir, "bad.json")), new Dictionary<Guid, ISpawner>());
|
||||
// Malformed parse must construct zero Items (DTO is GC-only); nothing placed or orphaned.
|
||||
Assert.Equal(before, CountSpawnersNear(new Point3D(320, 320, 0)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(dir, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static int CountSpawnersNear(Point3D p)
|
||||
{
|
||||
var n = 0;
|
||||
foreach (var _ in Map.Felucca.GetItemsAt<BaseSpawner>(p))
|
||||
{
|
||||
n++;
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Import_DuplicateLocation_ReplacesExistingSpawner()
|
||||
{
|
||||
// Verifies that an existing spawner at the same location and type is removed and replaced.
|
||||
var dir = Path.Combine(Path.GetTempPath(), "muo-spawner-import-dup-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(dir);
|
||||
var path = Path.Combine(dir, "test-dup.json");
|
||||
|
||||
var newGuid = new Guid("33333333-3333-3333-3333-333333333333");
|
||||
// Use a non-interpolated raw string literal; the guid is a known constant so hardcode it.
|
||||
File.WriteAllText(path, """
|
||||
[
|
||||
{
|
||||
"$type": "Spawner",
|
||||
"guid": "33333333-3333-3333-3333-333333333333",
|
||||
"location": [310, 310, 0],
|
||||
"map": "Felucca",
|
||||
"count": 1,
|
||||
"spawnBounds": { "x1": 305, "y1": 305, "x2": 315, "y2": 315 },
|
||||
"entries": []
|
||||
}
|
||||
]
|
||||
""");
|
||||
|
||||
// Place a pre-existing spawner at the same location.
|
||||
var existing = new Spawner(1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10));
|
||||
existing.MoveToWorld(new Point3D(310, 310, 0), Map.Felucca);
|
||||
|
||||
BaseSpawner placedSpawner = null;
|
||||
try
|
||||
{
|
||||
var all = new Dictionary<Guid, ISpawner> { [existing.Guid] = existing };
|
||||
ImportSpawnersCommand.ImportFile(new FileInfo(path), all);
|
||||
|
||||
// existing should have been deleted and replaced.
|
||||
Assert.True(existing.Deleted);
|
||||
Assert.DoesNotContain(existing.Guid, all.Keys);
|
||||
|
||||
foreach (var s in Map.Felucca.GetItemsAt<BaseSpawner>(new Point3D(310, 310, 0)))
|
||||
{
|
||||
if (s.Guid == newGuid)
|
||||
{
|
||||
placedSpawner = s;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.NotNull(placedSpawner);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!existing.Deleted)
|
||||
{
|
||||
existing.Delete();
|
||||
}
|
||||
placedSpawner?.Delete();
|
||||
if (Directory.Exists(dir))
|
||||
{
|
||||
Directory.Delete(dir, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners.Json;
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class LegacyHomeRangeTests
|
||||
{
|
||||
[Fact]
|
||||
public void HomeRange_NoSpawnBounds_ProducesCenteredBounds()
|
||||
{
|
||||
const string legacy = """
|
||||
[
|
||||
{
|
||||
"$type": "Spawner",
|
||||
"guid": "3df0543a-373c-4673-a98b-8191686f4ab3",
|
||||
"location": [100, 200, 5],
|
||||
"map": "Felucca",
|
||||
"count": 1,
|
||||
"homeRange": 3,
|
||||
"entries": [ { "name": "Fisherman", "maxCount": 1, "probability": 100 } ]
|
||||
}
|
||||
]
|
||||
""";
|
||||
|
||||
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(legacy, SpawnerJsonSerializer.Options);
|
||||
var dto = Assert.Single(dtos);
|
||||
var s = Assert.IsType<Spawner>(dto.ToSpawner());
|
||||
|
||||
try
|
||||
{
|
||||
// homeRange 3 -> Rectangle3D(100-3, 200-3, -128, 7, 7, 256)
|
||||
Assert.Equal(new Rectangle3D(97, 197, -128, 7, 7, 256), s.SpawnBounds);
|
||||
}
|
||||
finally
|
||||
{
|
||||
s.Delete();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HomeRangeZero_ProducesSingleTileBounds()
|
||||
{
|
||||
const string legacy = """
|
||||
[
|
||||
{
|
||||
"$type": "Spawner",
|
||||
"location": [100, 200, 5],
|
||||
"map": "Felucca",
|
||||
"count": 1,
|
||||
"homeRange": 0,
|
||||
"entries": [ { "name": "Fisherman", "maxCount": 1, "probability": 100 } ]
|
||||
}
|
||||
]
|
||||
""";
|
||||
|
||||
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(legacy, SpawnerJsonSerializer.Options);
|
||||
var dto = Assert.Single(dtos);
|
||||
var s = Assert.IsType<Spawner>(dto.ToSpawner());
|
||||
|
||||
try
|
||||
{
|
||||
// homeRange 0 -> Rectangle3D(100, 200, 5, 1, 1, 0)
|
||||
Assert.Equal(new Rectangle3D(100, 200, 5, 1, 1, 0), s.SpawnBounds);
|
||||
}
|
||||
finally
|
||||
{
|
||||
s.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
// Regression guard: verifies that a real migrated spawn file (post-uoml/felucca/Vendors.json)
|
||||
// can be deserialized as List<SpawnerDto> and each DTO produces a valid spawner via ToSpawner().
|
||||
// Exercises the $type discriminator path introduced by the data migration.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners.Json;
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class MigratedDataLoadTests
|
||||
{
|
||||
[Fact]
|
||||
public void MigratedFile_LoadsWithDollarType()
|
||||
{
|
||||
var path = Path.Combine(Core.BaseDirectory, "Data", "Spawns", "post-uoml", "felucca", "Vendors.json");
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return; // distribution data not present in this checkout
|
||||
}
|
||||
|
||||
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(File.ReadAllText(path), SpawnerJsonSerializer.Options);
|
||||
Assert.NotEmpty(dtos);
|
||||
|
||||
var spawners = new List<BaseSpawner>(dtos.Count);
|
||||
try
|
||||
{
|
||||
foreach (var dto in dtos)
|
||||
{
|
||||
spawners.Add(dto.ToSpawner());
|
||||
}
|
||||
|
||||
Assert.Equal(dtos.Count, spawners.Count);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var s in spawners)
|
||||
{
|
||||
s?.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners.Json;
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class SpawnerCompactWriterTests
|
||||
{
|
||||
[Fact]
|
||||
public void SerializeCompact_ProducesCompactLoadableFormat()
|
||||
{
|
||||
Spawner original = null;
|
||||
BaseSpawner rebuilt = null;
|
||||
try
|
||||
{
|
||||
original = new Spawner("Fisherman");
|
||||
original.MoveToWorld(new Point3D(200, 200, 0), Map.Felucca);
|
||||
original.SpawnBounds = new Rectangle3D(195, 195, -128, 11, 11, 256); // == homeRange 5
|
||||
|
||||
var json = SpawnerJsonSerializer.SerializeCompact(new List<SpawnerDto> { original.ToDto() });
|
||||
|
||||
// No BOM (StartsWith '[' proves it), UTF-8, LF, trailing newline.
|
||||
Assert.StartsWith("[", json);
|
||||
Assert.DoesNotContain("\r", json);
|
||||
Assert.EndsWith("]\n", json);
|
||||
|
||||
// $type first; scalar containers inline; entries (array of objects) expanded.
|
||||
Assert.Contains("\"$type\": \"Spawner\"", json);
|
||||
Assert.Contains("\"location\": [200, 200, 0]", json);
|
||||
Assert.Contains("\"homeRange\": 5", json);
|
||||
Assert.DoesNotContain("spawnBounds", json);
|
||||
Assert.Contains("\"entries\": [\n", json); // array of objects -> expanded
|
||||
Assert.Contains("{ \"name\": \"Fisherman\",", json); // each entry inline
|
||||
|
||||
// Round-trips back to an equivalent spawner.
|
||||
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(json, SpawnerJsonSerializer.Options);
|
||||
rebuilt = Assert.Single(dtos).ToSpawner();
|
||||
Assert.Equal(new Rectangle3D(195, 195, -128, 11, 11, 256), rebuilt.SpawnBounds);
|
||||
}
|
||||
finally
|
||||
{
|
||||
rebuilt?.Delete();
|
||||
original?.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Server.Engines.Spawners;
|
||||
using Server.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners.Json;
|
||||
|
||||
public class SpawnerDiscoveryValidationTests
|
||||
{
|
||||
[JsonDiscoverableType("dup")]
|
||||
private sealed record DupA : SpawnerDto
|
||||
{
|
||||
protected override BaseSpawner CreateEmpty() => new Spawner();
|
||||
}
|
||||
|
||||
[JsonDiscoverableType("dup")]
|
||||
private sealed record DupB : SpawnerDto
|
||||
{
|
||||
protected override BaseSpawner CreateEmpty() => new Spawner();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DuplicateDiscriminator_Throws()
|
||||
{
|
||||
var map = new Dictionary<string, Type>();
|
||||
var (disc, _) = SpawnerJsonSerializer.Validate(typeof(DupA), map);
|
||||
map[disc] = typeof(DupA);
|
||||
|
||||
var ex = Assert.Throws<Exception>(() => SpawnerJsonSerializer.Validate(typeof(DupB), map));
|
||||
Assert.Contains("discriminator 'dup'", ex.Message);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,157 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using Server;
|
||||
using Server.Engines.Spawners;
|
||||
using Server.Regions;
|
||||
using Xunit;
|
||||
|
||||
namespace UOContent.Tests.Engines.Spawners.Json;
|
||||
|
||||
[Collection("Sequential UOContent Tests")]
|
||||
public class SpawnerDtoRoundTripTests
|
||||
{
|
||||
[Fact]
|
||||
public void Spawner_NonSquareBounds_WritesSpawnBounds_RoundTrips()
|
||||
{
|
||||
Spawner original = null;
|
||||
BaseSpawner rebuilt = null;
|
||||
try
|
||||
{
|
||||
// Bounds centered on (102,102), placed at (105,105) -> not a homeRange square.
|
||||
original = new Spawner(2, TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(7), 0,
|
||||
new Rectangle3D(100, 100, 0, 5, 5, 0), "Fisherman");
|
||||
original.MoveToWorld(new Point3D(105, 105, 0), Map.Felucca);
|
||||
|
||||
var json = JsonSerializer.Serialize(new List<SpawnerDto> { original.ToDto() }, SpawnerJsonSerializer.Options);
|
||||
Assert.Contains("\"$type\": \"Spawner\"", json);
|
||||
Assert.Contains("\"count\": 2", json);
|
||||
Assert.Contains("spawnBounds", json);
|
||||
Assert.DoesNotContain("homeRange", json);
|
||||
|
||||
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(json, SpawnerJsonSerializer.Options);
|
||||
rebuilt = Assert.Single(dtos).ToSpawner();
|
||||
var s = Assert.IsType<Spawner>(rebuilt);
|
||||
Assert.Equal(2, s.Count);
|
||||
Assert.Equal(TimeSpan.FromMinutes(3), s.MinDelay);
|
||||
Assert.Equal(new Rectangle3D(100, 100, 0, 5, 5, 0), s.SpawnBounds);
|
||||
Assert.Equal("Fisherman", Assert.Single(s.Entries).SpawnedName);
|
||||
}
|
||||
finally
|
||||
{
|
||||
rebuilt?.Delete();
|
||||
original?.Delete();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Spawner_HomeRangeSquare_WritesHomeRange_RoundTrips()
|
||||
{
|
||||
Spawner original = null;
|
||||
BaseSpawner rebuilt = null;
|
||||
try
|
||||
{
|
||||
original = new Spawner("Fisherman");
|
||||
original.MoveToWorld(new Point3D(200, 200, 0), Map.Felucca);
|
||||
// Exactly what homeRange 5 reconstructs (centered square, standard z/depth).
|
||||
original.SpawnBounds = new Rectangle3D(195, 195, -128, 11, 11, 256);
|
||||
|
||||
var json = JsonSerializer.Serialize(new List<SpawnerDto> { original.ToDto() }, SpawnerJsonSerializer.Options);
|
||||
Assert.Contains("\"homeRange\": 5", json);
|
||||
Assert.DoesNotContain("spawnBounds", json);
|
||||
|
||||
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(json, SpawnerJsonSerializer.Options);
|
||||
rebuilt = Assert.Single(dtos).ToSpawner();
|
||||
Assert.Equal(new Rectangle3D(195, 195, -128, 11, 11, 256), rebuilt.SpawnBounds);
|
||||
}
|
||||
finally
|
||||
{
|
||||
rebuilt?.Delete();
|
||||
original?.Delete();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Spawner_WritesMandatory_OmitsOptionalDefaults()
|
||||
{
|
||||
Spawner original = null;
|
||||
try
|
||||
{
|
||||
// Default delays (5/10), team 0, default maxSpawnAttempts.
|
||||
original = new Spawner("Fisherman");
|
||||
original.MoveToWorld(new Point3D(110, 110, 0), Map.Felucca);
|
||||
var json = JsonSerializer.Serialize(new List<SpawnerDto> { original.ToDto() }, SpawnerJsonSerializer.Options);
|
||||
|
||||
// Mandatory — always written, even at default.
|
||||
Assert.Contains("\"guid\":", json);
|
||||
Assert.Contains("minDelay", json);
|
||||
Assert.Contains("maxDelay", json);
|
||||
|
||||
// Optional defaults — omitted.
|
||||
Assert.DoesNotContain("\"team\"", json);
|
||||
Assert.DoesNotContain("maxSpawnAttempts", json);
|
||||
Assert.DoesNotContain("spawnLocationIsHome", json);
|
||||
}
|
||||
finally
|
||||
{
|
||||
original?.Delete();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegionSpawner_RoundTrips_RegionByName()
|
||||
{
|
||||
var region = new BaseRegion("DtoTestRegion", Map.Felucca, 50, new Rectangle3D(1400, 1670, 0, 40, 40, 0));
|
||||
region.Register();
|
||||
RegionSpawner original = null;
|
||||
BaseSpawner rebuilt = null;
|
||||
try
|
||||
{
|
||||
original = new RegionSpawner("Fisherman") { SpawnRegion = region };
|
||||
original.MoveToWorld(new Point3D(1416, 1683, 0), Map.Felucca);
|
||||
var json = JsonSerializer.Serialize(new List<SpawnerDto> { original.ToDto() }, SpawnerJsonSerializer.Options);
|
||||
Assert.Contains("\"$type\": \"RegionSpawner\"", json);
|
||||
Assert.Contains("DtoTestRegion", json);
|
||||
Assert.DoesNotContain("homeRange", json);
|
||||
Assert.DoesNotContain("spawnBounds", json);
|
||||
|
||||
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(json, SpawnerJsonSerializer.Options);
|
||||
rebuilt = Assert.Single(dtos).ToSpawner();
|
||||
Assert.Equal("DtoTestRegion", Assert.IsType<RegionSpawner>(rebuilt).SpawnRegion?.Name);
|
||||
}
|
||||
finally
|
||||
{
|
||||
rebuilt?.Delete();
|
||||
original?.Delete();
|
||||
region.Unregister();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProximitySpawner_RoundTrips_Fields()
|
||||
{
|
||||
ProximitySpawner original = null;
|
||||
BaseSpawner rebuilt = null;
|
||||
try
|
||||
{
|
||||
original = new ProximitySpawner("Fisherman") { TriggerRange = 4, InstantFlag = true, SpawnMessage = 500000 };
|
||||
original.MoveToWorld(new Point3D(120, 120, 0), Map.Felucca);
|
||||
var json = JsonSerializer.Serialize(new List<SpawnerDto> { original.ToDto() }, SpawnerJsonSerializer.Options);
|
||||
Assert.Contains("\"$type\": \"ProximitySpawner\"", json);
|
||||
Assert.Contains("\"triggerRange\": 4", json);
|
||||
Assert.Contains("\"instant\": true", json);
|
||||
|
||||
var dtos = JsonSerializer.Deserialize<List<SpawnerDto>>(json, SpawnerJsonSerializer.Options);
|
||||
rebuilt = Assert.Single(dtos).ToSpawner();
|
||||
var p = Assert.IsType<ProximitySpawner>(rebuilt);
|
||||
Assert.Equal(4, p.TriggerRange);
|
||||
Assert.True(p.InstantFlag);
|
||||
Assert.Equal(500000, p.SpawnMessage.Number);
|
||||
}
|
||||
finally
|
||||
{
|
||||
rebuilt?.Delete();
|
||||
original?.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
117
Projects/UOContent/Engines/Spawners/BaseSpawner.Dto.cs
Normal file
117
Projects/UOContent/Engines/Spawners/BaseSpawner.Dto.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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}");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
217
Projects/UOContent/Engines/Spawners/Json/SpawnerDto.cs
Normal file
217
Projects/UOContent/Engines/Spawners/Json/SpawnerDto.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
45
Projects/UOContent/Engines/Spawners/ProximitySpawner.Dto.cs
Normal file
45
Projects/UOContent/Engines/Spawners/ProximitySpawner.Dto.cs
Normal 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
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
38
Projects/UOContent/Engines/Spawners/RegionSpawner.Dto.cs
Normal file
38
Projects/UOContent/Engines/Spawners/RegionSpawner.Dto.cs
Normal 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
|
||||
};
|
||||
}
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
42
Projects/UOContent/Engines/Spawners/Spawner.Dto.cs
Normal file
42
Projects/UOContent/Engines/Spawners/Spawner.Dto.cs
Normal 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
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
346
Projects/UOContent/Engines/Spawners/SpawnerJsonSerializer.cs
Normal file
346
Projects/UOContent/Engines/Spawners/SpawnerJsonSerializer.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue