diff --git a/RPGModder.Core/Merge/CommandBranch.cs b/RPGModder.Core/Merge/CommandBranch.cs new file mode 100644 index 0000000..aa90741 --- /dev/null +++ b/RPGModder.Core/Merge/CommandBranch.cs @@ -0,0 +1,11 @@ +using Newtonsoft.Json.Linq; + +namespace RPGModder.Core.Merge; + +/// +/// One body of a block (guide 3.6). Marker is null for an unmarked body, as the first body of a +/// Conditional Branch or a Loop. Body ends with its code 0 node. +/// +internal sealed record CommandBranch( + JObject? Marker, + IReadOnlyList Body); diff --git a/RPGModder.Core/Merge/CommandNode.cs b/RPGModder.Core/Merge/CommandNode.cs new file mode 100644 index 0000000..399e124 --- /dev/null +++ b/RPGModder.Core/Merge/CommandNode.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json.Linq; + +namespace RPGModder.Core.Merge; + +/// +/// One command of a list with what belongs to it (guide 3.6): the continuation lines of its block, its branches, and +/// the end marker that closes them. The code 0 command that ends a body or the list is a node of its own with +/// nothing below it. End is kept, and not rebuilt, so a list comes back unchanged (GR-T1). +/// +internal sealed record CommandNode( + JObject Head, + IReadOnlyList Continuations, + IReadOnlyList Branches, + JObject? End); diff --git a/RPGModder.Core/Merge/CommandTree.cs b/RPGModder.Core/Merge/CommandTree.cs new file mode 100644 index 0000000..b302221 --- /dev/null +++ b/RPGModder.Core/Merge/CommandTree.cs @@ -0,0 +1,279 @@ +using Newtonsoft.Json.Linq; + +namespace RPGModder.Core.Merge; + +/// +/// Parses a command list into its tree and back (guide 3.6). Structure is indent alone, as in the engine's +/// Game_Interpreter: a branch marker tests only the branch of its own indent, and skipBranch skips the +/// deeper commands. The parser is strict, so a list it accepts is walked by the engine the way the tree says, and +/// anything else is one Atomic value (GR-T2). +/// +internal static class CommandTree +{ + /// The code that ends a body and the list. + internal const int EndCode = 0; + + /// + /// A list nested deeper than this is one Atomic value. The editor stops far below it, and the bound keeps the + /// parser's recursion on a stack of any size. + /// + internal const int MaxDepth = 100; + + private const string CodeProperty = "code"; + private const string IndentProperty = "indent"; + + /// The blocks of guide 3.6 whose head is followed by lines of its own at the same indent. + private static readonly Dictionary ContinuationOf = new() + { + [101] = 401, + [105] = 405, + [108] = 408, + [205] = 505, + [302] = 605, + [355] = 655, + [357] = 657 + }; + + /// The blocks of guide 3.6 that hold bodies. + private static readonly Dictionary Blocks = new() + { + [102] = new BlockShape(FirstBodyUnmarked: false, Markers: [402, 403], End: 404, OnlyWithMarkers: false), + [111] = new BlockShape(FirstBodyUnmarked: true, Markers: [411], End: 412, OnlyWithMarkers: false), + [112] = new BlockShape(FirstBodyUnmarked: true, Markers: [], End: 413, OnlyWithMarkers: false), + [301] = new BlockShape(FirstBodyUnmarked: false, Markers: [601, 602, 603], End: 604, OnlyWithMarkers: true) + }; + + /// Codes that only follow their head: a list that starts a node with one is not parsed. + private static readonly HashSet Followers = ContinuationOf.Values + .Concat(Blocks.Values.SelectMany(shape => shape.Markers.Append(shape.End))) + .ToHashSet(); + + /// + /// The nodes of the list, the final code 0 node last, or null when the list is not well formed: a command + /// that is not an object with a whole code and indent, an indent that is not the depth of its + /// place, a continuation, marker or end marker without its head, a body or a list without its code 0, or + /// anything after the final one. + /// + internal static IReadOnlyList? Parse(JArray list) + { + ArgumentNullException.ThrowIfNull(list); + + var reader = new Reader(list); + return reader.TryBody(0, out List nodes) && reader.AtEnd ? nodes : null; + } + + /// The commands of in order, each a copy with its indent set to its depth (GR-T1). + internal static JArray Flatten(IReadOnlyList nodes) + { + ArgumentNullException.ThrowIfNull(nodes); + + var list = new JArray(); + Emit(nodes, 0, list); + return list; + } + + /// The commands of one node at , for comparing nodes and for fingerprints. + internal static JArray Flatten(CommandNode node, int depth) + { + var list = new JArray(); + Emit([node], depth, list); + return list; + } + + /// + /// GR-T8: indent steps of at most one, markers only after their head, every body terminated and the final + /// terminator. These are what checks, so a list is valid when it parses. + /// + internal static bool Validate(JArray list) + { + return Parse(list) is not null; + } + + internal static bool IsEnd(CommandNode node) + { + return node.Head.Value(CodeProperty) == EndCode; + } + + private static void Emit(IReadOnlyList nodes, int depth, JArray list) + { + foreach (CommandNode node in nodes) + { + Add(node.Head, depth, list); + foreach (JObject line in node.Continuations) + { + Add(line, depth, list); + } + + foreach (CommandBranch branch in node.Branches) + { + if (branch.Marker is not null) + { + Add(branch.Marker, depth, list); + } + + Emit(branch.Body, depth + 1, list); + } + + if (node.End is not null) + { + Add(node.End, depth, list); + } + } + } + + private static void Add(JObject command, int depth, JArray list) + { + var copy = (JObject)command.DeepClone(); + copy[IndentProperty] = depth; + list.Add(copy); + } + + private sealed record BlockShape(bool FirstBodyUnmarked, long[] Markers, long End, bool OnlyWithMarkers); + + private sealed class Reader + { + private readonly JArray _list; + private int _position; + + public Reader(JArray list) + { + _list = list; + } + + public bool AtEnd => _position == _list.Count; + + /// The nodes at up to and with the code 0 that ends them. + public bool TryBody(int depth, out List nodes) + { + nodes = new List(); + if (depth > MaxDepth) + { + return false; + } + + while (CodeAt(_position, depth) is long code) + { + var head = (JObject)_list[_position]; + _position++; + if (code == EndCode) + { + nodes.Add(new CommandNode(head, [], [], null)); + return true; + } + + if (!TryNode(head, code, depth, out CommandNode? node)) + { + return false; + } + + nodes.Add(node); + } + + return false; + } + + private bool TryNode(JObject head, long code, int depth, out CommandNode node) + { + node = new CommandNode(head, [], [], null); + if (Followers.Contains(code)) + { + return false; + } + + var continuations = new List(); + if (ContinuationOf.TryGetValue(code, out long continuation)) + { + while (CodeAt(_position, depth) == continuation) + { + continuations.Add((JObject)_list[_position]); + _position++; + } + } + + var branches = new List(); + JObject? end = null; + if (Blocks.TryGetValue(code, out BlockShape? shape)) + { + if (!TryBlock(shape, depth, branches, out end)) + { + return false; + } + } + else if (CodeAt(_position, depth + 1) is not null) + { + // GR-T2: a code the parser does not know, with deeper commands after it, holds one unmarked body. + if (!TryBody(depth + 1, out List body)) + { + return false; + } + + branches.Add(new CommandBranch(null, body)); + } + + node = new CommandNode(head, continuations, branches, end); + return true; + } + + private bool TryBlock(BlockShape shape, int depth, List branches, out JObject? end) + { + end = null; + if (shape.OnlyWithMarkers && !IsMarker(shape, CodeAt(_position, depth))) + { + // Battle Processing without Can Escape or Can Lose has no branches and no end. + return true; + } + + if (shape.FirstBodyUnmarked) + { + if (!TryBody(depth + 1, out List first)) + { + return false; + } + + branches.Add(new CommandBranch(null, first)); + } + + while (IsMarker(shape, CodeAt(_position, depth))) + { + var marker = (JObject)_list[_position]; + _position++; + if (!TryBody(depth + 1, out List body)) + { + return false; + } + + branches.Add(new CommandBranch(marker, body)); + } + + if (CodeAt(_position, depth) != shape.End) + { + return false; + } + + end = (JObject)_list[_position]; + _position++; + return true; + } + + private static bool IsMarker(BlockShape shape, long? code) + { + return code is long value && shape.Markers.Any(marker => marker == value); + } + + /// The code of the command at when it is a well-formed command at . + private long? CodeAt(int index, int depth) + { + if (index >= _list.Count || + _list[index] is not JObject command || + command.Property(CodeProperty, StringComparison.Ordinal)?.Value is not JValue { Value: long code } || + command.Property(IndentProperty, StringComparison.Ordinal)?.Value is not JValue { Value: long indent } || + indent != depth) + { + return null; + } + + // A whole number too large for a long is read as a BigInteger, so it is not a code. + return code; + } + } +} diff --git a/RPGModder.Core/Merge/Composer.Lists.cs b/RPGModder.Core/Merge/Composer.Lists.cs new file mode 100644 index 0000000..f4639f6 --- /dev/null +++ b/RPGModder.Core/Merge/Composer.Lists.cs @@ -0,0 +1,238 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Models; + +namespace RPGModder.Core.Merge; + +public static partial class Composer +{ + /// + /// Guide 3.6: a command list or a Sequence list that two or more mods edit in different ways is merged with + /// vanilla's (GR-T4, GR-T9), and stays one op whose value is the whole merged list (seam 11.5). Runs the mods + /// changed in different ways are one LogicClash or SequenceClash for the list, and inserts of more + /// than one mod at one gap one OrderAmbiguous. False leaves the cluster to the 2a path, where the list is + /// one value: no vanilla list, a list that is not well formed (GR-T2), or a merge some choice would leave invalid + /// (GR-T8). + /// + private static bool TryComposeList( + List cluster, + BaseRoots bases, + ILookup choices, + Dictionary priorities, + List ops, + List<(Collision, CollisionOutcome)> collisions, + List diagnostics) + { + if (cluster.Count != 1 || cluster[0].Variants.Count < 2) + { + return false; + } + + OpGroup group = cluster[0]; + ChangeKind kind = group.Variants[0].Op.Kind; + if (kind is not (ChangeKind.EditCommands or ChangeKind.EditSequence) || + group.Variants.Any(variant => variant.Op.Kind != kind || variant.Op.Value is not JArray) || + group.Variants.SelectMany(variant => variant.ModIds).GroupBy(id => id, StringComparer.Ordinal).Any(ids => ids.Count() > 1) || + bases.ValueAt(group.Key, group.Path) is not JArray vanilla) + { + return false; + } + + // Profile order: the side of the mod earliest in it first, as GR-T7 orders the inserts of one gap. + List variants = group.Variants + .OrderBy(variant => variant.ModIds.Min(id => priorities[id])) + .ThenBy(variant => variant.ModIds.Min(StringComparer.Ordinal), StringComparer.Ordinal) + .ToList(); + Func? run = kind == ChangeKind.EditCommands + ? CommandMerge(vanilla, variants) + : SequenceMerge(vanilla, variants); + if (run is null) + { + return false; + } + + // Each choice is merged once: the check of every choice below holds the first pass and the final one. + var results = new Dictionary(); + ListMergeResult Merge(ListPolicy policy) + { + if (!results.TryGetValue(policy, out ListMergeResult? result)) + { + result = run(policy); + results.Add(policy, result); + } + + return result; + } + + ListMergeResult found = Merge(ListPolicy.Unresolved); + var decisions = new List(); + (Collision Collision, CollisionOutcome Outcome)? clash = null; + if (found.ClashMods.Count > 0) + { + CollisionKind clashKind = kind == ChangeKind.EditCommands ? CollisionKind.LogicClash : CollisionKind.SequenceClash; + Collision collision = ListCollision(clashKind, group, found.ClashMods, found.ClashFingerprint); + clash = (collision, Decide(collision, choices, decisions)); + } + + (Collision Collision, CollisionOutcome Outcome)? order = null; + if (found.OrderMods.Count > 0) + { + Collision collision = ListCollision(CollisionKind.OrderAmbiguous, group, found.OrderMods, found.OrderFingerprint); + order = (collision, Decide(collision, choices, decisions)); + } + + if (kind == ChangeKind.EditCommands && !Policies(found).All(policy => CommandTree.Validate(Merge(policy).List))) + { + return false; + } + + diagnostics.AddRange(decisions); + if (clash is not null) + { + collisions.Add(clash.Value); + } + + if (order is not null) + { + collisions.Add(order.Value); + } + + if (clash is { Outcome.Source: ResolutionSource.Unresolved }) + { + // The clash is described by its collision and blocks the plan, so no op stands for the list. + return true; + } + + CollisionOutcome? clashOutcome = clash?.Outcome; + CollisionOutcome? orderOutcome = order?.Outcome; + var policy = new ListPolicy( + clashOutcome?.Kind, + clashOutcome?.Kind == ResolutionKind.PickMod ? clashOutcome.ModId : null, + orderOutcome?.Kind == ResolutionKind.PickMod ? orderOutcome.ModId : null); + ListMergeResult result = Merge(policy); + if (JToken.DeepEquals(result.List, vanilla)) + { + // Nothing of any mod is in the list: a clash kept as vanilla, or changes that undo each other. + return true; + } + + // Each side is every mod holding one list, so the variant of the first contributor sorts that mod first. + Variant lead = variants.First(variant => variant.ModIds.Contains(result.Contributors[0], StringComparer.Ordinal)); + ops.Add(new MergedOp(lead.Op with { Value = result.List }, result.Contributors)); + return true; + } + + private static Func? CommandMerge(JArray vanilla, List variants) + { + IReadOnlyList? vanillaNodes = CommandTree.Parse(vanilla); + var sides = new List>(); + foreach (Variant variant in variants) + { + IReadOnlyList? nodes = CommandTree.Parse((JArray)variant.Op.Value!); + if (nodes is null) + { + return null; + } + + sides.Add(new ListSide(nodes, variant.ModIds.Order(StringComparer.Ordinal).ToList())); + } + + return vanillaNodes is null ? null : policy => ListMerge.MergeCommands(vanillaNodes, sides, policy); + } + + private static Func SequenceMerge(JArray vanilla, List variants) + { + List vanillaItems = vanilla.ToList(); + List> sides = variants + .Select(variant => new ListSide(((JArray)variant.Op.Value!).ToList(), variant.ModIds.Order(StringComparer.Ordinal).ToList())) + .ToList(); + return policy => ListMerge.MergeSequence(vanillaItems, sides, policy); + } + + /// GR-T8: every choice the player could make for the list's collisions, so each one gives a valid list. + private static IEnumerable Policies(ListMergeResult found) + { + List<(ResolutionKind? Kind, string? Mod)> clashChoices = found.ClashMods.Count == 0 + ? [(null, null)] + : [(ResolutionKind.PickVanilla, null), .. found.ClashMods.Select(mod => ((ResolutionKind?)ResolutionKind.PickMod, (string?)mod))]; + List firstChoices = [null, .. found.OrderMods]; + foreach ((ResolutionKind? kind, string? mod) in clashChoices) + { + foreach (string? first in firstChoices) + { + yield return new ListPolicy(kind, mod, first); + } + } + } + + /// One collision for the list, its mods those of the runs or gaps it covers (seam 11.5). + private static Collision ListCollision(CollisionKind kind, OpGroup group, IReadOnlyList mods, string fingerprint) + { + return new Collision( + CollisionId(kind, group.Key, group.Path, mods), + kind, + group.Key, + group.Path, + mods, + IsBlocking(kind), + AllowedFor(kind), + fingerprint); + } + + /// The vanilla roots of one plan, each file read once. + private sealed class BaseRoots + { + private readonly BaseFileSet _files; + private readonly Dictionary _roots = new(StringComparer.Ordinal); + + public BaseRoots(BaseFileSet files) + { + _files = files; + } + + /// Vanilla's value at one place, or null when the file, the record or the path is not there. + public JToken? ValueAt(RecordKey key, string path) + { + if (!_roots.TryGetValue(key.File, out JToken? root)) + { + BaseFile? file = _files.Find(key.File); + root = file is not null && ChangeSetBuilder.TryReadBase(file, out JToken? read, out _) ? read : null; + _roots.Add(key.File, root); + } + + JToken? current = root is null ? null : RecordOf(root, key); + foreach (PathSegment segment in MergePath.Parse(path)) + { + if (current is null) + { + break; + } + + current = segment.Name is not null + ? (current as JObject)?.Property(segment.Name, StringComparison.Ordinal)?.Value + : current is JArray array && segment.Index < array.Count ? array[segment.Index] : null; + } + + return current; + } + + private static JToken? RecordOf(JToken root, RecordKey key) + { + if (key.IsWholeFile) + { + return root; + } + + JArray? records = null; + if (RecordKey.TryGetIndex(key.Record, out int index)) + { + records = root as JArray; + } + else if (RecordKey.TryGetEvent(key.Record, out index)) + { + records = (root as JObject)?.Property(RpgDataSchema.EventsProperty, StringComparison.Ordinal)?.Value as JArray; + } + + return records is not null && index < records.Count ? records[index] : null; + } + } +} diff --git a/RPGModder.Core/Merge/Composer.cs b/RPGModder.Core/Merge/Composer.cs index 9678e74..eaea843 100644 --- a/RPGModder.Core/Merge/Composer.cs +++ b/RPGModder.Core/Merge/Composer.cs @@ -8,10 +8,10 @@ namespace RPGModder.Core.Merge; /// /// Composes the change sets of every enabled mod into one plan (guide 3.4) and applies the stored choices -/// (guide 3.5). The result does not depend on the order of the inputs (GR-C4); priority is read only by the two -/// plugin order defaults, which name profile order. Nothing is merged by text, pattern or load order (GR-C11). +/// (guide 3.5). The result does not depend on the order of the inputs (GR-C4); priority is read only where a rule +/// names profile order, as the order defaults. Nothing is merged by text, pattern or load order (GR-C11). /// -public static class Composer +public static partial class Composer { /// /// The plan, when lane A ran : an IdClash one of its offers settles lists @@ -61,11 +61,12 @@ public static MergePlan Compose( var ops = new List(); var collisions = new List<(Collision Collision, CollisionOutcome Outcome)>(); IReadOnlyList offers = remapPlan?.Offers ?? []; + var bases = new BaseRoots(baseFiles); List groups = DropFiller(Group(ordered), changeSets, priorities); groups = FoldSharedNames(DropPaddingNames(groups, systemRoot), remapPlan, priorities); foreach (List cluster in Cluster(groups)) { - ComposeCluster(cluster, choices, priorities, offers, ops, collisions, diagnostics); + ComposeCluster(cluster, bases, choices, priorities, offers, ops, collisions, diagnostics); } foreach (SharedStateId shared in remapPlan?.SharedStateIds ?? []) @@ -287,6 +288,11 @@ private static List> Cluster(IReadOnlyList groups) return clusters; } + /// + /// The group a group's choice is made with: a whole-file op, else the nearest ancestor path, else the group + /// itself. GR-K4: a map's width and height go with its whole data, since tiles a resize lays + /// out again are only right with the size they were laid out for. + /// private static OpGroup HeadOf(OpGroup group, Dictionary<(string File, string Record, string Path), OpGroup> byPlace) { if (byPlace.TryGetValue((group.Key.File, RecordKey.WholeFile, ""), out OpGroup? wholeFile)) @@ -294,6 +300,12 @@ private static OpGroup HeadOf(OpGroup group, Dictionary<(string File, string Rec return wholeFile; } + if (RpgDataSchema.ResizedListOf(group.Key, group.Path) is string tiles && + byPlace.TryGetValue((group.Key.File, group.Key.Record, tiles), out OpGroup? data)) + { + return data; + } + foreach (string ancestor in MergePath.Ancestors(group.Path)) { if (byPlace.TryGetValue((group.Key.File, group.Key.Record, ancestor), out OpGroup? found)) @@ -307,6 +319,7 @@ private static OpGroup HeadOf(OpGroup group, Dictionary<(string File, string Rec private static void ComposeCluster( List cluster, + BaseRoots bases, ILookup choices, Dictionary priorities, IReadOnlyList offers, @@ -314,6 +327,11 @@ private static void ComposeCluster( List<(Collision, CollisionOutcome)> collisions, List diagnostics) { + if (TryComposeList(cluster, bases, choices, priorities, ops, collisions, diagnostics)) + { + return; + } + List mods = cluster .SelectMany(group => group.Variants) .SelectMany(variant => variant.ModIds) @@ -321,7 +339,8 @@ private static void ComposeCluster( .OrderBy(id => id, StringComparer.Ordinal) .ToList(); - bool clash = cluster.Count == 1 ? cluster[0].Variants.Count > 1 : mods.Count > 1; + // Mods that made one change together, such as two equal resizes with their tiles (GR-K4), do not clash. + bool clash = cluster.Count == 1 ? cluster[0].Variants.Count > 1 : mods.Count > 1 && !MadeTogether(cluster); if (!clash) { foreach (OpGroup group in cluster) @@ -344,11 +363,12 @@ private static void ComposeCluster( // Unresolved: the plan is not deployable and the clashing ops are described by the collision. break; case ResolutionKind.PickMod when cluster.Count > 1 && !IsHeadMod(cluster[0], outcome.ModId!): - // Choosing a change inside the head keeps every inner change: only the head is dropped, and the - // inner ops are composed again, so a clash among them becomes a collision of its own (seam 11). - foreach (List inner in Cluster(cluster.Skip(1).ToList())) + // Choosing a change inside the head keeps every inner change: the head is dropped with what only its + // mods changed inside it, such as a resize's width and height (GR-K4), and the inner ops are composed + // again, so a clash among them becomes a collision of its own (seam 11). + foreach (List inner in Cluster(WithoutHeadMods(cluster))) { - ComposeCluster(inner, choices, priorities, offers, ops, collisions, diagnostics); + ComposeCluster(inner, bases, choices, priorities, offers, ops, collisions, diagnostics); } break; @@ -367,7 +387,7 @@ private static void ComposeCluster( break; default: - // Decide accepts only kinds in Allowed, and no cluster kind of 2a allows another choice. + // Decide accepts only kinds in Allowed, and no kind a cluster can carry allows another choice. throw new UnreachableException($"Resolution {kind} is not applied to {collision.Kind}."); } } @@ -561,6 +581,35 @@ private static bool IsHeadMod(OpGroup head, string modId) return head.Variants.Any(variant => variant.ModIds.Contains(modId, StringComparer.Ordinal)); } + /// Every group holds one variant, and every variant the same mods. + private static bool MadeTogether(List cluster) + { + if (cluster.Any(group => group.Variants.Count != 1)) + { + return false; + } + + List first = cluster[0].Variants[0].ModIds.Order(StringComparer.Ordinal).ToList(); + return cluster.All(group => group.Variants[0].ModIds.Order(StringComparer.Ordinal).SequenceEqual(first, StringComparer.Ordinal)); + } + + /// The inner groups of a cluster without the variants whose mods all changed the head, empty groups left out. + private static List WithoutHeadMods(List cluster) + { + var inner = new List(); + foreach (OpGroup group in cluster.Skip(1)) + { + var kept = new OpGroup(group.Key, group.Path); + kept.Variants.AddRange(group.Variants.Where(variant => !variant.ModIds.All(id => IsHeadMod(cluster[0], id)))); + if (kept.Variants.Count > 0) + { + inner.Add(kept); + } + } + + return inner; + } + private static Collision MakeCollision(List cluster, List mods) { OpGroup head = cluster[0]; @@ -713,7 +762,7 @@ private static bool IsApplicable(Resolution resolution, Collision collision) (resolution.ModId is not null && collision.ModIds.Contains(resolution.ModId, StringComparer.Ordinal)); } - /// The "Blocks deploy until resolved" column of guide 3.5, for slice 2a. + /// The "Blocks deploy until resolved" column of guide 3.5. private static bool IsBlocking(CollisionKind kind) { return kind switch @@ -728,7 +777,7 @@ CollisionKind.PluginOrderClash or CollisionKind.OrderAmbiguous } /// - /// The "Allowed resolutions" column of guide 3.5 for slice 2a, in declaration order. Remap is added by + /// The "Allowed resolutions" column of guide 3.5, in declaration order. Remap is added by /// (2r) and Gate comes with 2c; a SwitchBandConflict is settled by moving the band, never by a choice. /// private static IReadOnlyList AllowedFor(CollisionKind kind) @@ -748,7 +797,7 @@ CollisionKind.ValueClash or CollisionKind.DeleteVersusEdit or CollisionKind.Sequ } /// - /// The "Default" column of guide 3.5 for slice 2a. Only the order kinds and StateIdOverlap have one; a + /// The "Default" column of guide 3.5. Only the order kinds and StateIdOverlap have one; a /// BaseMismatch waits for the player to accept that mod (owner decision, 2026-11-12). /// private static ResolutionKind? DefaultFor(CollisionKind kind) diff --git a/RPGModder.Core/Merge/DataDiff.cs b/RPGModder.Core/Merge/DataDiff.cs index e117481..89b542f 100644 --- a/RPGModder.Core/Merge/DataDiff.cs +++ b/RPGModder.Core/Merge/DataDiff.cs @@ -12,6 +12,7 @@ internal sealed class DataDiff private readonly string _fileKey; private readonly string? _sourceFile; private readonly List _ops = new(); + private bool _mapResized; private DataDiff(string modId, string fileKey, string? sourceFile) { @@ -73,6 +74,7 @@ private void CompareRoot(JToken vanilla, JToken modded) /// private void CompareMap(JObject vanilla, JObject modded) { + _mapResized = RpgDataSchema.IsResized(vanilla, modded); JToken? vanillaEvents = vanilla[RpgDataSchema.EventsProperty]; if (!RpgDataSchema.IsEventList(vanillaEvents) || modded[RpgDataSchema.EventsProperty] is not JArray moddedEvents) { @@ -185,7 +187,7 @@ private void CompareArray(string record, string path, JArray vanilla, JArray mod case ArrayPolicy.Commands: Add(record, path, ChangeKind.EditCommands, modded); break; - case ArrayPolicy.Positional when vanilla.Count == modded.Count: + case ArrayPolicy.Positional when vanilla.Count == modded.Count && !IsResizedTiles(record, path): for (int index = 0; index < vanilla.Count; index++) { CompareValue(record, MergePath.Index(path, index), vanilla[index], modded[index]); @@ -196,12 +198,18 @@ private void CompareArray(string record, string path, JArray vanilla, JArray mod CompareKeyed(record, path, vanilla, modded); break; default: - // Atomic, and a Positional array whose length changed (one value until GR-K4 in 2b). + // Atomic, and a Positional array whose length changed or a resized map's tiles: one value, and + // GR-K4 clusters the map's size with it in Compose. Add(record, path, ChangeKind.SetLeaf, modded); break; } } + private bool IsResizedTiles(string record, string path) + { + return _mapResized && record == RecordKey.WholeFile && RpgDataSchema.IsTilesPath(path); + } + private void CompareKeyed(string record, string path, JArray vanilla, JArray modded) { int count = Math.Max(vanilla.Count, modded.Count); diff --git a/RPGModder.Core/Merge/ListMerge.cs b/RPGModder.Core/Merge/ListMerge.cs new file mode 100644 index 0000000..b5dd1be --- /dev/null +++ b/RPGModder.Core/Merge/ListMerge.cs @@ -0,0 +1,920 @@ +using Newtonsoft.Json.Linq; + +namespace RPGModder.Core.Merge; + +/// +/// The three-way merge of one list (guide 3.6): a command list as a tree (GR-T3 to GR-T7) and a Sequence list by +/// its elements (GR-T9). Each side is compared with vanilla on its own by a longest common subsequence, and every +/// side's changes are then laid on vanilla's items in one pass (GR-T4), never folded pair by pair. +/// +/// +/// A change is a hunk: a run of vanilla's items one side replaces, possibly with nothing, or a gap it inserts into. +/// Hunks of two sides overlap when they share a vanilla item, when an insert falls strictly inside the other's run, +/// or when both insert at one gap. An insert at the edge of another side's run does not overlap it and goes on its +/// own side of the run. Overlapping hunks form one unit, in vanilla order. +/// +internal static class ListMerge +{ + /// + /// The cells of the comparison table one alignment may use. Past it the items between the common start and end + /// are one change: the alignment only gets coarser, which can add a clash, never a wrong merge. + /// + internal const long MaxCells = 4_000_000; + + internal static ListMergeResult MergeCommands( + IReadOnlyList vanilla, + IReadOnlyList> sides, + ListPolicy policy) + { + ArgumentNullException.ThrowIfNull(vanilla); + ArgumentNullException.ThrowIfNull(sides); + ArgumentNullException.ThrowIfNull(policy); + + var context = new Context(policy); + List merged = new Merger(new CommandRules(context), context).Merge(vanilla, sides); + return context.Result(CommandTree.Flatten(merged)); + } + + internal static ListMergeResult MergeSequence( + IReadOnlyList vanilla, + IReadOnlyList> sides, + ListPolicy policy) + { + ArgumentNullException.ThrowIfNull(vanilla); + ArgumentNullException.ThrowIfNull(sides); + ArgumentNullException.ThrowIfNull(policy); + + var context = new Context(policy); + List merged = new Merger(new ElementRules(context), context).Merge(vanilla, sides); + return context.Result(new JArray(merged.Select(item => item.DeepClone()))); + } + + /// + /// The pairs of one longest common subsequence of and within the + /// given ranges, as absolute indexes in order. On a tie the left item is the one left out. + /// + internal static List<(int Left, int Right)> CommonPairs(int[] left, int leftStart, int leftEnd, int[] right, int rightStart, int rightEnd) + { + var pairs = new List<(int Left, int Right)>(); + while (leftStart < leftEnd && rightStart < rightEnd && left[leftStart] == right[rightStart]) + { + pairs.Add((leftStart, rightStart)); + leftStart++; + rightStart++; + } + + var tail = new List<(int Left, int Right)>(); + while (leftEnd > leftStart && rightEnd > rightStart && left[leftEnd - 1] == right[rightEnd - 1]) + { + leftEnd--; + rightEnd--; + tail.Add((leftEnd, rightEnd)); + } + + int rows = leftEnd - leftStart; + int columns = rightEnd - rightStart; + if (rows > 0 && columns > 0 && (long)(rows + 1) * (columns + 1) <= MaxCells) + { + // suffix[i, j] is the length for left[leftStart + i ..] and right[rightStart + j ..]. + var suffix = new int[rows + 1, columns + 1]; + for (int i = rows - 1; i >= 0; i--) + { + for (int j = columns - 1; j >= 0; j--) + { + suffix[i, j] = left[leftStart + i] == right[rightStart + j] + ? suffix[i + 1, j + 1] + 1 + : Math.Max(suffix[i + 1, j], suffix[i, j + 1]); + } + } + + int row = 0; + int column = 0; + while (row < rows && column < columns) + { + if (left[leftStart + row] == right[rightStart + column]) + { + pairs.Add((leftStart + row, rightStart + column)); + row++; + column++; + } + else if (suffix[row + 1, column] >= suffix[row, column + 1]) + { + row++; + } + else + { + column++; + } + } + } + + tail.Reverse(); + pairs.AddRange(tail); + return pairs; + } + + /// A copy whose object properties are in ordinal order at every depth, so equal values print alike. + private static JToken Sorted(JToken token) + { + return token switch + { + JObject item => new JObject(item.Properties() + .OrderBy(property => property.Name, StringComparer.Ordinal) + .Select(property => new JProperty(property.Name, Sorted(property.Value)))), + JArray list => new JArray(list.Select(Sorted)), + _ => token.DeepClone() + }; + } + + /// What one list merge gathers on its way, through every nested body. + private sealed class Context + { + private readonly Dictionary _keys = new(StringComparer.Ordinal); + + public Context(ListPolicy policy) + { + Policy = policy; + } + + public ListPolicy Policy { get; } + + public SortedSet ClashMods { get; } = new(StringComparer.Ordinal); + + public SortedSet OrderMods { get; } = new(StringComparer.Ordinal); + + public SortedSet Contributors { get; } = new(StringComparer.Ordinal); + + public JArray ClashPrint { get; } = new(); + + public JArray OrderPrint { get; } = new(); + + /// + /// Deep equality as a small number (GR-T3), so items compare as numbers. Property order does not count, as + /// for , which groups the variants of one place. + /// + public int KeyOf(JToken token) + { + string text = MergeJson.Write(Sorted(token)); + if (!_keys.TryGetValue(text, out int key)) + { + key = _keys.Count; + _keys.Add(text, key); + } + + return key; + } + + public ListMergeResult Result(JArray list) + { + return new ListMergeResult( + list, + ClashMods.ToList(), + OrderMods.ToList(), + Contributors.ToList(), + MergeJson.Sha256Hex(MergeJson.Write(ClashPrint)), + MergeJson.Sha256Hex(MergeJson.Write(OrderPrint))); + } + } + + /// How the items of one kind of list compare, print and, for commands, merge inside. + private abstract class Rules + { + protected Rules(Context context) + { + Context = context; + } + + protected Context Context { get; } + + /// Deep equality as a number (GR-T3). + public abstract int Key(T item); + + /// Whether two items with one head can be merged inside, so a changed item is paired by its head. + public virtual bool HasHeads => false; + + /// The head as a number; only asked when is true. + public virtual int Head(T item) + { + throw new NotSupportedException(); + } + + public abstract JArray Print(IEnumerable items); + + /// + /// The key of the item and, for a command, of every node in its bodies but the ends, each with its depth below + /// . + /// + public virtual IEnumerable<(int Key, int Depth)> Nested(T item, int depth) + { + yield return (Key(item), depth); + } + + /// + /// The keys of the items, nested ones too, that holds fewer times at some depth than + /// , and those it holds more times. A node moved to another depth is in both, so a + /// copy put deeper never hides one taken away. + /// + public (HashSet Removed, HashSet Added) Change(IEnumerable vanilla, IEnumerable side) + { + var change = new Dictionary<(int Key, int Depth), int>(); + foreach ((int Key, int Depth) item in vanilla.SelectMany(item => Nested(item, 0))) + { + change[item] = change.GetValueOrDefault(item) - 1; + } + + foreach ((int Key, int Depth) item in side.SelectMany(item => Nested(item, 0))) + { + change[item] = change.GetValueOrDefault(item) + 1; + } + + return ( + change.Where(entry => entry.Value < 0).Select(entry => entry.Key.Key).ToHashSet(), + change.Where(entry => entry.Value > 0).Select(entry => entry.Key.Key).ToHashSet()); + } + + /// + /// GR-T6: merges the changes every side made inside one vanilla item whose head it kept. False when the + /// changes clash at the item itself, before anything below it was merged. + /// + public virtual bool TryMergeInside(T vanilla, IReadOnlyList<(ListSide Side, T Item)> sides, out T merged) + { + merged = vanilla; + return false; + } + } + + private sealed class ElementRules : Rules + { + public ElementRules(Context context) + : base(context) + { + } + + public override int Key(JToken item) + { + return Context.KeyOf(item); + } + + public override JArray Print(IEnumerable items) + { + return new JArray(items.Select(Sorted)); + } + } + + private sealed class CommandRules : Rules + { + private const int Missing = -1; + + private readonly Dictionary _nodeKeys = new(ReferenceEqualityComparer.Instance); + + public CommandRules(Context context) + : base(context) + { + } + + public override int Key(CommandNode item) + { + if (!_nodeKeys.TryGetValue(item, out int key)) + { + key = Context.KeyOf(CommandTree.Flatten(item, 0)); + _nodeKeys.Add(item, key); + } + + return key; + } + + public override bool HasHeads => true; + + public override int Head(CommandNode item) + { + return Context.KeyOf(item.Head); + } + + /// A key is the node at depth 0, so a node keeps its key at any depth and a move between bodies shows. + public override IEnumerable<(int Key, int Depth)> Nested(CommandNode item, int depth) + { + yield return (Key(item), depth); + foreach (CommandNode node in item.Branches.SelectMany(branch => branch.Body).Where(node => !CommandTree.IsEnd(node))) + { + foreach ((int Key, int Depth) inner in Nested(node, depth + 1)) + { + yield return inner; + } + } + } + + public override JArray Print(IEnumerable items) + { + return new JArray(CommandTree.Flatten(items.ToList()).Select(Sorted)); + } + + public override bool TryMergeInside( + CommandNode vanilla, + IReadOnlyList<(ListSide Side, CommandNode Item)> sides, + out CommandNode merged) + { + merged = vanilla; + + // A side that reshaped the branches, or moved a node from one of them into another, changed the whole node, + // and the continuations are one value (GR-T6). + if (!sides.All(side => SameShape(vanilla, side.Item)) || + sides.Any(side => MovedAcross(vanilla, side.Item)) || + !TryPick(Lines(vanilla), sides.Select(side => Lines(side.Item)).ToList(), out int lines)) + { + return false; + } + + var markers = new List(); + for (int index = 0; index < vanilla.Branches.Count; index++) + { + int branch = index; + if (!TryPick(Single(vanilla.Branches[branch].Marker), sides.Select(side => Single(side.Item.Branches[branch].Marker)).ToList(), out int marker)) + { + return false; + } + + markers.Add(marker); + } + + if (!TryPick(Single(vanilla.End), sides.Select(side => Single(side.Item.End)).ToList(), out int end)) + { + return false; + } + + // Nothing clashes at the node itself, so its parts are taken and its bodies merged. + IReadOnlyList continuations = Taken(lines, sides, vanilla, item => item.Continuations, Lines); + var branches = new List(); + for (int index = 0; index < vanilla.Branches.Count; index++) + { + int branch = index; + JObject? marker = Taken(markers[branch], sides, vanilla, item => item.Branches[branch].Marker, item => Single(item.Branches[branch].Marker)); + List> bodies = sides + .Select(side => new ListSide(side.Item.Branches[branch].Body, side.Side.ModIds)) + .ToList(); + List body = new Merger(this, Context).Merge(vanilla.Branches[branch].Body, bodies); + branches.Add(new CommandBranch(marker, body)); + } + + JObject? endMarker = Taken(end, sides, vanilla, item => item.End, item => Single(item.End)); + merged = new CommandNode(vanilla.Head, continuations, branches, endMarker); + return true; + } + + /// + /// The side whose value of one part is taken, or when no side changed it. False when + /// two sides changed it in different ways. + /// + private static bool TryPick(int vanilla, List values, out int winner) + { + winner = Missing; + for (int index = 0; index < values.Count; index++) + { + if (values[index] == vanilla) + { + continue; + } + + if (winner != Missing && values[winner] != values[index]) + { + return false; + } + + if (winner == Missing) + { + winner = index; + } + } + + return true; + } + + private TPart Taken( + int winner, + IReadOnlyList<(ListSide Side, CommandNode Item)> sides, + CommandNode vanilla, + Func part, + Func key) + { + if (winner == Missing) + { + return part(vanilla); + } + + Contribute(winner, sides, key); + return part(sides[winner].Item); + } + + /// Every side that holds the winning value contributed it. + private void Contribute(int winner, IReadOnlyList<(ListSide Side, CommandNode Item)> sides, Func key) + { + if (winner == Missing) + { + return; + } + + int value = key(sides[winner].Item); + foreach ((ListSide side, CommandNode item) in sides) + { + if (key(item) == value) + { + Context.Contributors.UnionWith(side.ModIds); + } + } + } + + private static bool SameShape(CommandNode vanilla, CommandNode side) + { + if (side.Branches.Count != vanilla.Branches.Count || (side.End is null) != (vanilla.End is null)) + { + return false; + } + + for (int index = 0; index < vanilla.Branches.Count; index++) + { + if (!JToken.DeepEquals(MarkerCode(vanilla.Branches[index].Marker), MarkerCode(side.Branches[index].Marker))) + { + return false; + } + } + + return true; + } + + /// A node, at any depth, the side removed from one branch and added to another. Asked of one shape only. + private bool MovedAcross(CommandNode vanilla, CommandNode side) + { + List<(HashSet Removed, HashSet Added)> changes = Enumerable.Range(0, vanilla.Branches.Count) + .Select(index => Change(vanilla.Branches[index].Body, side.Branches[index].Body)) + .ToList(); + for (int from = 0; from < changes.Count; from++) + { + for (int to = 0; to < changes.Count; to++) + { + if (from != to && changes[from].Removed.Overlaps(changes[to].Added)) + { + return true; + } + } + } + + return false; + } + + private static JToken? MarkerCode(JObject? marker) + { + return marker?.Property("code", StringComparison.Ordinal)?.Value; + } + + private int Lines(CommandNode node) + { + return Context.KeyOf(new JArray(node.Continuations)); + } + + private int Single(JObject? command) + { + return command is null ? Missing : Context.KeyOf(command); + } + } + + /// A run of vanilla items one side replaces, or a gap it inserts into when Start equals End. + private readonly record struct Hunk(int Side, int Start, int End, int SideStart, int SideEnd, bool Inside); + + private sealed record Unit(List Hunks, int Start, int End); + + private sealed class Merger + { + private readonly Rules _rules; + private readonly Context _context; + + public Merger(Rules rules, Context context) + { + _rules = rules; + _context = context; + } + + public List Merge(IReadOnlyList vanilla, IReadOnlyList> sides) + { + int[] vanillaKeys = vanilla.Select(_rules.Key).ToArray(); + int[]? vanillaHeads = Heads(vanilla); + var hunks = new List(); + for (int side = 0; side < sides.Count; side++) + { + hunks.AddRange(Diff(side, vanilla, vanillaKeys, vanillaHeads, sides[side].Items)); + } + + var merged = new List(); + int position = 0; + foreach (Unit unit in Units(hunks)) + { + for (; position < unit.Start; position++) + { + merged.Add(vanilla[position]); + } + + merged.AddRange(Resolve(unit, vanilla, sides)); + position = unit.End; + } + + for (; position < vanilla.Count; position++) + { + merged.Add(vanilla[position]); + } + + return merged; + } + + private int[]? Heads(IReadOnlyList items) + { + return _rules.HasHeads ? items.Select(_rules.Head).ToArray() : null; + } + + /// + /// One side's hunks. Within each run the common subsequence left unmatched, items with one head are paired + /// again, so a changed node is a change of its own and not part of a larger run (GR-T3). + /// + private List Diff(int side, IReadOnlyList vanilla, int[] vanillaKeys, int[]? vanillaHeads, IReadOnlyList items) + { + int[] keys = items.Select(_rules.Key).ToArray(); + int[]? heads = Heads(items); + var hunks = new List(); + int vanillaAt = 0; + int sideAt = 0; + foreach ((int left, int right) in CommonPairs(vanillaKeys, 0, vanillaKeys.Length, keys, 0, keys.Length).Append((vanillaKeys.Length, keys.Length))) + { + if (left > vanillaAt || right > sideAt) + { + Region(side, vanillaAt, left, sideAt, right, vanillaHeads, heads, hunks); + } + + vanillaAt = left + 1; + sideAt = right + 1; + } + + return JoinMoves(hunks, vanilla, items); + } + + private static void Region(int side, int start, int end, int sideStart, int sideEnd, int[]? vanillaHeads, int[]? heads, List hunks) + { + if (vanillaHeads is null || heads is null) + { + hunks.Add(new Hunk(side, start, end, sideStart, sideEnd, false)); + return; + } + + // A head pairs a changed node only when it names one node of the run on each side. Two nodes of one head, + // as two Show Text with one face, would be paired by a guess, so such a run stays one change. + var counts = new Dictionary(); + for (int index = start; index < end; index++) + { + (int Vanilla, int Side) count = counts.GetValueOrDefault(vanillaHeads[index]); + counts[vanillaHeads[index]] = (count.Vanilla + 1, count.Side); + } + + for (int index = sideStart; index < sideEnd; index++) + { + (int Vanilla, int Side) count = counts.GetValueOrDefault(heads[index]); + counts[heads[index]] = (count.Vanilla, count.Side + 1); + } + + // A repeated head becomes a negative number of its own, odd for vanilla and even for the side, so it pairs nothing. + int[] left = Enumerable.Range(start, end - start) + .Select(index => Pairable(counts[vanillaHeads[index]]) ? vanillaHeads[index] : -1 - (2 * index)) + .ToArray(); + int[] right = Enumerable.Range(sideStart, sideEnd - sideStart) + .Select(index => Pairable(counts[heads[index]]) ? heads[index] : -2 - (2 * index)) + .ToArray(); + + int vanillaAt = start; + int sideAt = sideStart; + foreach ((int pairLeft, int pairRight) in CommonPairs(left, 0, left.Length, right, 0, right.Length)) + { + int at = start + pairLeft; + int sideOf = sideStart + pairRight; + if (at > vanillaAt || sideOf > sideAt) + { + hunks.Add(new Hunk(side, vanillaAt, at, sideAt, sideOf, false)); + } + + hunks.Add(new Hunk(side, at, at + 1, sideOf, sideOf + 1, true)); + vanillaAt = at + 1; + sideAt = sideOf + 1; + } + + if (end > vanillaAt || sideEnd > sideAt) + { + hunks.Add(new Hunk(side, vanillaAt, end, sideAt, sideEnd, false)); + } + } + + private static bool Pairable((int Vanilla, int Side) count) + { + return count.Vanilla <= 1 && count.Side <= 1; + } + + /// + /// A side that removes an item and puts an equal one elsewhere moved it. Every hunk from the one place to the + /// other becomes one run, so the move clashes with what another side did in between, and never half applies. + /// A node changed in place into a copy of one the side removed counts too: its head paired it, but it moved. So + /// does a node moved into or out of another one's body, at any depth: the run reaches the node that holds it. + /// + private List JoinMoves(List hunks, IReadOnlyList vanilla, IReadOnlyList items) + { + var removed = new Dictionary(); + var added = new Dictionary(); + for (int index = 0; index < hunks.Count; index++) + { + Hunk hunk = hunks[index]; + (HashSet gone, HashSet put) = _rules.Change(Slice(vanilla, hunk.Start, hunk.End), Slice(items, hunk.SideStart, hunk.SideEnd)); + foreach (int key in gone) + { + removed[key] = Widen(removed, key, index); + } + + foreach (int key in put) + { + added[key] = Widen(added, key, index); + } + } + + List<(int First, int Last)> spans = removed + .Where(entry => added.ContainsKey(entry.Key)) + .Select(entry => (First: Math.Min(entry.Value.First, added[entry.Key].First), Last: Math.Max(entry.Value.Last, added[entry.Key].Last))) + .Where(span => span.First < span.Last) + .OrderBy(span => span.First) + .ToList(); + if (spans.Count == 0) + { + return hunks; + } + + var joined = new List(); + int next = 0; + int spanAt = 0; + while (next < hunks.Count) + { + if (spanAt < spans.Count && spans[spanAt].First == next) + { + int last = spans[spanAt].Last; + for (spanAt++; spanAt < spans.Count && spans[spanAt].First <= last; spanAt++) + { + last = Math.Max(last, spans[spanAt].Last); + } + + joined.Add(hunks[next] with { End = hunks[last].End, SideEnd = hunks[last].SideEnd, Inside = false }); + next = last + 1; + } + else + { + joined.Add(hunks[next++]); + } + } + + return joined; + } + + private static (int First, int Last) Widen(Dictionary places, int key, int index) + { + return places.TryGetValue(key, out (int First, int Last) place) ? (Math.Min(place.First, index), Math.Max(place.Last, index)) : (index, index); + } + + /// The hunks joined by overlap, as units in vanilla order; an insert unit comes before a run that starts at its gap. + private static List Units(List hunks) + { + List order = Enumerable.Range(0, hunks.Count) + .OrderBy(index => hunks[index].Start) + .ThenBy(index => hunks[index].End) + .ThenBy(index => hunks[index].Side) + .ToList(); + int[] parent = Enumerable.Range(0, hunks.Count).ToArray(); + + int Find(int index) + { + while (parent[index] != index) + { + parent[index] = parent[parent[index]]; + index = parent[index]; + } + + return index; + } + + for (int first = 0; first < order.Count; first++) + { + Hunk left = hunks[order[first]]; + for (int second = first + 1; second < order.Count && hunks[order[second]].Start <= left.End; second++) + { + Hunk right = hunks[order[second]]; + if (left.Side != right.Side && Overlap(left, right)) + { + parent[Find(order[second])] = Find(order[first]); + } + } + } + + return order + .GroupBy(Find) + .Select(group => group.Select(index => hunks[index]).ToList()) + .Select(members => new Unit(members, members.Min(hunk => hunk.Start), members.Max(hunk => hunk.End))) + .OrderBy(unit => unit.Start) + .ThenBy(unit => unit.End) + .ToList(); + } + + private static bool Overlap(Hunk left, Hunk right) + { + bool leftGap = left.Start == left.End; + bool rightGap = right.Start == right.End; + if (leftGap && rightGap) + { + return left.Start == right.Start; + } + + if (leftGap) + { + return right.Start < left.Start && left.Start < right.End; + } + + if (rightGap) + { + return left.Start < right.Start && right.Start < left.End; + } + + return left.Start < right.End && right.Start < left.End; + } + + private List Resolve(Unit unit, IReadOnlyList vanilla, IReadOnlyList> sides) + { + List versions = Versions(unit, vanilla, sides); + if (unit.Start == unit.End) + { + versions = Folded(versions); + } + + if (versions.Count == 1) + { + // GR-T5: one side changed this run, or several changed it the same way. + Contribute(versions[0], sides); + return versions[0].Items; + } + + if (unit.Start == unit.End) + { + return Ordered(versions, sides); + } + + if (unit.Hunks.All(hunk => hunk.Inside && hunk.Start == unit.Start) && + _rules.TryMergeInside(vanilla[unit.Start], unit.Hunks.Select(hunk => (sides[hunk.Side], sides[hunk.Side].Items[hunk.SideStart])).ToList(), out T merged)) + { + return [merged]; + } + + return Clash(unit, vanilla, versions, sides); + } + + /// + /// Inserts at one gap that another side's inserts there hold in order: that side's longer run is taken once, + /// with the mods of both, so a shared part is never doubled. + /// + private static List Folded(List versions) + { + List longest = versions + .Where(version => !versions.Any(other => other != version && Within(version.Keys, other.Keys))) + .ToList(); + foreach (Version version in versions.Except(longest)) + { + foreach (Version holder in longest.Where(item => Within(version.Keys, item.Keys))) + { + holder.Sides.AddRange(version.Sides); + } + } + + return longest; + } + + /// Whether is a subsequence of . + private static bool Within(int[] part, int[] whole) + { + int at = 0; + foreach (int key in whole) + { + if (at < part.Length && part[at] == key) + { + at++; + } + } + + return at == part.Length; + } + + /// GR-T7: inserts at one gap, distinct ones in profile order, or the chosen mod's first. + private List Ordered(List versions, IReadOnlyList> sides) + { + string? first = _context.Policy.FirstMod; + var print = new JArray(); + var items = new List(); + foreach (Version version in versions + .OrderBy(item => first is not null && item.Sides.Any(side => sides[side].ModIds.Contains(first, StringComparer.Ordinal)) ? 0 : 1) + .ThenBy(item => item.Sides.Min())) + { + Contribute(version, sides); + _context.OrderMods.UnionWith(Mods(version, sides)); + items.AddRange(version.Items); + } + + foreach (Version version in ByMods(versions, sides)) + { + print.Add(new JArray(new JArray(Mods(version, sides).ToArray()), _rules.Print(version.Items))); + } + + _context.OrderPrint.Add(print); + return items; + } + + /// GR-T6: a run the sides changed in different ways. The policy picks one version of it. + private List Clash(Unit unit, IReadOnlyList vanilla, List versions, IReadOnlyList> sides) + { + List original = Slice(vanilla, unit.Start, unit.End); + var print = new JArray(_rules.Print(original)); + foreach (Version version in ByMods(versions, sides)) + { + _context.ClashMods.UnionWith(Mods(version, sides)); + print.Add(new JArray(new JArray(Mods(version, sides).ToArray()), _rules.Print(version.Items))); + } + + _context.ClashPrint.Add(print); + + string? mod = _context.Policy.Clash == ResolutionKind.PickMod ? _context.Policy.ClashMod : null; + Version? picked = mod is null + ? null + : versions.FirstOrDefault(version => version.Sides.Any(side => sides[side].ModIds.Contains(mod, StringComparer.Ordinal))); + if (picked is null) + { + // Vanilla's run: the choice, a mod that left this run alone, or a placeholder while unresolved. + return original; + } + + Contribute(picked, sides); + return picked.Items; + } + + /// Each involved side's version of the unit's run, equal ones as one, in side order. + private List Versions(Unit unit, IReadOnlyList vanilla, IReadOnlyList> sides) + { + var versions = new List(); + foreach (IGrouping side in unit.Hunks.GroupBy(hunk => hunk.Side).OrderBy(group => group.Key)) + { + var items = new List(); + int position = unit.Start; + foreach (Hunk hunk in side.OrderBy(item => item.Start).ThenBy(item => item.End)) + { + items.AddRange(Slice(vanilla, position, hunk.Start)); + items.AddRange(Slice(sides[side.Key].Items, hunk.SideStart, hunk.SideEnd)); + position = hunk.End; + } + + items.AddRange(Slice(vanilla, position, unit.End)); + int[] keys = items.Select(_rules.Key).ToArray(); + Version? same = versions.FirstOrDefault(version => version.Keys.SequenceEqual(keys)); + if (same is null) + { + versions.Add(new Version(items, keys, [side.Key])); + } + else + { + same.Sides.Add(side.Key); + } + } + + return versions; + } + + private void Contribute(Version version, IReadOnlyList> sides) + { + _context.Contributors.UnionWith(Mods(version, sides)); + } + + private static IEnumerable Mods(Version version, IReadOnlyList> sides) + { + return version.Sides.SelectMany(side => sides[side].ModIds).Distinct().Order(StringComparer.Ordinal); + } + + /// The versions by their mods, for a fingerprint that a change of profile order keeps (GR-X2). + private static IEnumerable ByMods(List versions, IReadOnlyList> sides) + { + return versions.OrderBy(version => string.Join('\n', Mods(version, sides)), StringComparer.Ordinal); + } + + private static List Slice(IReadOnlyList items, int start, int end) + { + var slice = new List(Math.Max(0, end - start)); + for (int index = start; index < end; index++) + { + slice.Add(items[index]); + } + + return slice; + } + + private sealed record Version(List Items, int[] Keys, List Sides); + } +} diff --git a/RPGModder.Core/Merge/ListMergeResult.cs b/RPGModder.Core/Merge/ListMergeResult.cs new file mode 100644 index 0000000..a192bd8 --- /dev/null +++ b/RPGModder.Core/Merge/ListMergeResult.cs @@ -0,0 +1,17 @@ +using Newtonsoft.Json.Linq; + +namespace RPGModder.Core.Merge; + +/// +/// The outcome of one list merge. List is the merged value; while the clash is unresolved its clashing runs +/// hold vanilla's version, and the caller does not apply it. ClashMods and OrderMods are the mods of +/// the clashing runs and of the ambiguous gaps, Contributors the mods whose changes are in List, all +/// sorted. The two fingerprints hash the versions of the runs and of the gaps (GR-X2). +/// +internal sealed record ListMergeResult( + JArray List, + IReadOnlyList ClashMods, + IReadOnlyList OrderMods, + IReadOnlyList Contributors, + string ClashFingerprint, + string OrderFingerprint); diff --git a/RPGModder.Core/Merge/ListPolicy.cs b/RPGModder.Core/Merge/ListPolicy.cs new file mode 100644 index 0000000..56ab349 --- /dev/null +++ b/RPGModder.Core/Merge/ListPolicy.cs @@ -0,0 +1,15 @@ +namespace RPGModder.Core.Merge; + +/// +/// The choices a list merge carries out (seam 11.5). Clash is null while the list's clash is +/// unresolved, to keep vanilla's version of every clashing run, or +/// to take ClashMod's version of each. FirstMod puts that mod's +/// inserts first in every ambiguous gap; null keeps profile order. +/// +internal sealed record ListPolicy( + ResolutionKind? Clash, + string? ClashMod, + string? FirstMod) +{ + public static ListPolicy Unresolved { get; } = new(null, null, null); +} diff --git a/RPGModder.Core/Merge/ListSide.cs b/RPGModder.Core/Merge/ListSide.cs new file mode 100644 index 0000000..94639f2 --- /dev/null +++ b/RPGModder.Core/Merge/ListSide.cs @@ -0,0 +1,9 @@ +namespace RPGModder.Core.Merge; + +/// +/// One version of a list in a three-way merge: the items of one op variant and every mod that holds it. The sides of +/// one merge are given in profile order, which orders the inserts of an OrderAmbiguous gap (GR-T7). +/// +internal sealed record ListSide( + IReadOnlyList Items, + IReadOnlyList ModIds); diff --git a/RPGModder.Core/Merge/MergedOp.cs b/RPGModder.Core/Merge/MergedOp.cs index 70c7288..45aee19 100644 --- a/RPGModder.Core/Merge/MergedOp.cs +++ b/RPGModder.Core/Merge/MergedOp.cs @@ -1,8 +1,9 @@ namespace RPGModder.Core.Merge; /// -/// An op that survives composition. Op is the contribution of the mod whose id sorts first; -/// ModIds lists every mod that contributed an equal op, sorted (GR-C8). +/// An op that survives composition. Op is the contribution of the mod whose id sorts first, and for a list +/// several mods edit, that mod's op holding the merged list (seam 11.5). ModIds lists every mod that +/// contributed, sorted (GR-C8). /// public sealed record MergedOp( ChangeOp Op, diff --git a/RPGModder.Core/Merge/RpgDataSchema.cs b/RPGModder.Core/Merge/RpgDataSchema.cs index 3460f57..e8fe3c0 100644 --- a/RPGModder.Core/Merge/RpgDataSchema.cs +++ b/RPGModder.Core/Merge/RpgDataSchema.cs @@ -85,6 +85,9 @@ public static class RpgDataSchema private const string IdProperty = "id"; private const string PagesPath = "pages"; + private const string TilesPath = "data"; + private const string WidthPath = "width"; + private const string HeightPath = "height"; private static readonly HashSet ConfigSaveNames = new(StringComparer.Ordinal) { @@ -509,6 +512,31 @@ internal static bool IsPageSetting(RecordKey key, string path) return segments.Count < 3 || segments[1].Name is not null || segments[2].Name != "list"; } + /// + /// GR-K4: the list a map's width or height lays out, its tiles at data, or null for any + /// other place. + /// + internal static string? ResizedListOf(RecordKey key, string path) + { + return IsMapFile(key.File) && key.IsWholeFile && (path == WidthPath || path == HeightPath) ? TilesPath : null; + } + + /// + /// GR-K4: whether a map's width or height differs from vanilla's. Then every tile index means + /// another place, even when the count of tiles is the same, so the tiles are one value. + /// + internal static bool IsResized(JObject vanillaMap, JObject moddedMap) + { + return !JToken.DeepEquals(vanillaMap[WidthPath], moddedMap[WidthPath]) || + !JToken.DeepEquals(vanillaMap[HeightPath], moddedMap[HeightPath]); + } + + /// The map-level path of a map's tiles. + internal static bool IsTilesPath(string path) + { + return path == TilesPath; + } + /// The config save forms 2a decodes. Only files are asked. internal static bool IsDecodedConfigSave(string fileKey) { diff --git a/RPGModder.Tests/Merge/CommandListKit.cs b/RPGModder.Tests/Merge/CommandListKit.cs new file mode 100644 index 0000000..230b846 --- /dev/null +++ b/RPGModder.Tests/Merge/CommandListKit.cs @@ -0,0 +1,38 @@ +using Newtonsoft.Json.Linq; + +namespace RPGModder.Tests.Merge; + +/// Builders for command lists in the editor's form. Codes are the engine's; parameters are invented (TST-2). +internal static class CommandListKit +{ + public static JObject Cmd(int code, int indent, params object[] parameters) + { + return new JObject + { + ["code"] = code, + ["indent"] = indent, + ["parameters"] = new JArray(parameters) + }; + } + + public static JObject End(int indent) + { + return Cmd(0, indent); + } + + /// Wait, a command with no lines or bodies; the frame count tells waits apart. + public static JObject Wait(int indent, int frames) + { + return Cmd(230, indent, frames); + } + + public static JArray List(params JObject[] commands) + { + return new JArray(commands.Select(command => command.DeepClone())); + } + + public static string Text(JToken token) + { + return token.ToString(Newtonsoft.Json.Formatting.None); + } +} diff --git a/RPGModder.Tests/Merge/CommandTreeTests.cs b/RPGModder.Tests/Merge/CommandTreeTests.cs new file mode 100644 index 0000000..ba9d323 --- /dev/null +++ b/RPGModder.Tests/Merge/CommandTreeTests.cs @@ -0,0 +1,168 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using static RPGModder.Tests.Merge.CommandListKit; + +namespace RPGModder.Tests.Merge; + +public sealed class CommandTreeTests +{ + [Fact] + public void Parse_TerminatorOnly_GivesOneEndNode() + { + IReadOnlyList nodes = CommandTree.Parse(List(End(0)))!; + + CommandNode node = Assert.Single(nodes); + Assert.True(CommandTree.IsEnd(node)); + Assert.Empty(node.Continuations); + Assert.Empty(node.Branches); + Assert.Null(node.End); + } + + [Fact] + public void Parse_ShowTextWithLines_KeepsTheLinesWithTheirHead() + { + IReadOnlyList nodes = CommandTree.Parse(List(Cmd(101, 0, "", 0, 0, 2), Cmd(401, 0, "One"), Cmd(401, 0, "Two"), Wait(0, 5), End(0)))!; + + Assert.Equal(3, nodes.Count); + Assert.Equal(["One", "Two"], nodes[0].Continuations.Select(line => (string)line["parameters"]![0]!)); + Assert.Empty(nodes[1].Continuations); + } + + [Fact] + public void Parse_ConditionalBranchWithElse_HasTwoBodiesAndItsEnd() + { + JArray list = List(Cmd(111, 0, 0, 1, 0), Wait(1, 1), End(1), Cmd(411, 0), Wait(1, 2), End(1), Cmd(412, 0), End(0)); + + CommandNode branch = CommandTree.Parse(list)![0]; + + Assert.Equal(2, branch.Branches.Count); + Assert.Null(branch.Branches[0].Marker); + Assert.Equal(411, (int)branch.Branches[1].Marker!["code"]!); + Assert.Equal(2, branch.Branches[1].Body.Count); + Assert.Equal(412, (int)branch.End!["code"]!); + } + + [Fact] + public void Parse_ShowChoices_HasOneBodyPerChoiceAndCancel() + { + JArray list = List( + Cmd(102, 0, new JArray("Yes", "No"), 1, 0, 2, 0), + Cmd(402, 0, 0, "Yes"), End(1), + Cmd(402, 0, 1, "No"), Wait(1, 3), End(1), + Cmd(403, 0, 6), End(1), + Cmd(404, 0), + End(0)); + + CommandNode choices = CommandTree.Parse(list)![0]; + + Assert.Equal([402, 402, 403], choices.Branches.Select(item => (int)item.Marker!["code"]!)); + Assert.Equal(404, (int)choices.End!["code"]!); + } + + [Fact] + public void Parse_Loop_HasOneUnmarkedBodyAndRepeatAbove() + { + CommandNode loop = CommandTree.Parse(List(Cmd(112, 0), Cmd(113, 1), End(1), Cmd(413, 0), End(0)))![0]; + + CommandBranch body = Assert.Single(loop.Branches); + Assert.Null(body.Marker); + Assert.Equal(413, (int)loop.End!["code"]!); + } + + [Fact] + public void Parse_BattleWithoutEscapeOrLose_HasNoBodies() + { + CommandNode battle = CommandTree.Parse(List(Cmd(301, 0, 0, 1, false, false), Wait(0, 1), End(0)))![0]; + + Assert.Empty(battle.Branches); + Assert.Null(battle.End); + } + + [Fact] + public void Parse_BattleWithBranches_HasABodyPerOutcome() + { + JArray list = List(Cmd(301, 0, 0, 1, true, true), Cmd(601, 0), End(1), Cmd(602, 0), End(1), Cmd(603, 0), End(1), Cmd(604, 0), End(0)); + + CommandNode battle = CommandTree.Parse(list)![0]; + + Assert.Equal([601, 602, 603], battle.Branches.Select(item => (int)item.Marker!["code"]!)); + Assert.Equal(604, (int)battle.End!["code"]!); + } + + [Fact] + public void Parse_UnknownCodeWithDeeperCommands_HoldsOneUnmarkedBody() + { + CommandNode node = CommandTree.Parse(List(Cmd(999, 0), Wait(1, 1), End(1), End(0)))![0]; + + CommandBranch body = Assert.Single(node.Branches); + Assert.Null(body.Marker); + Assert.Null(node.End); + Assert.Equal(2, body.Body.Count); + } + + public static TheoryData Malformed => new() + { + { "empty", "[]" }, + { "no final terminator", "[{\"code\":230,\"indent\":0,\"parameters\":[1]}]" }, + { "command after the final terminator", "[{\"code\":0,\"indent\":0,\"parameters\":[]},{\"code\":230,\"indent\":0,\"parameters\":[1]}]" }, + { "line without its head", "[{\"code\":401,\"indent\":0,\"parameters\":[\"x\"]},{\"code\":0,\"indent\":0,\"parameters\":[]}]" }, + { "else without its branch", "[{\"code\":411,\"indent\":0,\"parameters\":[]},{\"code\":0,\"indent\":1,\"parameters\":[]},{\"code\":0,\"indent\":0,\"parameters\":[]}]" }, + { "branch without its end", "[{\"code\":111,\"indent\":0,\"parameters\":[]},{\"code\":0,\"indent\":1,\"parameters\":[]},{\"code\":0,\"indent\":0,\"parameters\":[]}]" }, + { "loop without repeat above", "[{\"code\":112,\"indent\":0,\"parameters\":[]},{\"code\":0,\"indent\":1,\"parameters\":[]},{\"code\":0,\"indent\":0,\"parameters\":[]}]" }, + { "body without its terminator", "[{\"code\":112,\"indent\":0,\"parameters\":[]},{\"code\":230,\"indent\":1,\"parameters\":[1]},{\"code\":413,\"indent\":0,\"parameters\":[]},{\"code\":0,\"indent\":0,\"parameters\":[]}]" }, + { "indent step of two", "[{\"code\":999,\"indent\":0,\"parameters\":[]},{\"code\":0,\"indent\":2,\"parameters\":[]},{\"code\":0,\"indent\":0,\"parameters\":[]}]" }, + { "no indent", "[{\"code\":0}]" }, + { "code as text", "[{\"code\":\"0\",\"indent\":0,\"parameters\":[]}]" }, + { "fractional indent", "[{\"code\":0,\"indent\":0.5,\"parameters\":[]}]" }, + { "command that is not an object", "[0]" } + }; + + [Theory] + [MemberData(nameof(Malformed))] + public void Parse_MalformedList_IsNull(string reason, string json) + { + Assert.True(CommandTree.Parse(JArray.Parse(json)) is null, reason); + Assert.False(CommandTree.Validate(JArray.Parse(json)), reason); + } + + [Theory] + [InlineData(CommandTree.MaxDepth, true)] + [InlineData(CommandTree.MaxDepth + 1, false)] + public void Parse_NestedBodies_StopAtTheDepthBound(int depth, bool parses) + { + var list = new JArray(); + for (int level = 0; level < depth; level++) + { + list.Add(Cmd(999, level)); + } + + for (int level = depth; level >= 0; level--) + { + list.Add(End(level)); + } + + Assert.Equal(parses, CommandTree.Parse(list) is not null); + } + + [Fact] + public void Flatten_ParsedList_GivesTheListBack() + { + JArray list = List( + Cmd(101, 0, "", 0, 0, 2), Cmd(401, 0, "Hello"), + Cmd(111, 0, 0, 1, 0), Cmd(112, 1), Wait(2, 1), End(2), Cmd(413, 1), End(1), Cmd(411, 0), End(1), Cmd(412, 0), + End(0)); + + Assert.True(JToken.DeepEquals(list, CommandTree.Flatten(CommandTree.Parse(list)!))); + } + + [Fact] + public void Flatten_NodeFromADeeperBody_TakesTheIndentOfItsNewPlace() + { + CommandNode inner = CommandTree.Parse(List(Cmd(112, 0), Wait(1, 4), End(1), Cmd(413, 0), End(0)))![0].Branches[0].Body[0]; + + JArray flat = CommandTree.Flatten(inner, 3); + + Assert.Equal(3, (int)Assert.Single(flat)["indent"]!); + Assert.Equal(1, (int)inner.Head["indent"]!); + } +} diff --git a/RPGModder.Tests/Merge/ComposerTests.cs b/RPGModder.Tests/Merge/ComposerTests.cs index 588b13d..92e04e3 100644 --- a/RPGModder.Tests/Merge/ComposerTests.cs +++ b/RPGModder.Tests/Merge/ComposerTests.cs @@ -134,7 +134,8 @@ public void DifferentSequences_AreASequenceClash_AndDifferentCommandLists_ALogic { ModSource Effects(string modId, int code) { - return FileMod(modId, Items, EditItems(items => items[2]!["effects"] = new JArray(new JObject { ["code"] = code }))); + // Both mods replace the one vanilla effect, so the change is one run the two make differently. + return FileMod(modId, Items, EditItems(items => items[1]!["effects"] = new JArray(new JObject { ["code"] = code }))); } const string events = "[null,{\"id\":1,\"list\":[{\"code\":0}]}]"; diff --git a/RPGModder.Tests/Merge/ListComposeTests.cs b/RPGModder.Tests/Merge/ListComposeTests.cs new file mode 100644 index 0000000..1506371 --- /dev/null +++ b/RPGModder.Tests/Merge/ListComposeTests.cs @@ -0,0 +1,315 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using static RPGModder.Tests.Merge.CommandListKit; +using static RPGModder.Tests.Merge.MergeTestKit; + +namespace RPGModder.Tests.Merge; + +/// Guide 3.6 in Compose: command and Sequence lists merged per run, with one collision per list and kind. +public sealed class ListComposeTests +{ + private const string CommonEvents = "data/CommonEvents.json"; + + private static readonly RecordKey EventKey = new("data/commonevents.json", "id:1"); + + private static readonly BaseFileSet EventBases = Bases(Base(CommonEvents, Events(Wait(0, 10), Wait(0, 20), End(0)))); + + private static string Events(params JObject[] commands) + { + return new JArray(JValue.CreateNull(), new JObject { ["id"] = 1, ["name"] = "Start", ["trigger"] = 0, ["list"] = List(commands) }).ToString(); + } + + private static ModSource EventMod(string modId, int priority, params JObject[] commands) + { + return FileMod(modId, CommonEvents, Events(commands), priority); + } + + private static JArray WrittenList(MergePlan plan, BaseFileSet bases) + { + return (JArray)JArray.Parse(Assert.Single(MergedFileWriter.Write(plan, bases, null)).Text!)[1]!["list"]!; + } + + private static ModSource[] ClashWithCleanEdit() + { + return + [ + EventMod("a-tin", 0, Wait(0, 11), Wait(0, 20), End(0)), + EventMod("b-oak", 1, Wait(0, 12), Wait(0, 20), End(0)), + EventMod("c-elm", 2, Wait(0, 10), Wait(0, 20), Wait(0, 30), End(0)) + ]; + } + + [Fact] + public void Compose_CommandListsChangedInDifferentPlaces_MergeIntoOneOp() + { + ModSource first = EventMod("a-tin", 0, Wait(0, 1), Wait(0, 10), Wait(0, 20), End(0)); + ModSource second = EventMod("b-oak", 1, Wait(0, 10), Wait(0, 20), Wait(0, 2), End(0)); + + MergePlan plan = Compose(EventBases, first, second); + + Assert.Empty(plan.Collisions); + Assert.True(plan.IsDeployable); + MergedOp merged = Assert.Single(plan.Ops); + Assert.Equal(ChangeKind.EditCommands, merged.Op.Kind); + Assert.Equal("a-tin", merged.Op.ModId); + Assert.Equal(["a-tin", "b-oak"], merged.ModIds); + Assert.Equal(Text(List(Wait(0, 1), Wait(0, 10), Wait(0, 20), Wait(0, 2), End(0))), Text(WrittenList(plan, EventBases))); + Assert.Equal(plan.MergeHash, Compose(EventBases, second, first).MergeHash); + } + + [Fact] + public void Compose_RunChangedTwoWays_IsOneLogicClashOfThoseModsOnly() + { + MergePlan plan = Compose(EventBases, ClashWithCleanEdit()); + + Collision clash = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.LogicClash, clash.Kind); + Assert.Equal(["a-tin", "b-oak"], clash.ModIds); + Assert.Equal(Composer.CollisionId(CollisionKind.LogicClash, EventKey, "list", ["a-tin", "b-oak"]), clash.Id); + Assert.True(clash.Blocking); + Assert.Equal([ResolutionKind.PickMod, ResolutionKind.PickVanilla], clash.Allowed); + Assert.False(plan.IsDeployable); + Assert.Empty(plan.Ops); + } + + [Fact] + public void Compose_PickMod_TakesThatModsRunAndKeepsTheCleanEdits() + { + Collision clash = Assert.Single(Compose(EventBases, ClashWithCleanEdit()).Collisions); + + MergePlan plan = Compose(EventBases, [new Resolution(clash.Id, ResolutionKind.PickMod, "b-oak", clash.Fingerprint)], ClashWithCleanEdit()); + + Assert.True(plan.IsDeployable); + Assert.Equal(ResolutionSource.Profile, Assert.Single(plan.Outcomes).Source); + MergedOp merged = Assert.Single(plan.Ops); + Assert.Equal("b-oak", merged.Op.ModId); + Assert.Equal(["b-oak", "c-elm"], merged.ModIds); + Assert.Equal(Text(List(Wait(0, 12), Wait(0, 20), Wait(0, 30), End(0))), Text(WrittenList(plan, EventBases))); + } + + [Fact] + public void Compose_PickVanilla_KeepsVanillasRunAndTheCleanEdits() + { + Collision clash = Assert.Single(Compose(EventBases, ClashWithCleanEdit()).Collisions); + + MergePlan plan = Compose(EventBases, [new Resolution(clash.Id, ResolutionKind.PickVanilla, null)], ClashWithCleanEdit()); + + MergedOp merged = Assert.Single(plan.Ops); + Assert.Equal(["c-elm"], merged.ModIds); + Assert.Equal(Text(List(Wait(0, 10), Wait(0, 20), Wait(0, 30), End(0))), Text(WrittenList(plan, EventBases))); + } + + [Fact] + public void Compose_PickVanillaWithNoCleanEdit_LeavesTheListAlone() + { + ModSource[] mods = [EventMod("a-tin", 0, Wait(0, 11), Wait(0, 20), End(0)), EventMod("b-oak", 1, Wait(0, 12), Wait(0, 20), End(0))]; + Collision clash = Assert.Single(Compose(EventBases, mods).Collisions); + + MergePlan plan = Compose(EventBases, [new Resolution(clash.Id, ResolutionKind.PickVanilla, null)], mods); + + Assert.True(plan.IsDeployable); + Assert.Empty(plan.Ops); + } + + [Fact] + public void Compose_CleanEditChanged_KeepsTheClashFingerprint() + { + ModSource[] mods = ClashWithCleanEdit(); + mods[2] = EventMod("c-elm", 2, Wait(0, 10), Wait(0, 20), Wait(0, 31), End(0)); + + Assert.Equal(Assert.Single(Compose(EventBases, ClashWithCleanEdit()).Collisions).Fingerprint, Assert.Single(Compose(EventBases, mods).Collisions).Fingerprint); + } + + [Fact] + public void Compose_InsertsAtOneGap_AreOrderAmbiguousInProfileOrderByDefault() + { + ModSource late = EventMod("a-tin", 1, Wait(0, 10), Wait(0, 1), Wait(0, 20), End(0)); + ModSource early = EventMod("b-oak", 0, Wait(0, 10), Wait(0, 2), Wait(0, 20), End(0)); + + MergePlan plan = Compose(EventBases, late, early); + + Collision order = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.OrderAmbiguous, order.Kind); + Assert.False(order.Blocking); + Assert.Equal(["a-tin", "b-oak"], order.ModIds); + Assert.Equal([ResolutionKind.PickMod, ResolutionKind.KeepBothInProfileOrder], order.Allowed); + Assert.Equal(new CollisionOutcome(order.Id, ResolutionSource.Default, ResolutionKind.KeepBothInProfileOrder, null), Assert.Single(plan.Outcomes)); + Assert.True(plan.IsDeployable); + Assert.Equal(Text(List(Wait(0, 10), Wait(0, 2), Wait(0, 1), Wait(0, 20), End(0))), Text(WrittenList(plan, EventBases))); + } + + [Fact] + public void Compose_OrderAmbiguousPickMod_PutsThatModsInsertsFirst() + { + ModSource late = EventMod("a-tin", 1, Wait(0, 10), Wait(0, 1), Wait(0, 20), End(0)); + ModSource early = EventMod("b-oak", 0, Wait(0, 10), Wait(0, 2), Wait(0, 20), End(0)); + Collision order = Assert.Single(Compose(EventBases, late, early).Collisions); + + MergePlan plan = Compose(EventBases, [new Resolution(order.Id, ResolutionKind.PickMod, "a-tin")], late, early); + + Assert.Equal(Text(List(Wait(0, 10), Wait(0, 1), Wait(0, 2), Wait(0, 20), End(0))), Text(WrittenList(plan, EventBases))); + } + + [Fact] + public void Compose_ClashAndInsertsAtOneGapInOneList_AreTwoCollisions() + { + MergePlan plan = Compose( + EventBases, + EventMod("a-tin", 0, Wait(0, 11), Wait(0, 20), Wait(0, 3), End(0)), + EventMod("b-oak", 1, Wait(0, 12), Wait(0, 20), Wait(0, 4), End(0))); + + Assert.Equal( + [CollisionKind.LogicClash, CollisionKind.OrderAmbiguous], + plan.Collisions.Select(collision => collision.Kind).Order()); + Assert.All(plan.Collisions, collision => Assert.Equal(["a-tin", "b-oak"], collision.ModIds)); + Assert.Empty(plan.Ops); + } + + [Fact] + public void Compose_EditsInDifferentBranchesOfOneBlock_MergeInsideIt() + { + BaseFileSet bases = Bases(Base(CommonEvents, Events(Cmd(111, 0, 0, 1, 0), Wait(1, 1), End(1), Cmd(411, 0), Wait(1, 2), End(1), Cmd(412, 0), End(0)))); + + MergePlan plan = Compose( + bases, + EventMod("a-tin", 0, Cmd(111, 0, 0, 1, 0), Wait(1, 5), End(1), Cmd(411, 0), Wait(1, 2), End(1), Cmd(412, 0), End(0)), + EventMod("b-oak", 1, Cmd(111, 0, 0, 1, 0), Wait(1, 1), End(1), Cmd(411, 0), Wait(1, 2), Wait(1, 6), End(1), Cmd(412, 0), End(0))); + + Assert.Empty(plan.Collisions); + Assert.Equal( + Text(List(Cmd(111, 0, 0, 1, 0), Wait(1, 5), End(1), Cmd(411, 0), Wait(1, 2), Wait(1, 6), End(1), Cmd(412, 0), End(0))), + Text(WrittenList(plan, bases))); + } + + [Fact] + public void Compose_ModListNotWellFormed_FallsBackToOneLogicClashOfTheWholeList() + { + MergePlan plan = Compose( + EventBases, + EventMod("a-tin", 0, Wait(0, 1), Wait(0, 10), Wait(0, 20), End(0)), + EventMod("b-oak", 1, Cmd(401, 0, "stray"), Wait(0, 10), Wait(0, 20), End(0))); + + Collision clash = Assert.Single(plan.Collisions); + Assert.Equal(CollisionKind.LogicClash, clash.Kind); + Assert.Equal(["a-tin", "b-oak"], clash.ModIds); + Assert.Empty(plan.Ops); + } + + [Fact] + public void Compose_MapEventPageLists_MergeLikeAnyCommandList() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + JArray Page(JObject map) => (JArray)map["events"]![1]!["pages"]![0]!["list"]!; + + MergePlan plan = Compose( + bases, + FileMod("a-tin", Map, EditMap(map => Page(map).Insert(0, Wait(0, 1)))), + FileMod("b-oak", Map, EditMap(map => Page(map).Insert(1, Wait(0, 2))))); + + Assert.Empty(plan.Collisions); + JObject written = JObject.Parse(Assert.Single(MergedFileWriter.Write(plan, bases, null)).Text!); + Assert.Equal(Text(List(Wait(0, 1), Cmd(101, 0, "", 0, 0, 2), Wait(0, 2), End(0))), Text(Page(written))); + } + + [Fact] + public void Compose_EffectReplacedAndAnotherAppended_MergeIntoOneSequence() + { + var changed = new JObject { ["code"] = 11, ["dataId"] = 0, ["value1"] = 0, ["value2"] = 50 }; + var added = new JObject { ["code"] = 21, ["dataId"] = 1, ["value1"] = 1, ["value2"] = 0 }; + + MergePlan plan = Compose( + ItemBases(), + FileMod("a-tin", Items, EditItems(items => items[1]!["effects"]![0] = changed)), + FileMod("b-oak", Items, EditItems(items => ((JArray)items[1]!["effects"]!).Add(added)), 1)); + + Assert.Empty(plan.Collisions); + MergedOp merged = Assert.Single(plan.Ops); + Assert.Equal(ChangeKind.EditSequence, merged.Op.Kind); + Assert.Equal(["a-tin", "b-oak"], merged.ModIds); + Assert.Equal(Text(new JArray(changed, added)), Text(merged.Op.Value!)); + } + + [Fact] + public void Compose_TwoAppendedEffects_AreOrderAmbiguous() + { + MergePlan plan = Compose( + ItemBases(), + FileMod("a-tin", Items, EditItems(items => ((JArray)items[1]!["effects"]!).Add(new JObject { ["code"] = 21 }))), + FileMod("b-oak", Items, EditItems(items => ((JArray)items[1]!["effects"]!).Add(new JObject { ["code"] = 22 })), 1)); + + Assert.Equal(CollisionKind.OrderAmbiguous, Assert.Single(plan.Collisions).Kind); + Assert.True(plan.IsDeployable); + Assert.Equal([11, 21, 22], ((JArray)Assert.Single(plan.Ops).Op.Value!).Select(effect => (int)effect["code"]!)); + } + + [Fact] + public void Compose_ResizeAndTileEdit_AreOneChoiceThatKeepsTheMapWhole() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource resize = FileMod("a-tin", Map, EditMap(map => + { + map["width"] = 3; + map["data"] = new JArray(1, 2, 0, 3, 4, 0); + })); + ModSource tile = FileMod("b-oak", Map, EditMap(map => map["data"]![1] = 9)); + + Collision clash = Assert.Single(Compose(bases, resize, tile).Collisions); + Assert.Equal(CollisionKind.ValueClash, clash.Kind); + Assert.Equal("data", clash.Path); + Assert.Equal(["a-tin", "b-oak"], clash.ModIds); + + JObject Written(string modId) + { + MergePlan plan = Compose(bases, [new Resolution(clash.Id, ResolutionKind.PickMod, modId)], resize, tile); + return JObject.Parse(Assert.Single(MergedFileWriter.Write(plan, bases, null)).Text!); + } + + JObject resized = Written("a-tin"); + JObject tiled = Written("b-oak"); + Assert.Equal((3, "[1,2,0,3,4,0]"), ((int)resized["width"]!, Text(resized["data"]!))); + Assert.Equal((2, "[1,9,3,4]"), ((int)tiled["width"]!, Text(tiled["data"]!))); + } + + [Fact] + public void Compose_EqualResizes_MergeWithoutAClash() + { + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + string resized = EditMap(map => + { + map["height"] = 1; + map["data"] = new JArray(1, 2); + }); + + MergePlan plan = Compose(bases, FileMod("a-tin", Map, resized), FileMod("b-oak", Map, resized)); + + Assert.Empty(plan.Collisions); + Assert.Equal(["data", "height"], plan.Ops.Select(op => op.Op.Path).Order(StringComparer.Ordinal)); + Assert.All(plan.Ops, op => Assert.Equal(["a-tin", "b-oak"], op.ModIds)); + } + + [Fact] + public void Compose_ReshapeOfTheSameTileCountAndATileEdit_AreOneChoice() + { + // 2x2 to 4x1 keeps four tiles, so the tiles must still be one value: index 1 is another cell after it. + BaseFileSet bases = Bases(Base(Map, VanillaMap)); + ModSource reshape = FileMod("a-tin", Map, EditMap(map => + { + map["width"] = 4; + map["height"] = 1; + map["data"]![3] = 5; + })); + ModSource tile = FileMod("b-oak", Map, EditMap(map => map["data"]![1] = 9)); + + Collision clash = Assert.Single(Compose(bases, reshape, tile).Collisions); + + Assert.Equal(CollisionKind.ValueClash, clash.Kind); + Assert.Equal("data", clash.Path); + Assert.Equal(["a-tin", "b-oak"], clash.ModIds); + } + + private static BaseFileSet ItemBases() + { + return Bases(Base(Items, VanillaItems)); + } +} diff --git a/RPGModder.Tests/Merge/ListMergePropertyTests.cs b/RPGModder.Tests/Merge/ListMergePropertyTests.cs new file mode 100644 index 0000000..739a742 --- /dev/null +++ b/RPGModder.Tests/Merge/ListMergePropertyTests.cs @@ -0,0 +1,959 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using static RPGModder.Tests.Merge.CommandListKit; + +namespace RPGModder.Tests.Merge; + +/// +/// TST-6: the list merge laws over generated command trees and Sequence lists. Seeds are fixed, so a failure names +/// the seed that reproduces it. Every node carries an id of its own in its parameters, so an edit is addressed by +/// that id and the expected list is the edits applied to vanilla directly. +/// +public sealed class ListMergePropertyTests +{ + private const int Seeds = 500; + + [Fact] + public void Commands_GeneratedTree_ParsesAndFlattensBack() + { + for (int seed = 0; seed < Seeds; seed++) + { + var tree = new Tree(new Random(seed)); + JArray list = tree.Flatten(); + + IReadOnlyList? nodes = CommandTree.Parse(list); + + Assert.True(nodes is not null, $"seed {seed}: {Text(list)}"); + Assert.True(JToken.DeepEquals(list, CommandTree.Flatten(nodes)), $"seed {seed}"); + } + } + + [Fact] + public void Commands_OneSideChanged_GivesThatSide() + { + for (int seed = 0; seed < Seeds; seed++) + { + var random = new Random(seed); + var tree = new Tree(random); + JArray vanilla = tree.Flatten(); + JArray changed = tree.Apply(tree.Edits(random, random.Next(1, 6))).Flatten(); + + Assert.True(Text(changed) == Text(MergeCommands(vanilla, changed, vanilla).List), $"seed {seed}: first side"); + Assert.True(Text(changed) == Text(MergeCommands(vanilla, vanilla, changed).List), $"seed {seed}: second side"); + Assert.True(Text(changed) == Text(MergeCommands(vanilla, changed, changed).List), $"seed {seed}: both sides"); + } + } + + [Fact] + public void Commands_DisjointEdits_MergeToAllEditsApplied() + { + int shared = 0; + for (int seed = 0; seed < Seeds; seed++) + { + var random = new Random(seed); + var tree = new Tree(random); + List edits = tree.Edits(random, random.Next(2, 9)); + List[] sides = [[], [], []]; + foreach (Edit edit in edits) + { + sides[random.Next(sides.Length)].Add(edit); + } + + ListMergeResult result = MergeCommands(tree.Flatten(), sides.Select(side => tree.Apply(side).Flatten()).ToArray()); + + Assert.True(result.ClashMods.Count == 0 && result.OrderMods.Count == 0, $"seed {seed}: clash or order"); + Assert.True(JToken.DeepEquals(tree.Apply(edits).Flatten(), result.List), $"seed {seed}: {Text(result.List)}"); + shared += result.Contributors.Count > 1 ? 1 : 0; + } + + // The law says nothing when one side holds every edit, so most seeds must merge two or more. + Assert.True(shared > Seeds / 2, $"only {shared} seeds merged edits of two sides"); + } + + [Fact] + public void Commands_AnyEdits_GiveAValidListUnderEveryChoice() + { + for (int seed = 0; seed < Seeds; seed++) + { + var random = new Random(seed); + var tree = new Tree(random); + JArray vanilla = tree.Flatten(); + JArray[] sides = Enumerable.Range(0, random.Next(2, 4)) + .Select(_ => tree.Apply(tree.Edits(random, random.Next(1, 5), disjoint: false)).Flatten()) + .ToArray(); + + ListMergeResult found = MergeCommands(vanilla, sides); + List policies = [ListPolicy.Unresolved]; + policies.AddRange(found.ClashMods.Select(mod => new ListPolicy(ResolutionKind.PickMod, mod, null))); + policies.AddRange(found.OrderMods.Select(mod => new ListPolicy(ResolutionKind.PickVanilla, null, mod))); + foreach (ListPolicy policy in policies) + { + ListMergeResult result = MergeCommands(vanilla, policy, sides); + + Assert.True(CommandTree.Validate(result.List), $"seed {seed}, {policy}: {Text(result.List)}"); + Assert.True(found.ClashFingerprint == result.ClashFingerprint, $"seed {seed}, {policy}: clash fingerprint"); + Assert.True(found.OrderFingerprint == result.OrderFingerprint, $"seed {seed}, {policy}: order fingerprint"); + } + } + } + + [Fact] + public void Sequence_OneSideChanged_GivesThatSide() + { + for (int seed = 0; seed < Seeds; seed++) + { + var random = new Random(seed); + var list = new Sequence(random); + JArray vanilla = list.Values(); + JArray changed = list.Apply(list.Edits(random, random.Next(1, 6))).Values(); + + Assert.True(Text(changed) == Text(MergeSequence(vanilla, changed, vanilla).List), $"seed {seed}: one side"); + Assert.True(Text(changed) == Text(MergeSequence(vanilla, changed, changed).List), $"seed {seed}: both sides"); + } + } + + [Fact] + public void Sequence_DisjointEdits_MergeToAllEditsApplied() + { + int shared = 0; + for (int seed = 0; seed < Seeds; seed++) + { + var random = new Random(seed); + var list = new Sequence(random); + List edits = list.Edits(random, random.Next(2, 8)); + List[] sides = [[], []]; + foreach (Edit edit in edits) + { + sides[random.Next(sides.Length)].Add(edit); + } + + ListMergeResult result = MergeSequence(list.Values(), sides.Select(side => list.Apply(side).Values()).ToArray()); + + Assert.True(result.ClashMods.Count == 0 && result.OrderMods.Count == 0, $"seed {seed}: clash or order"); + Assert.True(Text(list.Apply(edits).Values()) == Text(result.List), $"seed {seed}: {Text(result.List)}"); + shared += result.Contributors.Count > 1 ? 1 : 0; + } + + Assert.True(shared > Seeds / 2, $"only {shared} seeds merged edits of two sides"); + } + + /// + /// Safety: a merge never invents a copy. Under every choice, each command (with its indent) appears at most as + /// often as in vanilla plus its copies in the nodes each side added. Heads repeat and sides move nodes, the cases a + /// pairing by guess or a half-applied move would get wrong. A moved node is not added, so it must stay one copy; + /// an edited node is added, as the side may also have put it somewhere else. + /// + [Fact] + public void Commands_RepeatedHeadsAndMoves_NeverInventACopyUnderAnyChoice() + { + for (int seed = 0; seed < Seeds; seed++) + { + var random = new Random(seed); + List nodes = Enumerable.Range(0, random.Next(0, 8)).Select(_ => PoolNode(random)).ToList(); + JArray vanilla = Commands(nodes); + List> changed = Enumerable.Range(0, random.Next(2, 4)).Select(_ => Changed(random, nodes, PoolNode)).ToList(); + JArray[] sides = changed.Select(Commands).ToArray(); + List> added = changed + .Select(side => Counts(new JArray(Added(nodes, side, node => string.Join('\n', node.Select(Text))).SelectMany(node => node)))) + .ToList(); + + foreach ((ListPolicy policy, ListMergeResult result) in EveryChoice(MergeCommands(vanilla, sides), policy => MergeCommands(vanilla, policy, sides))) + { + Assert.True(CommandTree.Validate(result.List), $"seed {seed}, {policy}: {Text(result.List)}"); + Assert.True(NoInventedCopy(vanilla, added, result.List, out string line), $"seed {seed}, {policy}: {line} in {Text(result.List)}"); + } + } + } + + /// + /// Safety with moves into, out of and between bodies. Lines are counted without their indent, so a moved node + /// keeps its lines and a half-applied move shows as a copy too many. A side may add the own lines (head, + /// continuations, markers, ends) of each node it added at any depth, not the lines the node holds: a node that + /// holds a moved one changed, but did not add it. + /// + [Fact] + public void Commands_NestedMoves_NeverInventACopyUnderAnyChoice() + { + for (int seed = 0; seed < Seeds; seed++) + { + var random = new Random(seed); + List nodes = Enumerable.Range(0, random.Next(0, 6)).Select(_ => Pooled.Generate(random, 0)).ToList(); + JArray vanilla = Pooled.Emit(nodes); + JArray[] sides = Enumerable.Range(0, random.Next(2, 4)).Select(_ => Pooled.Emit(Pooled.Changed(random, nodes))).ToArray(); + List> added = sides.Select(side => OwnLinesAdded(vanilla, side)).ToList(); + + foreach ((ListPolicy policy, ListMergeResult result) in EveryChoice(MergeCommands(vanilla, sides), policy => MergeCommands(vanilla, policy, sides))) + { + Assert.True(CommandTree.Validate(result.List), $"seed {seed}, {policy}: {Text(result.List)}"); + Assert.True( + NoInventedCopy(Unindented(vanilla), added, Unindented(result.List), out string line), + $"seed {seed}, {policy}: {line} in {Text(result.List)}"); + } + } + } + + [Fact] + public void Sequence_RepeatedValuesAndMoves_NeverInventACopyUnderAnyChoice() + { + for (int seed = 0; seed < Seeds; seed++) + { + var random = new Random(seed); + List values = Enumerable.Range(0, random.Next(0, 8)).Select(_ => PoolValue(random)).ToList(); + var vanilla = new JArray(values); + List> changed = Enumerable.Range(0, random.Next(2, 4)).Select(_ => Changed(random, values, PoolValue)).ToList(); + JArray[] sides = changed.Select(side => new JArray(side)).ToArray(); + List> added = changed.Select(side => Counts(new JArray(Added(values, side, Text)))).ToList(); + + foreach ((ListPolicy policy, ListMergeResult result) in EveryChoice(MergeSequence(vanilla, sides), policy => MergeSequence(vanilla, policy, sides))) + { + Assert.True(NoInventedCopy(vanilla, added, result.List, out string value), $"seed {seed}, {policy}: {value} in {Text(result.List)}"); + } + } + } + + /// The open merge, then each choice its collisions offer. + private static IEnumerable<(ListPolicy Policy, ListMergeResult Result)> EveryChoice(ListMergeResult found, Func merge) + { + yield return (ListPolicy.Unresolved, found); + List policies = [new ListPolicy(ResolutionKind.PickVanilla, null, null)]; + policies.AddRange(found.ClashMods.Select(mod => new ListPolicy(ResolutionKind.PickMod, mod, null))); + policies.AddRange(found.OrderMods.Select(mod => new ListPolicy(null, null, mod))); + foreach (ListPolicy policy in policies) + { + yield return (policy, merge(policy)); + } + } + + private static bool NoInventedCopy(JArray vanilla, List> added, JArray merged, out string item) + { + Dictionary before = Counts(vanilla); + foreach ((string text, int count) in Counts(merged)) + { + int allowed = before.GetValueOrDefault(text) + added.Sum(side => side.GetValueOrDefault(text)); + if (count > allowed) + { + item = text; + return false; + } + } + + item = ""; + return true; + } + + /// The items of left after taking out one equal item per vanilla item. + private static List Added(List vanilla, List side, Func key) + { + Dictionary left = vanilla.GroupBy(key).ToDictionary(group => group.Key, group => group.Count()); + var added = new List(); + foreach (T item in side) + { + if (left.GetValueOrDefault(key(item)) > 0) + { + left[key(item)]--; + } + else + { + added.Add(item); + } + } + + return added; + } + + /// The own lines, without indents, of the nodes at any depth has more of than vanilla. + private static Dictionary OwnLinesAdded(JArray vanilla, JArray side) + { + // A body's end belongs to its block, as a marker does. + static List All(IReadOnlyList body) + { + return body + .Where(node => !CommandTree.IsEnd(node)) + .SelectMany(node => All(node.Branches.SelectMany(branch => branch.Body).ToList()).Prepend(node)) + .ToList(); + } + + static string Key(CommandNode node) + { + return Text(CommandTree.Flatten(node, 0)); + } + + List added = Added(All(CommandTree.Parse(vanilla)!), All(CommandTree.Parse(side)!), Key); + IEnumerable own = added.SelectMany(node => new[] { node.Head } + .Concat(node.Continuations) + .Concat(node.Branches.Select(branch => branch.Marker).OfType()) + .Concat(node.Branches.SelectMany(branch => branch.Body).Where(CommandTree.IsEnd).Select(end => end.Head)) + .Concat(node.End is null ? [] : [node.End])); + return Counts(Unindented(new JArray(own))); + } + + private static JArray Unindented(JArray list) + { + return new JArray(list.Select(command => + { + var copy = (JObject)command.DeepClone(); + copy.Remove("indent"); + return copy; + })); + } + + private static Dictionary Counts(JArray list) + { + return list.GroupBy(Text).ToDictionary(group => group.Key, group => group.Count()); + } + + /// A copy of with one to four deletes, inserts, replaces or moves. + private static List Changed(Random random, List items, Func pool) + { + var changed = new List(items); + for (int count = random.Next(1, 5); count > 0; count--) + { + int kind = random.Next(4); + if (kind == 0 || changed.Count == 0) + { + changed.Insert(random.Next(changed.Count + 1), pool(random)); + continue; + } + + int at = random.Next(changed.Count); + T item = changed[at]; + changed.RemoveAt(at); + if (kind == 2) + { + changed.Insert(at, pool(random)); + } + else if (kind == 3) + { + changed.Insert(random.Next(changed.Count + 1), item); + } + } + + return changed; + } + + /// A node from a pool small enough that heads and whole nodes repeat: waits, Show Text, and If. + private static JObject[] PoolNode(Random random) + { + return random.Next(3) switch + { + 0 => [Wait(0, random.Next(1, 4))], + 1 => [Cmd(101, 0, "", 0), Cmd(401, 0, random.Next(2) == 0 ? "x" : "y")], + _ => [Cmd(111, 0, 0, 1, 0), .. Enumerable.Range(0, random.Next(0, 3)).Select(_ => Wait(1, random.Next(1, 4))), End(1), Cmd(412, 0)] + }; + } + + private static JToken PoolValue(Random random) + { + return new JValue(random.Next(1, 4)); + } + + private static JArray Commands(List nodes) + { + return List([.. nodes.SelectMany(node => node), End(0)]); + } + + private static ListMergeResult MergeCommands(JArray vanilla, params JArray[] sides) + { + return MergeCommands(vanilla, ListPolicy.Unresolved, sides); + } + + private static ListMergeResult MergeCommands(JArray vanilla, ListPolicy policy, params JArray[] sides) + { + return ListMerge.MergeCommands( + CommandTree.Parse(vanilla)!, + sides.Select((side, index) => new ListSide(CommandTree.Parse(side)!, ["m" + index])).ToList(), + policy); + } + + private static ListMergeResult MergeSequence(JArray vanilla, params JArray[] sides) + { + return MergeSequence(vanilla, ListPolicy.Unresolved, sides); + } + + private static ListMergeResult MergeSequence(JArray vanilla, ListPolicy policy, params JArray[] sides) + { + return ListMerge.MergeSequence( + vanilla.ToList(), + sides.Select((side, index) => new ListSide(side.ToList(), ["m" + index])).ToList(), + policy); + } + + private enum EditKind + { + Insert, + Delete, + Replace, + Lines, + Marker + } + + /// One change addressed by the id of its node: an insert goes right before that node. + private sealed record Edit(EditKind Kind, int Target, int Fresh, Node? Inserted = null, int Part = 0); + + /// A command or Sequence item with the id it is addressed by; ids also tell the generated values apart. + private sealed class Node + { + public required int Id { get; init; } + + public required int Code { get; init; } + + public bool IsEnd => Code == 0; + + public JArray Parameters { get; set; } = new(); + + public List Lines { get; init; } = new(); + + public List<(JObject? Marker, List Body)> Branches { get; init; } = new(); + + public JObject? EndMarker { get; init; } + + public Node Clone() + { + return new Node + { + Id = Id, + Code = Code, + Parameters = (JArray)Parameters.DeepClone(), + Lines = Lines.Select(line => (JObject)line.DeepClone()).ToList(), + Branches = Branches.Select(branch => ((JObject?)branch.Marker?.DeepClone(), branch.Body.Select(node => node.Clone()).ToList())).ToList(), + EndMarker = (JObject?)EndMarker?.DeepClone() + }; + } + + public void Emit(int depth, JArray list) + { + list.Add(new JObject { ["code"] = Code, ["indent"] = depth, ["parameters"] = Parameters.DeepClone() }); + foreach (JObject line in Lines) + { + list.Add(At(line, depth)); + } + + foreach ((JObject? marker, List body) in Branches) + { + if (marker is not null) + { + list.Add(At(marker, depth)); + } + + foreach (Node node in body) + { + node.Emit(depth + 1, list); + } + } + + if (EndMarker is not null) + { + list.Add(At(EndMarker, depth)); + } + } + + private static JObject At(JObject command, int depth) + { + var copy = (JObject)command.DeepClone(); + copy["indent"] = depth; + return copy; + } + } + + /// A generated command list: every head and every line carries an id no other command has. + private sealed class Tree + { + private const int MaxDepth = 3; + + private readonly List _root; + private int _next = 1; + + public Tree(Random random) + { + _root = Body(random, 0); + } + + private Tree(List root, int next) + { + _root = root; + _next = next; + } + + public JArray Flatten() + { + var list = new JArray(); + foreach (Node node in _root) + { + node.Emit(0, list); + } + + return list; + } + + /// + /// Random edits. Disjoint ones never meet: at most one insert before a node, one delete or replace of a + /// node with nothing else at or under it, and one change to a node's lines or to each of its markers. + /// + public List Edits(Random random, int count, bool disjoint = true) + { + List<(Node Node, List Ancestors)> all = Walk(_root, []).ToList(); + var edits = new List(); + var gaps = new Gaps(Bodies(_root)); + var removed = new HashSet(); + var touched = new HashSet(); + var parts = new HashSet<(int, int)>(); + for (int attempt = 0; attempt < count * 10 && edits.Count < count; attempt++) + { + (Node node, List ancestors) = all[random.Next(all.Count)]; + EditKind kind = (EditKind)random.Next(5); + if (disjoint && ancestors.Any(removed.Contains)) + { + continue; + } + + Edit? edit = kind switch + { + EditKind.Insert when !disjoint || gaps.TryInsert(node.Id) => new Edit(kind, node.Id, 0, Generate(random, 2)), + EditKind.Delete or EditKind.Replace when !node.IsEnd && (!disjoint || (!touched.Contains(node.Id) && gaps.TryCut(node.Id))) => + new Edit(kind, node.Id, _next++), + EditKind.Lines when node.Lines.Count > 0 && (!disjoint || (!removed.Contains(node.Id) && parts.Add((node.Id, -1)))) => + new Edit(kind, node.Id, _next++, Part: random.Next(node.Lines.Count)), + EditKind.Marker when node.Branches.Any(branch => branch.Marker is not null) => + MarkerEdit(random, node, disjoint, removed, parts), + _ => null + }; + if (edit is null) + { + continue; + } + + // A removed node takes what is under it, so nothing may be edited there after it either. + touched.Add(node.Id); + touched.UnionWith(ancestors); + if (edit.Kind is EditKind.Delete or EditKind.Replace) + { + removed.Add(node.Id); + foreach ((Node under, _) in all.Where(item => item.Ancestors.Contains(node.Id))) + { + removed.Add(under.Id); + } + } + + edits.Add(edit); + } + + return edits; + } + + private Edit? MarkerEdit(Random random, Node node, bool disjoint, HashSet removed, HashSet<(int, int)> parts) + { + List marked = Enumerable.Range(0, node.Branches.Count).Where(index => node.Branches[index].Marker is not null).ToList(); + int branch = marked[random.Next(marked.Count)]; + return !disjoint || (!removed.Contains(node.Id) && parts.Add((node.Id, branch))) ? new Edit(EditKind.Marker, node.Id, _next++, Part: branch) : null; + } + + /// A copy with the edits applied: inserts first, each before its node, then the rest. + public Tree Apply(IEnumerable edits) + { + var copy = new Tree(_root.Select(node => node.Clone()).ToList(), _next); + List list = edits.ToList(); + foreach (Edit edit in list.Where(item => item.Kind == EditKind.Insert)) + { + (List body, int index) = copy.Find(edit.Target); + body.Insert(index, edit.Inserted!.Clone()); + } + + foreach (Edit edit in list.Where(item => item.Kind != EditKind.Insert)) + { + if (!copy.TryFind(edit.Target, out List? body, out int index)) + { + // Only when edits may meet: the node went with a removed one. + continue; + } + + Node node = body[index]; + switch (edit.Kind) + { + case EditKind.Delete: + body.RemoveAt(index); + break; + case EditKind.Replace: + node.Parameters = new JArray(edit.Fresh); + break; + case EditKind.Lines: + node.Lines[Math.Min(edit.Part, node.Lines.Count - 1)]["parameters"] = new JArray(edit.Fresh); + break; + case EditKind.Marker: + node.Branches[edit.Part].Marker!["parameters"] = new JArray(edit.Fresh); + break; + } + } + + return copy; + } + + private (List Body, int Index) Find(int id) + { + return TryFind(id, out List? body, out int index) ? (body, index) : throw new InvalidOperationException($"No node {id}."); + } + + private bool TryFind(int id, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out List? body, out int index) + { + var pending = new Stack>(); + pending.Push(_root); + while (pending.Count > 0) + { + List current = pending.Pop(); + index = current.FindIndex(node => node.Id == id); + if (index >= 0) + { + body = current; + return true; + } + + foreach (Node node in current) + { + foreach ((_, List inner) in node.Branches) + { + pending.Push(inner); + } + } + } + + body = null; + index = -1; + return false; + } + + private static IEnumerable> Bodies(List body) + { + yield return body; + foreach (Node node in body) + { + foreach ((_, List branch) in node.Branches) + { + foreach (List inner in Bodies(branch)) + { + yield return inner; + } + } + } + } + + private static IEnumerable<(Node Node, List Ancestors)> Walk(List body, List ancestors) + { + foreach (Node node in body) + { + yield return (node, ancestors); + List inner = [.. ancestors, node.Id]; + foreach ((_, List branch) in node.Branches) + { + foreach ((Node Node, List Ancestors) item in Walk(branch, inner)) + { + yield return item; + } + } + } + } + + private List Body(Random random, int depth) + { + var body = new List(); + int count = random.Next(0, depth == 0 ? 7 : 4); + for (int index = 0; index < count; index++) + { + body.Add(Generate(random, depth)); + } + + body.Add(new Node { Id = _next++, Code = 0 }); + return body; + } + + /// One command with its lines and bodies, of a shape guide 3.6 lists or an unknown code with a body. + private Node Generate(Random random, int depth) + { + int id = _next++; + int shape = random.Next(depth >= MaxDepth ? 2 : 7); + return shape switch + { + 0 => new Node { Id = id, Code = 230, Parameters = new JArray(id) }, + 1 => new Node + { + Id = id, + Code = 101, + Parameters = new JArray("", id), + Lines = Enumerable.Range(0, random.Next(0, 3)).Select(_ => Cmd(401, 0, "line " + _next++)).ToList() + }, + 2 => new Node + { + Id = id, + Code = 111, + Parameters = new JArray(id), + Branches = random.Next(2) == 0 + ? [(null, Body(random, depth + 1))] + : [(null, Body(random, depth + 1)), (Cmd(411, 0), Body(random, depth + 1))], + EndMarker = Cmd(412, 0) + }, + 3 => new Node { Id = id, Code = 112, Parameters = new JArray(id), Branches = [(null, Body(random, depth + 1))], EndMarker = Cmd(413, 0) }, + 4 => new Node + { + Id = id, + Code = 102, + Parameters = new JArray(id), + Branches = Enumerable.Range(0, random.Next(1, 4)).Select(choice => ((JObject?)Cmd(402, 0, choice, "choice " + _next++), Body(random, depth + 1))).ToList(), + EndMarker = Cmd(404, 0) + }, + 5 when random.Next(2) == 0 => new Node { Id = id, Code = 301, Parameters = new JArray(id) }, + 5 => new Node + { + Id = id, + Code = 301, + Parameters = new JArray(id), + Branches = [(Cmd(601, 0), Body(random, depth + 1)), (Cmd(602, 0), Body(random, depth + 1))], + EndMarker = Cmd(604, 0) + }, + _ => new Node { Id = id, Code = 999, Parameters = new JArray(id), Branches = [(null, Body(random, depth + 1))] } + }; + } + } + + /// + /// The inserts and cuts disjoint edits may hold: one insert before a node, one delete or replace of it, and never + /// an insert between two cut neighbors. A side that cuts both makes one run of them and the insert falls inside it, + /// which is a clash by design (GR-T6), whatever sides the edits go to. + /// + private sealed class Gaps + { + private readonly Dictionary _before = new(); + private readonly Dictionary _after = new(); + private readonly HashSet _inserted = new(); + private readonly HashSet _cut = new(); + + public Gaps(IEnumerable> bodies) + { + foreach (List body in bodies) + { + for (int index = 1; index < body.Count; index++) + { + _before[body[index].Id] = body[index - 1].Id; + _after[body[index - 1].Id] = body[index].Id; + } + } + } + + public bool TryInsert(int id) + { + return !Between(id) && _inserted.Add(id); + } + + public bool TryCut(int id) + { + if (_cut.Contains(id)) + { + return false; + } + + _cut.Add(id); + if ((_inserted.Contains(id) && Between(id)) || (_after.TryGetValue(id, out int next) && _inserted.Contains(next) && Between(next))) + { + _cut.Remove(id); + return false; + } + + return true; + } + + /// The gap before lies between two cut nodes. + private bool Between(int id) + { + return _cut.Contains(id) && _before.TryGetValue(id, out int previous) && _cut.Contains(previous); + } + } + + /// A command from a pool small enough that nodes repeat: a wait, a Show Text, or an If with one or two bodies. + private sealed class Pooled + { + private const int MaxDepth = 2; + + public required JObject[] Lines { get; init; } + + public List> Bodies { get; init; } = []; + + public static Pooled Generate(Random random, int depth) + { + int kind = random.Next(depth >= MaxDepth ? 2 : 4); + return kind switch + { + 0 => new Pooled { Lines = [Wait(0, random.Next(1, 4))] }, + 1 => new Pooled { Lines = [Cmd(101, 0, "", 0), Cmd(401, 0, random.Next(2) == 0 ? "x" : "y")] }, + _ => new Pooled + { + Lines = [Cmd(111, 0, 0, 1, 0)], + Bodies = Enumerable.Range(0, kind - 1) + .Select(_ => Enumerable.Range(0, random.Next(0, 3)).Select(_ => Generate(random, depth + 1)).ToList()) + .ToList() + } + }; + } + + public static JArray Emit(List nodes) + { + var list = new JArray(); + foreach (Pooled node in nodes) + { + node.Emit(0, list); + } + + list.Add(End(0)); + return list; + } + + /// A copy with one to four inserts, deletes, replaces or moves, each in a body at any depth. + public static List Changed(Random random, List nodes) + { + List root = nodes.Select(node => node.Clone()).ToList(); + for (int count = random.Next(1, 5); count > 0; count--) + { + List> bodies = AllBodies(root).ToList(); + List from = bodies[random.Next(bodies.Count)]; + int kind = random.Next(4); + if (kind == 0 || from.Count == 0) + { + from.Insert(random.Next(from.Count + 1), Generate(random, 1)); + continue; + } + + int at = random.Next(from.Count); + Pooled item = from[at]; + from.RemoveAt(at); + if (kind == 2) + { + from.Insert(at, Generate(random, 1)); + } + else if (kind == 3) + { + // The node is out of the tree, so it never lands in its own body. + List> left = AllBodies(root).ToList(); + List to = left[random.Next(left.Count)]; + to.Insert(random.Next(to.Count + 1), item); + } + } + + return root; + } + + private static IEnumerable> AllBodies(List body) + { + yield return body; + foreach (List inner in body.SelectMany(node => node.Bodies).SelectMany(AllBodies)) + { + yield return inner; + } + } + + private Pooled Clone() + { + return new Pooled { Lines = Lines, Bodies = Bodies.Select(body => body.Select(node => node.Clone()).ToList()).ToList() }; + } + + private void Emit(int depth, JArray list) + { + foreach (JObject line in Lines) + { + var copy = (JObject)line.DeepClone(); + copy["indent"] = depth; + list.Add(copy); + } + + for (int index = 0; index < Bodies.Count; index++) + { + if (index == 1) + { + list.Add(Cmd(411, depth)); + } + + foreach (Pooled node in Bodies[index]) + { + node.Emit(depth + 1, list); + } + + list.Add(End(depth + 1)); + } + + if (Bodies.Count > 0) + { + list.Add(Cmd(412, depth)); + } + } + } + + /// A generated Sequence list of distinct values, with a last node every append is addressed by. + private sealed class Sequence + { + private readonly List _items; + private int _next; + + public Sequence(Random random) + { + int count = random.Next(0, 8); + _items = Enumerable.Range(0, count).Select(index => Item(index)).Append(new Node { Id = -1, Code = 0 }).ToList(); + _next = count; + } + + private Sequence(List items, int next) + { + _items = items; + _next = next; + } + + public JArray Values() + { + return new JArray(_items.Where(item => !item.IsEnd).Select(item => item.Parameters[0])); + } + + public List Edits(Random random, int count) + { + var edits = new List(); + var gaps = new Gaps([_items]); + for (int attempt = 0; attempt < count * 10 && edits.Count < count; attempt++) + { + Node item = _items[random.Next(_items.Count)]; + if (random.Next(3) == 0 && gaps.TryInsert(item.Id)) + { + edits.Add(new Edit(EditKind.Insert, item.Id, 0, Item(_next++))); + } + else if (!item.IsEnd && gaps.TryCut(item.Id)) + { + edits.Add(new Edit(random.Next(2) == 0 ? EditKind.Delete : EditKind.Replace, item.Id, _next++)); + } + } + + return edits; + } + + public Sequence Apply(IEnumerable edits) + { + var copy = new Sequence(_items.Select(item => item.Clone()).ToList(), _next); + List list = edits.ToList(); + foreach (Edit edit in list.Where(item => item.Kind == EditKind.Insert)) + { + copy._items.Insert(copy._items.FindIndex(item => item.Id == edit.Target), edit.Inserted!.Clone()); + } + + foreach (Edit edit in list.Where(item => item.Kind != EditKind.Insert)) + { + int index = copy._items.FindIndex(item => item.Id == edit.Target); + if (edit.Kind == EditKind.Delete) + { + copy._items.RemoveAt(index); + } + else + { + copy._items[index].Parameters = new JArray(new JObject { ["code"] = 21, ["value"] = edit.Fresh }); + } + } + + return copy; + } + + private static Node Item(int id) + { + return new Node { Id = id, Code = 1, Parameters = new JArray(new JObject { ["code"] = 11, ["dataId"] = id }) }; + } + } +} diff --git a/RPGModder.Tests/Merge/ListMergeTests.cs b/RPGModder.Tests/Merge/ListMergeTests.cs new file mode 100644 index 0000000..3a34e52 --- /dev/null +++ b/RPGModder.Tests/Merge/ListMergeTests.cs @@ -0,0 +1,513 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using static RPGModder.Tests.Merge.CommandListKit; + +namespace RPGModder.Tests.Merge; + +public sealed class ListMergeTests +{ + /// Merges command lists, side i held by mod m{i}, given in profile order. + private static ListMergeResult Commands(JArray vanilla, ListPolicy policy, params JArray[] sides) + { + return ListMerge.MergeCommands( + CommandTree.Parse(vanilla)!, + sides.Select((side, index) => new ListSide(CommandTree.Parse(side)!, ["m" + index])).ToList(), + policy); + } + + private static ListMergeResult Sequence(JArray vanilla, ListPolicy policy, params JArray[] sides) + { + return ListMerge.MergeSequence( + vanilla.ToList(), + sides.Select((side, index) => new ListSide(side.ToList(), ["m" + index])).ToList(), + policy); + } + + private static readonly JArray Vanilla = List(Wait(0, 10), Wait(0, 20), Wait(0, 30), End(0)); + + /// A Conditional Branch with no else, its body one wait. + private static JObject[] If(int frames) + { + return [Cmd(111, 0, 0, 5, 0), Wait(1, frames), End(1), Cmd(412, 0)]; + } + + [Fact] + public void Commands_InsertsAtDifferentGaps_AreBothKept() + { + ListMergeResult result = Commands( + Vanilla, + ListPolicy.Unresolved, + List(Wait(0, 1), Wait(0, 10), Wait(0, 20), Wait(0, 30), End(0)), + List(Wait(0, 10), Wait(0, 20), Wait(0, 30), Wait(0, 2), End(0))); + + Assert.Equal(Text(List(Wait(0, 1), Wait(0, 10), Wait(0, 20), Wait(0, 30), Wait(0, 2), End(0))), Text(result.List)); + Assert.Empty(result.ClashMods); + Assert.Empty(result.OrderMods); + Assert.Equal(["m0", "m1"], result.Contributors); + } + + [Fact] + public void Commands_DeleteNextToAnotherSidesInsert_AreBothKept() + { + ListMergeResult result = Commands( + Vanilla, + ListPolicy.Unresolved, + List(Wait(0, 10), Wait(0, 30), End(0)), + List(Wait(0, 10), Wait(0, 20), Wait(0, 5), Wait(0, 30), End(0))); + + Assert.Equal(Text(List(Wait(0, 10), Wait(0, 5), Wait(0, 30), End(0))), Text(result.List)); + Assert.Empty(result.ClashMods); + } + + [Fact] + public void Commands_SameChangeOnTwoSides_IsTakenOnce() + { + JArray changed = List(Wait(0, 10), Wait(0, 21), Wait(0, 30), End(0)); + + ListMergeResult result = Commands(Vanilla, ListPolicy.Unresolved, changed, changed); + + Assert.Equal(Text(changed), Text(result.List)); + Assert.Empty(result.ClashMods); + Assert.Equal(["m0", "m1"], result.Contributors); + } + + [Fact] + public void Commands_InsertsAtOneGap_GoInProfileOrder_AndNameTheirMods() + { + ListMergeResult result = Commands( + Vanilla, + ListPolicy.Unresolved, + List(Wait(0, 10), Wait(0, 1), Wait(0, 20), Wait(0, 30), End(0)), + List(Wait(0, 10), Wait(0, 2), Wait(0, 20), Wait(0, 30), End(0))); + + Assert.Equal(Text(List(Wait(0, 10), Wait(0, 1), Wait(0, 2), Wait(0, 20), Wait(0, 30), End(0))), Text(result.List)); + Assert.Equal(["m0", "m1"], result.OrderMods); + Assert.Empty(result.ClashMods); + } + + [Fact] + public void Commands_FirstMod_PutsItsInsertsFirst_WithTheSameFingerprint() + { + JArray first = List(Wait(0, 10), Wait(0, 1), Wait(0, 20), Wait(0, 30), End(0)); + JArray second = List(Wait(0, 10), Wait(0, 2), Wait(0, 20), Wait(0, 30), End(0)); + + ListMergeResult profile = Commands(Vanilla, ListPolicy.Unresolved, first, second); + ListMergeResult chosen = Commands(Vanilla, new ListPolicy(null, null, "m1"), first, second); + + Assert.Equal(Text(List(Wait(0, 10), Wait(0, 2), Wait(0, 1), Wait(0, 20), Wait(0, 30), End(0))), Text(chosen.List)); + Assert.Equal(profile.OrderFingerprint, chosen.OrderFingerprint); + } + + [Fact] + public void Commands_RunChangedTwoWays_IsAClash_ThePolicyPicksPerRun() + { + // m0 and m1 change the middle wait; m2 adds one at the end, clear of the clash. + JArray zero = List(Wait(0, 10), Wait(0, 21), Wait(0, 30), End(0)); + JArray one = List(Wait(0, 10), Wait(0, 22), Wait(0, 30), End(0)); + JArray two = List(Wait(0, 10), Wait(0, 20), Wait(0, 30), Wait(0, 40), End(0)); + + ListMergeResult open = Commands(Vanilla, ListPolicy.Unresolved, zero, one, two); + ListMergeResult picked = Commands(Vanilla, new ListPolicy(ResolutionKind.PickMod, "m1", null), zero, one, two); + ListMergeResult vanilla = Commands(Vanilla, new ListPolicy(ResolutionKind.PickVanilla, null, null), zero, one, two); + ListMergeResult elsewhere = Commands(Vanilla, new ListPolicy(ResolutionKind.PickMod, "m2", null), zero, one, two); + + Assert.Equal(["m0", "m1"], open.ClashMods); + Assert.Equal(["m2"], open.Contributors); + Assert.Equal(Text(List(Wait(0, 10), Wait(0, 22), Wait(0, 30), Wait(0, 40), End(0))), Text(picked.List)); + Assert.Equal(["m1", "m2"], picked.Contributors); + Assert.Equal(Text(List(Wait(0, 10), Wait(0, 20), Wait(0, 30), Wait(0, 40), End(0))), Text(vanilla.List)); + Assert.Equal(Text(vanilla.List), Text(elsewhere.List)); + Assert.Equal(open.ClashFingerprint, picked.ClashFingerprint); + Assert.NotEqual(open.ClashFingerprint, Commands(Vanilla, ListPolicy.Unresolved, zero, List(Wait(0, 10), Wait(0, 23), Wait(0, 30), End(0))).ClashFingerprint); + } + + [Fact] + public void Commands_EditsInDifferentBodiesOfOneBlock_MergeInsideIt() + { + JArray vanilla = List(Cmd(111, 0, 0, 1, 0), Wait(1, 1), End(1), Cmd(411, 0), Wait(1, 2), End(1), Cmd(412, 0), End(0)); + JArray then = List(Cmd(111, 0, 0, 1, 0), Wait(1, 1), Wait(1, 3), End(1), Cmd(411, 0), Wait(1, 2), End(1), Cmd(412, 0), End(0)); + JArray otherwise = List(Cmd(111, 0, 0, 1, 0), Wait(1, 1), End(1), Cmd(411, 0), End(1), Cmd(412, 0), End(0)); + + ListMergeResult result = Commands(vanilla, ListPolicy.Unresolved, then, otherwise); + + Assert.Equal(Text(List(Cmd(111, 0, 0, 1, 0), Wait(1, 1), Wait(1, 3), End(1), Cmd(411, 0), End(1), Cmd(412, 0), End(0))), Text(result.List)); + Assert.Empty(result.ClashMods); + Assert.Equal(["m0", "m1"], result.Contributors); + } + + [Fact] + public void Commands_MarkerOfOneSideAndABodyOfAnother_MergeInsideTheNode() + { + JArray vanilla = List(Cmd(102, 0, new JArray("A", "B"), 1, 0, 2, 0), Cmd(402, 0, 0, "A"), End(1), Cmd(402, 0, 1, "B"), End(1), Cmd(404, 0), End(0)); + JArray marker = List(Cmd(102, 0, new JArray("A", "B"), 1, 0, 2, 0), Cmd(402, 0, 0, "Left"), End(1), Cmd(402, 0, 1, "B"), End(1), Cmd(404, 0), End(0)); + JArray body = List(Cmd(102, 0, new JArray("A", "B"), 1, 0, 2, 0), Cmd(402, 0, 0, "A"), End(1), Cmd(402, 0, 1, "B"), Wait(1, 9), End(1), Cmd(404, 0), End(0)); + + ListMergeResult result = Commands(vanilla, ListPolicy.Unresolved, marker, body); + + Assert.Equal( + Text(List(Cmd(102, 0, new JArray("A", "B"), 1, 0, 2, 0), Cmd(402, 0, 0, "Left"), End(1), Cmd(402, 0, 1, "B"), Wait(1, 9), End(1), Cmd(404, 0), End(0))), + Text(result.List)); + Assert.Empty(result.ClashMods); + } + + [Fact] + public void Commands_SameMarkerChangedTwoWays_IsAClashOfTheNode() + { + JArray vanilla = List(Cmd(102, 0, new JArray("A", "B"), 1, 0, 2, 0), Cmd(402, 0, 0, "A"), End(1), Cmd(402, 0, 1, "B"), End(1), Cmd(404, 0), End(0)); + JArray zero = List(Cmd(102, 0, new JArray("A", "B"), 1, 0, 2, 0), Cmd(402, 0, 0, "Left"), End(1), Cmd(402, 0, 1, "B"), End(1), Cmd(404, 0), End(0)); + JArray one = List(Cmd(102, 0, new JArray("A", "B"), 1, 0, 2, 0), Cmd(402, 0, 0, "Right"), End(1), Cmd(402, 0, 1, "B"), End(1), Cmd(404, 0), End(0)); + + ListMergeResult result = Commands(vanilla, ListPolicy.Unresolved, zero, one); + + Assert.Equal(["m0", "m1"], result.ClashMods); + Assert.Equal(Text(vanilla), Text(result.List)); + } + + [Fact] + public void Commands_SideWhoseOnlyChangeLosesAClashInsideANode_DoesNotContribute() + { + // m0 renames a choice and changes the wait in its body; m1 changes that wait another way. + JArray vanilla = List(Cmd(102, 0, new JArray("A", "B"), 1, 0, 2, 0), Cmd(402, 0, 0, "A"), Wait(1, 5), End(1), Cmd(402, 0, 1, "B"), End(1), Cmd(404, 0), End(0)); + JArray zero = List(Cmd(102, 0, new JArray("A", "B"), 1, 0, 2, 0), Cmd(402, 0, 0, "Left"), Wait(1, 6), End(1), Cmd(402, 0, 1, "B"), End(1), Cmd(404, 0), End(0)); + JArray one = List(Cmd(102, 0, new JArray("A", "B"), 1, 0, 2, 0), Cmd(402, 0, 0, "A"), Wait(1, 7), End(1), Cmd(402, 0, 1, "B"), End(1), Cmd(404, 0), End(0)); + + ListMergeResult kept = Commands(vanilla, new ListPolicy(ResolutionKind.PickVanilla, null, null), zero, one); + ListMergeResult picked = Commands(vanilla, new ListPolicy(ResolutionKind.PickMod, "m1", null), zero, one); + + Assert.Equal(["m0", "m1"], kept.ClashMods); + Assert.Equal( + Text(List(Cmd(102, 0, new JArray("A", "B"), 1, 0, 2, 0), Cmd(402, 0, 0, "Left"), Wait(1, 5), End(1), Cmd(402, 0, 1, "B"), End(1), Cmd(404, 0), End(0))), + Text(kept.List)); + Assert.Equal(["m0"], kept.Contributors); + Assert.Equal(["m0", "m1"], picked.Contributors); + } + + [Fact] + public void Commands_InsertAtAnAmbiguousGapChanged_ChangesTheOrderFingerprint() + { + JArray first = List(Wait(0, 10), Wait(0, 1), Wait(0, 20), Wait(0, 30), End(0)); + JArray second = List(Wait(0, 10), Wait(0, 2), Wait(0, 20), Wait(0, 30), End(0)); + JArray updated = List(Wait(0, 10), Wait(0, 3), Wait(0, 20), Wait(0, 30), End(0)); + + ListMergeResult before = Commands(Vanilla, ListPolicy.Unresolved, first, second); + ListMergeResult after = Commands(Vanilla, ListPolicy.Unresolved, first, updated); + + // A stored order choice was made for the inserts the player saw, so new ones ask again (GR-X2). + Assert.Equal(before.OrderMods, after.OrderMods); + Assert.NotEqual(before.OrderFingerprint, after.OrderFingerprint); + } + + [Fact] + public void Commands_NewBranchAgainstAnEditInsideTheBlock_IsAClashOfTheBlock() + { + JArray vanilla = List(Cmd(111, 0, 0, 1, 0), Wait(1, 1), End(1), Cmd(412, 0), End(0)); + JArray withElse = List(Cmd(111, 0, 0, 1, 0), Wait(1, 1), End(1), Cmd(411, 0), End(1), Cmd(412, 0), End(0)); + JArray edited = List(Cmd(111, 0, 0, 1, 0), Wait(1, 2), End(1), Cmd(412, 0), End(0)); + + ListMergeResult result = Commands(vanilla, ListPolicy.Unresolved, withElse, edited); + + Assert.Equal(["m0", "m1"], result.ClashMods); + Assert.Equal(Text(vanilla), Text(result.List)); + } + + [Fact] + public void Commands_ClashDeepInsideABlock_TakesThePickedVersionOfThatRunOnly() + { + JArray vanilla = List(Cmd(112, 0), Wait(1, 1), Wait(1, 2), End(1), Cmd(413, 0), End(0)); + JArray zero = List(Cmd(112, 0), Wait(1, 5), Wait(1, 2), End(1), Cmd(413, 0), End(0)); + JArray one = List(Cmd(112, 0), Wait(1, 6), Wait(1, 2), Wait(1, 7), End(1), Cmd(413, 0), End(0)); + + ListMergeResult result = Commands(vanilla, new ListPolicy(ResolutionKind.PickVanilla, null, null), zero, one); + + Assert.Equal(["m0", "m1"], result.ClashMods); + Assert.Equal(Text(List(Cmd(112, 0), Wait(1, 1), Wait(1, 2), Wait(1, 7), End(1), Cmd(413, 0), End(0))), Text(result.List)); + } + + [Fact] + public void Commands_TwoNodesOfOneHeadAndAnInsertBetweenThem_AreAClash() + { + // m0 drops one of two If nodes of one head and edits the other: which one it kept is a guess. + JArray vanilla = List([.. If(1), .. If(2), End(0)]); + JArray zero = List([.. If(222), End(0)]); + JArray one = List([.. If(1), Wait(0, 5), .. If(2), End(0)]); + + ListMergeResult result = Commands(vanilla, ListPolicy.Unresolved, zero, one); + + Assert.Equal(["m0", "m1"], result.ClashMods); + Assert.Equal(Text(vanilla), Text(result.List)); + } + + [Fact] + public void Commands_SameNodeMovedTwoWays_IsAClashAndNeverACopy() + { + JArray zero = List(Wait(0, 20), Wait(0, 30), Wait(0, 10), End(0)); + JArray one = List(Wait(0, 20), Wait(0, 10), Wait(0, 30), End(0)); + + ListMergeResult open = Commands(Vanilla, ListPolicy.Unresolved, zero, one); + ListMergeResult picked = Commands(Vanilla, new ListPolicy(ResolutionKind.PickMod, "m1", null), zero, one); + + Assert.Equal(["m0", "m1"], open.ClashMods); + Assert.Equal(Text(Vanilla), Text(open.List)); + Assert.Equal(Text(one), Text(picked.List)); + } + + [Fact] + public void Commands_NodeChangedIntoACopyOfOneItsSideRemoved_IsAMove() + { + // m0 moves "y" to the end over "x"; the Show Text heads pair "x" with "y", but it is still a move. + JArray vanilla = List(Cmd(101, 0, "", 0), Cmd(401, 0, "y"), Wait(0, 1), Cmd(101, 0, "", 0), Cmd(401, 0, "x"), End(0)); + JArray moved = List(Wait(0, 1), Cmd(101, 0, "", 0), Cmd(401, 0, "y"), End(0)); + JArray edited = List(Cmd(101, 0, "", 0), Cmd(401, 0, "z"), Wait(0, 1), Cmd(101, 0, "", 0), Cmd(401, 0, "x"), End(0)); + + ListMergeResult result = Commands(vanilla, ListPolicy.Unresolved, moved, edited); + + Assert.Equal(["m0", "m1"], result.ClashMods); + Assert.Equal(Text(vanilla), Text(result.List)); + } + + [Fact] + public void Commands_NodeMovedIntoAnotherNodesBody_IsAMove() + { + JArray vanilla = List([Wait(0, 1), .. If(5), End(0)]); + JArray moved = List(Cmd(111, 0, 0, 5, 0), Wait(1, 1), Wait(1, 5), End(1), Cmd(412, 0), End(0)); + JArray edited = List([Wait(0, 2), .. If(5), End(0)]); + + ListMergeResult open = Commands(vanilla, ListPolicy.Unresolved, moved, edited); + + Assert.Equal(["m0", "m1"], open.ClashMods); + Assert.Equal(Text(vanilla), Text(open.List)); + Assert.Equal(Text(moved), Text(Commands(vanilla, new ListPolicy(ResolutionKind.PickMod, "m0", null), moved, edited).List)); + } + + [Fact] + public void Commands_NodeMovedOutOfABody_IsAMove() + { + JArray vanilla = List([.. If(5), Wait(0, 30), End(0)]); + JArray moved = List(Cmd(111, 0, 0, 5, 0), End(1), Cmd(412, 0), Wait(0, 30), Wait(0, 5), End(0)); + JArray edited = List([.. If(6), Wait(0, 30), End(0)]); + + ListMergeResult open = Commands(vanilla, ListPolicy.Unresolved, moved, edited); + + Assert.Equal(["m0", "m1"], open.ClashMods); + Assert.Equal(Text(vanilla), Text(open.List)); + } + + [Fact] + public void Commands_NodeTakenAwayWhileCopiesGoDeeper_IsStillAMove() + { + // m0 takes the first wait away, puts two copies in a new If and one after the last wait. + JArray vanilla = List(Wait(0, 3), Wait(0, 1), Wait(0, 2), End(0)); + JArray moved = List(Cmd(111, 0, 0, 1, 0), Wait(1, 3), Wait(1, 3), End(1), Cmd(412, 0), Wait(0, 2), Wait(0, 3), End(0)); + JArray cut = List(Wait(0, 2), End(0)); + + ListMergeResult open = Commands(vanilla, ListPolicy.Unresolved, moved, cut); + + Assert.Equal(["m0", "m1"], open.ClashMods); + Assert.Equal(Text(vanilla), Text(open.List)); + } + + [Fact] + public void Commands_NodeMovedBetweenBranches_ChangedTheWholeNode() + { + JArray vanilla = List(Cmd(111, 0, 0, 5, 0), Wait(1, 1), End(1), Cmd(411, 0), Wait(1, 2), End(1), Cmd(412, 0), End(0)); + JArray moved = List(Cmd(111, 0, 0, 5, 0), End(1), Cmd(411, 0), Wait(1, 2), Wait(1, 1), End(1), Cmd(412, 0), End(0)); + JArray edited = List(Cmd(111, 0, 0, 5, 0), Wait(1, 3), End(1), Cmd(411, 0), Wait(1, 2), End(1), Cmd(412, 0), End(0)); + + ListMergeResult open = Commands(vanilla, ListPolicy.Unresolved, moved, edited); + + Assert.Equal(["m0", "m1"], open.ClashMods); + Assert.Equal(Text(vanilla), Text(open.List)); + } + + [Fact] + public void Commands_NodeMovedDeeperInOneBranch_MergesWithAnEditOfAnother() + { + JArray vanilla = List( + Cmd(111, 0, 0, 5, 0), Wait(1, 1), Cmd(111, 1, 0, 6, 0), End(2), Cmd(412, 1), End(1), + Cmd(411, 0), Wait(1, 2), End(1), Cmd(412, 0), End(0)); + JArray deeper = List( + Cmd(111, 0, 0, 5, 0), Cmd(111, 1, 0, 6, 0), Wait(2, 1), End(2), Cmd(412, 1), End(1), + Cmd(411, 0), Wait(1, 2), End(1), Cmd(412, 0), End(0)); + JArray edited = List( + Cmd(111, 0, 0, 5, 0), Wait(1, 1), Cmd(111, 1, 0, 6, 0), End(2), Cmd(412, 1), End(1), + Cmd(411, 0), Wait(1, 3), End(1), Cmd(412, 0), End(0)); + + ListMergeResult result = Commands(vanilla, ListPolicy.Unresolved, deeper, edited); + + Assert.Empty(result.ClashMods); + Assert.Equal( + Text(List( + Cmd(111, 0, 0, 5, 0), Cmd(111, 1, 0, 6, 0), Wait(2, 1), End(2), Cmd(412, 1), End(1), + Cmd(411, 0), Wait(1, 3), End(1), Cmd(412, 0), End(0))), + Text(result.List)); + } + + [Fact] + public void Commands_InsertsOneSideHoldsInOrder_AreTakenOnceFromTheLongerRun() + { + JArray shorter = List(Wait(0, 10), Wait(0, 1), Wait(0, 3), Wait(0, 20), Wait(0, 30), End(0)); + JArray longer = List(Wait(0, 10), Wait(0, 1), Wait(0, 2), Wait(0, 3), Wait(0, 20), Wait(0, 30), End(0)); + + ListMergeResult result = Commands(Vanilla, ListPolicy.Unresolved, shorter, longer); + + Assert.Equal(Text(longer), Text(result.List)); + Assert.Empty(result.OrderMods); + Assert.Empty(result.ClashMods); + Assert.Equal(["m0", "m1"], result.Contributors); + } + + [Fact] + public void Sequence_FoldedInsertsBesideAnotherInsert_StayOrderAmbiguousWithEveryMod() + { + ListMergeResult result = Sequence( + JArray.Parse("[1]"), + ListPolicy.Unresolved, + JArray.Parse("[1,2]"), + JArray.Parse("[1,2,3]"), + JArray.Parse("[1,4]")); + + Assert.Equal("[1,2,3,4]", Text(result.List)); + Assert.Equal(["m0", "m1", "m2"], result.OrderMods); + } + + [Fact] + public void Commands_SwapAgainstAnEdit_IsAClash_EachPickKeepsOneVersionWhole() + { + JArray vanilla = List(Wait(0, 1), Wait(0, 2), End(0)); + JArray swap = List(Wait(0, 2), Wait(0, 1), End(0)); + JArray edit = List(Wait(0, 5), Wait(0, 2), End(0)); + + ListMergeResult open = Commands(vanilla, ListPolicy.Unresolved, swap, edit); + + Assert.Equal(["m0", "m1"], open.ClashMods); + Assert.Equal(Text(vanilla), Text(Commands(vanilla, new ListPolicy(ResolutionKind.PickVanilla, null, null), swap, edit).List)); + Assert.Equal(Text(swap), Text(Commands(vanilla, new ListPolicy(ResolutionKind.PickMod, "m0", null), swap, edit).List)); + Assert.Equal(Text(edit), Text(Commands(vanilla, new ListPolicy(ResolutionKind.PickMod, "m1", null), swap, edit).List)); + } + + [Fact] + public void Commands_EqualInsertsWrittenInAnotherPropertyOrder_AreOneInsert() + { + var reordered = new JObject { ["parameters"] = new JArray(5), ["indent"] = 0, ["code"] = 230 }; + JArray zero = List(Wait(0, 10), Wait(0, 5), Wait(0, 20), Wait(0, 30), End(0)); + JArray one = List(Wait(0, 10), reordered, Wait(0, 20), Wait(0, 30), End(0)); + + ListMergeResult result = Commands(Vanilla, ListPolicy.Unresolved, zero, one); + + Assert.Equal(5, result.List.Count); + Assert.Empty(result.OrderMods); + Assert.Empty(result.ClashMods); + Assert.Equal(["m0", "m1"], result.Contributors); + } + + [Fact] + public void Commands_SameModsInAnotherProfileOrder_KeepBothFingerprints() + { + JArray clashing = List(Wait(0, 10), Wait(0, 21), Wait(0, 30), End(0)); + JArray other = List(Wait(0, 10), Wait(0, 22), Wait(0, 30), End(0)); + JArray first = List(Wait(0, 10), Wait(0, 1), Wait(0, 20), Wait(0, 30), End(0)); + JArray second = List(Wait(0, 10), Wait(0, 2), Wait(0, 20), Wait(0, 30), End(0)); + + static ListMergeResult Run(params (JArray List, string Mod)[] sides) + { + return ListMerge.MergeCommands( + CommandTree.Parse(Vanilla)!, + sides.Select(side => new ListSide(CommandTree.Parse(side.List)!, [side.Mod])).ToList(), + ListPolicy.Unresolved); + } + + Assert.Equal(Run((clashing, "a"), (other, "b")).ClashFingerprint, Run((other, "b"), (clashing, "a")).ClashFingerprint); + Assert.Equal(Run((first, "a"), (second, "b")).OrderFingerprint, Run((second, "b"), (first, "a")).OrderFingerprint); + } + + [Fact] + public void Commands_VersionWrittenInAnotherPropertyOrder_KeepsTheClashFingerprint() + { + JArray zero = List(Wait(0, 10), Wait(0, 21), Wait(0, 30), End(0)); + JArray reordered = List(Wait(0, 10), new JObject { ["parameters"] = new JArray(21), ["indent"] = 0, ["code"] = 230 }, Wait(0, 30), End(0)); + JArray one = List(Wait(0, 10), Wait(0, 22), Wait(0, 30), End(0)); + + Assert.Equal( + Commands(Vanilla, ListPolicy.Unresolved, zero, one).ClashFingerprint, + Commands(Vanilla, ListPolicy.Unresolved, reordered, one).ClashFingerprint); + } + + [Fact] + public void Commands_BodyAddedToANodeAgainstAnEditOfItsLines_IsAClash() + { + // A code the parser does not know holds one body when deeper commands follow it (GR-T2). + JArray vanilla = List(Cmd(355, 0, "a"), Cmd(655, 0, "b"), End(0)); + JArray body = List(Cmd(355, 0, "a"), Cmd(655, 0, "b"), Wait(1, 1), End(1), End(0)); + JArray lines = List(Cmd(355, 0, "a"), Cmd(655, 0, "c"), End(0)); + + ListMergeResult open = Commands(vanilla, ListPolicy.Unresolved, body, lines); + + Assert.Equal(["m0", "m1"], open.ClashMods); + Assert.Equal(Text(body), Text(Commands(vanilla, new ListPolicy(ResolutionKind.PickMod, "m0", null), body, lines).List)); + } + + [Fact] + public void Sequence_ElementMovedTwoWays_IsAClash() + { + ListMergeResult result = Sequence(JArray.Parse("[1,2,3]"), ListPolicy.Unresolved, JArray.Parse("[2,3,1]"), JArray.Parse("[2,1,3]")); + + Assert.Equal(["m0", "m1"], result.ClashMods); + Assert.Equal("[1,2,3]", Text(result.List)); + } + + [Fact] + public void Sequence_ReplaceAndAppend_AreBothKept() + { + var vanilla = JArray.Parse("[{\"code\":11,\"value\":1},{\"code\":12,\"value\":2}]"); + + ListMergeResult result = Sequence( + vanilla, + ListPolicy.Unresolved, + JArray.Parse("[{\"code\":11,\"value\":9},{\"code\":12,\"value\":2}]"), + JArray.Parse("[{\"code\":11,\"value\":1},{\"code\":12,\"value\":2},{\"code\":13,\"value\":3}]")); + + Assert.Equal("[{\"code\":11,\"value\":9},{\"code\":12,\"value\":2},{\"code\":13,\"value\":3}]", Text(result.List)); + Assert.Empty(result.ClashMods); + Assert.Empty(result.OrderMods); + } + + [Fact] + public void Sequence_TwoAppends_AreOrderAmbiguous() + { + var vanilla = JArray.Parse("[1]"); + + ListMergeResult result = Sequence(vanilla, ListPolicy.Unresolved, JArray.Parse("[1,2]"), JArray.Parse("[1,3]")); + + Assert.Equal("[1,2,3]", Text(result.List)); + Assert.Equal(["m0", "m1"], result.OrderMods); + } + + [Fact] + public void Sequence_ElementChangedTwoWays_IsAClash() + { + ListMergeResult result = Sequence(JArray.Parse("[1,2]"), ListPolicy.Unresolved, JArray.Parse("[1,5]"), JArray.Parse("[1,6]")); + + Assert.Equal(["m0", "m1"], result.ClashMods); + Assert.Equal("[1,2]", Text(result.List)); + } + + [Fact] + public void CommonPairs_FindsALongestCommonSubsequence() + { + List<(int Left, int Right)> pairs = ListMerge.CommonPairs([1, 2, 3, 4, 5], 0, 5, [1, 3, 9, 4, 5], 0, 5); + + Assert.Equal([(0, 0), (2, 1), (3, 3), (4, 4)], pairs); + } + + [Fact] + public void CommonPairs_PastTheCellBound_KeepsOnlyTheCommonEnds() + { + int size = (int)Math.Sqrt(ListMerge.MaxCells) + 1; + int[] left = [-1, .. Enumerable.Range(0, size), -2]; + int[] right = [-1, .. Enumerable.Range(0, size).Reverse(), -2]; + + List<(int Left, int Right)> pairs = ListMerge.CommonPairs(left, 0, left.Length, right, 0, right.Length); + + Assert.Equal([(0, 0), (left.Length - 1, right.Length - 1)], pairs); + } +} diff --git a/RPGModder.Tests/MergeContract/ComposerContractTests.cs b/RPGModder.Tests/MergeContract/ComposerContractTests.cs index 1cbb3dc..8c3419f 100644 --- a/RPGModder.Tests/MergeContract/ComposerContractTests.cs +++ b/RPGModder.Tests/MergeContract/ComposerContractTests.cs @@ -47,7 +47,7 @@ public void Compose_DifferentSequenceAndCommandEdits_AreSequenceAndLogicClashes( { BaseFileSet baseFiles = BaseFileSet.From(new[] { - CreateBaseFile("data/Items.json", "[null,{\"id\":1,\"name\":\"Herb\",\"effects\":[]}]"), + CreateBaseFile("data/Items.json", "[null,{\"id\":1,\"name\":\"Herb\",\"effects\":[{\"code\":10}]}]"), CreateBaseFile("data/CommonEvents.json", "[null,{\"id\":1,\"name\":\"Evt\",\"list\":[]}]") }); diff --git a/RPGModder.Tests/MergeContract/MapMergeContractTests.cs b/RPGModder.Tests/MergeContract/MapMergeContractTests.cs index ccba3b2..ec3394a 100644 --- a/RPGModder.Tests/MergeContract/MapMergeContractTests.cs +++ b/RPGModder.Tests/MergeContract/MapMergeContractTests.cs @@ -133,9 +133,14 @@ public void Compose_PageCountChangeByTwoMods_IsAPageClash() [Fact] public void Compose_MapEventPageSettingVersusListClash_DistinguishesPageClashFromLogicClash() { + // The page waits once; each mod replaces the wait with a command of its own, one run changed two ways. + string vanilla = VanillaMapJson.Replace( + "\"list\":[{\"code\":0,\"indent\":0,\"parameters\":[]}],\"moveFrequency\"", + "\"list\":[{\"code\":230,\"indent\":0,\"parameters\":[60]},{\"code\":0,\"indent\":0,\"parameters\":[]}],\"moveFrequency\"", + StringComparison.Ordinal); BaseFileSet baseFiles = BaseFileSet.From(new[] { - CreateBaseFile("data/Map001.json", VanillaMapJson) + CreateBaseFile("data/Map001.json", vanilla) }); RecordKey event1Key = new("data/map001.json", "event:1");