From ff58d369f53e89a849875f4be2431bcf1095680c Mon Sep 17 00:00:00 2001 From: Catherine Sangiovanni Date: Wed, 25 Nov 2026 02:14:48 -0500 Subject: [PATCH] launcher: merge a mod's copy of a frame rate variant's file into the variant's A files mod that ships one of a variant's game data files does nothing at that frame rate. On ACNH at 60 fps, ACNH Combined's River Hopping stops at the bank; at Game owned it crosses. Cause: the variant's romfs goes first in DM_ROMFS_OVERLAY and the first root that has a file wins. The 60 fps variant ships Pack/StaticParam.pack, and so does River Hopping (one float in Param/Actor/PlayerActor.byml, 35 to 100), so the variant's copy hid the mod's whole file. Fix: the pack step keeps the originals the variant was made from in //romfs-orig (romfs_rows.make orig_out, Pack.variantOriginals). At a start, dev.peanuts.mods.VariantMerge merges each enabled mod's copy into a copy of the variant's file, three ways against the original: a value the mod changed is written unless the variant changed it too. SARC entries are matched by name and BYML values by path, so a mod made from another game version still merges; other same-size data merges by changed runs. The merged files go first in the overlay, and each shared file gets a log line. Checks: test_pack_android_variants (VariantMergeJvm, Overlays), test_docs. On the real files (3.0.3 StaticParam.pack, the variant's, ACNH Combined's): 5 values merged in 66 ms on a PC JVM, none kept, none left out. --- .../nxnative/android/FpsVariantJvmTest.java | 2 + .../dev/peanuts/mods/VariantMergeJvmTest.java | 285 ++++++++++++++++ .../dev/nxnative/android/GameActivity.java | 7 +- .../main/java/dev/nxnative/android/Pack.java | 7 + .../java/dev/peanuts/mods/ModRuntime.java | 3 + .../java/dev/peanuts/mods/VariantMerge.java | 306 ++++++++++++++++++ dm/games/01006F8002326000/README.md | 4 + dm/tools/romfs_rows.py | 24 +- dm/tools/tests/test_pack_android_variants.py | 18 ++ docs/agents/symptoms.md | 1 + docs/reference/packing.md | 9 + scripts/pack_android.py | 9 +- 12 files changed, 660 insertions(+), 15 deletions(-) create mode 100644 android/app/src/jvmtest/java/dev/peanuts/mods/VariantMergeJvmTest.java create mode 100644 android/app/src/main/java/dev/peanuts/mods/VariantMerge.java diff --git a/android/app/src/jvmtest/java/dev/nxnative/android/FpsVariantJvmTest.java b/android/app/src/jvmtest/java/dev/nxnative/android/FpsVariantJvmTest.java index 3615954a..2f2a5b11 100644 --- a/android/app/src/jvmtest/java/dev/nxnative/android/FpsVariantJvmTest.java +++ b/android/app/src/jvmtest/java/dev/nxnative/android/FpsVariantJvmTest.java @@ -44,6 +44,8 @@ public static void main(String[] args) throws Exception { check(pk.variantReady("60") && new File(pack, "60/romfs").equals(pk.variantRomfs("60")), "ready, with its overlay: " + pk.variantRomfs("60")); check(pk.variantRomfs("evil") == null && pk.variantRomfs("none") == null && pk.variantRomfs("gone") == null, "never outside the pack, '-' is none"); check(!pk.variantReady("43") && !pk.variantReady(null), "no row: not ready"); + check(pk.variantOriginals("60") == null && pk.variantOriginals("none") == null, "an older pack: no originals to merge a mod's copy against"); + check(new File(pack, "60/romfs-orig").mkdirs() && new File(pack, "60/romfs-orig").equals(pk.variantOriginals("60")), "the originals beside the overlay: " + pk.variantOriginals("60")); Files.write(new File(pack, "pack.tsv").toPath(), head.getBytes(StandardCharsets.UTF_8)); check(!Pack.read(pack).variantReady("60"), "a pack without the row (another version, an older pack) is not ready though its 60/main is there"); System.out.println("ok"); diff --git a/android/app/src/jvmtest/java/dev/peanuts/mods/VariantMergeJvmTest.java b/android/app/src/jvmtest/java/dev/peanuts/mods/VariantMergeJvmTest.java new file mode 100644 index 00000000..e83de20e --- /dev/null +++ b/android/app/src/jvmtest/java/dev/peanuts/mods/VariantMergeJvmTest.java @@ -0,0 +1,285 @@ +package dev.peanuts.mods; // PEANUTS: a frame rate variant's files merged with the mods' copies (VariantMerge) + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * VariantMerge on the JVM, driven by dm/tools/tests/test_pack_android_variants.py. args[0]: an empty folder. Prints "ok" or throws. The files are made up + * here (a SARC of BYML documents and a table, in the layout Animal Crossing's StaticParam.pack has), never game data. Covers a value the mod changes, one + * both change, a mod laid out differently (another game version), two mods on one value, strings, same-size data, a pack without originals, a mod file + * like the original and one that does not parse. + */ +public final class VariantMergeJvmTest { + static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); } + + // ---- made-up files ---- + + /** A BYML v2 document of a root dictionary; values: Float, Integer, String, a Map (a dictionary) or a List (an array); keys and strings in the order given */ + static byte[] byml(Map root) { + List keys = new ArrayList<>(), strings = new ArrayList<>(); + collect(root, keys, strings); + java.util.Collections.sort(keys); java.util.Collections.sort(strings); // the tables are sorted, as the game's are + ByteArrayOutputStream body = new ByteArrayOutputStream(); + int keyAt = 16; + byte[] kt = table(keys), st = table(strings); + int strAt = keyAt + kt.length, rootAt = strAt + st.length; + Out o = new Out(rootAt); + o.node(root, keys, strings); + ByteBuffer h = le(16); + h.put((byte) 'Y').put((byte) 'B').putShort((short) 2).putInt(keyAt).putInt(strings.isEmpty() ? 0 : strAt).putInt(rootAt); + body.writeBytes(h.array()); body.writeBytes(kt); body.writeBytes(st); body.writeBytes(o.bytes()); + return body.toByteArray(); + } + + @SuppressWarnings("unchecked") + static void collect(Object v, List keys, List strings) { + if (v instanceof Map) for (Map.Entry e : ((Map) v).entrySet()) { if (!keys.contains(e.getKey())) keys.add(e.getKey()); collect(e.getValue(), keys, strings); } + else if (v instanceof List) for (Object x : (List) v) collect(x, keys, strings); + else if (v instanceof String && !strings.contains(v)) strings.add((String) v); + } + + static byte[] table(List names) { + if (names.isEmpty()) return new byte[0]; + ByteArrayOutputStream s = new ByteArrayOutputStream(); + int head = 4 + 4 * (names.size() + 1), at = head; + List offs = new ArrayList<>(); + for (String n : names) { offs.add(at); byte[] b = n.getBytes(StandardCharsets.UTF_8); s.writeBytes(b); s.write(0); at += b.length + 1; } + while (at % 4 != 0) { s.write(0); at++; } + ByteBuffer h = le(head); + h.putInt(0xC2 | names.size() << 8); + for (int x : offs) h.putInt(x); + h.putInt(at); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.writeBytes(h.array()); out.writeBytes(s.toByteArray()); + return out.toByteArray(); + } + + /** Containers written depth first, each after its parent, at 4-byte alignment */ + static final class Out { + final int base; + ByteArrayOutputStream b = new ByteArrayOutputStream(); + Out(int base) { this.base = base; } + byte[] bytes() { return b.toByteArray(); } + int pos() { return base + b.size(); } + + @SuppressWarnings("unchecked") + int node(Object v, List keys, List strings) { + int at = pos(); + if (v instanceof Map) { + Map m = (Map) v; + List ks = new ArrayList<>(m.keySet()); + ks.sort((x, y) -> Integer.compare(keys.indexOf(x), keys.indexOf(y))); // a dictionary's entries in key table order + ByteBuffer n = le(4 + 8 * ks.size()); + n.putInt(0xC1 | ks.size() << 8); + int[] fix = new int[ks.size()]; + for (int i = 0; i < ks.size(); i++) { Object x = m.get(ks.get(i)); n.putInt(keys.indexOf(ks.get(i)) | type(x) << 24); fix[i] = n.position(); n.putInt(scalar(x, strings)); } + b.writeBytes(n.array()); + for (int i = 0; i < ks.size(); i++) { Object x = m.get(ks.get(i)); if (x instanceof Map || x instanceof List) patch(at + fix[i] - base, node(x, keys, strings)); } + } else { + List l = (List) v; + int pad = (4 + l.size() + 3) & ~3; + ByteBuffer n = le(pad + 4 * l.size()); + n.putInt(0xC0 | l.size() << 8); + for (Object x : l) n.put((byte) type(x)); + n.position(pad); + int[] fix = new int[l.size()]; + for (int i = 0; i < l.size(); i++) { fix[i] = n.position(); n.putInt(scalar(l.get(i), strings)); } + b.writeBytes(n.array()); + for (int i = 0; i < l.size(); i++) { Object x = l.get(i); if (x instanceof Map || x instanceof List) patch(at + fix[i] - base, node(x, keys, strings)); } + } + return at; + } + + void patch(int rel, int value) { byte[] a = b.toByteArray(); ByteBuffer.wrap(a).order(ByteOrder.LITTLE_ENDIAN).putInt(rel, value); b = new ByteArrayOutputStream(); b.writeBytes(a); } + } + + static int type(Object x) { return x instanceof Map ? 0xC1 : x instanceof List ? 0xC0 : x instanceof String ? 0xA0 : x instanceof Float ? 0xD2 : 0xD1; } + static int scalar(Object x, List strings) { return x instanceof Float ? Float.floatToRawIntBits((Float) x) : x instanceof Integer ? (Integer) x : x instanceof String ? strings.indexOf(x) : 0; } + + /** A SARC of these entries, in this order, each at 8-byte alignment after a gap of pad bytes (another tool's layout) */ + static byte[] sarc(Map entries, int pad) { + int n = entries.size(); + ByteArrayOutputStream names = new ByteArrayOutputStream(); + List nameAt = new ArrayList<>(); + for (String k : entries.keySet()) { nameAt.add(names.size() / 4); names.writeBytes(k.getBytes(StandardCharsets.UTF_8)); do names.write(0); while (names.size() % 4 != 0); } + int head = 0x20 + 16 * n + 8 + names.size(), data = (head + 0x7F) & ~0x7F; + ByteArrayOutputStream d = new ByteArrayOutputStream(); + ByteBuffer h = le(head); + h.put("SARC".getBytes(StandardCharsets.US_ASCII)).putShort((short) 0x14).putShort((short) 0xFEFF).putInt(0).putInt(data).putInt(0x01000100); + h.put("SFAT".getBytes(StandardCharsets.US_ASCII)).putShort((short) 0xC).putShort((short) n).putInt(0x65); + int i = 0; + for (byte[] e : entries.values()) { + d.writeBytes(new byte[pad]); + while (d.size() % 8 != 0) d.write(0); + h.putInt(0x1000 + i).putInt(0x01000000 | nameAt.get(i)).putInt(d.size()).putInt(d.size() + e.length); + d.writeBytes(e); + i++; + } + h.put("SFNT".getBytes(StandardCharsets.US_ASCII)).putShort((short) 8).putShort((short) 0).put(names.toByteArray()); + byte[] out = new byte[data + d.size()]; + System.arraycopy(h.array(), 0, out, 0, head); + System.arraycopy(d.toByteArray(), 0, out, data, d.size()); + ByteBuffer.wrap(out).order(ByteOrder.LITTLE_ENDIAN).putInt(8, out.length); + return out; + } + + static ByteBuffer le(int n) { return ByteBuffer.allocate(n).order(ByteOrder.LITTLE_ENDIAN); } + + /** The made-up pack: a player's actor (a hop gap, a walk speed, a list, a nested dictionary, a name) and a table of fixed-size rows */ + static Map actor(float gap, float walk, int frames, String name, float nested) { + Map m = new LinkedHashMap<>(); + m.put("HopGap", gap); m.put("WalkSpeed", walk); m.put("Frames", new ArrayList<>(List.of(frames, frames * 2, 7))); + Map sub = new LinkedHashMap<>(); sub.put("Lean", nested); m.put("Body", sub); + m.put("Name", name); + return m; + } + + static byte[] table(int a, int b) { ByteBuffer t = le(32); for (int i = 0; i < 8; i++) t.putInt(i == 2 ? a : i == 6 ? b : 1000 + i); return t.array(); } + + static byte[] pack(Map actor, byte[] table, int pad) { + Map e = new LinkedHashMap<>(); + e.put("Param/Actor/PlayerActor.byml", byml(actor)); e.put("Param/Other.byml", byml(actor(1f, 2f, 3, "Other", 0f))); e.put("Bcsv/Table.bcsv", table); + return sarc(e, pad); + } + + // ---- reading a merged file back ---- + + static Map read(byte[] packBytes, String entry) { + VariantMerge.Span s = VariantMerge.Sarc.entries(new VariantMerge.Span(packBytes, 0, packBytes.length)).get(entry); + VariantMerge.Byml b = new VariantMerge.Byml(s); + Map out = new LinkedHashMap<>(); + for (Map.Entry e : b.slots().entrySet()) { + byte[] v = b.value(e.getValue()); + out.put(e.getKey(), e.getValue().type == 0xD2 ? (Object) ByteBuffer.wrap(v).order(ByteOrder.LITTLE_ENDIAN).getFloat() + : e.getValue().type == 0xA0 ? (Object) new String(v, StandardCharsets.UTF_8) : (Object) ByteBuffer.wrap(v).order(ByteOrder.LITTLE_ENDIAN).getInt()); + } + return out; + } + + static int tableValue(byte[] packBytes, int i) { + VariantMerge.Span s = VariantMerge.Sarc.entries(new VariantMerge.Span(packBytes, 0, packBytes.length)).get("Bcsv/Table.bcsv"); + return s.u32(4 * i); + } + + // ---- the cases ---- + + static File dir; + static int n; + + /** A pack folder with the variant's file and its original, and mods with their copies; returns the merge's result */ + static VariantMerge.Result run(byte[] orig, byte[] variant, boolean originals, byte[]... mods) throws Exception { + File d = new File(dir, "case" + (n++)); + File romfs = new File(d, "pack/60/romfs/Pack"), origs = new File(d, "pack/60/romfs-orig/Pack"); + check(romfs.mkdirs() && origs.mkdirs(), "folders"); + Files.write(new File(romfs, "StaticParam.pack").toPath(), variant); + Files.write(new File(d, "pack/60/romfs/Other.bin").toPath(), new byte[] {1, 2, 3}); // a variant file no mod ships + if (originals) Files.write(new File(origs, "StaticParam.pack").toPath(), orig); + List roots = new ArrayList<>(); + for (int i = 0; i < mods.length; i++) { + File r = new File(d, "mods/Mod" + i + "/romfs"); + check(new File(r, "Pack").mkdirs(), "mod folder"); + Files.write(new File(r, "Pack/StaticParam.pack").toPath(), mods[i]); + roots.add(r); + } + File stage = new File(d, "stage"); + check(new File(stage, "stale").mkdirs(), "a stale staging folder"); + return VariantMerge.merge(new File(d, "pack/60/romfs"), new File(d, "pack/60/romfs-orig"), roots, stage, "60"); + } + + static byte[] merged(VariantMerge.Result r) throws Exception { + check(r.root != null, "a merged folder: " + r.notes); + check(!new File(r.root, "stale").exists(), "the staging folder is emptied first"); + check(!new File(r.root, "Other.bin").exists(), "only merged files are staged; the others come from the variant's folder"); + return Files.readAllBytes(new File(r.root, "Pack/StaticParam.pack").toPath()); + } + + public static void main(String[] args) throws Exception { + dir = new File(args[0]); + // the original, the variant (it halves the walk speed and doubles the frames, as a 60 fps patch does) and the mod (it widens the hop gap) + byte[] orig = pack(actor(35f, 4f, 30, "Player", 0.243165f), table(10, 20), 0); + byte[] variant = pack(actor(35f, 2f, 60, "Player", 0.243165f), table(10, 40), 0); + byte[] mod = pack(actor(100f, 4f, 30, "Player", 0.243165f), table(10, 20), 0); + + // 1. a value only the mod changes is merged; the variant's own values stay; nothing moves (same size, same layout as the variant's) + VariantMerge.Result r = run(orig, variant, true, mod); + byte[] m = merged(r); + check(m.length == variant.length, "the variant's layout"); + Map v = read(m, "Param/Actor/PlayerActor.byml"); + check(v.get("/HopGap").equals(100f) && v.get("/WalkSpeed").equals(2f) && v.get("/Frames[0]").equals(60), "merged: " + v); + check(r.notes.size() == 1 && r.notes.get(0).equals("[nxlaunch] mods: Pack/StaticParam.pack (the 60 variant's game data): Mod0: 1 value merged"), r.notes.toString()); + + // 2. a value both change keeps the variant's (its frame rate needs it), and the log says so; the mod's other change is still merged + byte[] both = pack(actor(100f, 5f, 30, "Player", 0.243165f), table(10, 20), 0); + r = run(orig, variant, true, both); + v = read(merged(r), "Param/Actor/PlayerActor.byml"); + check(v.get("/HopGap").equals(100f) && v.get("/WalkSpeed").equals(2f), "clash: " + v); + check(r.notes.get(0).endsWith("Mod0: 1 value merged, 1 kept as the variant has them (it changes them too)"), r.notes.toString()); + + // 3. a mod made from another game version: its SARC laid out differently (gaps), a value rounded, a key the original lacks; still merged by path + Map other = actor(100f, 4f, 30, "Player", 0.24317f); + other.put("NewKey", 5); + r = run(orig, variant, true, pack(other, table(10, 20), 24)); + v = read(merged(r), "Param/Actor/PlayerActor.byml"); + check(v.get("/HopGap").equals(100f) && v.get("/Body/Lean").equals(0.24317f) && !v.containsKey("/NewKey"), "another layout: " + v); + check(r.notes.get(0).endsWith("Mod0: 2 values merged, 1 not merged (/Param/Actor/PlayerActor.byml/NewKey is added or retyped)"), r.notes.toString()); + + // 4. two mods on one value: the first in the list wins, as it wins a whole file in the overlay; each one's other values are merged + byte[] first = pack(actor(100f, 4f, 30, "Player", 0.243165f), table(10, 20), 0), second = pack(actor(50f, 4f, 30, "Player", 0.5f), table(10, 20), 0); + r = run(orig, variant, true, first, second); + v = read(merged(r), "Param/Actor/PlayerActor.byml"); + check(v.get("/HopGap").equals(100f) && v.get("/Body/Lean").equals(0.5f), "two mods: " + v); + check(r.notes.get(0).contains("Mod0: 1 value merged; Mod1: 2 values merged"), r.notes.toString()); + + // 5. strings: one the variant's string table has is merged (by its index there); one it lacks is not + byte[] origS = pack(actor(35f, 4f, 30, "Player", 0f), table(10, 20), 0); + Map varS = actor(35f, 2f, 60, "Player", 0f); varS.put("Alt", "Runner"); + byte[] variantS = pack(varS, table(10, 40), 0); + Map modS = actor(35f, 4f, 30, "Runner", 0f); modS.put("Alt", "Runner"); // Alt is added (not merged); Name becomes a string the variant has + v = read(merged(run(origS, variantS, true, pack(modS, table(10, 20), 0))), "Param/Actor/PlayerActor.byml"); + check(v.get("/Name").equals("Runner") && v.get("/Alt").equals("Runner"), "a string the variant has: " + v); + r = run(origS, variantS, true, pack(actor(35f, 4f, 30, "Swimmer", 0f), table(10, 20), 0)); + check(r.root == null && r.notes.get(0).endsWith("Mod0: 0 values merged, 1 not merged (/Param/Actor/PlayerActor.byml/Name is a string the variant's file lacks)"), r.notes.toString()); + + // 6. same-size data of no known shape: a run of bytes merged; one next to a value the variant changed is not + r = run(orig, variant, true, pack(actor(35f, 4f, 30, "Player", 0.243165f), table(11, 21), 0)); + m = merged(r); + check(tableValue(m, 2) == 11 && tableValue(m, 6) == 40, "table: " + tableValue(m, 2) + " " + tableValue(m, 6)); + check(r.notes.get(0).endsWith("Mod0: 1 value merged, 1 kept as the variant has them (it changes them too)"), r.notes.toString()); + + // 7. a pack from before the originals were kept: nothing merged, the hidden file named + r = run(orig, variant, false, mod); + check(r.root == null && r.notes.get(0).equals("[nxlaunch] mods: Pack/StaticParam.pack (the 60 variant's game data): Mod0's copy is hidden: this pack has no original to merge it against (prepare the game again)"), r.notes.toString()); + + // 8. a mod whose copy is the original: nothing to merge, nothing staged + r = run(orig, variant, true, orig.clone()); + check(r.root == null && r.notes.get(0).endsWith("Mod0: no change against the original"), r.notes.toString()); + + // 9. a mod file that does not parse: the variant's file as it is, never a half-merged one + r = run(orig, variant, true, Arrays.copyOf(mod, 0x30)); + check(r.root == null && r.notes.get(0).contains("Mod0's copy is hidden: not merged ("), r.notes.toString()); + byte[] bad = mod.clone(); + ByteBuffer.wrap(bad).order(ByteOrder.LITTLE_ENDIAN).putInt(0x20 + 8, 1 << 30); // an entry past the file's end + r = run(orig, variant, true, bad); + check(r.root == null && r.notes.get(0).contains("not merged ("), r.notes.toString()); + + // 10. a file of another size and no known shape is not merged + File d = new File(dir, "raw"); + check(new File(d, "v").mkdirs() && new File(d, "o").mkdirs() && new File(d, "m/romfs").mkdirs(), "folders"); + Files.write(new File(d, "v/T.bin").toPath(), new byte[] {1, 2, 3, 4}); + Files.write(new File(d, "o/T.bin").toPath(), new byte[] {1, 2, 3, 3}); + Files.write(new File(d, "m/romfs/T.bin").toPath(), new byte[] {9, 2, 3, 3, 0}); + r = VariantMerge.merge(new File(d, "v"), new File(d, "o"), List.of(new File(d, "m/romfs")), new File(d, "stage"), "60"); + check(r.root == null && r.notes.get(0).equals("[nxlaunch] mods: T.bin (the 60 variant's game data): m: 0 values merged, 1 not merged (the file has another size)"), r.notes.toString()); + + System.out.println("ok"); + } +} diff --git a/android/app/src/main/java/dev/nxnative/android/GameActivity.java b/android/app/src/main/java/dev/nxnative/android/GameActivity.java index 7af7de65..9fa802da 100644 --- a/android/app/src/main/java/dev/nxnative/android/GameActivity.java +++ b/android/app/src/main/java/dev/nxnative/android/GameActivity.java @@ -1022,7 +1022,12 @@ private void start() { if (fpsRomfs != null) { String chain = null; for (String kv : env) if (kv.startsWith(SceneRes.ENV + "=")) chain = kv.substring(SceneRes.ENV.length() + 1); // the line in force so far (the mods' or the scene's): kept after it - env.add(SceneRes.ENV + "=" + fpsRomfs.getPath() + (chain != null && !chain.isEmpty() ? ":" + chain : "")); + // PEANUTS: the enabled mods' copies of the variant's files, merged into the variant's (VariantMerge), ahead of it: else the variant's copy hid the mod's whole file + dev.peanuts.mods.VariantMerge.Result merged = dev.peanuts.mods.VariantMerge.merge(fpsRomfs, pack.variantOriginals(fpsVariantAtStart), + dev.peanuts.mods.ModRuntime.romfsDirs(game.isDirectory() ? game : game.getParentFile(), id, packDir), + new File(getFilesDir(), "mods_stage/" + id.toUpperCase(java.util.Locale.ROOT) + "/variant-romfs"), fpsVariantAtStart); + for (String n : merged.notes) if (!quietNotes.contains(n)) quietNotes.add(n); + env.add(SceneRes.ENV + "=" + (merged.root != null ? merged.root.getPath() + ":" : "") + fpsRomfs.getPath() + (chain != null && !chain.isEmpty() ? ":" + chain : "")); } String modCheats = dev.peanuts.mods.ModRuntime.cheatsEnv(this, game.isDirectory() ? game : game.getParentFile(), id, packDir); // PEANUTS: mods beside the game; a code mod's cheats only with its build if (modCheats != null && !cheatsMerged) env.add(modCheats); // PEANUTS: not beside upstream's own DM_CHEATS, which holds the mods' cheats then (cheatsEnv, ModCheats): the later line won, and the panel listed cheats the host did not run diff --git a/android/app/src/main/java/dev/nxnative/android/Pack.java b/android/app/src/main/java/dev/nxnative/android/Pack.java index fe15b5eb..e80ed1f9 100644 --- a/android/app/src/main/java/dev/nxnative/android/Pack.java +++ b/android/app/src/main/java/dev/nxnative/android/Pack.java @@ -38,6 +38,13 @@ File variantRomfs(String name) { File f = new File(dir, rel); return f.isDirectory() ? f : null; } + /** The files the variant's RomFS overlay was made from (pack_android.py variant_overlays: -orig), null for none (a pack from before they were kept): + * what an enabled mod's copy of one of its files is merged against at a start (dev.peanuts.mods.VariantMerge) */ + File variantOriginals(String name) { + File r = variantRomfs(name); + File f = r == null ? null : new File(r.getParentFile(), r.getName() + "-orig"); + return f != null && f.isDirectory() ? f : null; + } // PEANUTS end // A pack of program n > 0 of a dump folder (pack_android.py --program; a Switch 2 Edition's program 1, updates//program/1/): which program, its application (the save and the add-ons // are the application's) and each program index's RomFS (the host's DM_ROMFS_PROGRAM_: 0 is the game's, the edition mounts it as "conorig"). 0 / "" / empty otherwise diff --git a/android/app/src/main/java/dev/peanuts/mods/ModRuntime.java b/android/app/src/main/java/dev/peanuts/mods/ModRuntime.java index 97ed3572..ee73d361 100644 --- a/android/app/src/main/java/dev/peanuts/mods/ModRuntime.java +++ b/android/app/src/main/java/dev/peanuts/mods/ModRuntime.java @@ -65,6 +65,9 @@ static List forStart(File gameHome, String titleId, File packDir) return ModStore.contributing(mods, ModStore.playsVariant(titleId, ModStore.enabledCodeMods(mods), packDir)); } + /** The enabled mods' romfs folders for a start of packDir, first wins: what a frame rate variant's own files are merged with (VariantMerge) */ + public static List romfsDirs(File gameHome, String titleId, File packDir) { return ModStore.enabledRomfsDirs(forStart(gameHome, titleId, packDir)); } + /** As above for a start of packDir (GameActivity.start's pack folder): see {@link #forStart} */ public static String romfsOverlayEnv(Context c, File gameHome, String titleId, File sceneOverlayDirOrNull, File packDir) { List dirs = ModStore.enabledRomfsDirs(forStart(gameHome, titleId, packDir)); diff --git a/android/app/src/main/java/dev/peanuts/mods/VariantMerge.java b/android/app/src/main/java/dev/peanuts/mods/VariantMerge.java new file mode 100644 index 00000000..d5ba5dac --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/mods/VariantMerge.java @@ -0,0 +1,306 @@ +package dev.peanuts.mods; + +// PEANUTS: new file (a frame rate variant's game files merged with the enabled mods' copies of them at a start: Animal Crossing: New Horizons' 60 fps +// StaticParam.pack hid the mods' copy, and with it ACNH Combined's River Hopping) + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * A variant's RomFS overlay (pack_android.py variant_overlays: {@code //romfs}, the variant's rows applied to the player's own files) goes + * first in {@code DM_ROMFS_OVERLAY}, and the first root that has a file wins (hle_fs.c rom_overlay_path). So a mod that ships one of the variant's files + * lost all its changes to that file at the variant's frame rate, and nothing said so. This merges them instead, as a three-way merge against the file + * the variant was made from ({@code //romfs-orig}, which the pack step writes beside it): + *
    + *
  • every value a mod changed is written into a copy of the variant's file, unless the variant changed the same value: then the variant's stays (its + * frame rate needs it) and the log says so;
  • + *
  • values are matched by what they are, not where: SARC entries by name, BYML (v2 and later, little-endian) values by their path of keys and indexes, + * so a mod made from another game version, whose files are laid out differently, still merges. Other files of the same size are merged by changed + * runs of bytes;
  • + *
  • nothing is resized or moved: a value the mod adds, or a file whose shape differs and is neither SARC nor BYML, is not merged, and the log says so.
  • + *
