diff --git a/RPGModder.Core/Merge/Composer.cs b/RPGModder.Core/Merge/Composer.cs
index 8cccf1b..9678e74 100644
--- a/RPGModder.Core/Merge/Composer.cs
+++ b/RPGModder.Core/Merge/Composer.cs
@@ -15,8 +15,9 @@ public static class Composer
{
///
/// The plan, when lane A ran : an IdClash one of its offers settles lists
- /// and carries rules.remap_unchecked (GR-R11), and its diagnostics join
- /// the plan's.
+ /// and carries rules.remap_unchecked (GR-R11); each switch or variable
+ /// it found shared is a StateIdOverlap , which lists Remap too when an offer settles it and takes in
+ /// the mods' different names for it (GR-R15); and its diagnostics join the plan's.
///
public static MergePlan Compose(
IReadOnlyList changeSets,
@@ -47,7 +48,8 @@ public static MergePlan Compose(
// The writer stamps versionId into System.json (C-7), so a broken one must stop the plan here, not there.
BaseFile? system = baseFiles.Find(RpgDataSchema.SystemFileKey);
- if (system is not null && !ChangeSetBuilder.TryReadBase(system, out _, out OperationDiagnostic? systemProblem))
+ JToken? systemRoot = null;
+ if (system is not null && !ChangeSetBuilder.TryReadBase(system, out systemRoot, out OperationDiagnostic? systemProblem))
{
diagnostics.Add(systemProblem);
}
@@ -59,11 +61,19 @@ public static MergePlan Compose(
var ops = new List();
var collisions = new List<(Collision Collision, CollisionOutcome Outcome)>();
IReadOnlyList offers = remapPlan?.Offers ?? [];
- foreach (List cluster in Cluster(DropFiller(Group(ordered), changeSets, priorities)))
+ 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);
}
+ foreach (SharedStateId shared in remapPlan?.SharedStateIds ?? [])
+ {
+ Collision collision = OfferRemaps(StateOverlap(shared), offers, diagnostics);
+ collisions.Add((collision, Decide(collision, choices, diagnostics)));
+ }
+
ComposePluginOrder(ops, choices, priorities, collisions, diagnostics);
ops.Sort((left, right) => ChangeSetBuilder.CompareOps(left.Op, right.Op));
@@ -138,6 +148,108 @@ private static List DropFiller(List groups, IReadOnlyList
+ /// A mod that names a switch or variable past the end of vanilla's list pads the list with empty names up to it,
+ /// so an empty name where vanilla has none only pads: it yields to another mod's name at that id instead of
+ /// clashing with it. Two different names still clash.
+ ///
+ private static List DropPaddingNames(List groups, JToken? system)
+ {
+ foreach (OpGroup group in groups)
+ {
+ if (group.Variants.Count < 2 || !TryNameSlot(group, out string list, out int index) ||
+ !IsEmptyName((system?[list] as JArray)?.ElementAtOrDefault(index)))
+ {
+ continue;
+ }
+
+ if (group.Variants.Any(variant => !IsPadding(variant.Op)))
+ {
+ group.Variants.RemoveAll(variant => IsPadding(variant.Op));
+ }
+ }
+
+ return groups;
+ }
+
+ ///
+ /// GR-R15 (the owner, 2026-11-12): different names for a switch or variable the mods share are part of its
+ /// StateIdOverlap , not a clash of their own. The name of a mod that stays is kept, the latest in profile
+ /// order when several stay; a mod that takes its offered move carries its own name to the new id.
+ ///
+ private static List FoldSharedNames(List groups, RemapPlan? plan, Dictionary priorities)
+ {
+ if (plan is null || plan.SharedStateIds.Count == 0)
+ {
+ return groups;
+ }
+
+ foreach (OpGroup group in groups)
+ {
+ if (group.Variants.Count < 2 || !TryNameSlot(group, out string list, out int id))
+ {
+ continue;
+ }
+
+ IdKind kind = list == RpgDataSchema.SwitchNamesProperty ? IdKind.Switch : IdKind.Variable;
+ SharedStateId? shared = plan.SharedStateIds.FirstOrDefault(item => item.Kind == kind && item.Id == id);
+
+ // Only the names the sharing mods give fold. Anything else at the slot (another mod's name, a list cut
+ // short, a null) still clashes.
+ if (shared is null || group.Variants.Any(variant =>
+ !IsName(variant.Op) || variant.ModIds.Any(modId => !shared.ModIds.Contains(modId, StringComparer.Ordinal))))
+ {
+ continue;
+ }
+
+ bool Moves(string modId) => plan.Offers.Any(offer => offer.ModId == modId && offer.Kind == kind && offer.FromId == id);
+ List staying = group.Variants.SelectMany(variant => variant.ModIds).Where(modId => !Moves(modId)).ToList();
+ Variant kept = staying.Count == 0
+ ? Latest(group.Variants, priorities)
+ : group.Variants.First(variant => variant.ModIds.Contains(LatestMod(staying, priorities), StringComparer.Ordinal));
+ group.Variants.RemoveAll(variant => !ReferenceEquals(variant, kept));
+ }
+
+ return groups;
+ }
+
+ /// True when sets one name of System.json 's switches or variables .
+ private static bool TryNameSlot(OpGroup group, out string list, out int index)
+ {
+ list = "";
+ index = 0;
+ if (group.Key != RemapPlaces.StateKey || MergePath.IsPseudoLeaf(group.Path))
+ {
+ return false;
+ }
+
+ IReadOnlyList segments = MergePath.Parse(group.Path);
+ if (segments.Count != 2 || segments[1].Name is not null ||
+ segments[0].Name is not (RpgDataSchema.SwitchNamesProperty or RpgDataSchema.VariableNamesProperty))
+ {
+ return false;
+ }
+
+ list = segments[0].Name!;
+ index = segments[1].Index;
+ return true;
+ }
+
+ private static bool IsName(ChangeOp op)
+ {
+ return op.Kind == ChangeKind.SetLeaf && op.Value is JValue { Type: JTokenType.String };
+ }
+
+ private static bool IsPadding(ChangeOp op)
+ {
+ return op.Kind == ChangeKind.SetLeaf && op.Value is JValue { Value: string { Length: 0 } };
+ }
+
+ private static bool IsEmptyName(JToken? name)
+ {
+ return name is null || name.Type == JTokenType.Null || name is JValue { Value: string { Length: 0 } };
+ }
+
///
/// GR-C2: a group joins the outermost group whose place contains it: a whole-file value, else the shortest
/// ancestor path in the same record. The head comes first in each cluster, the rest follow in place order.
@@ -263,12 +375,26 @@ private static void ComposeCluster(
/// The variant of the mod latest in profile order; equal priorities fall back to the mod id that sorts last.
private static Variant LatestInProfileOrder(OpGroup group, Dictionary priorities)
{
- return group.Variants
+ return Latest(group.Variants, priorities);
+ }
+
+ private static Variant Latest(IEnumerable variants, Dictionary priorities)
+ {
+ return variants
.OrderByDescending(variant => variant.ModIds.Max(id => priorities[id]))
.ThenByDescending(variant => variant.ModIds.Max(StringComparer.Ordinal), StringComparer.Ordinal)
.First();
}
+ /// The mod latest in profile order, with the same tie-break as .
+ private static string LatestMod(IEnumerable modIds, Dictionary priorities)
+ {
+ return modIds
+ .OrderByDescending(id => priorities[id])
+ .ThenByDescending(id => id, StringComparer.Ordinal)
+ .First();
+ }
+
///
/// GR-C10: entries from more than one mod behind one anchor are an OrderAmbiguous collision (seam 11.1),
/// settled here, after every cluster, because the anchors are only final once each PluginOrderClash is.
@@ -403,7 +529,9 @@ private static string OrderFingerprint(List ops, List entries)
///
/// GR-R11: an IdClash an offer settles lists Remap , stays blocking and has no default, and each
/// offer carries the warning once, though a map offer settles two collisions (its file and its tree record).
- /// Lane A carries a chosen Remap out by recording the offer (seam 4.3).
+ /// A StateIdOverlap an offer settles lists Remap and keeps its default; the planner warns of its
+ /// plugin numbers itself, since such an offer is made for every move. Lane A carries a chosen Remap out by
+ /// recording (seam 4.3).
///
private static Collision OfferRemaps(Collision collision, IReadOnlyList offers, List diagnostics)
{
@@ -413,7 +541,7 @@ private static Collision OfferRemaps(Collision collision, IReadOnlyList
return collision;
}
- foreach (IdRemap offer in settling)
+ foreach (IdRemap offer in settling.Where(item => !RpgDataSchema.IsStateKind(item.Kind)))
{
diagnostics.Add(new OperationDiagnostic(
DiagnosticCodes.RulesRemapUnchecked,
@@ -484,6 +612,26 @@ private static Collision MakeCollision(List cluster, List mods)
return new Collision(id, kind, head.Key, head.Path, mods, IsBlocking(kind), allowed, Fingerprint(cluster));
}
+ ///
+ /// GR-R15: a switch or variable the mods share, on its name in System.json . Sharing may be meant, so it is
+ /// a warning the player accepts by default; no value takes part, so the fingerprint is the id and the mods.
+ ///
+ private static Collision StateOverlap(SharedStateId shared)
+ {
+ string path = RemapPlaces.StatePath(shared.Kind, shared.Id);
+ const CollisionKind kind = CollisionKind.StateIdOverlap;
+ var entries = new JArray(shared.Kind.ToString(), shared.Id, new JArray(shared.ModIds.ToArray()));
+ return new Collision(
+ CollisionId(kind, RemapPlaces.StateKey, path, shared.ModIds),
+ kind,
+ RemapPlaces.StateKey,
+ path,
+ shared.ModIds,
+ IsBlocking(kind),
+ AllowedFor(kind),
+ MergeJson.Sha256Hex(MergeJson.Write(entries)));
+ }
+
///
/// GR-X1: the first 16 hex characters of SHA-256 over the kind, file, record, path and sorted mod ids, one per
/// line. No value takes part, so a mod update keeps the player's choice.
@@ -670,7 +818,12 @@ public void Add(ChangeOp op, string modId)
{
if (variant.Op.Kind == op.Kind && ValuesEqual(variant.Op.Value, op.Value))
{
- variant.ModIds.Add(modId);
+ // One mod may hold two equal ops at a place: a moved name over its own empty one.
+ if (!variant.ModIds.Contains(modId, StringComparer.Ordinal))
+ {
+ variant.ModIds.Add(modId);
+ }
+
return;
}
}
diff --git a/RPGModder.Core/Merge/IdRemapPlanner.States.cs b/RPGModder.Core/Merge/IdRemapPlanner.States.cs
new file mode 100644
index 0000000..7fca441
--- /dev/null
+++ b/RPGModder.Core/Merge/IdRemapPlanner.States.cs
@@ -0,0 +1,333 @@
+using RPGModder.Core.Models;
+using RPGModder.Core.Operations;
+using RPGModder.Core.Services;
+using System.Globalization;
+
+namespace RPGModder.Core.Merge;
+
+/// Switches and variables (guide 3.11, step 3): shared ids are found and a move is only ever offered.
+public static partial class IdRemapPlanner
+{
+ private static readonly IdKind[] StateKinds = [IdKind.Switch, IdKind.Variable];
+
+ ///
+ /// GR-R15 for switches and variables: an id two enabled mods use and vanilla does not is shared, and the plan lists
+ /// it once ( ). Sharing may be meant, so no shared id moves on its own: each party
+ /// GR-R10 would move is offered a move of every id it must take along, on consecutive targets (GR-R14). A party
+ /// moves only when its range holds no vanilla id, no id it has a recorded entry for, and no id it names where a
+ /// move cannot follow (GR-R9). With no scan of vanilla, nothing is shared.
+ ///
+ private static void PlanStates(StateInputs inputs, StateResult result)
+ {
+ if (inputs.Vanilla is null)
+ {
+ return;
+ }
+
+ foreach (IdKind kind in StateKinds)
+ {
+ int limit = RpgDataSchema.RemapLimit(kind, inputs.Engine) ?? 0;
+ var vanillaIds = new HashSet(inputs.Vanilla.Of(kind));
+ var claims = new List();
+ foreach (RemapMod mod in inputs.Mods.Where(item => item.Enabled))
+ {
+ string modId = mod.ChangeSet.ModId;
+ bool deployed = inputs.Deployed.Contains(modId);
+ ModReferences references = inputs.ReferencesOf(mod);
+ foreach (int id in references.StateIds(kind, limit))
+ {
+ // An entry in force uses its target even when vanilla has come to use the old id.
+ bool pinned = inputs.Pins.TryGetValue((modId, kind, "", id), out int toId);
+ if (pinned)
+ {
+ claims.Add(new StateClaim(mod, id, toId, Pinned: true, deployed));
+ }
+
+ // A range the entries leave behind still reads the old id (GR-R14), so the mod uses that too.
+ if (!vanillaIds.Contains(id) && (!pinned || SplitsRange(new IdRemap(modId, kind, "", id, toId), references, inputs.Pins)))
+ {
+ claims.Add(new StateClaim(mod, id, id, Pinned: false, deployed));
+ }
+ }
+ }
+
+ MoveOwnTargets(claims, kind, vanillaIds, inputs, limit, result);
+
+ // One offer per mod and range, however many shared ids the range holds.
+ var offered = new HashSet<(string ModId, int Low)>();
+ foreach (IGrouping shared in claims.GroupBy(claim => claim.Effective).OrderBy(group => group.Key))
+ {
+ List parties = shared
+ .DistinctBy(claim => claim.Mod.ChangeSet.ModId)
+ .OrderBy(claim => claim.Rank)
+ .ThenBy(claim => claim.Mod.ChangeSet.Priority)
+ .ThenBy(claim => claim.Mod.ChangeSet.ModId, StringComparer.Ordinal)
+ .ToList();
+ if (parties.Count < 2)
+ {
+ continue;
+ }
+
+ result.Shared.Add(new SharedStateId(
+ kind,
+ shared.Key,
+ parties.Select(claim => claim.Mod.ChangeSet.ModId).Order(StringComparer.Ordinal).ToList()));
+
+ // GR-R10: every party that cannot move stays; when every party can, the first in order stays.
+ var closures = parties.ToDictionary(claim => claim, claim => claim.Pinned ? null : Closure(claim, kind, vanillaIds, inputs, limit));
+ List staying = parties.Where(claim => closures[claim] is null).ToList();
+ if (staying.Count == 0)
+ {
+ staying.Add(parties[0]);
+ }
+
+ foreach (StateClaim mover in parties.Except(staying))
+ {
+ (int low, int high) = closures[mover]!.Value;
+ if (offered.Add((mover.Mod.ChangeSet.ModId, low)))
+ {
+ Offer(mover, kind, low, high, inputs, result);
+ }
+ }
+ }
+ }
+ }
+
+ ///
+ /// A mod whose new switch or variable is the target of its own entry in force would read one id for two
+ /// meanings. The new id moves, with every id its ranges take along, onto consecutive free ids, as a new entry
+ /// (the owner, 2026-11-12; GR-R10 moves a record so). When it cannot, the two meanings share the id and the plan
+ /// warns with rules.remap_stale_reference . When a plugin file the mod ships names one of the ids, the move
+ /// is only offered ( ).
+ ///
+ private static void MoveOwnTargets(List claims, IdKind kind, HashSet vanillaIds, StateInputs inputs, int limit, StateResult result)
+ {
+ foreach (IGrouping mine in claims.GroupBy(claim => claim.Mod.ChangeSet.ModId).ToList())
+ {
+ var targets = mine.Where(claim => claim.Pinned).ToDictionary(claim => claim.Effective, claim => claim.Id);
+ var moved = new HashSet();
+ var offered = new HashSet();
+ foreach (StateClaim own in mine.Where(claim => !claim.Pinned && targets.ContainsKey(claim.Id)).OrderBy(claim => claim.Id))
+ {
+ if (moved.Contains(own.Id) || offered.Contains(own.Id))
+ {
+ continue;
+ }
+
+ (int Low, int High)? run = Closure(own, kind, vanillaIds, inputs, limit);
+ int? start = run is null ? null : inputs.Targets.TakeRun(kind, "", run.Value.High - run.Value.Low + 1);
+ if (start is null)
+ {
+ result.Diagnostics.Add(new OperationDiagnostic(
+ DiagnosticCodes.RulesRemapStaleReference,
+ string.Create(
+ CultureInfo.InvariantCulture,
+ $"Mod {mine.Key}: {kind} {own.Id} is new in the mod and is also where its recorded entry moved {kind} {targets[own.Id]}, and the new id cannot move, so both use {kind} {own.Id}."),
+ DiagnosticSeverity.Warning,
+ mine.Key));
+ continue;
+ }
+
+ List group = Enumerable.Range(run!.Value.Low, run.Value.High - run.Value.Low + 1)
+ .Select(id => new IdRemap(mine.Key, kind, "", id, start.Value + (id - run.Value.Low)))
+ .ToList();
+ ModReferences references = inputs.ReferencesOf(own.Mod);
+ if (group.Any(remap => references.IsUnchecked(remap.FromId)))
+ {
+ OfferOwn(own, targets[own.Id], group, claims, result);
+ offered.UnionWith(group.Select(remap => remap.FromId));
+ continue;
+ }
+
+ result.Moves.AddRange(group);
+ moved.UnionWith(group.Select(remap => remap.FromId));
+ }
+
+ // Fresh targets are free, so the moved ids share nothing any more.
+ claims.RemoveAll(claim => claim.Mod.ChangeSet.ModId == mine.Key && !claim.Pinned && moved.Contains(claim.Id));
+ }
+ }
+
+ ///
+ /// GR-R11 (the owner, 2026-11-17): a plugin file the mod ships holds a number of , so the
+ /// move of the mod's new id off its own entry's target is only offered. Until the player takes it, both meanings
+ /// share the id; when no other mod uses the id, that is a StateIdOverlap of the mod alone, which carries
+ /// the offer. When another mod does, the overlap the mods share carries it.
+ ///
+ private static void OfferOwn(StateClaim own, int entryFrom, List group, List claims, StateResult result)
+ {
+ string modId = own.Mod.ChangeSet.ModId;
+ result.Offers.AddRange(group);
+ result.Groups.Add(group);
+ if (!claims.Any(claim => claim.Effective == own.Id && claim.Mod.ChangeSet.ModId != modId))
+ {
+ result.Shared.Add(new SharedStateId(group[0].Kind, own.Id, [modId]));
+ }
+
+ result.Diagnostics.Add(new OperationDiagnostic(
+ DiagnosticCodes.RulesRemapUnchecked,
+ string.Create(
+ CultureInfo.InvariantCulture,
+ $"Mod {modId}: {group[0].Kind} {own.Id} is new in the mod and is also where its recorded entry moved {group[0].Kind} {entryFrom}. It can move to {group[0].ToId} onward, but a plugin file the mod ships contains one of those numbers, so the move is only offered."),
+ DiagnosticSeverity.Warning,
+ modId));
+ }
+
+ ///
+ /// The ids a move of 's id must take along: every range of the mod that holds one of them,
+ /// until none adds more (GR-R14). null when one of them cannot move.
+ ///
+ private static (int Low, int High)? Closure(StateClaim claim, IdKind kind, HashSet vanillaIds, StateInputs inputs, int limit)
+ {
+ ModReferences references = inputs.ReferencesOf(claim.Mod);
+ List<(int First, int Last)> ranges = references.RangesOf(kind).Where(range => range.Last >= Math.Max(range.First, 1)).ToList();
+ int low = claim.Id;
+ int high = claim.Id;
+ bool grew = true;
+ while (grew)
+ {
+ grew = false;
+ foreach ((int first, int last) in ranges)
+ {
+ int start = Math.Max(first, 1);
+ if (start <= high && last >= low && (start < low || last > high))
+ {
+ low = Math.Min(low, start);
+ high = Math.Max(high, last);
+ grew = true;
+ }
+ }
+ }
+
+ if (high > limit)
+ {
+ return null;
+ }
+
+ string modId = claim.Mod.ChangeSet.ModId;
+ for (int id = low; id <= high; id++)
+ {
+ if (vanillaIds.Contains(id) || inputs.Pins.ContainsKey((modId, kind, "", id)) || references.Blocks(kind, id))
+ {
+ return null;
+ }
+ }
+
+ return (low, high);
+ }
+
+ ///
+ /// Offers a move of every id from to onto consecutive free ids, in
+ /// order, unless that passes the limit (GR-R6). A number in a shipped plugin file makes the offer carry
+ /// rules.remap_unchecked (GR-R11).
+ ///
+ private static void Offer(StateClaim mover, IdKind kind, int low, int high, StateInputs inputs, StateResult result)
+ {
+ int? start = inputs.Targets.TakeRun(kind, "", high - low + 1);
+ if (start is null)
+ {
+ return;
+ }
+
+ string modId = mover.Mod.ChangeSet.ModId;
+ List group = Enumerable.Range(low, high - low + 1)
+ .Select(id => new IdRemap(modId, kind, "", id, start.Value + (id - low)))
+ .ToList();
+ result.Offers.AddRange(group);
+ result.Groups.Add(group);
+
+ ModReferences references = inputs.ReferencesOf(mover.Mod);
+ if (group.Any(remap => references.IsUnchecked(remap.FromId)))
+ {
+ string ids = low == high
+ ? low.ToString(CultureInfo.InvariantCulture)
+ : string.Create(CultureInfo.InvariantCulture, $"{low} to {high}");
+ result.Diagnostics.Add(new OperationDiagnostic(
+ DiagnosticCodes.RulesRemapUnchecked,
+ string.Create(
+ CultureInfo.InvariantCulture,
+ $"Mod {modId}: {kind} {ids} can move to {start.Value} onward to stop sharing an id with another mod, but a plugin file the mod ships contains one of those numbers."),
+ DiagnosticSeverity.Warning,
+ modId));
+ }
+ }
+
+ ///
+ /// GR-R14 for an entry in force: a range of the mod that holds its old id still reads the old ids unless the mod's
+ /// entries move the whole range onto consecutive ids, in order.
+ ///
+ private static bool SplitsRange(IdRemap remap, ModReferences references, Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int> pins)
+ {
+ if (!RpgDataSchema.IsStateKind(remap.Kind))
+ {
+ return false;
+ }
+
+ foreach ((int first, int last) in references.RangesOf(remap.Kind))
+ {
+ int low = Math.Max(first, 1);
+ if (remap.FromId < low || remap.FromId > last)
+ {
+ continue;
+ }
+
+ if ((long)last - low + 1 > pins.Count || !pins.TryGetValue((remap.ModId, remap.Kind, remap.Scope, low), out int start))
+ {
+ return true;
+ }
+
+ for (int id = low + 1; id <= last; id++)
+ {
+ if (!pins.TryGetValue((remap.ModId, remap.Kind, remap.Scope, id), out int target) || target != start + (id - low))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /// The highest switch or variable id an installed mod names, enabled or not, so no target lands on one.
+ private static int HighestStateId(IEnumerable mods, IdKind kind, Func referencesOf, int limit)
+ {
+ int highest = 0;
+ foreach (RemapMod mod in mods)
+ {
+ SortedSet ids = referencesOf(mod).StateIds(kind, limit);
+ highest = Math.Max(highest, ids.Count == 0 ? 0 : ids.Max);
+ }
+
+ return highest;
+ }
+
+ private sealed record StateInputs(
+ List Mods,
+ Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int> Pins,
+ HashSet Deployed,
+ VanillaStateIds? Vanilla,
+ Func ReferencesOf,
+ Targets Targets,
+ RpgMakerEngine? Engine);
+
+ private sealed class StateResult
+ {
+ /// Moves the plan makes on its own: a mod's new ids off its own entries' targets.
+ public List Moves { get; } = new();
+
+ public List Offers { get; } = new();
+
+ public List> Groups { get; } = new();
+
+ public List Shared { get; } = new();
+
+ public List Diagnostics { get; } = new();
+ }
+
+ /// One enabled mod's use of a switch or variable vanilla does not use, at the id it has after its recorded entry.
+ private sealed record StateClaim(RemapMod Mod, int Id, int Effective, bool Pinned, bool Deployed)
+ {
+ /// GR-R4: a recorded entry, then a mod in DeployedMods , then the rest.
+ public int Rank => Pinned ? 0 : Deployed ? 1 : 2;
+ }
+}
diff --git a/RPGModder.Core/Merge/IdRemapPlanner.cs b/RPGModder.Core/Merge/IdRemapPlanner.cs
index e6d92ef..8804fea 100644
--- a/RPGModder.Core/Merge/IdRemapPlanner.cs
+++ b/RPGModder.Core/Merge/IdRemapPlanner.cs
@@ -9,9 +9,10 @@ namespace RPGModder.Core.Merge;
///
/// Decides which added ids move before composition (guide 3.11, GR-R3 to GR-R12): map events, maps and the twelve
-/// database kinds. The result does not depend on the order of any input.
+/// database kinds move; a switch or variable two mods share is only offered a move (IdRemapPlanner.States.cs). The
+/// result does not depend on the order of any input.
///
-public static class IdRemapPlanner
+public static partial class IdRemapPlanner
{
/// Trait 55, Slot Type, whose data 1 is Dual Wield (MV and MZ Game_Actor.prototype.isDualWield ).
private const int SlotTypeTrait = 55;
@@ -32,14 +33,20 @@ public static class IdRemapPlanner
///
///
/// The game's engine, which sets the highest id a move may give (GR-R6): maps 2000 on MZ and 999 otherwise,
- /// database records 9999 on MZ and 999 otherwise, events 999. An unknown engine (null ) gets MV's limits.
+ /// database records 9999 on MZ and 999 otherwise, events 999, switches and variables 5000. An unknown engine
+ /// (null ) gets MV's limits.
+ ///
+ ///
+ /// What found in vanilla's data files. Without it no switch or variable is
+ /// shared and none is offered a move; recorded entries for them still apply, and none counts as taken.
///
public static RemapPlan Plan(
IReadOnlyList installed,
IReadOnlyList recorded,
IReadOnlyCollection deployedMods,
BaseFileSet baseFiles,
- RpgMakerEngine? engine)
+ RpgMakerEngine? engine,
+ VanillaStateIds? vanillaStates = null)
{
ArgumentNullException.ThrowIfNull(installed);
ArgumentNullException.ThrowIfNull(recorded);
@@ -58,7 +65,11 @@ public static RemapPlan Plan(
var added = mods.ToDictionary(mod => mod.ChangeSet.ModId, mod => AddedIdIndex.Of(mod.ChangeSet), StringComparer.Ordinal);
var deployed = new HashSet(deployedMods, StringComparer.Ordinal);
var diagnostics = new List();
- Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int> pins = Pins(mods, added, recorded, baseFiles, diagnostics);
+ var references = new Dictionary(StringComparer.Ordinal);
+ var dualWield = new Lazy(() => IsDualWield(mods, baseFiles));
+ Func referencesOf = mod => ReferencesOf(mod, dualWield, engine, references);
+ Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int> pins =
+ Pins(mods, added, recorded, baseFiles, engine, vanillaStates, referencesOf, diagnostics);
var claims = new List();
foreach (RemapMod mod in mods.Where(item => item.Enabled))
@@ -71,10 +82,14 @@ public static RemapPlan Plan(
}
}
- var targets = new Targets(added.Values.SelectMany(list => list).ToList(), recorded, baseFiles, engine);
- var references = new Dictionary(StringComparer.Ordinal);
- var dualWield = new Lazy(() => IsDualWield(mods, baseFiles));
- StaleReferences(mods, pins, mod => ReferencesOf(mod, dualWield, engine, references), diagnostics);
+ var targets = new Targets(
+ added.Values.SelectMany(list => list).ToList(),
+ recorded,
+ baseFiles,
+ engine,
+ vanillaStates,
+ kind => HighestStateId(mods, kind, referencesOf, RpgDataSchema.RemapLimit(kind, engine) ?? 0));
+ StaleReferences(mods, pins, referencesOf, diagnostics);
var moves = new List();
var offers = new List();
IEnumerable> groups = claims
@@ -93,7 +108,7 @@ public static RemapPlan Plan(
(IdKind kind, string scope, _) = group.Key;
foreach (Party party in parties)
{
- party.Classify(kind, claim => ReferencesOf(claim.Mod, dualWield, engine, references), claim => IsVanillaMapFile(kind, claim.Added.Id, baseFiles));
+ party.Classify(kind, claim => referencesOf(claim.Mod), claim => IsVanillaMapFile(kind, claim.Added.Id, baseFiles));
}
// GR-R4 and GR-R10: the parties that cannot move stay; when every party can, the first in order stays.
@@ -138,26 +153,41 @@ public static RemapPlan Plan(
}
}
+ var states = new StateResult();
+ PlanStates(new StateInputs(mods, pins, deployed, vanillaStates, referencesOf, targets, engine), states);
+ moves.AddRange(states.Moves);
+ offers.AddRange(states.Offers);
+ diagnostics.AddRange(states.Diagnostics);
+
List remaps = pins
.Select(pin => new IdRemap(pin.Key.ModId, pin.Key.Kind, pin.Key.Scope, pin.Key.FromId, pin.Value))
.Concat(moves)
.ToList();
- return new RemapPlan(Sorted(remaps), Sorted(moves), Sorted(offers), diagnostics);
+ return new RemapPlan(Sorted(remaps), Sorted(moves), Sorted(offers), diagnostics)
+ {
+ SharedStateIds = states.Shared,
+ OfferGroups = states.Groups
+ };
}
///
/// GR-R12: a recorded entry stands while its mod is enabled and still adds the old id. Two entries for one old
/// id cannot both stand; the one with the lowest target does, so the input order never decides. An entry whose
/// target vanilla now uses (a game update filled a hole) stands no more: the old id is planned again, and when no
- /// other entry stands for it the plan carries rules.remap_target_taken (the owner, 2026-11-12).
+ /// other entry stands for it the plan carries rules.remap_target_taken (the owner, 2026-11-12). A switch or
+ /// variable entry stands while its mod still names the old id, and its target is taken when vanilla uses it.
///
private static Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int> Pins(
List mods,
Dictionary> added,
IReadOnlyList recorded,
BaseFileSet baseFiles,
+ RpgMakerEngine? engine,
+ VanillaStateIds? vanillaStates,
+ Func referencesOf,
List diagnostics)
{
+ Dictionary byId = mods.ToDictionary(mod => mod.ChangeSet.ModId, StringComparer.Ordinal);
var taken = new List();
var enabled = new HashSet(mods.Where(mod => mod.Enabled).Select(mod => mod.ChangeSet.ModId), StringComparer.Ordinal);
var pins = new Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int>();
@@ -165,15 +195,19 @@ public static RemapPlan Plan(
foreach (IdRemap remap in Sorted(recorded))
{
(string ModId, IdKind Kind, string Scope, int FromId) from = (remap.ModId, remap.Kind, remap.Scope, remap.FromId);
+ // A switch or variable target past the limit only comes from a damaged profile; the game would pad its list up to it.
if (!RpgDataSchema.IsRemappable(remap.Kind) || remap.ToId <= 0 || !enabled.Contains(remap.ModId) ||
- !AddedIdIndex.IsActive(remap, added[remap.ModId]) || pins.ContainsKey(from) ||
+ (RpgDataSchema.IsStateKind(remap.Kind) && remap.ToId > RpgDataSchema.RemapLimit(remap.Kind, engine)) ||
+ !IsActive(remap, added[remap.ModId], () => referencesOf(byId[remap.ModId])) || pins.ContainsKey(from) ||
!targets.Add((remap.ModId, remap.Kind, remap.Scope, remap.ToId)))
{
// Only a standing entry holds its target, so a losing duplicate leaves the next entry free.
continue;
}
- if (VanillaUses(remap.Kind, remap.Scope, remap.ToId, baseFiles))
+ if (RpgDataSchema.IsStateKind(remap.Kind)
+ ? vanillaStates?.Of(remap.Kind).Contains(remap.ToId) == true
+ : VanillaUses(remap.Kind, remap.Scope, remap.ToId, baseFiles))
{
taken.Add(remap);
continue;
@@ -198,10 +232,23 @@ public static RemapPlan Plan(
return pins;
}
+ ///
+ /// GR-R12: an entry stands while its mod still adds the old id, or, for a switch or variable, still names it
+ /// through the reference table (free text is no use, GR-R15). A switch or variable has no scope.
+ ///
+ internal static bool IsActive(IdRemap remap, IReadOnlyList added, Func referencesOf)
+ {
+ return RpgDataSchema.IsStateKind(remap.Kind)
+ ? remap.Scope.Length == 0 && referencesOf().NamesState(remap.Kind, remap.FromId)
+ : AddedIdIndex.IsActive(remap, added);
+ }
+
///
/// GR-R12 over GR-R9 (the owner, 2026-11-12): an entry in force still applies when its mod now names the old id
/// where a move cannot follow it (a mod update), since saves already hold the new id. The plan says so with
- /// rules.remap_stale_reference , one per entry, in the order of .
+ /// rules.remap_stale_reference , one per entry, in the order of . A switch or variable
+ /// entry is stale too when a range of its mod holds the old id and the mod's entries do not move that range whole
+ /// (GR-R14).
///
private static void StaleReferences(
List mods,
@@ -213,7 +260,8 @@ private static void StaleReferences(
foreach (IdRemap remap in Sorted(standing))
{
RemapMod mod = mods.First(item => item.ChangeSet.ModId == remap.ModId);
- if (!referencesOf(mod).Blocks(remap.Kind, remap.FromId))
+ ModReferences references = referencesOf(mod);
+ if (!references.Blocks(remap.Kind, remap.FromId) && !SplitsRange(remap, references, pins))
{
continue;
}
@@ -223,7 +271,7 @@ private static void StaleReferences(
DiagnosticCodes.RulesRemapStaleReference,
string.Create(
CultureInfo.InvariantCulture,
- $"Mod {remap.ModId}: {remap.Kind} {remap.FromId}{where} was recorded as moved to {remap.ToId}, but the mod now names {remap.FromId} where a move cannot follow it (a script, a note, a formula, a plugin's text code or a value of unclear kind). The entry still applies, so saves keep the record, but that place still reads {remap.FromId}."),
+ $"Mod {remap.ModId}: {remap.Kind} {remap.FromId}{where} was recorded as moved to {remap.ToId}, but the mod now names {remap.FromId} where a move cannot follow it (a script, a note, a formula, a plugin's text code, a value of unclear kind or a range that does not move whole). The entry still applies, so saves keep the record, but that place still reads {remap.FromId}."),
DiagnosticSeverity.Warning,
remap.ModId));
}
@@ -389,24 +437,43 @@ public void Classify(IdKind kind, Func referencesOf, Func<
}
}
- /// GR-R5: the next free id per kind and scope, above vanilla, every installed mod and every entry.
+ ///
+ /// GR-R5: the next free id per kind and scope, above vanilla, every installed mod and every entry. For a switch or
+ /// variable, vanilla is its scanned ids and the length of its list of names.
+ ///
private sealed class Targets
{
private readonly List _added;
private readonly IReadOnlyList _recorded;
private readonly BaseFileSet _baseFiles;
private readonly RpgMakerEngine? _engine;
+ private readonly VanillaStateIds? _states;
+ private readonly Func _modStates;
private readonly Dictionary<(IdKind Kind, string Scope), int?> _next = new();
- public Targets(List added, IReadOnlyList recorded, BaseFileSet baseFiles, RpgMakerEngine? engine)
+ public Targets(
+ List added,
+ IReadOnlyList recorded,
+ BaseFileSet baseFiles,
+ RpgMakerEngine? engine,
+ VanillaStateIds? states,
+ Func modStates)
{
_added = added;
_recorded = recorded;
_baseFiles = baseFiles;
_engine = engine;
+ _states = states;
+ _modStates = modStates;
}
public int? Take(IdKind kind, string scope)
+ {
+ return TakeRun(kind, scope, 1);
+ }
+
+ /// The first of consecutive free ids, or null when the last would pass the limit.
+ public int? TakeRun(IdKind kind, string scope, int count)
{
if (!_next.TryGetValue((kind, scope), out int? next))
{
@@ -419,26 +486,40 @@ public Targets(List added, IReadOnlyList recorded, BaseFileSet
next++;
}
+ _next[(kind, scope)] = next;
int? limit = RpgDataSchema.RemapLimit(kind, _engine);
- if (next is null || limit is null || next > limit)
+ if (next is null || limit is null || (long)next.Value + count - 1 > limit)
{
- _next[(kind, scope)] = next;
return null;
}
- _next[(kind, scope)] = next + 1;
+ _next[(kind, scope)] = next + count;
return next;
}
private int? First(IdKind kind, string scope)
{
- JArray? vanilla = VanillaList(kind, scope, _baseFiles);
- if (vanilla is null)
+ int used;
+ if (RpgDataSchema.IsStateKind(kind))
+ {
+ if (_states is null)
+ {
+ return null;
+ }
+
+ IReadOnlyList vanillaIds = _states.Of(kind);
+ used = Math.Max(Math.Max(0, _states.CountOf(kind) - 1), vanillaIds.Count == 0 ? 0 : vanillaIds.Max());
+ used = Math.Max(used, _modStates(kind));
+ }
+ else if (VanillaList(kind, scope, _baseFiles) is JArray vanilla)
+ {
+ used = Math.Max(0, vanilla.Count - 1);
+ }
+ else
{
return null;
}
- int used = Math.Max(0, vanilla.Count - 1);
foreach (AddedId id in _added.Where(item => item.Kind == kind && item.Scope == scope))
{
used = Math.Max(used, id.Id);
@@ -449,7 +530,8 @@ public Targets(List added, IReadOnlyList recorded, BaseFileSet
used = Math.Max(used, Math.Max(remap.FromId, remap.ToId));
}
- return used + 1;
+ // A damaged entry or id at the top of the range leaves no target, rather than one that wraps around.
+ return used == int.MaxValue ? null : used + 1;
}
}
}
diff --git a/RPGModder.Core/Merge/IdRemapper.cs b/RPGModder.Core/Merge/IdRemapper.cs
index c42896f..ae2a286 100644
--- a/RPGModder.Core/Merge/IdRemapper.cs
+++ b/RPGModder.Core/Merge/IdRemapper.cs
@@ -1,3 +1,4 @@
+using Newtonsoft.Json.Linq;
using RPGModder.Core.Models;
using RPGModder.Core.Operations;
using System.Globalization;
@@ -13,8 +14,11 @@ public static class IdRemapper
///
/// Applies the entries of that name this mod and an id it still adds; the others are
/// inactive and change nothing (GR-R12). All moves of one mod apply in one pass, so an id moved onto another
- /// moved id is not moved twice. Each applied entry adds rules.remap_applied (GR-R13). Map events, maps and
- /// the twelve database kinds move; an entry of another kind changes nothing.
+ /// moved id is not moved twice. Each applied entry adds rules.remap_applied (GR-R13). Map events, maps, the
+ /// twelve database kinds, switches and variables move; an entry of another kind changes nothing. A switch or
+ /// variable entry is active while the mod still names the old id; its name in System.json moves with it,
+ /// and the mod gets an empty name at the new id when it sets none there, so the list of names reaches the new id
+ /// (the game ignores an id past its end).
///
public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList remaps)
{
@@ -27,8 +31,12 @@ public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList
}
IReadOnlyList added = AddedIdIndex.Of(changeSet);
+ // Read as MV, whose rows are a superset: the planner already left out an entry its engine finds out of force,
+ // so this only keeps the entries the plan holds.
+ var references = new Lazy(() => ReferenceMap.Scan(changeSet, [], dualWield: true, mz: false));
List active = remaps
- .Where(remap => remap.ModId == changeSet.ModId && RpgDataSchema.IsRemappable(remap.Kind) && AddedIdIndex.IsActive(remap, added))
+ .Where(remap => remap.ModId == changeSet.ModId && RpgDataSchema.IsRemappable(remap.Kind) && InRange(remap) &&
+ IdRemapPlanner.IsActive(remap, added, () => references.Value))
.Distinct()
.OrderBy(remap => remap.Kind)
.ThenBy(remap => remap.Scope, StringComparer.Ordinal)
@@ -54,7 +62,9 @@ public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList
}
// A stable sort: two ops can share a place when a recorded move lands on an id the mod now adds too.
- List ops = ReferenceMap.Rewrite(changeSet, table)
+ IReadOnlyList rewritten = KeepOwnNames(changeSet.Ops, ReferenceMap.Rewrite(changeSet, table));
+ List ops = rewritten
+ .Concat(NameSlots(changeSet.ModId, active, rewritten))
.OrderBy(op => op, Comparer.Create(ChangeSetBuilder.CompareOps))
.ToList();
@@ -68,6 +78,59 @@ public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList
return changeSet with { Ops = ops, Diagnostics = diagnostics };
}
+ ///
+ /// The owner, 2026-11-17: a name a recorded entry moves onto a slot the mod's own file names (its new id there
+ /// could not move, so both meanings share the id and the plan warns) gives way to the file's name, so the mod does
+ /// not clash with itself. An empty name in the file is only padding and gives way to the moved one later.
+ ///
+ private static IReadOnlyList KeepOwnNames(IReadOnlyList original, IReadOnlyList rewritten)
+ {
+ RecordKey system = RemapPlaces.StateKey;
+ List<(ChangeOp Before, ChangeOp After)> pairs = original.Zip(rewritten).ToList();
+ var ownNames = new HashSet(
+ pairs.Where(pair => pair.After.Key == system && pair.After.Path == pair.Before.Path &&
+ pair.After.Value is JValue { Value: string { Length: > 0 } })
+ .Select(pair => pair.After.Path),
+ StringComparer.Ordinal);
+ if (ownNames.Count == 0)
+ {
+ return rewritten;
+ }
+
+ return pairs
+ .Where(pair => pair.After.Key != system || pair.After.Path == pair.Before.Path || !ownNames.Contains(pair.After.Path))
+ .Select(pair => pair.After)
+ .ToList();
+ }
+
+ /// A switch or variable target from 1 to 5000 on any engine (GR-R6); a database target is checked by the planner, which knows the engine.
+ private static bool InRange(IdRemap remap)
+ {
+ return !RpgDataSchema.IsStateKind(remap.Kind) || (remap.ToId >= 1 && remap.ToId <= RpgDataSchema.RemapLimit(remap.Kind, null));
+ }
+
+ ///
+ /// An empty name at each new switch or variable id the rewritten ops set no name for: Game_Switches and
+ /// Game_Variables ignore an id past the end of System.json 's list.
+ ///
+ private static IEnumerable NameSlots(string modId, List active, IReadOnlyList rewritten)
+ {
+ RecordKey system = RemapPlaces.StateKey;
+ var named = new HashSet(
+ rewritten.Where(op => op.Key == system).Select(op => op.Path),
+ StringComparer.Ordinal);
+ bool wholeFile = rewritten.Any(op => op.Key == system && op.Path.Length == 0);
+ foreach (IdRemap remap in active.Where(item => RpgDataSchema.IsStateKind(item.Kind)))
+ {
+ string property = RpgDataSchema.StateNamesOf(remap.Kind)!;
+ string path = MergePath.Index(property, remap.ToId);
+ if (!wholeFile && !named.Contains(property) && named.Add(path))
+ {
+ yield return new ChangeOp(modId, system, path, ChangeKind.SetLeaf, new JValue(""), null);
+ }
+ }
+ }
+
/// The mod, kind, old id and new id GR-R13 asks for, with the map file of an event.
private static string Describe(IdRemap remap)
{
diff --git a/RPGModder.Core/Merge/MergedFileWriter.cs b/RPGModder.Core/Merge/MergedFileWriter.cs
index df49225..b834ee1 100644
--- a/RPGModder.Core/Merge/MergedFileWriter.cs
+++ b/RPGModder.Core/Merge/MergedFileWriter.cs
@@ -97,6 +97,7 @@ private static MergedFile WriteDataFile(
JToken root = Render(file, baseFile, fileOps);
FillHoles(file, root, engine);
+ FillNameHoles(file, root);
if (file == RpgDataSchema.SystemFileKey && systemVersionId is not null)
{
SetVersionId(root, systemVersionId.Value);
@@ -126,6 +127,34 @@ private static void FillHoles(string file, JToken root, RpgMakerEngine? engine)
}
}
+ ///
+ /// A switch or variable name past the end of vanilla's list pads it with null ; the editor writes an empty
+ /// name there, so each null above index 0 in System.json 's switches and variables becomes one.
+ ///
+ private static void FillNameHoles(string file, JToken root)
+ {
+ if (file != RpgDataSchema.SystemFileKey || root is not JObject system)
+ {
+ return;
+ }
+
+ foreach (string property in new[] { RpgDataSchema.SwitchNamesProperty, RpgDataSchema.VariableNamesProperty })
+ {
+ if (system[property] is not JArray names)
+ {
+ continue;
+ }
+
+ for (int index = 1; index < names.Count; index++)
+ {
+ if (names[index].Type == JTokenType.Null)
+ {
+ names[index] = "";
+ }
+ }
+ }
+ }
+
private static bool HasHoles(string file, JToken root)
{
return RpgDataSchema.DatabaseKindOf(file) is not null &&
diff --git a/RPGModder.Core/Merge/ModReferences.cs b/RPGModder.Core/Merge/ModReferences.cs
index 9578181..783b21a 100644
--- a/RPGModder.Core/Merge/ModReferences.cs
+++ b/RPGModder.Core/Merge/ModReferences.cs
@@ -1,11 +1,12 @@
namespace RPGModder.Core.Merge;
-/// What found in one mod: the numbers a remap cannot rewrite.
+/// What found in one mod: the numbers a remap cannot rewrite, and the ids it uses.
internal sealed class ModReferences
{
private readonly Dictionary> _ambiguous = new();
private readonly HashSet _unknownIds = new();
private readonly Dictionary> _used = new();
+ private readonly List<(IdKind Kind, int First, int Last)> _ranges = new();
/// Whole numbers in the change set's free text (GR-R9).
public HashSet FreeTextNumbers { get; } = new();
@@ -20,8 +21,8 @@ internal sealed class ModReferences
public HashSet PluginScriptNumbers { get; } = new();
///
- /// The kinds the mod names through a variable: a map (201 with p[0] 1, 202 with p[1] 1), a troop
- /// (301 with p[0] 1), an actor (311 to 318 and 326 with p[0] 1).
+ /// The kinds the mod names through a variable: a map (201 with p[0] not 0, 202 with p[1] not 0), a
+ /// troop (301 with p[0] 1), an actor (311 to 318 and 326 with p[0] not 0).
///
public HashSet ByVariableKinds { get; } = new();
@@ -62,18 +63,78 @@ public void AddUsed(IdKind kind, long id)
ids.Add(id);
}
+ ///
+ /// Records a range command (121, 122) that sets every id of from
+ /// to . A range whose first end is past its last names no id, as the game loops no time.
+ ///
+ public void AddRange(IdKind kind, int first, int last)
+ {
+ _ranges.Add((kind, first, last));
+ }
+
+ /// The ranges of the change set holds, as their ends: p[0] , then p[1] .
+ public IEnumerable<(int First, int Last)> RangesOf(IdKind kind)
+ {
+ return _ranges.Where(range => range.Kind == kind).Select(range => (range.First, range.Last));
+ }
+
///
/// True when the change set may refer to of : a place a remap
- /// rewrites, a place of no known kind, or free text (GR-R7).
+ /// rewrites, a range that holds it, a place of no known kind, or free text (GR-R7).
///
public bool Uses(IdKind kind, int id)
{
return FreeTextNumbers.Contains(id) ||
(_used.TryGetValue(kind, out HashSet? ids) && ids.Contains(id)) ||
+ InRange(kind, id) ||
(_ambiguous.TryGetValue(kind, out HashSet? unknown) && unknown.Contains(id)) ||
ByVariable(kind, id);
}
+ ///
+ /// True when the change set names switch or variable as counts it.
+ /// Free text names no kind, so a number in a note keeps no entry in force.
+ ///
+ public bool NamesState(IdKind kind, int id)
+ {
+ return id >= 1 &&
+ ((_used.TryGetValue(kind, out HashSet? ids) && ids.Contains(id)) ||
+ (_ambiguous.TryGetValue(kind, out HashSet? unknown) && unknown.Contains(id)) ||
+ InRange(kind, id));
+ }
+
+ ///
+ /// The switch or variable ids the change set names through the reference table, from 1 to
+ /// : places a remap rewrites, ranges, places of no known kind, names in
+ /// System.json . Free text is left out, as it names no kind.
+ ///
+ public SortedSet StateIds(IdKind kind, int limit)
+ {
+ var ids = new SortedSet();
+ foreach (long id in _used.GetValueOrDefault(kind, []).Concat(_ambiguous.GetValueOrDefault(kind, [])))
+ {
+ if (id >= 1 && id <= limit)
+ {
+ ids.Add((int)id);
+ }
+ }
+
+ foreach ((int first, int last) in RangesOf(kind))
+ {
+ for (int id = Math.Max(first, 1); id <= Math.Min(last, limit); id++)
+ {
+ ids.Add(id);
+ }
+ }
+
+ return ids;
+ }
+
+ private bool InRange(IdKind kind, int id)
+ {
+ return id >= 1 && _ranges.Exists(range => range.Kind == kind && range.First <= id && id <= range.Last);
+ }
+
/// True when the change set refers to where a remap cannot follow it (GR-R9).
public bool Blocks(IdKind kind, int id)
{
diff --git a/RPGModder.Core/Merge/ReferenceMap.cs b/RPGModder.Core/Merge/ReferenceMap.cs
index 6cb1a34..d75c0bc 100644
--- a/RPGModder.Core/Merge/ReferenceMap.cs
+++ b/RPGModder.Core/Merge/ReferenceMap.cs
@@ -7,8 +7,9 @@ namespace RPGModder.Core.Merge;
///
/// Where an id is referenced (guide 3.11). One walker reads a change set with the rows of :
-/// collects what a remap cannot rewrite (GR-R9), moves every reference the
-/// rows name. Only whole numbers above 0 are ids.
+/// collects what a remap cannot rewrite (GR-R9) and the switches and variables a mod uses (GR-R2),
+/// moves every reference the rows name, whole ranges (GR-R14) and the names in System.json
+/// with them. Only whole numbers above 0 are ids.
///
internal static class ReferenceMap
{
@@ -63,21 +64,103 @@ private static ChangeOp Rewrite(ChangeOp op, RemapTable table, SiblingOps siblin
{
JToken? value = op.Value?.DeepClone();
RecordKey key = op.Kind == ChangeKind.AddRecord && op.Path.Length == 0 ? OwnKey(op.Key, value, table) : op.Key;
+ string path = op.Key.File == RpgDataSchema.SystemFileKey ? OwnNamePath(op.Path, table) : op.Path;
if (value is not null && !MergePath.IsPseudoLeaf(op.Path))
{
// Event references are scoped to the map file the commands sit in, so the op's own file decides.
Dictionary? events = table.Events.GetValueOrDefault(op.Key.File);
new Walker(op, siblings, dualWield: false, mz: true, hit => Move(hit, table, events)).Walk(value);
+ if (op.Key.File == RpgDataSchema.SystemFileKey)
+ {
+ MoveNameLists(op.Path, value, table);
+ }
}
- if (key == op.Key && JToken.DeepEquals(value, op.Value))
+ if (key == op.Key && path == op.Path && JToken.DeepEquals(value, op.Value))
{
return op;
}
// A whole new file whose content changed loses its source file, so it is written as text.
string? source = op.Kind == ChangeKind.AddRecord && op.Key.IsWholeFile ? null : op.SourceFile;
- return op with { Key = key, Value = value, SourceFile = source };
+ return op with { Key = key, Path = path, Value = value, SourceFile = source };
+ }
+
+ ///
+ /// The path of a System.json op on one name of a switch or variable that moves (switches[n] ): the
+ /// name goes with its id. Any other path is returned as it was.
+ ///
+ private static string OwnNamePath(string path, RemapTable table)
+ {
+ if (path.Length == 0 || MergePath.IsPseudoLeaf(path))
+ {
+ return path;
+ }
+
+ IReadOnlyList segments = MergePath.Parse(path);
+ if (segments.Count != 2 || segments[1].Name is not null || StateKindOfNames(segments[0].Name) is not { } kind ||
+ table.MovesOf(kind) is not { } moves || !moves.TryGetValue(segments[1].Index, out int newId))
+ {
+ return path;
+ }
+
+ return MergePath.Index(segments[0].Name!, newId);
+ }
+
+ ///
+ /// A System.json op whose value holds a whole list of names (the file, or switches itself): each
+ /// moved id's name goes to its new index, the old index is left empty, and the list grows with empty names.
+ ///
+ private static void MoveNameLists(string path, JToken value, RemapTable table)
+ {
+ if (path.Length == 0 && value is JObject system)
+ {
+ foreach (IdKind kind in new[] { IdKind.Switch, IdKind.Variable })
+ {
+ if (system[RpgDataSchema.StateNamesOf(kind)!] is JArray names && table.MovesOf(kind) is { } moves)
+ {
+ MoveNames(names, moves);
+ }
+ }
+ }
+ else if (StateKindOfNames(path) is { } kind && value is JArray names && table.MovesOf(kind) is { } moves)
+ {
+ MoveNames(names, moves);
+ }
+ }
+
+ private static void MoveNames(JArray names, Dictionary moves)
+ {
+ List<(int To, JToken Name)> moved = moves
+ .Where(move => move.Key < names.Count)
+ .OrderBy(move => move.Key)
+ .Select(move => (move.Value, names[move.Key].DeepClone()))
+ .ToList();
+ foreach (int from in moves.Keys.Where(from => from < names.Count))
+ {
+ names[from] = "";
+ }
+
+ foreach ((int to, JToken name) in moved)
+ {
+ while (names.Count <= to)
+ {
+ names.Add("");
+ }
+
+ names[to] = name;
+ }
+ }
+
+ /// The state kind a System.json list of names belongs to, or null for any other property.
+ private static IdKind? StateKindOfNames(string? property)
+ {
+ return property switch
+ {
+ RpgDataSchema.SwitchNamesProperty => IdKind.Switch,
+ RpgDataSchema.VariableNamesProperty => IdKind.Variable,
+ _ => null
+ };
}
/// The key an added record moves to, with its own id set: a map file, a tree record, an event or a database record.
@@ -158,11 +241,35 @@ private static void Collect(Hit hit, ModReferences references)
case HitUse.ByVariable:
references.ByVariableKinds.Add(hit.Kind);
break;
+ case HitUse.Range when hit.Token is JArray parameters && TryRange(parameters, out int first, out int last):
+ references.AddRange(hit.Kind, first, last);
+ break;
+ case HitUse.Range:
+ // Ends that are not whole numbers: the range may hold any id of its kind.
+ references.AddUnknownId(hit.Kind);
+ break;
+ case HitUse.Name when hit.Token is JValue { Value: long index }:
+ references.AddUsed(hit.Kind, index);
+ break;
}
}
+ /// The two ends of a range command (121, 122): p[0] and p[1] , as the game loops from one to the other.
+ private static bool TryRange(JArray parameters, out int first, out int last)
+ {
+ last = 0;
+ first = 0;
+ return At(parameters, 0) is JValue low && TryInt(low, out first) && At(parameters, 1) is JValue high && TryInt(high, out last);
+ }
+
private static void Move(Hit hit, RemapTable table, Dictionary? events)
{
+ if (hit.Use == HitUse.Range && hit.Token is JArray parameters)
+ {
+ MoveRange(parameters, table.MovesOf(hit.Kind));
+ return;
+ }
+
if (hit.Token is not JValue value)
{
return;
@@ -187,6 +294,37 @@ private static void Move(Hit hit, RemapTable table, Dictionary? events
}
}
+ ///
+ /// GR-R14: a range moves only when every id in it moves, onto consecutive ids in the same order; its ends then
+ /// name the new first and last id. A range that moves in part, or not at all, is left as it was: the planner
+ /// never makes such a move, and warns of a recorded one (rules.remap_stale_reference ).
+ ///
+ private static void MoveRange(JArray parameters, Dictionary? moves)
+ {
+ if (moves is null || !TryRange(parameters, out int first, out int last))
+ {
+ return;
+ }
+
+ // Id 0 and below name no switch or variable: the game skips them.
+ int low = Math.Max(first, 1);
+ if (last < low || (long)last - low + 1 > moves.Count || !moves.TryGetValue(low, out int start))
+ {
+ return;
+ }
+
+ for (int id = low + 1; id <= last; id++)
+ {
+ if (!moves.TryGetValue(id, out int target) || target != start + (id - low))
+ {
+ return;
+ }
+ }
+
+ parameters[0] = (long)start;
+ parameters[1] = (long)(start + (last - low));
+ }
+
///
/// with every text code that names a moved id rewritten, or the same instance when none
/// does. A pair of backslashes is a literal backslash, as the game reads it; a code letter matches in either case.
@@ -284,7 +422,7 @@ private static bool TryCommand(JObject item, out int code, [NotNullWhen(true)] o
private static bool Holds(JArray parameters, ParameterTest test)
{
- return At(parameters, test.Index) is JValue value && TryInt(value, out int actual) && actual >= test.Min && actual <= test.Max;
+ return At(parameters, test.Index) is JValue value && TryInt(value, out int actual) && (actual >= test.Min && actual <= test.Max) != test.Outside;
}
/// An id is a whole number above 0 (reference table).
@@ -397,6 +535,12 @@ private enum HitUse
ByVariable,
+ /// A range command's parameters: every id of from p[0] to p[1] (GR-R14).
+ Range,
+
+ /// The index of a name in a System.json list of switches or variables, as a new integer value.
+ Name,
+
/// A string, whose text codes a remap rewrites.
Text,
@@ -547,6 +691,8 @@ private void Visit(JToken token, string? name, JObject? parent, bool isRoot)
_emit(new Hit(HitUse.FreeText, default, text));
}
+ VisitName(text);
+
_emit(new Hit(_inComment ? HitUse.Comment : HitUse.Text, default, text));
if (name is not null && ReferenceTable.MayBeField(name))
{
@@ -575,6 +721,12 @@ private void VisitCommand(int code, JArray parameters)
JToken? place = At(parameters, row.Index);
switch (row.Use)
{
+ case PlaceUse.Id when row.NotMz && _mz:
+ break;
+ case PlaceUse.Id when place is JValue value && row.Kind is { } kind && row.NotMz:
+ // MV reads a variable here and MZ does not; MV and an unknown engine are not told apart.
+ _emit(new Hit(HitUse.Ambiguous, kind, value));
+ break;
case PlaceUse.Id when place is JValue value && row.Kind is { } kind && row.MzOnly && !_mz:
// MV reads the parameter another way (285 p[2] 2 is by variable there), so its kind is unknown.
_emit(new Hit(HitUse.Ambiguous, kind, value));
@@ -595,10 +747,26 @@ private void VisitCommand(int code, JArray parameters)
case PlaceUse.ByVariable when row.Kind is { } kind:
_emit(new Hit(HitUse.ByVariable, kind, parameters));
break;
+ case PlaceUse.Range when row.Kind is { } kind:
+ _emit(new Hit(HitUse.Range, kind, parameters));
+ break;
}
}
}
+ ///
+ /// A name in System.json switches or variables : a name that is not empty names the id at
+ /// its index (GR-R2).
+ ///
+ private void VisitName(JValue text)
+ {
+ if (_table == RpgDataSchema.SystemTable && _path.Count == 2 && _path[1].Name is null && _path[1].Index > 0 &&
+ StateKindOfNames(_path[0].Name) is { } kind && text.Value is string { Length: > 0 })
+ {
+ _emit(new Hit(HitUse.Name, kind, new JValue((long)_path[1].Index)));
+ }
+ }
+
private void VisitField(JValue number, JObject? parent, bool isRoot)
{
IReadOnlyList rows = ReferenceTable.Fields(_table, Pattern(_path));
diff --git a/RPGModder.Core/Merge/ReferenceTable.cs b/RPGModder.Core/Merge/ReferenceTable.cs
index 11df4c1..b676259 100644
--- a/RPGModder.Core/Merge/ReferenceTable.cs
+++ b/RPGModder.Core/Merge/ReferenceTable.cs
@@ -18,6 +18,7 @@ internal static class ReferenceTable
private const string Enemies = "enemies.json";
private const string States = "states.json";
private const string Troops = "troops.json";
+ private const string CommonEvents = "commonevents.json";
private const string MapInfos = "mapinfos.json";
private const string SystemFile = "system.json";
@@ -39,8 +40,8 @@ internal static class ReferenceTable
// Maps.
Id(IdKind.Map, 201, 1, Is(0, 0)), // Transfer Player, direct
Id(IdKind.Map, 202, 2, Is(1, 0)), // Set Vehicle Location, direct
- ByVariable(IdKind.Map, 201, Is(0, 1)), // Transfer Player by variable
- ByVariable(IdKind.Map, 202, Is(1, 1)), // Set Vehicle Location by variable
+ ByVariable(IdKind.Map, 201, NonZero(0)), // Transfer Player by variable
+ ByVariable(IdKind.Map, 202, NonZero(1)), // Set Vehicle Location by variable
new(122, 4, PlaceUse.Constant, null, [Is(3, 0)]), // Control Variables: constant, for every by-variable row
new(122, 4, PlaceUse.RandomRange, null, [Is(3, 2)]), // Control Variables: random p[4] to p[5], likewise
@@ -87,7 +88,7 @@ internal static class ReferenceTable
ByVariable(IdKind.Troop, 301, Is(0, 1)), // ... by variable
Id(IdKind.CommonEvent, 117, 0), // Common Event
- // Actors. 311 to 318 and 326 name an actor when p[0] is 0, a variable when it is 1.
+ // Actors. 311 to 318 and 326 name an actor when p[0] is 0, a variable for any other value.
Id(IdKind.Actor, 129, 0), // Change Party Member
Id(IdKind.Actor, 303, 0), // Name Input Processing
Id(IdKind.Actor, 111, 1, Is(0, 4)),
@@ -101,22 +102,22 @@ internal static class ReferenceTable
Id(IdKind.Actor, 317, 1, Is(0, 0)),
Id(IdKind.Actor, 318, 1, Is(0, 0)),
Id(IdKind.Actor, 326, 1, Is(0, 0)),
- ByVariable(IdKind.Actor, 311, Is(0, 1)),
- ByVariable(IdKind.Actor, 312, Is(0, 1)),
- ByVariable(IdKind.Actor, 313, Is(0, 1)),
- ByVariable(IdKind.Actor, 314, Is(0, 1)),
- ByVariable(IdKind.Actor, 315, Is(0, 1)),
- ByVariable(IdKind.Actor, 316, Is(0, 1)),
- ByVariable(IdKind.Actor, 317, Is(0, 1)),
- ByVariable(IdKind.Actor, 318, Is(0, 1)),
- ByVariable(IdKind.Actor, 326, Is(0, 1)),
+ ByVariable(IdKind.Actor, 311, NonZero(0)),
+ ByVariable(IdKind.Actor, 312, NonZero(0)),
+ ByVariable(IdKind.Actor, 313, NonZero(0)),
+ ByVariable(IdKind.Actor, 314, NonZero(0)),
+ ByVariable(IdKind.Actor, 315, NonZero(0)),
+ ByVariable(IdKind.Actor, 316, NonZero(0)),
+ ByVariable(IdKind.Actor, 317, NonZero(0)),
+ ByVariable(IdKind.Actor, 318, NonZero(0)),
+ ByVariable(IdKind.Actor, 326, NonZero(0)),
Id(IdKind.Actor, 319, 0), // Change Equipment
Id(IdKind.Actor, 320, 0), // Change Name
Id(IdKind.Actor, 321, 0), // Change Class
Id(IdKind.Actor, 322, 0), // Change Actor Images
Id(IdKind.Actor, 324, 0), // Change Nickname
Id(IdKind.Actor, 325, 0), // Change Profile
- Id(IdKind.Actor, 339, 1, Is(0, 1)), // Force Action by an actor
+ Id(IdKind.Actor, 339, 1, NonZero(0)), // Force Action by an actor
// Classes, animations, tilesets.
Id(IdKind.Class, 321, 1),
@@ -125,6 +126,64 @@ internal static class ReferenceTable
Id(IdKind.Animation, 337, 1), // Show Battle Animation
Id(IdKind.Tileset, 282, 0), // Change Tileset
+ // Switches. 121 sets every switch from p[0] to p[1]; route commands 27 and 28 sit in move routes.
+ Range(IdKind.Switch, 121), // Control Switches
+ Id(IdKind.Switch, 111, 1, Is(0, 0)), // Conditional Branch: switch
+ Id(IdKind.Switch, 27, 0), // Switch ON, in a move route
+ Id(IdKind.Switch, 28, 0), // Switch OFF, in a move route
+
+ // Variables. 122 sets every variable from p[0] to p[1].
+ Range(IdKind.Variable, 122), // Control Variables
+ Id(IdKind.Variable, 122, 4, Is(3, 1)), // ... its operand, a variable
+ Id(IdKind.Variable, 111, 1, Is(0, 1)), // Conditional Branch: variable
+ Id(IdKind.Variable, 111, 3, Is(0, 1), NonZero(2)), // ... compared with a variable
+ Id(IdKind.Variable, 103, 0), // Input Number
+ Id(IdKind.Variable, 104, 0), // Select Item
+ Id(IdKind.Variable, 285, 0), // Get Location Info: the result
+
+ // Variables as operands ("by variable"): the value or the place comes from a variable. The engine reads a
+ // variable whenever the designation is not 0 (operateValue, iterateActorEx and the location commands), so
+ // these rows test p[n] != 0. 203, 301 and 122 pick among more forms and test the exact value.
+ Id(IdKind.Variable, 125, 2, NonZero(1)), // Change Gold
+ Id(IdKind.Variable, 126, 3, NonZero(2)), // Change Items
+ Id(IdKind.Variable, 127, 3, NonZero(2)), // Change Weapons
+ Id(IdKind.Variable, 128, 3, NonZero(2)), // Change Armors
+ Id(IdKind.Variable, 201, 1, NonZero(0)), // Transfer Player: map, x, y
+ Id(IdKind.Variable, 201, 2, NonZero(0)),
+ Id(IdKind.Variable, 201, 3, NonZero(0)),
+ Id(IdKind.Variable, 202, 2, NonZero(1)), // Set Vehicle Location: map, x, y
+ Id(IdKind.Variable, 202, 3, NonZero(1)),
+ Id(IdKind.Variable, 202, 4, NonZero(1)),
+ Id(IdKind.Variable, 203, 2, Is(1, 1)), // Set Event Location: x, y
+ Id(IdKind.Variable, 203, 3, Is(1, 1)),
+ Id(IdKind.Variable, 231, 4, NonZero(3)), // Show Picture: x, y
+ Id(IdKind.Variable, 231, 5, NonZero(3)),
+ Id(IdKind.Variable, 232, 4, NonZero(3)), // Move Picture: x, y
+ Id(IdKind.Variable, 232, 5, NonZero(3)),
+ Id(IdKind.Variable, 285, 3, Is(2, 1)), // Get Location Info: x, y
+ Id(IdKind.Variable, 285, 4, Is(2, 1)),
+ Id(IdKind.Variable, 285, 3, NotIn(2, 0, 1)) with { NotMz = true }, // ... MV reads any p[2] but 0 as variables
+ Id(IdKind.Variable, 285, 4, NotIn(2, 0, 1)) with { NotMz = true },
+ Id(IdKind.Variable, 301, 1, Is(0, 1)), // Battle Processing: the troop
+ Id(IdKind.Variable, 311, 1, NonZero(0)), // 311 to 318 and 326: the actor
+ Id(IdKind.Variable, 312, 1, NonZero(0)),
+ Id(IdKind.Variable, 313, 1, NonZero(0)),
+ Id(IdKind.Variable, 314, 1, NonZero(0)),
+ Id(IdKind.Variable, 315, 1, NonZero(0)),
+ Id(IdKind.Variable, 316, 1, NonZero(0)),
+ Id(IdKind.Variable, 317, 1, NonZero(0)),
+ Id(IdKind.Variable, 318, 1, NonZero(0)),
+ Id(IdKind.Variable, 326, 1, NonZero(0)),
+ Id(IdKind.Variable, 311, 4, NonZero(3)), // Change HP: the amount
+ Id(IdKind.Variable, 312, 4, NonZero(3)), // Change MP
+ Id(IdKind.Variable, 315, 4, NonZero(3)), // Change EXP
+ Id(IdKind.Variable, 316, 4, NonZero(3)), // Change Level
+ Id(IdKind.Variable, 317, 5, NonZero(4)), // Change Parameter
+ Id(IdKind.Variable, 326, 4, NonZero(3)), // Change TP
+ Id(IdKind.Variable, 331, 3, NonZero(2)), // Change Enemy HP
+ Id(IdKind.Variable, 332, 3, NonZero(2)), // Change Enemy MP
+ Id(IdKind.Variable, 342, 3, NonZero(2)), // Change Enemy TP
+
// Free text (GR-R9): a whole number here stops a move of that id, of any kind.
FreeText(355, 0), // Script
FreeText(655, 0), // ... its further lines
@@ -149,6 +208,9 @@ internal static class ReferenceTable
new([Map], "encounterList[*].troopId", IdKind.Troop),
new([Map], "pages[*].conditions.itemId", IdKind.Item),
new([Map], "pages[*].conditions.actorId", IdKind.Actor),
+ new([Map], "pages[*].conditions.switch1Id", IdKind.Switch),
+ new([Map], "pages[*].conditions.switch2Id", IdKind.Switch),
+ new([Map], "pages[*].conditions.variableId", IdKind.Variable),
// Database records.
new([Actors], "classId", IdKind.Class),
@@ -159,11 +221,14 @@ internal static class ReferenceTable
new([Skills, Items, Weapons], "animationId", IdKind.Animation),
new([Enemies], "actions[*].skillId", IdKind.Skill),
new([Enemies], "actions[*].conditionParam1", IdKind.State, new FieldTest("conditionType", [4])),
+ new([Enemies], "actions[*].conditionParam1", IdKind.Switch, new FieldTest("conditionType", [6])),
new([Enemies], "dropItems[*].dataId", IdKind.Item, new FieldTest("kind", [1])),
new([Enemies], "dropItems[*].dataId", IdKind.Weapon, new FieldTest("kind", [2])),
new([Enemies], "dropItems[*].dataId", IdKind.Armor, new FieldTest("kind", [3])),
new([Troops], "members[*].enemyId", IdKind.Enemy),
new([Troops], "pages[*].conditions.actorId", IdKind.Actor),
+ new([Troops], "pages[*].conditions.switchId", IdKind.Switch),
+ new([CommonEvents], "switchId", IdKind.Switch),
// Traits 13, 14 and 32 name a state; 35 (MZ), 43 and 44 a skill.
new(TraitFiles, "traits[*].dataId", IdKind.State, new FieldTest("code", [13, 14, 32])),
@@ -203,9 +268,12 @@ internal static class ReferenceTable
private static readonly HashSet SiblingNames =
new(FieldRows.Where(row => row.When is not null).Select(row => row.When!.Sibling), StringComparer.Ordinal);
- /// The text codes that name an id inside message text, by their letters: \N[n] is an actor's name.
+ ///
+ /// The text codes that name an id inside message text, by their letters: \N[n] is an actor's name,
+ /// \V[n] a variable's value.
+ ///
public static IReadOnlyDictionary TextCodes { get; } =
- new Dictionary(StringComparer.Ordinal) { ["N"] = IdKind.Actor };
+ new Dictionary(StringComparer.Ordinal) { ["N"] = IdKind.Actor, ["V"] = IdKind.Variable };
///
/// The text codes with a number that the MV and MZ message windows read themselves: a variable, an actor, a party
@@ -259,6 +327,12 @@ private static CommandPlace Id(IdKind kind, int code, int index, params Paramete
return new CommandPlace(code, index, PlaceUse.Id, kind, when);
}
+ /// A command that sets every id of from p[0] to p[1] (GR-R14).
+ private static CommandPlace Range(IdKind kind, int code)
+ {
+ return new CommandPlace(code, 0, PlaceUse.Range, kind, []);
+ }
+
/// A command that names an id of through a variable (3.11).
private static CommandPlace ByVariable(IdKind kind, int code, params ParameterTest[] when)
{
@@ -275,6 +349,17 @@ private static ParameterTest Is(int index, int value)
return new ParameterTest(index, value, value);
}
+ /// The engine's p[n] === 0 ? constant : variable : any whole number but 0 reads a variable.
+ private static ParameterTest NonZero(int index)
+ {
+ return NotIn(index, 0, 0);
+ }
+
+ private static ParameterTest NotIn(int index, int min, int max)
+ {
+ return new ParameterTest(index, min, max, Outside: true);
+ }
+
private static string SiblingPattern(FieldPlace row)
{
int dot = row.Pattern.LastIndexOf('.');
@@ -311,13 +396,21 @@ internal enum PlaceUse
/// An id of the row's kind that a variable holds: a transfer or vehicle move to a map, a battle with a troop, an
/// actor of 311 to 318 and 326.
///
- ByVariable
+ ByVariable,
+
+ ///
+ /// The first id of a range of the row's kind, the next parameter being the last: every id from one to the other.
+ /// It moves only as a whole, onto consecutive ids in the same order (GR-R14).
+ ///
+ Range
}
///
/// One command row: parameter Index of command Code , when every test holds. SecondSlot marks
/// the second equip slot, which holds a weapon for a dual-wield actor. MzOnly marks a row only MZ reads so;
-/// on any other engine the id is of no known kind.
+/// on any other engine the id is of no known kind. NotMz marks a row MV reads so and MZ does not: on MZ it
+/// is no reference, and on any other engine the id is of no known kind, since MV and an unknown engine are not told
+/// apart.
///
internal sealed record CommandPlace(
int Code,
@@ -326,10 +419,14 @@ internal sealed record CommandPlace(
IdKind? Kind,
ParameterTest[] When,
bool SecondSlot = false,
- bool MzOnly = false);
+ bool MzOnly = false,
+ bool NotMz = false);
-/// Parameter Index holds a whole number from Min to Max .
-internal readonly record struct ParameterTest(int Index, int Min, int Max);
+///
+/// Parameter Index holds a whole number from Min to Max , or, when Outside is set, any whole
+/// number out of that range.
+///
+internal readonly record struct ParameterTest(int Index, int Min, int Max, bool Outside = false);
///
/// One field row: the leaves of Tables whose path pattern is Pattern (relative to the record, or to
diff --git a/RPGModder.Core/Merge/RemapPlaces.cs b/RPGModder.Core/Merge/RemapPlaces.cs
index fdccbdb..ad68753 100644
--- a/RPGModder.Core/Merge/RemapPlaces.cs
+++ b/RPGModder.Core/Merge/RemapPlaces.cs
@@ -1,21 +1,34 @@
namespace RPGModder.Core.Merge;
-/// The places an added id occupies in a change set, so an offer can be matched to its IdClash .
+///
+/// The places an added id occupies in a change set, so an offer can be matched to its IdClash , and the place
+/// that stands for a shared switch or variable, so an offer can be matched to its StateIdOverlap .
+///
internal static class RemapPlaces
{
+ /// The key of every StateIdOverlap : System.json as a whole.
+ public static RecordKey StateKey { get; } = new(RpgDataSchema.SystemFileKey, RecordKey.WholeFile);
+
///
/// True when moves the id is about: a map event is the
/// record event:n of its map; a map is its file on * and its MapInfos record; a database
- /// record is the record id:n of its file.
+ /// record is the record id:n of its file; a switch or variable is its name in System.json .
///
public static bool Settles(IdRemap remap, Collision collision)
{
- if (collision.Kind != CollisionKind.IdClash || !collision.ModIds.Contains(remap.ModId, StringComparer.Ordinal))
+ bool stateKind = RpgDataSchema.IsStateKind(remap.Kind);
+ CollisionKind expected = stateKind ? CollisionKind.StateIdOverlap : CollisionKind.IdClash;
+ if (collision.Kind != expected || !collision.ModIds.Contains(remap.ModId, StringComparer.Ordinal))
{
return false;
}
RecordKey key = collision.Key;
+ if (stateKind)
+ {
+ return key == StateKey && collision.Path == StatePath(remap.Kind, remap.FromId);
+ }
+
return remap.Kind switch
{
IdKind.MapEvent => key.File == remap.Scope && key.Record == RecordKey.ForEvent(remap.FromId),
@@ -24,4 +37,10 @@ public static bool Settles(IdRemap remap, Collision collision)
_ => RpgDataSchema.DatabaseFileOf(remap.Kind) is { } file && key.File == file && key.Record == RecordKey.ForIndex(remap.FromId)
};
}
+
+ /// The path of a StateIdOverlap : the name of the id, switches[n] or variables[n] .
+ public static string StatePath(IdKind kind, int id)
+ {
+ return MergePath.Index(RpgDataSchema.StateNamesOf(kind) ?? throw new ArgumentOutOfRangeException(nameof(kind)), id);
+ }
}
diff --git a/RPGModder.Core/Merge/RemapPlan.cs b/RPGModder.Core/Merge/RemapPlan.cs
index 0e761b7..4af7d6b 100644
--- a/RPGModder.Core/Merge/RemapPlan.cs
+++ b/RPGModder.Core/Merge/RemapPlan.cs
@@ -10,6 +10,8 @@ namespace RPGModder.Core.Merge;
/// chooses . Diagnostics holds rules.remap_target_taken , one per
/// recorded entry whose target vanilla now uses, and rules.remap_stale_reference , one per entry in force whose
/// mod now names the old id where a move cannot follow it; carries them into the plan.
+/// A switch or variable two mods share is never moved, only offered: its offers move a whole range together, so lane
+/// A appends every entry of when the player chooses .
///
public sealed record RemapPlan(
IReadOnlyList Remaps,
@@ -25,4 +27,35 @@ public sealed record RemapPlan(
return Offers.FirstOrDefault(offer => offer.ModId == modId && RemapPlaces.Settles(offer, collision));
}
+
+ ///
+ /// Every entry to record when the player settles by moving :
+ /// for a switch or variable, the whole group the settling offer belongs to (GR-R14); otherwise that offer alone.
+ /// Empty when no offer settles it.
+ ///
+ public IReadOnlyList OffersFor(Collision collision, string modId)
+ {
+ IdRemap? offer = OfferFor(collision, modId);
+ if (offer is null)
+ {
+ return [];
+ }
+
+ return OfferGroups.FirstOrDefault(group => group.Contains(offer)) ?? [offer];
+ }
+
+ ///
+ /// The switches and variables two or more enabled mods use and vanilla does not, one entry per id (GR-R15), and
+ /// the id one mod uses for two meanings when the move of its new id is only offered (GR-R11).
+ ///
+ internal IReadOnlyList SharedStateIds { get; init; } = [];
+
+ /// The offers that move together, one group per mod and range of switches or variables (GR-R14).
+ internal IReadOnlyList> OfferGroups { get; init; } = [];
}
+
+///
+/// A switch or variable id that the mods , sorted, all use and vanilla does not; one mod alone
+/// when it uses the id for two meanings.
+///
+internal sealed record SharedStateId(IdKind Kind, int Id, IReadOnlyList ModIds);
diff --git a/RPGModder.Core/Merge/RpgDataSchema.cs b/RPGModder.Core/Merge/RpgDataSchema.cs
index af225d8..3460f57 100644
--- a/RPGModder.Core/Merge/RpgDataSchema.cs
+++ b/RPGModder.Core/Merge/RpgDataSchema.cs
@@ -16,6 +16,9 @@ public static class RpgDataSchema
/// The file that carries (C-7).
internal const string SystemFileKey = "data/system.json";
+ /// The reference table name of .
+ internal const string SystemTable = "system.json";
+
/// The field the game reads to tell its saves apart; the writer stamps it (C-7).
internal const string VersionIdField = "versionId";
@@ -55,6 +58,14 @@ public static class RpgDataSchema
///
private const int MvRecordIdLimit = 999;
+ /// The highest switch and variable id a move gives, on either engine (GR-R6): the editors stop at 5000.
+ private const int StateIdLimit = 5000;
+
+ /// The System.json lists that name the switches and the variables, one name per id.
+ internal const string SwitchNamesProperty = "switches";
+
+ internal const string VariableNamesProperty = "variables";
+
/// The config save forms 2a decodes (GR-M10); config.save gives merge.config_save_unsupported .
private const string MvConfigSave = "config.rpgsave";
@@ -370,14 +381,35 @@ internal static string MapKey(int id)
IdKind.Map => mz ? MzMapIdLimit : MvMapIdLimit,
IdKind.MapEvent => MapEventIdLimit,
_ when DatabaseFiles.ContainsKey(kind) => mz ? MzRecordIdLimit : MvRecordIdLimit,
+ IdKind.Switch or IdKind.Variable => StateIdLimit,
_ => null
};
}
- /// True for the kinds a remap moves: map events, maps and the twelve database kinds (steps 1 and 2).
+ ///
+ /// True for the kinds a remap moves: map events, maps and the twelve database kinds (steps 1 and 2), switches and
+ /// variables (step 3).
+ ///
internal static bool IsRemappable(IdKind kind)
{
- return kind is IdKind.MapEvent or IdKind.Map || DatabaseFiles.ContainsKey(kind);
+ return kind is IdKind.MapEvent or IdKind.Map || DatabaseFiles.ContainsKey(kind) || IsStateKind(kind);
+ }
+
+ /// True for switches and variables, whose ids no record holds: vanilla names or references them, or not (GR-R2).
+ internal static bool IsStateKind(IdKind kind)
+ {
+ return kind is IdKind.Switch or IdKind.Variable;
+ }
+
+ /// The System.json list that names ids of a state kind, or null for any other kind.
+ internal static string? StateNamesOf(IdKind kind)
+ {
+ return kind switch
+ {
+ IdKind.Switch => SwitchNamesProperty,
+ IdKind.Variable => VariableNamesProperty,
+ _ => null
+ };
}
/// The key of the database file that holds , or null for a kind with no such file.
diff --git a/RPGModder.Core/Merge/VanillaStateIds.cs b/RPGModder.Core/Merge/VanillaStateIds.cs
new file mode 100644
index 0000000..ef21711
--- /dev/null
+++ b/RPGModder.Core/Merge/VanillaStateIds.cs
@@ -0,0 +1,109 @@
+using Newtonsoft.Json.Linq;
+using RPGModder.Core.Services;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The switch and variable ids vanilla names in System.json or refers to through the reference table, from 1 up
+/// to the remap limit (GR-R6). A mod never moves onto one, and two mods that share one are no overlap: vanilla owns it.
+/// SwitchCount and VariableCount are the lengths of vanilla's lists of names, slot 0 included. Free text
+/// names no kind, so it does not count (GR-R15). Lane A runs once per vanilla version and keeps the
+/// result with and the hashes of the files it read.
+///
+public sealed class VanillaStateIds
+{
+ /// Raised when what reads changes, so a kept result is scanned again.
+ public const int ScanVersion = 1;
+
+ public VanillaStateIds(IReadOnlyList switches, IReadOnlyList variables, int switchCount, int variableCount)
+ {
+ ArgumentNullException.ThrowIfNull(switches);
+ ArgumentNullException.ThrowIfNull(variables);
+ Switches = switches;
+ Variables = variables;
+ SwitchCount = switchCount;
+ VariableCount = variableCount;
+ }
+
+ /// The switch ids vanilla uses, ascending.
+ public IReadOnlyList Switches { get; }
+
+ /// The variable ids vanilla uses, ascending.
+ public IReadOnlyList Variables { get; }
+
+ /// The length of vanilla's list of switch names, slot 0 included.
+ public int SwitchCount { get; }
+
+ /// The length of vanilla's list of variable names, slot 0 included.
+ public int VariableCount { get; }
+
+ ///
+ /// Reads every data file in (other kinds are skipped) and returns the ids vanilla
+ /// uses, or null when a data file cannot be read, because a missed id could let a mod move onto it.
+ ///
+ public static VanillaStateIds? Scan(IEnumerable dataFiles, RpgMakerEngine? engine)
+ {
+ ArgumentNullException.ThrowIfNull(dataFiles);
+
+ var ops = new List();
+ int switchCount = 0;
+ int variableCount = 0;
+ foreach (BaseFile file in dataFiles.OrderBy(file => MergePath.ToKey(file.Path), StringComparer.Ordinal))
+ {
+ string key = MergePath.ToKey(file.Path);
+ if (RpgDataSchema.KindOf(key) != MergeFileKind.Data)
+ {
+ continue;
+ }
+
+ if (!ChangeSetBuilder.TryReadBase(file, out JToken? root, out _))
+ {
+ return null;
+ }
+
+ if (key == RpgDataSchema.SystemFileKey)
+ {
+ switchCount = (root[RpgDataSchema.SwitchNamesProperty] as JArray)?.Count ?? 0;
+ variableCount = (root[RpgDataSchema.VariableNamesProperty] as JArray)?.Count ?? 0;
+ }
+
+ // Vanilla reads as one mod that adds every file whole, so the walker sees each place the table names.
+ ops.Add(new ChangeOp("", new RecordKey(key, RecordKey.WholeFile), "", ChangeKind.AddRecord, root, null));
+ }
+
+ ModReferences references = ReferenceMap.Scan(new ModChangeSet("", 0, ops, []), [], dualWield: true, mz: engine == RpgMakerEngine.MZ);
+ return new VanillaStateIds(
+ IdsOf(references, IdKind.Switch, engine),
+ IdsOf(references, IdKind.Variable, engine),
+ switchCount,
+ variableCount);
+ }
+
+ /// The ids of vanilla uses, ascending.
+ public IReadOnlyList Of(IdKind kind)
+ {
+ return kind switch
+ {
+ IdKind.Switch => Switches,
+ IdKind.Variable => Variables,
+ _ => []
+ };
+ }
+
+ /// The length of vanilla's list of names of , slot 0 included.
+ public int CountOf(IdKind kind)
+ {
+ return kind switch
+ {
+ IdKind.Switch => SwitchCount,
+ IdKind.Variable => VariableCount,
+ _ => 0
+ };
+ }
+
+ private static List IdsOf(ModReferences references, IdKind kind, RpgMakerEngine? engine)
+ {
+ int limit = RpgDataSchema.RemapLimit(kind, engine) ?? 0;
+ return references.StateIds(kind, limit).ToList();
+ }
+}
diff --git a/RPGModder.Tests/Merge/IdRemapDatabaseTests.cs b/RPGModder.Tests/Merge/IdRemapDatabaseTests.cs
index db7c745..608b092 100644
--- a/RPGModder.Tests/Merge/IdRemapDatabaseTests.cs
+++ b/RPGModder.Tests/Merge/IdRemapDatabaseTests.cs
@@ -3,6 +3,7 @@
using RPGModder.Core.Models;
using RPGModder.Core.Operations;
using RPGModder.Core.Services;
+using RPGModder.Tests.Support;
using static RPGModder.Tests.Merge.MergeTestKit;
namespace RPGModder.Tests.Merge;
@@ -255,6 +256,7 @@ public void Plan_TwoModsAddingOneRecordId_MovesTheLaterModAndBothDeploy(IdKind k
{ IdKind.Actor, 324, "[3,\"Bold\"]", "[4,\"Bold\"]" },
{ IdKind.Actor, 325, "[3,\"Tall\"]", "[4,\"Tall\"]" },
{ IdKind.Actor, 339, "[1,3,1,-1]", "[1,4,1,-1]" },
+ { IdKind.Actor, 339, "[2,3,1,-1]", "[2,4,1,-1]" },
{ IdKind.Class, 321, "[1,3,false]", "[1,4,false]" },
{ IdKind.Class, 111, "[4,1,2,3]", "[4,1,2,4]" },
{ IdKind.Animation, 212, "[0,3,false]", "[0,4,false]" },
@@ -476,7 +478,11 @@ public void Plan_IdNotStoredAsAnInteger_IsAmbiguousWhenTheGameReadsItAsTheId(str
{ IdKind.Actor, 316, "[1,5,0,0,1,false]" },
{ IdKind.Actor, 317, "[1,5,0,0,0,1]" },
{ IdKind.Actor, 318, "[1,5,0,1]" },
- { IdKind.Actor, 326, "[1,5,0,0,10]" }
+ { IdKind.Actor, 326, "[1,5,0,0,10]" },
+
+ // Any designation but 0 reads a variable.
+ { IdKind.Actor, 311, "[2,5,0,0,10,false]" },
+ { IdKind.Actor, 314, "[-1,5]" }
};
/// The command names its id through variable 5, which a Control Variables sets to .
@@ -1002,6 +1008,50 @@ public void Write_NewDatabaseFileWithHoles_FillsThemWithBlankRecords()
Assert.Equal("B", records[3]!["name"]!.Value());
}
+ public static TheoryData DatabaseKindsOnBothEngines()
+ {
+ var data = new TheoryData();
+ foreach (IdKind kind in FileOfKind.Keys)
+ {
+ data.Add(kind, RpgMakerEngine.MZ);
+ data.Add(kind, RpgMakerEngine.MV);
+ }
+
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(DatabaseKindsOnBothEngines))]
+ public void Write_RecordedTargetPastTheEnd_FillsTheHoleWithBlankRecordsTheTestInterpreterLoads(IdKind kind, RpgMakerEngine engine)
+ {
+ var game = new Game();
+ (RemapMod a, RemapMod b) = game.Clash(kind);
+ string file = FileOfKind[kind];
+
+ RemapPlan plan = IdRemapPlanner.Plan([a, b], [new IdRemap("b-oak", kind, "", 3, 6)], ["a-tin", "b-oak"], game.Bases, engine);
+ MergePlan merged = ComposeRemapped(plan, game, a, b);
+ string text = MergedFileWriter.Write(merged, game.Bases, null, engine)
+ .Single(item => string.Equals(item.File, file, StringComparison.OrdinalIgnoreCase)).Text!;
+
+ JArray records = TestInterpreter.LoadDatabase(file, text);
+ Assert.Equal([$"b-oak|{kind}||3>6"], plan.Remaps.Select(Entry));
+ Assert.Equal(7, records.Count);
+ Assert.All([4, 5], id => Assert.True(RpgDataSchema.HasBlankShape(file.ToLowerInvariant(), records[id]), $"{file} {id}"));
+ Assert.Equal(("A", "B"), (records[3]!["name"]!.Value(), records[6]!["name"]!.Value()));
+ }
+
+ [Fact]
+ public void Plan_RecordedTargetAtTheTopOfTheRange_LeavesNoTargetRatherThanWrapping()
+ {
+ var game = new Game();
+ (RemapMod a, RemapMod b) = game.Clash(IdKind.Actor);
+
+ RemapPlan plan = IdRemapPlanner.Plan([a, b], [new IdRemap("z-old", IdKind.Actor, "", 9, int.MaxValue)], [], game.Bases, RpgMakerEngine.MZ);
+
+ Assert.DoesNotContain(plan.Remaps, remap => remap.ToId < 1);
+ Assert.Empty(plan.NewEntries);
+ }
+
[Fact]
public void Write_NewDatabaseFileWithoutHoles_IsTheModsOwnFile()
{
diff --git a/RPGModder.Tests/Merge/IdRemapStateTests.cs b/RPGModder.Tests/Merge/IdRemapStateTests.cs
new file mode 100644
index 0000000..d394a91
--- /dev/null
+++ b/RPGModder.Tests/Merge/IdRemapStateTests.cs
@@ -0,0 +1,1456 @@
+using Newtonsoft.Json.Linq;
+using RPGModder.Core.Merge;
+using RPGModder.Core.Models;
+using RPGModder.Core.Operations;
+using RPGModder.Core.Services;
+using static RPGModder.Tests.Merge.MergeTestKit;
+
+namespace RPGModder.Tests.Merge;
+
+/// TST-15, step 3: switches and variables. Content is invented (TST-2).
+public sealed class IdRemapStateTests
+{
+ private const string CommonEvents = "data/CommonEvents.json";
+ private const string Troops = "data/Troops.json";
+ private const string Enemies = "data/Enemies.json";
+
+ /// Vanilla names switches 1 and 2 and variable 1; its map and common event read switch 1.
+ private const string StateSystem =
+ "{\"gameTitle\":\"Sample\",\"versionId\":11,\"switches\":[\"\",\"Door\",\"Lever\"],\"variables\":[\"\",\"Gold\"],\"partyMembers\":[1]}";
+
+ private const string VanillaCommonEvents =
+ "[null,{\"id\":1,\"list\":[{\"code\":0,\"indent\":0,\"parameters\":[]}],\"name\":\"Start\",\"switchId\":1,\"trigger\":0}]";
+
+ private const string VanillaTroops =
+ "[null,{\"id\":1,\"members\":[],\"name\":\"Pair\",\"pages\":[{\"conditions\":{\"switchId\":1,\"switchValid\":false},\"list\":[],\"span\":0}]}]";
+
+ private const string VanillaEnemies =
+ "[null,{\"id\":1,\"actions\":[{\"conditionParam1\":0,\"conditionParam2\":0,\"conditionType\":0,\"rating\":5,\"skillId\":1}],\"name\":\"Blob\",\"note\":\"\"}]";
+
+ private static readonly IdRemap SwitchTen = new("b-oak", IdKind.Switch, "", 10, 11);
+ private static readonly IdRemap VariableTen = new("b-oak", IdKind.Variable, "", 10, 11);
+
+ private sealed class Game
+ {
+ private readonly Dictionary _vanilla = new(StringComparer.Ordinal)
+ {
+ [SystemFile] = StateSystem,
+ [Map] = VanillaMap,
+ [CommonEvents] = VanillaCommonEvents,
+ [Troops] = VanillaTroops,
+ [Enemies] = VanillaEnemies
+ };
+
+ public Game(params (string Path, string Text)[] overrides)
+ {
+ foreach ((string path, string text) in overrides)
+ {
+ _vanilla[path] = text;
+ }
+
+ Bases = MergeTestKit.Bases(_vanilla.Select(pair => Base(pair.Key, pair.Value)).ToArray());
+ Files = _vanilla.Select(pair => Base(pair.Key, pair.Value)).ToList();
+ }
+
+ public BaseFileSet Bases { get; }
+
+ public List Files { get; }
+
+ public VanillaStateIds Scan(RpgMakerEngine? engine = RpgMakerEngine.MZ)
+ {
+ return VanillaStateIds.Scan(Files, engine)!;
+ }
+
+ /// A mod whose files are vanilla's with applied; it ships the files it touched.
+ public RemapMod Mod(string modId, int priority, Action> edit, params string[] scripts)
+ {
+ var files = new Dictionary(StringComparer.Ordinal);
+ edit(path =>
+ {
+ if (!files.TryGetValue(path, out JToken? root))
+ {
+ root = JToken.Parse(_vanilla[path]);
+ files[path] = root;
+ }
+
+ return root;
+ });
+
+ var source = new ModSource(
+ modId,
+ priority,
+ files.Select(pair =>
+ {
+ string text = pair.Value.ToString();
+ return new ModFile(pair.Key, "files/" + Path.GetFileName(pair.Key), text, Hash(text));
+ }).ToList(),
+ [],
+ []);
+ return new RemapMod(ChangeSetBuilder.Build(source, Bases), true, scripts);
+ }
+ }
+
+ private static JObject Command(int code, params object[] parameters)
+ {
+ return new JObject { ["code"] = code, ["indent"] = 0, ["parameters"] = new JArray(parameters) };
+ }
+
+ private static JObject Command(int code, string parameters)
+ {
+ return new JObject { ["code"] = code, ["indent"] = 0, ["parameters"] = JArray.Parse(parameters) };
+ }
+
+ /// Puts first in event 's page.
+ private static Action> InEvent(JObject command, int eventId = 1)
+ {
+ return file => ((JArray)file(Map)["events"]![eventId]!["pages"]![0]!["list"]!).Insert(0, command.DeepClone());
+ }
+
+ private static Action> Both(params Action>[] edits)
+ {
+ return file =>
+ {
+ foreach (Action> edit in edits)
+ {
+ edit(file);
+ }
+ };
+ }
+
+ private static Action> Set(string file, string path, string json)
+ {
+ return files =>
+ {
+ JToken root = files(file);
+ int dot = path.LastIndexOf('.');
+ var parent = (JObject)(dot < 0 ? root : root.SelectToken(path[..dot])!);
+ parent[path[(dot + 1)..]] = JToken.Parse(json);
+ };
+ }
+
+ private static Action> NameSwitch(int id, string name)
+ {
+ return Name("switches", id, name);
+ }
+
+ private static Action> NameVariable(int id, string name)
+ {
+ return Name("variables", id, name);
+ }
+
+ private static Action> Name(string list, int id, string name)
+ {
+ return files =>
+ {
+ var names = (JArray)files(SystemFile)[list]!;
+ while (names.Count <= id)
+ {
+ names.Add("");
+ }
+
+ names[id] = name;
+ };
+ }
+
+ private static Action> UseSwitches(int first, int last, int eventId = 1)
+ {
+ return InEvent(Command(121, first, last, 0), eventId);
+ }
+
+ private static string Key(string path)
+ {
+ return MergePath.ToKey(path);
+ }
+
+ private static string Entry(IdRemap remap)
+ {
+ return $"{remap.ModId}|{remap.Kind}|{remap.FromId}>{remap.ToId}";
+ }
+
+ private static string Flat(JToken? token)
+ {
+ return token!.ToString(Newtonsoft.Json.Formatting.None);
+ }
+
+ private static RemapPlan Plan(Game game, IReadOnlyList recorded, IReadOnlyCollection deployed, VanillaStateIds? states, params RemapMod[] mods)
+ {
+ return IdRemapPlanner.Plan(mods, recorded, deployed, game.Bases, RpgMakerEngine.MZ, states);
+ }
+
+ private static RemapPlan Plan(Game game, params RemapMod[] mods)
+ {
+ return Plan(game, [], [], game.Scan(), mods);
+ }
+
+ private static MergePlan ComposeRemapped(RemapPlan plan, Game game, params RemapMod[] mods)
+ {
+ List sets = mods.Select(mod => IdRemapper.Apply(mod.ChangeSet, plan.Remaps)).ToList();
+ return Composer.Compose(sets, [], game.Bases, plan);
+ }
+
+ private static JArray SwitchNames(MergePlan merged, Game game)
+ {
+ string text = MergedFileWriter.Write(merged, game.Bases, null, RpgMakerEngine.MZ).Single(file => file.File == Key(SystemFile)).Text!;
+ return (JArray)JToken.Parse(text)["switches"]!;
+ }
+
+ private static JToken FirstCommand(ModChangeSet set, int eventId = 1)
+ {
+ ChangeOp edited = Assert.Single(set.Ops, op => op.Key.File == Key(Map) && op.Key.Record == "event:" + eventId);
+ return edited.Value is JArray list ? list[0]! : edited.Value!["pages"]![0]!["list"]![0]!;
+ }
+
+ // ---- Rows ----
+
+ public static TheoryData CommandRows => new()
+ {
+ { IdKind.Switch, 121, "[10,10,0]", "[11,11,0]" },
+ { IdKind.Switch, 111, "[0,10,0]", "[0,11,0]" },
+ { IdKind.Variable, 122, "[10,10,0,0,5]", "[11,11,0,0,5]" },
+ { IdKind.Variable, 122, "[1,1,0,1,10]", "[1,1,0,1,11]" },
+ { IdKind.Variable, 111, "[1,10,0,5,0]", "[1,11,0,5,0]" },
+ { IdKind.Variable, 111, "[1,1,1,10,0]", "[1,1,1,11,0]" },
+ { IdKind.Variable, 103, "[10,2]", "[11,2]" },
+ { IdKind.Variable, 104, "[10,1]", "[11,1]" },
+ { IdKind.Variable, 285, "[10,0,0,1,1]", "[11,0,0,1,1]" },
+ { IdKind.Variable, 285, "[1,0,1,10,10]", "[1,0,1,11,11]" },
+ { IdKind.Variable, 125, "[0,1,10]", "[0,1,11]" },
+ { IdKind.Variable, 126, "[1,0,1,10]", "[1,0,1,11]" },
+ { IdKind.Variable, 127, "[1,0,1,10,false]", "[1,0,1,11,false]" },
+ { IdKind.Variable, 128, "[1,0,1,10,false]", "[1,0,1,11,false]" },
+ { IdKind.Variable, 201, "[1,10,10,10,2,0]", "[1,11,11,11,2,0]" },
+ { IdKind.Variable, 202, "[0,1,10,10,10]", "[0,1,11,11,11]" },
+ { IdKind.Variable, 203, "[0,1,10,10,2]", "[0,1,11,11,2]" },
+ { IdKind.Variable, 231, "[1,\"pic\",0,1,10,10,100,100,255,0]", "[1,\"pic\",0,1,11,11,100,100,255,0]" },
+ { IdKind.Variable, 232, "[1,0,0,1,10,10,100,100,255,0,60,true]", "[1,0,0,1,11,11,100,100,255,0,60,true]" },
+ { IdKind.Variable, 301, "[1,10,false,false]", "[1,11,false,false]" },
+ { IdKind.Variable, 311, "[1,10,0,0,5,false]", "[1,11,0,0,5,false]" },
+ { IdKind.Variable, 311, "[0,1,0,1,10,false]", "[0,1,0,1,11,false]" },
+ { IdKind.Variable, 312, "[0,1,0,1,10]", "[0,1,0,1,11]" },
+ { IdKind.Variable, 312, "[1,10,0,0,5]", "[1,11,0,0,5]" },
+ { IdKind.Variable, 313, "[1,10,0,1]", "[1,11,0,1]" },
+ { IdKind.Variable, 314, "[1,10]", "[1,11]" },
+ { IdKind.Variable, 315, "[0,1,0,1,10,false]", "[0,1,0,1,11,false]" },
+ { IdKind.Variable, 315, "[1,10,0,0,5,false]", "[1,11,0,0,5,false]" },
+ { IdKind.Variable, 316, "[0,1,0,1,10,false]", "[0,1,0,1,11,false]" },
+ { IdKind.Variable, 316, "[1,10,0,0,5,false]", "[1,11,0,0,5,false]" },
+ { IdKind.Variable, 317, "[0,1,0,0,1,10]", "[0,1,0,0,1,11]" },
+ { IdKind.Variable, 317, "[1,10,0,0,0,5]", "[1,11,0,0,0,5]" },
+ { IdKind.Variable, 318, "[1,10,0,1]", "[1,11,0,1]" },
+ { IdKind.Variable, 326, "[0,1,0,1,10]", "[0,1,0,1,11]" },
+ { IdKind.Variable, 326, "[1,10,0,0,5]", "[1,11,0,0,5]" },
+ { IdKind.Variable, 331, "[0,0,1,10,false]", "[0,0,1,11,false]" },
+ { IdKind.Variable, 332, "[0,0,1,10]", "[0,0,1,11]" },
+ { IdKind.Variable, 342, "[0,0,1,10]", "[0,0,1,11]" },
+ { IdKind.Variable, 401, "[\"Has \\\\V[10] and \\\\v[10]\"]", "[\"Has \\\\V[11] and \\\\v[11]\"]" },
+
+ // The engine reads a variable for any designation but 0, not only the 1 the editor writes.
+ { IdKind.Variable, 111, "[1,1,2,10,0]", "[1,1,2,11,0]" },
+ { IdKind.Variable, 125, "[0,2,10]", "[0,2,11]" },
+ { IdKind.Variable, 126, "[1,0,-1,10]", "[1,0,-1,11]" },
+ { IdKind.Variable, 201, "[2,10,10,10,2,0]", "[2,11,11,11,2,0]" },
+ { IdKind.Variable, 202, "[0,2,10,10,10]", "[0,2,11,11,11]" },
+ { IdKind.Variable, 231, "[1,\"pic\",0,2,10,10,100,100,255,0]", "[1,\"pic\",0,2,11,11,100,100,255,0]" },
+ { IdKind.Variable, 232, "[1,0,0,-1,10,10,100,100,255,0,60,true]", "[1,0,0,-1,11,11,100,100,255,0,60,true]" },
+ { IdKind.Variable, 311, "[2,10,0,0,5,false]", "[2,11,0,0,5,false]" },
+ { IdKind.Variable, 317, "[0,1,0,0,2,10]", "[0,1,0,0,2,11]" },
+ { IdKind.Variable, 331, "[0,0,-1,10,false]", "[0,0,-1,11,false]" },
+
+ // Same codes, other forms: the 10 is a constant, another kind's id, or read so only by MV.
+ { IdKind.Switch, 111, "[1,10,0,0,0]", "[1,10,0,0,0]" },
+ { IdKind.Switch, 111, "[2,\"A\",0]", "[2,\"A\",0]" },
+ { IdKind.Variable, 111, "[0,10,0]", "[0,10,0]" },
+ { IdKind.Variable, 111, "[1,1,0,10,0]", "[1,1,0,10,0]" },
+ { IdKind.Variable, 122, "[1,1,0,0,10]", "[1,1,0,0,10]" },
+ { IdKind.Variable, 122, "[1,1,0,2,10,20]", "[1,1,0,2,10,20]" },
+ { IdKind.Variable, 122, "[1,1,0,3,0,10,0]", "[1,1,0,3,0,10,0]" },
+ { IdKind.Variable, 122, "[9,12,0,0,5]", "[9,12,0,0,5]" },
+ { IdKind.Variable, 127, "[1,0,0,10,false]", "[1,0,0,10,false]" },
+ { IdKind.Variable, 128, "[1,0,0,10,false]", "[1,0,0,10,false]" },
+ { IdKind.Variable, 232, "[1,0,0,0,10,10,100,100,255,0,60,true]", "[1,0,0,0,10,10,100,100,255,0,60,true]" },
+ { IdKind.Variable, 125, "[0,0,10]", "[0,0,10]" },
+ { IdKind.Variable, 126, "[1,0,0,10]", "[1,0,0,10]" },
+ { IdKind.Variable, 201, "[0,10,10,10,2,0]", "[0,10,10,10,2,0]" },
+ { IdKind.Variable, 202, "[0,0,10,10,10]", "[0,0,10,10,10]" },
+ { IdKind.Variable, 203, "[0,0,10,10,2]", "[0,0,10,10,2]" },
+ { IdKind.Variable, 231, "[1,\"pic\",0,0,10,10,100,100,255,0]", "[1,\"pic\",0,0,10,10,100,100,255,0]" },
+ { IdKind.Variable, 285, "[1,0,0,10,10]", "[1,0,0,10,10]" },
+ { IdKind.Variable, 285, "[1,0,2,10,10]", "[1,0,2,10,10]" },
+ { IdKind.Variable, 285, "[1,0,3,10,10]", "[1,0,3,10,10]" },
+ { IdKind.Variable, 203, "[0,2,10,10,2]", "[0,2,10,10,2]" },
+ { IdKind.Variable, 301, "[2,10,false,false]", "[2,10,false,false]" },
+ { IdKind.Variable, 301, "[0,10,false,false]", "[0,10,false,false]" },
+ { IdKind.Variable, 311, "[0,10,0,0,5,false]", "[0,10,0,0,5,false]" },
+ { IdKind.Variable, 311, "[0,1,0,0,10,false]", "[0,1,0,0,10,false]" },
+ { IdKind.Variable, 312, "[0,1,0,0,10]", "[0,1,0,0,10]" },
+ { IdKind.Variable, 315, "[0,1,0,0,10,false]", "[0,1,0,0,10,false]" },
+ { IdKind.Variable, 316, "[0,1,0,0,10,false]", "[0,1,0,0,10,false]" },
+ { IdKind.Variable, 317, "[0,1,0,0,0,10]", "[0,1,0,0,0,10]" },
+ { IdKind.Variable, 326, "[0,1,0,0,10]", "[0,1,0,0,10]" },
+ { IdKind.Variable, 331, "[0,0,0,10,false]", "[0,0,0,10,false]" },
+ { IdKind.Variable, 332, "[0,0,0,10]", "[0,0,0,10]" },
+ { IdKind.Variable, 342, "[0,0,0,10]", "[0,0,0,10]" }
+ };
+
+ [Theory]
+ [MemberData(nameof(CommandRows))]
+ public void Apply_MovedStateId_RewritesEveryCommandRowOfItsKind(IdKind kind, int code, string before, string after)
+ {
+ var game = new Game();
+
+ // The anchor in event 2 keeps the entry active when the row under test names no id of the kind.
+ JObject anchor = kind == IdKind.Switch ? Command(121, 10, 10, 0) : Command(122, 10, 10, 0, 0, 5);
+ RemapMod b = game.Mod("b-oak", 1, Both(InEvent(Command(code, before)), InEvent(anchor, 2)));
+
+ ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, [kind == IdKind.Switch ? SwitchTen : VariableTen]);
+
+ Assert.Equal(after, Flat(FirstCommand(moved)["parameters"]));
+ }
+
+ [Theory]
+ [InlineData(27)]
+ [InlineData(28)]
+ public void Apply_MovedSwitch_RewritesTheMoveRouteSwitchCommands(int code)
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Set(Map, "events[1].pages[0].moveRoute", $"{{\"list\":[{{\"code\":{code},\"parameters\":[10]}},{{\"code\":0}}],\"repeat\":true}}"));
+
+ ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, [SwitchTen]);
+
+ ChangeOp edited = Assert.Single(moved.Ops, op => op.Key.Record == "event:1");
+ JObject route = ((JContainer)edited.Value!).DescendantsAndSelf().OfType().First(item => item["code"]?.Value() == code);
+ Assert.Equal($"{{\"code\":{code},\"parameters\":[11]}}", Flat(route));
+ }
+
+ public static TheoryData FieldRows => new()
+ {
+ { IdKind.Switch, Map, "events[1].pages[0].conditions.switch1Id", "10", "11" },
+ { IdKind.Switch, Map, "events[1].pages[0].conditions.switch2Id", "10", "11" },
+ { IdKind.Variable, Map, "events[1].pages[0].conditions.variableId", "10", "11" },
+ { IdKind.Switch, Troops, "[1].pages[0].conditions.switchId", "10", "11" },
+ { IdKind.Switch, CommonEvents, "[1].switchId", "10", "11" },
+ { IdKind.Switch, Enemies, "[1].actions[0].conditionParam1", "10", "11" }
+ };
+
+ [Theory]
+ [MemberData(nameof(FieldRows))]
+ public void Apply_MovedStateId_RewritesEveryFieldRowOfItsKind(IdKind kind, string file, string path, string before, string after)
+ {
+ var game = new Game();
+ Action> edit = Set(file, path, before);
+ if (file == Enemies)
+ {
+ edit = Both(edit, Set(file, "[1].actions[0].conditionType", "6"));
+ }
+
+ RemapMod b = game.Mod("b-oak", 1, edit);
+
+ ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, [kind == IdKind.Switch ? SwitchTen : VariableTen]);
+
+ string leaf = path[(path.LastIndexOf('.') + 1)..];
+ List ops = moved.Ops.Where(op => op.Key.File == Key(file)).ToList();
+ Assert.Contains(ops, op => Flat(op.Value).Contains($"\"{leaf}\":{after}", StringComparison.Ordinal) ||
+ (op.Path.EndsWith(leaf, StringComparison.Ordinal) && Flat(op.Value) == after));
+ Assert.DoesNotContain(ops, op => Flat(op.Value).Contains($"\"{leaf}\":{before}", StringComparison.Ordinal) ||
+ (op.Path.EndsWith(leaf, StringComparison.Ordinal) && Flat(op.Value) == before));
+ }
+
+ [Fact]
+ public void Apply_EnemyActionOfAnotherConditionType_KeepsItsParameter()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(
+ Set(Enemies, "[1].actions[0].conditionParam1", "10"),
+ Set(Enemies, "[1].actions[0].conditionType", "5"),
+ UseSwitches(10, 10)));
+
+ ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, [SwitchTen]);
+
+ Assert.DoesNotContain(moved.Ops, op => op.Key.File == Key(Enemies) && Flat(op.Value).Contains("\"conditionParam1\":11", StringComparison.Ordinal));
+ }
+
+ // ---- Names ----
+
+ [Fact]
+ public void Apply_MovedSwitchTheModNames_MovesTheNameWithTheId()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, NameSwitch(10, "Mine"));
+
+ ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, [SwitchTen]);
+
+ Assert.Contains(moved.Ops, op => op.Key.File == Key(SystemFile) && op.Path == "switches[11]" && Flat(op.Value) == "\"Mine\"");
+ Assert.DoesNotContain(moved.Ops, op => op.Key.File == Key(SystemFile) && op.Path == "switches[10]");
+ Assert.Single(moved.Ops, op => op.Path == "switches[11]");
+ }
+
+ [Fact]
+ public void Apply_MovedSwitchTheModDoesNotName_AddsAnEmptyNameSoTheListReachesIt()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+
+ ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, [SwitchTen]);
+
+ ChangeOp slot = Assert.Single(moved.Ops, op => op.Key.File == Key(SystemFile));
+ Assert.Equal(("switches[11]", ChangeKind.SetLeaf, "\"\""), (slot.Path, slot.Kind, Flat(slot.Value)));
+ Assert.Equal(moved.Ops.OrderBy(op => op, Comparer.Create(ChangeSetBuilder.CompareOps)), moved.Ops);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData("switches")]
+ public void Apply_OpHoldingTheWholeNameList_MovesTheNameEmptiesTheOldSlotAndAddsNoSlot(string path)
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+ JArray names = JArray.Parse("[\"\",\"Door\",\"Lever\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"Mine\"]");
+ JToken value = path.Length == 0 ? new JObject { ["switches"] = names, ["variables"] = JArray.Parse("[\"\",\"Gold\"]") } : names;
+ ChangeKind kind = path.Length == 0 ? ChangeKind.ReplaceFile : ChangeKind.SetLeaf;
+ var whole = new ChangeOp("b-oak", RemapPlaces.StateKey, path, kind, value, null);
+ var set = new ModChangeSet("b-oak", 1, b.ChangeSet.Ops.Append(whole).ToList(), []);
+
+ ModChangeSet moved = IdRemapper.Apply(set, [SwitchTen]);
+
+ ChangeOp system = Assert.Single(moved.Ops, op => op.Key == RemapPlaces.StateKey);
+ JToken list = path.Length == 0 ? system.Value!["switches"]! : system.Value!;
+ Assert.Equal("[\"\",\"Door\",\"Lever\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"Mine\"]", Flat(list));
+ }
+
+ [Fact]
+ public void Write_MovedSwitch_PadsTheNamesWithEmptyNamesUpToTheNewId()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+ var plan = new RemapPlan([SwitchTen], [], [], []);
+
+ MergePlan merged = ComposeRemapped(plan, game, b);
+ JToken system = JToken.Parse(MergedFileWriter.Write(merged, game.Bases, null, RpgMakerEngine.MZ).Single(file => file.File == Key(SystemFile)).Text!);
+
+ Assert.Equal("[\"\",\"Door\",\"Lever\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]", Flat(system["switches"]));
+ }
+
+ [Fact]
+ public void Compose_EmptyNamePaddingTheList_YieldsToAnotherModsName()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, Both(NameSwitch(10, "Mine"), UseSwitches(10, 10)));
+ RemapMod b = game.Mod("b-oak", 1, Both(NameSwitch(12, "Theirs"), UseSwitches(12, 12, 2)));
+
+ MergePlan merged = ComposeRemapped(Plan(game, a, b), game, a, b);
+ JToken system = JToken.Parse(MergedFileWriter.Write(merged, game.Bases, null, RpgMakerEngine.MZ).Single(file => file.File == Key(SystemFile)).Text!);
+
+ Assert.Empty(merged.Collisions);
+ Assert.Equal("[\"\",\"Door\",\"Lever\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"Mine\",\"\",\"Theirs\"]", Flat(system["switches"]));
+ }
+
+ [Fact]
+ public void Apply_MovedVariableTheModNames_MovesTheNameWithTheId()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(NameVariable(10, "Mine"), InEvent(Command(122, 10, 10, 0, 0, 5))));
+
+ ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, [VariableTen]);
+
+ Assert.Contains(moved.Ops, op => op.Path == "variables[11]" && Flat(op.Value) == "\"Mine\"");
+ Assert.DoesNotContain(moved.Ops, op => op.Path == "variables[10]" && Flat(op.Value) == "\"Mine\"");
+ }
+
+ [Fact]
+ public void Write_MovedVariable_PadsTheNamesWithEmptyNamesUpToTheNewId()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, InEvent(Command(122, 10, 10, 0, 0, 5)));
+ var plan = new RemapPlan([VariableTen], [], [], []);
+
+ MergePlan merged = ComposeRemapped(plan, game, b);
+ JToken system = JToken.Parse(MergedFileWriter.Write(merged, game.Bases, null, RpgMakerEngine.MZ).Single(file => file.File == Key(SystemFile)).Text!);
+
+ Assert.Equal("[\"\",\"Gold\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]", Flat(system["variables"]));
+ }
+
+ [Fact]
+ public void Compose_EmptyVariableNamePaddingTheList_YieldsToAnotherModsName()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, Both(NameVariable(10, "Mine"), InEvent(Command(122, 10, 10, 0, 0, 5))));
+ RemapMod b = game.Mod("b-oak", 1, Both(NameVariable(12, "Theirs"), InEvent(Command(122, 12, 12, 0, 0, 5), 2)));
+
+ MergePlan merged = ComposeRemapped(Plan(game, a, b), game, a, b);
+ JToken system = JToken.Parse(MergedFileWriter.Write(merged, game.Bases, null, RpgMakerEngine.MZ).Single(file => file.File == Key(SystemFile)).Text!);
+
+ Assert.Empty(merged.Collisions);
+ Assert.Equal("[\"\",\"Gold\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"Mine\",\"\",\"Theirs\"]", Flat(system["variables"]));
+ }
+
+ [Fact]
+ public void Compose_MovedEmptyNameOverTheModsOwnEmptyName_ListsTheModOnce()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), NameSwitch(11, "")));
+
+ MergePlan merged = ComposeRemapped(new RemapPlan([SwitchTen], [], [], []), game, b);
+
+ MergedOp slot = Assert.Single(merged.Ops, item => item.Op.Path == "switches[11]");
+ Assert.Equal(["b-oak"], slot.ModIds);
+ }
+
+ [Fact]
+ public void Compose_EmptyNameOverAVanillaName_StillClashes()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, NameSwitch(2, "Pull"));
+ RemapMod b = game.Mod("b-oak", 1, NameSwitch(2, ""));
+
+ Collision clash = Assert.Single(ComposeRemapped(Plan(game, a, b), game, a, b).Collisions);
+
+ Assert.Equal((CollisionKind.ValueClash, "switches[2]"), (clash.Kind, clash.Path));
+ }
+
+ [Fact]
+ public void Compose_TwoNamesForASharedSwitch_FoldIntoTheOverlapWithTheStayingModsName()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, Both(NameSwitch(10, "Mine"), UseSwitches(10, 10)));
+ RemapMod b = game.Mod("b-oak", 1, Both(NameSwitch(10, "Theirs"), UseSwitches(10, 10, 2)));
+
+ RemapPlan plan = Plan(game, a, b);
+ MergePlan merged = ComposeRemapped(plan, game, a, b);
+
+ Collision overlap = Assert.Single(merged.Collisions);
+ Assert.Equal(CollisionKind.StateIdOverlap, overlap.Kind);
+ Assert.True(merged.IsDeployable);
+ Assert.Equal("\"Mine\"", Flat(SwitchNames(merged, game)[10]));
+
+ // Taking the offer carries b-oak's name to its new id.
+ RemapPlan moved = Plan(game, plan.OffersFor(overlap, "b-oak"), [], game.Scan(), a, b);
+ MergePlan after = ComposeRemapped(moved, game, a, b);
+ Assert.Empty(after.Collisions);
+ Assert.Equal(("\"Mine\"", "\"Theirs\""), (Flat(SwitchNames(after, game)[10]), Flat(SwitchNames(after, game)[11])));
+ }
+
+ [Fact]
+ public void Compose_TwoNamesForASharedSwitchNeitherModCanMove_KeepTheLatestName()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, Both(NameSwitch(10, "Mine"), UseSwitches(10, 10), Set(Enemies, "[1].note", "\"10\"")));
+ RemapMod b = game.Mod("b-oak", 1, Both(NameSwitch(10, "Theirs"), UseSwitches(10, 10), Set(Map, "events[2].note", "\"10!\"")));
+
+ MergePlan merged = ComposeRemapped(Plan(game, a, b), game, a, b);
+
+ Assert.Equal(CollisionKind.StateIdOverlap, Assert.Single(merged.Collisions).Kind);
+ Assert.Equal("\"Theirs\"", Flat(SwitchNames(merged, game)[10]));
+ }
+
+ [Fact]
+ public void Compose_SharedSwitchWhoseSlotOneModSetsToNull_StillClashes()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, Both(NameSwitch(10, "Mine"), UseSwitches(10, 10)));
+ RemapMod b = game.Mod("b-oak", 1, Both(NameSwitch(10, "Theirs"), files => files(SystemFile)["switches"]![10] = JValue.CreateNull(), UseSwitches(10, 10, 2)));
+
+ RemapPlan plan = Plan(game, a, b);
+ MergePlan merged = ComposeRemapped(plan, game, a, b);
+
+ Assert.Equal("a-tin,b-oak", string.Join(',', Assert.Single(plan.SharedStateIds).ModIds));
+ Assert.Equal(
+ [(CollisionKind.ValueClash, "switches[10]"), (CollisionKind.StateIdOverlap, "switches[10]")],
+ merged.Collisions.Select(item => (item.Kind, item.Path)).Order());
+ }
+
+ [Fact]
+ public void Compose_SharedSwitchWhoseMoverIsLatest_KeepsTheLatestStayingModsName()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, Both(NameSwitch(10, "Mine"), UseSwitches(10, 10), Set(Enemies, "[1].note", "\"10\"")));
+ RemapMod b = game.Mod("b-oak", 1, Both(NameSwitch(10, "Theirs"), UseSwitches(10, 10), Set(Map, "events[2].note", "\"10!\"")));
+ RemapMod c = game.Mod("c-elm", 2, Both(NameSwitch(10, "Mine"), UseSwitches(10, 10, 2)));
+
+ RemapPlan plan = Plan(game, a, b, c);
+ MergePlan merged = ComposeRemapped(plan, game, a, b, c);
+
+ // c-elm gives a-tin's name but takes its offer, so b-oak is the latest mod that stays.
+ Assert.Equal("c-elm", Assert.Single(plan.Offers).ModId);
+ Assert.Equal(CollisionKind.StateIdOverlap, Assert.Single(merged.Collisions).Kind);
+ Assert.Equal("\"Theirs\"", Flat(SwitchNames(merged, game)[10]));
+ }
+
+ [Fact]
+ public void Compose_SharedSwitchTwoModsOfOnePriorityKeep_TheLaterIdsName()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("b-oak", 1, Both(NameSwitch(10, "Theirs"), UseSwitches(10, 10), Set(Enemies, "[1].note", "\"10\"")));
+ RemapMod b = game.Mod("a-tin", 1, Both(NameSwitch(10, "Mine"), UseSwitches(10, 10), Set(Map, "events[2].note", "\"10!\"")));
+
+ MergePlan merged = ComposeRemapped(Plan(game, a, b), game, a, b);
+
+ Assert.Equal("\"Theirs\"", Flat(SwitchNames(merged, game)[10]));
+ Assert.Equal("\"Theirs\"", Flat(SwitchNames(ComposeRemapped(Plan(game, b, a), game, b, a), game)[10]));
+ }
+
+ [Theory]
+ [InlineData(121)]
+ [InlineData(122)]
+ public void Compose_SharedSwitchNeitherModCanMoveWithAnOfferElsewhere_KeepsTheLatestName(int code)
+ {
+ var game = new Game();
+ JObject other = code == 121 ? Command(121, 12, 12, 0) : Command(122, 10, 10, 0, 0, 1);
+ // Vanilla's switch 2 holds both ranges where they are.
+ RemapMod a = game.Mod("a-tin", 0, Both(NameSwitch(10, "Mine"), UseSwitches(2, 10), InEvent(other)));
+ RemapMod b = game.Mod("b-oak", 1, Both(NameSwitch(10, "Theirs"), UseSwitches(2, 10, 2), InEvent(other, 2)));
+
+ RemapPlan plan = Plan(game, a, b);
+ MergePlan merged = ComposeRemapped(plan, game, a, b);
+
+ // b-oak is offered a move of the other id, switch 12 or variable 10, not of switch 10.
+ IdRemap offer = Assert.Single(plan.Offers);
+ Assert.Equal(("b-oak", code == 121 ? IdKind.Switch : IdKind.Variable), (offer.ModId, offer.Kind));
+ Assert.Equal("\"Theirs\"", Flat(SwitchNames(merged, game)[10]));
+ }
+
+ [Theory]
+ [InlineData("switches", 2)]
+ [InlineData("variables", 10)]
+ public void Compose_TwoNamesBesideASharedSwitch_StillClashWhereNothingIsShared(string list, int index)
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, Both(Name(list, index, "Mine"), UseSwitches(10, 10)));
+ RemapMod b = game.Mod("b-oak", 1, Both(Name(list, index, "Theirs"), UseSwitches(10, 10)));
+ var vanilla = new VanillaStateIds([1, 2], [1, 10], 3, 2);
+
+ MergePlan merged = ComposeRemapped(Plan(game, [], [], vanilla, a, b), game, a, b);
+
+ Assert.Equal(
+ [(CollisionKind.ValueClash, $"{list}[{index}]"), (CollisionKind.StateIdOverlap, "switches[10]")],
+ merged.Collisions.Select(item => (item.Kind, item.Path)).Order());
+ }
+
+ [Fact]
+ public void Compose_TwoNamesWithoutAVanillaScan_StillClash()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, Both(NameSwitch(10, "Mine"), UseSwitches(10, 10)));
+ RemapMod b = game.Mod("b-oak", 1, Both(NameSwitch(10, "Theirs"), UseSwitches(10, 10)));
+
+ Collision clash = Assert.Single(ComposeRemapped(Plan(game, [], [], null, a, b), game, a, b).Collisions);
+
+ Assert.Equal((CollisionKind.ValueClash, true), (clash.Kind, clash.Blocking));
+ }
+
+ [Fact]
+ public void Apply_InactiveStateEntry_ChangesNothing()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(12, 12));
+
+ Assert.Same(b.ChangeSet.Ops, IdRemapper.Apply(b.ChangeSet, [SwitchTen]).Ops);
+ Assert.Same(b.ChangeSet.Ops, IdRemapper.Apply(b.ChangeSet, [SwitchTen with { Scope = "data/Map001.json" }]).Ops);
+ }
+
+ [Fact]
+ public void Apply_StateEntryNamedOnlyInFreeText_ChangesNothing()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Set(Enemies, "[1].note", "\"\""));
+
+ Assert.Same(b.ChangeSet.Ops, IdRemapper.Apply(b.ChangeSet, [SwitchTen]).Ops);
+ }
+
+ [Theory]
+ [InlineData(0, 11)]
+ [InlineData(10, 5001)]
+ [InlineData(10, 0)]
+ public void Apply_DamagedStateEntry_ChangesNothing(int fromId, int toId)
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(InEvent(Command(111, 0, 0, 0)), UseSwitches(10, 10, 2)));
+
+ Assert.Same(b.ChangeSet.Ops, IdRemapper.Apply(b.ChangeSet, [new IdRemap("b-oak", IdKind.Switch, "", fromId, toId)]).Ops);
+ }
+
+ [Fact]
+ public void Apply_EntryNamedOnlyInAnMvLocationRow_StaysInForce()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, InEvent(Command(285, 1, 0, 2, 10, 10)));
+
+ ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, [VariableTen]);
+
+ Assert.Contains(moved.Ops, op => op.Key == RemapPlaces.StateKey && op.Path == "variables[11]");
+ }
+
+ // ---- Ranges (GR-R14) ----
+
+ [Theory]
+ [InlineData("[9,12,0]", "9>13,10>14,11>15,12>16", "[13,16,0]")]
+ [InlineData("[9,12,0]", "10>11", "[9,12,0]")]
+ [InlineData("[9,10,0]", "9>13,10>15", "[9,10,0]")]
+ [InlineData("[0,1,0]", "1>13", "[13,13,0]")]
+ [InlineData("[12,9,0]", "9>13,10>14,11>15,12>16", "[12,9,0]")]
+ public void Apply_Range_MovesOnlyWhenEveryIdMovesOntoConsecutiveIds(string before, string entries, string after)
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(InEvent(Command(121, before)), NameSwitch(9, "N9"), NameSwitch(10, "N10"), NameSwitch(1, "Door")));
+ List remaps = entries.Split(',')
+ .Select(item => item.Split('>'))
+ .Select(pair => new IdRemap("b-oak", IdKind.Switch, "", int.Parse(pair[0]), int.Parse(pair[1])))
+ .ToList();
+
+ ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, remaps);
+
+ Assert.Equal(after, Flat(FirstCommand(moved)["parameters"]));
+ }
+
+ // ---- Scan ----
+
+ [Fact]
+ public void Scan_References_CountRangesNamesAndRowsButNotFreeText()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(
+ InEvent(Command(121, 20, 22, 0)),
+ InEvent(Command(122, 7, 7, 0, 0, 1), 2),
+ NameSwitch(30, "Lamp"),
+ NameSwitch(31, ""),
+ Set(CommonEvents, "[1].name", "\"Uses 40\"")));
+
+ ModReferences references = ReferenceMap.Scan(b.ChangeSet, [], dualWield: false, mz: true);
+
+ Assert.Equal([20, 21, 22, 30], references.StateIds(IdKind.Switch, 5000));
+ Assert.Equal([7], references.StateIds(IdKind.Variable, 5000));
+ Assert.Equal([20, 21], references.StateIds(IdKind.Switch, 21));
+ Assert.True(references.Uses(IdKind.Switch, 21));
+ Assert.False(references.Uses(IdKind.Switch, 31));
+ }
+
+ [Fact]
+ public void Scan_RangeWithAnEndThatIsNotAWholeNumber_BlocksEveryIdOfItsKind()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, InEvent(Command(121, "[\"9\",12,0]")));
+
+ ModReferences references = ReferenceMap.Scan(b.ChangeSet, [], dualWield: false, mz: true);
+
+ Assert.True(references.Blocks(IdKind.Switch, 500));
+ Assert.False(references.Blocks(IdKind.Variable, 500));
+ }
+
+ [Theory]
+ [InlineData(true, false)]
+ [InlineData(false, true)]
+ public void Scan_LocationInfoByCharacter_IsAVariableOnlyOffMz(bool mz, bool blocks)
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, InEvent(Command(285, 1, 0, 2, 10, 10)));
+
+ ModReferences references = ReferenceMap.Scan(b.ChangeSet, [], dualWield: false, mz);
+
+ Assert.Equal(blocks, references.Blocks(IdKind.Variable, 10));
+ Assert.Equal(blocks, references.StateIds(IdKind.Variable, 5000).Contains(10));
+ }
+
+ [Theory]
+ [InlineData(3)]
+ [InlineData(-1)]
+ public void Scan_LocationInfoByAnyOtherDesignation_IsAVariableOnlyOffMz(int designation)
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, InEvent(Command(285, 1, 0, designation, 10, 10)));
+
+ Assert.True(ReferenceMap.Scan(b.ChangeSet, [], dualWield: false, mz: false).Blocks(IdKind.Variable, 10));
+ Assert.False(ReferenceMap.Scan(b.ChangeSet, [], dualWield: false, mz: true).Blocks(IdKind.Variable, 10));
+ }
+
+ [Fact]
+ public void ScanVanilla_Game_FindsNamesAndTableReferencesAndCounts()
+ {
+ var game = new Game(
+ (Map, EditMap(map => map["events"]![2]!["pages"]![0]!["list"]!.First!.AddBeforeSelf(Command(122, 4, 5, 0, 0, 1)))),
+ (CommonEvents, "[null,{\"id\":1,\"list\":[],\"name\":\"Uses 70 in its name\",\"switchId\":3,\"trigger\":0}]"),
+ (PluginList, VanillaPlugins));
+
+ VanillaStateIds vanilla = game.Scan();
+
+ Assert.Equal([1, 2, 3], vanilla.Switches);
+ Assert.Equal([1, 4, 5], vanilla.Variables);
+ Assert.Equal((3, 2), (vanilla.SwitchCount, vanilla.VariableCount));
+ Assert.Equal(vanilla.Switches, vanilla.Of(IdKind.Switch));
+ Assert.Empty(vanilla.Of(IdKind.Item));
+ }
+
+ [Theory]
+ [InlineData(RpgMakerEngine.MZ, "1")]
+ [InlineData(RpgMakerEngine.MV, "1,7,8")]
+ public void ScanVanilla_LocationInfoByCharacter_CountsOnlyOffMz(RpgMakerEngine engine, string variables)
+ {
+ var game = new Game((Map, EditMap(map => map["events"]![2]!["pages"]![0]!["list"]!.First!.AddBeforeSelf(Command(285, 1, 0, 2, 7, 8)))));
+
+ Assert.Equal(variables, string.Join(',', game.Scan(engine).Variables));
+ }
+
+ [Fact]
+ public void ScanVanilla_UnreadableDataFile_ReturnsNull()
+ {
+ var game = new Game((Troops, "[null,{"));
+
+ Assert.Null(VanillaStateIds.Scan(game.Files, RpgMakerEngine.MZ));
+ }
+
+ // ---- Planner and composer ----
+
+ [Fact]
+ public void Plan_TwoModsSharingASwitch_OffersTheLaterModAMoveAndTheOverlapDefaultsToAccept()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+
+ RemapPlan plan = Plan(game, a, b);
+ MergePlan merged = ComposeRemapped(plan, game, a, b);
+
+ Assert.Empty(plan.Remaps);
+ Assert.Equal(["b-oak|Switch|10>11"], plan.Offers.Select(Entry));
+ Collision overlap = Assert.Single(merged.Collisions);
+ Assert.Equal(CollisionKind.StateIdOverlap, overlap.Kind);
+ Assert.Equal((Key(SystemFile), "*", "switches[10]"), (overlap.Key.File, overlap.Key.Record, overlap.Path));
+ Assert.Equal(["a-tin", "b-oak"], overlap.ModIds);
+ Assert.False(overlap.Blocking);
+ Assert.Equal([ResolutionKind.Remap, ResolutionKind.Accept], overlap.Allowed);
+ CollisionOutcome outcome = Assert.Single(merged.Outcomes);
+ Assert.Equal((ResolutionSource.Default, ResolutionKind.Accept), (outcome.Source, outcome.Kind));
+ Assert.True(merged.IsDeployable);
+ Assert.DoesNotContain(merged.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapUnchecked);
+ Assert.Equal(["b-oak|Switch|10>11"], plan.OffersFor(overlap, "b-oak").Select(Entry));
+ Assert.Empty(plan.OffersFor(overlap, "a-tin"));
+ }
+
+ [Fact]
+ public void Plan_SharedVariable_IsAnOverlapOnItsName()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, InEvent(Command(122, 10, 10, 0, 0, 1)));
+ RemapMod b = game.Mod("b-oak", 1, InEvent(Command(103, 10, 2), 2));
+
+ RemapPlan plan = Plan(game, a, b);
+ Collision overlap = Assert.Single(ComposeRemapped(plan, game, a, b).Collisions);
+
+ Assert.Equal("variables[10]", overlap.Path);
+ Assert.Equal(["b-oak|Variable|10>11"], plan.OffersFor(overlap, "b-oak").Select(Entry));
+ }
+
+ [Fact]
+ public void Plan_OverlapStoredAsAccepted_KeepsTheChoiceAcrossModUpdates()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+ RemapMod newerB = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), InEvent(Command(121, 10, 10, 1), 2)));
+
+ RemapPlan plan = Plan(game, a, b);
+ Collision overlap = Assert.Single(ComposeRemapped(plan, game, a, b).Collisions);
+ RemapPlan newer = Plan(game, a, newerB);
+ Collision again = Assert.Single(ComposeRemapped(newer, game, a, newerB).Collisions);
+
+ Assert.Equal(overlap.Id, again.Id);
+ Assert.Equal(overlap.Fingerprint, again.Fingerprint);
+ List sets = [a.ChangeSet, newerB.ChangeSet];
+ MergePlan stored = Composer.Compose(sets, [new Resolution(overlap.Id, ResolutionKind.Accept, null, overlap.Fingerprint)], game.Bases, newer);
+ CollisionOutcome outcome = Assert.Single(stored.Outcomes);
+ Assert.Equal((ResolutionSource.Profile, ResolutionKind.Accept), (outcome.Source, outcome.Kind));
+ }
+
+ [Fact]
+ public void Plan_WithoutAVanillaScan_SharesNothing()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+
+ RemapPlan plan = Plan(game, [], [], null, a, b);
+
+ Assert.Empty(plan.Offers);
+ Assert.Empty(ComposeRemapped(plan, game, a, b).Collisions);
+ }
+
+ [Fact]
+ public void Plan_TwoModsUsingAVanillaSwitch_DoNotOverlap()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(1, 2));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(2, 2, 2));
+
+ RemapPlan plan = Plan(game, a, b);
+
+ Assert.Empty(ComposeRemapped(plan, game, a, b).Collisions);
+ Assert.Empty(plan.Offers);
+ }
+
+ [Fact]
+ public void Plan_DeployedMod_StaysAndTheOtherIsOffered()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+
+ RemapPlan plan = Plan(game, [], ["b-oak"], game.Scan(), a, b);
+
+ Assert.Equal(["a-tin|Switch|10>11"], plan.Offers.Select(Entry));
+ }
+
+ [Fact]
+ public void Plan_ModThatCannotMove_StaysAndTheOtherIsOffered()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, Both(UseSwitches(10, 10), Set(CommonEvents, "[1].name", "\"Flag 10\"")));
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), Set(Enemies, "[1].note", "\"\"")));
+ RemapMod c = game.Mod("c-elm", 2, UseSwitches(10, 10));
+
+ // a-tin names 10 only in a name (no free text there); b-oak names it in a note, so b-oak cannot move.
+ RemapPlan plan = Plan(game, a, b, c);
+
+ Assert.Equal(["a-tin|Switch|10>11", "c-elm|Switch|10>12"], plan.Offers.Select(Entry));
+ }
+
+ [Fact]
+ public void Plan_EveryModBlocked_OffersNothingButStillOverlaps()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, Both(UseSwitches(10, 10), Set(Enemies, "[1].note", "\"10\"")));
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), Set(Map, "events[2].note", "\"10!\"")));
+
+ RemapPlan plan = Plan(game, a, b);
+ Collision overlap = Assert.Single(ComposeRemapped(plan, game, a, b).Collisions);
+
+ Assert.Empty(plan.Offers);
+ Assert.Equal([ResolutionKind.Accept], overlap.Allowed);
+ }
+
+ [Fact]
+ public void Plan_SharedIdInARange_OffersTheWholeRangeOnConsecutiveIds()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(9, 11, 2), UseSwitches(11, 12, 2)));
+
+ RemapPlan plan = Plan(game, a, b);
+ Collision overlap = Assert.Single(ComposeRemapped(plan, game, a, b).Collisions);
+
+ string[] expected = ["b-oak|Switch|9>13", "b-oak|Switch|10>14", "b-oak|Switch|11>15", "b-oak|Switch|12>16"];
+ Assert.Equal(expected, plan.Offers.Select(Entry));
+ Assert.Equal(expected, plan.OffersFor(overlap, "b-oak").Select(Entry));
+ }
+
+ [Fact]
+ public void Plan_RangeHoldingAVanillaId_CannotMoveSoTheOtherModIsOffered()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(2, 10));
+
+ RemapPlan plan = Plan(game, a, b);
+
+ // b-oak would move first by priority, but its range holds vanilla's switch 2.
+ Assert.Equal(["a-tin|Switch|10>11"], plan.Offers.Select(Entry));
+ }
+
+ [Fact]
+ public void Plan_RangeHoldingAnIdTheModHasAnEntryFor_CannotMoveSoTheOtherModIsOffered()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 11));
+
+ RemapPlan plan = Plan(game, [new IdRemap("b-oak", IdKind.Switch, "", 11, 20)], [], game.Scan(), a, b);
+
+ Assert.Equal("a-tin", Assert.Single(plan.Offers).ModId);
+ }
+
+ [Fact]
+ public void Plan_RunThatWouldEndPastTheLimit_IsNotOfferedAndTakesNoIds()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 11));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 11));
+ RemapMod c = game.Mod("c-elm", 2, UseSwitches(20, 20));
+ RemapMod d = game.Mod("d-ash", 3, UseSwitches(20, 20));
+ var vanilla = new VanillaStateIds([1, 2], [1], 5000, 2);
+
+ RemapPlan plan = Plan(game, [], [], vanilla, a, b, c, d);
+
+ // The floor is 4999: b-oak's pair would end at 5001, so only d-ash's single id fits, at 5000.
+ Assert.Equal(["d-ash|Switch|20>5000"], plan.Offers.Select(Entry));
+ }
+
+ [Fact]
+ public void Plan_TwoSeparateSharedIds_EachOverlapListsOnlyItsOwnOffer()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, Both(UseSwitches(10, 10), UseSwitches(20, 20, 2)));
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), UseSwitches(20, 20, 2)));
+
+ RemapPlan plan = Plan(game, a, b);
+ MergePlan merged = ComposeRemapped(plan, game, a, b);
+
+ Collision twenty = Assert.Single(merged.Collisions, item => item.Path == "switches[20]");
+ Assert.Equal(["b-oak|Switch|20>22"], plan.OffersFor(twenty, "b-oak").Select(Entry));
+ }
+
+ [Fact]
+ public void Plan_EarlierModWithAMovableRange_StaysAndTheLaterIsOffered()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(5, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+
+ RemapPlan plan = Plan(game, a, b);
+
+ Assert.Equal(["b-oak|Switch|10>11"], plan.Offers.Select(Entry));
+ Assert.Single(plan.SharedStateIds);
+ }
+
+ [Fact]
+ public void Plan_OneModSharingSeveralIdsOfOneRange_GetsOneOffer()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 11));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 12));
+
+ RemapPlan plan = Plan(game, a, b);
+
+ Assert.Equal(["b-oak|Switch|10>13", "b-oak|Switch|11>14", "b-oak|Switch|12>15"], plan.Offers.Select(Entry));
+ Assert.Equal(2, plan.SharedStateIds.Count);
+ }
+
+ [Fact]
+ public void Plan_TargetsPastTheLimit_OfferNothing()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 11));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 11));
+ RemapMod c = game.Mod("c-elm", 2, UseSwitches(20, 20));
+ RemapMod d = game.Mod("d-ash", 3, UseSwitches(20, 20));
+ var vanilla = new VanillaStateIds([1, 2], [1], 4999, 2);
+
+ RemapPlan plan = Plan(game, [], [], vanilla, a, b, c, d);
+
+ // The floor is 4998: b-oak's pair takes 4999 and 5000, so d-ash's single id would pass the limit.
+ Assert.Equal(["b-oak|Switch|10>4999", "b-oak|Switch|11>5000"], plan.Offers.Select(Entry));
+ Assert.Equal(3, plan.SharedStateIds.Count);
+ }
+
+ [Fact]
+ public void Plan_DisabledModsIds_AreNeverATarget()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+ RemapMod off = game.Mod("c-elm", 2, UseSwitches(11, 11)) with { Enabled = false };
+
+ RemapPlan plan = Plan(game, a, b, off);
+
+ Assert.Equal(["b-oak|Switch|10>12"], plan.Offers.Select(Entry));
+ }
+
+ [Fact]
+ public void Plan_DisabledMod_FormsNoOverlap()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod off = game.Mod("b-oak", 1, UseSwitches(10, 10)) with { Enabled = false };
+
+ RemapPlan plan = Plan(game, a, off);
+
+ Assert.Empty(plan.SharedStateIds);
+ Assert.Empty(plan.Offers);
+ Assert.Empty(ComposeRemapped(plan, game, a).Collisions);
+ }
+
+ [Fact]
+ public void Plan_PluginNumber_StillOffersAndWarnsOnce()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10), "$gameSwitches.value(10)");
+
+ RemapPlan plan = Plan(game, a, b);
+ MergePlan merged = ComposeRemapped(plan, game, a, b);
+
+ Assert.Equal(["b-oak|Switch|10>11"], plan.Offers.Select(Entry));
+ OperationDiagnostic warning = Assert.Single(merged.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapUnchecked);
+ Assert.Equal("b-oak", warning.Subject);
+ }
+
+ [Fact]
+ public void Plan_InputOrder_DoesNotChangeThePlan()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 12));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(11, 11));
+ RemapMod c = game.Mod("c-elm", 2, UseSwitches(12, 14));
+
+ RemapPlan forward = Plan(game, a, b, c);
+ RemapPlan backward = Plan(game, c, b, a);
+ MergePlan forwardMerge = ComposeRemapped(forward, game, a, b, c);
+ MergePlan backwardMerge = ComposeRemapped(backward, game, c, b, a);
+
+ Assert.Equal(forward.Offers, backward.Offers);
+ Assert.Equal(forward.SharedStateIds.Select(item => (item.Kind, item.Id, string.Join(',', item.ModIds))),
+ backward.SharedStateIds.Select(item => (item.Kind, item.Id, string.Join(',', item.ModIds))));
+ Assert.Equal(forward.OfferGroups.Select(group => string.Join(',', group.Select(Entry))),
+ backward.OfferGroups.Select(group => string.Join(',', group.Select(Entry))));
+ Assert.Equal(forward.Diagnostics, backward.Diagnostics);
+ Assert.Equal(forwardMerge.Diagnostics, backwardMerge.Diagnostics);
+ Assert.Equal(forwardMerge.MergeHash, backwardMerge.MergeHash);
+ }
+
+ // ---- Recorded entries ----
+
+ [Fact]
+ public void Plan_RecordedStateEntry_AppliesAndEndsTheOverlap()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10, 2));
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), a, b);
+ MergePlan merged = ComposeRemapped(plan, game, a, b);
+
+ Assert.Equal(["b-oak|Switch|10>11"], plan.Remaps.Select(Entry));
+ Assert.Empty(plan.NewEntries);
+ Assert.Empty(plan.Offers);
+ Assert.Empty(merged.Collisions);
+ Assert.Contains(merged.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapApplied);
+ }
+
+ [Fact]
+ public void Plan_RecordedStateEntryTheModNoLongerNames_IsInactive()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(12, 12));
+
+ Assert.Empty(Plan(game, [SwitchTen], [], game.Scan(), b).Remaps);
+ }
+
+ [Fact]
+ public void Plan_RecordedStateEntryWhoseTargetVanillaNowUses_IsTakenAndPlannedAgain()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+ var vanilla = new VanillaStateIds([1, 2, 11], [1], 3, 2);
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], vanilla, a, b);
+
+ Assert.Empty(plan.Remaps);
+ Assert.Contains(plan.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapTargetTaken);
+ Assert.Equal(["b-oak|Switch|10>12"], plan.Offers.Select(Entry));
+ }
+
+ [Fact]
+ public void Plan_RecordedStateEntryNamedOnlyInFreeText_IsInactive()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Set(Enemies, "[1].note", "\"\""));
+
+ Assert.Empty(Plan(game, [SwitchTen], [], game.Scan(), b).Remaps);
+ }
+
+ [Theory]
+ [InlineData(0, 11)]
+ [InlineData(10, 5001)]
+ public void Plan_DamagedStateEntry_IsIgnored(int fromId, int toId)
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(InEvent(Command(111, 0, 0, 0)), UseSwitches(10, 10, 2)));
+
+ RemapPlan plan = Plan(game, [new IdRemap("b-oak", IdKind.Switch, "", fromId, toId)], [], game.Scan(), b);
+
+ Assert.Empty(plan.Remaps);
+ Assert.Empty(plan.Diagnostics);
+ }
+
+ [Theory]
+ [InlineData(RpgMakerEngine.MV, 1)]
+ [InlineData(RpgMakerEngine.MZ, 0)]
+ public void Plan_EntryNamedOnlyInALocationRowByCharacter_StaysInForceOnlyOffMz(RpgMakerEngine engine, int remaps)
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, InEvent(Command(285, 1, 0, 2, 10, 10)));
+
+ RemapPlan plan = IdRemapPlanner.Plan([b], [VariableTen], [], game.Bases, engine, game.Scan(engine));
+
+ Assert.Equal(remaps, plan.Remaps.Count);
+ }
+
+ [Fact]
+ public void Plan_EntryInForceWhoseOldIdVanillaNowUses_StillClaimsItsTarget()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+ RemapMod c = game.Mod("c-elm", 2, UseSwitches(11, 11, 2));
+ var vanilla = new VanillaStateIds([1, 2, 10], [1], 10, 2);
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], vanilla, b, c);
+
+ Assert.Equal(["b-oak|Switch|10>11"], plan.Remaps.Select(Entry));
+ SharedStateId shared = Assert.Single(plan.SharedStateIds);
+ Assert.Equal((11, "b-oak,c-elm"), (shared.Id, string.Join(',', shared.ModIds)));
+ Assert.Equal(["c-elm|Switch|11>12"], plan.Offers.Select(Entry));
+ }
+
+ [Fact]
+ public void Plan_RangeAnEntryLeavesBehind_StillSharesTheOldId()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(9, 12, 2));
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), a, b);
+
+ SharedStateId shared = Assert.Single(plan.SharedStateIds);
+ Assert.Equal((10, "a-tin,b-oak"), (shared.Id, string.Join(',', shared.ModIds)));
+ Assert.Equal("a-tin", Assert.Single(plan.Offers).ModId);
+ }
+
+ [Fact]
+ public void Plan_NewIdOnTheModsOwnTarget_MovesAsANewEntry()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), UseSwitches(11, 11, 2)));
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), b);
+ ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, plan.Remaps);
+
+ Assert.Equal(["b-oak|Switch|10>11", "b-oak|Switch|11>12"], plan.Remaps.Select(Entry));
+ Assert.Equal(["b-oak|Switch|11>12"], plan.NewEntries.Select(Entry));
+ Assert.Empty(plan.SharedStateIds);
+ Assert.Equal(("[11,11,0]", "[12,12,0]"), (Flat(FirstCommand(moved)["parameters"]), Flat(FirstCommand(moved, 2)["parameters"])));
+ }
+
+ [Fact]
+ public void Plan_NewRangeOnTheModsOwnTarget_MovesWhole()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), UseSwitches(11, 12, 2)));
+ RemapMod c = game.Mod("c-elm", 2, UseSwitches(12, 12));
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), b, c);
+
+ // Once b-oak's range moves on, it no longer shares 12 with c-elm.
+ Assert.Equal(["b-oak|Switch|11>13", "b-oak|Switch|12>14"], plan.NewEntries.Select(Entry));
+ Assert.Empty(plan.SharedStateIds);
+ }
+
+ [Fact]
+ public void Plan_NewIdOnTheModsOwnTargetThatCannotMove_StaysAndWarns()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), UseSwitches(11, 11, 2), Set(Enemies, "[1].note", "\"\"")));
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), b);
+
+ Assert.Empty(plan.NewEntries);
+ OperationDiagnostic warning = Assert.Single(plan.Diagnostics);
+ Assert.Equal((DiagnosticCodes.RulesRemapStaleReference, "b-oak"), (warning.Code, warning.Subject));
+ }
+
+ [Fact]
+ public void Plan_NewIdOnTheModsOwnTargetWithNoFreeIdLeft_StaysAndWarns()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), UseSwitches(5000, 5000, 2)));
+
+ RemapPlan plan = Plan(game, [SwitchTen with { ToId = 5000 }], [], game.Scan(), b);
+
+ Assert.Empty(plan.NewEntries);
+ Assert.Equal((DiagnosticCodes.RulesRemapStaleReference, "b-oak"), (Assert.Single(plan.Diagnostics).Code, plan.Diagnostics[0].Subject));
+ }
+
+ [Fact]
+ public void Plan_NewRangeHoldingTwoOwnTargets_MovesOnce()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(9, 9), UseSwitches(10, 10, 2), UseSwitches(11, 12)));
+ IdRemap[] recorded = [new("b-oak", IdKind.Switch, "", 9, 12), SwitchTen];
+
+ RemapPlan plan = Plan(game, recorded, [], game.Scan(), b);
+
+ Assert.Equal(["b-oak|Switch|11>13", "b-oak|Switch|12>14"], plan.NewEntries.Select(Entry));
+ }
+
+ [Fact]
+ public void Plan_NewEntryOnTheModsOwnTargetOnceRecorded_ChangesNothingMore()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), UseSwitches(11, 11, 2)));
+ IdRemap[] recorded = [SwitchTen, new("b-oak", IdKind.Switch, "", 11, 12)];
+
+ RemapPlan plan = Plan(game, recorded, ["b-oak"], game.Scan(), b);
+
+ Assert.Equal(["b-oak|Switch|10>11", "b-oak|Switch|11>12"], plan.Remaps.Select(Entry));
+ Assert.Empty(plan.NewEntries);
+ Assert.Empty(plan.Diagnostics);
+ }
+
+ [Fact]
+ public void Plan_NewIdOnTheModsOwnTargetThatAnotherModAlsoUses_StillSharesItWithTheEntry()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), UseSwitches(11, 11, 2)));
+ RemapMod c = game.Mod("c-elm", 2, UseSwitches(11, 11));
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), b, c);
+
+ // b-oak's new 11 moves on; its entry 10>11 still meets c-elm's 11.
+ Assert.Equal(["b-oak|Switch|11>12"], plan.NewEntries.Select(Entry));
+ SharedStateId shared = Assert.Single(plan.SharedStateIds);
+ Assert.Equal((11, "b-oak,c-elm"), (shared.Id, string.Join(',', shared.ModIds)));
+ }
+
+ [Fact]
+ public void Compose_NewNameOnTheModsOwnTargetThatCannotMove_KeepsTheNameInTheModsFile()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(NameSwitch(10, "Old"), NameSwitch(11, "New"), UseSwitches(10, 10), UseSwitches(11, 11, 2), Set(Enemies, "[1].note", "\"\"")));
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), b);
+ MergePlan merged = ComposeRemapped(plan, game, b);
+
+ Assert.Empty(plan.NewEntries);
+ Assert.Empty(merged.Collisions);
+ Assert.Equal("\"New\"", Flat(SwitchNames(merged, game)[11]));
+ }
+
+ [Fact]
+ public void Compose_MovedNameOverPaddingInTheModsFile_KeepsTheMovedName()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(NameSwitch(10, "Old"), NameSwitch(12, "Far"), UseSwitches(10, 10), UseSwitches(12, 12, 2)));
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), b);
+ MergePlan merged = ComposeRemapped(plan, game, b);
+
+ Assert.Empty(plan.NewEntries);
+ Assert.Empty(merged.Collisions);
+ Assert.Equal(("\"Old\"", "\"Far\""), (Flat(SwitchNames(merged, game)[11]), Flat(SwitchNames(merged, game)[12])));
+ }
+
+ [Fact]
+ public void Compose_NewIdOnTheModsOwnTargetThatAPluginNames_IsOfferedOnAnOverlapOfTheModAlone()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(NameSwitch(10, "Old"), NameSwitch(11, "New"), UseSwitches(10, 10), UseSwitches(11, 11, 2)), "$gameSwitches.value(11)");
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), b);
+ MergePlan merged = ComposeRemapped(plan, game, b);
+
+ Assert.Empty(plan.NewEntries);
+ Assert.Equal(["b-oak|Switch|11>12"], plan.Offers.Select(Entry));
+ Assert.Equal(DiagnosticCodes.RulesRemapUnchecked, Assert.Single(plan.Diagnostics).Code);
+ Collision overlap = Assert.Single(merged.Collisions);
+ Assert.Equal((CollisionKind.StateIdOverlap, "switches[11]", "b-oak"), (overlap.Kind, overlap.Path, string.Join(',', overlap.ModIds)));
+ Assert.Contains(ResolutionKind.Remap, overlap.Allowed);
+ Assert.Equal("\"New\"", Flat(SwitchNames(merged, game)[11]));
+
+ // Taking the offer moves the new id on, as when no plugin names it.
+ RemapPlan moved = Plan(game, [SwitchTen, .. plan.OffersFor(overlap, "b-oak")], [], game.Scan(), b);
+ MergePlan after = ComposeRemapped(moved, game, b);
+ Assert.Empty(after.Collisions);
+ Assert.Equal(("\"Old\"", "\"New\""), (Flat(SwitchNames(after, game)[11]), Flat(SwitchNames(after, game)[12])));
+ }
+
+ [Fact]
+ public void Compose_NewRangeHoldingTwoOwnTargetsThatAPluginNames_IsOfferedOnceAndWhole()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(9, 9), UseSwitches(10, 10, 2), UseSwitches(11, 12)), "$gameSwitches.value(12)");
+ IdRemap[] recorded = [new("b-oak", IdKind.Switch, "", 9, 12), SwitchTen];
+
+ RemapPlan plan = Plan(game, recorded, [], game.Scan(), b);
+ Collision overlap = Assert.Single(ComposeRemapped(plan, game, b).Collisions);
+
+ Assert.Empty(plan.NewEntries);
+ Assert.Equal((CollisionKind.StateIdOverlap, "switches[11]"), (overlap.Kind, overlap.Path));
+ Assert.Equal(["b-oak|Switch|11>13", "b-oak|Switch|12>14"], plan.OffersFor(overlap, "b-oak").Select(Entry));
+ Assert.Equal(2, plan.Offers.Count);
+ }
+
+ [Fact]
+ public void Plan_NewIdOnTheModsOwnTargetThatAPluginAndAnotherModName_IsOfferedOnTheSharedOverlap()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(UseSwitches(10, 10), UseSwitches(11, 11, 2)), "$gameSwitches.value(11)");
+ RemapMod c = game.Mod("c-elm", 2, UseSwitches(11, 11));
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), b, c);
+
+ SharedStateId shared = Assert.Single(plan.SharedStateIds);
+ Assert.Equal((11, "b-oak,c-elm"), (shared.Id, string.Join(',', shared.ModIds)));
+ Assert.Contains("b-oak|Switch|11>12", plan.Offers.Select(Entry));
+ Assert.Empty(plan.NewEntries);
+ }
+
+ [Fact]
+ public void Compose_NewNameOnTheModsOwnTarget_MovesOnWithItsId()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, Both(NameSwitch(10, "Old"), NameSwitch(11, "New"), UseSwitches(10, 10), UseSwitches(11, 11, 2)));
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), b);
+ MergePlan merged = ComposeRemapped(plan, game, b);
+
+ Assert.Empty(merged.Collisions);
+ Assert.Equal("[\"\",\"Door\",\"Lever\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"Old\",\"New\"]", Flat(SwitchNames(merged, game)));
+ }
+
+ [Fact]
+ public void Plan_RecordedEntryThatSplitsARange_StillAppliesAndWarns()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(9, 12));
+
+ RemapPlan plan = Plan(game, [SwitchTen], [], game.Scan(), b);
+
+ Assert.Equal(["b-oak|Switch|10>11"], plan.Remaps.Select(Entry));
+ Assert.Contains(plan.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapStaleReference);
+ }
+
+ [Fact]
+ public void Plan_RecordedEntriesMovingARangeWhole_DoNotWarn()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(9, 10));
+ IdRemap[] recorded = [new("b-oak", IdKind.Switch, "", 9, 20), new("b-oak", IdKind.Switch, "", 10, 21)];
+
+ RemapPlan plan = Plan(game, recorded, [], game.Scan(), b);
+
+ Assert.Equal(2, plan.Remaps.Count);
+ Assert.DoesNotContain(plan.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapStaleReference);
+ }
+
+ [Fact]
+ public void Plan_RecordedEntriesMovingARangeOutOfOrder_Warn()
+ {
+ var game = new Game();
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(9, 10));
+ IdRemap[] recorded = [new("b-oak", IdKind.Switch, "", 9, 20), new("b-oak", IdKind.Switch, "", 10, 22)];
+
+ RemapPlan plan = Plan(game, recorded, [], game.Scan(), b);
+
+ Assert.Equal(2, plan.Remaps.Count);
+ Assert.Contains(plan.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapStaleReference);
+ }
+
+ [Fact]
+ public void Plan_RecordedTargets_AreNeverOfferedAgain()
+ {
+ var game = new Game();
+ RemapMod a = game.Mod("a-tin", 0, UseSwitches(10, 10));
+ RemapMod b = game.Mod("b-oak", 1, UseSwitches(10, 10));
+ RemapMod c = game.Mod("c-elm", 2, UseSwitches(10, 10));
+
+ RemapPlan plan = Plan(game, [new IdRemap("c-elm", IdKind.Switch, "", 10, 30)], [], game.Scan(), a, b, c);
+
+ Assert.Equal(["b-oak|Switch|10>31"], plan.Offers.Select(Entry));
+ }
+}
diff --git a/RPGModder.Tests/Merge/IdRemapTests.cs b/RPGModder.Tests/Merge/IdRemapTests.cs
index 97d6fff..1cc1c7c 100644
--- a/RPGModder.Tests/Merge/IdRemapTests.cs
+++ b/RPGModder.Tests/Merge/IdRemapTests.cs
@@ -490,7 +490,9 @@ private static string EditMapText(string text, Action edit)
public static TheoryData MapsByVariable => new()
{
"[201,1,5,6,7,0,0]",
- "[202,0,1,5,6,7]"
+ "[202,0,1,5,6,7]",
+ "[201,2,5,6,7,0,0]",
+ "[202,0,-1,5,6,7]"
};
[Theory]
diff --git a/RPGModder.Tests/Support/TestInterpreter.cs b/RPGModder.Tests/Support/TestInterpreter.cs
new file mode 100644
index 0000000..760ab4a
--- /dev/null
+++ b/RPGModder.Tests/Support/TestInterpreter.cs
@@ -0,0 +1,53 @@
+using Newtonsoft.Json.Linq;
+
+namespace RPGModder.Tests.Support;
+
+///
+/// The load step of RPG Maker's DataManager for one database file, written from its behavior in the MV and MZ
+/// core scripts (TST-15). The game parses the file as strict JSON, then reads the note tags of every entry that is
+/// an object; reading tags cannot fail. Every later lookup takes a record by its index, so this also checks what the
+/// editor writes: entry 0 is null and every other entry is null or an object whose id is its
+/// index. It runs no game code.
+///
+internal static class TestInterpreter
+{
+ /// Returns the records of , or throws naming the first problem.
+ public static JArray LoadDatabase(string file, string text)
+ {
+ try
+ {
+ // Newtonsoft accepts comments, NaN and single quotes; JSON.parse in the game does not.
+ System.Text.Json.JsonDocument.Parse(text).Dispose();
+ }
+ catch (System.Text.Json.JsonException error)
+ {
+ throw new InvalidDataException($"{file}: not JSON the game can parse ({error.Message}).", error);
+ }
+
+ if (JToken.Parse(text) is not JArray records)
+ {
+ throw new InvalidDataException($"{file}: the root is not a list.");
+ }
+
+ if (records.Count == 0 || records[0].Type != JTokenType.Null)
+ {
+ throw new InvalidDataException($"{file}: entry 0 is not null.");
+ }
+
+ for (int index = 1; index < records.Count; index++)
+ {
+ JToken entry = records[index];
+ if (entry.Type == JTokenType.Null)
+ {
+ continue;
+ }
+
+ if (entry is not JObject record || record["id"] is not JValue { Type: JTokenType.Integer } id || id.Value() != index)
+ {
+ throw new InvalidDataException($"{file}: entry {index} is not a record whose id is {index}.");
+ }
+ }
+
+ return records;
+ }
+}