Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Tools: the map editor window, step 2 of the map editor (Refs #1009) (#1266)

Eyal Golan6f817dce7036
diff --git a/changelog.d/map-editor-window-1009.md b/changelog.d/map-editor-window-1009.md
new file mode 100644
index 000000000..27f83cc56
--- /dev/null
+++ b/changelog.d/map-editor-window-1009.md
@@ -0,0 +1,6 @@
+- The map override editor window (Statecraft/Map override editor) edits land terrain, one control period at a time and
+ named-location positions in `content/map/overrides.yaml`, with map selection, coordinate and drag moves, Unity
+ undo/redo, discard, and the city, site and corridor records a move touches listed before saving. Save checks the whole
+ content through the game's loader first, so an edit that would break it (a settlement moved onto a designated site)
+ leaves the saved file as it was; saving unchanged data does not rewrite the file. Unsaved edits survive a script
+ reload, and closing the window or choosing Reload with them asks first (refs #1009).
diff --git a/sim/Statecraft.Sim.Tests/MapOverridesTests.cs b/sim/Statecraft.Sim.Tests/MapOverridesTests.cs
index f52102fc6..3bffd8c3a 100644
--- a/sim/Statecraft.Sim.Tests/MapOverridesTests.cs
+++ b/sim/Statecraft.Sim.Tests/MapOverridesTests.cs
@@ -49,6 +49,22 @@ public class MapOverridesTests
Assert.False(o.TryLocation("town_a", out _, out _));
}
+ [Fact]
+ public void SerializeWritesTheShippedFormatInAStableOrderAndParsesBack()
+ {
+ // #1009 step 2: the editor's only writer. The shipped file comes back byte for byte, so an unchanged save writes nothing.
+ var shipped = File.ReadAllText(Path.Combine(RealContentTests.ContentRoot(), MapOverrides.FileName));
+ Assert.Equal(shipped, MapOverrides.Serialize(MapOverrides.Parse(shipped)));
+ var text = MapOverrides.Serialize(Checked("terrain:\n - { hex: { q: 2, r: 2 }, value: desert }\n - { hex: { q: 1, r: 2 }, value: hills }\n"
+ + "control:\n - { hex: { q: 1, r: 2 }, period: truce1, value: E }\n - { hex: { q: 1, r: 2 }, period: opening, value: '-' }\n"
+ + "locations:\n - { id: town_a, hex: { q: 1, r: 2 } }\n - { id: fort_a, hex: { q: 2, r: 2 } }\n"));
+ Assert.Equal("# yaml-language-server: $schema=../schema/map-overrides.schema.json\n"
+ + "terrain:\n - { hex: { q: 1, r: 2 }, value: 'hills' }\n - { hex: { q: 2, r: 2 }, value: 'desert' }\n"
+ + "control:\n - { hex: { q: 1, r: 2 }, period: 'opening', value: '-' }\n - { hex: { q: 1, r: 2 }, period: 'truce1', value: 'E' }\n"
+ + "locations:\n - { id: 'fort_a', hex: { q: 2, r: 2 } }\n - { id: 'town_a', hex: { q: 1, r: 2 } }\n", text);
+ Assert.Equal(text, MapOverrides.Serialize(Checked(text)));
+ }
+
[Fact]
public void AControlOverrideReplacesOnePeriodOfOneHexAndNothingElse()
{
diff --git a/sim/Statecraft.Sim/MapOverrides.cs b/sim/Statecraft.Sim/MapOverrides.cs
index 84ebe096d..4ef2b5250 100644
--- a/sim/Statecraft.Sim/MapOverrides.cs
+++ b/sim/Statecraft.Sim/MapOverrides.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Text;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
@@ -50,6 +51,57 @@ namespace Statecraft.Sim
.WithNamingConvention(UnderscoredNamingConvention.Instance)
.WithDuplicateKeyChecking().Build();
+ /// <summary>The map editor's one canonical representation: schema header, fixed sections and stable ordinal
+ /// ordering. Parse is the only reader and this is the only writer, so the editor cannot drift from the format the
+ /// sim and map consume. The input is not mutated.</summary>
+ public static string Serialize(MapOverrides value)
+ {
+ if (value == null) throw new ArgumentNullException(nameof(value));
+ var copy = Parse(SerializeUnvalidated(value));
+ var text = new StringBuilder("# yaml-language-server: $schema=../schema/map-overrides.schema.json\n");
+ Section(text, "terrain", copy.Terrain.OrderBy(x => x.Hex.R).ThenBy(x => x.Hex.Q), x =>
+ FormattableString.Invariant($"{{ hex: {{ q: {x.Hex.Q}, r: {x.Hex.R} }}, value: {Quote(x.Value)} }}"));
+ Section(text, "control", copy.Control.OrderBy(x => x.Hex.R).ThenBy(x => x.Hex.Q).ThenBy(x => x.Period, StringComparer.Ordinal), x =>
+ FormattableString.Invariant($"{{ hex: {{ q: {x.Hex.Q}, r: {x.Hex.R} }}, period: {Quote(x.Period)}, value: {Quote(x.Value)} }}"));
+ Section(text, "locations", copy.Locations.OrderBy(x => x.Id, StringComparer.Ordinal), x =>
+ FormattableString.Invariant($"{{ id: {Quote(x.Id)}, hex: {{ q: {x.Hex.Q}, r: {x.Hex.R} }} }}"));
+ return text.ToString();
+ }
+
+ static string SerializeUnvalidated(MapOverrides value)
+ {
+ if (value.Terrain == null) throw new ContentException(FileName, "terrain", "must be a list");
+ if (value.Control == null) throw new ContentException(FileName, "control", "must be a list");
+ if (value.Locations == null) throw new ContentException(FileName, "locations", "must be a list");
+ for (int i = 0; i < value.Terrain.Count; i++) Serializable(value.Terrain[i], value.Terrain[i]?.Hex, $"terrain[{i}]");
+ for (int i = 0; i < value.Control.Count; i++) Serializable(value.Control[i], value.Control[i]?.Hex, $"control[{i}]");
+ for (int i = 0; i < value.Locations.Count; i++) Serializable(value.Locations[i], value.Locations[i]?.Hex, $"locations[{i}]");
+ var text = new StringBuilder();
+ Section(text, "terrain", value.Terrain, x =>
+ FormattableString.Invariant($"{{ hex: {{ q: {x.Hex.Q}, r: {x.Hex.R} }}, value: {Quote(x.Value ?? "")} }}"));
+ Section(text, "control", value.Control, x =>
+ FormattableString.Invariant($"{{ hex: {{ q: {x.Hex.Q}, r: {x.Hex.R} }}, period: {Quote(x.Period ?? "")}, value: {Quote(x.Value ?? "")} }}"));
+ Section(text, "locations", value.Locations, x =>
+ FormattableString.Invariant($"{{ id: {Quote(x.Id ?? "")}, hex: {{ q: {x.Hex.Q}, r: {x.Hex.R} }} }}"));
+ return text.ToString();
+ }
+
+ static void Serializable(object? row, MapHexRef? hex, string at)
+ {
+ if (row == null) throw new ContentException(FileName, at, "must be an object");
+ if (hex == null) throw new ContentException(FileName, at + ".hex", "required");
+ }
+
+ static void Section<T>(StringBuilder text, string name, IEnumerable<T> rows, Func<T, string> row)
+ {
+ var list = rows.ToList();
+ if (list.Count == 0) { text.Append(name).Append(": []\n"); return; }
+ text.Append(name).Append(":\n");
+ foreach (var item in list) text.Append(" - ").Append(row(item)).Append('\n');
+ }
+
+ static string Quote(string value) => "'" + value.Replace("'", "''") + "'";
+
/// <summary>Parses the file and checks its shape: the three lists, a hex on every entry and no target twice. A
/// missing or blank file (null, "") has no overrides. Throws ContentException naming the file and field.</summary>
public static MapOverrides Parse(string? yaml, string file = FileName)
diff --git a/unity/Assets/Editor/MapOverrideEditorWindow.cs b/unity/Assets/Editor/MapOverrideEditorWindow.cs
new file mode 100644
index 000000000..e06c2786e
--- /dev/null
+++ b/unity/Assets/Editor/MapOverrideEditorWindow.cs
@@ -0,0 +1,391 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Game.Map;
+using UnityEditor;
+using UnityEngine;
+
+namespace Statecraft.Game.EditorTools
+{
+ /// <summary>Internal authoring window for content/map/overrides.yaml (#1009). It never edits generated inputs,
+ /// historical coordinates, identities, sources, localities_1948 or route geometry. Unsaved edits survive a domain
+ /// reload (the document is serialized and restored), and closing the window with them asks to save or discard.</summary>
+ public sealed class MapOverrideEditorWindow : EditorWindow
+ {
+ [SerializeField] MapOverrideEditorDocument? document;
+ string error = "", message = "";
+ Vector2 inspectorScroll, pan;
+ float zoom = 1f;
+ (int q, int r)? selectedHex;
+ string selectedLocation = "";
+ int coordinateQ, coordinateR, periodIndex;
+ bool draggingLocation, panning;
+ (int q, int r)? dragTarget;
+ Vector2 lastMouse;
+
+ [MenuItem("Statecraft/Map override editor")]
+ public static void Open() => GetWindow<MapOverrideEditorWindow>("Map overrides");
+
+ void OnEnable()
+ {
+ Undo.undoRedoPerformed += OnUndoRedo;
+ saveChangesMessage = "The map override editor has unsaved edits to content/map/overrides.yaml. Save them?";
+ if (document == null) Load();
+ else if (!document.IsLoaded) Restore();
+ else UpdateUnsaved();
+ }
+
+ // A domain reload disables the window and keeps the document; only closing the window destroys it.
+ void OnDisable() => Undo.undoRedoPerformed -= OnUndoRedo;
+
+ void OnDestroy()
+ {
+ if (document != null) DestroyImmediate(document);
+ }
+
+ /// <summary>Unity calls this when the window closes with unsaved edits and the author chooses Save. A failed save
+ /// keeps hasUnsavedChanges set, so the window stays open with the error.</summary>
+ public override void SaveChanges() => Save();
+
+ void OnUndoRedo()
+ {
+ message = "Undo/redo applied";
+ error = "";
+ UpdateUnsaved();
+ Repaint();
+ }
+
+ void UpdateUnsaved() => hasUnsavedChanges = document != null && document.HasUnsavedChanges;
+
+ void Restore()
+ {
+ try
+ {
+ document!.Restore();
+ SyncCoordinateFields();
+ error = "";
+ message = "Restored unsaved edits after a script reload";
+ }
+ catch (Exception exception) { error = exception.Message; }
+ UpdateUnsaved();
+ }
+
+ void Reload()
+ {
+ if (document != null && !document.IsLoaded) { Restore(); return; } // retry, keeping the restored edits
+ if (hasUnsavedChanges && !EditorUtility.DisplayDialog("Reload map overrides",
+ "Reloading discards your unsaved edits to content/map/overrides.yaml.", "Discard and reload", "Cancel"))
+ return;
+ Load();
+ }
+
+ void Load()
+ {
+ try
+ {
+ if (document != null) DestroyImmediate(document);
+ document = MapOverrideEditorDocument.Load(Paths.Content);
+ var first = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).FirstOrDefault();
+ selectedLocation = first?.Id ?? "";
+ if (first != null) SetCoordinateFields(document.LocationAt(first.Id));
+ error = "";
+ message = "Loaded " + document.OverridePath;
+ }
+ catch (Exception exception)
+ {
+ document = null;
+ error = exception.Message;
+ }
+ UpdateUnsaved();
+ }
+
+ void OnGUI()
+ {
+ Toolbar();
+ if (!string.IsNullOrEmpty(error)) EditorGUILayout.HelpBox(error, MessageType.Error);
+ if (document == null || !document.IsLoaded)
+ {
+ EditorGUILayout.HelpBox("The map could not be loaded. Fix the named input and choose Reload.", MessageType.Info);
+ return;
+ }
+
+ var mapRect = GUILayoutUtility.GetRect(240f, 100000f, 240f, 100000f, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
+ var inspectorWidth = Mathf.Min(360f, Mathf.Max(290f, position.width * 0.32f));
+ var canvas = new Rect(mapRect.x, mapRect.y, Mathf.Max(100f, mapRect.width - inspectorWidth - 6f), mapRect.height);
+ var inspector = new Rect(canvas.xMax + 6f, mapRect.y, inspectorWidth, mapRect.height);
+ DrawMap(canvas);
+ GUILayout.BeginArea(inspector, EditorStyles.helpBox);
+ inspectorScroll = EditorGUILayout.BeginScrollView(inspectorScroll);
+ DrawInspector();
+ EditorGUILayout.EndScrollView();
+ GUILayout.EndArea();
+ }
+
+ void Toolbar()
+ {
+ using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
+ {
+ if (GUILayout.Button("Reload", EditorStyles.toolbarButton, GUILayout.Width(60))) Reload();
+ using (new EditorGUI.DisabledScope(document == null || !hasUnsavedChanges))
+ {
+ if (GUILayout.Button("Discard", EditorStyles.toolbarButton, GUILayout.Width(60))) Discard();
+ if (GUILayout.Button("Save", EditorStyles.toolbarButton, GUILayout.Width(50))) Save();
+ }
+ if (GUILayout.Button("Undo", EditorStyles.toolbarButton, GUILayout.Width(45))) Undo.PerformUndo();
+ if (GUILayout.Button("Redo", EditorStyles.toolbarButton, GUILayout.Width(45))) Undo.PerformRedo();
+ GUILayout.Space(8);
+ GUILayout.Label(hasUnsavedChanges ? "Unsaved changes" : "Saved", EditorStyles.miniLabel);
+ GUILayout.FlexibleSpace();
+ GUILayout.Label("Scroll: zoom · middle drag: pan · drag a marker: move", EditorStyles.miniLabel);
+ }
+ if (!string.IsNullOrEmpty(message)) EditorGUILayout.LabelField(message, EditorStyles.miniLabel);
+ }
+
+ void Discard()
+ {
+ if (document == null) return;
+ try
+ {
+ Undo.RecordObject(document, "Discard map override edits");
+ document.Reload();
+ error = "";
+ message = "Discarded unsaved edits and reloaded the saved override file";
+ SyncCoordinateFields();
+ }
+ catch (Exception exception) { error = exception.Message; }
+ UpdateUnsaved();
+ }
+
+ void Save()
+ {
+ if (document == null || !document.IsLoaded) return;
+ if (document.Save(out error))
+ {
+ AssetDatabase.Refresh();
+ message = "Saved " + document.OverridePath;
+ }
+ UpdateUnsaved();
+ }
+
+ void DrawInspector()
+ {
+ if (document == null) return;
+ EditorGUILayout.LabelField("Hex", EditorStyles.boldLabel);
+ if (selectedHex is not { } hex) EditorGUILayout.HelpBox("Select a hex on the map.", MessageType.Info);
+ else
+ {
+ EditorGUILayout.LabelField("Coordinates", $"q={hex.q}, r={hex.r}");
+ if (!document.IsLand(hex.q, hex.r)) EditorGUILayout.HelpBox("Water hex: land/water flips and terrain edits are not permitted.", MessageType.Info);
+ else
+ {
+ var terrain = document.TerrainAt(hex.q, hex.r);
+ var terrainIndex = Math.Max(0, document.LandBiomes.ToList().IndexOf(terrain));
+ EditorGUI.BeginChangeCheck();
+ terrainIndex = EditorGUILayout.Popup("Terrain", terrainIndex, document.LandBiomes.ToArray());
+ if (EditorGUI.EndChangeCheck()) Mutate("Change hex terrain", () => document.SetTerrain(hex.q, hex.r, document.LandBiomes[terrainIndex]));
+ }
+ DrawControl(hex.q, hex.r);
+ }
+
+ EditorGUILayout.Space(12);
+ EditorGUILayout.LabelField("Location", EditorStyles.boldLabel);
+ var choices = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).ToList();
+ var selected = Math.Max(0, choices.FindIndex(x => x.Id == selectedLocation));
+ EditorGUI.BeginChangeCheck();
+ selected = EditorGUILayout.Popup("Location", selected, choices.Select(x => x.Name + " (" + x.Id + ")").ToArray());
+ if (EditorGUI.EndChangeCheck() && choices.Count > 0)
+ {
+ selectedLocation = choices[selected].Id;
+ SyncCoordinateFields();
+ }
+ var location = choices.FirstOrDefault(x => x.Id == selectedLocation);
+ if (location != null)
+ {
+ EditorGUILayout.LabelField("Identity", location.Id);
+ EditorGUILayout.LabelField("Kind", location.Kind);
+ var at = document.LocationAt(location.Id);
+ EditorGUILayout.LabelField("Authored position", $"q={at.q}, r={at.r}");
+ coordinateQ = EditorGUILayout.IntField("q", coordinateQ);
+ coordinateR = EditorGUILayout.IntField("r", coordinateR);
+ if (GUILayout.Button("Move to coordinates"))
+ Mutate("Move map location", () => document.SetLocation(location.Id, coordinateQ, coordinateR));
+ DrawDependencies(location.Id);
+ }
+ }
+
+ void DrawControl(int q, int r)
+ {
+ if (document == null || document.Periods.Count == 0) return;
+ periodIndex = Mathf.Clamp(periodIndex, 0, document.Periods.Count - 1);
+ periodIndex = EditorGUILayout.Popup("Control period", periodIndex, document.Periods.Select(x => x.Id).ToArray());
+ var period = document.Periods[periodIndex].Id;
+ try
+ {
+ var current = document.ControlAt(q, r, period);
+ var index = Math.Max(0, document.ControlValues.ToList().IndexOf(current));
+ EditorGUI.BeginChangeCheck();
+ index = EditorGUILayout.Popup("Control", index, document.ControlValues.ToArray());
+ if (EditorGUI.EndChangeCheck()) Mutate("Change one control period", () => document.SetControl(q, r, period, document.ControlValues[index]));
+ }
+ catch (ArgumentException)
+ {
+ EditorGUILayout.HelpBox("This hex is not in the 1948–49 control file, so its control cannot be edited.", MessageType.Info);
+ }
+ }
+
+ void DrawDependencies(string id)
+ {
+ if (document == null) return;
+ var dependencies = document.Dependencies(id);
+ EditorGUILayout.Space(6);
+ EditorGUILayout.HelpBox("Moving a marker changes only its authored gameplay hex. Identity, sources, city/site records, sourced route waypoints and route geometry remain unchanged.", MessageType.Warning);
+ DependencyLines("Cities", dependencies.Cities);
+ DependencyLines("Sites", dependencies.Sites);
+ DependencyLines("Corridors", dependencies.Corridors);
+ }
+
+ static void DependencyLines(string title, IReadOnlyList<string> rows)
+ {
+ EditorGUILayout.LabelField(title, EditorStyles.boldLabel);
+ if (rows.Count == 0) EditorGUILayout.LabelField("None", EditorStyles.wordWrappedMiniLabel);
+ else foreach (var row in rows) EditorGUILayout.LabelField("• " + row, EditorStyles.wordWrappedMiniLabel);
+ }
+
+ void Mutate(string label, Action change)
+ {
+ if (document == null) return;
+ try
+ {
+ Undo.RecordObject(document, label);
+ change();
+ EditorUtility.SetDirty(document);
+ error = "";
+ message = label;
+ UpdateUnsaved();
+ SyncCoordinateFields();
+ Repaint();
+ }
+ catch (Exception exception) when (exception is ArgumentException || exception is Statecraft.Sim.ContentException)
+ {
+ error = exception.Message;
+ }
+ }
+
+ void DrawMap(Rect rect)
+ {
+ if (document == null) return;
+ EditorGUI.DrawRect(rect, new Color(0.10f, 0.11f, 0.12f));
+ var hexes = document.Hexes.ToList();
+ if (hexes.Count == 0) return;
+ var centres = hexes.ToDictionary(x => (x.Q, x.R), x => HexGrid.Centre(x.Q, x.R, 1f));
+ var minX = centres.Values.Min(x => x.x); var maxX = centres.Values.Max(x => x.x);
+ var minY = centres.Values.Min(x => x.y); var maxY = centres.Values.Max(x => x.y);
+ var span = new Vector2(Mathf.Max(1f, maxX - minX), Mathf.Max(1f, maxY - minY));
+ var mapCentre = new Vector2((minX + maxX) * .5f, (minY + maxY) * .5f);
+ var scale = Mathf.Min((rect.width - 20f) / span.x, (rect.height - 20f) / span.y) * zoom;
+ Vector2 Screen(Vector2 point) => rect.center + Vector2.Scale(point - mapCentre, new Vector2(scale, scale)) + pan;
+ var radius = Mathf.Max(1.2f, scale * .72f);
+
+ Handles.BeginGUI();
+ foreach (var hex in hexes)
+ {
+ var centre = Screen(centres[(hex.Q, hex.R)]);
+ if (!rect.Contains(centre)) continue;
+ var biome = document.TerrainAt(hex.Q, hex.R);
+ var colour = MapBuilder.BiomeColours.TryGetValue(biome, out var found) ? found : Color.gray;
+ colour.a = hex.Land ? .92f : .55f;
+ Handles.color = colour;
+ if (radius < 2.2f) Handles.DrawSolidDisc(centre, Vector3.forward, radius);
+ else Handles.DrawAAConvexPolygon(HexPoints(centre, radius));
+ }
+ if (selectedHex is { } selected && centres.TryGetValue(selected, out var selectedCentre))
+ {
+ Handles.color = Color.yellow;
+ Handles.DrawWireDisc(Screen(selectedCentre), Vector3.forward, Mathf.Max(4f, radius + 2f), 2f);
+ }
+ foreach (var location in document.Locations)
+ {
+ var at = dragTarget.HasValue && draggingLocation && location.Id == selectedLocation ? dragTarget.Value : document.LocationAt(location.Id);
+ if (!centres.TryGetValue(at, out var point)) continue;
+ var screen = Screen(point);
+ Handles.color = location.Id == selectedLocation ? new Color(1f, .82f, .18f) : Color.white;
+ Handles.DrawSolidDisc(screen, Vector3.forward, location.Id == selectedLocation ? 5f : 3f);
+ if (location.Id == selectedLocation)
+ Handles.Label(screen + new Vector2(7f, -8f), location.Name, EditorStyles.miniLabel);
+ }
+ Handles.EndGUI();
+ HandleMapInput(rect, centres, Screen);
+ }
+
+ static Vector3[] HexPoints(Vector2 centre, float radius)
+ {
+ var points = new Vector3[6];
+ for (int i = 0; i < points.Length; i++)
+ {
+ var angle = Mathf.Deg2Rad * (60f * i - 30f);
+ points[i] = centre + new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * radius;
+ }
+ return points;
+ }
+
+ void HandleMapInput(Rect rect, Dictionary<(int q, int r), Vector2> centres, Func<Vector2, Vector2> screen)
+ {
+ if (document == null) return;
+ var current = Event.current;
+ if (!rect.Contains(current.mousePosition) && !draggingLocation && !panning) return;
+ if (current.type == EventType.ScrollWheel)
+ {
+ zoom = Mathf.Clamp(zoom * (current.delta.y > 0 ? .9f : 1.1f), .6f, 8f);
+ current.Use(); Repaint(); return;
+ }
+ if (current.type == EventType.MouseDown && current.button == 2)
+ {
+ panning = true; lastMouse = current.mousePosition; current.Use(); return;
+ }
+ if (current.type == EventType.MouseDrag && panning)
+ {
+ pan += current.mousePosition - lastMouse; lastMouse = current.mousePosition; current.Use(); Repaint(); return;
+ }
+ if (current.type == EventType.MouseUp && current.button == 2) { panning = false; current.Use(); return; }
+ if (current.type == EventType.MouseDown && current.button == 0)
+ {
+ var marker = document.Locations.Select(x => (location: x, at: document.LocationAt(x.Id)))
+ .Where(x => centres.ContainsKey(x.at))
+ .OrderBy(x => Vector2.Distance(screen(centres[x.at]), current.mousePosition)).FirstOrDefault();
+ if (marker.location != null && Vector2.Distance(screen(centres[marker.at]), current.mousePosition) <= 9f)
+ {
+ selectedLocation = marker.location.Id;
+ draggingLocation = true;
+ dragTarget = marker.at;
+ SetCoordinateFields(marker.at);
+ }
+ else
+ {
+ selectedHex = centres.OrderBy(x => Vector2.Distance(screen(x.Value), current.mousePosition)).First().Key;
+ dragTarget = null;
+ }
+ current.Use(); Repaint(); return;
+ }
+ if (current.type == EventType.MouseDrag && draggingLocation)
+ {
+ dragTarget = centres.OrderBy(x => Vector2.Distance(screen(x.Value), current.mousePosition)).First().Key;
+ current.Use(); Repaint(); return;
+ }
+ if (current.type == EventType.MouseUp && current.button == 0 && draggingLocation)
+ {
+ draggingLocation = false;
+ if (dragTarget is { } target) Mutate("Drag map location", () => document.SetLocation(selectedLocation, target.q, target.r));
+ dragTarget = null;
+ current.Use(); Repaint();
+ }
+ }
+
+ void SyncCoordinateFields()
+ {
+ if (document != null && !string.IsNullOrEmpty(selectedLocation)) SetCoordinateFields(document.LocationAt(selectedLocation));
+ }
+
+ void SetCoordinateFields((int q, int r) at) { coordinateQ = at.q; coordinateR = at.r; }
+ }
+}
diff --git a/unity/Assets/Editor/MapOverrideEditorWindow.cs.meta b/unity/Assets/Editor/MapOverrideEditorWindow.cs.meta
new file mode 100644
index 000000000..fafd8bc22
--- /dev/null
+++ b/unity/Assets/Editor/MapOverrideEditorWindow.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 9f5fbe1bb0d6456b87e61198fa65911a
diff --git a/unity/Assets/Scripts/Map/Control1948.cs b/unity/Assets/Scripts/Map/Control1948.cs
index 5a9ea8893..328b7a0af 100644
--- a/unity/Assets/Scripts/Map/Control1948.cs
+++ b/unity/Assets/Scripts/Map/Control1948.cs
@@ -82,6 +82,10 @@ namespace Statecraft.Game.Map
readonly Dictionary<(int q, int r), string> codes;
/// <summary>Each hex's codes as read (a test aid: the runtime file must give the YAML's, issue #321).</summary>
internal IReadOnlyDictionary<(int q, int r), string> Codes => codes;
+ /// <summary>The control codes the map editor may assign, in a stable order.</summary>
+ public static IReadOnlyList<string> EditorCodes { get; } = CodeOf.Keys.Select(x => x.ToString()).OrderBy(x => x, StringComparer.Ordinal).ToList();
+ /// <summary>The control-file hexes the map editor may change.</summary>
+ public IEnumerable<(int q, int r)> EditorHexes => codes.Keys;
readonly RegionLayer?[] layers;
IReadOnlyCollection<(int q, int r)> outside = Array.Empty<(int, int)>();
@@ -107,6 +111,18 @@ namespace Statecraft.Game.Map
return -1;
}
+ /// <summary>A control-file hex's code in one named period, for the map editor. Throws with the same vocabulary as
+ /// override validation when either target is absent.</summary>
+ public string EditorCodeAt(int q, int r, string period)
+ {
+ if (!codes.TryGetValue((q, r), out var row))
+ throw new ArgumentException(FormattableString.Invariant($"unknown control hex q={q} r={r}"), nameof(q));
+ int index = -1;
+ for (int i = 0; i < Periods.Count; i++) if (Periods[i].Id == period) { index = i; break; }
+ if (index < 0) throw new ArgumentException($"unknown control period '{period}'", nameof(period));
+ return row[index].ToString();
+ }
+
/// <summary>The hexes outside Mandatory Palestine (the sub-district layer's "outside" region): a region of style none,
/// so the bands run along the frontier and nothing is drawn beyond it, as for the sub-districts.</summary>
public void SetOutside(IEnumerable<(int q, int r)> hexes) { outside = hexes.ToList(); Array.Clear(layers, 0, layers.Length); }
diff --git a/unity/Assets/Scripts/Map/MapOverrideEditorDocument.cs b/unity/Assets/Scripts/Map/MapOverrideEditorDocument.cs
new file mode 100644
index 000000000..c58804533
--- /dev/null
+++ b/unity/Assets/Scripts/Map/MapOverrideEditorDocument.cs
@@ -0,0 +1,254 @@
+#nullable enable
+#if UNITY_EDITOR
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Statecraft.Sim;
+using UnityEngine;
+
+namespace Statecraft.Game.Map
+{
+ [Serializable]
+ public sealed class MapEditorTerrainEdit
+ {
+ public int q, r;
+ public string value = "";
+ }
+
+ [Serializable]
+ public sealed class MapEditorControlEdit
+ {
+ public int q, r;
+ public string period = "", value = "";
+ }
+
+ [Serializable]
+ public sealed class MapEditorLocationEdit
+ {
+ public string id = "";
+ public int q, r;
+ }
+
+ public sealed class MapEditorLocation
+ {
+ public readonly string Id, Name, Kind;
+ public readonly int BaseQ, BaseR;
+
+ public MapEditorLocation(string id, string name, string kind, int q, int r)
+ { Id = id; Name = name; Kind = kind; BaseQ = q; BaseR = r; }
+ }
+
+ public sealed class MapEditorDependencies
+ {
+ public readonly IReadOnlyList<string> Cities, Sites, Corridors;
+
+ public MapEditorDependencies(IEnumerable<string> cities, IEnumerable<string> sites, IEnumerable<string> corridors)
+ {
+ Cities = cities.OrderBy(x => x, StringComparer.Ordinal).ToList();
+ Sites = sites.OrderBy(x => x, StringComparer.Ordinal).ToList();
+ Corridors = corridors.OrderBy(x => x, StringComparer.Ordinal).ToList();
+ }
+ }
+
+ /// <summary>The undoable data behind the Unity map editor. It edits only content/map/overrides.yaml; generated map
+ /// inputs and historical evidence stay read-only. Unity serializes the three edit lists, so Undo restores every
+ /// terrain, one-period control and location-position edit. The content root is serialized too, so after a domain
+ /// reload <see cref="Restore"/> rebuilds the map around the surviving edits.</summary>
+ public sealed class MapOverrideEditorDocument : ScriptableObject
+ {
+ [SerializeField] List<MapEditorTerrainEdit> terrain = new List<MapEditorTerrainEdit>();
+ [SerializeField] List<MapEditorControlEdit> control = new List<MapEditorControlEdit>();
+ [SerializeField] List<MapEditorLocationEdit> locations = new List<MapEditorLocationEdit>();
+
+ [SerializeField] string contentRoot = "";
+ string path = "", savedCanonical = "";
+ readonly Dictionary<(int q, int r), MapHex> baseHexes = new Dictionary<(int, int), MapHex>();
+ readonly Dictionary<string, MapEditorLocation> baseLocations = new Dictionary<string, MapEditorLocation>(StringComparer.Ordinal);
+ readonly List<string> landBiomes = new List<string>();
+ Content baseContent = null!;
+ Control1948 controlFile = null!;
+
+ public IReadOnlyCollection<MapHex> Hexes => baseHexes.Values;
+ public IReadOnlyCollection<MapEditorLocation> Locations => baseLocations.Values;
+ public IReadOnlyList<string> LandBiomes => landBiomes;
+ public IReadOnlyList<Control1948.Period> Periods => controlFile.Periods;
+ public IReadOnlyList<string> ControlValues => Control1948.EditorCodes;
+ public bool HasUnsavedChanges => Canonical() != savedCanonical;
+ public string OverridePath => path;
+ /// <summary>False after a domain reload, which keeps the serialized edits but not the map read from disk.</summary>
+ public bool IsLoaded => controlFile != null;
+
+ public static MapOverrideEditorDocument Load(string root)
+ {
+ var result = CreateInstance<MapOverrideEditorDocument>();
+ result.hideFlags = HideFlags.HideAndDontSave;
+ result.Reload(root);
+ return result;
+ }
+
+ public void Reload() => Reload(contentRoot);
+
+ /// <summary>Reads the map and the saved override file again and keeps the current edits (after a domain reload).</summary>
+ public void Restore() => ReadSaved(contentRoot);
+
+ void Reload(string root) => SetFrom(ReadSaved(root));
+
+ MapOverrides ReadSaved(string root)
+ {
+ if (string.IsNullOrWhiteSpace(root)) throw new ArgumentException("The content directory is required", nameof(root));
+ contentRoot = Path.GetFullPath(root);
+ path = Path.Combine(contentRoot, MapOverrides.FileName);
+ var eventRoot = Path.Combine(contentRoot, "events");
+ var events = Directory.Exists(eventRoot)
+ ? Directory.GetFiles(eventRoot, "*.yaml").Select(x => "events/" + Path.GetFileName(x)).ToList()
+ : new List<string>();
+ baseContent = ContentLoader.Load(relative =>
+ {
+ if (relative == MapOverrides.FileName) return null;
+ var file = Path.Combine(contentRoot, relative);
+ return File.Exists(file) ? File.ReadAllText(file) : null;
+ }, events);
+ controlFile = Control1948.Parse(File.ReadAllText(Path.Combine(contentRoot, "map", Control1948.FileName)));
+
+ baseHexes.Clear();
+ foreach (var hex in baseContent.Hexes) baseHexes[(hex.Q, hex.R)] = hex;
+ landBiomes.Clear();
+ landBiomes.AddRange(baseContent.Hexes.Where(x => x.Land).Select(x => x.Biome).Distinct().OrderBy(x => x, StringComparer.Ordinal));
+ baseLocations.Clear();
+ foreach (var item in baseContent.SettlementHexes)
+ baseLocations[item.Id] = new MapEditorLocation(item.Id, baseContent.SettlementNames[item.Id], "settlement", item.Q, item.R);
+ foreach (var item in baseContent.MapLocations)
+ baseLocations[item.Id] = new MapEditorLocation(item.Id, item.Name, item.Kind, item.Q, item.R);
+
+ var source = File.Exists(path) ? File.ReadAllText(path) : "";
+ var parsed = MapOverrides.Parse(source);
+ parsed.ValidateMap(baseContent.Hexes, baseLocations.Keys);
+ parsed.ValidateControl(controlFile.EditorHexes, controlFile.Periods.Select(x => x.Id), Control1948.EditorCodes);
+ savedCanonical = MapOverrides.Serialize(parsed);
+ name = "Map overrides";
+ return parsed;
+ }
+
+ public string TerrainAt(int q, int r)
+ {
+ if (!baseHexes.TryGetValue((q, r), out var hex)) throw new ArgumentException(FormattableString.Invariant($"unknown hex q={q} r={r}"));
+ return terrain.FirstOrDefault(x => x.q == q && x.r == r)?.value ?? hex.Biome;
+ }
+
+ public string ControlAt(int q, int r, string period) =>
+ control.FirstOrDefault(x => x.q == q && x.r == r && x.period == period)?.value
+ ?? controlFile.EditorCodeAt(q, r, period);
+
+ public (int q, int r) LocationAt(string id)
+ {
+ if (!baseLocations.TryGetValue(id, out var item)) throw new ArgumentException($"unknown location id '{id}'", nameof(id));
+ var edit = locations.FirstOrDefault(x => x.id == id);
+ return edit == null ? (item.BaseQ, item.BaseR) : (edit.q, edit.r);
+ }
+
+ public bool IsLand(int q, int r) => baseHexes.TryGetValue((q, r), out var hex) && hex.Land;
+
+ public void SetTerrain(int q, int r, string value)
+ {
+ if (!baseHexes.TryGetValue((q, r), out var hex)) throw new ArgumentException(FormattableString.Invariant($"unknown hex q={q} r={r}"));
+ if (!hex.Land) throw new ArgumentException(FormattableString.Invariant($"hex q={q} r={r} is not a land hex"));
+ if (!landBiomes.Contains(value)) throw new ArgumentException($"unknown land terrain '{value}'", nameof(value));
+ terrain.RemoveAll(x => x.q == q && x.r == r);
+ if (value != hex.Biome) terrain.Add(new MapEditorTerrainEdit { q = q, r = r, value = value });
+ }
+
+ public void SetControl(int q, int r, string period, string value)
+ {
+ var original = controlFile.EditorCodeAt(q, r, period);
+ if (!Control1948.EditorCodes.Contains(value)) throw new ArgumentException($"unknown control value '{value}'", nameof(value));
+ control.RemoveAll(x => x.q == q && x.r == r && x.period == period);
+ if (value != original) control.Add(new MapEditorControlEdit { q = q, r = r, period = period, value = value });
+ }
+
+ public void SetLocation(string id, int q, int r)
+ {
+ if (!baseLocations.TryGetValue(id, out var item)) throw new ArgumentException($"unknown location id '{id}'", nameof(id));
+ if (!baseHexes.TryGetValue((q, r), out var hex)) throw new ArgumentException(FormattableString.Invariant($"unknown hex q={q} r={r}"));
+ if (!hex.Land) throw new ArgumentException(FormattableString.Invariant($"hex q={q} r={r} is not a land hex"));
+ locations.RemoveAll(x => x.id == id);
+ if (q != item.BaseQ || r != item.BaseR) locations.Add(new MapEditorLocationEdit { id = id, q = q, r = r });
+ }
+
+ public MapEditorDependencies Dependencies(string id)
+ {
+ if (!baseLocations.TryGetValue(id, out var item)) throw new ArgumentException($"unknown location id '{id}'", nameof(id));
+ var current = LocationAt(id);
+ var cities = baseContent.Cities.Where(x => x.Id == id).Select(x => $"city '{x.Id}' uses this location identity");
+ var sites = baseContent.Sites.Where(x => x.Id == id || x.City == id
+ || (x.Q == item.BaseQ && x.R == item.BaseR) || (x.Q == current.q && x.R == current.r))
+ .Select(x => $"site '{x.Id}'" + (x.City == id ? $" is bound to city '{id}'" : $" shares hex q={x.Q} r={x.R}"));
+ var corridors = baseContent.Corridors.SelectMany(x => x.Segments.Select((segment, i) => (corridor: x, segment, number: i + 1)))
+ .Where(x => x.segment.Hexes.Any(h => (h[0] == item.BaseQ && h[1] == item.BaseR) || (h[0] == current.q && h[1] == current.r)))
+ .Select(x => $"corridor '{x.corridor.Id}' segment {x.number} (to {x.segment.To}) crosses this location's hex; its hexes stay as traced");
+ return new MapEditorDependencies(cities, sites, corridors);
+ }
+
+ public bool Save(out string error)
+ {
+ try
+ {
+ var value = ToOverrides();
+ value.ValidateMap(baseContent.Hexes, baseLocations.Keys);
+ value.ValidateControl(controlFile.EditorHexes, controlFile.Periods.Select(x => x.Id), Control1948.EditorCodes);
+ var canonical = MapOverrides.Serialize(value);
+ if (canonical == savedCanonical) { error = ""; return true; }
+ // Validate the candidate through the game's full content loader before replacing the saved map: a valid
+ // land-hex move can still break a dependent record (for example a settlement moved onto a site).
+ var eventRoot = Path.Combine(contentRoot, "events");
+ var events = Directory.Exists(eventRoot)
+ ? Directory.GetFiles(eventRoot, "*.yaml").Select(x => "events/" + Path.GetFileName(x)).ToList()
+ : new List<string>();
+ ContentLoader.Load(relative =>
+ {
+ if (relative == MapOverrides.FileName) return canonical;
+ var file = Path.Combine(contentRoot, relative);
+ return File.Exists(file) ? File.ReadAllText(file) : null;
+ }, events);
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ var temporary = path + ".tmp-" + Guid.NewGuid().ToString("N");
+ try
+ {
+ File.WriteAllText(temporary, canonical);
+ var check = MapOverrides.Parse(File.ReadAllText(temporary));
+ check.ValidateMap(baseContent.Hexes, baseLocations.Keys);
+ check.ValidateControl(controlFile.EditorHexes, controlFile.Periods.Select(x => x.Id), Control1948.EditorCodes);
+ if (File.Exists(path)) File.Replace(temporary, path, null);
+ else File.Move(temporary, path);
+ }
+ finally { if (File.Exists(temporary)) File.Delete(temporary); }
+ savedCanonical = canonical;
+ error = "";
+ return true;
+ }
+ catch (Exception exception) when (exception is IOException || exception is UnauthorizedAccessException
+ || exception is ArgumentException || exception is ContentException)
+ {
+ error = exception.Message;
+ return false;
+ }
+ }
+
+ public MapOverrides ToOverrides() => new MapOverrides
+ {
+ Terrain = terrain.Select(x => new TerrainOverride { Hex = new MapHexRef { Q = x.q, R = x.r }, Value = x.value }).ToList(),
+ Control = control.Select(x => new ControlOverride { Hex = new MapHexRef { Q = x.q, R = x.r }, Period = x.period, Value = x.value }).ToList(),
+ Locations = locations.Select(x => new LocationOverride { Id = x.id, Hex = new MapHexRef { Q = x.q, R = x.r } }).ToList(),
+ };
+
+ string Canonical() => MapOverrides.Serialize(ToOverrides());
+
+ void SetFrom(MapOverrides value)
+ {
+ terrain = value.Terrain.Select(x => new MapEditorTerrainEdit { q = x.Hex.Q, r = x.Hex.R, value = x.Value }).ToList();
+ control = value.Control.Select(x => new MapEditorControlEdit { q = x.Hex.Q, r = x.Hex.R, period = x.Period, value = x.Value }).ToList();
+ locations = value.Locations.Select(x => new MapEditorLocationEdit { id = x.Id, q = x.Hex.Q, r = x.Hex.R }).ToList();
+ }
+ }
+}
+#endif
diff --git a/unity/Assets/Scripts/Map/MapOverrideEditorDocument.cs.meta b/unity/Assets/Scripts/Map/MapOverrideEditorDocument.cs.meta
new file mode 100644
index 000000000..dc688f647
--- /dev/null
+++ b/unity/Assets/Scripts/Map/MapOverrideEditorDocument.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: fff4822c7f4d4a22a9e471779974a0e7
diff --git a/unity/Assets/Tests/EditMode/MapOverrideEditorTests.cs b/unity/Assets/Tests/EditMode/MapOverrideEditorTests.cs
new file mode 100644
index 000000000..f987416c2
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/MapOverrideEditorTests.cs
@@ -0,0 +1,232 @@
+#nullable enable
+using System;
+using System.IO;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Map;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+
+/// <summary>#1009 step 2: the Unity map editor round-trips the one override file through the sim's parser/serializer, does not
+/// touch an unchanged file, rejects invalid moves before save, and records edits with Unity Undo.</summary>
+public sealed class MapOverrideEditorTests
+{
+ string temporary = "";
+
+ [SetUp]
+ public void SetUp()
+ {
+ temporary = Path.Combine(Path.GetTempPath(), "statecraft-map-editor-" + Guid.NewGuid().ToString("N"));
+ CopyDirectory(Paths.Content, temporary);
+ }
+
+ [TearDown]
+ public void TearDown()
+ {
+ if (Directory.Exists(temporary)) Directory.Delete(temporary, true);
+ }
+
+ [Test]
+ public void LoadEditSaveAndReloadHaveTheSameData()
+ {
+ var document = MapOverrideEditorDocument.Load(temporary);
+ MapOverrideEditorDocument? reloaded = null;
+ try
+ {
+ var hex = document.Hexes.First(x => x.Land);
+ var terrain = document.LandBiomes.First(x => x != hex.Biome);
+ var location = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).First();
+ var target = document.Hexes.First(x => x.Land && (x.Q != location.BaseQ || x.R != location.BaseR));
+ var controlHex = Control1948.Parse(File.ReadAllText(Path.Combine(temporary, "map", Control1948.FileName))).EditorHexes.First();
+ var period = document.Periods[0].Id;
+ var control = document.ControlValues.First(x => x != document.ControlAt(controlHex.q, controlHex.r, period));
+
+ document.SetTerrain(hex.Q, hex.R, terrain);
+ document.SetControl(controlHex.q, controlHex.r, period, control);
+ document.SetLocation(location.Id, target.Q, target.R);
+ Assert.IsTrue(document.Save(out var error), error);
+
+ reloaded = MapOverrideEditorDocument.Load(temporary);
+ Assert.AreEqual(terrain, reloaded.TerrainAt(hex.Q, hex.R));
+ Assert.AreEqual(control, reloaded.ControlAt(controlHex.q, controlHex.r, period));
+ Assert.AreEqual((target.Q, target.R), reloaded.LocationAt(location.Id));
+ Assert.AreEqual(MapOverrides.Serialize(document.ToOverrides()), MapOverrides.Serialize(reloaded.ToOverrides()));
+ }
+ finally
+ {
+ if (reloaded != null) UnityEngine.Object.DestroyImmediate(reloaded);
+ UnityEngine.Object.DestroyImmediate(document);
+ }
+ }
+
+ [Test]
+ public void SavingUnchangedDataDoesNotRewriteTheFile()
+ {
+ var path = Path.Combine(temporary, MapOverrides.FileName);
+ var before = File.ReadAllBytes(path);
+ var beforeWrite = File.GetLastWriteTimeUtc(path);
+ var document = MapOverrideEditorDocument.Load(temporary);
+ try
+ {
+ Assert.IsFalse(document.HasUnsavedChanges);
+ Assert.IsTrue(document.Save(out var error), error);
+ CollectionAssert.AreEqual(before, File.ReadAllBytes(path));
+ Assert.AreEqual(beforeWrite, File.GetLastWriteTimeUtc(path), "an unchanged save does not touch the file");
+ }
+ finally { UnityEngine.Object.DestroyImmediate(document); }
+ }
+
+ [Test]
+ public void UnityUndoAndRedoRestoreEveryEditKind()
+ {
+ var document = MapOverrideEditorDocument.Load(temporary);
+ try
+ {
+ var hex = document.Hexes.First(x => x.Land);
+ var terrainBefore = document.TerrainAt(hex.Q, hex.R);
+ var terrainAfter = document.LandBiomes.First(x => x != terrainBefore);
+ var location = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).First();
+ var before = document.LocationAt(location.Id);
+ var target = document.Hexes.First(x => x.Land && (x.Q != before.q || x.R != before.r));
+ var controlHex = Control1948.Parse(File.ReadAllText(Path.Combine(temporary, "map", Control1948.FileName))).EditorHexes.First();
+ var period = document.Periods[0].Id;
+ var controlBefore = document.ControlAt(controlHex.q, controlHex.r, period);
+ var controlAfter = document.ControlValues.First(x => x != controlBefore);
+ Undo.IncrementCurrentGroup();
+ Undo.RecordObject(document, "Edit map overrides");
+ document.SetTerrain(hex.Q, hex.R, terrainAfter);
+ document.SetControl(controlHex.q, controlHex.r, period, controlAfter);
+ document.SetLocation(location.Id, target.Q, target.R);
+ Undo.FlushUndoRecordObjects();
+ Assert.AreEqual(terrainAfter, document.TerrainAt(hex.Q, hex.R));
+ Assert.AreEqual(controlAfter, document.ControlAt(controlHex.q, controlHex.r, period));
+ Assert.AreEqual((target.Q, target.R), document.LocationAt(location.Id));
+ Undo.PerformUndo();
+ Assert.AreEqual(terrainBefore, document.TerrainAt(hex.Q, hex.R));
+ Assert.AreEqual(controlBefore, document.ControlAt(controlHex.q, controlHex.r, period));
+ Assert.AreEqual(before, document.LocationAt(location.Id));
+ Undo.PerformRedo();
+ Assert.AreEqual(terrainAfter, document.TerrainAt(hex.Q, hex.R));
+ Assert.AreEqual(controlAfter, document.ControlAt(controlHex.q, controlHex.r, period));
+ Assert.AreEqual((target.Q, target.R), document.LocationAt(location.Id));
+ }
+ finally
+ {
+ Undo.ClearUndo(document);
+ UnityEngine.Object.DestroyImmediate(document);
+ }
+ }
+
+ [Test]
+ public void InvalidInputIsClearAndLeavesTheSavedFileIntact()
+ {
+ var path = Path.Combine(temporary, MapOverrides.FileName);
+ var before = File.ReadAllBytes(path);
+ var document = MapOverrideEditorDocument.Load(temporary);
+ try
+ {
+ var location = document.Locations.First();
+ var water = document.Hexes.First(x => !x.Land);
+ var error = Assert.Throws<ArgumentException>(() => document.SetLocation(location.Id, water.Q, water.R));
+ StringAssert.Contains("not a land hex", error!.Message);
+ error = Assert.Throws<ArgumentException>(() => document.SetLocation("unknown_location", water.Q, water.R));
+ StringAssert.Contains("unknown location id", error!.Message);
+ Assert.IsFalse(document.HasUnsavedChanges);
+ CollectionAssert.AreEqual(before, File.ReadAllBytes(path));
+ }
+ finally { UnityEngine.Object.DestroyImmediate(document); }
+ }
+
+ [Test]
+ public void ALocationMoveThatBreaksASiteCannotReplaceTheSavedMap()
+ {
+ var path = Path.Combine(temporary, MapOverrides.FileName);
+ var before = File.ReadAllBytes(path);
+ var content = LoadSavedContent();
+ var site = content.Sites.First();
+ var location = content.SettlementHexes.First();
+ var document = MapOverrideEditorDocument.Load(temporary);
+ try
+ {
+ document.SetLocation(location.Id, site.Q, site.R);
+ Assert.IsFalse(document.Save(out var error), "a settlement cannot occupy a designated site's hex");
+ StringAssert.Contains(site.Id, error, "the failure identifies the affected dependent record");
+ CollectionAssert.AreEqual(before, File.ReadAllBytes(path), "the last valid saved map stays intact");
+ Assert.DoesNotThrow(() => { LoadSavedContent(); }, "the saved map still loads in the game");
+ }
+ finally { UnityEngine.Object.DestroyImmediate(document); }
+ }
+
+ [Test]
+ public void MovingACorridorEndpointReportsTheCorridorAndKeepsItsTracedHexes()
+ {
+ // A corridor is bound to hexes, not to a location id (corridors.yaml; ContentLoader.ValidateCorridors), so moving the
+ // location at its end cannot break loading: the move saves, the dependency is reported and no hex is rewritten.
+ var path = Path.Combine(temporary, MapOverrides.FileName);
+ var content = LoadSavedContent();
+ var corridor = content.Corridors.Single(x => x.Id == "tlv_netanya_road");
+ var tracedBefore = corridor.Segments.SelectMany(x => x.Hexes).Select(h => (h[0], h[1])).ToList();
+ var end = corridor.Segments.Last().Hexes.Last();
+ var occupied = content.SettlementHexes.Select(x => (x.Q, x.R)).Concat(content.MapLocations.Select(x => (x.Q, x.R)))
+ .Concat(content.Sites.Select(x => (x.Q, x.R))).ToHashSet();
+ var document = MapOverrideEditorDocument.Load(temporary);
+ try
+ {
+ var location = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).First(x => x.BaseQ == end[0] && x.BaseR == end[1]);
+ var target = document.Hexes.First(x => x.Land && !occupied.Contains((x.Q, x.R)));
+ StringAssert.Contains("tlv_netanya_road", string.Join("\n", document.Dependencies(location.Id).Corridors),
+ "the corridor that ends on the location is reported before saving");
+ document.SetLocation(location.Id, target.Q, target.R);
+ Assert.IsTrue(document.Save(out var error), error);
+ var saved = LoadSavedContent();
+ CollectionAssert.AreEqual(tracedBefore, saved.Corridors.Single(x => x.Id == corridor.Id).Segments
+ .SelectMany(x => x.Hexes).Select(h => (h[0], h[1])).ToList(), "the corridor keeps its traced hexes");
+ var moved = saved.SettlementHexes.Select(x => (x.Id, x.Q, x.R)).Concat(saved.MapLocations.Select(x => (x.Id, x.Q, x.R)))
+ .Single(x => x.Id == location.Id);
+ Assert.AreEqual((target.Q, target.R), (moved.Q, moved.R), "the game reads the moved location");
+ StringAssert.Contains(location.Id, File.ReadAllText(path));
+ }
+ finally { UnityEngine.Object.DestroyImmediate(document); }
+ }
+
+ [Test]
+ public void UnsavedEditsSurviveADomainReload()
+ {
+ // A domain reload keeps a document's serialized fields and drops the rest; EditorJsonUtility does the same round trip.
+ var document = MapOverrideEditorDocument.Load(temporary);
+ var restored = ScriptableObject.CreateInstance<MapOverrideEditorDocument>();
+ try
+ {
+ var hex = document.Hexes.First(x => x.Land);
+ var terrain = document.LandBiomes.First(x => x != hex.Biome);
+ document.SetTerrain(hex.Q, hex.R, terrain);
+ EditorJsonUtility.FromJsonOverwrite(EditorJsonUtility.ToJson(document), restored);
+ Assert.IsFalse(restored.IsLoaded, "the map read from disk is not serialized");
+ restored.Restore();
+ Assert.IsTrue(restored.IsLoaded);
+ Assert.AreEqual(terrain, restored.TerrainAt(hex.Q, hex.R), "the unsaved edit survives");
+ Assert.IsTrue(restored.HasUnsavedChanges, "and still counts as unsaved");
+ }
+ finally
+ {
+ UnityEngine.Object.DestroyImmediate(restored);
+ UnityEngine.Object.DestroyImmediate(document);
+ }
+ }
+
+ Content LoadSavedContent() => ContentLoader.Load(relative =>
+ {
+ var file = Path.Combine(temporary, relative);
+ return File.Exists(file) ? File.ReadAllText(file) : null;
+ }, Directory.GetFiles(Path.Combine(temporary, "events"), "*.yaml").Select(x => "events/" + Path.GetFileName(x)).ToList());
+
+ static void CopyDirectory(string source, string destination)
+ {
+ Directory.CreateDirectory(destination);
+ foreach (var file in Directory.GetFiles(source)) File.Copy(file, Path.Combine(destination, Path.GetFileName(file)));
+ foreach (var directory in Directory.GetDirectories(source))
+ CopyDirectory(directory, Path.Combine(destination, Path.GetFileName(directory)));
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/MapOverrideEditorTests.cs.meta b/unity/Assets/Tests/EditMode/MapOverrideEditorTests.cs.meta
new file mode 100644
index 000000000..49cb14c44
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/MapOverrideEditorTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: b8f8bd81009b43f28209a01beb27ebd9