+ * A mod higher in the list wins a value two mods change, as it wins a whole file in the overlay. The merged files go to a staging folder the caller puts + * ahead of the variant's folder; the files no mod ships still come from the variant's folder. Plain Java (no Android classes): VariantMergeJvmTest. + */ +public final class VariantMerge { + private VariantMerge() {} + + /** What a start takes: the folder to put first in the overlay (null when nothing was merged) and the lines for the log */ + public static final class Result { + public final File root; + public final List notes; + Result(File root, List notes) { this.root = root; this.notes = notes; } + } + + /** + * The enabled mods' copies of the variant's files, merged into the variant's. variantRomfs: the variant's overlay folder; originals: the files it was + * made from (null or missing for a pack from before they were kept: then nothing is merged and the log names the hidden files); mods: the enabled + * mods' romfs folders, first wins; stage: emptied, then the merged files are written to it; variant: its name, for the log + */ + public static Result merge(File variantRomfs, File originals, List mods, File stage, String variant) { + List notes = new ArrayList<>(); + deleteTree(stage); + boolean wrote = false; + for (String rel : files(variantRomfs)) { + List theirs = new ArrayList<>(); // the mods (their romfs folders) that ship this file + for (File m : mods) if (new File(m, rel).isFile()) theirs.add(m); + if (theirs.isEmpty()) continue; + String what = "[nxlaunch] mods: " + rel + " (the " + variant + " variant's game data)"; + File orig = originals == null ? null : new File(originals, rel); + if (orig == null || !orig.isFile()) { + notes.add(what + ": " + names(theirs) + "'s copy is hidden: this pack has no original to merge it against (prepare the game again)"); + continue; + } + try { + byte[] base = Files.readAllBytes(orig.toPath()), ours = Files.readAllBytes(new File(variantRomfs, rel).toPath()), out = ours.clone(); + List parts = new ArrayList<>(); + for (int i = theirs.size() - 1; i >= 0; i--) { // the last in the list first, so the first one's values are written last and win + Merger mg = new Merger(base, ours, out); + mg.merge(Files.readAllBytes(new File(theirs.get(i), rel).toPath())); + parts.add(0, mod(theirs.get(i)) + ": " + mg.summary()); + } + notes.add(what + ": " + String.join("; ", parts)); + if (!Arrays.equals(out, ours)) { + File dst = new File(stage, rel); + File parent = dst.getParentFile(); + if (parent != null && !parent.isDirectory() && !parent.mkdirs()) throw new IOException("cannot make " + parent); + File tmp = new File(dst.getPath() + ".partial"); + Files.write(tmp.toPath(), out); + Files.move(tmp.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING); + wrote = true; + } + } catch (IOException | RuntimeException e) { // a file that cannot be read or parsed: the variant's file as it is, never a half-merged one + new File(stage, rel).delete(); + notes.add(what + ": " + names(theirs) + "'s copy is hidden: not merged (" + e + ")"); + } + } + return new Result(wrote ? stage : null, notes); + } + + /** + * One mod's file merged into out: base is the original, ours the variant's file (out's layout: the merge writes in place), theirs the mod's. A change + * clashes when the variant changed the same value against base; then out keeps what it has + */ + static final class Merger { + final byte[] base, ours, out; + int ported, clashes, unmerged; + final List why = new ArrayList<>(); + + Merger(byte[] base, byte[] ours, byte[] out) { this.base = base; this.ours = ours; this.out = out; } + + void merge(byte[] theirs) { node("", new Span(base, 0, base.length), new Span(ours, 0, ours.length), new Span(theirs, 0, theirs.length), 0); } + + String summary() { + if (ported == 0 && clashes == 0 && unmerged == 0) return "no change against the original"; + String s = ported + " value" + (ported == 1 ? "" : "s") + " merged"; + if (clashes > 0) s += ", " + clashes + " kept as the variant has them (it changes them too)"; + if (unmerged > 0) s += ", " + unmerged + " not merged (" + String.join(", ", why) + (unmerged > why.size() ? ", ..." : "") + ")"; + return s; + } + + private void miss(String what) { unmerged++; if (why.size() < 4) why.add(what); } + + private void node(String path, Span b, Span o, Span t, int depth) { + if (b.equalTo(t)) return; + if (depth < 8 && Sarc.is(b) && Sarc.is(o) && Sarc.is(t)) { sarc(path, b, o, t, depth); return; } + if (Byml.is(b) && Byml.is(o) && Byml.is(t)) { byml(path, b, o, t); return; } + if (b.len == o.len && b.len == t.len) { runs(path, b, o, t); return; } + miss((path.isEmpty() ? "the file" : path) + " has another size"); + } + + private void sarc(String path, Span b, Span o, Span t, int depth) { + Map bs = Sarc.entries(b), os = Sarc.entries(o), ts = Sarc.entries(t); + for (Map.Entry e : ts.entrySet()) { + String p = path + "/" + e.getKey(); + Span be = bs.get(e.getKey()), oe = os.get(e.getKey()); + if (be == null || oe == null) { miss(p + " is not in the " + (be == null ? "original" : "variant")); continue; } + node(p, be, oe, e.getValue(), depth + 1); + } + } + + private void byml(String path, Span b, Span o, Span t) { + Byml bb = new Byml(b), ob = new Byml(o), tb = new Byml(t); + Map bv = bb.slots(), ov = ob.slots(), tv = tb.slots(); + for (Map.Entry e : tv.entrySet()) { + Byml.Slot bs = bv.get(e.getKey()), os = ov.get(e.getKey()), ts = e.getValue(); + if (bs == null || bs.type != ts.type) { miss(path + e.getKey() + " is added or retyped"); continue; } + if (os == null || os.type != ts.type) { miss(path + e.getKey() + " is not in the variant's file"); continue; } + byte[] v0 = bb.value(bs), v1 = ob.value(os), v2 = tb.value(ts); + if (Arrays.equals(v2, v0)) continue; + if (!Arrays.equals(v1, v0)) { clashes++; continue; } + byte[] w = v2; + if (ts.type == Byml.STRING) { // a string is an index into the file's own string table: the variant's index of the mod's string + int k = ob.stringIndex(new String(v2, StandardCharsets.UTF_8)); + if (k < 0) { miss(path + e.getKey() + " is a string the variant's file lacks"); continue; } + w = new byte[] {(byte) k, (byte) (k >> 8), (byte) (k >> 16), (byte) (k >>> 24)}; + } + System.arraycopy(w, 0, out, o.off + ob.valueAt(os), w.length); + ported++; + } + } + + /** Same-size data of no known shape: each run of bytes the mod changed, unless the variant changed a byte within 3 of it (a value the variant changed) */ + private void runs(String path, Span b, Span o, Span t) { + int n = b.len, i = 0; + while (i < n) { + if (t.at(i) == b.at(i)) { i++; continue; } + int j = i; + while (j < n && t.at(j) != b.at(j)) j++; + boolean clash = false; + for (int k = Math.max(0, i - 3); k < Math.min(n, j + 3) && !clash; k++) clash = o.at(k) != b.at(k); + if (clash) clashes++; + else { System.arraycopy(t.a, t.off + i, out, o.off + i, j - i); ported++; } + i = j; + } + } + } + + /** A slice of a file */ + static final class Span { + final byte[] a; final int off, len; + Span(byte[] a, int off, int len) { + if (off < 0 || len < 0 || off + len > a.length || off + len < 0) throw new IllegalArgumentException("a slice past the file's end"); + this.a = a; this.off = off; this.len = len; + } + int at(int i) { return a[off + i] & 0xFF; } + int u16(int i) { return at(i) | at(i + 1) << 8; } + int u32(int i) { return u16(i) | u16(i + 2) << 16; } + int u24(int i) { return at(i) | at(i + 1) << 8 | at(i + 2) << 16; } + boolean equalTo(Span s) { return Arrays.equals(a, off, off + len, s.a, s.off, s.off + s.len); } + String cstr(int i) { + int e = i; + while (e < len && a[off + e] != 0) e++; + if (e >= len) throw new IllegalArgumentException("a name past the file's end"); + return new String(a, off + i, e - i, StandardCharsets.UTF_8); + } + } + + /** SARC archives (little-endian): entry name → its data */ + static final class Sarc { + static boolean is(Span s) { return s.len >= 0x28 && s.at(0) == 'S' && s.at(1) == 'A' && s.at(2) == 'R' && s.at(3) == 'C' && s.u16(6) == 0xFEFF; } + + static Map entries(Span s) { + int data = s.u32(0xC); + if (s.at(0x14) != 'S' || s.at(0x15) != 'F' || s.at(0x16) != 'A' || s.at(0x17) != 'T') throw new IllegalArgumentException("a SARC without SFAT"); + int n = s.u16(0x1A), names = 0x20 + 16 * n + 8; + Map out = new LinkedHashMap<>(); + for (int i = 0; i < n; i++) { + int e = 0x20 + 16 * i, hash = s.u32(e), attr = s.u32(e + 4), start = s.u32(e + 8), end = s.u32(e + 12); + String name = (attr >>> 24) != 0 ? s.cstr(names + (attr & 0xFFFF) * 4) : String.format("%08x", hash); + if (end < start) throw new IllegalArgumentException("a SARC entry that ends before it starts"); + out.put(name, new Span(s.a, s.off + data + start, end - start)); + } + return out; + } + } + + /** BYML v2 and later (little-endian "YB"): every value that is not a container, by its path (/key for a dictionary, [i] for an array) */ + static final class Byml { + static final int STRING = 0xA0; + final Span s; + final String[] keys, strings; + + static boolean is(Span s) { return s.len >= 16 && s.at(0) == 'Y' && s.at(1) == 'B' && s.u16(2) >= 2; } + + Byml(Span s) { this.s = s; keys = table(s.u32(4)); strings = table(s.u32(8)); } + + private String[] table(int at) { + if (at == 0) return new String[0]; + if (s.at(at) != 0xC2) throw new IllegalArgumentException("not a BYML string table"); + int n = s.u24(at + 1); + String[] out = new String[n]; + for (int i = 0; i < n; i++) out[i] = s.cstr(at + s.u32(at + 4 + 4 * i)); + return out; + } + + int stringIndex(String v) { for (int i = 0; i < strings.length; i++) if (strings[i].equals(v)) return i; return -1; } + + /** A value's place: where its 4-byte slot is, and its type */ + static final class Slot { final int at, type; Slot(int at, int type) { this.at = at; this.type = type; } } + + Map slots() { + Map out = new HashMap<>(); + int root = s.u32(12); + if (root != 0) walk(root, "", out, 0); + return out; + } + + private void walk(int at, String path, Map out, int depth) { + if (depth > 64) throw new IllegalArgumentException("a BYML nested too deep"); + int type = s.at(at), n = s.u24(at + 1); + List items = new ArrayList<>(); + if (type == 0xC0) { + int values = (at + 4 + n + 3) & ~3; + for (int i = 0; i < n; i++) items.add(new Object[] {path + "[" + i + "]", s.at(at + 4 + i), values + 4 * i}); + } else if (type == 0xC1) { + for (int i = 0; i < n; i++) { + int e = at + 4 + 8 * i, k = s.u24(e); + if (k >= keys.length) throw new IllegalArgumentException("a BYML key past its table"); + items.add(new Object[] {path + "/" + keys[k], s.at(e + 3), e + 4}); + } + } else return; // another container type (later BYML versions): its values are not merged + for (Object[] it : items) { + int t = (Integer) it[1], slot = (Integer) it[2]; + if (t == 0xC0 || t == 0xC1) walk(s.u32(slot), (String) it[0], out, depth + 1); + else if (t == STRING || (t >= 0xD0 && t <= 0xD6)) out.put((String) it[0], new Slot(slot, t)); + } + } + + /** Where the value's bytes are in this file: the slot itself, or for a 64-bit value the place the slot points at */ + int valueAt(Slot v) { return v.type >= 0xD4 ? s.u32(v.at) : v.at; } + + byte[] value(Slot v) { + if (v.type == STRING) { + int k = s.u32(v.at); + if (k < 0 || k >= strings.length) throw new IllegalArgumentException("a BYML string past its table"); + return strings[k].getBytes(StandardCharsets.UTF_8); + } + int at = valueAt(v), w = v.type >= 0xD4 ? 8 : 4; + if (at < 0 || at + w > s.len) throw new IllegalArgumentException("a BYML value past the file's end"); + return Arrays.copyOfRange(s.a, s.off + at, s.off + at + w); + } + } + + /** The files under root, as RomFS paths ('/'), sorted */ + static List files(File root) { + List out = new ArrayList<>(); + walk(root, "", out); + java.util.Collections.sort(out); + return out; + } + + private static void walk(File dir, String rel, List out) { + File[] kids = dir.listFiles(); + if (kids == null) return; + for (File k : kids) { + String r = rel.isEmpty() ? k.getName() : rel + "/" + k.getName(); + if (k.isDirectory()) walk(k, r, out); + else if (k.isFile() && !k.getName().endsWith(".partial")) out.add(r); + } + } + + /** A mod's name in the log: its folder (//romfs) */ + private static String mod(File romfs) { File m = romfs.getParentFile(); return m == null ? romfs.getPath() : m.getName(); } + + private static String names(List fs) { + List out = new ArrayList<>(); + for (File f : fs) out.add(mod(f)); + return String.join(", ", out); + } + + private static void deleteTree(File f) { + if (f == null || !f.exists()) return; + File[] kids = f.listFiles(); + if (kids != null) for (File k : kids) deleteTree(k); + f.delete(); + } +} diff --git a/dm/games/01006F8002326000/README.md b/dm/games/01006F8002326000/README.md index 1f6e07ab..2d5726b1 100644 --- a/dm/games/01006F8002326000/README.md +++ b/dm/games/01006F8002326000/README.md @@ -28,6 +28,9 @@ per-frame speeds halved and its frame counts doubled, so it plays at normal spee `Pack/StaticParam.pack`). [speedfix60/romfs.tsv](speedfix60/romfs.tsv) holds only the changed bytes, with each original file's size and SHA-256 (`dm/tools/romfs_rows.py`); the pack step applies them to the player's own 3.0.3 files into `/60/romfs/` and lists the variant in `pack.tsv` only when every file matched. The start passes that folder first in `DM_ROMFS_OVERLAY`. +- **Mods**: a mod that ships one of those files (ACNH Combined's River Hopping ships `Pack/StaticParam.pack`) has its changes merged into the variant's copy at + each start, except the values the variant changes too; before, the variant's copy hid the mod's whole file at 60 fps + ([A frame rate variant's game data hides a mod's copy of the same file](../../../docs/reference/packing.md#a-frame-rate-variants-game-data-hides-a-mods-copy-of-the-same-file-android)). - **Pacing**: one frame a display tick (`DM_PRESENT_INTERVAL=display`), which does what the mod's `sdk` patch does on the console (swap interval 2 to 1 inside NVN code the host replaces); that patch is not used. - Measured on an AYN Thor with the mod imported (before the built-in choice): 60 fps, 16.7 ms frames. @@ -78,6 +81,7 @@ General host changes first needed here; each applies to every game: - **The game's own HIPC clients answered by host sessions** (`hle_sf.c`, `DM_SF_TRACE`), **device save data and shared transactions** (`mount_ex`), **`fs::Commit` with a mount list or a `CommitOption`**, and the adjustable user clock, region code and SDK 20 album and steady-clock calls: [Game-linked HIPC clients of system services](../../../docs/reference/services.md#game-linked-hipc-clients-of-system-services), [Device save data on the account save's directory](../../../docs/reference/services.md#device-save-data-on-the-account-saves-directory), [`fs::Commit` with a list of mounts](../../../docs/reference/services.md#fscommit-with-a-list-of-mounts), [Steady clock, clock snapshots and user clocks](../../../docs/reference/services.md#steady-clock-clock-snapshots-and-user-clocks), [Region code from the language](../../../docs/reference/services.md#region-code-from-the-language), [Album calls fail with no album](../../../docs/reference/services.md#album-calls-fail-with-no-album). - **16 output slots for video movie decoders** (`MD_NOUT_VIDEO` in `hle_movie.c`): [Video output slots: how far the extractor gets ahead](../../../docs/reference/movies.md#video-output-slots-how-far-the-extractor-gets-ahead). - **Functions with function constants specialized by the pipeline** (`fn_spec`): the HUD's `Compiled 2 shaders … Consider adopting MTL4Compiler` during play on the iPhone with Metal 4 pipelines on: [Functions with function constants specialized by the pipeline, not the library](../../../docs/reference/shaders.md#functions-with-function-constants-specialized-by-the-pipeline-not-the-library). +- **A mod's copy of a frame rate variant's file merged into the variant's** (`VariantMerge`): ACNH Combined's River Hopping did nothing at 60 fps; [A frame rate variant's game data hides a mod's copy of the same file](../../../docs/reference/packing.md#a-frame-rate-variants-game-data-hides-a-mods-copy-of-the-same-file-android). - [The alpha test through a library of its own](../../../docs/reference/rendering.md#the-alpha-test-through-a-library-of-its-own): the island map's corruption (issue #73) improved with an alpha test in a downstream runtime (PR #430). ## Open diff --git a/dm/tools/romfs_rows.py b/dm/tools/romfs_rows.py index d25dfb4c..d3b3289d 100644 --- a/dm/tools/romfs_rows.py +++ b/dm/tools/romfs_rows.py @@ -140,19 +140,23 @@ def read_original(root, path): except OSError as e: raise Error(f'{path}: cannot be read from the game files ({e.strerror or e})') from None -def make(rows_path, root, out): +def make(rows_path, root, out, orig_out=None): """Every file of the rows applied to its original in root, written to out/: [RomFS path]. All or nothing: a file that does not apply stops - it before anything is written (Error), and out is emptied first so that a file of an earlier run cannot stay beside new ones""" + it before anything is written (Error), and out is emptied first so that a file of an earlier run cannot stay beside new ones. With orig_out, each + original is written to orig_out/ as well (emptied first too): what the launcher merges a mod's copy of the same file against + (dev.peanuts.mods.VariantMerge)""" frs = load(rows_path) - made = [(fr.path, apply(fr, read_original(root, fr.path))) for fr in frs] + origs = [(fr.path, read_original(root, fr.path)) for fr in frs] + made = [(fr.path, apply(fr, data)) for fr, (_, data) in zip(frs, origs)] import shutil - shutil.rmtree(out, ignore_errors=True) - for path, data in made: - dst = os.path.join(out, *path.split('/')) - os.makedirs(os.path.dirname(dst), exist_ok=True) - tmp = dst + '.partial' - with open(tmp, 'wb') as f: f.write(data) - os.replace(tmp, dst) + for folder, files in ((out, made),) + (((orig_out, origs),) if orig_out is not None else ()): + shutil.rmtree(folder, ignore_errors=True) + for path, data in files: + dst = os.path.join(folder, *path.split('/')) + os.makedirs(os.path.dirname(dst), exist_ok=True) + tmp = dst + '.partial' + with open(tmp, 'wb') as f: f.write(data) + os.replace(tmp, dst) return [p for p, _ in made] diff --git a/dm/tools/tests/test_pack_android_variants.py b/dm/tools/tests/test_pack_android_variants.py index 8a020dd9..0ca89b07 100644 --- a/dm/tools/tests/test_pack_android_variants.py +++ b/dm/tools/tests/test_pack_android_variants.py @@ -156,6 +156,7 @@ def test_a_complete_variant_is_listed_with_its_game_data(self): r, _ = self.run_({'main': 'aa' * 16}) self.assertEqual(r, [('60', '60/romfs')]) self.assertEqual((self.out / '60/romfs/Bcsv/A.bcsv').read_bytes(), self.modded) + self.assertEqual((self.out / '60/romfs-orig/Bcsv/A.bcsv').read_bytes(), (self.romfs / 'Bcsv/A.bcsv').read_bytes(), "the original beside it: what a mod's copy is merged against") def test_another_main_build_or_other_files_are_not_listed(self): r, log = self.run_({'main': 'bb' * 16}) @@ -164,6 +165,7 @@ def test_another_main_build_or_other_files_are_not_listed(self): r, log = self.run_({'main': 'aa' * 16}) self.assertEqual(r, []); self.assertIn('do not apply to these game files', log) self.assertFalse((self.out / '60/romfs').exists(), 'no game data of an earlier run stays') + self.assertFalse((self.out / '60/romfs-orig').exists(), 'nor its originals') def test_an_unfinished_rewrite_is_not_listed(self): (self.out / '60/main.android.key').unlink() @@ -287,11 +289,27 @@ def test_the_start(self): self.assertIn('pack.variantReady(fv)', act) self.assertLess(act.index('pack.variantRomfs(fpsVariantAtStart)'), act.index('env.addAll(user);'), "the player's own DM_ROMFS_OVERLAY line comes later and wins") self.assertLess(act.index('if (modOverlay != null) env.add(modOverlay);'), act.index('pack.variantRomfs(fpsVariantAtStart)'), "the variant's data goes first, before the mods' chain") + start = act[act.index('pack.variantRomfs(fpsVariantAtStart)'):act.index('env.addAll(user);')] + self.assertIn('VariantMerge.merge(fpsRomfs, pack.variantOriginals(fpsVariantAtStart)', start, "the mods' copies of the variant's files are merged into it") + self.assertIn('(merged.root != null ? merged.root.getPath() + ":" : "") + fpsRomfs.getPath()', start, 'the merged files first, then the variant, then the chain') prefs = (SRC / 'Prefs.java').read_text(encoding='utf-8') self.assertIn('applies at the next start', prefs.split('FPS_VARIANT_NOTE = ')[1].split(';')[0]) self.assertIn("('variant', f'{v}\\t{p}')", (REPO / 'scripts/pack_android.py').read_text(encoding='utf-8')) +@unittest.skipUnless(shutil.which('javac') and shutil.which('java'), 'no JDK') +class VariantMergeJvm(unittest.TestCase): + def test_jvm(self): # VariantMerge: a variant's files merged with the enabled mods' copies (made-up SARC and BYML files) + with tempfile.TemporaryDirectory() as d: + d = Path(d); (d / 'run').mkdir() + srcs = [REPO / 'android/app/src/main/java/dev/peanuts/mods/VariantMerge.java', REPO / 'android/app/src/jvmtest/java/dev/peanuts/mods/VariantMergeJvmTest.java'] + r = subprocess.run(['javac', '-Xlint:all', '-Werror', '-encoding', 'UTF-8', '-d', str(d / 'classes'), *map(str, srcs)], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + r = subprocess.run(['java', '-cp', str(d / 'classes'), 'dev.peanuts.mods.VariantMergeJvmTest', str(d / 'run')], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(r.stdout.strip(), 'ok') + + @unittest.skipUnless(shutil.which('javac') and shutil.which('java'), 'no JDK') class FpsVariantJvm(unittest.TestCase): def test_jvm(self): diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index ccfe883b..02dfcab5 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -50,6 +50,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - after an update with a new Android library version and no shader change (the release notes' stamp rows), `scripts/pack_android.py` on a Mac packs most games in seconds, but for a profile with a selected set it translates the whole shader map into `android-shaders/lib/v-/results`: Pokopia's 131,426 shaders at about 6 hours, mostly on one core, though its older library plays fine. The same happened at the version before. → [The Mac's pack translates every shader of a selected profile at a new library version](../reference/packing.md#the-macs-pack-translates-every-shader-of-a-selected-profile-at-a-new-library-version) - on the phone, Prepare of Mario Tennis Fever stops at "Finding the shaders" on every Retry; `split.log` ends with `[RED] /42: a CRA archive, and no NRO in DM_NRO_DIR (None) holds its file table`. The same dump packs on a computer. → [Prepare stops at the split of a game whose code a boot stub packs into `main`](../reference/packing.md#prepare-stops-at-the-split-of-a-game-whose-code-a-boot-stub-packs-into-main) - Prepare of Mario Tennis Fever stands at "Finding the shaders: reading the 1 files that hold shaders" for about an hour, one of its 56 ranges a minute on an Odin 3, with one core busy and the others idle. → [The phone's split of Camelot's archive takes about an hour on one core](../reference/packing.md#the-phones-split-of-camelots-archive-takes-about-an-hour-on-one-core) +- a files mod works at the game's own frame rate and does nothing at a frame rate that starts a variant, with nothing in the log. On Animal Crossing: New Horizons at 60 fps, ACNH Combined's River Hopping (hopping a river without a pole) stops at the bank; at Game owned, on the same save and route, it crosses. → [A frame rate variant's game data hides a mod's copy of the same file (Android)](../reference/packing.md#a-frame-rate-variants-game-data-hides-a-mods-copy-of-the-same-file-android) - Settings › Check for updates answers "You're up to date" on every phone, and no popup comes at start, for hours after a new release is published on git.eden-emu.dev (v0.2.3); the release page shows it, and `curl` of the updater's URL, `https://git.eden-emu.dev/api/v1/repos/moceure/BananaNative/releases?limit=10`, returns the old list (3 releases) with `cache-control: public, max-age=180` and `x-cache-enabled: true`, while `...?limit=11` or `...?limit=10&_=1` returns the current one (4 releases). → [The app says up to date though a newer release is on git.eden-emu.dev](../reference/packing.md#the-app-says-up-to-date-though-a-newer-release-is-on-giteden-emudev) - a game whose profile has `recommend` rows for this GPU (Ocarina of Time's `driver.id=8 driver=system` and `gpu.vendor=0x5143 res_preset=performance vegetation=off` on an Adreno 840 with Qualcomm's own driver) shows no Recommended / Custom card and no Recommended tags, on a fresh install and on a phone that has played; the start log's `[nxlaunch] settings:` line names every setting `(default)`. → [Game settings shows no "Recommended for this phone" card](../reference/packing.md#game-settings-shows-no-recommended-for-this-phone-card) - the launcher closes within seconds of every start, with `FATAL EXCEPTION: nx-pack-check`, `java.lang.OutOfMemoryError: Failed to allocate a 105294414 byte allocation` and a stack `Zstd$Frame.run` ← `Zstd.decode` ← `Nup.read` ← `BuildCheck$Mod.hash` ← `RewriteKey.keys` ← `PackCheck.codeNow`, heap `467MB/512MB`. Reinstalling the APK does not help; only deleting the app's data (the games and packs it remembers) does. → [The app closes at launch with an OutOfMemoryError in `Zstd.decode` (Android)](../reference/packing.md#the-app-closes-at-launch-with-an-outofmemoryerror-in-zstddecode-android) diff --git a/docs/reference/packing.md b/docs/reference/packing.md index db799184..48db4d40 100644 --- a/docs/reference/packing.md +++ b/docs/reference/packing.md @@ -357,6 +357,15 @@ - **Check:** `dm/tools/tests/test_split_cra.py` `Native` (every variant, against the Python loop; a library that does not load). 514 MB/s on one Mac core; the in-process split of 1.1.1 in 40 s on a Mac, every file passing the game's checksums and the tables the profile's; on an Odin 3 the split took 6 min 23 s, against about an hour. - **Found on:** [Mario Tennis Fever](../../dm/games/0400D4201C6EA000/README.md#found-on-this-game) 1.1.1, the only game with this archive. +### A frame rate variant's game data hides a mod's copy of the same file (Android) + + +- **Symptom:** a files mod works at the game's own frame rate and does nothing at a frame rate that starts a variant, with nothing in the log. On Animal Crossing: New Horizons at 60 fps, ACNH Combined's River Hopping (hopping a river without a pole) stops at the bank; at Game owned, on the same save and route, it crosses. +- **Cause:** the variant's game data (`//romfs`, the variant's rows applied to the player's own files) goes first in `DM_ROMFS_OVERLAY`, ahead of the mods, and the first root that has a file wins (`rom_overlay_path`, `hle_fs.c`). The 60 fps variant ships `Pack/StaticParam.pack`, and so does River Hopping, whose one change is a float in `Param/Actor/PlayerActor.byml` (the widest gap the player hops, 35 to 100). The variant's copy hid the mod's whole file. +- **Fix:** the pack step keeps the files the variant was made from beside it (`//romfs-orig`, `romfs_rows.make`'s `orig_out`; `Pack.variantOriginals`). At a start, `dev.peanuts.mods.VariantMerge` merges each enabled mod's copy of one of the variant's files into a copy of the variant's, three ways against that original: every value the mod changed is written unless the variant changed the same value, which keeps the variant's (its frame rate needs it). Values are matched by what they are, not by offset: SARC entries by name, BYML (v2 and later) values by their path of keys and indexes, so a mod made from another game version, laid out differently, still merges; other data of the same size merges by changed runs of bytes. Nothing is resized or moved, so a value the mod adds is not merged. A mod higher in the list wins a value two mods change, as it wins a whole file. The merged files go to `/mods_stage//variant-romfs`, first in the overlay. Each file a mod shares with the variant gets a log line: `[nxlaunch] mods: Pack/StaticParam.pack (the 60 variant's game data): ACNH-Combined: 5 values merged`, with the values kept as the variant has them and those not merged when there are any. A pack made before the originals were kept merges nothing and says `... copy is hidden: this pack has no original to merge it against (prepare the game again)`. +- **Check:** `dm/tools/tests/test_pack_android_variants.py`: `VariantMergeJvm` (made-up SARC and BYML files: a value only the mod changes, one both change, a mod laid out differently, two mods, strings, same-size data, no originals, a file that does not parse) and `Overlays` (the originals). On the real files (3.0.3's `StaticParam.pack`, the variant's made from it by the rows, ACNH Combined's, none in the repository) the merge takes 66 ms on a PC's JVM: 5 values merged, none kept, none left out. They are the hop gap and 4 floats the mod's tool rounded (0.243165 to 0.24317), which the game gets at Game owned too. A merged pack of the same values made by hand hops the river at 60 fps on an AYN Thor. +- **Found on:** [Animal Crossing: New Horizons](../../dm/games/01006F8002326000/README.md#60-fps). + ## In-app updates (Android) ### The app says up to date though a newer release is on git.eden-emu.dev diff --git a/scripts/pack_android.py b/scripts/pack_android.py index bacaeacd..327586a2 100755 --- a/scripts/pack_android.py +++ b/scripts/pack_android.py @@ -1114,7 +1114,8 @@ def variant_cut_builds(g): def variant_overlays(g, romfs, out, ids): """The variants the pack holds complete, [(variant, its RomFS overlay folder in the pack or '-')]: each module of the variant row rewritten into out/<variant>/ with its key, every one of them a build the variant has cuts for (variant_cut_builds), and its game.tsv variant_romfs rows (dm/tools/romfs_rows.py) applied to - this RomFS into out/<variant>/romfs/. Anything else (another game version, a build with code mods, rows that do not apply) is a line in the log and no row: the + this RomFS into out/<variant>/romfs/, the files they were applied to into out/<variant>/romfs-orig/ (Pack.variantOriginals: the launcher merges a mod's copy + of one of those files into the variant's, dev.peanuts.mods.VariantMerge). Anything else (another game version, a build with code mods, rows that do not apply) is a line in the log and no row: the launcher then does not start the variant (Pack.variantReady). The pack is made all the same""" rows = {r[0]: r[1] for r in g.values('variant_romfs') if len(r) > 1} out_rows = [] @@ -1125,16 +1126,16 @@ def variant_overlays(g, romfs, out, ids): if lacking or uncut: print(f'[YELLOW] variant {v} not offered: ' + '; '.join(([f'no rewritten {", ".join(lacking)}'] if lacking else []) + ([f'no cuts for build {", ".join(ids[m] for m in uncut)} of {", ".join(uncut)}'] if uncut else [])), flush=True) - shutil.rmtree(vout / 'romfs', ignore_errors=True); continue + shutil.rmtree(vout / 'romfs', ignore_errors=True); shutil.rmtree(vout / 'romfs-orig', ignore_errors=True); continue if v not in rows: out_rows.append((v, '-')); continue label = next((r[2] for r in g.values('variant') if r and r[0] == v and len(r) > 2), v) stage(f'making the {label.replace("fps", " fps")} game data from your game files') sys.path.insert(0, str(REPO / 'dm/tools')) import romfs_rows - try: made = romfs_rows.make(g.dir / rows[v], str(romfs), vout / 'romfs') + try: made = romfs_rows.make(g.dir / rows[v], str(romfs), vout / 'romfs', vout / 'romfs-orig') # the originals: what a mod's copy of a file is merged against at a start except (romfs_rows.Error, OSError) as e: print(f'[YELLOW] variant {v} not offered: its game data rows do not apply to these game files: {e}', flush=True) - shutil.rmtree(vout / 'romfs', ignore_errors=True); continue + shutil.rmtree(vout / 'romfs', ignore_errors=True); shutil.rmtree(vout / 'romfs-orig', ignore_errors=True); continue print(f' variant {v}: {len(made)} game files made from yours ({", ".join(made)})', flush=True) out_rows.append((v, f'{v}/romfs')) return out_rows