diff --git a/RPGModder.Core/Merge/AddedIdIndex.cs b/RPGModder.Core/Merge/AddedIdIndex.cs
index 7c52c94..cf62088 100644
--- a/RPGModder.Core/Merge/AddedIdIndex.cs
+++ b/RPGModder.Core/Merge/AddedIdIndex.cs
@@ -5,14 +5,17 @@ namespace RPGModder.Core.Merge;
///
/// The ids a change set adds, by kind and scope (GR-R2, GR-R3). An op the builder writes for a record vanilla does
/// not have is the only kind of added id: a map event is an AddRecord on event:n of a vanilla map; a
-/// map is a whole new MapNNN.json, its MapInfos record, or both. Step 1 lists these two kinds only.
+/// map is a whole new MapNNN.json, its MapInfos record, or both; a database record is an
+/// AddRecord on id:n of its file.
///
internal static class AddedIdIndex
{
public static IReadOnlyList Of(ModChangeSet changeSet)
{
var events = new List();
+ var records = new List();
var maps = new SortedDictionary();
+ var filler = new FillerTest(changeSet);
foreach (ChangeOp op in changeSet.Ops)
{
if (op.Kind != ChangeKind.AddRecord || op.Path.Length != 0 || op.Value is null)
@@ -32,9 +35,14 @@ public static IReadOnlyList Of(ModChangeSet changeSet)
{
events.Add(new AddedId(IdKind.MapEvent, op.Key.File, eventId, op.Value));
}
+ else if (RpgDataSchema.DatabaseKindOf(op.Key.File) is { } kind && RecordKey.TryGetIndex(op.Key.Record, out int recordId) && recordId > 0)
+ {
+ records.Add(new AddedId(kind, "", recordId, op.Value, filler.IsFiller(op.Key, op.Value)));
+ }
}
var result = new List(events);
+ result.AddRange(records);
foreach ((int id, (JToken? file, JToken? info)) in maps)
{
// Both halves are the content, cloned so no op gains a parent; two mods that add one map with one tree entry are one map (GR-R3).
@@ -44,12 +52,18 @@ public static IReadOnlyList Of(ModChangeSet changeSet)
return result;
}
- /// True when the change set still adds 's old id; otherwise the entry is inactive (GR-R12).
+ ///
+ /// True when the change set still adds 's old id, and not as filler; otherwise the entry
+ /// is inactive (GR-R12, GR-R7).
+ ///
public static bool IsActive(IdRemap remap, IReadOnlyList added)
{
- return added.Any(item => item.Kind == remap.Kind && item.Scope == remap.Scope && item.Id == remap.FromId);
+ return added.Any(item => item.Kind == remap.Kind && item.Scope == remap.Scope && item.Id == remap.FromId && !item.IsFiller);
}
}
-/// One added id and the content that decides whether two mods add the same thing.
-internal sealed record AddedId(IdKind Kind, string Scope, int Id, JToken Content);
+///
+/// One added id and the content that decides whether two mods add the same thing. Filler (GR-R7) holds its id but
+/// never claims it.
+///
+internal sealed record AddedId(IdKind Kind, string Scope, int Id, JToken Content, bool IsFiller = false);
diff --git a/RPGModder.Core/Merge/BlankRecords.cs b/RPGModder.Core/Merge/BlankRecords.cs
new file mode 100644
index 0000000..4288038
--- /dev/null
+++ b/RPGModder.Core/Merge/BlankRecords.cs
@@ -0,0 +1,142 @@
+using Newtonsoft.Json.Linq;
+using RPGModder.Core.Services;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The record the editor writes when a database maximum is raised (GR-R8), with id 0. The MZ shapes are the
+/// records the MZ 1.10.0 editor wrote into a default project; the MV shapes are the MZ ones without the fields MV's
+/// data format (json_docs.js in the MV core script) does not list, and MV's own animation fields. An unknown
+/// engine gets the MV shapes, which both engines read.
+///
+internal static class BlankRecords
+{
+ /// A field of skills and states only the MZ editor writes; the game never reads it.
+ private const string MessageTypeProperty = "messageType";
+
+ private const string ParamsProperty = "params";
+
+ private static readonly Dictionary MzShapes = new(StringComparer.Ordinal)
+ {
+ ["actors.json"] =
+ """{"id":0,"battlerName":"","characterIndex":0,"characterName":"","classId":1,"equips":[0,0,0,0,0],"faceIndex":0,"faceName":"","traits":[],"initialLevel":1,"maxLevel":99,"name":"","nickname":"","note":"","profile":""}""",
+ ["classes.json"] =
+ """{"id":0,"expParams":[30,20,30,30],"traits":[{"code":23,"dataId":0,"value":1},{"code":22,"dataId":0,"value":0.95},{"code":22,"dataId":1,"value":0.05},{"code":22,"dataId":2,"value":0.04},{"code":41,"dataId":1,"value":0},{"code":51,"dataId":1,"value":0},{"code":52,"dataId":1,"value":0}],"learnings":[],"name":"","note":"","params":[]}""",
+ ["skills.json"] =
+ """{"id":0,"animationId":0,"damage":{"critical":false,"elementId":0,"formula":"0","type":0,"variance":20},"description":"","effects":[],"hitType":0,"iconIndex":0,"message1":"","message2":"","mpCost":0,"name":"","note":"","occasion":0,"repeats":1,"requiredWtypeId1":0,"requiredWtypeId2":0,"scope":1,"speed":0,"stypeId":1,"successRate":100,"tpCost":0,"tpGain":0,"messageType":1}""",
+ ["items.json"] =
+ """{"id":0,"animationId":0,"consumable":true,"damage":{"critical":false,"elementId":0,"formula":"0","type":0,"variance":20},"description":"","effects":[],"hitType":0,"iconIndex":0,"itypeId":1,"name":"","note":"","occasion":0,"price":0,"repeats":1,"scope":7,"speed":0,"successRate":100,"tpGain":0}""",
+ ["weapons.json"] =
+ """{"id":0,"animationId":0,"description":"","etypeId":1,"traits":[{"code":31,"dataId":1,"value":0},{"code":22,"dataId":0,"value":0}],"iconIndex":0,"name":"","note":"","params":[0,0,0,0,0,0,0,0],"price":0,"wtypeId":0}""",
+ ["armors.json"] =
+ """{"id":0,"atypeId":0,"description":"","etypeId":2,"traits":[{"code":22,"dataId":1,"value":0}],"iconIndex":0,"name":"","note":"","params":[0,0,0,0,0,0,0,0],"price":0}""",
+ ["enemies.json"] =
+ """{"id":0,"actions":[{"conditionParam1":0,"conditionParam2":0,"conditionType":0,"rating":5,"skillId":1}],"battlerHue":0,"battlerName":"","dropItems":[{"dataId":1,"denominator":1,"kind":0},{"dataId":1,"denominator":1,"kind":0},{"dataId":1,"denominator":1,"kind":0}],"exp":0,"traits":[{"code":22,"dataId":0,"value":0.95},{"code":22,"dataId":1,"value":0.05},{"code":31,"dataId":1,"value":0}],"gold":0,"name":"","note":"","params":[100,0,10,10,10,10,10,10]}""",
+ ["troops.json"] =
+ """{"id":0,"members":[],"name":"","pages":[{"conditions":{"actorHp":50,"actorId":1,"actorValid":false,"enemyHp":50,"enemyIndex":0,"enemyValid":false,"switchId":1,"switchValid":false,"turnA":0,"turnB":0,"turnEnding":false,"turnValid":false},"list":[{"code":0,"indent":0,"parameters":[]}],"span":0}]}""",
+ ["states.json"] =
+ """{"id":0,"autoRemovalTiming":0,"chanceByDamage":100,"iconIndex":0,"maxTurns":1,"message1":"","message2":"","message3":"","message4":"","minTurns":1,"motion":0,"name":"","note":"","overlay":0,"priority":50,"removeAtBattleEnd":false,"removeByDamage":false,"removeByRestriction":false,"removeByWalking":false,"restriction":0,"stepsToRemove":100,"traits":[],"messageType":1}""",
+ ["animations.json"] =
+ """{"id":0,"displayType":0,"effectName":"","flashTimings":[],"name":"","offsetX":0,"offsetY":0,"rotation":{"x":0,"y":0,"z":0},"scale":100,"soundTimings":[],"speed":100,"alignBottom":false}""",
+ ["tilesets.json"] =
+ """{"id":0,"flags":[16],"mode":1,"name":"","note":"","tilesetNames":["","","","","","","","",""]}""",
+ ["commonevents.json"] =
+ """{"id":0,"list":[{"code":0,"indent":0,"parameters":[]}],"name":"","switchId":1,"trigger":0}"""
+ };
+
+ ///
+ /// The MV animation format: two sprite sheets, a frame list and timings. One empty frame, so the game can play
+ /// the blank without reading past the list; position 1 is the center. Not pinned against an MV editor.
+ ///
+ private const string MvAnimation =
+ """{"id":0,"animation1Hue":0,"animation1Name":"","animation2Hue":0,"animation2Name":"","frames":[[]],"name":"","position":1,"timings":[]}""";
+
+ /// The eight parameter curves of a blank class, levels 0 to 99, as the MZ editor writes them.
+ private static readonly int[][] ClassCurves =
+ [
+ [
+ 1, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350,
+ 1400, 1450, 1500, 1550, 1600, 1650, 1700, 1750, 1800, 1850, 1900, 1950, 2000, 2050, 2100, 2150, 2200, 2250, 2300, 2350,
+ 2400, 2450, 2500, 2550, 2600, 2650, 2700, 2750, 2800, 2850, 2900, 2950, 3000, 3050, 3100, 3150, 3200, 3250, 3300, 3350,
+ 3400, 3450, 3500, 3550, 3600, 3650, 3700, 3750, 3800, 3850, 3900, 3950, 4000, 4050, 4100, 4150, 4200, 4250, 4300, 4350,
+ 4400, 4450, 4500, 4550, 4600, 4650, 4700, 4750, 4800, 4850, 4900, 4950, 5000, 5050, 5100, 5150, 5200, 5250, 5300, 5350
+ ],
+ [
+ 0, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270,
+ 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, 420, 430, 440, 450, 460, 470,
+ 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640, 650, 660, 670,
+ 680, 690, 700, 710, 720, 730, 740, 750, 760, 770, 780, 790, 800, 810, 820, 830, 840, 850, 860, 870,
+ 880, 890, 900, 910, 920, 930, 940, 950, 960, 970, 980, 990, 1000, 1010, 1020, 1030, 1040, 1050, 1060, 1070
+ ],
+ [
+ 1, 16, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 30, 31, 33, 34, 35, 36, 38, 39,
+ 40, 41, 43, 44, 45, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 59, 60, 61, 63, 64,
+ 65, 66, 68, 69, 70, 71, 73, 74, 75, 76, 77, 79, 80, 81, 82, 84, 85, 86, 87, 89,
+ 90, 91, 92, 94, 95, 96, 97, 99, 100, 101, 102, 104, 105, 106, 107, 109, 110, 111, 112, 114,
+ 115, 116, 117, 119, 120, 121, 122, 124, 125, 126, 127, 129, 130, 131, 132, 134, 135, 136, 137, 138
+ ],
+ [
+ 0, 16, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 30, 31, 33, 34, 35, 36, 38, 39,
+ 40, 41, 43, 44, 45, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 59, 60, 61, 63, 64,
+ 65, 66, 68, 69, 70, 71, 73, 74, 75, 76, 77, 79, 80, 81, 82, 84, 85, 86, 87, 89,
+ 90, 91, 92, 94, 95, 96, 97, 99, 100, 101, 102, 104, 105, 106, 107, 109, 110, 111, 112, 114,
+ 115, 116, 117, 119, 120, 121, 122, 124, 125, 126, 127, 129, 130, 131, 132, 134, 135, 136, 137, 138
+ ],
+ [
+ 0, 16, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 30, 31, 33, 34, 35, 36, 38, 39,
+ 40, 41, 43, 44, 45, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 59, 60, 61, 63, 64,
+ 65, 66, 68, 69, 70, 71, 73, 74, 75, 76, 77, 79, 80, 81, 82, 84, 85, 86, 87, 89,
+ 90, 91, 92, 94, 95, 96, 97, 99, 100, 101, 102, 104, 105, 106, 107, 109, 110, 111, 112, 114,
+ 115, 116, 117, 119, 120, 121, 122, 124, 125, 126, 127, 129, 130, 131, 132, 134, 135, 136, 137, 138
+ ],
+ [
+ 0, 16, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 30, 31, 33, 34, 35, 36, 38, 39,
+ 40, 41, 43, 44, 45, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 59, 60, 61, 63, 64,
+ 65, 66, 68, 69, 70, 71, 73, 74, 75, 76, 77, 79, 80, 81, 82, 84, 85, 86, 87, 89,
+ 90, 91, 92, 94, 95, 96, 97, 99, 100, 101, 102, 104, 105, 106, 107, 109, 110, 111, 112, 114,
+ 115, 116, 117, 119, 120, 121, 122, 124, 125, 126, 127, 129, 130, 131, 132, 134, 135, 136, 137, 138
+ ],
+ [
+ 0, 32, 35, 37, 40, 42, 45, 47, 50, 52, 55, 57, 60, 62, 65, 67, 70, 72, 75, 77,
+ 80, 82, 85, 87, 90, 92, 95, 97, 100, 102, 105, 107, 110, 112, 115, 117, 120, 122, 125, 127,
+ 130, 132, 135, 137, 140, 142, 145, 147, 150, 152, 155, 157, 160, 162, 165, 167, 170, 172, 175, 177,
+ 180, 182, 185, 187, 190, 192, 195, 197, 200, 202, 205, 207, 210, 212, 215, 217, 220, 222, 225, 227,
+ 230, 232, 235, 237, 240, 242, 245, 247, 250, 252, 255, 257, 260, 262, 265, 267, 270, 272, 275, 277
+ ],
+ [
+ 0, 32, 35, 37, 40, 42, 45, 47, 50, 52, 55, 57, 60, 62, 65, 67, 70, 72, 75, 77,
+ 80, 82, 85, 87, 90, 92, 95, 97, 100, 102, 105, 107, 110, 112, 115, 117, 120, 122, 125, 127,
+ 130, 132, 135, 137, 140, 142, 145, 147, 150, 152, 155, 157, 160, 162, 165, 167, 170, 172, 175, 177,
+ 180, 182, 185, 187, 190, 192, 195, 197, 200, 202, 205, 207, 210, 212, 215, 217, 220, 222, 225, 227,
+ 230, 232, 235, 237, 240, 242, 245, 247, 250, 252, 255, 257, 260, 262, 265, 267, 270, 272, 275, 277
+ ]
+ ];
+
+ /// A new copy of the blank record of , or null for a file that is not a database file.
+ public static JObject? For(string fileName, RpgMakerEngine? engine)
+ {
+ if (!MzShapes.TryGetValue(fileName, out string? text))
+ {
+ return null;
+ }
+
+ bool mz = engine == RpgMakerEngine.MZ;
+ if (!mz && fileName == "animations.json")
+ {
+ return JObject.Parse(MvAnimation);
+ }
+
+ var record = JObject.Parse(text);
+ if (fileName == "classes.json")
+ {
+ record[ParamsProperty] = new JArray(ClassCurves.Select(curve => new JArray(curve)));
+ }
+
+ if (!mz)
+ {
+ record.Remove(MessageTypeProperty);
+ }
+
+ return record;
+ }
+}
diff --git a/RPGModder.Core/Merge/Composer.cs b/RPGModder.Core/Merge/Composer.cs
index 4039bcd..8cccf1b 100644
--- a/RPGModder.Core/Merge/Composer.cs
+++ b/RPGModder.Core/Merge/Composer.cs
@@ -59,7 +59,7 @@ 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(Group(ordered)))
+ foreach (List cluster in Cluster(DropFiller(Group(ordered), changeSets, priorities)))
{
ComposeCluster(cluster, choices, priorities, offers, ops, collisions, diagnostics);
}
@@ -112,6 +112,32 @@ private static List Group(List ordered)
return groups.Values.ToList();
}
+ ///
+ /// GR-R7: filler yields to a real record at the same id and never forms an IdClash. Where every variant
+ /// adds a database record, the filler variants drop when a real one is there; when none is, only the variant of
+ /// the mod latest in profile order stays.
+ ///
+ private static List DropFiller(List groups, IReadOnlyList changeSets, Dictionary priorities)
+ {
+ Dictionary fillers = changeSets.ToDictionary(set => set.ModId, set => new FillerTest(set), StringComparer.Ordinal);
+ foreach (OpGroup group in groups)
+ {
+ if (group.Path.Length != 0 ||
+ group.Variants.Count < 2 ||
+ RpgDataSchema.DatabaseKindOf(group.Key.File) is null ||
+ group.Variants.Any(variant => variant.Op.Kind != ChangeKind.AddRecord))
+ {
+ continue;
+ }
+
+ List real = group.Variants.Where(variant => !fillers[variant.Op.ModId].IsFiller(group.Key, variant.Op.Value)).ToList();
+ List kept = real.Count > 0 ? real : [LatestInProfileOrder(group, priorities)];
+ group.Variants.RemoveAll(variant => !kept.Contains(variant));
+ }
+
+ return groups;
+ }
+
///
/// 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.
diff --git a/RPGModder.Core/Merge/FillerTest.cs b/RPGModder.Core/Merge/FillerTest.cs
new file mode 100644
index 0000000..b8247dc
--- /dev/null
+++ b/RPGModder.Core/Merge/FillerTest.cs
@@ -0,0 +1,34 @@
+using Newtonsoft.Json.Linq;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// GR-R7: an added database record is filler when it has the shape of an editor blank
+/// () and its own mod names its id nowhere: no event command, record field,
+/// text code, free text or plugin text code. A blank the mod fills while the game runs (an actor named by 303 or
+/// drawn by 322) is a real record. The mod's references are read once, at its first blank-shaped record.
+///
+internal sealed class FillerTest
+{
+ private readonly ModChangeSet _changeSet;
+ private ModReferences? _references;
+
+ public FillerTest(ModChangeSet changeSet)
+ {
+ _changeSet = changeSet;
+ }
+
+ public bool IsFiller(RecordKey key, JToken? record)
+ {
+ if (RpgDataSchema.DatabaseKindOf(key.File) is not { } kind ||
+ !RecordKey.TryGetIndex(key.Record, out int id) ||
+ !RpgDataSchema.HasBlankShape(key.File, record))
+ {
+ return false;
+ }
+
+ // Read as a dual-wield game on no known engine, so an id of either possible kind counts as used.
+ _references ??= ReferenceMap.Scan(_changeSet, [], dualWield: true, mz: false);
+ return !_references.Uses(kind, id);
+ }
+}
diff --git a/RPGModder.Core/Merge/IdRemapPlanner.cs b/RPGModder.Core/Merge/IdRemapPlanner.cs
index 8faae1b..e6d92ef 100644
--- a/RPGModder.Core/Merge/IdRemapPlanner.cs
+++ b/RPGModder.Core/Merge/IdRemapPlanner.cs
@@ -2,28 +2,37 @@
using RPGModder.Core.Models;
using RPGModder.Core.Operations;
using RPGModder.Core.Services;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace RPGModder.Core.Merge;
///
-/// Decides which added ids move before composition (guide 3.11, GR-R3 to GR-R12). Step 1 plans the
-/// and kinds. The result does not depend on the order of any
-/// input.
+/// 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.
///
public static class IdRemapPlanner
{
+ /// Trait 55, Slot Type, whose data 1 is Dual Wield (MV and MZ Game_Actor.prototype.isDualWield).
+ private const int SlotTypeTrait = 55;
+
+ private const int DualWieldSlot = 1;
+ private const string TraitCode = "code";
+ private const string TraitData = "dataId";
+
/// Every installed mod, enabled or not, once each.
/// The profile's Remaps, every entry, active or not.
/// The profile's DeployedMods (GR-R4).
///
/// Vanilla's files, for the ids vanilla uses (GR-R5): the map file of every map that gets an event, and, when a
- /// mod adds a map, data/MapInfos.json and every vanilla map file, listed in the tree or not. A clash whose
- /// base file is missing cannot move, and a map id whose file vanilla has is never a target and never moves.
+ /// mod adds a map, data/MapInfos.json and every vanilla map file, listed in the tree or not; the database
+ /// file of every kind a mod adds a record to; and, to tell a dual-wield game (trait 55, data 1), the actors,
+ /// classes, weapons, armors and states. A clash whose base file is missing cannot move, a map id whose file
+ /// vanilla has is never a target and never moves, and a missing dual-wield file counts as dual wield.
///
///
- /// The game's engine, which sets the highest map id a move may give (GR-R6): 2000 for MZ, 999 for MV and for an
- /// unknown engine (null).
+ /// 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.
///
public static RemapPlan Plan(
IReadOnlyList installed,
@@ -55,7 +64,7 @@ public static RemapPlan Plan(
foreach (RemapMod mod in mods.Where(item => item.Enabled))
{
string modId = mod.ChangeSet.ModId;
- foreach (AddedId id in added[modId])
+ foreach (AddedId id in added[modId].Where(item => !item.IsFiller))
{
bool pinned = pins.TryGetValue((modId, id.Kind, id.Scope, id.Id), out int toId);
claims.Add(new Claim(mod, id, pinned ? toId : id.Id, pinned, deployed.Contains(modId)));
@@ -64,6 +73,8 @@ 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 moves = new List();
var offers = new List();
IEnumerable> groups = claims
@@ -82,7 +93,7 @@ public static RemapPlan Plan(
(IdKind kind, string scope, _) = group.Key;
foreach (Party party in parties)
{
- party.Classify(kind, claim => ReferencesOf(claim.Mod, references), claim => IsVanillaMapFile(kind, claim.Added.Id, baseFiles));
+ party.Classify(kind, claim => ReferencesOf(claim.Mod, dualWield, engine, references), 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.
@@ -154,7 +165,7 @@ 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);
- if (remap.Kind is not (IdKind.MapEvent or IdKind.Map) || remap.ToId <= 0 || !enabled.Contains(remap.ModId) ||
+ if (!RpgDataSchema.IsRemappable(remap.Kind) || remap.ToId <= 0 || !enabled.Contains(remap.ModId) ||
!AddedIdIndex.IsActive(remap, added[remap.ModId]) || pins.ContainsKey(from) ||
!targets.Add((remap.ModId, remap.Kind, remap.Scope, remap.ToId)))
{
@@ -187,7 +198,38 @@ public static RemapPlan Plan(
return pins;
}
- /// True when vanilla has a record at : a map file or tree record, or a map's event.
+ ///
+ /// 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 .
+ ///
+ private static void StaleReferences(
+ List mods,
+ Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int> pins,
+ Func referencesOf,
+ List diagnostics)
+ {
+ IEnumerable standing = pins.Select(pin => new IdRemap(pin.Key.ModId, pin.Key.Kind, pin.Key.Scope, pin.Key.FromId, pin.Value));
+ foreach (IdRemap remap in Sorted(standing))
+ {
+ RemapMod mod = mods.First(item => item.ChangeSet.ModId == remap.ModId);
+ if (!referencesOf(mod).Blocks(remap.Kind, remap.FromId))
+ {
+ continue;
+ }
+
+ string where = remap.Kind == IdKind.MapEvent ? " in " + remap.Scope : "";
+ diagnostics.Add(new OperationDiagnostic(
+ 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}."),
+ DiagnosticSeverity.Warning,
+ remap.ModId));
+ }
+ }
+
+ /// True when vanilla has a record at : a map file or tree record, a map's event, a database record.
private static bool VanillaUses(IdKind kind, string scope, int id, BaseFileSet baseFiles)
{
if (kind == IdKind.Map && baseFiles.Find(RpgDataSchema.MapKey(id)) is not null)
@@ -198,17 +240,60 @@ private static bool VanillaUses(IdKind kind, string scope, int id, BaseFileSet b
return VanillaList(kind, scope, baseFiles) is JArray list && id < list.Count && list[id].Type != JTokenType.Null;
}
- /// Vanilla's list for a kind and scope, holes included: the map tree for maps, a map's events for events.
+ ///
+ /// Vanilla's list for a kind and scope, holes included: the map tree for maps, a map's events for events, the
+ /// database file for a database kind.
+ ///
private static JArray? VanillaList(IdKind kind, string scope, BaseFileSet baseFiles)
{
- string file = kind == IdKind.Map ? RpgDataSchema.MapInfosKey : scope;
- BaseFile? baseFile = baseFiles.Find(file);
- if (baseFile is null || !ChangeSetBuilder.TryReadBase(baseFile, out JToken? root, out _))
+ string? file = kind switch
+ {
+ IdKind.Map => RpgDataSchema.MapInfosKey,
+ IdKind.MapEvent => scope,
+ _ => RpgDataSchema.DatabaseFileOf(kind)
+ };
+ if (file is null || !TryReadBase(baseFiles, file, out JToken? root))
{
return null;
}
- return (kind == IdKind.Map ? root : (root as JObject)?[RpgDataSchema.EventsProperty]) as JArray;
+ return (kind == IdKind.MapEvent ? (root as JObject)?[RpgDataSchema.EventsProperty] : root) as JArray;
+ }
+
+ ///
+ /// True when an actor may wield two weapons, so the second equip slot may hold a weapon: a trait 55 with data 1
+ /// in vanilla's or an enabled mod's actors, classes, weapons, armors or states. A file vanilla lacks or that cannot
+ /// be read counts as dual wield, the side on which fewer ids move.
+ ///
+ private static bool IsDualWield(List mods, BaseFileSet baseFiles)
+ {
+ IdKind[] kinds = [IdKind.Actor, IdKind.Class, IdKind.Weapon, IdKind.Armor, IdKind.State];
+ var files = new HashSet(kinds.Select(kind => RpgDataSchema.DatabaseFileOf(kind)!), StringComparer.Ordinal);
+ foreach (string file in files)
+ {
+ if (!TryReadBase(baseFiles, file, out JToken? root) || HasDualWield(root))
+ {
+ return true;
+ }
+ }
+
+ return mods.Where(mod => mod.Enabled)
+ .SelectMany(mod => mod.ChangeSet.Ops)
+ .Any(op => files.Contains(op.Key.File) && op.Value is not null && HasDualWield(op.Value));
+ }
+
+ private static bool HasDualWield(JToken token)
+ {
+ return token is JContainer container && container.DescendantsAndSelf().OfType().Any(item =>
+ item[TraitCode] is JValue { Value: long code } && code == SlotTypeTrait &&
+ item[TraitData] is JValue { Value: long data } && data == DualWieldSlot);
+ }
+
+ private static bool TryReadBase(BaseFileSet baseFiles, string file, [NotNullWhen(true)] out JToken? root)
+ {
+ root = null;
+ BaseFile? baseFile = baseFiles.Find(file);
+ return baseFile is not null && ChangeSetBuilder.TryReadBase(baseFile, out root, out _);
}
/// GR-R3: claims with equal content are one party, because their ops fold into one.
@@ -244,11 +329,15 @@ private static bool IsVanillaMapFile(IdKind kind, int id, BaseFileSet baseFiles)
return kind == IdKind.Map && baseFiles.Find(RpgDataSchema.MapKey(id)) is not null;
}
- private static ModReferences ReferencesOf(RemapMod mod, Dictionary cache)
+ private static ModReferences ReferencesOf(
+ RemapMod mod,
+ Lazy dualWield,
+ RpgMakerEngine? engine,
+ Dictionary cache)
{
if (!cache.TryGetValue(mod.ChangeSet.ModId, out ModReferences? found))
{
- found = ReferenceMap.Scan(mod.ChangeSet, mod.PluginScripts);
+ found = ReferenceMap.Scan(mod.ChangeSet, mod.PluginScripts, dualWield.Value, engine == RpgMakerEngine.MZ);
cache.Add(mod.ChangeSet.ModId, found);
}
diff --git a/RPGModder.Core/Merge/IdRemapper.cs b/RPGModder.Core/Merge/IdRemapper.cs
index 9e1dcc0..c42896f 100644
--- a/RPGModder.Core/Merge/IdRemapper.cs
+++ b/RPGModder.Core/Merge/IdRemapper.cs
@@ -13,8 +13,8 @@ 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). Step 1 applies the
- /// and kinds and ignores the others.
+ /// 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.
///
public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList remaps)
{
@@ -28,7 +28,7 @@ public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList
IReadOnlyList added = AddedIdIndex.Of(changeSet);
List active = remaps
- .Where(remap => remap.ModId == changeSet.ModId && remap.Kind is IdKind.MapEvent or IdKind.Map && AddedIdIndex.IsActive(remap, added))
+ .Where(remap => remap.ModId == changeSet.ModId && RpgDataSchema.IsRemappable(remap.Kind) && AddedIdIndex.IsActive(remap, added))
.Distinct()
.OrderBy(remap => remap.Kind)
.ThenBy(remap => remap.Scope, StringComparer.Ordinal)
@@ -38,7 +38,7 @@ public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList
var table = new RemapTable();
foreach (IdRemap remap in active)
{
- Dictionary moves = remap.Kind == IdKind.Map ? table.Maps : EventMoves(table, remap.Scope);
+ Dictionary moves = table.For(remap.Kind, remap.Scope);
if (remap.ToId <= 0 || moves.ContainsValue(remap.ToId) || !moves.TryAdd(remap.FromId, remap.ToId))
{
// The planner gives each old id one positive target of its own; anything else is a caller bug.
@@ -54,8 +54,7 @@ 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 = changeSet.Ops
- .Select(op => ReferenceMap.Rewrite(op, table))
+ List ops = ReferenceMap.Rewrite(changeSet, table)
.OrderBy(op => op, Comparer.Create(ChangeSetBuilder.CompareOps))
.ToList();
@@ -77,15 +76,4 @@ private static string Describe(IdRemap remap)
CultureInfo.InvariantCulture,
$"Mod {remap.ModId}: {remap.Kind} {remap.FromId}{where} moved to {remap.ToId}.");
}
-
- private static Dictionary EventMoves(RemapTable table, string scope)
- {
- if (!table.Events.TryGetValue(scope, out Dictionary? moves))
- {
- moves = new Dictionary();
- table.Events.Add(scope, moves);
- }
-
- return moves;
- }
}
diff --git a/RPGModder.Core/Merge/MergedFileWriter.cs b/RPGModder.Core/Merge/MergedFileWriter.cs
index fa94258..df49225 100644
--- a/RPGModder.Core/Merge/MergedFileWriter.cs
+++ b/RPGModder.Core/Merge/MergedFileWriter.cs
@@ -1,5 +1,6 @@
using Newtonsoft.Json.Linq;
using RPGModder.Core.Models;
+using RPGModder.Core.Services;
namespace RPGModder.Core.Merge;
@@ -10,7 +11,11 @@ namespace RPGModder.Core.Merge;
///
public static class MergedFileWriter
{
- public static IReadOnlyList Write(MergePlan plan, BaseFileSet baseFiles, int? systemVersionId)
+ ///
+ /// The game's engine, which picks the blank record that fills a hole in a database file (GR-R8). An unknown
+ /// engine (null) gets MV's blanks.
+ ///
+ public static IReadOnlyList Write(MergePlan plan, BaseFileSet baseFiles, int? systemVersionId, RpgMakerEngine? engine = null)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(baseFiles);
@@ -56,14 +61,20 @@ public static IReadOnlyList Write(MergePlan plan, BaseFileSet baseFi
MergeFileKind.Opaque => Copy(file, fileOps, modIds),
MergeFileKind.PluginList => new MergedFile(file, MergedFileSource.Text, RenderPluginList(file, fileOps, baseFiles), null, null, modIds),
MergeFileKind.ConfigSave => new MergedFile(file, MergedFileSource.Text, RenderConfigSave(file, fileOps, baseFiles), null, null, modIds),
- _ => WriteDataFile(file, fileOps, baseFiles, systemVersionId, modIds)
+ _ => WriteDataFile(file, fileOps, baseFiles, systemVersionId, engine, modIds)
});
}
return result;
}
- private static MergedFile WriteDataFile(string file, List fileOps, BaseFileSet baseFiles, int? systemVersionId, List modIds)
+ private static MergedFile WriteDataFile(
+ string file,
+ List fileOps,
+ BaseFileSet baseFiles,
+ int? systemVersionId,
+ RpgMakerEngine? engine,
+ List modIds)
{
BaseFile? baseFile = baseFiles.Find(file);
if (baseFile is null)
@@ -71,13 +82,21 @@ private static MergedFile WriteDataFile(string file, List fileOps, Bas
// GR-M9: a new file is one AddRecord on *, copied as the mod shipped it unless a patch or a remap changed
// it. Written as text, it names its mod so lane A takes the casing of that mod's file (seam 4.2 step 2);
// a map gets the casing the game loads instead (step 0), because a remapped one has no mod file name.
+ // A database file with a hole is written as text too, so the hole gets its blank record (GR-R8).
ChangeOp added = SingleOp(fileOps, ChangeKind.AddRecord);
- return added.SourceFile is null
- ? new MergedFile(file, MergedFileSource.Text, MergeJson.Write(Value(added)), added.ModId, null, modIds, RpgDataSchema.DiskPathOf(file))
- : new MergedFile(file, MergedFileSource.ModFile, null, added.ModId, added.SourceFile, modIds);
+ JToken value = Value(added);
+ if (added.SourceFile is not null && !HasHoles(file, value))
+ {
+ return new MergedFile(file, MergedFileSource.ModFile, null, added.ModId, added.SourceFile, modIds);
+ }
+
+ JToken filled = value.DeepClone();
+ FillHoles(file, filled, engine);
+ return new MergedFile(file, MergedFileSource.Text, MergeJson.Write(filled), added.ModId, null, modIds, RpgDataSchema.DiskPathOf(file));
}
JToken root = Render(file, baseFile, fileOps);
+ FillHoles(file, root, engine);
if (file == RpgDataSchema.SystemFileKey && systemVersionId is not null)
{
SetVersionId(root, systemVersionId.Value);
@@ -86,6 +105,34 @@ private static MergedFile WriteDataFile(string file, List fileOps, Bas
return new MergedFile(file, MergedFileSource.Text, MergeJson.Write(root), null, null, modIds);
}
+ ///
+ /// GR-R8: a database file gets no null above index 0. Each hole, left by a removed, disabled or moved
+ /// record, takes the file's blank record with its own id. MapInfos and a map's events keep their holes.
+ ///
+ private static void FillHoles(string file, JToken root, RpgMakerEngine? engine)
+ {
+ if (root is not JArray records)
+ {
+ return;
+ }
+
+ for (int index = 1; index < records.Count; index++)
+ {
+ if (records[index].Type == JTokenType.Null && RpgDataSchema.BlankRecord(file, engine) is { } blank)
+ {
+ blank["id"] = index;
+ records[index] = blank;
+ }
+ }
+ }
+
+ private static bool HasHoles(string file, JToken root)
+ {
+ return RpgDataSchema.DatabaseKindOf(file) is not null &&
+ root is JArray records &&
+ records.Skip(1).Any(record => record.Type == JTokenType.Null);
+ }
+
/// A replaced opaque file is the bytes of the mod whose id sorts first among those that ship them.
private static MergedFile Copy(string file, List fileOps, List modIds)
{
diff --git a/RPGModder.Core/Merge/ModReferences.cs b/RPGModder.Core/Merge/ModReferences.cs
index f432a32..9578181 100644
--- a/RPGModder.Core/Merge/ModReferences.cs
+++ b/RPGModder.Core/Merge/ModReferences.cs
@@ -3,33 +3,92 @@ namespace RPGModder.Core.Merge;
/// What found in one mod: the numbers a remap cannot rewrite.
internal sealed class ModReferences
{
+ private readonly Dictionary> _ambiguous = new();
+ private readonly HashSet _unknownIds = new();
+ private readonly Dictionary> _used = new();
+
/// Whole numbers in the change set's free text (GR-R9).
public HashSet FreeTextNumbers { get; } = new();
- /// Event ids named by event commands in a common event or a troop, which act on any map (3.11).
- public HashSet AmbiguousEventIds { get; } = new();
-
- /// Constants Control Variables assigns; with a transfer by variable, one of them may be a map id.
+ /// Constants Control Variables assigns; with a by-variable command, one of them may be its id.
public HashSet VariableConstants { get; } = new();
+ /// Random ranges Control Variables assigns, low end first; with a by-variable command, any id in one may be its id.
+ public List<(long Min, long Max)> VariableRanges { get; } = new();
+
/// Whole numbers in the plugin files the mod ships (GR-R11).
public HashSet PluginScriptNumbers { get; } = new();
///
- /// True when the mod sends the player or a vehicle to a map named by a variable (201 with p[0] 1, 202 with
- /// p[1] 1).
+ /// 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).
+ ///
+ public HashSet ByVariableKinds { get; } = new();
+
+ ///
+ /// Records an id that may be of where a remap cannot tell (3.11): an event command outside
+ /// a map, the second equip slot of a dual-wield game, a field whose kind sits in a vanilla sibling.
///
- public bool UsesVariableTransfer { get; set; }
+ public void AddAmbiguous(IdKind kind, long id)
+ {
+ if (!_ambiguous.TryGetValue(kind, out HashSet? ids))
+ {
+ ids = new HashSet();
+ _ambiguous.Add(kind, ids);
+ }
+
+ ids.Add(id);
+ }
+
+ ///
+ /// Records that some id of that only vanilla holds is named where a remap cannot see it:
+ /// a field whose deciding sibling the mod changed alone, such as a drop whose kind changed and whose
+ /// dataId did not.
+ ///
+ public void AddUnknownId(IdKind kind)
+ {
+ _unknownIds.Add(kind);
+ }
+
+ /// Records an id of the change set names where a remap rewrites it.
+ public void AddUsed(IdKind kind, long id)
+ {
+ if (!_used.TryGetValue(kind, out HashSet? ids))
+ {
+ ids = new HashSet();
+ _used.Add(kind, ids);
+ }
+
+ ids.Add(id);
+ }
+
+ ///
+ /// 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).
+ ///
+ public bool Uses(IdKind kind, int id)
+ {
+ return FreeTextNumbers.Contains(id) ||
+ (_used.TryGetValue(kind, out HashSet? ids) && ids.Contains(id)) ||
+ (_ambiguous.TryGetValue(kind, out HashSet? unknown) && unknown.Contains(id)) ||
+ ByVariable(kind, id);
+ }
/// True when the change set refers to where a remap cannot follow it (GR-R9).
public bool Blocks(IdKind kind, int id)
{
- return FreeTextNumbers.Contains(id) || kind switch
- {
- IdKind.MapEvent => AmbiguousEventIds.Contains(id),
- IdKind.Map => UsesVariableTransfer && VariableConstants.Contains(id),
- _ => true
- };
+ return FreeTextNumbers.Contains(id) ||
+ !RpgDataSchema.IsRemappable(kind) ||
+ (_ambiguous.TryGetValue(kind, out HashSet? ids) && ids.Contains(id)) ||
+ _unknownIds.Contains(kind) ||
+ ByVariable(kind, id);
+ }
+
+ /// True when a by-variable command of may get from a constant or a random range.
+ private bool ByVariable(IdKind kind, int id)
+ {
+ return ByVariableKinds.Contains(kind) &&
+ (VariableConstants.Contains(id) || VariableRanges.Exists(range => range.Min <= id && id <= range.Max));
}
/// True when appears in a shipped plugin file, so a move is only offered (GR-R11).
diff --git a/RPGModder.Core/Merge/ReferenceMap.cs b/RPGModder.Core/Merge/ReferenceMap.cs
index dd03786..6cb1a34 100644
--- a/RPGModder.Core/Merge/ReferenceMap.cs
+++ b/RPGModder.Core/Merge/ReferenceMap.cs
@@ -1,84 +1,41 @@
using Newtonsoft.Json.Linq;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
+using System.Text;
namespace RPGModder.Core.Merge;
///
-/// Where an id is referenced (guide 3.11, reference table), for the two kinds of step 1. reads a
-/// change set's free text and the references the table cannot rewrite (GR-R9); moves every
-/// reference the table lists. p[n] below is parameters[n] of an event or route command; only values
-/// above 0 are ids. Every position was checked against the MV and MZ core scripts.
+/// 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.
///
internal static class ReferenceMap
{
- // Route command (inside a moveRoute list): Script.
- private const int RouteScript = 45;
-
- // Event commands.
- private const int ConditionalBranch = 111;
- private const int ControlVariables = 122;
- private const int TransferPlayer = 201;
- private const int SetVehicleLocation = 202;
- private const int SetEventLocation = 203;
- private const int SetMovementRoute = 205;
- private const int ShowAnimation = 212;
- private const int ShowBalloon = 213;
- private const int GetLocationInfo = 285;
- private const int Script = 355;
- private const int PluginCommandMv = 356;
- private const int PluginCommandMz = 357;
- private const int ScriptMore = 655;
-
- // 111 p[0], 122 p[3] and p[4], 201 p[0], 202 p[1], 203 p[1], 285 p[2]: the operand forms the table names.
- private const int BranchCharacter = 6;
- private const int BranchScript = 12;
- private const int OperandConstant = 0;
- private const int OperandGameData = 3;
- private const int OperandScript = 4;
- private const int GameDataCharacter = 5;
- private const int DesignationDirect = 0;
- private const int DesignationByVariable = 1;
- private const int EventLocationExchange = 2;
- private const int LocationByCharacter = 2;
-
private const string NoteProperty = "note";
private const string DamageProperty = "damage";
private const string FormulaProperty = "formula";
- private const string ParentIdProperty = "parentId";
private const string IdProperty = "id";
private const string ParametersProperty = "parameters";
private const string CodeProperty = "code";
+ private const int CommentCode = 108;
+ private const int CommentMoreCode = 408;
- /// The System.json places that hold a map id.
- private static readonly HashSet StartMapPaths = new(StringComparer.Ordinal)
- {
- "startMapId",
- "boat.startMapId",
- "ship.startMapId",
- "airship.startMapId"
- };
-
- /// What in one mod's change set stops a move (GR-R9) or makes it unchecked (GR-R11).
- public static ModReferences Scan(ModChangeSet changeSet, IReadOnlyList pluginScripts)
+ ///
+ /// What in one mod's change set stops a move (GR-R9), makes it unchecked (GR-R11) or uses an id (GR-R7). With
+ /// , the second equip slot may hold a weapon, so its ids are of no known kind. Without
+ /// , a row only MZ reads so is of no known kind too.
+ ///
+ public static ModReferences Scan(ModChangeSet changeSet, IReadOnlyList pluginScripts, bool dualWield, bool mz)
{
var references = new ModReferences();
+ var siblings = new SiblingOps(changeSet);
foreach (ChangeOp op in changeSet.Ops)
{
- if (op.Value is null || MergePath.IsPseudoLeaf(op.Path))
+ if (op.Value is not null && !MergePath.IsPseudoLeaf(op.Path))
{
- continue;
+ new Walker(op, siblings, dualWield, mz, hit => Collect(hit, references)).Walk(op.Value);
}
-
- IReadOnlyList segments = MergePath.Parse(op.Path);
- string? name = segments.Count > 0 ? segments[^1].Name : null;
- string? parent = segments.Count > 1 ? segments[^2].Name : null;
- bool isPluginList = op.Key.File == RpgDataSchema.PluginListKey;
- var context = new ScanContext(references, RpgDataSchema.IsMapFile(op.Key.File), isPluginList);
-
- // Plugin parameters the mod sets are free text (GR-R9), whether the op names one or the whole entry.
- bool inParameters = isPluginList && segments.Count > 0 && segments[0].Name == ParametersProperty;
- Visit(op.Value, name, parent, inParameters, context);
}
foreach (string script in pluginScripts)
@@ -90,257 +47,234 @@ public static ModReferences Scan(ModChangeSet changeSet, IReadOnlyList p
}
///
- /// with every listed reference moved by , or the op itself when
- /// nothing moved. A whole new file whose content changed loses its source file, so it is written as text.
+ /// The change set's ops with every reference the rows name moved by , and every added
+ /// record that moves on its new id. An op nothing moved is returned as it was. A reference of no known kind is
+ /// left alone: the planner never moves an id a mod names so (GR-R9). The second equip slot is read as an armor,
+ /// because in a dual-wield game the planner moves neither kind of an id a mod puts there; a row only MZ reads so
+ /// is read as on MZ, because on any other engine the planner never moves its id.
///
- public static ChangeOp Rewrite(ChangeOp op, RemapTable table)
+ public static IReadOnlyList Rewrite(ModChangeSet changeSet, RemapTable table)
{
- RecordKey key = op.Key;
- JToken? value = op.Value?.DeepClone();
- if (op.Kind == ChangeKind.AddRecord && op.Path.Length == 0)
- {
- if (key.IsWholeFile && RpgDataSchema.TryGetMapId(key.File, out int mapId) && table.Maps.TryGetValue(mapId, out int newMap))
- {
- key = new RecordKey(RpgDataSchema.MapKey(newMap), RecordKey.WholeFile);
- }
- else if (key.File == RpgDataSchema.MapInfosKey && RecordKey.TryGetIndex(key.Record, out int infoId) &&
- table.Maps.TryGetValue(infoId, out int newInfo))
- {
- key = key with { Record = RecordKey.ForIndex(newInfo) };
- SetOwnId(value, infoId, newInfo);
- }
- else if (table.Events.TryGetValue(key.File, out Dictionary? moved) && RecordKey.TryGetEvent(key.Record, out int eventId) &&
- moved.TryGetValue(eventId, out int newEvent))
- {
- key = key with { Record = RecordKey.ForEvent(newEvent) };
- SetOwnId(value, eventId, newEvent);
- }
- }
+ var siblings = new SiblingOps(changeSet);
+ return changeSet.Ops.Select(op => Rewrite(op, table, siblings)).ToList();
+ }
+ private static ChangeOp Rewrite(ChangeOp op, RemapTable table, SiblingOps siblings)
+ {
+ JToken? value = op.Value?.DeepClone();
+ RecordKey key = op.Kind == ChangeKind.AddRecord && op.Path.Length == 0 ? OwnKey(op.Key, value, table) : op.Key;
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);
- VisitCommands(value, command => RewriteCommand(command, table.Maps, events));
- if (op.Key.File == RpgDataSchema.MapInfosKey && !op.Key.IsWholeFile)
- {
- // A map's parent, in the moved map's own record or in a vanilla map the mod hangs under it.
- value = RewriteAt(value, op.Path, path => path == ParentIdProperty, table.Maps);
- }
- else if (op.Key.File == RpgDataSchema.SystemFileKey)
- {
- value = RewriteAt(value, op.Path, StartMapPaths.Contains, table.Maps);
- }
+ new Walker(op, siblings, dualWield: false, mz: true, hit => Move(hit, table, events)).Walk(value);
}
- bool changed = key != op.Key || !JToken.DeepEquals(value, op.Value);
- if (!changed)
+ if (key == op.Key && 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 };
}
- private static void Visit(JToken token, string? name, string? parent, bool inParameters, ScanContext context)
+ /// The key an added record moves to, with its own id set: a map file, a tree record, an event or a database record.
+ private static RecordKey OwnKey(RecordKey key, JToken? value, RemapTable table)
{
- if (inParameters)
+ if (key.IsWholeFile)
{
- AddNumbers(token, context.References.FreeTextNumbers);
- return;
+ return RpgDataSchema.TryGetMapId(key.File, out int mapId) && table.MovesOf(IdKind.Map) is { } maps && maps.TryGetValue(mapId, out int newMap)
+ ? new RecordKey(RpgDataSchema.MapKey(newMap), RecordKey.WholeFile)
+ : key;
}
- switch (token)
+ Dictionary? moves = null;
+ Func recordOf = RecordKey.ForIndex;
+ if (RecordKey.TryGetEvent(key.Record, out int oldId))
{
- case JObject item:
- if (TryCommand(item, out int code, out JArray? parameters))
- {
- ScanCommand(code, parameters, context);
- }
-
- foreach (JProperty property in item.Properties())
- {
- bool pluginParameters = context.IsPluginList && property.Name == ParametersProperty;
- Visit(property.Value, property.Name, name, pluginParameters, context);
- }
+ moves = table.Events.GetValueOrDefault(key.File);
+ recordOf = RecordKey.ForEvent;
+ }
+ else if (RecordKey.TryGetIndex(key.Record, out oldId))
+ {
+ IdKind? kind = key.File == RpgDataSchema.MapInfosKey ? IdKind.Map : RpgDataSchema.DatabaseKindOf(key.File);
+ moves = kind is null ? null : table.MovesOf(kind.Value);
+ }
- break;
- case JArray list:
- foreach (JToken element in list)
- {
- Visit(element, null, name, false, context);
- }
+ if (moves is null || !moves.TryGetValue(oldId, out int newId))
+ {
+ return key;
+ }
- break;
- case JValue { Type: JTokenType.String } text when name == NoteProperty || (name == FormulaProperty && parent == DamageProperty):
- AddNumbers(text, context.References.FreeTextNumbers);
- break;
+ if (value is JObject record && record[IdProperty] is JValue id && TryId(id, out int current) && current == oldId)
+ {
+ record[IdProperty] = newId;
}
+
+ return key with { Record = recordOf(newId) };
}
- private static void ScanCommand(int code, JArray parameters, ScanContext context)
+ private static void Collect(Hit hit, ModReferences references)
{
- ModReferences references = context.References;
- switch (code)
+ // An Id hit, or a text code the table knows, is a reference a remap rewrites: it stops nothing, but it uses the id.
+ switch (hit.Use)
{
- case Script or ScriptMore or PluginCommandMv or RouteScript:
- AddNumbers(At(parameters, 0), references.FreeTextNumbers);
+ case HitUse.Id when hit.Token is JValue value && TryId(value, out int used):
+ references.AddUsed(hit.Kind, used);
+ break;
+ case HitUse.Text or HitUse.Comment when hit.Token is JValue { Value: string text } && text.Contains('\\'):
+ foreach ((string letters, _, _, int id) in TextCodesIn(text))
+ {
+ if (ReferenceTable.TextCodes.TryGetValue(letters, out IdKind kind))
+ {
+ references.AddUsed(kind, id);
+ }
+ else if (hit.Use == HitUse.Text && !ReferenceTable.BuiltInTextCodes.Contains(letters))
+ {
+ // A plugin's code may name an id of any kind, so it is free text (GR-R9); a comment is not read.
+ references.FreeTextNumbers.Add(id);
+ }
+ }
+
break;
- case PluginCommandMz:
- AddNumbers(At(parameters, 3), references.FreeTextNumbers);
+ case HitUse.FreeText:
+ AddNumbers(hit.Token, references.FreeTextNumbers);
break;
- case ConditionalBranch when Is(parameters, 0, BranchScript):
- AddNumbers(At(parameters, 1), references.FreeTextNumbers);
+ case HitUse.Ambiguous when hit.Token is JValue value && TryLooseId(value, out int id):
+ references.AddAmbiguous(hit.Kind, id);
break;
- case ControlVariables when Is(parameters, 3, OperandScript):
- AddNumbers(At(parameters, 4), references.FreeTextNumbers);
+ case HitUse.UnknownId:
+ references.AddUnknownId(hit.Kind);
break;
- case ControlVariables when Is(parameters, 3, OperandConstant):
- AddId(At(parameters, 4), references.VariableConstants);
+ case HitUse.Constant when hit.Token is JValue value && TryId(value, out int constant):
+ references.VariableConstants.Add(constant);
break;
- case TransferPlayer when Is(parameters, 0, DesignationByVariable):
- case SetVehicleLocation when Is(parameters, 1, DesignationByVariable):
- references.UsesVariableTransfer = true;
+ case HitUse.RandomRange when hit.Token is JArray { Count: 2 } range && range[0] is JValue low && TryInt(low, out int min) &&
+ range[1] is JValue high && TryInt(high, out int max):
+ references.VariableRanges.Add((Math.Min(min, max), Math.Max(min, max)));
+ break;
+ case HitUse.ByVariable:
+ references.ByVariableKinds.Add(hit.Kind);
break;
- }
-
- if (context.IsMapFile)
- {
- return;
- }
-
- // Outside a map the event commands act on whatever map is loaded, so their ids cannot be rewritten (3.11).
- foreach (int index in EventPositions(code, parameters))
- {
- AddId(At(parameters, index), references.AmbiguousEventIds);
}
}
- private static void RewriteCommand(JObject command, Dictionary maps, Dictionary? events)
+ private static void Move(Hit hit, RemapTable table, Dictionary? events)
{
- if (!TryCommand(command, out int code, out JArray? parameters))
+ if (hit.Token is not JValue value)
{
return;
}
- if (maps.Count > 0)
+ if (hit.Use is HitUse.Text or HitUse.Comment)
{
- if (code == TransferPlayer && Is(parameters, 0, DesignationDirect))
- {
- Move(parameters, 1, maps);
- }
- else if (code == SetVehicleLocation && Is(parameters, 1, DesignationDirect))
+ string text = value.Value() ?? "";
+ string moved = MoveTextCodes(text, table);
+ if (!ReferenceEquals(moved, text))
{
- Move(parameters, 2, maps);
+ value.Value = moved;
}
+
+ return;
}
- if (events is not null)
+ Dictionary? moves = hit.Kind == IdKind.MapEvent ? events : table.MovesOf(hit.Kind);
+ if (hit.Use == HitUse.Id && moves is not null && TryId(value, out int id) && moves.TryGetValue(id, out int newId))
{
- foreach (int index in EventPositions(code, parameters))
- {
- Move(parameters, index, events);
- }
+ value.Value = (long)newId;
}
}
- /// The positions of a command that hold an event id of the current map, from the reference table.
- private static IEnumerable EventPositions(int code, JArray parameters)
+ ///
+ /// 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.
+ ///
+ private static string MoveTextCodes(string text, RemapTable table)
{
- switch (code)
+ StringBuilder? builder = null;
+ int copied = 0;
+ foreach ((string letters, int start, int end, int id) in TextCodesIn(text))
{
- case SetEventLocation:
- yield return 0;
- if (Is(parameters, 1, EventLocationExchange))
- {
- yield return 2;
- }
-
- break;
- case SetMovementRoute or ShowAnimation or ShowBalloon:
- yield return 0;
- break;
- case ConditionalBranch when Is(parameters, 0, BranchCharacter):
- yield return 1;
- break;
- case ControlVariables when Is(parameters, 3, OperandGameData) && Is(parameters, 4, GameDataCharacter):
- yield return 5;
- break;
- case GetLocationInfo when Is(parameters, 2, LocationByCharacter):
- yield return 3;
- break;
+ if (ReferenceTable.TextCodes.TryGetValue(letters, out IdKind kind) &&
+ table.MovesOf(kind) is { } moves &&
+ moves.TryGetValue(id, out int newId))
+ {
+ builder ??= new StringBuilder(text.Length);
+ builder.Append(text, copied, start - copied).Append(newId.ToString(CultureInfo.InvariantCulture));
+ copied = end;
+ }
}
+
+ return builder is null ? text : builder.Append(text, copied, text.Length - copied).ToString();
}
- /// Every command object in , including route commands inside a move route.
- private static void VisitCommands(JToken token, Action visit)
+ ///
+ /// Every text code with a number above 0 in , its letters in upper case. A pair of
+ /// backslashes is a literal backslash, as the game reads it. Start and End bound the digits.
+ ///
+ private static IEnumerable<(string Letters, int Start, int End, int Id)> TextCodesIn(string text)
{
- switch (token)
+ for (int index = 0; index < text.Length; index++)
{
- case JObject item:
- visit(item);
- foreach (JProperty property in item.Properties())
- {
- VisitCommands(property.Value, visit);
- }
+ if (text[index] != '\\')
+ {
+ continue;
+ }
- break;
- case JArray list:
- foreach (JToken element in list)
- {
- VisitCommands(element, visit);
- }
+ if (index + 1 < text.Length && text[index + 1] == '\\')
+ {
+ index++;
+ continue;
+ }
- break;
+ if (TryTextCode(text, index, out string letters, out int start, out int end, out int id))
+ {
+ yield return (letters, start, end, id);
+ index = end;
+ }
}
}
- ///
- /// Moves the map ids at the places accepts, walking down
- /// from its own path (relative to the record, as op paths are).
- ///
- private static JToken RewriteAt(JToken token, string path, Func isPlace, Dictionary maps)
+ /// A text code at : letters, then digits in brackets, as the message window reads it.
+ private static bool TryTextCode(string text, int slash, out string letters, out int start, out int end, out int id)
{
- if (isPlace(path))
+ letters = "";
+ id = 0;
+ int open = slash + 1;
+ while (open < text.Length && char.IsAsciiLetter(text[open]))
{
- return token is JValue value && TryId(value, out int id) && maps.TryGetValue(id, out int moved) ? new JValue(moved) : token;
+ open++;
}
- if (token is not JObject item)
+ start = open + 1;
+ end = start;
+ if (open == slash + 1 || open >= text.Length || text[open] != '[')
{
- return token;
+ return false;
}
- foreach (JProperty property in item.Properties().ToList())
+ while (end < text.Length && char.IsAsciiDigit(text[end]))
{
- property.Value = RewriteAt(property.Value, MergePath.Child(path, property.Name), isPlace, maps);
+ end++;
}
- return item;
- }
-
- private static void SetOwnId(JToken? value, int oldId, int newId)
- {
- if (value is JObject record && record[IdProperty] is JValue id && TryId(id, out int current) && current == oldId)
+ if (end == start || end >= text.Length || text[end] != ']' ||
+ !int.TryParse(text.AsSpan(start, end - start), NumberStyles.None, CultureInfo.InvariantCulture, out id) || id <= 0)
{
- record[IdProperty] = newId;
+ return false;
}
- }
- private static void Move(JArray parameters, int index, Dictionary moves)
- {
- if (At(parameters, index) is JValue value && TryId(value, out int id) && moves.TryGetValue(id, out int moved))
- {
- parameters[index] = moved;
- }
+ letters = text[(slash + 1)..open].ToUpperInvariant();
+ return true;
}
private static bool TryCommand(JObject item, out int code, [NotNullWhen(true)] out JArray? parameters)
{
parameters = item[ParametersProperty] as JArray;
code = 0;
- return parameters is not null && item[CodeProperty] is JValue { Type: JTokenType.Integer } value && TryInt(value, out code);
+ return parameters is not null && item[CodeProperty] is JValue value && TryInt(value, out code);
}
private static JToken? At(JArray parameters, int index)
@@ -348,9 +282,9 @@ private static bool TryCommand(JObject item, out int code, [NotNullWhen(true)] o
return index < parameters.Count ? parameters[index] : null;
}
- private static bool Is(JArray parameters, int index, int expected)
+ private static bool Holds(JArray parameters, ParameterTest test)
{
- return At(parameters, index) is JValue value && TryInt(value, out int actual) && actual == expected;
+ return At(parameters, test.Index) is JValue value && TryInt(value, out int actual) && actual >= test.Min && actual <= test.Max;
}
/// An id is a whole number above 0 (reference table).
@@ -359,6 +293,30 @@ private static bool TryId(JValue value, out int id)
return TryInt(value, out id) && id > 0;
}
+ ///
+ /// An id the game reads although the editor never writes it so: a whole number stored as a float (3.0) or
+ /// as a string of digits ("3"), which JavaScript turns into the same array index.
+ ///
+ private static bool TryLooseId(JValue value, out int id)
+ {
+ id = 0;
+ switch (value.Value)
+ {
+ case long:
+ return TryId(value, out id);
+ case double real when real is >= 1 and <= int.MaxValue && real == Math.Floor(real):
+ id = (int)real;
+ return true;
+ case decimal exact when exact is >= 1 and <= int.MaxValue && exact == decimal.Truncate(exact):
+ id = (int)exact;
+ return true;
+ case string text when text.Length > 0 && text[0] != '0' && text.All(char.IsAsciiDigit):
+ return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out id);
+ default:
+ return false;
+ }
+ }
+
private static bool TryInt(JValue value, out int number)
{
number = 0;
@@ -371,14 +329,6 @@ private static bool TryInt(JValue value, out int number)
return true;
}
- private static void AddId(JToken? token, HashSet ids)
- {
- if (token is JValue value && TryId(value, out int id))
- {
- ids.Add(id);
- }
- }
-
/// Every whole number in : each run of ASCII digits in its text, and each integer.
private static void AddNumbers(JToken? token, HashSet numbers)
{
@@ -425,5 +375,350 @@ private static void AddNumbers(string text, HashSet numbers)
}
}
- private sealed record ScanContext(ModReferences References, bool IsMapFile, bool IsPluginList);
+ private enum HitUse
+ {
+ /// An id of a known kind, which a remap rewrites.
+ Id,
+
+ ///
+ /// An id that may be of or of another kind, or that is not stored as an integer, so a
+ /// remap cannot follow it.
+ ///
+ Ambiguous,
+
+ /// Some id of that only vanilla holds; which one, this walk cannot see.
+ UnknownId,
+
+ FreeText,
+ Constant,
+
+ /// A random range's two ends, as a new array of two values.
+ RandomRange,
+
+ ByVariable,
+
+ /// A string, whose text codes a remap rewrites.
+ Text,
+
+ /// A string of a comment (108, 408): its text codes are rewritten, but a plugin's code stops nothing.
+ Comment
+ }
+
+ private readonly record struct Hit(HitUse Use, IdKind Kind, JToken Token);
+
+ ///
+ /// The values other ops of the same change set set: the sibling a field row asks for when the op is a single
+ /// leaf (a drop's dataId without its kind).
+ ///
+ private sealed class SiblingOps
+ {
+ private readonly ModChangeSet _changeSet;
+ private Dictionary<(RecordKey Key, string Path), JToken?>? _values;
+
+ public SiblingOps(ModChangeSet changeSet)
+ {
+ _changeSet = changeSet;
+ }
+
+ /// False when the change set has no op there, so the value is vanilla's and unknown here.
+ public bool TryGet(RecordKey key, string path, out JToken? value)
+ {
+ _values ??= _changeSet.Ops
+ .GroupBy(op => (op.Key, op.Path))
+ .ToDictionary(group => group.Key, group => group.Last().Value);
+ return _values.TryGetValue((key, path), out value);
+ }
+ }
+
+ ///
+ /// One walk over one op's value. The path is kept as segments relative to the record (or to the root of an
+ /// object file) and turned into a pattern only at a leaf whose name a field row ends in, so a map's tile data
+ /// builds no strings.
+ ///
+ private sealed class Walker
+ {
+ private readonly ChangeOp _op;
+ private readonly SiblingOps _siblings;
+ private readonly bool _dualWield;
+ private readonly bool _mz;
+ private readonly Action _emit;
+ private bool _inComment;
+ private readonly string _table;
+ private readonly bool _isMap;
+ private readonly List _path;
+
+ public Walker(ChangeOp op, SiblingOps siblings, bool dualWield, bool mz, Action emit)
+ {
+ _op = op;
+ _siblings = siblings;
+ _dualWield = dualWield;
+ _mz = mz;
+ _emit = emit;
+ _table = RpgDataSchema.TableOf(op.Key.File);
+ _isMap = RpgDataSchema.IsMapFile(op.Key.File);
+ _path = MergePath.Parse(op.Path).ToList();
+ }
+
+ public void Walk(JToken value)
+ {
+ if (_op.Key.File == RpgDataSchema.PluginListKey)
+ {
+ WalkPluginList(value);
+ return;
+ }
+
+ bool recordsFile = RpgDataSchema.DatabaseKindOf(_op.Key.File) is not null || _op.Key.File == RpgDataSchema.MapInfosKey;
+ if (_op.Key.IsWholeFile && _path.Count == 0 && recordsFile && value is JArray records)
+ {
+ // A whole records file: each element is a record, and paths start again inside it.
+ foreach (JToken record in records)
+ {
+ Visit(record, null, null, isRoot: false);
+ }
+
+ return;
+ }
+
+ Visit(value, LastName(_path), null, isRoot: true);
+ }
+
+ /// Plugin parameters the mod sets are free text (GR-R9), whether the op names one or the whole entry.
+ private void WalkPluginList(JToken value)
+ {
+ if (_path.Count > 0 && _path[0].Name == ParametersProperty)
+ {
+ _emit(new Hit(HitUse.FreeText, default, value));
+ return;
+ }
+
+ foreach (JToken parameters in value.SelectTokens("$.." + ParametersProperty))
+ {
+ _emit(new Hit(HitUse.FreeText, default, parameters));
+ }
+ }
+
+ /// The token at .
+ /// The property name of the token, or of its array for an element.
+ /// The object that holds the token as a property, when it is part of this value.
+ /// True for the op's own value, whose siblings are other ops.
+ private void Visit(JToken token, string? name, JObject? parent, bool isRoot)
+ {
+ switch (token)
+ {
+ case JObject item:
+ bool wasComment = _inComment;
+ if (TryCommand(item, out int code, out JArray? parameters))
+ {
+ VisitCommand(code, parameters);
+ _inComment = code is CommentCode or CommentMoreCode;
+ }
+
+ foreach (JProperty property in item.Properties())
+ {
+ _path.Add(PathSegment.Property(property.Name));
+ Visit(property.Value, property.Name, item, isRoot: false);
+ _path.RemoveAt(_path.Count - 1);
+ }
+
+ _inComment = wasComment;
+ break;
+ case JArray list when _isMap && _op.Key.IsWholeFile && _path.Count == 1 && _path[0].Name == RpgDataSchema.EventsProperty:
+ // A whole map's events are records: paths start again inside each one.
+ _path.Clear();
+ foreach (JToken record in list)
+ {
+ Visit(record, null, null, isRoot: false);
+ }
+
+ _path.Add(PathSegment.Property(RpgDataSchema.EventsProperty));
+ break;
+ case JArray list:
+ for (int index = 0; index < list.Count; index++)
+ {
+ _path.Add(PathSegment.At(index));
+ Visit(list[index], name, null, isRoot: false);
+ _path.RemoveAt(_path.Count - 1);
+ }
+
+ break;
+ case JValue { Type: JTokenType.String } text:
+ if (name == NoteProperty || (name == FormulaProperty && _path.Count > 1 && _path[^2].Name == DamageProperty))
+ {
+ _emit(new Hit(HitUse.FreeText, default, text));
+ }
+
+ _emit(new Hit(_inComment ? HitUse.Comment : HitUse.Text, default, text));
+ if (name is not null && ReferenceTable.MayBeField(name))
+ {
+ VisitField(text, parent, isRoot);
+ }
+
+ break;
+ case JValue { Type: JTokenType.Integer or JTokenType.Float } number when name is not null && ReferenceTable.MayBeField(name):
+ VisitField(number, parent, isRoot);
+ break;
+ case JValue { Type: JTokenType.Integer } number when isRoot && name is not null && ReferenceTable.MayBeSibling(name):
+ VisitSibling(number);
+ break;
+ }
+ }
+
+ private void VisitCommand(int code, JArray parameters)
+ {
+ foreach (CommandPlace row in ReferenceTable.Commands(code))
+ {
+ if (!row.When.All(test => Holds(parameters, test)))
+ {
+ continue;
+ }
+
+ JToken? place = At(parameters, row.Index);
+ switch (row.Use)
+ {
+ 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));
+ break;
+ case PlaceUse.Id when place is JValue value && row.Kind is { } kind:
+ // Outside a map the event commands act on whatever map is loaded, so their ids are no map's (3.11).
+ EmitId(kind, value, row.SecondSlot, scoped: kind != IdKind.MapEvent || _isMap);
+ break;
+ case PlaceUse.FreeText when place is not null:
+ _emit(new Hit(HitUse.FreeText, default, place));
+ break;
+ case PlaceUse.Constant when place is not null:
+ _emit(new Hit(HitUse.Constant, default, place));
+ break;
+ case PlaceUse.RandomRange when place is JValue low && At(parameters, row.Index + 1) is JValue high:
+ _emit(new Hit(HitUse.RandomRange, default, new JArray(low.DeepClone(), high.DeepClone())));
+ break;
+ case PlaceUse.ByVariable when row.Kind is { } kind:
+ _emit(new Hit(HitUse.ByVariable, kind, parameters));
+ break;
+ }
+ }
+ }
+
+ private void VisitField(JValue number, JObject? parent, bool isRoot)
+ {
+ IReadOnlyList rows = ReferenceTable.Fields(_table, Pattern(_path));
+ if (rows.Count == 0)
+ {
+ return;
+ }
+
+ int last = _path[^1].Name is null ? _path[^1].Index : 0;
+ foreach (FieldPlace row in rows.Where(item => last >= item.MinIndex && last <= item.MaxIndex))
+ {
+ if (row.When is null)
+ {
+ EmitId(row.Kind, number, row.SecondSlot, scoped: true);
+ }
+ else if (!TrySibling(row.When.Sibling, parent, isRoot, out int? sibling))
+ {
+ // The sibling is vanilla's, which this walk cannot see: the id may be of any kind the rows name.
+ _emit(new Hit(HitUse.Ambiguous, row.Kind, number));
+ }
+ else if (sibling is { } known && row.When.Values.Contains(known))
+ {
+ EmitId(row.Kind, number, row.SecondSlot, scoped: true);
+ }
+ }
+ }
+
+ ///
+ /// A leaf op that sets only a deciding sibling (a drop's kind): when no op sets the id beside it, the id
+ /// is vanilla's, and it now names the row's kind without this walk seeing which id it is.
+ ///
+ private void VisitSibling(JValue number)
+ {
+ IReadOnlyList rows = ReferenceTable.FieldsBySibling(_table, Pattern(_path));
+ if (rows.Count == 0 || !TryInt(number, out int sibling))
+ {
+ return;
+ }
+
+ string parentPath = MergePath.Format(_path.Take(_path.Count - 1));
+ foreach (FieldPlace row in rows.Where(item => item.When!.Values.Contains(sibling)))
+ {
+ if (!_siblings.TryGet(_op.Key, MergePath.Child(parentPath, ReferenceTable.FieldName(row)), out _))
+ {
+ _emit(new Hit(HitUse.UnknownId, row.Kind, number));
+ }
+ }
+ }
+
+ ///
+ /// An id of a known kind, unless the place is no map's, the slot may hold either kind, or the id is not stored
+ /// as an integer, which a remap does not rewrite.
+ ///
+ private void EmitId(IdKind kind, JValue value, bool secondSlot, bool scoped)
+ {
+ if (!scoped || value.Type != JTokenType.Integer)
+ {
+ _emit(new Hit(HitUse.Ambiguous, kind, value));
+ }
+ else if (secondSlot && _dualWield)
+ {
+ _emit(new Hit(HitUse.Ambiguous, IdKind.Weapon, value));
+ _emit(new Hit(HitUse.Ambiguous, IdKind.Armor, value));
+ }
+ else
+ {
+ _emit(new Hit(HitUse.Id, kind, value));
+ }
+ }
+
+ ///
+ /// The whole number in the sibling property , null when it holds none. False
+ /// when the leaf is the op's whole value and no other op sets the sibling.
+ ///
+ private bool TrySibling(string name, JObject? parent, bool isRoot, out int? sibling)
+ {
+ JToken? token = parent?[name];
+ if (parent is null && isRoot && _path.Count > 0)
+ {
+ string path = MergePath.Child(MergePath.Format(_path.Take(_path.Count - 1)), name);
+ if (!_siblings.TryGet(_op.Key, path, out token))
+ {
+ sibling = null;
+ return false;
+ }
+ }
+
+ sibling = token is JValue value && TryInt(value, out int whole) ? whole : null;
+ return true;
+ }
+
+ private static string? LastName(List path)
+ {
+ for (int index = path.Count - 1; index >= 0; index--)
+ {
+ if (path[index].Name is { } name)
+ {
+ return name;
+ }
+ }
+
+ return null;
+ }
+
+ private static string Pattern(List path)
+ {
+ var builder = new StringBuilder();
+ foreach (PathSegment segment in path)
+ {
+ if (segment.Name is null)
+ {
+ builder.Append("[*]");
+ }
+ else
+ {
+ builder.Append(builder.Length == 0 ? "" : ".").Append(segment.Name);
+ }
+ }
+
+ return builder.ToString();
+ }
+ }
}
diff --git a/RPGModder.Core/Merge/ReferenceTable.cs b/RPGModder.Core/Merge/ReferenceTable.cs
new file mode 100644
index 0000000..11df4c1
--- /dev/null
+++ b/RPGModder.Core/Merge/ReferenceTable.cs
@@ -0,0 +1,349 @@
+namespace RPGModder.Core.Merge;
+
+///
+/// The reference table of guide 3.11 as rows: where an id sits in an event command () and in a
+/// record field (), and the text codes that name one ().
+/// walks a change set once with these rows, to scan and to rewrite. p[n] is
+/// parameters[n]; only values above 0 are ids. Every command row was checked against the MV and MZ core scripts.
+///
+internal static class ReferenceTable
+{
+ private const string Map = RpgDataSchema.MapTable;
+ private const string Actors = "actors.json";
+ private const string Classes = "classes.json";
+ private const string Skills = "skills.json";
+ private const string Items = "items.json";
+ private const string Weapons = "weapons.json";
+ private const string Armors = "armors.json";
+ private const string Enemies = "enemies.json";
+ private const string States = "states.json";
+ private const string Troops = "troops.json";
+ private const string MapInfos = "mapinfos.json";
+ private const string SystemFile = "system.json";
+
+ /// The files whose records carry traits; an enemy's traits use the same codes.
+ private static readonly string[] TraitFiles = [Actors, Classes, Weapons, Armors, Enemies, States];
+
+ private static readonly CommandPlace[] CommandRows =
+ [
+ // Map events: rewritten in the map's own file, ambiguous anywhere else (they act on whatever map is loaded).
+ Id(IdKind.MapEvent, 203, 0), // Set Event Location
+ Id(IdKind.MapEvent, 203, 2, Is(1, 2)), // ... exchanged with another event
+ Id(IdKind.MapEvent, 205, 0), // Set Movement Route
+ Id(IdKind.MapEvent, 212, 0), // Show Animation
+ Id(IdKind.MapEvent, 213, 0), // Show Balloon Icon
+ Id(IdKind.MapEvent, 111, 1, Is(0, 6)), // Conditional Branch: character
+ Id(IdKind.MapEvent, 122, 5, Is(3, 3), Is(4, 5)), // Control Variables: game data, character
+ Id(IdKind.MapEvent, 285, 3, Is(2, 2)) with { MzOnly = true }, // Get Location Info: by character (MV: by variable)
+
+ // 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
+ 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
+
+ // Items.
+ Id(IdKind.Item, 126, 0), // Change Items
+ Id(IdKind.Item, 111, 1, Is(0, 8)),
+ Id(IdKind.Item, 122, 5, Is(3, 3), Is(4, 0)),
+ Id(IdKind.Item, 302, 1, Is(0, 0)), // Shop Processing
+ Id(IdKind.Item, 605, 1, Is(0, 0)), // ... its further goods
+
+ // Weapons.
+ Id(IdKind.Weapon, 127, 0), // Change Weapons
+ Id(IdKind.Weapon, 111, 1, Is(0, 9)),
+ Id(IdKind.Weapon, 111, 3, Is(0, 4), Is(2, 4)),
+ Id(IdKind.Weapon, 122, 5, Is(3, 3), Is(4, 1)),
+ Id(IdKind.Weapon, 302, 1, Is(0, 1)),
+ Id(IdKind.Weapon, 605, 1, Is(0, 1)),
+ Id(IdKind.Weapon, 319, 2, Is(1, 1)), // Change Equipment, equip type 1
+
+ // Armors. Equip type 2 is a weapon slot for a dual-wield actor (trait 55), so that row is a second slot.
+ Id(IdKind.Armor, 128, 0), // Change Armors
+ Id(IdKind.Armor, 111, 1, Is(0, 10)),
+ Id(IdKind.Armor, 111, 3, Is(0, 4), Is(2, 5)),
+ Id(IdKind.Armor, 122, 5, Is(3, 3), Is(4, 2)),
+ Id(IdKind.Armor, 302, 1, Is(0, 2)),
+ Id(IdKind.Armor, 605, 1, Is(0, 2)),
+ new(319, 2, PlaceUse.Id, IdKind.Armor, [Is(1, 2)], SecondSlot: true),
+ Id(IdKind.Armor, 319, 2, new ParameterTest(1, 3, int.MaxValue)),
+
+ // Skills.
+ Id(IdKind.Skill, 318, 3), // Change Skill
+ Id(IdKind.Skill, 339, 2), // Force Action
+ Id(IdKind.Skill, 111, 3, Is(0, 4), Is(2, 3)),
+
+ // States.
+ Id(IdKind.State, 313, 3), // Change State
+ Id(IdKind.State, 333, 2), // Change Enemy State
+ Id(IdKind.State, 111, 3, Is(0, 4), Is(2, 6)),
+ Id(IdKind.State, 111, 3, Is(0, 5), Is(2, 1)),
+
+ // Enemies, troops, common events.
+ Id(IdKind.Enemy, 336, 1), // Enemy Transform
+ Id(IdKind.Troop, 301, 1, Is(0, 0)), // Battle Processing, direct
+ 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.
+ Id(IdKind.Actor, 129, 0), // Change Party Member
+ Id(IdKind.Actor, 303, 0), // Name Input Processing
+ Id(IdKind.Actor, 111, 1, Is(0, 4)),
+ Id(IdKind.Actor, 122, 5, Is(3, 3), Is(4, 3)),
+ Id(IdKind.Actor, 311, 1, Is(0, 0)),
+ Id(IdKind.Actor, 312, 1, Is(0, 0)),
+ Id(IdKind.Actor, 313, 1, Is(0, 0)),
+ Id(IdKind.Actor, 314, 1, Is(0, 0)),
+ Id(IdKind.Actor, 315, 1, Is(0, 0)),
+ Id(IdKind.Actor, 316, 1, Is(0, 0)),
+ 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)),
+ 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
+
+ // Classes, animations, tilesets.
+ Id(IdKind.Class, 321, 1),
+ Id(IdKind.Class, 111, 3, Is(0, 4), Is(2, 2)),
+ Id(IdKind.Animation, 212, 1), // Show Animation
+ Id(IdKind.Animation, 337, 1), // Show Battle Animation
+ Id(IdKind.Tileset, 282, 0), // Change Tileset
+
+ // 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
+ FreeText(356, 0), // Plugin Command (MV)
+ FreeText(357, 3), // Plugin Command (MZ): the arguments
+ FreeText(45, 0), // Script in a move route
+ FreeText(111, 1, Is(0, 12)), // Conditional Branch: script
+ FreeText(122, 4, Is(3, 4)) // Control Variables: script
+ ];
+
+ private static readonly FieldPlace[] FieldRows =
+ [
+ // Maps.
+ new([MapInfos], "parentId", IdKind.Map),
+ new([SystemFile], "startMapId", IdKind.Map),
+ new([SystemFile], "boat.startMapId", IdKind.Map),
+ new([SystemFile], "ship.startMapId", IdKind.Map),
+ new([SystemFile], "airship.startMapId", IdKind.Map),
+
+ // A map's own fields, and its events' page conditions.
+ new([Map], "tilesetId", IdKind.Tileset),
+ new([Map], "encounterList[*].troopId", IdKind.Troop),
+ new([Map], "pages[*].conditions.itemId", IdKind.Item),
+ new([Map], "pages[*].conditions.actorId", IdKind.Actor),
+
+ // Database records.
+ new([Actors], "classId", IdKind.Class),
+ new([Actors], "equips[*]", IdKind.Weapon, MaxIndex: 0),
+ new([Actors], "equips[*]", IdKind.Armor, MinIndex: 1, MaxIndex: 1, SecondSlot: true),
+ new([Actors], "equips[*]", IdKind.Armor, MinIndex: 2),
+ new([Classes], "learnings[*].skillId", IdKind.Skill),
+ 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], "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),
+
+ // 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])),
+ new(TraitFiles, "traits[*].dataId", IdKind.Skill, new FieldTest("code", [35, 43, 44])),
+
+ // Effects 21 and 22 name a state, 43 a skill, 44 a common event.
+ new([Skills, Items], "effects[*].dataId", IdKind.State, new FieldTest("code", [21, 22])),
+ new([Skills, Items], "effects[*].dataId", IdKind.Skill, new FieldTest("code", [43])),
+ new([Skills, Items], "effects[*].dataId", IdKind.CommonEvent, new FieldTest("code", [44])),
+
+ // System: the starting party and the battle test.
+ new([SystemFile], "partyMembers[*]", IdKind.Actor),
+ new([SystemFile], "testBattlers[*].actorId", IdKind.Actor),
+ new([SystemFile], "testBattlers[*].equips[*]", IdKind.Weapon, MaxIndex: 0),
+ new([SystemFile], "testBattlers[*].equips[*]", IdKind.Armor, MinIndex: 1, MaxIndex: 1, SecondSlot: true),
+ new([SystemFile], "testBattlers[*].equips[*]", IdKind.Armor, MinIndex: 2),
+ new([SystemFile], "testTroopId", IdKind.Troop)
+ ];
+
+ private static readonly ILookup CommandsByCode = CommandRows.ToLookup(row => row.Code);
+
+ private static readonly Dictionary<(string Table, string Pattern), FieldPlace[]> FieldsByPlace = FieldRows
+ .SelectMany(row => row.Tables.Select(table => (Table: table, Row: row)))
+ .GroupBy(pair => (pair.Table, pair.Row.Pattern))
+ .ToDictionary(group => group.Key, group => group.Select(pair => pair.Row).ToArray());
+
+ /// The last property name of every field pattern; a leaf under any other name is no field reference.
+ private static readonly HashSet FieldNames = new(FieldRows.Select(row => LastName(row.Pattern)), StringComparer.Ordinal);
+
+ /// The rows whose deciding sibling sits at a pattern (dropItems[*].kind for a drop's dataId).
+ private static readonly Dictionary<(string Table, string Pattern), FieldPlace[]> FieldsBySiblingPlace = FieldRows
+ .Where(row => row.When is not null)
+ .SelectMany(row => row.Tables.Select(table => (Table: table, Row: row)))
+ .GroupBy(pair => (pair.Table, SiblingPattern(pair.Row)))
+ .ToDictionary(group => group.Key, group => group.Select(pair => pair.Row).ToArray());
+
+ 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.
+ public static IReadOnlyDictionary TextCodes { get; } =
+ new Dictionary(StringComparer.Ordinal) { ["N"] = IdKind.Actor };
+
+ ///
+ /// The text codes with a number that the MV and MZ message windows read themselves: a variable, an actor, a party
+ /// member, a color, an icon, a position and a font size. A code with a number and other letters is a plugin's,
+ /// and may name any id (GR-R9).
+ ///
+ public static IReadOnlySet BuiltInTextCodes { get; } =
+ new HashSet(StringComparer.Ordinal) { "V", "N", "P", "C", "I", "PX", "PY", "FS" };
+
+ /// The rows for event command .
+ public static IEnumerable Commands(int code)
+ {
+ return CommandsByCode[code];
+ }
+
+ ///
+ /// True when a leaf named (or the elements of an array named so) can be a field
+ /// reference, so the walker builds its path only then.
+ ///
+ public static bool MayBeField(string name)
+ {
+ return FieldNames.Contains(name);
+ }
+
+ /// The rows for a leaf of table whose path has the pattern .
+ public static IReadOnlyList Fields(string table, string pattern)
+ {
+ return FieldsByPlace.TryGetValue((table, pattern), out FieldPlace[]? rows) ? rows : [];
+ }
+
+ /// True when a leaf named can decide the kind of a field row's id.
+ public static bool MayBeSibling(string name)
+ {
+ return SiblingNames.Contains(name);
+ }
+
+ /// The rows whose deciding sibling is the leaf of table at .
+ public static IReadOnlyList FieldsBySibling(string table, string pattern)
+ {
+ return FieldsBySiblingPlace.TryGetValue((table, pattern), out FieldPlace[]? rows) ? rows : [];
+ }
+
+ /// The property name of the id a field row reads (dataId for dropItems[*].dataId).
+ public static string FieldName(FieldPlace row)
+ {
+ return LastName(row.Pattern);
+ }
+
+ private static CommandPlace Id(IdKind kind, int code, int index, params ParameterTest[] when)
+ {
+ return new CommandPlace(code, index, PlaceUse.Id, kind, when);
+ }
+
+ /// A command that names an id of through a variable (3.11).
+ private static CommandPlace ByVariable(IdKind kind, int code, params ParameterTest[] when)
+ {
+ return new CommandPlace(code, 0, PlaceUse.ByVariable, kind, when);
+ }
+
+ private static CommandPlace FreeText(int code, int index, params ParameterTest[] when)
+ {
+ return new CommandPlace(code, index, PlaceUse.FreeText, null, when);
+ }
+
+ private static ParameterTest Is(int index, int value)
+ {
+ return new ParameterTest(index, value, value);
+ }
+
+ private static string SiblingPattern(FieldPlace row)
+ {
+ int dot = row.Pattern.LastIndexOf('.');
+ return (dot < 0 ? "" : row.Pattern[..(dot + 1)]) + row.When!.Sibling;
+ }
+
+ private static string LastName(string pattern)
+ {
+ string trimmed = pattern.EndsWith("[*]", StringComparison.Ordinal) ? pattern[..^3] : pattern;
+ int dot = trimmed.LastIndexOf('.');
+ return dot < 0 ? trimmed : trimmed[(dot + 1)..];
+ }
+}
+
+/// What a place of the reference table holds.
+internal enum PlaceUse
+{
+ /// An id of the row's kind; rewritten when that id moves.
+ Id,
+
+ /// Text a remap cannot rewrite (GR-R9).
+ FreeText,
+
+ /// A constant Control Variables assigns; with a by-variable row it may be that row's id (3.11).
+ Constant,
+
+ ///
+ /// The low end of a random range Control Variables assigns, the next parameter being the high end; with a
+ /// by-variable row any id in it may be that row's id.
+ ///
+ RandomRange,
+
+ ///
+ /// 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
+}
+
+///
+/// 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.
+///
+internal sealed record CommandPlace(
+ int Code,
+ int Index,
+ PlaceUse Use,
+ IdKind? Kind,
+ ParameterTest[] When,
+ bool SecondSlot = false,
+ bool MzOnly = false);
+
+/// Parameter Index holds a whole number from Min to Max.
+internal readonly record struct ParameterTest(int Index, int Min, int Max);
+
+///
+/// One field row: the leaves of Tables whose path pattern is Pattern (relative to the record, or to
+/// the root of an object file). A pattern ending in [*] can limit the last index. When asks a sibling
+/// property of the leaf for one of its values.
+///
+internal sealed record FieldPlace(
+ string[] Tables,
+ string Pattern,
+ IdKind Kind,
+ FieldTest? When = null,
+ int MinIndex = 0,
+ int MaxIndex = int.MaxValue,
+ bool SecondSlot = false);
+
+/// The sibling property Sibling holds one of Values.
+internal sealed record FieldTest(string Sibling, int[] Values);
diff --git a/RPGModder.Core/Merge/RemapPlaces.cs b/RPGModder.Core/Merge/RemapPlaces.cs
index 9a46a41..fdccbdb 100644
--- a/RPGModder.Core/Merge/RemapPlaces.cs
+++ b/RPGModder.Core/Merge/RemapPlaces.cs
@@ -5,7 +5,8 @@ internal static class RemapPlaces
{
///
/// 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.
+ /// 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.
///
public static bool Settles(IdRemap remap, Collision collision)
{
@@ -20,7 +21,7 @@ public static bool Settles(IdRemap remap, Collision collision)
IdKind.MapEvent => key.File == remap.Scope && key.Record == RecordKey.ForEvent(remap.FromId),
IdKind.Map => (key.File == RpgDataSchema.MapKey(remap.FromId) && key.IsWholeFile) ||
(key.File == RpgDataSchema.MapInfosKey && key.Record == RecordKey.ForIndex(remap.FromId)),
- _ => false
+ _ => RpgDataSchema.DatabaseFileOf(remap.Kind) is { } file && key.File == file && key.Record == RecordKey.ForIndex(remap.FromId)
};
}
}
diff --git a/RPGModder.Core/Merge/RemapPlan.cs b/RPGModder.Core/Merge/RemapPlan.cs
index 513bea1..0e761b7 100644
--- a/RPGModder.Core/Merge/RemapPlan.cs
+++ b/RPGModder.Core/Merge/RemapPlan.cs
@@ -8,7 +8,8 @@ namespace RPGModder.Core.Merge;
/// deployed (GR-R12). Offers are moves the planner did not make because the old id appears in a plugin file
/// the mod ships (GR-R11); lane A passes them to and appends one when the player
/// chooses . Diagnostics holds rules.remap_target_taken, one per
-/// recorded entry whose target vanilla now uses; carries them into the plan.
+/// 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.
///
public sealed record RemapPlan(
IReadOnlyList Remaps,
diff --git a/RPGModder.Core/Merge/RemapTable.cs b/RPGModder.Core/Merge/RemapTable.cs
index db03ba6..8e944c1 100644
--- a/RPGModder.Core/Merge/RemapTable.cs
+++ b/RPGModder.Core/Merge/RemapTable.cs
@@ -3,10 +3,28 @@ namespace RPGModder.Core.Merge;
/// One mod's moves, old id to new id, applied together so no move feeds another.
internal sealed class RemapTable
{
- public Dictionary Maps { get; } = new();
+ /// The moves of every kind but , whose ids are one per map.
+ public Dictionary> Global { get; } = new();
/// Event moves by map file key.
public Dictionary> Events { get; } = new(StringComparer.Ordinal);
- public bool IsEmpty => Maps.Count == 0 && Events.Count == 0;
+ public bool IsEmpty => Global.Values.All(moves => moves.Count == 0) && Events.Values.All(moves => moves.Count == 0);
+
+ /// The moves of , or null when none of that kind moves.
+ public Dictionary? MovesOf(IdKind kind)
+ {
+ return Global.GetValueOrDefault(kind);
+ }
+
+ /// The moves an entry of and joins, made on first use.
+ public Dictionary For(IdKind kind, string scope)
+ {
+ if (kind == IdKind.MapEvent)
+ {
+ return Events.TryGetValue(scope, out Dictionary? events) ? events : Events[scope] = new Dictionary();
+ }
+
+ return Global.TryGetValue(kind, out Dictionary? moves) ? moves : Global[kind] = new Dictionary();
+ }
}
diff --git a/RPGModder.Core/Merge/RpgDataSchema.cs b/RPGModder.Core/Merge/RpgDataSchema.cs
index 25d2413..af225d8 100644
--- a/RPGModder.Core/Merge/RpgDataSchema.cs
+++ b/RPGModder.Core/Merge/RpgDataSchema.cs
@@ -43,18 +43,35 @@ public static class RpgDataSchema
///
private const int MapEventIdLimit = 999;
+ ///
+ /// The highest database record id the MZ 1.10.0 editor gives (GR-R6): its Change Maximum box stops at 9999, on
+ /// every database tab.
+ ///
+ private const int MzRecordIdLimit = 9999;
+
+ ///
+ /// The highest database record id a move gives on MV and on an unknown engine (GR-R6). The MV editor was not
+ /// checked, so this is the lower limit of the editors before it: a move that stays a choice is the safe side.
+ ///
+ private const int MvRecordIdLimit = 999;
+
/// The config save forms 2a decodes (GR-M10); config.save gives merge.config_save_unsupported.
private const string MvConfigSave = "config.rpgsave";
private const string MzConfigSave = "config.rmmzsave";
+ private const string DataFolder = "data/";
private const string SystemFile = "system.json";
private const string MapInfosFile = "mapinfos.json";
private const string MapPrefix = "data/map";
private const string JsonSuffix = ".json";
/// The policy table name every MapNNN.json shares; no real file name has angle brackets.
- private const string MapTable = "