diff --git a/build.gradle b/build.gradle index 3dfbb49ae..8d77321dd 100644 --- a/build.gradle +++ b/build.gradle @@ -57,6 +57,43 @@ sourceSets.main.java { srcDirs += apiDir } +// ============================================================================ +// Scribe fixtures -- an offline generator for CustomNPC+ save data. +// +// Its own source set, so nothing here reaches the mod jar. It runs CustomNPC+'s +// own writeToNBT/writeNBT methods against a bootstrapped-but-unlaunched +// Minecraft, and writes the results into a world layout copied from each +// controller. See src/fixtures/README.md. +// ============================================================================ +sourceSets { + fixtures { + java.srcDirs = ['src/fixtures/java'] + compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath + runtimeClasspath += sourceSets.main.output + sourceSets.main.runtimeClasspath + } +} + +tasks.register('scribeFixtures', JavaExec) { + group 'CustomNPC+' + description 'Generates CustomNPC+ save fixtures for Scribe. -Pout=, -Pworlds=' + dependsOn 'fixturesClasses' + classpath = sourceSets.fixtures.runtimeClasspath + mainClass = 'kamkeel.npcs.fixtures.FixtureGenerator' + // Off the project dir, because CustomNpcs.getWorldSaveDirectory() resolves "." and + // a stray relative write would land in the repo root. + workingDir = project.buildDir + doFirst { + // Resolved against the project directory, not workingDir, so -Pout=build/x means what it + // looks like rather than build/build/x. + def out = project.hasProperty('out') ? project.file(project.property('out')) + : new File(project.buildDir, 'scribe-fixtures') + args = [out.absolutePath] + if (project.hasProperty('worlds')) { + args += ['--worlds', project.property('worlds')] + } + } +} + // ============================================================================ // TypeScript Definition Generation Task // Generates .d.ts files from Java API sources for scripting IDE support diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/Case.java b/src/fixtures/java/kamkeel/npcs/fixtures/Case.java new file mode 100644 index 000000000..490d8f7cf --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/Case.java @@ -0,0 +1,21 @@ +package kamkeel.npcs.fixtures; + +/** + * One piece of content, the category it belongs in, and why it exists. + * + *

The note is the part that does not survive serialization. A directory of numbered files says + * nothing about which one is the dialog whose availability is gated four ways, and the next person + * to need that case will otherwise author a second one. + */ +public final class Case { + + public final String category; + public final T value; + public final String note; + + public Case(String category, T value, String note) { + this.category = category; + this.value = value; + this.note = note; + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/FixtureGenerator.java b/src/fixtures/java/kamkeel/npcs/fixtures/FixtureGenerator.java new file mode 100644 index 000000000..497242782 --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/FixtureGenerator.java @@ -0,0 +1,118 @@ +package kamkeel.npcs.fixtures; + +import kamkeel.npcs.fixtures.worlds.DefaultsWorld; +import kamkeel.npcs.fixtures.worlds.EdgeWorld; +import kamkeel.npcs.fixtures.worlds.LegacyWorld; +import kamkeel.npcs.fixtures.worlds.MaximalWorld; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Generates CustomNPC+ save data offline, for use as test fixtures. + * + *

The point is that the bytes are written by CustomNPC+ itself. Hand-authoring a + * {@code factions.dat} that looks right is easy and proves nothing: it asserts what its author + * believed the format to be. Everything here goes through the shipping data classes' own + * serialization, so a fixture is evidence about the format rather than about the author. + * + *

Usage: {@code gradlew scribeFixtures -Pout=

[-Pworlds=maximal,edge]} + */ +public final class FixtureGenerator { + + private static final List ALL = Arrays.asList( + new MaximalWorld(), + new DefaultsWorld(), + new EdgeWorld(), + new LegacyWorld()); + + public static void main(String[] args) throws Exception { + if (args.length < 1) { + System.err.println("usage: FixtureGenerator [--worlds a,b,c]"); + System.exit(2); + } + File out = new File(args[0]).getAbsoluteFile(); + + List selected = new ArrayList(ALL); + for (int i = 1; i < args.length - 1; i++) { + if ("--worlds".equals(args[i])) { + selected = select(args[i + 1]); + } + } + + System.out.println("[fixtures] bootstrapping Minecraft"); + Fixtures.bootMinecraft(); + + Manifest manifest = new Manifest(); + recordKnownWarnings(manifest); + + int normalized = 0; + for (FixtureWorld world : selected) { + WorldWriter writer = new WorldWriter(out, world.name(), manifest); + manifest.world(world.name(), world.purpose()); + int before = manifest.count(); + world.build(writer); + normalized += writer.normalizedCount(); + System.out.println("[fixtures] " + pad(world.name()) + + (manifest.count() - before) + " files"); + } + + manifest.write(new File(out, "manifest.json")); + Readme.write(new File(out, "README.md"), selected, manifest); + + System.out.println("[fixtures] " + manifest.count() + " files total -> " + out); + System.out.println("[fixtures] dialogs " + manifest.countOf("dialog") + + ", quests " + manifest.countOf("quest")); + // Reported every run so the one normalization cannot quietly spread to other keys. + System.out.println("[fixtures] " + normalized + " wall-clock values pinned (TimePast)"); + } + + /** + * Facts a consumer cannot get from the bytes, and would otherwise learn from a flaky test. + * + *

Each was found by reading the writer, not by guessing. + */ + private static void recordKnownWarnings(Manifest manifest) { + manifest.warn("NORMALIZED: TimePast is pinned to 0 in every document. PlayerMail.writeNBT " + + "stamps it with System.currentTimeMillis() - time, and a PlayerMail hangs off every " + + "dialog and every quest whether or not mail was configured -- so left alone, every " + + "file here would differ between two runs and a version-controlled corpus would churn " + + "completely on each regeneration. This is the ONLY key these fixtures rewrite after " + + "CustomNPC+ produced it. Nothing reads the value back except a live-clock display."); + manifest.warn("Quest.writeToNBTPartial writes NextQuestTitle from the live QuestController, " + + "which is empty offline, so NextQuestTitle is written as the value set on the object " + + "rather than resolved from the target quest. NextQuestId is the real link."); + manifest.warn("PlayerMail.writeNBT writes MailQuestTitle only when the quest resolves in the " + + "live QuestController. Offline it never resolves, so the key is absent."); + manifest.warn("These worlds hold no level.dat and no region files. They are the customnpcs/ " + + "directory of a world, which is the part CustomNPC+ owns."); + } + + private static List select(String csv) { + Map byName = new LinkedHashMap(); + for (FixtureWorld w : ALL) { + byName.put(w.name(), w); + } + List selected = new ArrayList(); + for (String name : csv.split(",")) { + FixtureWorld w = byName.get(name.trim()); + if (w == null) { + throw new IllegalArgumentException("No such world: " + name + " (have " + byName.keySet() + ")"); + } + selected.add(w); + } + return selected; + } + + private static String pad(String name) { + StringBuilder sb = new StringBuilder(name); + while (sb.length() < 12) { + sb.append(' '); + } + return sb.toString(); + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/FixtureWorld.java b/src/fixtures/java/kamkeel/npcs/fixtures/FixtureWorld.java new file mode 100644 index 000000000..f336ad877 --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/FixtureWorld.java @@ -0,0 +1,13 @@ +package kamkeel.npcs.fixtures; + +/** One generated world. Each answers a different question, so tests can load only what they need. */ +public interface FixtureWorld { + + /** Directory name, and the name a test refers to. */ + String name(); + + /** What this world is for. Goes into the manifest, because a folder of ids explains nothing. */ + String purpose(); + + void build(WorldWriter out); +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/Fixtures.java b/src/fixtures/java/kamkeel/npcs/fixtures/Fixtures.java new file mode 100644 index 000000000..92d4c8f15 --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/Fixtures.java @@ -0,0 +1,161 @@ +package kamkeel.npcs.fixtures; + +import cpw.mods.fml.common.Loader; +import net.minecraft.init.Bootstrap; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagString; +import noppes.npcs.NoppesUtilServer; +import sun.misc.Unsafe; + +import java.lang.reflect.Field; + +/** + * Shared machinery for the fixture generator: bringing Minecraft far enough up to serialize, and + * building the item stacks the content refers to. + * + *

Nothing here decides what a fixture contains. That lives in the world builders. + */ +public final class Fixtures { + + /** + * A fixed instant, used everywhere a fixture wants a timestamp. + * + *

2021-03-14T01:59:26Z. Any constant would do; what matters is that it is a constant, so + * two runs of the generator produce the same bytes and a diff means something changed. + */ + public static final long EPOCH = 1615687166000L; + + private static boolean booted; + + private Fixtures() { + } + + /** + * Registers vanilla blocks and items so item stacks can be serialized. + * + *

{@link Item#itemRegistry} is Forge's {@code FMLControlledNamespacedRegistry}, and + * {@link noppes.npcs.NoppesUtilServer#writeItem} asks it for a registry name -- so a stack + * written before this call would be saved as {@code minecraft:air} rather than failing, which + * is the quiet kind of wrong. + */ + public static void bootMinecraft() { + if (booted) { + return; + } + installBareLoader(); + Bootstrap.func_151354_b(); + booted = true; + verifyRegistry(); + } + + /** + * Makes {@code Loader.instance()} answerable without launching FML. + * + *

Registering an item goes {@code FMLControlledNamespacedRegistry.addObject} -> + * {@code GameData.register} -> {@code GameData.addPrefix}, and addPrefix asks + * {@code Loader.instance().activeModContainer()} which namespace to use. Reaching that + * normally constructs a {@code Loader}, whose constructor builds a {@code ModClassLoader} and + * casts its parent to LaunchWrapper's {@code LaunchClassLoader} -- which fails outside a + * LaunchWrapper launch, and is where this generator first stopped. + * + *

So the singleton is filled with an allocated-but-unconstructed Loader. Its + * {@code modController} is null, {@code activeModContainer()} returns null, and addPrefix + * takes its own documented branch: "no mod container, assume minecraft". That is + * exactly the branch real vanilla registration takes, because no mod is active while + * {@code Item.registerItems()} runs. + * + *

Nothing about the naming rule is reimplemented here -- Forge still computes it. What this + * removes is only the classloader assumption. {@link #verifyRegistry()} then checks the result + * against what real CustomNPC+ save files contain, so the shortcut is measured rather than + * trusted. On the registration path {@code Loader} is touched at that one call and nowhere + * else; the other uses in GameData are world remapping and mod-declared substitutions. + */ + private static void installBareLoader() { + try { + Field instance = Loader.class.getDeclaredField("instance"); + instance.setAccessible(true); + if (instance.get(null) != null) { + return; + } + Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); + theUnsafe.setAccessible(true); + Unsafe unsafe = (Unsafe) theUnsafe.get(null); + instance.set(null, unsafe.allocateInstance(Loader.class)); + } catch (Exception e) { + throw new IllegalStateException( + "Could not install a bare FML Loader. Without it the item registry cannot be " + + "populated outside a LaunchWrapper launch.", e); + } + } + + /** + * Checks that registration produced the names real save files contain. + * + *

{@code minecraft:diamond}, not {@code diamond}: the prefix comes from Forge, and a + * generator that quietly lost it would emit fixtures that every reader tested against them + * would then agree with. The expected values here were read out of the CustomNPC+ worlds in + * {@code run/saves/}, not from the code that produces them. + */ + private static void verifyRegistry() { + String diamond = Item.itemRegistry.getNameForObject(Items.diamond); + if (!"minecraft:diamond".equals(diamond)) { + throw new IllegalStateException("Item registry produced '" + diamond + + "' where real CustomNPC+ saves contain 'minecraft:diamond'. Item stacks in these " + + "fixtures would not match anything the mod writes."); + } + NBTTagCompound probe = new NBTTagCompound(); + NoppesUtilServer.writeItem(new ItemStack(Items.golden_apple, 2, 1), probe); + if (!"minecraft:golden_apple".equals(probe.getString("id")) + || probe.getByte("Count") != 2 + || probe.getShort("Damage") != 1) { + throw new IllegalStateException( + "NoppesUtilServer.writeItem produced " + probe + ", which is not an item stack."); + } + } + + /** A stack of a vanilla item, by registry name, so the fixture reads as what it is. */ + public static ItemStack item(String registryName, int count, int damage) { + Item item = (Item) Item.itemRegistry.getObject(registryName); + if (item == null) { + throw new IllegalArgumentException("No such item: " + registryName); + } + return new ItemStack(item, count, damage); + } + + public static ItemStack item(String registryName, int count) { + return item(registryName, count, 0); + } + + /** + * A stack carrying custom NBT, which is the case that matters most to Scribe: item state above + * (id, damage) is what the Flattening and Data Components rearranged. + */ + public static ItemStack namedItem(String registryName, int count, int damage, String displayName) { + ItemStack stack = item(registryName, count, damage); + NBTTagCompound display = new NBTTagCompound(); + display.setString("Name", displayName); + NBTTagList lore = new NBTTagList(); + lore.appendTag(new NBTTagString("Written by the Scribe fixture generator")); + display.setTag("Lore", lore); + + NBTTagCompound tag = new NBTTagCompound(); + tag.setTag("display", display); + tag.setBoolean("Unbreakable", true); + tag.setInteger("RepairCost", 7); + stack.stackTagCompound = tag; + return stack; + } + + /** + * A stack whose identity is a pre-Flattening variant -- damage as a variant selector rather + * than durability. Scribe converts these through a table that throws on a gap, so a fixture + * holding one is the only way to find out which entries the table is still missing. + */ + public static ItemStack variant(String registryName, int count, int variantDamage) { + return item(registryName, count, variantDamage); + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/Manifest.java b/src/fixtures/java/kamkeel/npcs/fixtures/Manifest.java new file mode 100644 index 000000000..ac719112d --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/Manifest.java @@ -0,0 +1,159 @@ +package kamkeel.npcs.fixtures; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * An index of what was generated, why, and where it landed. + * + *

Deliberately not a second copy of the data. The files are the fixture; this says which file + * holds which case, so a test can pick the one it needs without opening twenty of them, and so a + * reviewer can see the intent that a compound of integers does not carry. + */ +public final class Manifest { + + /** One generated file. */ + public static final class Entry { + final String world; + final String system; + final String id; + final String path; + final String note; + + Entry(String world, String system, String id, String path, String note) { + this.world = world; + this.system = system; + this.id = id; + this.path = path; + this.note = note; + } + } + + private final List entries = new ArrayList(); + private final Set warnings = new LinkedHashSet(); + private final List worlds = new ArrayList(); + + public void world(String name, String purpose) { + worlds.add(new String[]{name, purpose}); + } + + public void record(String world, String system, String id, String path, String note) { + entries.add(new Entry(world, system, id, path, note)); + } + + /** + * Records something a consumer of these fixtures has to know and could not discover from the + * bytes -- above all, the places CustomNPC+ writes a value that changes between runs. + */ + public void warn(String warning) { + warnings.add(warning); + } + + public Set warnings() { + return warnings; + } + + public int count() { + return entries.size(); + } + + public int countOf(String system) { + int n = 0; + for (Entry e : entries) { + if (e.system.equals(system)) { + n++; + } + } + return n; + } + + public void write(File file) throws IOException { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + sb.append(" \"generatedBy\": \"CustomNPC+ scribeFixtures\",\n"); + sb.append(" \"note\": \"The files are the fixture. This index records intent and location, "); + sb.append("not a second copy of the data. Readable renderings of every .dat sit under "); + sb.append("/_readable/, written by CustomNPC+'s own NBTJsonUtil.\",\n"); + + sb.append(" \"warnings\": [\n"); + int wi = 0; + for (String w : warnings) { + sb.append(" ").append(quote(w)); + sb.append(++wi < warnings.size() ? ",\n" : "\n"); + } + sb.append(" ],\n"); + + sb.append(" \"worlds\": {\n"); + for (int i = 0; i < worlds.size(); i++) { + String[] w = worlds.get(i); + sb.append(" ").append(quote(w[0])).append(": ").append(quote(w[1])); + sb.append(i + 1 < worlds.size() ? ",\n" : "\n"); + } + sb.append(" },\n"); + + sb.append(" \"entries\": [\n"); + for (int i = 0; i < entries.size(); i++) { + Entry e = entries.get(i); + sb.append(" {"); + sb.append("\"world\": ").append(quote(e.world)); + sb.append(", \"system\": ").append(quote(e.system)); + sb.append(", \"id\": ").append(quote(e.id)); + sb.append(", \"path\": ").append(quote(e.path)); + sb.append(", \"note\": ").append(quote(e.note)); + sb.append("}"); + sb.append(i + 1 < entries.size() ? ",\n" : "\n"); + } + sb.append(" ]\n"); + sb.append("}\n"); + + Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); + try { + out.write(sb.toString()); + } finally { + out.close(); + } + } + + /** + * JSON string escaping. Hand-rolled rather than pulled from a library because the manifest is + * the one file here that is not written by CustomNPC+, so it should have no dependency that + * could change what it produces between environments. + */ + private static String quote(String s) { + StringBuilder sb = new StringBuilder("\""); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + switch (c) { + case '"': + sb.append("\\\""); + break; + case '\\': + sb.append("\\\\"); + break; + case '\n': + sb.append("\\n"); + break; + case '\r': + sb.append("\\r"); + break; + case '\t': + sb.append("\\t"); + break; + default: + if (c < 0x20 || c > 0x7E) { + sb.append(String.format("\\u%04x", (int) c)); + } else { + sb.append(c); + } + } + } + return sb.append('"').toString(); + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/Normalize.java b/src/fixtures/java/kamkeel/npcs/fixtures/Normalize.java new file mode 100644 index 000000000..cb5602a02 --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/Normalize.java @@ -0,0 +1,73 @@ +package kamkeel.npcs.fixtures; + +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Replaces the values CustomNPC+ writes from the wall clock with a constant. + * + *

This is the one place a generated file departs from what the mod would write, and it exists + * because of a specific property of one writer. {@code PlayerMail.writeNBT} does: + * + *

compound.setLong("TimePast", System.currentTimeMillis() - time);
+ * + *

and a {@code PlayerMail} hangs off every dialog and every quest whether or not any mail was + * configured -- so every dialog and quest file differs between two runs, on that one key. + * + *

Why normalize rather than document and accept. There is no "the" value here to be + * faithful to; the mod writes a different one every second. Left alone, regenerating rewrites all + * 70-odd files, so a corpus held in version control churns completely on every run and a real + * change is invisible in the noise. Pinning it to zero makes the corpus byte-reproducible, which + * is what lets a diff mean something. + * + *

Zero is also the honest value: {@code TimePast} means "how long ago, relative to now", and a + * file on disk has no now. Nothing reads it back -- {@code PlayerMail.readNBT} loads + * {@code timePast} and the field is only used for display against a live clock. + * + *

Every key touched is listed here rather than matched by pattern, and the count is reported, + * so this can never quietly grow to cover a field that actually matters. + */ +public final class Normalize { + + /** Keys written from the wall clock. Exhaustive, and each one deliberate. */ + private static final List WALL_CLOCK_KEYS = Arrays.asList("TimePast"); + + private Normalize() { + } + + /** Rewrites wall-clock keys in place, at any depth. Returns how many were changed. */ + public static int wallClock(NBTTagCompound compound) { + int changed = 0; + for (String key : keysOf(compound)) { + NBTBase tag = compound.getTag(key); + if (tag == null) { + continue; + } + if (WALL_CLOCK_KEYS.contains(key) && tag.getId() == 4) { + compound.setLong(key, 0L); + changed++; + } else if (tag.getId() == 10) { + changed += wallClock((NBTTagCompound) tag); + } else if (tag.getId() == 9) { + NBTTagList list = (NBTTagList) tag; + if (list.func_150303_d() == 10) { + for (int i = 0; i < list.tagCount(); i++) { + // getCompoundTagAt returns the live entry, so this edits in place. + changed += wallClock(list.getCompoundTagAt(i)); + } + } + } + } + return changed; + } + + @SuppressWarnings("unchecked") + private static List keysOf(NBTTagCompound compound) { + return new ArrayList(compound.func_150296_c()); + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/Readme.java b/src/fixtures/java/kamkeel/npcs/fixtures/Readme.java new file mode 100644 index 000000000..522f9d05d --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/Readme.java @@ -0,0 +1,79 @@ +package kamkeel.npcs.fixtures; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.List; + +/** Writes the README that ships beside the generated worlds. */ +public final class Readme { + + private Readme() { + } + + public static void write(File file, List worlds, Manifest manifest) throws IOException { + StringBuilder sb = new StringBuilder(); + sb.append("# CustomNPC+ fixtures\n\n"); + sb.append("Generated by `gradlew scribeFixtures` in the CustomNPC+ repository, on the\n"); + sb.append("`scribe` branch. Do not edit by hand -- regenerate.\n\n"); + + sb.append("## What these are\n\n"); + sb.append("Real CustomNPC+ save data, written by CustomNPC+'s own serialization running\n"); + sb.append("against a bootstrapped-but-unlaunched Minecraft. No world was played to produce\n"); + sb.append("them and no byte here was hand-authored.\n\n"); + sb.append("That distinction is the whole point. A hand-written `factions.dat` asserts what\n"); + sb.append("its author believed the format to be, so a reader tested against it only proves\n"); + sb.append("it agrees with that belief. These files are evidence about the format itself.\n\n"); + + sb.append("## Layout\n\n"); + sb.append("```\n"); + for (FixtureWorld world : worlds) { + sb.append(world.name()).append("/\n"); + sb.append(" customnpcs/ <- exactly a CustomNPC+ world directory, and nothing else\n"); + sb.append(" _readable/ <- NBTJsonUtil renderings of the .dat files, for humans\n"); + } + sb.append("manifest.json <- which file holds which case, and why\n"); + sb.append("```\n\n"); + sb.append("`customnpcs/` can be dropped straight into a save directory. `_readable/` is a\n"); + sb.append("debugging aid: it is CustomNPC+'s own JSON rendering, which suffixes scalars\n"); + sb.append("with their type (`5b`, `5L`, `1.0f`) and so is deliberately not strict JSON.\n\n"); + + sb.append("## The worlds\n\n"); + for (FixtureWorld world : worlds) { + sb.append("- **`").append(world.name()).append("`** -- ").append(world.purpose()).append("\n"); + } + sb.append("\n"); + + sb.append("## Two formats, not one\n\n"); + sb.append("- **`.dat`** -- gzipped NBT, written with `CompressedStreamTools`. Factions,\n"); + sb.append(" custom effects, recipes, magic, animations, linked items, tags, and the rest.\n"); + sb.append("- **Dialogs and quests are not `.dat`.** They are `NBTJsonUtil` text files at\n"); + sb.append(" `customnpcs/dialogs//.json`. The directory *is* the category and\n"); + sb.append(" the filename *is* the id -- neither appears inside the file, because\n"); + sb.append(" `saveDialog` writes `writeToNBTPartial`, which omits `DialogId`.\n\n"); + + sb.append("## Reproducibility\n\n"); + sb.append("Regenerating produces byte-identical output, with the exceptions below. Those\n"); + sb.append("are properties of CustomNPC+'s writers, not of this generator.\n\n"); + for (String warning : manifest.warnings()) { + sb.append("- ").append(warning).append("\n"); + } + sb.append("\n"); + + sb.append("## Totals\n\n"); + sb.append("`").append(manifest.count()).append("` files: "); + sb.append(manifest.countOf("dialog")).append(" dialogs, "); + sb.append(manifest.countOf("quest")).append(" quests, "); + sb.append(manifest.count() - manifest.countOf("dialog") - manifest.countOf("quest")); + sb.append(" other documents.\n"); + + Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); + try { + out.write(sb.toString()); + } finally { + out.close(); + } + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/WorldWriter.java b/src/fixtures/java/kamkeel/npcs/fixtures/WorldWriter.java new file mode 100644 index 000000000..225ebd01a --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/WorldWriter.java @@ -0,0 +1,189 @@ +package kamkeel.npcs.fixtures; + +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.NoppesStringUtils; +import noppes.npcs.controllers.data.Dialog; +import noppes.npcs.controllers.data.Quest; +import noppes.npcs.util.NBTJsonUtil; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; + +/** + * Writes one CustomNPC+ world. + * + *

What is authoritative and what is copied. Every byte of content here comes from + * CustomNPC+'s own {@code writeToNBT} / {@code writeNBT} and from {@link NBTJsonUtil} and + * {@link CompressedStreamTools}. What this class supplies is only where the file goes and what + * it is called, because the controllers reach that through + * {@code CustomNpcs.getWorldSaveDirectory()}, which returns null without a running server, and + * because every {@code save*} fires {@code SyncController.syncUpdate} into a network stack that + * does not exist offline. + * + *

So each method below names the controller and method it was copied from. If a layout changes + * upstream, that reference is where to look. The layout logic is a handful of lines per system; + * the serialization, which is the part a fixture actually asserts, is never reimplemented. + * + *

The generated {@code /customnpcs/} directory is exactly a CustomNPC+ world and holds + * nothing else. Readable renderings of the binary files go in a sibling {@code _readable/} tree so + * that dropping {@code customnpcs/} into a real save is safe. + */ +public final class WorldWriter { + + private final String world; + private final File root; + private final File customnpcs; + private final File readable; + private final Manifest manifest; + private int normalized; + + public WorldWriter(File outputRoot, String world, Manifest manifest) { + this.world = world; + this.root = new File(outputRoot, world); + this.customnpcs = new File(root, "customnpcs"); + this.readable = new File(root, "_readable"); + this.manifest = manifest; + mkdirs(customnpcs); + mkdirs(readable); + } + + public String world() { + return world; + } + + // ------------------------------------------------------------------ + // Dialogs -- DialogController.saveDialog / loadCategoryDir + // + // The directory is the category and the filename is the id. Neither appears inside the file: + // saveDialog writes writeToNBTPartial, which omits DialogId, and loadCategoryDir recovers the + // id by parsing the filename. A dialog's identity is where it sits. + // ------------------------------------------------------------------ + public void dialog(String category, Dialog dialog, String note) { + String dir = NoppesStringUtils.cleanFileName(category); + File file = new File(new File(customnpcs, "dialogs"), dir + "/" + dialog.id + ".json"); + writeJson(file, dialog.writeToNBTPartial(new NBTTagCompound())); + manifest.record(world, "dialog", String.valueOf(dialog.id), rel(file), note); + } + + // ------------------------------------------------------------------ + // Quests -- QuestController.saveQuest / loadCategoryDir + // + // Same shape as dialogs, and the same identity rule. + // ------------------------------------------------------------------ + public void quest(String category, Quest quest, String note) { + String dir = NoppesStringUtils.cleanFileName(category); + File file = new File(new File(customnpcs, "quests"), dir + "/" + quest.id + ".json"); + writeJson(file, quest.writeToNBTPartial(new NBTTagCompound())); + manifest.record(world, "quest", String.valueOf(quest.id), rel(file), note); + } + + /** + * A dialog written from a compound rather than from a {@link Dialog}. + * + *

Only for the legacy world, which ages a document by removing keys a newer CustomNPC+ + * added. The compound still comes from CustomNPC+'s writer; what is synthesized is the + * subtraction. Every caller must say in its note which keys it removed and why. + */ + public void dialogRaw(String category, int id, NBTTagCompound compound, String note) { + String dir = NoppesStringUtils.cleanFileName(category); + File file = new File(new File(customnpcs, "dialogs"), dir + "/" + id + ".json"); + writeJson(file, compound); + manifest.record(world, "dialog", String.valueOf(id), rel(file), note); + } + + /** As {@link #dialogRaw}, for quests. */ + public void questRaw(String category, int id, NBTTagCompound compound, String note) { + String dir = NoppesStringUtils.cleanFileName(category); + File file = new File(new File(customnpcs, "quests"), dir + "/" + id + ".json"); + writeJson(file, compound); + manifest.record(world, "quest", String.valueOf(id), rel(file), note); + } + + /** + * A gzipped NBT document at the root of the world. + * + *

The shape every {@code .dat} controller uses -- FactionController.saveFactions, + * CustomEffectController.saveCustomEffects, GlobalDataController.save and the rest: build one + * compound, {@code CompressedStreamTools.writeCompressed} it, rotate the previous file to + * {@code _old}. The rotation is not reproduced, because a generated world has no previous file + * and inventing a {@code .dat_old} would be inventing history. + */ + public void dat(String system, String fileName, NBTTagCompound compound, String note) { + File file = new File(customnpcs, fileName); + mkdirs(file.getParentFile()); + normalized += Normalize.wallClock(compound); + try { + OutputStream out = new FileOutputStream(file); + try { + CompressedStreamTools.writeCompressed(compound, out); + } finally { + out.close(); + } + } catch (IOException e) { + throw new IllegalStateException("Failed writing " + file, e); + } + renderReadable(fileName, compound); + manifest.record(world, system, fileName, rel(file), note); + } + + /** A JSON document at an explicit path under {@code customnpcs/}, for the per-player records. */ + public void json(String system, String id, String relativePath, NBTTagCompound compound, String note) { + File file = new File(customnpcs, relativePath); + writeJson(file, compound); + manifest.record(world, system, id, rel(file), note); + } + + private void writeJson(File file, NBTTagCompound compound) { + mkdirs(file.getParentFile()); + normalized += Normalize.wallClock(compound); + try { + NBTJsonUtil.SaveFile(file, compound); + } catch (Exception e) { + throw new IllegalStateException("Failed writing " + file, e); + } + } + + /** How many wall-clock values were pinned in this world. See {@link Normalize}. */ + public int normalizedCount() { + return normalized; + } + + /** + * Writes CustomNPC+'s own JSON rendering of a binary document beside the world, for reading. + * + *

Not a fixture and not parseable as strict JSON -- NBTJsonUtil suffixes scalars with their + * type ({@code 5b}, {@code 5L}, {@code 1.0f}), which is exactly what makes it worth having: + * the widths are visible, and a fixture whose value silently became a byte shows up here. + */ + private void renderReadable(String fileName, NBTTagCompound compound) { + File file = new File(readable, fileName + ".txt"); + mkdirs(file.getParentFile()); + try { + Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); + try { + out.write(NBTJsonUtil.Convert(compound)); + } finally { + out.close(); + } + } catch (IOException e) { + throw new IllegalStateException("Failed writing " + file, e); + } + } + + private String rel(File file) { + String base = root.getAbsolutePath(); + String path = file.getAbsolutePath(); + return path.startsWith(base) ? path.substring(base.length() + 1).replace('\\', '/') : path; + } + + private static void mkdirs(File dir) { + if (dir != null && !dir.exists() && !dir.mkdirs()) { + throw new IllegalStateException("Could not create " + dir); + } + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/content/DialogFixtures.java b/src/fixtures/java/kamkeel/npcs/fixtures/content/DialogFixtures.java new file mode 100644 index 000000000..e43b959d0 --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/content/DialogFixtures.java @@ -0,0 +1,484 @@ +package kamkeel.npcs.fixtures.content; + +import kamkeel.npcs.fixtures.Case; +import kamkeel.npcs.fixtures.Fixtures; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.EnumAvailabilityDialog; +import noppes.npcs.constants.EnumAvailabilityFaction; +import noppes.npcs.constants.EnumAvailabilityFactionType; +import noppes.npcs.constants.EnumAvailabilityQuest; +import noppes.npcs.constants.EnumDayTime; +import noppes.npcs.constants.EnumOptionType; +import noppes.npcs.controllers.data.Dialog; +import noppes.npcs.controllers.data.DialogImage; +import noppes.npcs.controllers.data.DialogOption; + +import java.util.ArrayList; +import java.util.List; + +/** + * Dialogs, built by axis rather than by example. + * + *

A dialog has about forty fields across six sub-objects, and picking a few realistic-looking + * ones covers the fields the author happened to think of. So each block below walks one axis to + * its ends -- every enum constant, every slot, both sides of every boolean -- and the id ranges + * are reserved per axis so a new case does not renumber the others. + * + *

Ranges: 1-9 basics, 10-29 options, 30-59 availability, 60-79 appearance, 80-89 images, + * 90-99 mail / quest link / faction rewards. + */ +public final class DialogFixtures { + + private DialogFixtures() { + } + + public static List> maximal() { + List> out = new ArrayList>(); + basics(out); + options(out); + availability(out); + appearance(out); + images(out); + attachments(out); + return out; + } + + // ------------------------------------------------------------------ basics + + private static void basics(List> out) { + Dialog bare = dialog(1, "Bare", ""); + out.add(new Case

("Basics", bare, + "every field left at its constructor default, with an empty text. The baseline a " + + "reader's defaults are compared against")); + + Dialog plain = dialog(2, "Plain Greeting", + "Hello {player},\n\nWelcome to our village. I hope you enjoy your stay"); + out.add(new Case("Basics", plain, + "title and text only, with the {player} placeholder and embedded newlines that " + + "CustomNPC+'s own default dialog uses")); + + Dialog longText = dialog(3, "Long Text", repeat( + "This sentence exists so the stored text crosses the length CustomNPC+ warns about. ", 200)); + out.add(new Case("Basics", longText, + "text over 15000 chars, which DialogController logs as an 'Extremely big dialog'. " + + "Loads normally -- the check is a warning, not a limit")); + + Dialog unicode = dialog(4, Text.KATAKANA_FACTION + " " + Text.EM_DASH + " " + Text.ELEVES, + Text.CYRILLIC_QUEST + "\n" + Text.RTL + "\n" + Text.ASTRAL); + out.add(new Case("Basics", unicode, + "title and text outside Latin-1, including one astral-plane code point. NBT strings " + + "are modified UTF-8, so the astral char is stored as a surrogate pair")); + + Dialog formatted = dialog(5, Text.SECTION + "6Formatted " + Text.SECTION + "lTitle", + Text.SECTION + "cRed " + Text.SECTION + "aGreen " + Text.SECTION + "r" + "plain"); + out.add(new Case("Basics", formatted, + "section-sign colour codes in title and text, which is how all CustomNPC+ content is " + + "coloured")); + + Dialog command = dialog(6, "Runs A Command", "The gate opens."); + command.command = "/say {player} opened the gate"; + out.add(new Case("Basics", command, + "DialogCommand set -- a command run on the server when the dialog opens")); + + Dialog sounds = dialog(7, "Sounds", "Listen."); + sounds.sound = "customnpcs:dialog.open"; + sounds.textSound = "minecraft:random.orb"; + sounds.textPitch = 0.75F; + out.add(new Case("Basics", sounds, + "DialogSound plus a non-default TextSound and TextPitch. Note DialogSound is written " + + "only when non-empty, so the key is absent on every other dialog here")); + } + + // ------------------------------------------------------------------ options + + private static void options(List> out) { + // One dialog per option type, because the type drives what the other fields mean. + int id = 10; + for (EnumOptionType type : EnumOptionType.values()) { + Dialog d = dialog(id, "Option " + type.name(), "Choose."); + DialogOption option = new DialogOption(); + option.title = type.name() + " option"; + option.optionType = type; + option.dialogId = type == EnumOptionType.DialogOption ? 2 : -1; + option.optionColor = 0x00FF00; + option.command = type == EnumOptionType.CommandBlock ? "/time set day" : ""; + d.options.put(0, option); + out.add(new Case("Options", d, + "a single option of type " + type.name() + " (ordinal " + type.ordinal() + ")")); + id++; + } + + Dialog full = dialog(20, "Six Options", "Pick one."); + for (int slot = 0; slot < 6; slot++) { + DialogOption option = new DialogOption(); + option.title = "Option in slot " + slot; + option.optionType = EnumOptionType.DialogOption; + option.dialogId = 2; + option.optionColor = 0x100000 * (slot + 1); + full.options.put(slot, option); + } + out.add(new Case("Options", full, + "six options in contiguous slots 0-5, each a different colour")); + + // Slots are a map key, not a list index. A reader that treats Options as an ordered list + // silently renumbers this one. + Dialog sparse = dialog(21, "Sparse Slots", "The gaps matter."); + int[] slots = {0, 3, 7, 12}; + for (int slot : slots) { + DialogOption option = new DialogOption(); + option.title = "Slot " + slot; + option.optionType = EnumOptionType.DialogOption; + option.dialogId = 2; + sparse.options.put(slot, option); + } + out.add(new Case("Options", sparse, + "options at non-contiguous slots 0, 3, 7 and 12. OptionSlot is stored per entry, so " + + "the gaps survive; a reader treating the list as positional loses them")); + + Dialog dangling = dialog(22, "Dangling Option", "Where does this go?"); + DialogOption toNowhere = new DialogOption(); + toNowhere.title = "To a dialog that is not here"; + toNowhere.optionType = EnumOptionType.DialogOption; + toNowhere.dialogId = 999999; + dangling.options.put(0, toNowhere); + out.add(new Case("Options", dangling, + "an option pointing at a dialog id that does not exist in this world. Conversion must " + + "keep the id rather than resolve it")); + + Dialog emptyTitle = dialog(23, "Empty Option Title", "..."); + DialogOption blank = new DialogOption(); + blank.title = ""; + blank.optionType = EnumOptionType.DialogOption; + blank.dialogId = 2; + blank.optionColor = 0; + emptyTitle.options.put(0, blank); + out.add(new Case("Options", emptyTitle, + "an option with an empty title and DialogColor 0. On read, colour 0 is replaced by the " + + "default 0xe0e0e0 -- so this file does not round-trip, by design upstream")); + } + + // ------------------------------------------------------------------ availability + + private static void availability(List> out) { + // Every EnumAvailabilityQuest constant, one dialog each. These are the rules whose loss + // makes a gated dialog visible to everybody, so each constant gets its own file. + int id = 30; + for (EnumAvailabilityQuest rule : EnumAvailabilityQuest.values()) { + Dialog d = dialog(id, "Quest rule " + rule.name(), "Gated on a quest."); + d.availability.questAvailable = rule; + d.availability.questId = 1; + out.add(new Case("Availability", d, + "AvailabilityQuest = " + rule.name() + " (ordinal " + rule.ordinal() + + ") against quest 1")); + id++; + } + + // All four quest slots at once, each a different rule and a different target. + Dialog fourQuests = dialog(40, "Four Quest Rules", "Four gates."); + fourQuests.availability.questAvailable = EnumAvailabilityQuest.After; + fourQuests.availability.questId = 1; + fourQuests.availability.quest2Available = EnumAvailabilityQuest.Before; + fourQuests.availability.quest2Id = 2; + fourQuests.availability.quest3Available = EnumAvailabilityQuest.Active; + fourQuests.availability.quest3Id = 3; + fourQuests.availability.quest4Available = EnumAvailabilityQuest.NotAcceptable; + fourQuests.availability.quest4Id = 4; + out.add(new Case("Availability", fourQuests, + "all four AvailabilityQuest slots set to different rules and different quests. The " + + "case a reader that reads only the first slot passes anyway")); + + int dialogRuleId = 41; + for (EnumAvailabilityDialog rule : EnumAvailabilityDialog.values()) { + Dialog d = dialog(dialogRuleId, "Dialog rule " + rule.name(), "Gated on a dialog."); + d.availability.dialogAvailable = rule; + d.availability.dialogId = 2; + out.add(new Case("Availability", d, + "AvailabilityDialog = " + rule.name() + " against dialog 2 -- read tracking")); + dialogRuleId++; + } + + Dialog fourDialogs = dialog(44, "Four Dialog Rules", "Four read-gates."); + fourDialogs.availability.dialogAvailable = EnumAvailabilityDialog.After; + fourDialogs.availability.dialogId = 1; + fourDialogs.availability.dialog2Available = EnumAvailabilityDialog.Before; + fourDialogs.availability.dialog2Id = 2; + fourDialogs.availability.dialog3Available = EnumAvailabilityDialog.After; + fourDialogs.availability.dialog3Id = 3; + fourDialogs.availability.dialog4Available = EnumAvailabilityDialog.Before; + fourDialogs.availability.dialog4Id = 4; + out.add(new Case("Availability", fourDialogs, + "all four AvailabilityDialog slots set")); + + // Faction rules: type x stance, both slots. + int factionRuleId = 45; + for (EnumAvailabilityFactionType type : EnumAvailabilityFactionType.values()) { + for (EnumAvailabilityFaction stance : EnumAvailabilityFaction.values()) { + if (type == EnumAvailabilityFactionType.Always && stance != EnumAvailabilityFaction.Friendly) { + continue; // Always ignores the stance; one file is enough for it. + } + Dialog d = dialog(factionRuleId, "Faction " + type.name() + " " + stance.name(), + "Gated on standing."); + d.availability.factionAvailable = type; + d.availability.factionStance = stance; + d.availability.factionId = 10; + out.add(new Case("Availability", d, + "AvailabilityFaction = " + type.name() + ", stance " + stance.name() + + ", against faction 10 (Hidden Watchers)")); + factionRuleId++; + } + } + + Dialog bothFactions = dialog(53, "Both Faction Slots", "Two standings."); + bothFactions.availability.factionAvailable = EnumAvailabilityFactionType.Is; + bothFactions.availability.factionStance = EnumAvailabilityFaction.Friendly; + bothFactions.availability.factionId = 0; + bothFactions.availability.faction2Available = EnumAvailabilityFactionType.IsNot; + bothFactions.availability.faction2Stance = EnumAvailabilityFaction.Hostile; + bothFactions.availability.faction2Id = 2; + out.add(new Case("Availability", bothFactions, + "both faction slots, one Is/Friendly and one IsNot/Hostile")); + + int daytimeId = 54; + for (EnumDayTime time : EnumDayTime.values()) { + Dialog d = dialog(daytimeId, "Daytime " + time.name(), "Time-gated."); + d.availability.daytime = time; + out.add(new Case("Availability", d, + "AvailabilityDayTime = " + time.name() + " (ordinal " + time.ordinal() + ")")); + daytimeId++; + } + + Dialog level = dialog(57, "Min Level", "You look experienced."); + level.availability.minPlayerLevel = 30; + out.add(new Case("Availability", level, + "AvailabilityMinPlayerLevel = 30")); + + Dialog everything = dialog(58, "Every Rule At Once", "Nothing gets through this."); + everything.availability.daytime = EnumDayTime.Night; + everything.availability.minPlayerLevel = 99; + everything.availability.dialogAvailable = EnumAvailabilityDialog.After; + everything.availability.dialogId = 1; + everything.availability.dialog2Available = EnumAvailabilityDialog.Before; + everything.availability.dialog2Id = 2; + everything.availability.dialog3Available = EnumAvailabilityDialog.After; + everything.availability.dialog3Id = 3; + everything.availability.dialog4Available = EnumAvailabilityDialog.Before; + everything.availability.dialog4Id = 4; + everything.availability.questAvailable = EnumAvailabilityQuest.After; + everything.availability.questId = 1; + everything.availability.quest2Available = EnumAvailabilityQuest.Active; + everything.availability.quest2Id = 2; + everything.availability.quest3Available = EnumAvailabilityQuest.NotActive; + everything.availability.quest3Id = 3; + everything.availability.quest4Available = EnumAvailabilityQuest.Acceptable; + everything.availability.quest4Id = 4; + everything.availability.factionAvailable = EnumAvailabilityFactionType.Is; + everything.availability.factionStance = EnumAvailabilityFaction.Friendly; + everything.availability.factionId = 0; + everything.availability.faction2Available = EnumAvailabilityFactionType.IsNot; + everything.availability.faction2Stance = EnumAvailabilityFaction.Hostile; + everything.availability.faction2Id = 2; + out.add(new Case("Availability", everything, + "every availability slot set simultaneously -- ten rules plus daytime and level. The " + + "single densest availability block in these fixtures")); + } + + // ------------------------------------------------------------------ appearance + + private static void appearance(List> out) { + Dialog flags = dialog(60, "Flags Inverted", "Every boolean off its default."); + flags.hideNPC = true; + flags.showWheel = true; + flags.disableEsc = true; + flags.darkenScreen = false; + flags.showOptionLine = false; + flags.renderGradual = true; + flags.showPreviousBlocks = false; + out.add(new Case("Appearance", flags, + "all seven display booleans flipped away from their defaults. Four of them read back " + + "as true when their key is absent, so a writer that omits defaults changes " + + "behaviour")); + + Dialog colors = dialog(61, "Colors", "Coloured."); + colors.color = 0x336699; + colors.titleColor = 0xCC3300; + out.add(new Case("Appearance", colors, + "Color and TitleColor off the 0xe0e0e0 default")); + + Dialog colorData = dialog(62, "Color Data Enabled", "Full chrome colours."); + colorData.colorData.setEnableColorSettings(true); + colorData.colorData.setLineColor1(0xff112233); + colorData.colorData.setLineColor2(0xff445566); + colorData.colorData.setLineColor3(0xff778899); + colorData.colorData.setSlotColor(0xffaabbcc); + colorData.colorData.setButtonAcceptColor(0xff00ff00); + colorData.colorData.setButtonRejectColor(0xffff0000); + out.add(new Case("Appearance", colorData, + "DialogColorData with ColorSettings enabled and all six colours set. The six keys are " + + "written ONLY when the flag is on -- see id 63 for the other half")); + + Dialog colorDataOff = dialog(63, "Color Data Disabled", "Colours set but not enabled."); + colorDataOff.colorData.setEnableColorSettings(false); + colorDataOff.colorData.setLineColor1(0xff112233); + colorDataOff.colorData.setSlotColor(0xffaabbcc); + out.add(new Case("Appearance", colorDataOff, + "ColorSettings off with colours assigned. Proves the six colour keys are absent from " + + "the file, so the values are lost upstream and there is nothing to convert")); + + Dialog layout = dialog(64, "Layout", "Positioned."); + layout.textWidth = 420; + layout.textHeight = 260; + layout.textOffsetX = -12; + layout.textOffsetY = 34; + layout.titlePos = 2; + layout.titleOffsetX = 8; + layout.titleOffsetY = -6; + layout.optionOffsetX = 5; + layout.optionOffsetY = -5; + layout.optionSpaceX = 3; + layout.optionSpaceY = 14; + layout.npcScale = 2.25F; + layout.npcOffsetX = -40; + layout.npcOffsetY = 18; + out.add(new Case("Appearance", layout, + "every geometry field set, several negative. Fourteen integers and one float that a " + + "dialog screen has to place things by")); + + for (byte alignment = 0; alignment <= 2; alignment++) { + Dialog d = dialog(65 + alignment, "Alignment " + alignment, "Aligned."); + d.alignment = alignment; + out.add(new Case("Appearance", d, + "DialogAlignment = " + alignment + " (0 bottom, 1 top, 2 centre). Stored as a byte, " + + "not an int -- the one narrow scalar on a dialog")); + } + } + + // ------------------------------------------------------------------ images + + private static void images(List> out) { + Dialog one = dialog(80, "One Image", "Look."); + one.dialogImages.put(0, image(0, "customnpcs:textures/gui/dialog.png", 1)); + out.add(new Case("Images", one, + "a single DialogImage with every field at a non-default")); + + Dialog many = dialog(81, "Three Images", "Look again."); + for (int i = 0; i < 3; i++) { + DialogImage img = image(i, "customnpcs:textures/gui/image" + i + ".png", i); + img.x = 10 * i; + img.y = 20 * i; + img.alignment = i; + many.dialogImages.put(i, img); + } + out.add(new Case("Images", many, + "three images with imageType 0, 1 and 2 -- Default, Text and Option")); + + Dialog defaults = dialog(82, "Default Image", "An untouched image."); + defaults.dialogImages.put(0, new DialogImage(0)); + out.add(new Case("Images", defaults, + "a DialogImage left entirely at its constructor defaults, including an empty texture")); + } + + // ------------------------------------------------------------------ attachments + + private static void attachments(List> out) { + Dialog quest = dialog(90, "Starts A Quest", "Take this."); + quest.quest = 1; + out.add(new Case("Attachments", quest, + "DialogQuest = 1 -- opening this dialog starts quest 1. The link a conversion that " + + "drops the field turns into a quest nobody can be given")); + + Dialog mail = dialog(91, "Sends Mail", "Check your inbox."); + mail.mail.subject = "A letter from the village"; + mail.mail.sender = "Elder Marrow"; + mail.mail.time = Fixtures.EPOCH; + mail.mail.beenRead = false; + NBTTagCompound message = new NBTTagCompound(); + message.setString("Text", "Thank you for your help."); + mail.mail.message = message; + mail.mail.items[0] = Fixtures.item("minecraft:golden_apple", 3, 1); + mail.mail.items[2] = Fixtures.namedItem("minecraft:diamond_sword", 1, 12, "Villager's Thanks"); + out.add(new Case("Attachments", mail, + "DialogMail with subject, sender, a message compound and two of four item slots -- " + + "one of them a variant damage, one carrying custom NBT. NOTE: TimePast inside " + + "this compound is not reproducible between runs")); + + Dialog reward = dialog(92, "Faction Reward", "The Legion remembers."); + reward.factionOptions.factionId = 14; + reward.factionOptions.factionPoints = 250; + reward.factionOptions.decreaseFactionPoints = false; + reward.factionOptions.faction2Id = 15; + reward.factionOptions.faction2Points = 100; + reward.factionOptions.decreaseFaction2Points = true; + out.add(new Case("Attachments", reward, + "both faction reward slots -- one granting points, one decreasing them")); + + Dialog everything = dialog(93, "Everything At Once", + "This dialog exercises every sub-object CustomNPC+ hangs off a dialog."); + everything.quest = 2; + everything.command = "/say done"; + everything.sound = "customnpcs:dialog.open"; + everything.color = 0x445566; + everything.titleColor = 0x998877; + everything.hideNPC = true; + everything.renderGradual = true; + everything.npcScale = 1.5F; + everything.availability.daytime = EnumDayTime.Day; + everything.availability.minPlayerLevel = 5; + everything.availability.questAvailable = EnumAvailabilityQuest.Before; + everything.availability.questId = 3; + everything.factionOptions.factionId = 0; + everything.factionOptions.factionPoints = 10; + everything.colorData.setEnableColorSettings(true); + everything.colorData.setSlotColor(0xff00ffff); + everything.mail.subject = "Everything"; + everything.mail.sender = "The Generator"; + everything.mail.time = Fixtures.EPOCH; + everything.mail.items[0] = Fixtures.item("minecraft:emerald", 64); + everything.dialogImages.put(0, image(0, "customnpcs:textures/gui/all.png", 2)); + DialogOption opt = new DialogOption(); + opt.title = "Continue"; + opt.optionType = EnumOptionType.DialogOption; + opt.dialogId = 2; + opt.optionColor = 0xFFAA00; + everything.options.put(0, opt); + out.add(new Case("Attachments", everything, + "one dialog touching every sub-object at once: options, availability, faction rewards, " + + "colour data, mail, an image and a quest link")); + } + + // ------------------------------------------------------------------ helpers + + private static Dialog dialog(int id, String title, String text) { + Dialog dialog = new Dialog(); + dialog.id = id; + dialog.title = title; + dialog.text = text; + return dialog; + } + + private static DialogImage image(int id, String texture, int imageType) { + DialogImage image = new DialogImage(id); + image.texture = texture; + image.x = 12; + image.y = 34; + image.width = 64; + image.height = 48; + image.textureX = 8; + image.textureY = 16; + image.scale = 1.75F; + image.color = 0x88CCFF; + image.selectedColor = 0xFFCC88; + image.alpha = 0.5F; + image.rotation = 45.0F; + image.imageType = imageType; + image.alignment = 1; + return image; + } + + static String repeat(String s, int times) { + StringBuilder sb = new StringBuilder(s.length() * times); + for (int i = 0; i < times; i++) { + sb.append(s); + } + return sb.toString(); + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/content/FactionFixtures.java b/src/fixtures/java/kamkeel/npcs/fixtures/content/FactionFixtures.java new file mode 100644 index 000000000..1410206ba --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/content/FactionFixtures.java @@ -0,0 +1,153 @@ +package kamkeel.npcs.fixtures.content; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.data.Faction; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Factions, and the {@code factions.dat} document that holds them. + * + *

Layout copied from FactionController.getNBT: {@code lastID} plus an {@code NPCFactions} list + * of {@link Faction#writeNBT} compounds. The controller iterates a HashMap; this iterates a list, + * so the order is stable between runs. Order is not part of the format -- the loader keys each + * entry on its own {@code Slot} -- but an unstable order would make every regeneration a diff. + */ +public final class FactionFixtures { + + private FactionFixtures() { + } + + /** The three CustomNPC+ creates for a new world, when factions.dat is absent or empty. */ + public static List vanillaDefaults() { + return new ArrayList(Arrays.asList( + new Faction(0, "Friendly", 0x00DD00, 2000), + new Faction(1, "Neutral", 0xF2DD00, 1000), + new Faction(2, "Aggressive", 0xDD0000, 0))); + } + + /** + * Every flag and threshold moved off its default, and the mutual-hostility graph populated. + * + *

The three booleans are the interesting part for a port: {@code hideFaction} suppresses the + * standing message, {@code getsAttacked} lets vanilla mobs target members, {@code isPassive} + * stops members retaliating. They are independent, so they get an entry each rather than one + * faction with all three set. + */ + public static List maximal() { + List factions = vanillaDefaults(); + + Faction hidden = faction(10, "Hidden Watchers", 0x2B2B2B, 900); + hidden.hideFaction = true; + hidden.neutralPoints = 250; + hidden.friendlyPoints = 2750; + factions.add(hidden); + + Faction attacked = faction(11, "Hunted", 0xAA5500, 1200); + attacked.getsAttacked = true; + factions.add(attacked); + + Faction passive = faction(12, "Pacifists", 0x55FFFF, 1800); + passive.isPassive = true; + factions.add(passive); + + Faction all = faction(13, "Every Flag", 0xFF00FF, 0); + all.hideFaction = true; + all.getsAttacked = true; + all.isPassive = true; + all.neutralPoints = 0; + all.friendlyPoints = 0; + factions.add(all); + + // A hostility graph rather than a single edge: the reader has to keep a set per faction, + // and a reader that keeps one integer looks correct until the second entry. + Faction warring = faction(14, "Iron Legion", 0xB0B0B0, 400); + warring.attackFactions.addAll(Arrays.asList(2, 10, 11, 12)); + factions.add(warring); + + Faction rival = faction(15, "Ash Covenant", 0x7A0000, 600); + rival.attackFactions.addAll(Arrays.asList(14, 0)); + factions.add(rival); + + // Thresholds inverted -- friendly below neutral. CustomNPC+ does not validate this, and + // Availability and Faction read the boundary differently, so it is worth having on disk. + Faction inverted = faction(16, "Inverted Bands", 0x123456, 1000); + inverted.neutralPoints = 1800; + inverted.friendlyPoints = 200; + factions.add(inverted); + + Faction negative = faction(17, "Debtors", 0x000080, -500); + negative.neutralPoints = -1000; + negative.friendlyPoints = -100; + factions.add(negative); + + return factions; + } + + /** Names and values that are legal, unusual, and have broken a reader somewhere. */ + public static List edge() { + List factions = new ArrayList(); + + factions.add(faction(0, "", 0, 0)); + + // Built from code points rather than written as literals. This source stays pure ASCII on + // purpose: a generator whose own file gets mojibaked by a CP-1252 toolchain would emit + // fixtures that assert the mojibake, and every reader downstream would agree with it. + Faction unicode = faction(1, Text.KATAKANA_FACTION + " " + Text.EM_DASH + " " + Text.ELEVES, + 0xFFFFFF, 1000); + factions.add(unicode); + + Faction formatting = faction(2, + Text.SECTION + "cRed " + Text.SECTION + "lBold" + Text.SECTION + "r", 0xFF5555, 1000); + factions.add(formatting); + + Faction longName = faction(3, repeat("Faction With A Very Long Name ", 12), 0x00FF00, 1000); + factions.add(longName); + + Faction extremes = faction(4, "Integer Extremes", 0xFFFFFF, Integer.MAX_VALUE); + extremes.neutralPoints = Integer.MIN_VALUE; + extremes.friendlyPoints = Integer.MAX_VALUE; + extremes.color = -1; + factions.add(extremes); + + // Points to factions that are not in this file. A converter that resolves eagerly breaks + // here; one that keeps the id does not. + Faction dangling = faction(5, "Dangling References", 0x808080, 1000); + dangling.attackFactions.addAll(Arrays.asList(9001, -3, 0)); + factions.add(dangling); + + // A non-contiguous, high id. Nothing requires ids to be dense, and lastID is separate. + factions.add(faction(4096, "Sparse Id", 0x00FFFF, 1000)); + + return factions; + } + + /** The controller-shaped document. Copied from FactionController.getNBT. */ + public static NBTTagCompound document(List factions, int lastUsedId) { + NBTTagList list = new NBTTagList(); + for (Faction faction : factions) { + NBTTagCompound tag = new NBTTagCompound(); + faction.writeNBT(tag); + list.appendTag(tag); + } + NBTTagCompound compound = new NBTTagCompound(); + compound.setInteger("lastID", lastUsedId); + compound.setTag("NPCFactions", list); + return compound; + } + + private static Faction faction(int id, String name, int color, int defaultPoints) { + return new Faction(id, name, color, defaultPoints); + } + + private static String repeat(String s, int times) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < times; i++) { + sb.append(s); + } + return sb.toString(); + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/content/Text.java b/src/fixtures/java/kamkeel/npcs/fixtures/content/Text.java new file mode 100644 index 000000000..e9e523045 --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/content/Text.java @@ -0,0 +1,52 @@ +package kamkeel.npcs.fixtures.content; + +/** + * Non-ASCII strings the fixtures use, built from code points. + * + *

Every source file here is pure ASCII, and this class is why. A generator whose own source has + * been mojibaked by a CP-1252 toolchain emits fixtures that contain the mojibake, and then every + * reader tested against those fixtures agrees with it -- the corruption becomes the specification. + * Writing the code points out removes the whole class of accident, at the cost of one indirection. + * + *

The strings themselves matter: CustomNPC+ content is authored by players, in every language, + * with the section sign used for colour codes throughout. + */ +public final class Text { + + private Text() { + } + + /** The colour-code prefix, U+00A7. Appears in CustomNPC+'s own default effect name. */ + public static final String SECTION = cp(0x00A7); + + /** U+2014. Punctuation above Latin-1 that a byte-oriented reader truncates. */ + public static final String EM_DASH = cp(0x2014); + + /** "Eleves" with acute and grave accents -- two-byte UTF-8, still one char in Java. */ + public static final String ELEVES = cp(0x00C9, 0x6C, 0x00E8, 0x76, 0x65, 0x73); + + /** Katakana for "faction". Three-byte UTF-8, and outside anything CP-1252 can represent. */ + public static final String KATAKANA_FACTION = cp(0x30D5, 0x30A1, 0x30AF, 0x30B7, 0x30E7, 0x30F3); + + /** Cyrillic "Zadanie" (quest). */ + public static final String CYRILLIC_QUEST = cp(0x0417, 0x0430, 0x0434, 0x0430, 0x043D, 0x0438, 0x0435); + + /** + * A character outside the Basic Multilingual Plane -- U+1F5FF, the moai. One code point, two + * Java chars, four UTF-8 bytes. NBT strings are modified UTF-8, which encodes this as a + * surrogate pair rather than as one four-byte sequence, so it is the case where a reader that + * treats NBT strings as standard UTF-8 diverges from one that does not. + */ + public static final String ASTRAL = cp(0x1F5FF); + + /** A right-to-left string: Arabic for "quest". Exercises no encoding rule, only rendering. */ + public static final String RTL = cp(0x0645, 0x0647, 0x0645, 0x0629); + + private static String cp(int... codePoints) { + StringBuilder sb = new StringBuilder(codePoints.length); + for (int codePoint : codePoints) { + sb.appendCodePoint(codePoint); + } + return sb.toString(); + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/worlds/DefaultsWorld.java b/src/fixtures/java/kamkeel/npcs/fixtures/worlds/DefaultsWorld.java new file mode 100644 index 000000000..a14abf615 --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/worlds/DefaultsWorld.java @@ -0,0 +1,86 @@ +package kamkeel.npcs.fixtures.worlds; + +import kamkeel.npcs.fixtures.FixtureWorld; +import kamkeel.npcs.fixtures.WorldWriter; +import kamkeel.npcs.fixtures.content.FactionFixtures; +import noppes.npcs.constants.EnumOptionType; +import noppes.npcs.controllers.data.Dialog; +import noppes.npcs.controllers.data.DialogOption; +import noppes.npcs.controllers.data.Faction; + +import java.util.List; + +/** + * What CustomNPC+ writes for a world nobody has edited. + * + *

Worth its own world because "the defaults" is a real contract and an easy thing to get subtly + * wrong: a reader that supplies its own idea of a default agrees with this file on every field it + * happens to share and disagrees on the rest, silently. Reproduced from + * FactionController.loadFactions and DialogController.loadDefaultDialogs. + */ +public final class DefaultsWorld implements FixtureWorld { + + public String name() { + return "defaults"; + } + + public String purpose() { + return "exactly what CustomNPC+ creates for a fresh world -- the three default factions and " + + "the three Villager dialogs -- and nothing else."; + } + + public void build(WorldWriter out) { + List factions = FactionFixtures.vanillaDefaults(); + out.dat("faction", "factions.dat", FactionFixtures.document(factions, 0), + "the three factions FactionController creates when factions.dat is missing or empty: " + + "Friendly 2000, Neutral 1000, Aggressive 0"); + + // Copied field for field from DialogController.loadDefaultDialogs. + Dialog start = new Dialog(); + start.id = 1; + start.title = "Start"; + start.text = "Hello {player}, \n\nWelcome to our village. I hope you enjoy your stay"; + + Dialog village = new Dialog(); + village.id = 2; + village.title = "Ask about village"; + village.text = "This village has been around for ages. Enjoy your stay here."; + + Dialog who = new Dialog(); + who.id = 3; + who.title = "Who are you"; + who.text = "I'm a villager here. I have lived in this village my whole life."; + + DialogOption toVillage = new DialogOption(); + toVillage.title = "Tell me something about this village"; + toVillage.dialogId = 2; + toVillage.optionType = EnumOptionType.DialogOption; + + DialogOption toWho = new DialogOption(); + toWho.title = "Who are you?"; + toWho.dialogId = 3; + toWho.optionType = EnumOptionType.DialogOption; + + DialogOption goodbye = new DialogOption(); + goodbye.title = "Goodbye"; + goodbye.optionType = EnumOptionType.QuitOption; + + start.options.put(0, toWho); + start.options.put(1, toVillage); + start.options.put(2, goodbye); + + DialogOption back = new DialogOption(); + back.title = "Back"; + back.dialogId = 1; + + village.options.put(1, back); + who.options.put(1, back); + + out.dialog("Villager", start, + "CustomNPC+'s own default dialog 1, with its three options. Note showWheel is false " + + "here because the object was never read back -- readNBTPartial defaults an " + + "absent DialogShowWheel to true, which the writer does not do"); + out.dialog("Villager", village, "CustomNPC+'s own default dialog 2"); + out.dialog("Villager", who, "CustomNPC+'s own default dialog 3"); + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/worlds/EdgeWorld.java b/src/fixtures/java/kamkeel/npcs/fixtures/worlds/EdgeWorld.java new file mode 100644 index 000000000..017352812 --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/worlds/EdgeWorld.java @@ -0,0 +1,86 @@ +package kamkeel.npcs.fixtures.worlds; + +import kamkeel.npcs.fixtures.FixtureWorld; +import kamkeel.npcs.fixtures.WorldWriter; +import kamkeel.npcs.fixtures.content.FactionFixtures; +import noppes.npcs.controllers.data.Dialog; +import noppes.npcs.controllers.data.Faction; + +import java.util.List; + +/** + * Legal content that readers get wrong. + * + *

Nothing here is corrupt. Every file is something CustomNPC+ will write and load: empty + * strings, integer extremes, ids that resolve nowhere, names outside Latin-1, and the same id + * living in two categories. The last is the one worth having -- it is what makes "a dialog's + * identity is its id" wrong on its own. + */ +public final class EdgeWorld implements FixtureWorld { + + public String name() { + return "edge"; + } + + public String purpose() { + return "legal but awkward content: empty strings, integer extremes, dangling ids, non-Latin " + + "names, and one dialog id occupying two categories at once."; + } + + public void build(WorldWriter out) { + List factions = FactionFixtures.edge(); + out.dat("faction", "factions.dat", FactionFixtures.document(factions, 4096), + "empty and non-Latin names, Integer.MIN_VALUE/MAX_VALUE thresholds, colour -1, " + + "attack lists naming factions that are not in the file, and a sparse id of 4096"); + + // The same id in two categories. DialogController loads categories directory by + // directory, and on the second occurrence renames the file and reassigns the id -- so + // this world does not survive a load unchanged, which is exactly the behaviour worth + // pinning. Whichever category is read second is decided by File.listFiles order. + Dialog first = new Dialog(); + first.id = 1; + first.title = "Start"; + first.text = "I am dialog 1 in category A."; + + Dialog second = new Dialog(); + second.id = 1; + second.title = "Start"; + second.text = "I am dialog 1 in category B."; + + out.dialog("Category A", first, + "dialog id 1 in the first category. See the note on its twin"); + out.dialog("Category B", second, + "dialog id 1 AGAIN, in a second category, with the same title. CustomNPC+ resolves " + + "this on load by renaming the file and reassigning the id, so a converter that " + + "keys on the id alone silently merges two distinct dialogs. Which one is " + + "reassigned depends on File.listFiles order and is not fixed"); + + Dialog emptyEverything = new Dialog(); + emptyEverything.id = 2; + emptyEverything.title = ""; + emptyEverything.text = ""; + emptyEverything.command = ""; + emptyEverything.textSound = ""; + out.dialog("Empty", emptyEverything, + "every string field empty, including TextSound, which has a non-empty default. " + + "DialogSound is absent entirely because the writer omits it when empty"); + + Dialog extremes = new Dialog(); + extremes.id = 3; + extremes.title = "Integer Extremes"; + extremes.text = "Every numeric field at a boundary."; + extremes.quest = Integer.MAX_VALUE; + extremes.color = Integer.MIN_VALUE; + extremes.titleColor = -1; + extremes.textWidth = Integer.MAX_VALUE; + extremes.textHeight = Integer.MIN_VALUE; + extremes.textOffsetX = Integer.MIN_VALUE; + extremes.textOffsetY = Integer.MAX_VALUE; + extremes.npcScale = Float.MAX_VALUE; + extremes.textPitch = Float.MIN_VALUE; + extremes.alignment = Byte.MAX_VALUE; + out.dialog("Empty", extremes, + "integer and float fields at their type boundaries, and DialogAlignment at 127 -- " + + "outside the 0-2 the field documents, because nothing validates it on write"); + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/worlds/LegacyWorld.java b/src/fixtures/java/kamkeel/npcs/fixtures/worlds/LegacyWorld.java new file mode 100644 index 000000000..aa0e9afd8 --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/worlds/LegacyWorld.java @@ -0,0 +1,163 @@ +package kamkeel.npcs.fixtures.worlds; + +import kamkeel.npcs.fixtures.FixtureWorld; +import kamkeel.npcs.fixtures.WorldWriter; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.EnumAvailabilityQuest; +import noppes.npcs.constants.EnumQuestType; +import noppes.npcs.controllers.data.Dialog; +import noppes.npcs.controllers.data.Quest; +import noppes.npcs.quests.QuestKill; + +/** + * Documents as an older CustomNPC+ would have left them. + * + *

Synthesized, and the only world here that is. Every other file in these fixtures is + * whatever CustomNPC+ writes today. These are produced by writing a current document and then + * removing keys and lowering {@code ModRev} -- because producing genuinely old output means + * checking out an old CustomNPC+ and running it, which is worth doing and is not this. + * + *

They are still worth having, because the upgrade path is real code with no other test. When a + * loaded document's {@code ModRev} differs from {@code VersionCompatibility.ModRev}, + * {@code CheckAvailabilityCompatibility} walks a freshly constructed object's NBT and copies in + * every key the file is missing. A reader that skips that step reads zero for absent integers, + * which is a valid-looking value for most of these fields and a wrong one for all of them. + * + *

Each case names exactly what was removed, so the synthesis is auditable rather than implied. + */ +public final class LegacyWorld implements FixtureWorld { + + /** Anything below VersionCompatibility.ModRev, which is 23 at the time of writing. */ + private static final int OLD_REV = 17; + + public String name() { + return "legacy"; + } + + public String purpose() { + return "documents aged by hand -- keys removed and ModRev lowered -- to exercise the " + + "default-filling upgrade path. The only synthesized world here; every case names " + + "which keys it removed."; + } + + public void build(WorldWriter out) { + agedDialog(out); + preUpgradeKillQuest(out); + questWithoutAvailability(out); + } + + private void agedDialog(WorldWriter out) { + Dialog dialog = new Dialog(); + dialog.id = 1; + dialog.title = "Aged Dialog"; + dialog.text = "Written by a version that had fewer fields."; + dialog.color = 0x336699; + + NBTTagCompound compound = dialog.writeToNBTPartial(new NBTTagCompound()); + String[] removed = { + "TextSound", "TextPitch", "TextWidth", "TextHeight", "ShowOptionLine", + "PreviousBlocks", "NPCScale", "Color", "TitleColor", "DialogShowWheel", + "DialogDarkScreen", "Images", "ColorSettings" + }; + for (String key : removed) { + compound.removeTag(key); + } + compound.setInteger("ModRev", OLD_REV); + + out.dialogRaw("Aged", 1, compound, + "ModRev lowered to " + OLD_REV + " and 13 keys removed: " + join(removed) + ". Ten of " + + "them have a non-zero default that readNBTPartial restores explicitly, and the " + + "Color that was set is among the removed ones -- so a reader that does not " + + "default-fill produces a black dialog with no text sound and a zero scale"); + } + + /** + * The trap Scribe's own notes record: before the kill/dialog split, a Kill quest stored its + * targets under {@code QuestDialogs} -- the dialog quest's key. QuestKill.readEntityFromNBT + * still falls back to it when {@code QuestKills} is absent. Miss the fallback and every + * pre-upgrade kill quest converts with no targets, which reads as already complete. + */ + private void preUpgradeKillQuest(WorldWriter out) { + Quest quest = new Quest(); + quest.id = 1; + quest.title = "Old Kill Quest"; + quest.logText = "Cull the pigs."; + quest.setType(EnumQuestType.Kill); + QuestKill kill = (QuestKill) quest.questInterface; + kill.targets.put("Pig", 10); + kill.targets.put("Cow", 4); + kill.targetType = 0; + + NBTTagCompound compound = quest.writeToNBTPartial(new NBTTagCompound()); + NBTBase targets = compound.getTag("QuestKills"); + compound.removeTag("QuestKills"); + compound.setTag("QuestDialogs", targets); + compound.setInteger("ModRev", OLD_REV); + + out.questRaw("Aged", 1, compound, + "a Kill quest whose targets sit under QuestDialogs instead of QuestKills, which is " + + "where a pre-split CustomNPC+ put them. QuestKill.readEntityFromNBT falls back " + + "to that key. A reader without the fallback loads two targets as zero targets, " + + "and a quest with no targets counts as complete"); + } + + private void questWithoutAvailability(WorldWriter out) { + Quest quest = new Quest(); + quest.id = 2; + quest.title = "Aged Item Quest"; + quest.logText = "Bring me three ingots."; + quest.setType(EnumQuestType.Item); + quest.rewardExp = 500; + + NBTTagCompound compound = quest.writeToNBTPartial(new NBTTagCompound()); + String[] removed = { + "PartyOptions", "ProfileOptions", "CustomCooldown", "RandomReward", "QuestCompletion" + }; + for (String key : removed) { + compound.removeTag(key); + } + compound.setInteger("ModRev", OLD_REV); + + out.questRaw("Aged", 2, compound, + "ModRev lowered and the newer sub-objects removed: " + join(removed) + ". Party and " + + "profile options are whole compounds, so this exercises the recursive half of " + + "CompatabilityFix rather than the flat half"); + + // A dialog whose quest availability slots were never written at all, which is what every + // document below the availability rework looks like. + Dialog gated = new Dialog(); + gated.id = 2; + gated.title = "Gated, Then Aged"; + gated.text = "Only for those who finished quest 1."; + gated.availability.questAvailable = EnumAvailabilityQuest.After; + gated.availability.questId = 1; + + NBTTagCompound gatedCompound = gated.writeToNBTPartial(new NBTTagCompound()); + String[] gatedRemoved = { + "AvailabilityQuest2", "AvailabilityQuest3", "AvailabilityQuest4", + "AvailabilityQuest2Id", "AvailabilityQuest3Id", "AvailabilityQuest4Id" + }; + for (String key : gatedRemoved) { + gatedCompound.removeTag(key); + } + gatedCompound.setInteger("ModRev", OLD_REV); + + out.dialogRaw("Aged", 2, gatedCompound, + "the first AvailabilityQuest slot set and the other three absent entirely. Their " + + "defaults are Always/-1, so default-filling and reading-zero happen to agree " + + "here -- which is why this file is a weak test on its own and a useful one " + + "beside the aged dialog above, where they disagree"); + } + + private static String join(String[] keys) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < keys.length; i++) { + sb.append(keys[i]); + if (i + 1 < keys.length) { + sb.append(", "); + } + } + return sb.toString(); + } +} diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/worlds/MaximalWorld.java b/src/fixtures/java/kamkeel/npcs/fixtures/worlds/MaximalWorld.java new file mode 100644 index 000000000..ab9abb551 --- /dev/null +++ b/src/fixtures/java/kamkeel/npcs/fixtures/worlds/MaximalWorld.java @@ -0,0 +1,40 @@ +package kamkeel.npcs.fixtures.worlds; + +import kamkeel.npcs.fixtures.Case; +import kamkeel.npcs.fixtures.FixtureWorld; +import kamkeel.npcs.fixtures.WorldWriter; +import kamkeel.npcs.fixtures.content.DialogFixtures; +import kamkeel.npcs.fixtures.content.FactionFixtures; +import noppes.npcs.controllers.data.Dialog; +import noppes.npcs.controllers.data.Faction; + +import java.util.List; + +/** + * Every field CustomNPC+ can store, moved off its default at least once. + * + *

The world a reader is measured against. If a field is written by CustomNPC+ and absent from + * here, that is a gap in the fixtures rather than a decision. + */ +public final class MaximalWorld implements FixtureWorld { + + public String name() { + return "maximal"; + } + + public String purpose() { + return "every storable field moved off its default at least once, with each enum walked to " + + "all of its constants. The world a reader is measured against."; + } + + public void build(WorldWriter out) { + List factions = FactionFixtures.maximal(); + out.dat("faction", "factions.dat", FactionFixtures.document(factions, 17), + factions.size() + " factions: the three CustomNPC+ defaults, each boolean flag alone " + + "and all together, a hostility graph, inverted thresholds and negative points"); + + for (Case

c : DialogFixtures.maximal()) { + out.dialog(c.category, c.value, c.note); + } + } +}