mirror of
https://github.com/KAMKEEL/CustomNPC-Plus.git
synced 2026-11-24 12:54:25 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0a7a2e698 | ||
|
|
30f65ca6e0 | ||
|
|
d6d6111803 | ||
|
|
517ccb09c3 | ||
|
|
b37f57966d | ||
|
|
3fc15091fa | ||
|
|
5f49d28f7c | ||
|
|
5403060ee5 | ||
|
|
8612d4442a | ||
|
|
b6f2bae770 | ||
|
|
e3a1017770 | ||
|
|
7f606fbec2 | ||
|
|
3dfcf7764a | ||
|
|
1a1871f803 | ||
|
|
277c056417 | ||
|
|
c634c4bd35 | ||
|
|
715b38e694 | ||
|
|
9ff4b8ae16 | ||
|
|
e3d1c9b1a7 | ||
|
|
605907681c | ||
|
|
32c5cc78c7 | ||
|
|
795464fb81 | ||
|
|
4a52690d99 | ||
|
|
fae2c21893 | ||
|
|
c2ad3ef015 | ||
|
|
98c94bd406 | ||
|
|
f175e3fb82 | ||
|
|
67ddaaab6f | ||
|
|
22a8ef5036 | ||
|
|
2de0795a8e | ||
|
|
3193a2bfc3 | ||
|
|
c6e361f8e6 | ||
|
|
74511b7449 | ||
|
|
3535e7b819 | ||
|
|
179fd4f834 | ||
|
|
1d0b640c61 | ||
|
|
d4b9a18a1a | ||
|
|
fab1062ce8 | ||
|
|
1532ef722c | ||
|
|
caa39d6d5d | ||
|
|
a71532f49a | ||
|
|
a028142dda | ||
|
|
71bb4b451e | ||
|
|
677d50fa03 | ||
|
|
466b49db5e | ||
|
|
dedbe94cd8 | ||
|
|
c79f5998d6 | ||
|
|
1acda0e6b0 | ||
|
|
4341c15cf4 | ||
|
|
6477ede022 | ||
|
|
7cafa4f677 | ||
|
|
9f4334a803 | ||
|
|
6af66b8883 | ||
|
|
abd1c7cbeb | ||
|
|
3565c66cf8 | ||
|
|
aaf6734bd9 | ||
|
|
68b5191db6 | ||
|
|
17f61de57a | ||
|
|
5aa843966a | ||
|
|
0829b6285f | ||
|
|
2c134fe627 | ||
|
|
322626015d | ||
|
|
50e16dc538 | ||
|
|
4a7c7b09c7 | ||
|
|
1a77728bcd | ||
|
|
7f63b64a66 | ||
|
|
8e8ab06507 | ||
|
|
4c301b3c1c | ||
|
|
67c6cf14d3 | ||
|
|
0a4bc4126f | ||
|
|
b8d68f771f | ||
|
|
332f1bfd57 | ||
|
|
facee7c388 | ||
|
|
22de352dd9 | ||
|
|
b28ea7226f | ||
|
|
6d0655ad7d | ||
|
|
48281c8d34 | ||
|
|
948eb91b42 | ||
|
|
07a914272a | ||
|
|
b2c279feeb | ||
|
|
b8cac96c46 | ||
|
|
554fbeb1a8 | ||
|
|
e0a6bac642 | ||
|
|
f6e7809a29 | ||
|
|
85ef28ca76 | ||
|
|
f4062f3edd | ||
|
|
92133afe75 | ||
|
|
b989a89889 | ||
|
|
edf5ff7c73 | ||
|
|
ab60fdbd12 | ||
|
|
ac953685c8 | ||
|
|
9b52c8088e | ||
|
|
524c014fc2 | ||
|
|
a31638f05f | ||
|
|
415de16917 | ||
|
|
613bb7a2b5 | ||
|
|
3d789cdf3a | ||
|
|
17d8c99e8b | ||
|
|
605466e011 | ||
|
|
4535d2ba7f | ||
|
|
f96b6ad020 | ||
|
|
698fcf20ab | ||
|
|
66afe80c3c | ||
|
|
529ee63866 | ||
|
|
d20c701635 | ||
|
|
3be5e2ebb5 |
No files matched your search
+38
-1
@@ -6,7 +6,7 @@ plugins {
|
||||
id "dts.typescript-generator"
|
||||
}
|
||||
|
||||
version = "1.11.1"
|
||||
version = "1.11.2"
|
||||
group= "kamkeel.customnpc-plus"
|
||||
archivesBaseName = "CustomNPC-Plus"
|
||||
|
||||
@@ -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=<dir>, -Pworlds=<a,b>'
|
||||
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
|
||||
|
||||
+1
-1
@@ -199,7 +199,7 @@ disableCheckstyle = true
|
||||
# ideaCheckSpotlessOnBuild = true
|
||||
|
||||
# Non-GTNH properties
|
||||
modVersion = 1.11.0
|
||||
modVersion = 1.11.2
|
||||
|
||||
# Increase Gradle's JVM memory usage to avoid daemon expiration due to
|
||||
# insufficient heap space on CI builds.
|
||||
|
||||
+1
-1
Submodule src/api updated: 04fd348d13...e7f363727e.
@@ -0,0 +1,21 @@
|
||||
package kamkeel.npcs.fixtures;
|
||||
|
||||
/**
|
||||
* One piece of content, the category it belongs in, and why it exists.
|
||||
*
|
||||
* <p>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<T> {
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>Usage: {@code gradlew scribeFixtures -Pout=<dir> [-Pworlds=maximal,edge]}
|
||||
*/
|
||||
public final class FixtureGenerator {
|
||||
|
||||
private static final List<FixtureWorld> ALL = Arrays.<FixtureWorld>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 <output-dir> [--worlds a,b,c]");
|
||||
System.exit(2);
|
||||
}
|
||||
File out = new File(args[0]).getAbsoluteFile();
|
||||
|
||||
List<FixtureWorld> selected = new ArrayList<FixtureWorld>(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.
|
||||
*
|
||||
* <p>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<FixtureWorld> select(String csv) {
|
||||
Map<String, FixtureWorld> byName = new LinkedHashMap<String, FixtureWorld>();
|
||||
for (FixtureWorld w : ALL) {
|
||||
byName.put(w.name(), w);
|
||||
}
|
||||
List<FixtureWorld> selected = new ArrayList<FixtureWorld>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package kamkeel.npcs.fixtures;
|
||||
|
||||
import cpw.mods.fml.common.Loader;
|
||||
import kamkeel.npcs.addon.DBCAddon;
|
||||
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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>{@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();
|
||||
// PlayerData.getNBT ends with DBCAddon.instance.writeToNBT(...), and the field is only set
|
||||
// by the constructor. DBCAddon is a shell whose methods a companion mod replaces by mixin,
|
||||
// so every method here is a no-op -- constructing one costs nothing and is what stops a
|
||||
// player record from throwing on its last line. Without the addon installed this is
|
||||
// exactly the state a real server is in.
|
||||
new DBCAddon();
|
||||
booted = true;
|
||||
verifyRegistry();
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes {@code Loader.instance()} answerable without launching FML.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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: <i>"no mod container, assume minecraft"</i>. That is
|
||||
* exactly the branch real vanilla registration takes, because no mod is active while
|
||||
* {@code Item.registerItems()} runs.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>{@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);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<Entry> entries = new ArrayList<Entry>();
|
||||
private final Set<String> warnings = new LinkedHashSet<String>();
|
||||
private final List<String[]> worlds = new ArrayList<String[]>();
|
||||
|
||||
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<String> 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("<world>/_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();
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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:
|
||||
*
|
||||
* <pre>compound.setLong("TimePast", System.currentTimeMillis() - time);</pre>
|
||||
*
|
||||
* <p>and a {@code PlayerMail} hangs off every dialog and every quest whether or not any mail was
|
||||
* configured -- so <i>every</i> dialog and quest file differs between two runs, on that one key.
|
||||
*
|
||||
* <p><b>Why normalize rather than document and accept.</b> 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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<String> 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<String> keysOf(NBTTagCompound compound) {
|
||||
return new ArrayList<String>(compound.func_150296_c());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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<FixtureWorld> 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("/customnpcs/ <- a CustomNPC+ world directory, and nothing else\n");
|
||||
}
|
||||
sb.append("_readable/<world>/ <- 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("Each `<world>/` holds `customnpcs/` and nothing else, so it drops straight into\n");
|
||||
sb.append("a save directory -- or, in Scribe, works as-is as a `cnpc_data_sets` overlay.\n");
|
||||
sb.append("The readable renderings sit outside the world directories for that reason.\n\n");
|
||||
sb.append("`_readable/` is a debugging aid, not a fixture: it is CustomNPC+'s own JSON\n");
|
||||
sb.append("rendering, which suffixes scalars with their type (`5b`, `5L`, `1.0f`) and is\n");
|
||||
sb.append("therefore deliberately not strict JSON. The widths being visible is the point.\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/<category>/<id>.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package kamkeel.npcs.fixtures;
|
||||
|
||||
import net.minecraft.nbt.CompressedStreamTools;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.NoppesStringUtils;
|
||||
import noppes.npcs.controllers.data.CustomEffect;
|
||||
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.
|
||||
*
|
||||
* <p><b>What is authoritative and what is copied.</b> 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 <i>where the file goes and what
|
||||
* it is called</i>, 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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>The generated {@code <world>/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");
|
||||
// Outside the world directory, not inside it. A generated <world>/ is meant to be usable
|
||||
// as a drop-in overlay -- Scribe's smoke harness copies a set's contents straight into a
|
||||
// server's world -- so it must contain customnpcs/ and nothing else.
|
||||
this.readable = new File(new File(outputRoot, "_readable"), world);
|
||||
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);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Custom effects -- CustomEffectController.saveCustomEffect / loadEffectsFromDir
|
||||
//
|
||||
// The filename is the name: loadEffectsFromDir overwrites whatever `name` the file contained
|
||||
// with the filename minus .json. An empty category means the effect sits at the root of
|
||||
// customeffects/, which is what CategoryManager calls Uncategorized -- there is no category
|
||||
// file anywhere, only the directory.
|
||||
// ------------------------------------------------------------------
|
||||
public void effect(String category, CustomEffect effect, String note) {
|
||||
effect(category, effect.getName(), effect, note);
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #effect}, with the filename stated separately.
|
||||
*
|
||||
* <p>Needed because the filename and the {@code name} key are genuinely independent on disk,
|
||||
* and a fixture proving the loader prefers the filename has to be able to disagree with it.
|
||||
*/
|
||||
public void effect(String category, String fileName, CustomEffect effect, String note) {
|
||||
File dir = new File(customnpcs, "customeffects");
|
||||
if (category != null && !category.isEmpty()) {
|
||||
dir = new File(dir, NoppesStringUtils.cleanFileName(category));
|
||||
}
|
||||
File file = new File(dir, NoppesStringUtils.cleanFileName(fileName) + ".json");
|
||||
writeJson(file, effect.writeToNBT(true));
|
||||
manifest.record(world, "effect", String.valueOf(effect.id), rel(file), note);
|
||||
}
|
||||
|
||||
/**
|
||||
* A dialog written from a compound rather than from a {@link Dialog}.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<Case<Dialog>> maximal() {
|
||||
List<Case<Dialog>> out = new ArrayList<Case<Dialog>>();
|
||||
basics(out);
|
||||
options(out);
|
||||
availability(out);
|
||||
appearance(out);
|
||||
images(out);
|
||||
attachments(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ basics
|
||||
|
||||
private static void basics(List<Case<Dialog>> out) {
|
||||
Dialog bare = dialog(1, "Bare", "");
|
||||
out.add(new Case<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Case<Dialog>> 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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Case<Dialog>> 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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Case<Dialog>> 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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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<Case<Dialog>> out) {
|
||||
Dialog one = dialog(80, "One Image", "Look.");
|
||||
one.dialogImages.put(0, image(0, "customnpcs:textures/gui/dialog.png", 1));
|
||||
out.add(new Case<Dialog>("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<Dialog>("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<Dialog>("Images", defaults,
|
||||
"a DialogImage left entirely at its constructor defaults, including an empty texture"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ attachments
|
||||
|
||||
private static void attachments(List<Case<Dialog>> out) {
|
||||
Dialog quest = dialog(90, "Starts A Quest", "Take this.");
|
||||
quest.quest = 1;
|
||||
out.add(new Case<Dialog>("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<Dialog>("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<Dialog>("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<Dialog>("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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package kamkeel.npcs.fixtures.content;
|
||||
|
||||
import kamkeel.npcs.fixtures.Case;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.controllers.ScriptContainer;
|
||||
import noppes.npcs.controllers.data.CustomEffect;
|
||||
import noppes.npcs.controllers.data.EffectScript;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Custom effects, which persist in two places at once.
|
||||
*
|
||||
* <p>Each effect is a file at {@code customeffects/<Name>.json} -- or
|
||||
* {@code customeffects/<Category>/<Name>.json}, where the subdirectory is the category -- written
|
||||
* with {@code writeToNBT(true)}. <b>The filename is the name</b>: {@code loadEffectsFromDir}
|
||||
* overwrites whatever {@code name} the file contained with the filename minus {@code .json}, so
|
||||
* the {@code name} key inside is dead weight and the two can legitimately disagree. There is a
|
||||
* fixture for that below.
|
||||
*
|
||||
* <p>Alongside them, {@code customeffects.dat} is an index of {@code {Name, ID}} pairs plus
|
||||
* {@code lastID} -- not the effects themselves. An effect whose name is empty is left out of the
|
||||
* index entirely, which is its own case.
|
||||
*/
|
||||
public final class EffectFixtures {
|
||||
|
||||
private EffectFixtures() {
|
||||
}
|
||||
|
||||
public static List<Case<CustomEffect>> maximal() {
|
||||
List<Case<CustomEffect>> out = new ArrayList<Case<CustomEffect>>();
|
||||
|
||||
CustomEffect bare = effect(1, "Bare");
|
||||
out.add(new Case<CustomEffect>("", bare,
|
||||
"every field at its constructor default. Note menuName defaults to a coloured "
|
||||
+ "'NEW EFFECT' containing a section sign, so even the bare case is not ASCII"));
|
||||
|
||||
CustomEffect full = effect(2, "Fully Configured");
|
||||
full.menuName = Text.SECTION + "bFully " + Text.SECTION + "6Configured";
|
||||
full.length = 1200;
|
||||
full.everyXTick = 10;
|
||||
full.lossOnDeath = false;
|
||||
full.icon = "customnpcs:textures/gui/effects.png";
|
||||
full.iconX = 32;
|
||||
full.iconY = 48;
|
||||
full.width = 24;
|
||||
full.height = 24;
|
||||
out.add(new Case<CustomEffect>("", full,
|
||||
"every scalar off its default: a 60-second duration, a 10-tick period, an icon with "
|
||||
+ "its atlas offsets and size, and lossOnDeath cleared"));
|
||||
|
||||
CustomEffect animated = effect(3, "Animated Icon");
|
||||
animated.animated = true;
|
||||
animated.frameCount = 8;
|
||||
animated.frametime = 3;
|
||||
animated.icon = "customnpcs:textures/gui/anim.png";
|
||||
out.add(new Case<CustomEffect>("", animated,
|
||||
"an animated icon -- iconAnimated, iconFrameCount and iconFrameTime. Both counts are "
|
||||
+ "clamped to a minimum of 1 on read, so zero cannot round-trip"));
|
||||
|
||||
CustomEffect tagged = effect(4, "Tagged");
|
||||
tagged.tagUUIDs.addAll(Arrays.asList(
|
||||
UUID.fromString("0e5f2b6a-1c3d-4e5f-8a9b-0c1d2e3f4a5b"),
|
||||
UUID.fromString("1a2b3c4d-5e6f-4071-8293-a4b5c6d7e8f9"),
|
||||
UUID.fromString("ffffffff-ffff-4fff-bfff-ffffffffffff")));
|
||||
out.add(new Case<CustomEffect>("", tagged,
|
||||
"three tag UUIDs. TagController.writeTagUUIDs omits the key entirely when the set is "
|
||||
+ "empty, so every other effect here has no TagUUIDs key at all"));
|
||||
|
||||
CustomEffect scripted = effect(5, "Scripted");
|
||||
scripted.setScriptHandler(script(
|
||||
"function onEffectAdd(event) { event.player.message('effect added'); }\n"
|
||||
+ "function onEffectTick(event) {}\n"
|
||||
+ "function onEffectRemove(event) {}\n", true, "ECMAScript"));
|
||||
out.add(new Case<CustomEffect>("", scripted,
|
||||
"a ScriptData compound carrying ScriptLanguage, ScriptEnabled and a ScriptContent "
|
||||
+ "unit with three hook functions"));
|
||||
|
||||
CustomEffect scriptDisabled = effect(6, "Script Disabled");
|
||||
scriptDisabled.setScriptHandler(script("function onEffectTick(event) {}", false, "javascript"));
|
||||
out.add(new Case<CustomEffect>("", scriptDisabled,
|
||||
"ScriptEnabled false, and a language string that is not the canonical 'ECMAScript' -- "
|
||||
+ "normalizeLanguage runs on read, not on write"));
|
||||
|
||||
CustomEffect hugeScript = effect(7, "Huge Script");
|
||||
StringBuilder sb = new StringBuilder();
|
||||
while (sb.length() < 70000) {
|
||||
sb.append("// a line of script that exists only to push past the 65535 char limit\n");
|
||||
}
|
||||
hugeScript.setScriptHandler(script(sb.toString(), true, "ECMAScript"));
|
||||
out.add(new Case<CustomEffect>("", hugeScript,
|
||||
"a script over 65535 characters. NBT strings cannot hold that, so ScriptContainer "
|
||||
+ "splits it across Script plus ExpandedScript0..N, bounded by "
|
||||
+ "ConfigScript.ExpandedScriptLimit which defaults to 2. Check the written file "
|
||||
+ "to see how many parts survived -- this fixture exists to record that"));
|
||||
|
||||
CustomEffect noName = effect(8, "");
|
||||
out.add(new Case<CustomEffect>("", noName,
|
||||
"an EMPTY name. writeMapNBT skips these, so this effect is absent from "
|
||||
+ "customeffects.dat while its file exists on disk -- and since the filename is "
|
||||
+ "the name, its file is '.json'. Recorded rather than avoided"));
|
||||
|
||||
CustomEffect categorised = effect(10, "In A Category");
|
||||
out.add(new Case<CustomEffect>("Buffs", categorised,
|
||||
"an effect inside a category subdirectory. Categories are directories and nothing "
|
||||
+ "else -- there is no category file and no id stored anywhere"));
|
||||
|
||||
CustomEffect unicode = effect(11, "Unicode");
|
||||
unicode.menuName = Text.KATAKANA_FACTION + " " + Text.EM_DASH + " " + Text.ELEVES;
|
||||
out.add(new Case<CustomEffect>("Buffs", unicode,
|
||||
"a non-Latin menu name inside a category"));
|
||||
|
||||
CustomEffect extremes = effect(12, "Extremes");
|
||||
extremes.length = Integer.MAX_VALUE;
|
||||
extremes.everyXTick = Integer.MAX_VALUE;
|
||||
extremes.iconX = Integer.MIN_VALUE;
|
||||
extremes.iconY = Integer.MIN_VALUE;
|
||||
extremes.width = 0;
|
||||
extremes.height = 0;
|
||||
extremes.frameCount = 0;
|
||||
extremes.frametime = 0;
|
||||
out.add(new Case<CustomEffect>("", extremes,
|
||||
"integer boundaries, plus zero width, height, frame count and frame time. Width and "
|
||||
+ "height fall back to 16 on read only when their key is ABSENT, so an explicit "
|
||||
+ "zero survives where a missing key does not"));
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The filename for {@link #nameMismatch()}, deliberately unequal to the effect's name field.
|
||||
*/
|
||||
public static final String MISMATCH_FILENAME = "Name On Disk";
|
||||
|
||||
/**
|
||||
* An effect whose {@code name} key disagrees with its filename.
|
||||
*
|
||||
* <p>Kept out of {@link #maximal()} because it cannot be expressed there: everything in that
|
||||
* list is written to a file named after the effect, which is what makes a mismatch impossible
|
||||
* to state. loadEffectsFromDir assigns {@code effect.name} from the filename after reading, so
|
||||
* the key inside is discarded and a reader that trusts it gets a different answer.
|
||||
*/
|
||||
public static CustomEffect nameMismatch() {
|
||||
CustomEffect mismatched = effect(9, "Name Inside The File");
|
||||
return mismatched;
|
||||
}
|
||||
|
||||
/** The index document. Copied from CustomEffectController.writeMapNBT. */
|
||||
public static NBTTagCompound index(List<Case<CustomEffect>> effects, int lastUsedId) {
|
||||
NBTTagList list = new NBTTagList();
|
||||
for (Case<CustomEffect> c : effects) {
|
||||
CustomEffect effect = c.value;
|
||||
// writeMapNBT skips unnamed effects. Reproduced, because the omission is the contract.
|
||||
if (!effect.getName().isEmpty()) {
|
||||
NBTTagCompound entry = new NBTTagCompound();
|
||||
entry.setString("Name", effect.getName());
|
||||
entry.setInteger("ID", effect.id);
|
||||
list.appendTag(entry);
|
||||
}
|
||||
}
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
compound.setTag("CustomEffects", list);
|
||||
compound.setInteger("lastID", lastUsedId);
|
||||
return compound;
|
||||
}
|
||||
|
||||
private static CustomEffect effect(int id, String name) {
|
||||
CustomEffect effect = new CustomEffect();
|
||||
effect.id = id;
|
||||
effect.name = name;
|
||||
return effect;
|
||||
}
|
||||
|
||||
private static EffectScript script(String source, boolean enabled, String language) {
|
||||
EffectScript handler = new EffectScript();
|
||||
handler.setLanguage(language);
|
||||
handler.setEnabled(enabled);
|
||||
ScriptContainer container = new ScriptContainer(handler);
|
||||
container.script = source;
|
||||
handler.addScriptUnit(container);
|
||||
return handler;
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<Faction> vanillaDefaults() {
|
||||
return new ArrayList<Faction>(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.
|
||||
*
|
||||
* <p>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<Faction> maximal() {
|
||||
List<Faction> 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<Faction> edge() {
|
||||
List<Faction> factions = new ArrayList<Faction>();
|
||||
|
||||
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<Faction> 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package kamkeel.npcs.fixtures.content;
|
||||
|
||||
import kamkeel.npcs.fixtures.Case;
|
||||
import kamkeel.npcs.fixtures.Fixtures;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.controllers.data.PlayerData;
|
||||
import noppes.npcs.controllers.data.Quest;
|
||||
import noppes.npcs.controllers.data.QuestData;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Per-player records, and the name/uuid index beside them.
|
||||
*
|
||||
* <p>A record is {@code playerdata/<uuid>.json}, written by {@code PlayerData.getNBT}, which
|
||||
* composes fifteen sub-writers -- dialog, bank, quest, transport, faction, item giver, mail,
|
||||
* timers, skin overlays, animation, effect, magic, trade, ability and hotbar. Only some are
|
||||
* populated here; the rest write their empty form, which is itself worth having, since "what an
|
||||
* untouched sub-record looks like" is a contract too.
|
||||
*
|
||||
* <p>{@code playerdatamap.dat} is a flat {@code {Name, UUID}} list. It is a lookup index rebuilt
|
||||
* by scanning the directory when absent, so it is derived rather than authoritative -- but it is
|
||||
* what CustomNPC+ reads first.
|
||||
*
|
||||
* <p>The record can also be gzipped NBT rather than JSON, chosen by {@code ConfigMain.DatFormat}.
|
||||
* Both forms are generated, because a reader that only handles the default will meet the other on
|
||||
* somebody's server.
|
||||
*/
|
||||
public final class PlayerFixtures {
|
||||
|
||||
private PlayerFixtures() {
|
||||
}
|
||||
|
||||
/** uuid -> display name, in a fixed order so the index document is reproducible. */
|
||||
public static Map<String, String> roster() {
|
||||
Map<String, String> roster = new LinkedHashMap<String, String>();
|
||||
roster.put("29cc52dd-2c50-4e8f-a388-be6c497cf0b4", "Fresh");
|
||||
roster.put("8667ba71-b85a-4004-af54-457a9734eed7", "Progressed");
|
||||
roster.put("069a79f4-44e9-4726-a5be-fca90e38aaf5", "Notch");
|
||||
roster.put("00000000-0000-0000-0000-000000000000", "NilUuid");
|
||||
return roster;
|
||||
}
|
||||
|
||||
public static List<Case<PlayerData>> records() {
|
||||
List<Case<PlayerData>> out = new ArrayList<Case<PlayerData>>();
|
||||
|
||||
PlayerData fresh = player("29cc52dd-2c50-4e8f-a388-be6c497cf0b4", "Fresh");
|
||||
out.add(new Case<PlayerData>("", fresh,
|
||||
"a player who has done nothing. Every one of the fifteen sub-records writes its empty "
|
||||
+ "form -- the baseline for what an untouched record contains"));
|
||||
|
||||
PlayerData progressed = player("8667ba71-b85a-4004-af54-457a9734eed7", "Progressed");
|
||||
progressed.dialogData.dialogsRead.addAll(Arrays.asList(1, 2, 3, 41, 90));
|
||||
progressed.factionData.factionData.put(0, 1800);
|
||||
progressed.factionData.factionData.put(1, 1000);
|
||||
progressed.factionData.factionData.put(2, 0);
|
||||
progressed.factionData.factionData.put(14, -250);
|
||||
progressed.questData.finishedQuests.put(1, Fixtures.EPOCH);
|
||||
progressed.questData.finishedQuests.put(30, Fixtures.EPOCH + 86400000L);
|
||||
progressed.questData.activeQuests.put(2, questData(2, false));
|
||||
progressed.questData.activeQuests.put(71, questData(71, true));
|
||||
progressed.companionID = 4;
|
||||
progressed.profileSlot = 2;
|
||||
out.add(new Case<PlayerData>("", progressed,
|
||||
"read dialogs, standing in four factions including a negative one, two finished "
|
||||
+ "quests with completion timestamps, and two active quests -- one of them marked "
|
||||
+ "complete but not turned in. Also a companion id and a non-zero profile slot"));
|
||||
|
||||
PlayerData extras = player("069a79f4-44e9-4726-a5be-fca90e38aaf5", "Notch");
|
||||
QuestData withExtras = questData(75, false);
|
||||
withExtras.extraData.setTag("Killed", killed("Zombie", 14, "Skeleton", 3));
|
||||
withExtras.extraData.setBoolean("LocationFound", true);
|
||||
withExtras.extraData.setBoolean("Location2Found", true);
|
||||
extras.questData.activeQuests.put(75, withExtras);
|
||||
extras.dialogData.dialogsRead.add(58);
|
||||
out.add(new Case<PlayerData>("", extras,
|
||||
"an active quest whose ExtraData holds per-objective progress, in the shapes the "
|
||||
+ "quest classes actually read. Kill counts are a Killed tag list of Slot/Value "
|
||||
+ "compounds -- NBTTags.getStringIntegerMap -- not loose integers keyed by mob "
|
||||
+ "name, and a reached location is a boolean under its own key. The quest stores "
|
||||
+ "only the targets, so a reader that ignores ExtraData can never show progress"));
|
||||
|
||||
PlayerData party = player("11111111-2222-3333-4444-555555555555", "PartyMember");
|
||||
QuestData shared = questData(76, false);
|
||||
// The per-player half of a party kill quest: QuestKill keys it by the player's own name
|
||||
// rather than by slot, so two members of one party each carry their own tally.
|
||||
shared.extraData.setTag("PartyMemberKilled", killed("Creeper", 2));
|
||||
shared.extraData.setTag("Killed", killed("Creeper", 5));
|
||||
party.questData.activeQuests.put(76, shared);
|
||||
out.add(new Case<PlayerData>("", party,
|
||||
"a party kill quest, which stores the group total under Killed and each member's own "
|
||||
+ "share under <playerName>Killed. The second key is composed from a name, so it "
|
||||
+ "cannot be enumerated from the quest -- only from the party that took it"));
|
||||
|
||||
PlayerData foreign = player("22222222-3333-4444-5555-666666666666", "AddonUser");
|
||||
QuestData unclaimed = questData(77, false);
|
||||
// ExtraData is an opaque compound: nothing validates its keys, so an addon that stores
|
||||
// its own progress there produces a file no objective kind here can read. Deliberate,
|
||||
// and the case a reader has to report rather than silently drop.
|
||||
unclaimed.extraData.setInteger("dbcaddon:KiCharged", 900);
|
||||
unclaimed.extraData.setString("dbcaddon:Form", "SuperSaiyan");
|
||||
foreign.questData.activeQuests.put(77, unclaimed);
|
||||
out.add(new Case<PlayerData>("", foreign,
|
||||
"an active quest whose ExtraData holds only keys no objective kind claims, which is "
|
||||
+ "what an addon writing its own progress leaves behind. Nothing validates this "
|
||||
+ "compound, so a reader meets it on a real server and has to say so rather than "
|
||||
+ "drop it"));
|
||||
|
||||
PlayerData nil = player("00000000-0000-0000-0000-000000000000", "NilUuid");
|
||||
nil.dialogData.dialogsRead.add(1);
|
||||
out.add(new Case<PlayerData>("", nil,
|
||||
"the nil UUID, which is legal in the file and names no player. A reader that treats "
|
||||
+ "it as absent rather than as a value diverges here"));
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/** PlayerDataController.writeNBT -- a flat Name/UUID list, with no lastID. */
|
||||
public static NBTTagCompound index(Map<String, String> roster) {
|
||||
NBTTagList list = new NBTTagList();
|
||||
for (Map.Entry<String, String> entry : roster.entrySet()) {
|
||||
NBTTagCompound player = new NBTTagCompound();
|
||||
// The controller keys the map by NAME and stores the uuid as the value, which is the
|
||||
// opposite of what the file's key order suggests at a glance.
|
||||
player.setString("Name", entry.getValue());
|
||||
player.setString("UUID", entry.getKey());
|
||||
list.appendTag(player);
|
||||
}
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
compound.setTag("PlayerDataMap", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
private static PlayerData player(String uuid, String name) {
|
||||
PlayerData data = new PlayerData();
|
||||
data.uuid = uuid;
|
||||
data.playername = name;
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* An entry in a player's active quest list.
|
||||
*
|
||||
* <p>{@code QuestData} needs a {@link Quest} to construct, but only writes three keys and
|
||||
* never touches it -- the quest id is the map key in the enclosing list, not part of the
|
||||
* entry. So a bare Quest carrying the right id is enough and nothing is invented.
|
||||
*/
|
||||
/**
|
||||
* A counter map in the shape {@code NBTTags.nbtStringIntegerMap} writes and
|
||||
* {@code getStringIntegerMap} reads: a list of {@code {Slot, Value}} compounds.
|
||||
*
|
||||
* <p>Written out by hand rather than through {@code NBTTags} so the fixture states the shape
|
||||
* it is asserting. A generator that borrows the reader's own helper agrees with it by
|
||||
* construction and proves nothing about it.
|
||||
*/
|
||||
private static NBTTagList killed(Object... slotsAndCounts) {
|
||||
NBTTagList list = new NBTTagList();
|
||||
for (int at = 0; at < slotsAndCounts.length; at += 2) {
|
||||
NBTTagCompound entry = new NBTTagCompound();
|
||||
entry.setString("Slot", (String) slotsAndCounts[at]);
|
||||
entry.setInteger("Value", ((Integer) slotsAndCounts[at + 1]).intValue());
|
||||
list.appendTag(entry);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static QuestData questData(int questId, boolean completed) {
|
||||
Quest quest = new Quest();
|
||||
quest.id = questId;
|
||||
QuestData data = new QuestData(quest);
|
||||
data.isCompleted = completed;
|
||||
data.sendAlerts = true;
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
package kamkeel.npcs.fixtures.content;
|
||||
|
||||
import kamkeel.npcs.fixtures.Case;
|
||||
import kamkeel.npcs.fixtures.Fixtures;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.constants.EnumPartyExchange;
|
||||
import noppes.npcs.constants.EnumPartyObjectives;
|
||||
import noppes.npcs.constants.EnumPartyRequirements;
|
||||
import noppes.npcs.constants.EnumProfileSync;
|
||||
import noppes.npcs.constants.EnumQuestCompletion;
|
||||
import noppes.npcs.constants.EnumQuestRepeat;
|
||||
import noppes.npcs.constants.EnumQuestType;
|
||||
import noppes.npcs.controllers.data.Quest;
|
||||
import noppes.npcs.quests.QuestDialog;
|
||||
import noppes.npcs.quests.QuestItem;
|
||||
import noppes.npcs.quests.QuestKill;
|
||||
import noppes.npcs.quests.QuestLocation;
|
||||
import noppes.npcs.quests.QuestManual;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Quests, one axis at a time.
|
||||
*
|
||||
* <p><b>A quest has no availability.</b> Worth stating because it is easy to conclude otherwise:
|
||||
* {@code Quest.readNBTPartial} calls {@code VersionCompatibility.CheckAvailabilityCompatibility},
|
||||
* whose name says availability, and which is in fact a generic "fill in keys this file predates"
|
||||
* pass applied to every {@code ICompatibilty}. {@code Quest} declares no {@code Availability}
|
||||
* field, {@code writeToNBTPartial} writes no {@code Availability*} key, and neither does the 1.20
|
||||
* line. Gating is a property of the dialog that offers the quest.
|
||||
*
|
||||
* <p>Ranges: 1-9 the six types, 10-29 repeat and completion, 30-49 rewards, 50-69 party and
|
||||
* profile, 70-89 objectives in depth, 90-99 combinations.
|
||||
*/
|
||||
public final class QuestFixtures {
|
||||
|
||||
private QuestFixtures() {
|
||||
}
|
||||
|
||||
public static List<Case<Quest>> maximal() {
|
||||
List<Case<Quest>> out = new ArrayList<Case<Quest>>();
|
||||
types(out);
|
||||
repeatAndCompletion(out);
|
||||
rewards(out);
|
||||
partyAndProfile(out);
|
||||
objectives(out);
|
||||
combinations(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ types
|
||||
|
||||
private static void types(List<Case<Quest>> out) {
|
||||
int id = 1;
|
||||
for (EnumQuestType type : EnumQuestType.values()) {
|
||||
Quest quest = quest(id, "Type " + type.name(), type);
|
||||
populateObjective(quest, type);
|
||||
out.add(new Case<Quest>("Types", quest,
|
||||
"quest type " + type.name() + " (ordinal " + type.ordinal() + ") with its "
|
||||
+ "objective populated. NOTE: Kill and AreaKill both build a QuestKill and "
|
||||
+ "write the same keys -- the only thing separating them on disk is Type"));
|
||||
id++;
|
||||
}
|
||||
}
|
||||
|
||||
/** Kill and AreaKill differ by Type alone, so they get compared directly. */
|
||||
private static void populateObjective(Quest quest, EnumQuestType type) {
|
||||
if (type == EnumQuestType.Item) {
|
||||
QuestItem items = (QuestItem) quest.questInterface;
|
||||
items.items.items.put(0, Fixtures.item("minecraft:iron_ingot", 12));
|
||||
items.items.items.put(1, Fixtures.namedItem("minecraft:written_book", 1, 0, "Proof"));
|
||||
items.leaveItems = true;
|
||||
items.ignoreDamage = true;
|
||||
items.ignoreNBT = false;
|
||||
} else if (type == EnumQuestType.Dialog) {
|
||||
QuestDialog dialogs = (QuestDialog) quest.questInterface;
|
||||
dialogs.dialogs.put(0, 1);
|
||||
dialogs.dialogs.put(1, 2);
|
||||
dialogs.dialogs.put(2, 3);
|
||||
} else if (type == EnumQuestType.Kill || type == EnumQuestType.AreaKill) {
|
||||
QuestKill kill = (QuestKill) quest.questInterface;
|
||||
kill.targets.put("Zombie", 20);
|
||||
kill.targets.put("Skeleton", 15);
|
||||
kill.targetType = type == EnumQuestType.AreaKill ? 1 : 0;
|
||||
kill.customTargetType = "noppes.npcs.entity.EntityCustomNpc";
|
||||
} else if (type == EnumQuestType.Location) {
|
||||
QuestLocation location = (QuestLocation) quest.questInterface;
|
||||
location.location = "Northern Watchtower";
|
||||
location.location2 = "Sunken Crypt";
|
||||
location.location3 = "The Long Bridge";
|
||||
} else if (type == EnumQuestType.Manual) {
|
||||
QuestManual manual = (QuestManual) quest.questInterface;
|
||||
manual.manuals.put("Speak to the smith", 1);
|
||||
manual.manuals.put("Gather reeds", 30);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ repeat and completion
|
||||
|
||||
private static void repeatAndCompletion(List<Case<Quest>> out) {
|
||||
int id = 10;
|
||||
for (EnumQuestRepeat repeat : EnumQuestRepeat.values()) {
|
||||
Quest quest = quest(id, "Repeat " + repeat.name(), EnumQuestType.Manual);
|
||||
quest.repeat = repeat;
|
||||
// The two CUSTOM modes are the only ones that read customCooldown, but it is written
|
||||
// unconditionally, so setting it everywhere shows that.
|
||||
quest.customCooldown = 3600000L;
|
||||
((QuestManual) quest.questInterface).manuals.put("Do the thing", 1);
|
||||
out.add(new Case<Quest>("Repeat", quest,
|
||||
"QuestRepeat = " + repeat.name() + " (ordinal " + repeat.ordinal() + ") with "
|
||||
+ "CustomCooldown 3600000. MCDAILY/MCWEEKLY count world ticks, RLDAILY/RLWEEKLY "
|
||||
+ "count wall time, and only MCCUSTOM/RLCUSTOM read the cooldown"));
|
||||
id++;
|
||||
}
|
||||
|
||||
int completionId = 18;
|
||||
for (EnumQuestCompletion completion : EnumQuestCompletion.values()) {
|
||||
Quest quest = quest(completionId, "Completion " + completion.name(), EnumQuestType.Manual);
|
||||
quest.completion = completion;
|
||||
quest.completerNpc = completion == EnumQuestCompletion.Npc ? "Quest Giver" : "";
|
||||
((QuestManual) quest.questInterface).manuals.put("Do the thing", 1);
|
||||
out.add(new Case<Quest>("Repeat", quest,
|
||||
"QuestCompletion = " + completion.name() + ". Npc requires turning in to the named "
|
||||
+ "NPC; Instant completes the moment the objective is met"));
|
||||
completionId++;
|
||||
}
|
||||
|
||||
Quest cooldownExtremes = quest(20, "Cooldown Extremes", EnumQuestType.Manual);
|
||||
cooldownExtremes.repeat = EnumQuestRepeat.RLCUSTOM;
|
||||
cooldownExtremes.customCooldown = Long.MAX_VALUE;
|
||||
((QuestManual) cooldownExtremes.questInterface).manuals.put("Wait", 1);
|
||||
out.add(new Case<Quest>("Repeat", cooldownExtremes,
|
||||
"CustomCooldown at Long.MAX_VALUE -- the one long on a quest, and the field most "
|
||||
+ "likely to be narrowed to an int by a reader"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ rewards
|
||||
|
||||
private static void rewards(List<Case<Quest>> out) {
|
||||
Quest exp = quest(30, "Experience Reward", EnumQuestType.Manual);
|
||||
exp.rewardExp = 2500;
|
||||
((QuestManual) exp.questInterface).manuals.put("Earn it", 1);
|
||||
out.add(new Case<Quest>("Rewards", exp, "RewardExp only"));
|
||||
|
||||
Quest items = quest(31, "Item Rewards", EnumQuestType.Manual);
|
||||
items.rewardItems.items.put(0, Fixtures.item("minecraft:diamond", 5));
|
||||
items.rewardItems.items.put(1, Fixtures.item("minecraft:gold_ingot", 32));
|
||||
items.rewardItems.items.put(8, Fixtures.namedItem("minecraft:diamond_pickaxe", 1, 3, "Miner's Due"));
|
||||
((QuestManual) items.questInterface).manuals.put("Earn it", 1);
|
||||
out.add(new Case<Quest>("Rewards", items,
|
||||
"three of the nine reward slots filled, including slot 8 and one stack with custom "
|
||||
+ "NBT. Stored under the Rewards tag as an NpcMiscInventory"));
|
||||
|
||||
Quest full = quest(32, "Nine Item Rewards", EnumQuestType.Manual);
|
||||
String[] nine = {
|
||||
"minecraft:stone", "minecraft:dirt", "minecraft:oak_stairs", "minecraft:torch",
|
||||
"minecraft:bread", "minecraft:coal", "minecraft:string", "minecraft:bone",
|
||||
"minecraft:paper"
|
||||
};
|
||||
for (int i = 0; i < nine.length; i++) {
|
||||
full.rewardItems.items.put(i, Fixtures.item(nine[i], i + 1));
|
||||
}
|
||||
((QuestManual) full.questInterface).manuals.put("Earn it", 1);
|
||||
out.add(new Case<Quest>("Rewards", full,
|
||||
"all nine reward slots filled, each a different count -- the inventory at capacity"));
|
||||
|
||||
Quest random = quest(33, "Random Reward", EnumQuestType.Manual);
|
||||
random.randomReward = true;
|
||||
random.rewardItems.items.put(0, Fixtures.item("minecraft:emerald", 1));
|
||||
random.rewardItems.items.put(1, Fixtures.item("minecraft:redstone", 1));
|
||||
((QuestManual) random.questInterface).manuals.put("Earn it", 1);
|
||||
out.add(new Case<Quest>("Rewards", random,
|
||||
"RandomReward true -- one of the reward slots is granted rather than all of them"));
|
||||
|
||||
Quest faction = quest(34, "Faction Reward", EnumQuestType.Manual);
|
||||
faction.factionOptions.factionId = 14;
|
||||
faction.factionOptions.factionPoints = 500;
|
||||
faction.factionOptions.decreaseFactionPoints = false;
|
||||
faction.factionOptions.faction2Id = 15;
|
||||
faction.factionOptions.faction2Points = 250;
|
||||
faction.factionOptions.decreaseFaction2Points = true;
|
||||
((QuestManual) faction.questInterface).manuals.put("Earn it", 1);
|
||||
out.add(new Case<Quest>("Rewards", faction,
|
||||
"both faction reward slots, nested under QuestFactionPoints -- note a dialog writes "
|
||||
+ "the same FactionOptions keys flat, not nested"));
|
||||
|
||||
Quest mail = quest(35, "Mail Reward", EnumQuestType.Manual);
|
||||
mail.mail.subject = "Your reward";
|
||||
mail.mail.sender = "The Guild";
|
||||
mail.mail.time = Fixtures.EPOCH;
|
||||
NBTTagCompound message = new NBTTagCompound();
|
||||
message.setString("Text", "Enclosed, with thanks.");
|
||||
mail.mail.message = message;
|
||||
mail.mail.items[0] = Fixtures.item("minecraft:gold_nugget", 64);
|
||||
mail.mail.items[3] = Fixtures.item("minecraft:cake", 1);
|
||||
((QuestManual) mail.questInterface).manuals.put("Earn it", 1);
|
||||
out.add(new Case<Quest>("Rewards", mail,
|
||||
"QuestMail with two of four item slots, including the last slot"));
|
||||
|
||||
Quest command = quest(36, "Command On Completion", EnumQuestType.Manual);
|
||||
command.command = "/give {player} minecraft:diamond 1";
|
||||
((QuestManual) command.questInterface).manuals.put("Earn it", 1);
|
||||
out.add(new Case<Quest>("Rewards", command, "QuestCommand with a {player} placeholder"));
|
||||
|
||||
Quest chain = quest(37, "Chains To Another", EnumQuestType.Manual);
|
||||
chain.nextQuestid = 30;
|
||||
chain.nextQuestTitle = "Experience Reward";
|
||||
((QuestManual) chain.questInterface).manuals.put("Earn it", 1);
|
||||
out.add(new Case<Quest>("Rewards", chain,
|
||||
"NextQuestId 30 with a matching NextQuestTitle. On read CustomNPC+ overwrites the "
|
||||
+ "title from the live controller and blanks it when the target is missing, so "
|
||||
+ "the id is the real link and the title is a cache"));
|
||||
|
||||
Quest danglingChain = quest(38, "Chains Nowhere", EnumQuestType.Manual);
|
||||
danglingChain.nextQuestid = 999999;
|
||||
danglingChain.nextQuestTitle = "A quest that does not exist";
|
||||
((QuestManual) danglingChain.questInterface).manuals.put("Earn it", 1);
|
||||
out.add(new Case<Quest>("Rewards", danglingChain,
|
||||
"NextQuestId pointing at nothing, with a stale title still on disk -- what a world "
|
||||
+ "looks like after the target quest was deleted"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ party and profile
|
||||
|
||||
private static void partyAndProfile(List<Case<Quest>> out) {
|
||||
// The party block is written only when AllowParty is true. Both halves matter.
|
||||
Quest disabled = quest(50, "Party Disabled", EnumQuestType.Manual);
|
||||
disabled.partyOptions.allowParty = false;
|
||||
disabled.partyOptions.minPartySize = 4;
|
||||
disabled.partyOptions.maxPartySize = 8;
|
||||
((QuestManual) disabled.questInterface).manuals.put("Solo", 1);
|
||||
out.add(new Case<Quest>("Party", disabled,
|
||||
"AllowParty false with sizes assigned. Proves the eight party keys are ABSENT from "
|
||||
+ "the file when the flag is off -- the values are lost upstream, so there is "
|
||||
+ "nothing for a converter to preserve"));
|
||||
|
||||
Quest enabled = quest(51, "Party Enabled", EnumQuestType.Manual);
|
||||
enabled.partyOptions.allowParty = true;
|
||||
enabled.partyOptions.onlyParty = true;
|
||||
enabled.partyOptions.partyRequirements = EnumPartyRequirements.All;
|
||||
enabled.partyOptions.rewardControl = EnumPartyExchange.Enrolled;
|
||||
enabled.partyOptions.completeFor = EnumPartyExchange.Valid;
|
||||
enabled.partyOptions.executeCommand = EnumPartyExchange.All;
|
||||
enabled.partyOptions.minPartySize = 2;
|
||||
enabled.partyOptions.maxPartySize = 6;
|
||||
enabled.partyOptions.objectiveRequirement = EnumPartyObjectives.Leader;
|
||||
((QuestManual) enabled.questInterface).manuals.put("Together", 1);
|
||||
out.add(new Case<Quest>("Party", enabled,
|
||||
"AllowParty true and all eight party keys set to non-default enum constants"));
|
||||
|
||||
int id = 52;
|
||||
for (EnumPartyRequirements requirement : EnumPartyRequirements.values()) {
|
||||
Quest quest = quest(id, "Party Requirement " + requirement.name(), EnumQuestType.Manual);
|
||||
quest.partyOptions.allowParty = true;
|
||||
quest.partyOptions.partyRequirements = requirement;
|
||||
((QuestManual) quest.questInterface).manuals.put("Together", 1);
|
||||
out.add(new Case<Quest>("Party", quest,
|
||||
"PartyRequirements = " + requirement.name() + " (ordinal " + requirement.ordinal() + ")"));
|
||||
id++;
|
||||
}
|
||||
for (EnumPartyExchange exchange : EnumPartyExchange.values()) {
|
||||
Quest quest = quest(id, "Party Reward " + exchange.name(), EnumQuestType.Manual);
|
||||
quest.partyOptions.allowParty = true;
|
||||
quest.partyOptions.rewardControl = exchange;
|
||||
((QuestManual) quest.questInterface).manuals.put("Together", 1);
|
||||
out.add(new Case<Quest>("Party", quest,
|
||||
"RewardControl = " + exchange.name() + " (ordinal " + exchange.ordinal() + ")"));
|
||||
id++;
|
||||
}
|
||||
for (EnumPartyObjectives objective : EnumPartyObjectives.values()) {
|
||||
Quest quest = quest(id, "Party Objective " + objective.name(), EnumQuestType.Manual);
|
||||
quest.partyOptions.allowParty = true;
|
||||
quest.partyOptions.objectiveRequirement = objective;
|
||||
((QuestManual) quest.questInterface).manuals.put("Together", 1);
|
||||
out.add(new Case<Quest>("Party", quest,
|
||||
"ObjectiveRequirement = " + objective.name() + " (ordinal " + objective.ordinal() + ")"));
|
||||
id++;
|
||||
}
|
||||
|
||||
Quest profileOff = quest(62, "Profiles Disabled", EnumQuestType.Manual);
|
||||
profileOff.profileOptions.enableOptions = false;
|
||||
profileOff.profileOptions.cooldownControl = EnumProfileSync.Shared;
|
||||
((QuestManual) profileOff.questInterface).manuals.put("Alone", 1);
|
||||
out.add(new Case<Quest>("Party", profileOff,
|
||||
"EnableProfiles false with a Shared cooldown assigned -- the two profile keys are "
|
||||
+ "absent from the file, same shape as the party block"));
|
||||
|
||||
int profileId = 63;
|
||||
for (EnumProfileSync sync : EnumProfileSync.values()) {
|
||||
Quest quest = quest(profileId, "Profile " + sync.name(), EnumQuestType.Manual);
|
||||
quest.profileOptions.enableOptions = true;
|
||||
quest.profileOptions.cooldownControl = sync;
|
||||
quest.profileOptions.completeControl = sync;
|
||||
((QuestManual) quest.questInterface).manuals.put("Alone", 1);
|
||||
out.add(new Case<Quest>("Party", quest,
|
||||
"EnableProfiles true, CooldownControl and CompleteControl = " + sync.name()));
|
||||
profileId++;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ objectives in depth
|
||||
|
||||
private static void objectives(List<Case<Quest>> out) {
|
||||
Quest emptyKill = quest(70, "Kill Nothing", EnumQuestType.Kill);
|
||||
out.add(new Case<Quest>("Objectives", emptyKill,
|
||||
"a Kill quest with an EMPTY target list. isCompleted counts completed targets against "
|
||||
+ "the target count, so zero of zero passes -- this quest is complete on accept"));
|
||||
|
||||
Quest manyKill = quest(71, "Kill Many Kinds", EnumQuestType.Kill);
|
||||
QuestKill kill = (QuestKill) manyKill.questInterface;
|
||||
String[] mobs = {"Zombie", "Skeleton", "Creeper", "Spider", "Enderman", "Blaze"};
|
||||
for (int i = 0; i < mobs.length; i++) {
|
||||
kill.targets.put(mobs[i], (i + 1) * 10);
|
||||
}
|
||||
out.add(new Case<Quest>("Objectives", manyKill,
|
||||
"six kill targets. Stored as a TreeMap, so the file is alphabetical rather than "
|
||||
+ "insertion-ordered -- Blaze first, Zombie last"));
|
||||
|
||||
Quest customTarget = quest(72, "Kill A Custom NPC", EnumQuestType.Kill);
|
||||
QuestKill custom = (QuestKill) customTarget.questInterface;
|
||||
custom.targets.put("Village Elder", 1);
|
||||
custom.targetType = 1;
|
||||
custom.customTargetType = "noppes.npcs.entity.EntityCustomNpc";
|
||||
out.add(new Case<Quest>("Objectives", customTarget,
|
||||
"TargetType 1 with a CustomTargetType class name -- targets an NPC by display name "
|
||||
+ "rather than an entity by type"));
|
||||
|
||||
Quest emptyItems = quest(73, "Bring Nothing", EnumQuestType.Item);
|
||||
QuestItem noItems = (QuestItem) emptyItems.questInterface;
|
||||
noItems.ignoreDamage = true;
|
||||
noItems.ignoreNBT = true;
|
||||
noItems.leaveItems = true;
|
||||
out.add(new Case<Quest>("Objectives", emptyItems,
|
||||
"an Item quest with no required items and all three matching flags on"));
|
||||
|
||||
Quest variantItems = quest(74, "Bring Variants", EnumQuestType.Item);
|
||||
QuestItem variants = (QuestItem) variantItems.questInterface;
|
||||
variants.items.items.put(0, Fixtures.variant("minecraft:wool", 8, 14));
|
||||
variants.items.items.put(1, Fixtures.variant("minecraft:planks", 4, 3));
|
||||
variants.items.items.put(2, Fixtures.variant("minecraft:dye", 16, 4));
|
||||
out.add(new Case<Quest>("Objectives", variantItems,
|
||||
"three pre-Flattening variants -- red wool (14), jungle planks (3) and lapis dye (4). "
|
||||
+ "Damage is a variant selector here, not durability, and each becomes a distinct "
|
||||
+ "item after 1.13, so this is the case a variant table has to cover"));
|
||||
|
||||
Quest manyDialogs = quest(75, "Read Many Dialogs", EnumQuestType.Dialog);
|
||||
QuestDialog dialogs = (QuestDialog) manyDialogs.questInterface;
|
||||
for (int i = 0; i < 5; i++) {
|
||||
dialogs.dialogs.put(i, 30 + i);
|
||||
}
|
||||
out.add(new Case<Quest>("Objectives", manyDialogs,
|
||||
"five dialog objectives. NOTE the key collision worth knowing about: a Dialog quest "
|
||||
+ "stores these under QuestDialogs, which is exactly where a pre-split Kill quest "
|
||||
+ "stored its targets -- see the legacy world"));
|
||||
|
||||
Quest oneLocation = quest(76, "One Location", EnumQuestType.Location);
|
||||
((QuestLocation) oneLocation.questInterface).location = "The Old Well";
|
||||
out.add(new Case<Quest>("Objectives", oneLocation,
|
||||
"only the first of three location slots set; the other two are written as empty"));
|
||||
|
||||
Quest manuals = quest(77, "Manual Counters", EnumQuestType.Manual);
|
||||
QuestManual manual = (QuestManual) manuals.questInterface;
|
||||
manual.manuals.put("Deliver the letter", 1);
|
||||
manual.manuals.put("Light the beacons", 3);
|
||||
manual.manuals.put("Survive the night", 1);
|
||||
out.add(new Case<Quest>("Objectives", manuals,
|
||||
"three manual counters -- progress a script or an operator advances by hand"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ combinations
|
||||
|
||||
private static void combinations(List<Case<Quest>> out) {
|
||||
Quest everything = quest(90, "Everything At Once", EnumQuestType.Item);
|
||||
everything.logText = "Bring the ingots, and be quick about it.";
|
||||
everything.completeText = "You have my thanks.";
|
||||
everything.completerNpc = "Quartermaster";
|
||||
everything.command = "/say {player} finished";
|
||||
everything.repeat = EnumQuestRepeat.MCCUSTOM;
|
||||
everything.customCooldown = 172800000L;
|
||||
everything.completion = EnumQuestCompletion.Instant;
|
||||
everything.nextQuestid = 1;
|
||||
everything.nextQuestTitle = "Type Item";
|
||||
everything.rewardExp = 1000;
|
||||
everything.randomReward = true;
|
||||
everything.rewardItems.items.put(0, Fixtures.item("minecraft:diamond", 3));
|
||||
everything.rewardItems.items.put(4, Fixtures.namedItem("minecraft:iron_sword", 1, 5, "Reward"));
|
||||
everything.factionOptions.factionId = 0;
|
||||
everything.factionOptions.factionPoints = 75;
|
||||
everything.partyOptions.allowParty = true;
|
||||
everything.partyOptions.onlyParty = false;
|
||||
everything.partyOptions.partyRequirements = EnumPartyRequirements.Valid;
|
||||
everything.partyOptions.rewardControl = EnumPartyExchange.All;
|
||||
everything.partyOptions.minPartySize = 2;
|
||||
everything.partyOptions.maxPartySize = 4;
|
||||
everything.profileOptions.enableOptions = true;
|
||||
everything.profileOptions.cooldownControl = EnumProfileSync.Shared;
|
||||
everything.profileOptions.completeControl = EnumProfileSync.Individual;
|
||||
everything.mail.subject = "Everything";
|
||||
everything.mail.sender = "Quartermaster";
|
||||
everything.mail.time = Fixtures.EPOCH;
|
||||
everything.mail.items[0] = Fixtures.item("minecraft:emerald", 12);
|
||||
QuestItem items = (QuestItem) everything.questInterface;
|
||||
items.items.items.put(0, Fixtures.item("minecraft:iron_ingot", 20));
|
||||
items.items.items.put(2, Fixtures.variant("minecraft:wool", 1, 11));
|
||||
items.leaveItems = false;
|
||||
items.ignoreDamage = false;
|
||||
items.ignoreNBT = true;
|
||||
out.add(new Case<Quest>("Combinations", everything,
|
||||
"every quest sub-object populated at once: objective, rewards, faction, party, "
|
||||
+ "profile, mail, chain, cooldown and command"));
|
||||
|
||||
Quest bare = quest(91, "Bare", EnumQuestType.Item);
|
||||
out.add(new Case<Quest>("Combinations", bare,
|
||||
"every field at its constructor default, for comparison against id 90"));
|
||||
|
||||
Quest unicode = quest(92, Text.CYRILLIC_QUEST + " " + Text.EM_DASH + " " + Text.ELEVES,
|
||||
EnumQuestType.Manual);
|
||||
unicode.logText = Text.RTL;
|
||||
unicode.completeText = Text.ASTRAL;
|
||||
unicode.completerNpc = Text.KATAKANA_FACTION;
|
||||
((QuestManual) unicode.questInterface).manuals.put(Text.CYRILLIC_QUEST, 1);
|
||||
out.add(new Case<Quest>("Combinations", unicode,
|
||||
"non-Latin title, log text, complete text, completer name and objective key. The "
|
||||
+ "objective key is the interesting one -- it is an NBT map key, not a value"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ helpers
|
||||
|
||||
/**
|
||||
* Builds a quest with its type applied.
|
||||
*
|
||||
* <p>Order matters: {@code setType} replaces {@code questInterface} and stamps it with the
|
||||
* quest id, so both must be set before the objective is populated.
|
||||
*/
|
||||
private static Quest quest(int id, String title, EnumQuestType type) {
|
||||
Quest quest = new Quest();
|
||||
quest.id = id;
|
||||
quest.title = title;
|
||||
quest.setType(type);
|
||||
quest.logText = "Objective for " + title + ".";
|
||||
quest.completeText = "Done: " + title + ".";
|
||||
return quest;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package kamkeel.npcs.fixtures.content;
|
||||
|
||||
/**
|
||||
* Non-ASCII strings the fixtures use, built from code points.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package kamkeel.npcs.fixtures.content;
|
||||
|
||||
import kamkeel.npcs.fixtures.Fixtures;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.controllers.data.Bank;
|
||||
import noppes.npcs.controllers.data.SpawnData;
|
||||
import noppes.npcs.controllers.data.Tag;
|
||||
import noppes.npcs.controllers.data.TransportCategory;
|
||||
import noppes.npcs.controllers.data.TransportLocation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* The world-level {@code .dat} documents: global, tags, transport, banks and spawns.
|
||||
*
|
||||
* <p>All five share a shape -- one compound holding a list of entries plus a {@code lastID} -- and
|
||||
* each list is built here in a fixed order rather than by iterating the controller's HashMap, so
|
||||
* regeneration is a no-op rather than a reshuffle.
|
||||
*
|
||||
* <p>Every document format below is copied from its controller's {@code getNBT}, named per method.
|
||||
*/
|
||||
public final class WorldDataFixtures {
|
||||
|
||||
private WorldDataFixtures() {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ global.dat
|
||||
|
||||
/** GlobalDataController.saveData -- a single integer, and the smallest document CNPC+ writes. */
|
||||
public static NBTTagCompound global(int itemGiverId) {
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
compound.setInteger("itemGiverId", itemGiverId);
|
||||
return compound;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tags.dat
|
||||
|
||||
/**
|
||||
* Tags. Note {@link Tag#uuid} defaults to {@code randomUUID()}, so every fixture here sets one
|
||||
* explicitly -- otherwise the corpus would differ on every run and the reproducibility check
|
||||
* would fail for a reason that has nothing to do with the format.
|
||||
*/
|
||||
public static NBTTagCompound tags() {
|
||||
List<Tag> tags = new ArrayList<Tag>();
|
||||
|
||||
tags.add(tag(1, "Boss", 0xFF0000, "3f2504e0-4f89-41d3-9a0c-0305e82c3301", false));
|
||||
tags.add(tag(2, "Hidden", 0x333333, "3f2504e0-4f89-41d3-9a0c-0305e82c3302", true));
|
||||
tags.add(tag(3, "", 0x00FF00, "3f2504e0-4f89-41d3-9a0c-0305e82c3303", false));
|
||||
tags.add(tag(4, Text.KATAKANA_FACTION, 0xFFFFFF,
|
||||
"3f2504e0-4f89-41d3-9a0c-0305e82c3304", false));
|
||||
tags.add(tag(5, "Extremes", -1, "ffffffff-ffff-ffff-ffff-ffffffffffff", true));
|
||||
|
||||
NBTTagList list = new NBTTagList();
|
||||
for (Tag tag : tags) {
|
||||
NBTTagCompound entry = new NBTTagCompound();
|
||||
tag.writeNBT(entry);
|
||||
list.appendTag(entry);
|
||||
}
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
compound.setInteger("lastID", 5);
|
||||
compound.setTag("NPCTags", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
private static Tag tag(int id, String name, int color, String uuid, boolean hidden) {
|
||||
Tag tag = new Tag();
|
||||
tag.id = id;
|
||||
tag.name = name;
|
||||
tag.color = color;
|
||||
tag.uuid = UUID.fromString(uuid);
|
||||
tag.hideTag = hidden;
|
||||
return tag;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ transport.dat
|
||||
|
||||
/**
|
||||
* Transport locations, grouped into categories.
|
||||
*
|
||||
* <p>The one place CustomNPC+ stores a dimension as a bare {@code int} alongside a position --
|
||||
* which is the signature that stopped being expressible after 1.16, so it is worth having on
|
||||
* disk in both a vanilla dimension and a modded id.
|
||||
*/
|
||||
public static NBTTagCompound transport() {
|
||||
List<TransportCategory> categories = new ArrayList<TransportCategory>();
|
||||
|
||||
TransportCategory overworld = category(1, "Overworld");
|
||||
overworld.locations.put(1, location(1, "Spawn Plaza", 0.5D, 64.0D, 0.5D, 0, 0));
|
||||
overworld.locations.put(2, location(2, "Northern Watchtower", -1204.5D, 96.0D, 3311.5D, 1, 0));
|
||||
overworld.locations.put(3, location(3, "Negative Coordinates",
|
||||
-30000000.0D, -64.0D, -30000000.0D, 2, 0));
|
||||
categories.add(overworld);
|
||||
|
||||
TransportCategory other = category(2, "Other Dimensions");
|
||||
other.locations.put(4, location(4, "Nether Hub", 12.0D, 70.0D, -8.0D, 0, -1));
|
||||
other.locations.put(5, location(5, "The End", 100.0D, 50.0D, 0.0D, 0, 1));
|
||||
// A modded dimension id, which is the case a numeric-to-key translation table must either
|
||||
// cover or refuse rather than silently map to the overworld.
|
||||
other.locations.put(6, location(6, "Modded Dimension", 0.0D, 0.0D, 0.0D, 0, 7265));
|
||||
categories.add(other);
|
||||
|
||||
TransportCategory empty = category(3, "Empty Category");
|
||||
categories.add(empty);
|
||||
|
||||
NBTTagList list = new NBTTagList();
|
||||
for (TransportCategory category : categories) {
|
||||
NBTTagCompound entry = new NBTTagCompound();
|
||||
category.writeNBT(entry);
|
||||
list.appendTag(entry);
|
||||
}
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
compound.setInteger("lastID", 6);
|
||||
compound.setTag("NPCTransportCategories", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
private static TransportCategory category(int id, String title) {
|
||||
TransportCategory category = new TransportCategory();
|
||||
category.id = id;
|
||||
category.title = title;
|
||||
return category;
|
||||
}
|
||||
|
||||
private static TransportLocation location(int id, String name, double x, double y, double z,
|
||||
int type, int dimension) {
|
||||
TransportLocation location = new TransportLocation();
|
||||
location.id = id;
|
||||
location.name = name;
|
||||
location.posX = x;
|
||||
location.posY = y;
|
||||
location.posZ = z;
|
||||
location.type = type;
|
||||
location.dimension = dimension;
|
||||
return location;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ bank.dat
|
||||
|
||||
/** BankController.getNBT -- note the key is "Data" and there is no lastID. */
|
||||
public static NBTTagCompound banks() {
|
||||
List<Bank> banks = new ArrayList<Bank>();
|
||||
|
||||
Bank basic = bank(1, "Village Bank", 2, 9);
|
||||
basic.currencyInventory.items.put(0, Fixtures.item("minecraft:emerald", 1));
|
||||
basic.upgradeInventory.items.put(0, Fixtures.item("minecraft:gold_ingot", 8));
|
||||
for (int slot = 0; slot < 9; slot++) {
|
||||
basic.slotTypes.put(slot, slot % 3);
|
||||
}
|
||||
banks.add(basic);
|
||||
|
||||
Bank bare = bank(2, "", 1, 1);
|
||||
banks.add(bare);
|
||||
|
||||
Bank big = bank(3, "Vault", 6, 54);
|
||||
big.currencyInventory.items.put(0, Fixtures.namedItem("minecraft:diamond", 64, 0, "Deposit"));
|
||||
for (int slot = 0; slot < 54; slot++) {
|
||||
big.slotTypes.put(slot, slot % 4);
|
||||
}
|
||||
banks.add(big);
|
||||
|
||||
NBTTagList list = new NBTTagList();
|
||||
for (Bank bank : banks) {
|
||||
NBTTagCompound entry = new NBTTagCompound();
|
||||
bank.writeEntityToNBT(entry);
|
||||
list.appendTag(entry);
|
||||
}
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
compound.setTag("Data", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
private static Bank bank(int id, String name, int startSlots, int maxSlots) {
|
||||
Bank bank = new Bank();
|
||||
bank.id = id;
|
||||
bank.name = name;
|
||||
bank.startSlots = startSlots;
|
||||
bank.maxSlots = maxSlots;
|
||||
return bank;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ spawns.dat
|
||||
|
||||
/**
|
||||
* Natural spawn entries.
|
||||
*
|
||||
* <p>The interesting shape here is {@code SpawnCompound<n>}: the per-variant NPC data is
|
||||
* written as a numbered key rather than a list, so a reader has to probe for
|
||||
* {@code SpawnCompound0}, {@code SpawnCompound1}, ... rather than iterate. The dimension set
|
||||
* is written only when non-empty, so the key is absent on most entries.
|
||||
*/
|
||||
public static NBTTagCompound spawns() {
|
||||
List<SpawnData> spawns = new ArrayList<SpawnData>();
|
||||
|
||||
SpawnData plains = spawn(1, "Plains Wanderer", 10);
|
||||
plains.biomes.addAll(Arrays.asList("Plains", "Sunflower Plains", "Forest"));
|
||||
plains.spawnCompounds.put(0, npcStub("Wanderer"));
|
||||
spawns.add(plains);
|
||||
|
||||
SpawnData variants = spawn(2, "Cave Dweller", 3);
|
||||
variants.biomes.add("Extreme Hills");
|
||||
variants.dimensions.addAll(Arrays.asList(0, -1, 7265));
|
||||
variants.monsterSpawning = true;
|
||||
variants.animalSpawning = false;
|
||||
variants.airSpawning = true;
|
||||
variants.liquidSpawning = true;
|
||||
variants.spawnHeightMin = 5;
|
||||
variants.spawnHeightMax = 40;
|
||||
variants.maxAlive = 12;
|
||||
variants.cooldownTicks = 600;
|
||||
variants.attemptsPerCycle = 4;
|
||||
// Three numbered compounds, which is the shape worth pinning.
|
||||
variants.spawnCompounds.put(0, npcStub("Dweller A"));
|
||||
variants.spawnCompounds.put(1, npcStub("Dweller B"));
|
||||
variants.spawnCompounds.put(2, npcStub("Dweller C"));
|
||||
spawns.add(variants);
|
||||
|
||||
SpawnData bare = spawn(3, "", 0);
|
||||
spawns.add(bare);
|
||||
|
||||
NBTTagList list = new NBTTagList();
|
||||
for (SpawnData spawn : spawns) {
|
||||
list.appendTag(spawn.writeNBT(new NBTTagCompound()));
|
||||
}
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
compound.setInteger("lastID", 3);
|
||||
compound.setTag("NPCSpawnData", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
private static SpawnData spawn(int id, String name, int weight) {
|
||||
SpawnData spawn = new SpawnData();
|
||||
spawn.id = id;
|
||||
spawn.name = name;
|
||||
spawn.itemWeight = weight;
|
||||
return spawn;
|
||||
}
|
||||
|
||||
/**
|
||||
* A stand-in for a stored NPC.
|
||||
*
|
||||
* <p>Deliberately not a real {@code EntityCustomNpc}: constructing one needs a World, and a
|
||||
* spawn entry stores whatever compound it was given without inspecting it. A fixture with a
|
||||
* full NPC in it belongs with the NPC system, which is not covered here yet -- so this says
|
||||
* what it is rather than pretending.
|
||||
*/
|
||||
private static NBTTagCompound npcStub(String name) {
|
||||
NBTTagCompound stub = new NBTTagCompound();
|
||||
stub.setString("Name", name);
|
||||
stub.setString("FixtureNote", "placeholder -- not a serialized EntityCustomNpc");
|
||||
return stub;
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<Faction> 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");
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<Faction> 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");
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p><b>Synthesized, and the only world here that is.</b> 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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
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.EffectFixtures;
|
||||
import kamkeel.npcs.fixtures.content.FactionFixtures;
|
||||
import kamkeel.npcs.fixtures.content.PlayerFixtures;
|
||||
import kamkeel.npcs.fixtures.content.QuestFixtures;
|
||||
import kamkeel.npcs.fixtures.content.WorldDataFixtures;
|
||||
import noppes.npcs.controllers.data.PlayerData;
|
||||
import noppes.npcs.controllers.data.CustomEffect;
|
||||
import noppes.npcs.controllers.data.Dialog;
|
||||
import noppes.npcs.controllers.data.Faction;
|
||||
import noppes.npcs.controllers.data.Quest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Every field CustomNPC+ can store, moved off its default at least once.
|
||||
*
|
||||
* <p>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<Faction> 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<Dialog> c : DialogFixtures.maximal()) {
|
||||
out.dialog(c.category, c.value, c.note);
|
||||
}
|
||||
|
||||
for (Case<Quest> c : QuestFixtures.maximal()) {
|
||||
out.quest(c.category, c.value, c.note);
|
||||
}
|
||||
|
||||
List<Case<CustomEffect>> effects = EffectFixtures.maximal();
|
||||
for (Case<CustomEffect> c : effects) {
|
||||
out.effect(c.category, c.value, c.note);
|
||||
}
|
||||
out.effect("", EffectFixtures.MISMATCH_FILENAME, EffectFixtures.nameMismatch(),
|
||||
"the name key inside the file says 'Name Inside The File' while the file is called '"
|
||||
+ EffectFixtures.MISMATCH_FILENAME + ".json'. loadEffectsFromDir overwrites the "
|
||||
+ "field from the filename after reading, so the filename wins and a reader "
|
||||
+ "trusting the key gets a different answer");
|
||||
|
||||
out.dat("effect", "customeffects.dat", EffectFixtures.index(effects, 12),
|
||||
"the custom effect INDEX -- {Name, ID} pairs and lastID, not the effects themselves, "
|
||||
+ "which are the .json files under customeffects/. The unnamed effect is absent "
|
||||
+ "from this index by design");
|
||||
|
||||
out.dat("global", "global.dat", WorldDataFixtures.global(42),
|
||||
"one integer. The smallest document CustomNPC+ writes, and a useful floor for a "
|
||||
+ "reader's envelope handling");
|
||||
|
||||
out.dat("tag", "tags.dat", WorldDataFixtures.tags(),
|
||||
"five tags with explicit UUIDs, covering hidden, empty-named, non-Latin and a colour "
|
||||
+ "of -1. Tag.uuid defaults to randomUUID(), so these are pinned deliberately");
|
||||
|
||||
out.dat("transport", "transport.dat", WorldDataFixtures.transport(),
|
||||
"three categories and six locations, including negative coordinates, the Nether and "
|
||||
+ "End by numeric id, and a modded dimension 7265 -- the int dimension that "
|
||||
+ "stopped being expressible after 1.16");
|
||||
|
||||
out.dat("bank", "bank.dat", WorldDataFixtures.banks(),
|
||||
"three banks with currency and upgrade inventories and per-slot types. Keyed under "
|
||||
+ "'Data' with no lastID, unlike every other document here");
|
||||
|
||||
out.dat("spawn", "spawns.dat", WorldDataFixtures.spawns(),
|
||||
"three natural spawn entries. One carries three numbered SpawnCompound keys rather "
|
||||
+ "than a list, which a reader has to probe for rather than iterate");
|
||||
|
||||
List<Case<PlayerData>> players = PlayerFixtures.records();
|
||||
for (Case<PlayerData> c : players) {
|
||||
out.json("player", c.value.uuid, "playerdata/" + c.value.uuid + ".json",
|
||||
c.value.getNBT(), c.note);
|
||||
}
|
||||
// The same record as gzipped NBT, which is what ConfigMain.DatFormat selects instead. Same
|
||||
// compound, different container -- a reader has to handle both because a server operator
|
||||
// chooses between them.
|
||||
PlayerData asDat = players.get(1).value;
|
||||
out.dat("player", "playerdata/" + asDat.uuid + ".dat", asDat.getNBT(),
|
||||
"the Progressed player again, written as gzipped NBT rather than JSON. "
|
||||
+ "ConfigMain.DatFormat picks the container; the compound is identical. Both "
|
||||
+ "extensions are loaded by PlayerDataController, so both are real");
|
||||
|
||||
out.dat("player", "playerdatamap.dat", PlayerFixtures.index(PlayerFixtures.roster()),
|
||||
"the name/uuid index. Derived rather than authoritative -- CustomNPC+ rebuilds it by "
|
||||
+ "scanning playerdata/ when the file is missing -- but it is what gets read first");
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import foxz.commandhelper.annotations.SubCommand;
|
||||
import foxz.commandhelper.permissions.OpOnly;
|
||||
import foxz.commandhelper.permissions.ParamCheck;
|
||||
import kamkeel.npcs.controllers.SyncController;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.command.CommandBase;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import noppes.npcs.NoppesUtilServer;
|
||||
@@ -90,7 +91,7 @@ public class CmdDialog extends ChMcLogger {
|
||||
)
|
||||
public boolean reload(String args[]) {
|
||||
new DialogController().load();
|
||||
SyncController.syncAllDialogs();
|
||||
SyncController.syncAll(SyncType.DIALOG_CATEGORY);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import foxz.commandhelper.annotations.SubCommand;
|
||||
import foxz.commandhelper.permissions.OpOnly;
|
||||
import foxz.commandhelper.permissions.ParamCheck;
|
||||
import kamkeel.npcs.controllers.SyncController;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import kamkeel.npcs.network.packets.data.AchievementPacket;
|
||||
import kamkeel.npcs.network.packets.data.ChatAlertPacket;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
@@ -170,7 +171,7 @@ public class CmdQuest extends ChMcLogger {
|
||||
)
|
||||
public boolean reload(String args[]) {
|
||||
new QuestController().load();
|
||||
SyncController.syncAllQuests();
|
||||
SyncController.syncAll(SyncType.QUEST_CATEGORY);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import net.minecraft.entity.Entity;
|
||||
import net.minecraft.util.Vec3;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 3D Vector helper class for lightning calculations.
|
||||
* Adapted from Botania's Vector3 by ChickenBones.
|
||||
@@ -181,4 +183,9 @@ public class Vec3d {
|
||||
Vec3d v = (Vec3d) o;
|
||||
return x == v.x && y == v.y && z == v.z;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(x, y, z);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package kamkeel.npcs.command;
|
||||
|
||||
import kamkeel.npcs.controllers.SyncController;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.command.CommandBase;
|
||||
import net.minecraft.command.CommandException;
|
||||
import net.minecraft.command.ICommandSender;
|
||||
@@ -93,7 +94,7 @@ public class DialogCommand extends CommandKamkeelBase {
|
||||
)
|
||||
public void reload(ICommandSender sender, String args[]) {
|
||||
new DialogController().load();
|
||||
SyncController.syncAllDialogs();
|
||||
SyncController.syncAll(SyncType.DIALOG_CATEGORY);
|
||||
sendResult(sender, "Dialogs Reloaded");
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package kamkeel.npcs.command;
|
||||
|
||||
import kamkeel.npcs.controllers.ProfileController;
|
||||
import kamkeel.npcs.controllers.SyncController;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import kamkeel.npcs.network.packets.data.AchievementPacket;
|
||||
import kamkeel.npcs.network.packets.data.ChatAlertPacket;
|
||||
import net.minecraft.command.CommandException;
|
||||
@@ -393,7 +394,7 @@ public class QuestCommand extends CommandKamkeelBase {
|
||||
)
|
||||
public void reload(ICommandSender sender, String args[]) {
|
||||
new QuestController().load();
|
||||
SyncController.syncAllQuests();
|
||||
SyncController.syncAll(SyncType.QUEST_CATEGORY);
|
||||
sendResult(sender, "Quests Reloaded");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import kamkeel.npcs.controllers.data.ability.type.AbilitySlam;
|
||||
import kamkeel.npcs.controllers.data.ability.type.AbilityTeleport;
|
||||
import kamkeel.npcs.controllers.data.ability.type.AbilityTrap;
|
||||
import kamkeel.npcs.controllers.data.ability.type.AbilityVortex;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import kamkeel.npcs.controllers.data.ability.type.energy.AbilityBeam;
|
||||
import kamkeel.npcs.controllers.data.ability.type.energy.AbilityDisc;
|
||||
import kamkeel.npcs.controllers.data.ability.type.energy.AbilityDome;
|
||||
@@ -44,7 +45,10 @@ import net.minecraftforge.common.util.Constants;
|
||||
import noppes.npcs.controllers.data.AbilityScript;
|
||||
import noppes.npcs.controllers.data.ChainedAbilityScript;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
import kamkeel.npcs.controllers.sync.handlers.PlayerAbilitySyncHelper;
|
||||
import kamkeel.npcs.entity.EntityEnergyBarrier;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.CustomNpcs;
|
||||
import noppes.npcs.LogWriter;
|
||||
@@ -393,7 +397,7 @@ public class AbilityController implements IAbilityHandler {
|
||||
customAbilitiesById.put(uuid, ability);
|
||||
customAbilityRevision++;
|
||||
LogWriter.script("Saved custom ability: " + name + " [" + uuid + "]");
|
||||
SyncController.syncAllCustomAbilities();
|
||||
SyncController.syncAll(SyncType.CUSTOM_ABILITY);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LogWriter.error("Error saving custom ability: " + name, e);
|
||||
@@ -469,16 +473,30 @@ public class AbilityController implements IAbilityHandler {
|
||||
pData.abilityData.lockAbility(name);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (uuid != null && !uuid.isEmpty()) {
|
||||
pData.abilityData.setToggleEntryDirect(uuid, 0);
|
||||
}
|
||||
pData.abilityData.setToggleEntryDirect(name, 0);
|
||||
|
||||
if (pData.hotbarData != null) {
|
||||
pData.hotbarData.validateSlots();
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
pData.save();
|
||||
}
|
||||
|
||||
if (pData.player instanceof EntityPlayerMP) {
|
||||
PlayerAbilitySyncHelper.syncAbilities((EntityPlayerMP) pData.player);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
customAbilityRevision++;
|
||||
LogWriter.script("Deleted custom ability: " + name);
|
||||
SyncController.syncAllCustomAbilities();
|
||||
SyncController.syncAll(SyncType.CUSTOM_ABILITY);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -765,7 +783,7 @@ public class AbilityController implements IAbilityHandler {
|
||||
chainedAbilitiesById.put(uuid, chain);
|
||||
chainedAbilityRevision++;
|
||||
LogWriter.script("Saved chained ability: " + name + " [" + uuid + "]");
|
||||
SyncController.syncAllChainedAbilities();
|
||||
SyncController.syncAll(SyncType.CHAINED_ABILITY);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LogWriter.error("Error saving chained ability: " + name, e);
|
||||
@@ -845,7 +863,7 @@ public class AbilityController implements IAbilityHandler {
|
||||
|
||||
chainedAbilityRevision++;
|
||||
LogWriter.script("Deleted chained ability: " + name);
|
||||
SyncController.syncAllChainedAbilities();
|
||||
SyncController.syncAll(SyncType.CHAINED_ABILITY);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1362,6 +1380,17 @@ public class AbilityController implements IAbilityHandler {
|
||||
return health;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire modifyBarrierMeleeDamage on all extenders. Cumulative — each extender's output feeds the next.
|
||||
*/
|
||||
public float fireModifyBarrierMeleeDamage(EntityEnergyBarrier barrier, EntityLivingBase attacker, float baseDamage) {
|
||||
float damage = baseDamage;
|
||||
for (IAbilityExtender ext : extenders) {
|
||||
damage = ext.modifyBarrierMeleeDamage(barrier, attacker, damage);
|
||||
}
|
||||
return damage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire onAbilityHeal on all extenders. Chain of responsibility — first true wins.
|
||||
*/
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -840,19 +840,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
|
||||
return sb.toString();
|
||||
}).tab("General"));
|
||||
|
||||
defs.add(FieldDef.subGuiField("ability.magic.editor",
|
||||
() -> new SubGuiAbilityMagic(magicData.copy()),
|
||||
gui -> {
|
||||
MagicData result = ((SubGuiAbilityMagic) gui).magicData;
|
||||
magicData.getMagics().clear();
|
||||
for (Map.Entry<Integer, MagicEntry> e : result.getMagics().entrySet()) {
|
||||
magicData.getMagics().put(e.getKey(), e.getValue());
|
||||
}
|
||||
})
|
||||
.buttonLabel(() -> magicData.isEmpty()
|
||||
? StatCollector.translateToLocal("ability.magic.usesCaster")
|
||||
: magicData.getMagics().size() + " Magic(s)")
|
||||
.tab("General"));
|
||||
defs.add(SubGuiAbilityMagic.createMagicField(magicData));
|
||||
}
|
||||
|
||||
// ── Target tab ───────────────────────────────────────────────
|
||||
@@ -1062,10 +1050,11 @@ public abstract class Ability implements IAbility, IAbilityAction {
|
||||
return null;
|
||||
}
|
||||
|
||||
telegraph.setDurationTicks(windUpTicks);
|
||||
int windUp = getWindUpTicks();
|
||||
telegraph.setDurationTicks(windUp);
|
||||
telegraph.setColor(windUpColor);
|
||||
telegraph.setWarningColor(activeColor);
|
||||
telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4));
|
||||
telegraph.setWarningStartTick(Math.max(5, windUp / 4));
|
||||
telegraph.setHeightOffset(telegraphHeightOffset);
|
||||
|
||||
TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw);
|
||||
@@ -1183,7 +1172,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
|
||||
this.burstIndex = 0;
|
||||
this.burstEntities.clear();
|
||||
|
||||
if (windUpTicks <= 0) {
|
||||
if (getWindUpTicks() <= 0) {
|
||||
this.phase = AbilityPhase.ACTIVE;
|
||||
} else {
|
||||
this.phase = AbilityPhase.WINDUP;
|
||||
@@ -1205,7 +1194,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
|
||||
|
||||
switch (phase) {
|
||||
case WINDUP:
|
||||
if (currentTick >= windUpTicks) {
|
||||
if (currentTick >= getWindUpTicks()) {
|
||||
phase = AbilityPhase.ACTIVE;
|
||||
currentTick = 0;
|
||||
return true;
|
||||
|
||||
+7
-19
@@ -34,27 +34,15 @@ public class ConditionHasEffect extends AbilityCondition {
|
||||
return CustomEffectController.getInstance().hasEffect(player, effectId, effectIndex);
|
||||
}
|
||||
|
||||
public void setEffect(int effectId, int effectIndex) {
|
||||
this.effectId = effectId;
|
||||
this.effectIndex = effectIndex;
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void getConditionDefinitions(List<FieldDef> defs) {
|
||||
defs.add(FieldDef.subGuiField("condition.select_effect",
|
||||
() -> new SubGuiCustomEffectSelect(effectId, effectIndex),
|
||||
gui -> {
|
||||
SubGuiCustomEffectSelect sel = (SubGuiCustomEffectSelect) gui;
|
||||
if (sel.getSelectedEffectId() >= 0) {
|
||||
effectId = sel.getSelectedEffectId();
|
||||
effectIndex = sel.getSelectedIndex();
|
||||
}
|
||||
})
|
||||
.buttonLabel(() -> {
|
||||
if (effectId < 0) return "None";
|
||||
CustomEffect effect = getEffect();
|
||||
return effect != null ? effect.getName() : "ID:" + effectId;
|
||||
})
|
||||
.clearable(() -> {
|
||||
effectId = -1;
|
||||
effectIndex = 0;
|
||||
}));
|
||||
defs.add(SubGuiCustomEffectSelect.createSelectField(this));
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@@ -74,7 +62,7 @@ public class ConditionHasEffect extends AbilityCondition {
|
||||
return effectId >= 0;
|
||||
}
|
||||
|
||||
private CustomEffect getEffect() {
|
||||
public CustomEffect getEffect() {
|
||||
HashMap<Integer, CustomEffect> map = CustomEffectController.getInstance().getEffectMap(effectIndex);
|
||||
return map != null ? map.get(effectId) : null;
|
||||
}
|
||||
|
||||
+1
-14
@@ -38,20 +38,7 @@ public class ConditionQuestCompleted extends AbilityCondition {
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void getConditionDefinitions(List<FieldDef> defs) {
|
||||
defs.add(FieldDef.subGuiField("condition.select_quest",
|
||||
() -> new GuiQuestSelection(questId),
|
||||
gui -> {
|
||||
GuiQuestSelection sel = (GuiQuestSelection) gui;
|
||||
if (sel.selectedQuest != null) {
|
||||
questId = sel.selectedQuest.id;
|
||||
}
|
||||
})
|
||||
.buttonLabel(() -> {
|
||||
if (questId < 0) return "None";
|
||||
Quest q = QuestController.Instance.quests.get(questId);
|
||||
return q != null ? q.title : "ID:" + questId;
|
||||
})
|
||||
.clearable(() -> questId = -1));
|
||||
defs.add(GuiQuestSelection.createConditionField(this));
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
|
||||
@@ -51,6 +51,16 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
|
||||
*/
|
||||
private int cooldownTicks = 100;
|
||||
|
||||
/**
|
||||
* If true, only this chain goes on cooldown (not the global cooldown).
|
||||
*/
|
||||
private boolean perAbilityCooldown = false;
|
||||
|
||||
/**
|
||||
* If true, skip cooldown entirely after chain completes.
|
||||
*/
|
||||
private boolean ignoreCooldown = false;
|
||||
|
||||
/**
|
||||
* Minimum range for NPC eligibility check.
|
||||
*/
|
||||
@@ -159,6 +169,22 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
|
||||
this.cooldownTicks = Math.max(0, cooldownTicks);
|
||||
}
|
||||
|
||||
public boolean isPerAbilityCooldown() {
|
||||
return perAbilityCooldown;
|
||||
}
|
||||
|
||||
public void setPerAbilityCooldown(boolean perAbilityCooldown) {
|
||||
this.perAbilityCooldown = perAbilityCooldown;
|
||||
}
|
||||
|
||||
public boolean isIgnoreCooldown() {
|
||||
return ignoreCooldown;
|
||||
}
|
||||
|
||||
public void setIgnoreCooldown(boolean ignoreCooldown) {
|
||||
this.ignoreCooldown = ignoreCooldown;
|
||||
}
|
||||
|
||||
public float getMinRange() {
|
||||
return minRange;
|
||||
}
|
||||
@@ -402,6 +428,8 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
|
||||
nbt.setInteger("Weight", weight);
|
||||
nbt.setBoolean("WindUpAll", windUpAll);
|
||||
nbt.setInteger("CooldownTicks", cooldownTicks);
|
||||
nbt.setBoolean("PerAbilityCooldown", perAbilityCooldown);
|
||||
nbt.setBoolean("IgnoreCooldown", ignoreCooldown);
|
||||
nbt.setFloat("MinRange", minRange);
|
||||
nbt.setFloat("MaxRange", maxRange);
|
||||
|
||||
@@ -443,6 +471,8 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
|
||||
weight = nbt.hasKey("Weight") ? nbt.getInteger("Weight") : 10;
|
||||
windUpAll = !nbt.hasKey("WindUpAll") || nbt.getBoolean("WindUpAll");
|
||||
cooldownTicks = nbt.hasKey("CooldownTicks") ? nbt.getInteger("CooldownTicks") : 100;
|
||||
perAbilityCooldown = nbt.getBoolean("PerAbilityCooldown");
|
||||
ignoreCooldown = nbt.getBoolean("IgnoreCooldown");
|
||||
minRange = nbt.getFloat("MinRange");
|
||||
maxRange = nbt.hasKey("MaxRange") ? nbt.getFloat("MaxRange") : 20;
|
||||
// AllowedBy is computed from child abilities
|
||||
|
||||
@@ -3,6 +3,7 @@ package kamkeel.npcs.controllers.data.ability.extender;
|
||||
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
|
||||
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
|
||||
import kamkeel.npcs.controllers.data.ability.Ability;
|
||||
import kamkeel.npcs.entity.EntityEnergyBarrier;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
|
||||
/**
|
||||
@@ -108,6 +109,13 @@ public interface IAbilityExtender {
|
||||
return baseHealth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify melee damage dealt to a barrier. Cumulative across all extenders.
|
||||
*/
|
||||
default float modifyBarrierMeleeDamage(EntityEnergyBarrier barrier, EntityLivingBase attacker, float baseDamage) {
|
||||
return baseDamage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when an ability is about to heal an entity.
|
||||
* Return true to handle the healing (skip default entity.heal()).
|
||||
|
||||
@@ -43,7 +43,7 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge {
|
||||
this.targetingMode = TargetingMode.AGGRO_TARGET;
|
||||
this.maxRange = 20.0f;
|
||||
this.minRange = 4.0f;
|
||||
this.lockMovement = LockMode.WINDUP;
|
||||
this.lockMovement = LockMode.WINDUP_AND_ACTIVE;
|
||||
this.cooldownTicks = 0;
|
||||
this.windUpTicks = 20;
|
||||
// LINE telegraph showing charge path
|
||||
@@ -58,6 +58,11 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge {
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasAbilityMovement() {
|
||||
return true; // This ability drives the NPC's motion itself
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTargetingModeLocked() {
|
||||
return true;
|
||||
|
||||
@@ -3,14 +3,21 @@ package kamkeel.npcs.controllers.data.ability.type;
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.addon.DBCAddon;
|
||||
import noppes.npcs.AbstractDataAbilities;
|
||||
import noppes.npcs.controllers.AnimationController;
|
||||
import kamkeel.npcs.controllers.data.ability.Ability;
|
||||
import kamkeel.npcs.controllers.data.ability.enums.UserType;
|
||||
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.util.DamageSource;
|
||||
import noppes.npcs.controllers.data.Animation;
|
||||
import noppes.npcs.controllers.data.PlayerData;
|
||||
import noppes.npcs.api.ability.type.IAbilityCounter;
|
||||
import noppes.npcs.client.gui.builder.FieldDef;
|
||||
import noppes.npcs.entity.EntityNPCInterface;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
@@ -25,6 +32,11 @@ public class AbilityCounter extends AbilityDefend implements IAbilityCounter {
|
||||
private int counterAnimationId = -1;
|
||||
private String counterAnimationName = "Ability_Guard_Counter";
|
||||
|
||||
// True only while this counter is synchronously dispatching its retaliation damage.
|
||||
// Another counter that is hit by that retaliation inspects this flag on the source
|
||||
// entity's active counter to avoid reacting and creating infinite mutual retaliation.
|
||||
private transient boolean retaliating;
|
||||
|
||||
public AbilityCounter() {
|
||||
this.typeId = "ability.cnpc.counter";
|
||||
this.name = "Counter";
|
||||
@@ -60,6 +72,35 @@ public class AbilityCounter extends AbilityDefend implements IAbilityCounter {
|
||||
// DEFEND HOOKS
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
@Override
|
||||
protected boolean isValidDamageSource(DamageSource source) {
|
||||
if (!super.isValidDamageSource(source)) {
|
||||
return false;
|
||||
}
|
||||
// Break counter-vs-counter recursion: if the hit is itself a retaliation
|
||||
// from another counter that is mid-dispatch, don't counter it back.
|
||||
Entity sourceEntity = source.getEntity();
|
||||
AbstractDataAbilities abilities = getAbilitiesOf(sourceEntity);
|
||||
if (abilities != null) {
|
||||
Ability current = abilities.getCurrentAbility();
|
||||
if (current instanceof AbilityCounter && ((AbilityCounter) current).retaliating) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static AbstractDataAbilities getAbilitiesOf(Entity entity) {
|
||||
if (entity instanceof EntityPlayer) {
|
||||
PlayerData pData = PlayerData.get((EntityPlayer) entity);
|
||||
return pData != null ? pData.abilityData : null;
|
||||
}
|
||||
if (entity instanceof EntityNPCInterface) {
|
||||
return ((EntityNPCInterface) entity).abilities;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected float performDefend(EntityLivingBase attacker, float amount) {
|
||||
// For PERCENT mode with DBC, use the full DBC-calculated damage, not vanilla base
|
||||
@@ -78,13 +119,24 @@ public class AbilityCounter extends AbilityDefend implements IAbilityCounter {
|
||||
|
||||
// Counter-attack through the standard ability damage pipeline.
|
||||
// DBCAbilityExtender handles DBC stat routing (ignore flags, scaling, etc.) automatically.
|
||||
if (caster != null && attacker.isEntityAlive() && damage > 0) {
|
||||
applyAbilityDamage(caster, attacker, damage, 0);
|
||||
if (caster != null && attacker != null && attacker.isEntityAlive() && damage > 0) {
|
||||
retaliating = true;
|
||||
try {
|
||||
applyAbilityDamage(caster, attacker, damage, 0);
|
||||
} finally {
|
||||
retaliating = false;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
super.reset();
|
||||
retaliating = false;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// OVERRIDES
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -10,9 +10,11 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.util.DamageSource;
|
||||
import noppes.npcs.EventHooks;
|
||||
import noppes.npcs.api.ability.type.IAbilityDefend;
|
||||
import noppes.npcs.client.gui.builder.FieldDef;
|
||||
import noppes.npcs.controllers.data.Animation;
|
||||
import noppes.npcs.scripted.event.AbilityEvent;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -72,6 +74,10 @@ public abstract class AbilityDefend extends Ability implements IAbilityDefend {
|
||||
hitCount = 0;
|
||||
lastAttacker = null;
|
||||
lastDamageTaken = 0.0f;
|
||||
pendingDefendAnimation = null;
|
||||
defendAnimEndTick = -1;
|
||||
lastDefendTick = -1;
|
||||
pendingCompletion = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -147,8 +153,14 @@ public abstract class AbilityDefend extends Ability implements IAbilityDefend {
|
||||
}
|
||||
}
|
||||
|
||||
//inject defend event
|
||||
AbilityEvent.DefendEvent event = new AbilityEvent.DefendEvent(caster, this, attacker, lastAttacker, amount);
|
||||
if (EventHooks.onAbilityDefend(this, event)) {
|
||||
return event.getDamage();
|
||||
}
|
||||
|
||||
// Always calculate the correct reduction for the caller's damage amount
|
||||
return performDefend(attacker, amount);
|
||||
return performDefend(attacker, event.getDamage());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -107,7 +107,7 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard {
|
||||
readZoneNBT(nbt, 300);
|
||||
this.radius = nbt.getFloat("radius");
|
||||
this.damagePerSecond = nbt.getFloat("damagePerSecond");
|
||||
this.damageInterval = nbt.getInteger("damageInterval");
|
||||
setDamageInterval(nbt.getInteger("damageInterval"));
|
||||
this.affectsCaster = nbt.getBoolean("affectsCaster");
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard {
|
||||
}
|
||||
|
||||
public void setDamageInterval(int damageInterval) {
|
||||
this.damageInterval = damageInterval;
|
||||
this.damageInterval = Math.max(EntityAbilityZone.MIN_DAMAGE_INTERVAL, damageInterval);
|
||||
}
|
||||
|
||||
public boolean isAffectsCaster() {
|
||||
@@ -171,6 +171,7 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard {
|
||||
FieldDef.row(
|
||||
FieldDef.floatField("gui.dps", this::getDamagePerSecond, this::setDamagePerSecond),
|
||||
FieldDef.intField("gui.interval", this::getDamageInterval, this::setDamageInterval)
|
||||
.range(EntityAbilityZone.MIN_DAMAGE_INTERVAL, 2000)
|
||||
),
|
||||
FieldDef.boolField("ability.affectsCaster", this::isAffectsCaster, this::setAffectsCaster)
|
||||
.hover("ability.hover.affectsCaster"),
|
||||
|
||||
@@ -97,6 +97,13 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile {
|
||||
dz /= len;
|
||||
}
|
||||
|
||||
if (isRotationLockedForCurrentPhase()) {
|
||||
Vec3 look = caster.getLookVec();
|
||||
if (look != null && (dx * look.xCoord + dy * look.yCoord + dz * look.zCoord) < 0.95) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
applyAbilityDamageWithDirection(caster, target, damage, knockback, dx, dz);
|
||||
world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f);
|
||||
|
||||
|
||||
@@ -300,14 +300,7 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap {
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
protected void addPresetFieldDef(List<FieldDef> defs) {
|
||||
defs.add(FieldDef.subGuiField("gui.applyPreset",
|
||||
SubGuiTrapPresetSelector::new,
|
||||
gui -> {
|
||||
SubGuiTrapPresetSelector selector = (SubGuiTrapPresetSelector) gui;
|
||||
if (selector.selectedPreset != null) {
|
||||
applyTrapPresetDefaults(selector.selectedPreset);
|
||||
}
|
||||
}));
|
||||
defs.add(SubGuiTrapPresetSelector.createPresetField(this::applyTrapPresetDefaults));
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
|
||||
@@ -690,14 +690,7 @@ public abstract class AbilityZone extends Ability {
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
protected void addPresetFieldDef(List<FieldDef> defs) {
|
||||
defs.add(FieldDef.subGuiField("gui.applyPreset",
|
||||
SubGuiZonePresetSelector::new,
|
||||
gui -> {
|
||||
SubGuiZonePresetSelector selector = (SubGuiZonePresetSelector) gui;
|
||||
if (selector.selectedPreset != null) {
|
||||
applyPresetDefaults(selector.selectedPreset);
|
||||
}
|
||||
}));
|
||||
defs.add(SubGuiZonePresetSelector.createPresetField(this::applyPresetDefaults));
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
|
||||
+3
-1
@@ -248,7 +248,9 @@ public abstract class AbilityEnergyProjectile<E extends EntityEnergyProjectile>
|
||||
* NPCs use their resolved target so launch math can track the target immediately.
|
||||
*/
|
||||
protected EntityLivingBase getLaunchTarget(EntityLivingBase caster, EntityLivingBase target) {
|
||||
return isPlayerCaster(caster) ? null : target;
|
||||
if (isPlayerCaster(caster)) return null;
|
||||
if (isRotationLockedForCurrentPhase()) return null;
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package kamkeel.npcs.controllers.data.profile;
|
||||
|
||||
import kamkeel.npcs.controllers.SyncController;
|
||||
import kamkeel.npcs.controllers.sync.handlers.PlayerDataSyncHandler;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
@@ -30,7 +30,7 @@ public class CNPCData implements IProfileData {
|
||||
public void save(EntityPlayer player) {
|
||||
PlayerData customNPCData = PlayerData.get(player);
|
||||
customNPCData.save();
|
||||
SyncController.syncPlayerData((EntityPlayerMP) player, false);
|
||||
PlayerDataSyncHandler.syncPlayerData((EntityPlayerMP) player, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package kamkeel.npcs.controllers.sync;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Contract for a synchronized data type. Implementors handle both
|
||||
* server-side serialization and client-side deserialization for their
|
||||
* specific data type.
|
||||
*
|
||||
* <p>Each handler is registered with {@link SyncRegistry} and covers
|
||||
* all three sync actions: RELOAD (full), UPDATE (single entity),
|
||||
* and REMOVE (delete entity).</p>
|
||||
*
|
||||
* <p>Handlers that don't support UPDATE or REMOVE should use the
|
||||
* default no-op implementations.</p>
|
||||
*/
|
||||
public interface SyncHandler {
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
/**
|
||||
* Serialize ALL objects of this type into an NBTTagCompound.
|
||||
* This is the supplier for the cache system.
|
||||
*
|
||||
* <p>Called lazily when the cache is dirty and a player needs data.
|
||||
* The returned compound is cached and chunked for transmission.</p>
|
||||
*
|
||||
* @return the serialized compound, or null if this type has no independent cache
|
||||
*/
|
||||
NBTTagCompound serializeAll();
|
||||
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
/**
|
||||
* Handle a RELOAD action on the client. Deserialize the full
|
||||
* dataset and replace the client-side data.
|
||||
*
|
||||
* <p>Implementations should:
|
||||
* <ol>
|
||||
* <li>Deserialize from the compound into a sync buffer</li>
|
||||
* <li>Atomically swap the sync buffer to the primary map</li>
|
||||
* <li>Reset the sync buffer for the next reload</li>
|
||||
* </ol>
|
||||
*
|
||||
* @param fullCompound the full serialized dataset from {@link #serializeAll()}
|
||||
*/
|
||||
@SideOnly(Side.CLIENT)
|
||||
default void clientHandleReload(NBTTagCompound fullCompound){
|
||||
// No-op: type does not support individual updates
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an UPDATE action on the client.
|
||||
* Deserialize a single object and insert/replace it in the client-side data.
|
||||
*
|
||||
* <p>Default: no-op. Types that don't support individual updates
|
||||
* use {@code syncAll()} for full reload instead.</p>
|
||||
*
|
||||
* @param compound the serialized single object
|
||||
*/
|
||||
@SideOnly(Side.CLIENT)
|
||||
default void clientHandleUpdate(NBTTagCompound compound) {
|
||||
// No-op: type does not support individual updates
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an UPDATE action on the client.
|
||||
* Deserialize a single object and insert/replace it in the client-side data.
|
||||
*
|
||||
* <p>Default: no-op. Types that don't support individual updates
|
||||
* use {@code syncAll()} for full reload instead.</p>
|
||||
*
|
||||
* @param compound the serialized single object
|
||||
* @param categoryKey the parent category key (null if not applicable)
|
||||
*/
|
||||
@SideOnly(Side.CLIENT)
|
||||
default void clientHandleUpdate(NBTTagCompound compound, String categoryKey) {
|
||||
// No-op: type does not support individual updates
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handle an UPDATE action on the client. Deserialize a single
|
||||
* entity and insert/replace it in the client-side data.
|
||||
*
|
||||
* <p>Default: no-op. Types that don't support individual updates
|
||||
* use {@code syncAll()} for full reload instead.</p>
|
||||
*
|
||||
* @param compound the serialized single entity
|
||||
* @param categoryId the parent category ID (-1 if not applicable)
|
||||
*/
|
||||
@SideOnly(Side.CLIENT)
|
||||
default void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
|
||||
// No-op: type does not support individual updates
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a single object from client-side data.
|
||||
* Full object NBTTagCompound sent finer query control
|
||||
* Int-keyed handlers should override {@link #clientHandleRemove(int)} instead.
|
||||
*/
|
||||
@SideOnly(Side.CLIENT)
|
||||
default void clientHandleRemove(String key) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a single object with the given ID from client-side data.
|
||||
*
|
||||
* @param id the ID of the object to remove
|
||||
*/
|
||||
@SideOnly(Side.CLIENT)
|
||||
default void clientHandleRemove(int id) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this handler supports the UPDATE action.
|
||||
* Used for validation and self-documentation.
|
||||
*/
|
||||
default boolean supportsUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this handler supports the REMOVE action.
|
||||
* Used for validation and self-documentation.
|
||||
*/
|
||||
default boolean supportsRemove() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this type should be included in login sync.
|
||||
* Types that return true will be sent to players on login
|
||||
* and checked for revision deltas on reconnect.
|
||||
*
|
||||
* <p>Default: true. Override to false for types like PLAYERDATA
|
||||
* that are synced through separate mechanisms, or child types
|
||||
* (DIALOG, QUEST) that share their parent's cache.</p>
|
||||
*/
|
||||
default boolean isCachedType() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the set of cache types that must be invalidated when
|
||||
* this type changes. Used for cascade invalidation.
|
||||
*
|
||||
* <p>Most types return just themselves. Parent-child types
|
||||
* (e.g. DIALOG maps to DIALOG_CATEGORY) point children
|
||||
* to the parent's cache.</p>
|
||||
*
|
||||
* @param self the SyncType this handler is registered under
|
||||
* @return the set of types to invalidate
|
||||
*/
|
||||
default Set<SyncType> getInvalidationTargets(SyncType self) {
|
||||
Set<SyncType> set = new HashSet<>();
|
||||
set.add(self);
|
||||
return set;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package kamkeel.npcs.controllers.sync;
|
||||
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import noppes.npcs.LogWriter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public final class SyncRegistry {
|
||||
|
||||
private static final LinkedHashMap<SyncType, SyncHandler> handlers = new LinkedHashMap<>();
|
||||
|
||||
private static SyncType[] loginTypesCache = null;
|
||||
|
||||
private SyncRegistry() {}
|
||||
|
||||
public static void register(SyncType type, SyncHandler handler) {
|
||||
if (type == null) throw new IllegalArgumentException("SyncType must not be null");
|
||||
if (handler == null) throw new IllegalArgumentException("SyncHandler must not be null for " + type);
|
||||
if (handlers.containsKey(type)) throw new IllegalStateException("SyncHandler already registered for " + type);
|
||||
|
||||
handlers.put(type, handler);
|
||||
loginTypesCache = null;
|
||||
}
|
||||
|
||||
public static SyncHandler getHandler(SyncType type) {
|
||||
return handlers.get(type);
|
||||
}
|
||||
|
||||
public static SyncType[] getLoginTypes() {
|
||||
if (loginTypesCache == null) {
|
||||
List<SyncType> list = new ArrayList<>();
|
||||
for (Map.Entry<SyncType, SyncHandler> e : handlers.entrySet())
|
||||
if (e.getValue().isCachedType())
|
||||
list.add(e.getKey());
|
||||
|
||||
loginTypesCache = list.toArray(new SyncType[0]);
|
||||
}
|
||||
return loginTypesCache;
|
||||
}
|
||||
|
||||
public static Set<SyncType> getInvalidationTargets(SyncType type) {
|
||||
SyncHandler handler = handlers.get(type);
|
||||
if (handler == null) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return handler.getInvalidationTargets(type);
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
handlers.clear();
|
||||
loginTypesCache = null;
|
||||
}
|
||||
|
||||
|
||||
public static boolean isRegistered(SyncType type) {
|
||||
return handlers.containsKey(type);
|
||||
}
|
||||
|
||||
public static Collection<SyncType> getRegisteredTypes() {
|
||||
return Collections.unmodifiableCollection(handlers.keySet());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.controllers.RecipeController;
|
||||
import noppes.npcs.controllers.data.RecipeAnvil;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#ANVIL_RECIPES}.
|
||||
* RELOAD-only family — does not support individual UPDATE or REMOVE.
|
||||
*/
|
||||
public class AnvilRecipeSyncHandler implements SyncHandler {
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
RecipeController controller = RecipeController.Instance;
|
||||
NBTTagList list = new NBTTagList();
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
for (RecipeAnvil recipe : controller.anvilRecipes.values()) {
|
||||
list.appendTag(recipe.writeNBT(false));
|
||||
}
|
||||
compound.setTag("recipes", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
NBTTagList list = fullCompound.getTagList("recipes", 10);
|
||||
if (list == null)
|
||||
return;
|
||||
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
RecipeAnvil recipe = new RecipeAnvil();
|
||||
recipe.readNBT(list.getCompoundTagAt(i));
|
||||
RecipeController.syncAnvilRecipes.put(recipe.id, recipe);
|
||||
}
|
||||
|
||||
RecipeController.Instance.anvilRecipes = RecipeController.syncAnvilRecipes;
|
||||
RecipeController.syncAnvilRecipes = new HashMap<>();
|
||||
}
|
||||
|
||||
// RELOAD-only: supportsUpdate() and supportsRemove() remain false (default)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.controllers.RecipeController;
|
||||
import noppes.npcs.controllers.data.RecipeCarpentry;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#CARPENTRY_RECIPES}.
|
||||
* RELOAD-only family — does not support individual UPDATE or REMOVE.
|
||||
*/
|
||||
public class CarpentryRecipeSyncHandler implements SyncHandler {
|
||||
|
||||
private static final CarpentryRecipeSyncHandler INSTANCE = new CarpentryRecipeSyncHandler();
|
||||
|
||||
public static CarpentryRecipeSyncHandler getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
RecipeController controller = RecipeController.Instance;
|
||||
NBTTagList list = new NBTTagList();
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
for (RecipeCarpentry recipe : controller.carpentryRecipes.values()) {
|
||||
list.appendTag(recipe.writeNBT(false));
|
||||
}
|
||||
compound.setTag("recipes", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
NBTTagList list = fullCompound.getTagList("recipes", 10);
|
||||
if (list == null)
|
||||
return;
|
||||
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
NBTTagCompound recipeCompound = list.getCompoundTagAt(i);
|
||||
RecipeCarpentry recipe = RecipeCarpentry.create(recipeCompound);
|
||||
recipe.readNBT(recipeCompound);
|
||||
RecipeController.syncRecipes.put(recipe.id, recipe);
|
||||
}
|
||||
|
||||
RecipeController.Instance.carpentryRecipes = RecipeController.syncRecipes;
|
||||
RecipeController.syncRecipes = new HashMap<>();
|
||||
}
|
||||
|
||||
// RELOAD-only: supportsUpdate() and supportsRemove() remain false (default)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.AbilityController;
|
||||
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#CHAINED_ABILITY}.
|
||||
* String-keyed family using ordered {@link LinkedHashMap} to preserve
|
||||
* registration/reload order. Supports RELOAD only for global sync.
|
||||
*/
|
||||
public class ChainedAbilitySyncHandler implements SyncHandler {
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
NBTTagList list = new NBTTagList();
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
for (Map.Entry<String, ChainedAbility> entry : AbilityController.Instance.getChainedAbilities().entrySet()) {
|
||||
NBTTagCompound chainNBT = entry.getValue().writeNBT(false);
|
||||
chainNBT.setString("ChainedAbilityId", entry.getKey());
|
||||
list.appendTag(chainNBT);
|
||||
}
|
||||
compound.setTag("Data", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
NBTTagList list = fullCompound.getTagList("Data", 10);
|
||||
LinkedHashMap<String, ChainedAbility> sync = new LinkedHashMap<>();
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
NBTTagCompound nbt = list.getCompoundTagAt(i);
|
||||
String id = nbt.getString("ChainedAbilityId");
|
||||
ChainedAbility chain = new ChainedAbility();
|
||||
chain.readNBT(nbt);
|
||||
chain.setName(id);
|
||||
sync.put(id, chain);
|
||||
}
|
||||
AbilityController.Instance.setChainedAbilities(sync);
|
||||
}
|
||||
|
||||
// RELOAD-only for global sync: supportsUpdate() and supportsRemove() remain false (default)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.AbilityController;
|
||||
import kamkeel.npcs.controllers.data.ability.Ability;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#CUSTOM_ABILITY}.
|
||||
* String-keyed family using ordered {@link LinkedHashMap} to preserve
|
||||
* registration/reload order. Supports RELOAD only for global sync.
|
||||
*/
|
||||
public class CustomAbilitySyncHandler implements SyncHandler {
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
NBTTagList list = new NBTTagList();
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
for (Map.Entry<String, Ability> entry : AbilityController.Instance.getCustomAbilities().entrySet()) {
|
||||
NBTTagCompound abilityNBT = entry.getValue().writeNBT(false);
|
||||
abilityNBT.setString("CustomAbilityId", entry.getKey());
|
||||
list.appendTag(abilityNBT);
|
||||
}
|
||||
compound.setTag("Data", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
NBTTagList list = fullCompound.getTagList("Data", 10);
|
||||
LinkedHashMap<String, Ability> sync = new LinkedHashMap<>();
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
NBTTagCompound nbt = list.getCompoundTagAt(i);
|
||||
String name = nbt.getString("CustomAbilityId");
|
||||
Ability ability = AbilityController.Instance.fromNBT(nbt);
|
||||
if (ability != null) {
|
||||
ability.setName(name);
|
||||
sync.put(name, ability);
|
||||
}
|
||||
}
|
||||
AbilityController.Instance.setCustomAbilities(sync);
|
||||
}
|
||||
|
||||
// RELOAD-only for global sync: supportsUpdate() and supportsRemove() remain false (default)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.client.ClientCacheHandler;
|
||||
import noppes.npcs.controllers.CustomEffectController;
|
||||
import noppes.npcs.controllers.data.CustomEffect;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#CUSTOM_EFFECTS}.
|
||||
* Simple int-keyed map family with RELOAD, UPDATE, and REMOVE support.
|
||||
* Client-side RELOAD precaches effect icons via {@link ClientCacheHandler#getImageData}.
|
||||
*/
|
||||
public class CustomEffectSyncHandler implements SyncHandler {
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
NBTTagList list = new NBTTagList();
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
for (CustomEffect effect : CustomEffectController.getInstance().getCustomEffects().values()) {
|
||||
list.appendTag(effect.writeToNBT(false));
|
||||
}
|
||||
compound.setTag("Data", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
NBTTagList list = fullCompound.getTagList("Data", 10);
|
||||
CustomEffectController ce = CustomEffectController.getInstance();
|
||||
ce.customEffectsSync.clear();
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
CustomEffect effect = new CustomEffect();
|
||||
effect.readFromNBT(list.getCompoundTagAt(i));
|
||||
ClientCacheHandler.getImageData(effect.icon);
|
||||
ce.customEffectsSync.put(effect.id, effect);
|
||||
}
|
||||
|
||||
ce.getCustomEffects().clear();
|
||||
ce.getCustomEffects().putAll(ce.customEffectsSync);
|
||||
ce.customEffectsSync.clear();
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
|
||||
CustomEffect effect = new CustomEffect();
|
||||
effect.readFromNBT(compound);
|
||||
ClientCacheHandler.getImageData(effect.icon);
|
||||
|
||||
CustomEffectController.Instance.getCustomEffects().put(effect.id, effect);
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleRemove(int id) {
|
||||
CustomEffectController.Instance.getCustomEffects().remove(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsRemove() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.controllers.DialogController;
|
||||
import noppes.npcs.controllers.data.Dialog;
|
||||
import noppes.npcs.controllers.data.DialogCategory;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#DIALOG_CATEGORY}.
|
||||
* Parent-child category family. DIALOG children share this cache.
|
||||
* Invalidation from DIALOG or DIALOG_CATEGORY both target this cache.
|
||||
*/
|
||||
public class DialogCategorySyncHandler implements SyncHandler {
|
||||
|
||||
/**
|
||||
* Serialize a single dialog category for UPDATE packets.
|
||||
*/
|
||||
public static NBTTagCompound serializeCategory(DialogCategory dialogCategory) {
|
||||
NBTTagCompound dialogCompound = new NBTTagCompound();
|
||||
NBTTagList dialogList = new NBTTagList();
|
||||
for (int questID : dialogCategory.dialogs.keySet()) {
|
||||
Dialog dialog = dialogCategory.dialogs.get(questID);
|
||||
dialogList.appendTag(dialog.writeToNBT(new NBTTagCompound()));
|
||||
}
|
||||
dialogCompound.setTag("Data", dialogList);
|
||||
dialogCompound.setTag("CatNBT", dialogCategory.writeSmallNBT(new NBTTagCompound()));
|
||||
return dialogCompound;
|
||||
}
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
NBTTagList categoryList = new NBTTagList();
|
||||
for (DialogCategory category : DialogController.Instance.categories.values()) {
|
||||
NBTTagCompound questCompound = new NBTTagCompound();
|
||||
NBTTagList dialogList = new NBTTagList();
|
||||
for (int dialogID : category.dialogs.keySet()) {
|
||||
Dialog quest = category.dialogs.get(dialogID);
|
||||
dialogList.appendTag(quest.writeToNBT(new NBTTagCompound()));
|
||||
}
|
||||
questCompound.setTag("Data", dialogList);
|
||||
questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound()));
|
||||
categoryList.appendTag(questCompound);
|
||||
}
|
||||
compound.setTag("DialogCategories", categoryList);
|
||||
return compound;
|
||||
}
|
||||
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
if (!fullCompound.hasNoTags()) {
|
||||
NBTTagList categories = fullCompound.getTagList("DialogCategories", 10);
|
||||
for (int j = 0; j < fullCompound.getTagList("DialogCategories", 10).tagCount(); j++) {
|
||||
NBTTagCompound categoryCompound = categories.getCompoundTagAt(j);
|
||||
if (categoryCompound.hasNoTags())
|
||||
continue;
|
||||
|
||||
DialogCategory category = new DialogCategory();
|
||||
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
|
||||
NBTTagList dialogList = categoryCompound.getTagList("Data", 10);
|
||||
if (DialogController.Instance.categoriesSync.containsKey(category.id)) {
|
||||
category = DialogController.Instance.categoriesSync.get(category.id);
|
||||
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
|
||||
}
|
||||
for (int i = 0; i < dialogList.tagCount(); i++) {
|
||||
Dialog dialog = new Dialog();
|
||||
dialog.readNBT(dialogList.getCompoundTagAt(i));
|
||||
dialog.category = category;
|
||||
category.dialogs.put(dialog.id, dialog);
|
||||
}
|
||||
DialogController.Instance.categoriesSync.put(category.id, category);
|
||||
}
|
||||
}
|
||||
|
||||
HashMap<Integer, Dialog> dialogs = new HashMap<>();
|
||||
for (DialogCategory category : DialogController.Instance.categoriesSync.values()) {
|
||||
for (Dialog dialog : category.dialogs.values()) {
|
||||
dialogs.put(dialog.id, dialog);
|
||||
}
|
||||
}
|
||||
|
||||
DialogController.Instance.categories = DialogController.Instance.categoriesSync;
|
||||
DialogController.Instance.dialogs = dialogs;
|
||||
DialogController.Instance.categoriesSync = new HashMap<>();
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
|
||||
DialogCategory category = new DialogCategory();
|
||||
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
|
||||
NBTTagList list = compound.getTagList("Data", 10);
|
||||
if (DialogController.Instance.categoriesSync.containsKey(category.id)) {
|
||||
category = DialogController.Instance.categoriesSync.get(category.id);
|
||||
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
|
||||
}
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
Dialog dialog = new Dialog();
|
||||
dialog.readNBT(list.getCompoundTagAt(i));
|
||||
dialog.category = category;
|
||||
category.dialogs.put(dialog.id, dialog);
|
||||
}
|
||||
DialogController.Instance.categories.put(category.id, category);
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleRemove(int id) {
|
||||
DialogCategory dialogCategory = DialogController.Instance.categories.remove(id);
|
||||
if (dialogCategory != null) {
|
||||
DialogController.Instance.dialogs.keySet().removeAll(dialogCategory.dialogs.keySet());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsRemove() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.controllers.DialogController;
|
||||
import noppes.npcs.controllers.data.Dialog;
|
||||
import noppes.npcs.controllers.data.DialogCategory;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#DIALOG}.
|
||||
* Child family — does not have its own cache. UPDATE and REMOVE only.
|
||||
* Invalidation targets the parent {@link SyncType#DIALOG_CATEGORY} cache.
|
||||
*/
|
||||
public class DialogSyncHandler implements SyncHandler {
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
/**
|
||||
* DIALOG does not have its own independent cache; it shares
|
||||
* the DIALOG_CATEGORY parent cache.
|
||||
*/
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
// DIALOG does not handle standalone RELOAD; it's part of DIALOG_CATEGORY
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
|
||||
DialogCategory category = DialogController.Instance.categories.get(categoryId);
|
||||
if (category == null) {
|
||||
return; // Defensive: category may have been removed
|
||||
}
|
||||
Dialog dialog = new Dialog();
|
||||
dialog.category = category;
|
||||
dialog.readNBT(compound);
|
||||
DialogController.Instance.dialogs.put(dialog.id, dialog);
|
||||
category.dialogs.put(dialog.id, dialog);
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleRemove(int id) {
|
||||
Dialog dialog = DialogController.Instance.dialogs.remove(id);
|
||||
if (dialog != null) {
|
||||
dialog.category.dialogs.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsRemove() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Not a cached type — DIALOG shares the DIALOG_CATEGORY cache.
|
||||
*/
|
||||
@Override
|
||||
public boolean isCachedType() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SyncType> getInvalidationTargets(SyncType self) {
|
||||
// Child invalidates the parent cache
|
||||
Set<SyncType> set = new HashSet<>();
|
||||
set.add(SyncType.DIALOG_CATEGORY);
|
||||
return set;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.controllers.FactionController;
|
||||
import noppes.npcs.controllers.data.Faction;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#FACTION}.
|
||||
* Simple int-keyed map family with RELOAD, UPDATE, and REMOVE support.
|
||||
*/
|
||||
public class FactionSyncHandler implements SyncHandler {
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
NBTTagList list = new NBTTagList();
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
for (Faction faction : FactionController.getInstance().factions.values()) {
|
||||
NBTTagCompound factionNBT = new NBTTagCompound();
|
||||
faction.writeNBT(factionNBT);
|
||||
list.appendTag(factionNBT);
|
||||
}
|
||||
compound.setTag("Factions", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
NBTTagList list = fullCompound.getTagList("Factions", 10);
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
Faction faction = new Faction();
|
||||
faction.readNBT(list.getCompoundTagAt(i));
|
||||
FactionController.getInstance().factionsSync.put(faction.id, faction);
|
||||
}
|
||||
FactionController.getInstance().factions = FactionController.getInstance().factionsSync;
|
||||
FactionController.getInstance().factionsSync = new HashMap<Integer, Faction>();
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
|
||||
Faction faction = new Faction();
|
||||
faction.readNBT(compound);
|
||||
FactionController.getInstance().factions.put(faction.id, faction);
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleRemove(int id) {
|
||||
FactionController.getInstance().factions.remove(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsRemove() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.controllers.MagicController;
|
||||
import noppes.npcs.controllers.data.MagicCycle;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#MAGIC_CYCLE}.
|
||||
* Simple int-keyed map family with RELOAD, UPDATE, and REMOVE support.
|
||||
*/
|
||||
public class MagicCycleSyncHandler implements SyncHandler {
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
NBTTagList list = new NBTTagList();
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
for (MagicCycle cycle : MagicController.getInstance().cycles.values()) {
|
||||
NBTTagCompound cycleCompound = new NBTTagCompound();
|
||||
cycle.writeNBT(cycleCompound);
|
||||
list.appendTag(cycleCompound);
|
||||
}
|
||||
compound.setTag("Data", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
NBTTagList list = fullCompound.getTagList("Data", 10);
|
||||
MagicController mc = MagicController.getInstance();
|
||||
mc.cyclesSync.clear();
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
MagicCycle cycle = new MagicCycle();
|
||||
cycle.readNBT(list.getCompoundTagAt(i));
|
||||
mc.cyclesSync.put(cycle.id, cycle);
|
||||
}
|
||||
|
||||
mc.cycles.clear();
|
||||
mc.cycles.putAll(mc.cyclesSync);
|
||||
mc.cyclesSync.clear();
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
|
||||
MagicCycle cycle = new MagicCycle();
|
||||
cycle.readNBT(compound);
|
||||
MagicController.getInstance().cycles.put(cycle.id, cycle);
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleRemove(int id) {
|
||||
MagicController.getInstance().cycles.remove(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsRemove() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.controllers.MagicController;
|
||||
import noppes.npcs.controllers.data.Magic;
|
||||
import noppes.npcs.controllers.data.MagicCycle;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#MAGIC}.
|
||||
* Simple int-keyed map family.
|
||||
* REMOVE dissociates cycle associations before removing the magic entry.
|
||||
*
|
||||
* <p>Note: The original code had a bug where MAGIC REMOVE incorrectly
|
||||
* removed from {@code cycles} instead of {@code magics}. This handler
|
||||
* fixes that by properly removing from {@code magics} after dissociating.</p>
|
||||
*/
|
||||
public class MagicSyncHandler implements SyncHandler {
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
NBTTagList list = new NBTTagList();
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
for (Magic magic : MagicController.getInstance().magics.values()) {
|
||||
NBTTagCompound magicCompound = new NBTTagCompound();
|
||||
magic.writeNBT(magicCompound);
|
||||
list.appendTag(magicCompound);
|
||||
}
|
||||
compound.setTag("Data", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
NBTTagList list = fullCompound.getTagList("Data", 10);
|
||||
MagicController mc = MagicController.getInstance();
|
||||
mc.magicSync.clear();
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
Magic magic = new Magic();
|
||||
magic.readNBT(list.getCompoundTagAt(i));
|
||||
mc.magicSync.put(magic.id, magic);
|
||||
}
|
||||
|
||||
mc.magics.clear();
|
||||
mc.magics.putAll(mc.magicSync);
|
||||
mc.magicSync.clear();
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
|
||||
Magic magic = new Magic();
|
||||
magic.readNBT(compound);
|
||||
MagicController.getInstance().magics.put(magic.id, magic);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a magic entry from the client. First dissociates cycle
|
||||
* references, then removes from the magics map.
|
||||
* <p>Bug fix: The original code incorrectly removed from {@code cycles}
|
||||
* instead of {@code magics} after dissociating cycle associations.</p>
|
||||
*/
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleRemove(int id) {
|
||||
// First remove this magic's association from all cycles
|
||||
for (MagicCycle cycle : MagicController.getInstance().cycles.values()) {
|
||||
cycle.associations.remove(id);
|
||||
}
|
||||
// Then remove the magic itself (fixed: was cycles.remove(id))
|
||||
MagicController.getInstance().magics.remove(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsRemove() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket;
|
||||
import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket;
|
||||
import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import noppes.npcs.controllers.data.PlayerData;
|
||||
|
||||
/**
|
||||
* Direct per-player sync helper for player ability state.
|
||||
* This is NOT a cached global sync family — it operates outside the
|
||||
* registry-driven reload/revision system.
|
||||
*
|
||||
* <p>Abilities are synced per-player on demand (e.g. ability unlock,
|
||||
* entity reconstruction, periodic cooldown ticks).</p>
|
||||
*/
|
||||
public final class PlayerAbilitySyncHelper {
|
||||
|
||||
private PlayerAbilitySyncHelper() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Full sync of all player ability state to the client: unlocked abilities,
|
||||
* selection, toggles, hotbar layout, and cooldowns.
|
||||
* Used for entity reconstruction and other full-refresh scenarios.
|
||||
*/
|
||||
public static void syncAbilities(EntityPlayerMP playerMP) {
|
||||
PlayerData playerData = PlayerData.get(playerMP);
|
||||
if (playerData == null) return;
|
||||
|
||||
PlayerAbilitySyncPacket.sendToPlayer(playerMP);
|
||||
AbilityHotbarSyncPacket.sendToPlayer(playerMP);
|
||||
AbilityCooldownSyncPacket.sendToPlayer(playerMP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight sync of cooldown state only (global + per-ability).
|
||||
* Called periodically (every 10 ticks) to keep the client's cooldown
|
||||
* display accurate. Cooldowns are transient and not part of NBT sync.
|
||||
*/
|
||||
public static void syncAbilityCooldowns(EntityPlayerMP playerMP) {
|
||||
PlayerData playerData = PlayerData.get(playerMP);
|
||||
if (playerData == null) return;
|
||||
|
||||
AbilityCooldownSyncPacket.sendToPlayer(playerMP);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.SyncController;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.client.ClientCacheHandler;
|
||||
import noppes.npcs.controllers.data.PlayerData;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#PLAYERDATA}.
|
||||
* Special non-cached per-player path. Not included in login cache iteration.
|
||||
* RELOAD and UPDATE are sent as direct per-player packets.
|
||||
*/
|
||||
public class PlayerDataSyncHandler implements SyncHandler {
|
||||
|
||||
public static void syncPlayerData(EntityPlayerMP player, boolean update) {
|
||||
PlayerData data = PlayerData.get(player);
|
||||
if (data != null)
|
||||
SyncController.syncPlayerData(SyncType.PLAYERDATA, update ? data.getSyncNBTFull() : data.getSyncNBT(), update, player);
|
||||
}
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
/**
|
||||
* PLAYERDATA is not a global cached type — it is per-player.
|
||||
*/
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
|
||||
if (categoryId == 1) ClientCacheHandler.playerData.setSyncNBTFull(compound);
|
||||
else ClientCacheHandler.playerData.setSyncNBT(compound);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Not a cached type — PLAYERDATA uses direct per-player sync.
|
||||
*/
|
||||
@Override
|
||||
public boolean isCachedType() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.network.PacketHandler;
|
||||
import kamkeel.npcs.network.packets.data.large.SyncEffectPacket;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.controllers.CustomEffectController;
|
||||
import noppes.npcs.controllers.data.EffectKey;
|
||||
import noppes.npcs.controllers.data.PlayerData;
|
||||
import noppes.npcs.controllers.data.PlayerEffect;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Direct per-player sync helper for player effects.
|
||||
* This is NOT a cached global sync family — it operates outside the
|
||||
* registry-driven reload/revision system.
|
||||
*
|
||||
* <p>Effects are synced per-player on demand (e.g. effect application,
|
||||
* periodic ticks). The data mutates {@code playerData.effectData}
|
||||
* before sending the packet.</p>
|
||||
*/
|
||||
public final class PlayerEffectSyncHelper {
|
||||
|
||||
private PlayerEffectSyncHelper() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-side: sync the player's active effects to their client.
|
||||
* Mutates {@code playerData.effectData} before sending.
|
||||
*/
|
||||
public static void syncEffects(EntityPlayerMP playerMP) {
|
||||
ConcurrentHashMap<EffectKey, PlayerEffect> playerEffects = CustomEffectController.getInstance().getPlayerEffects(playerMP);
|
||||
PlayerData playerData = PlayerData.get(playerMP);
|
||||
playerData.effectData.setEffects(playerEffects);
|
||||
|
||||
NBTTagCompound compound = playerData.getPlayerEffects();
|
||||
PacketHandler.Instance.sendToPlayer(new SyncEffectPacket(compound), playerMP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Client-side: apply incoming effect data to the local player.
|
||||
*/
|
||||
@SideOnly(Side.CLIENT)
|
||||
public static void clientSyncEffects(NBTTagCompound compound) {
|
||||
PlayerData playerData = PlayerData.get(Minecraft.getMinecraft().thePlayer);
|
||||
if (playerData != null) {
|
||||
playerData.setPlayerEffects(compound);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.controllers.QuestController;
|
||||
import noppes.npcs.controllers.data.Quest;
|
||||
import noppes.npcs.controllers.data.QuestCategory;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#QUEST_CATEGORY}.
|
||||
* Parent-child category family. QUEST children share this cache.
|
||||
* Invalidation from QUEST or QUEST_CATEGORY both target this cache.
|
||||
*/
|
||||
public class QuestCategorySyncHandler implements SyncHandler {
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
NBTTagList categoryList = new NBTTagList();
|
||||
for (QuestCategory category : QuestController.Instance.categories.values()) {
|
||||
NBTTagCompound questCompound = new NBTTagCompound();
|
||||
;
|
||||
NBTTagList questList = new NBTTagList();
|
||||
for (int questID : category.quests.keySet()) {
|
||||
Quest quest = category.quests.get(questID);
|
||||
questList.appendTag(quest.writeToNBT(new NBTTagCompound()));
|
||||
}
|
||||
questCompound.setTag("Data", questList);
|
||||
questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound()));
|
||||
categoryList.appendTag(questCompound);
|
||||
}
|
||||
compound.setTag("QuestCategories", categoryList);
|
||||
return compound;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize a single quest category for UPDATE packets.
|
||||
*/
|
||||
public static NBTTagCompound serializeCategory(QuestCategory questCategory) {
|
||||
NBTTagCompound questCompound = new NBTTagCompound();
|
||||
NBTTagList questList = new NBTTagList();
|
||||
for (int questID : questCategory.quests.keySet()) {
|
||||
Quest quest = questCategory.quests.get(questID);
|
||||
questList.appendTag(quest.writeToNBT(new NBTTagCompound()));
|
||||
}
|
||||
questCompound.setTag("Data", questList);
|
||||
questCompound.setTag("CatNBT", questCategory.writeSmallNBT(new NBTTagCompound()));
|
||||
return questCompound;
|
||||
}
|
||||
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
if (!fullCompound.hasNoTags()) {
|
||||
NBTTagList categories = fullCompound.getTagList("QuestCategories", 10);
|
||||
for (int j = 0; j < fullCompound.getTagList("QuestCategories", 10).tagCount(); j++) {
|
||||
NBTTagCompound categoryCompound = categories.getCompoundTagAt(j);
|
||||
if (categoryCompound.hasNoTags())
|
||||
continue;
|
||||
|
||||
QuestCategory category = new QuestCategory();
|
||||
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
|
||||
NBTTagList questList = categoryCompound.getTagList("Data", 10);
|
||||
if (QuestController.Instance.categoriesSync.containsKey(category.id)) {
|
||||
category = QuestController.Instance.categoriesSync.get(category.id);
|
||||
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
|
||||
}
|
||||
for (int i = 0; i < questList.tagCount(); i++) {
|
||||
Quest quest = new Quest();
|
||||
quest.readNBT(questList.getCompoundTagAt(i));
|
||||
quest.category = category;
|
||||
category.quests.put(quest.id, quest);
|
||||
}
|
||||
QuestController.Instance.categoriesSync.put(category.id, category);
|
||||
}
|
||||
}
|
||||
|
||||
HashMap<Integer, Quest> quests = new HashMap<>();
|
||||
for (QuestCategory category : QuestController.Instance.categoriesSync.values()) {
|
||||
for (Quest quest : category.quests.values()) {
|
||||
quests.put(quest.id, quest);
|
||||
}
|
||||
}
|
||||
|
||||
QuestController.Instance.categories = QuestController.Instance.categoriesSync;
|
||||
QuestController.Instance.quests = quests;
|
||||
QuestController.Instance.categoriesSync = new HashMap<>();
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
|
||||
QuestCategory category = new QuestCategory();
|
||||
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
|
||||
NBTTagList list = compound.getTagList("Data", 10);
|
||||
if (QuestController.Instance.categoriesSync.containsKey(category.id)) {
|
||||
category = QuestController.Instance.categoriesSync.get(category.id);
|
||||
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
|
||||
}
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
Quest quest = new Quest();
|
||||
quest.readNBT(list.getCompoundTagAt(i));
|
||||
quest.category = category;
|
||||
category.quests.put(quest.id, quest);
|
||||
}
|
||||
QuestController.Instance.categories.put(category.id, category);
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleRemove(int id) {
|
||||
QuestCategory questCategory = QuestController.Instance.categories.remove(id);
|
||||
if (questCategory != null) {
|
||||
QuestController.Instance.quests.keySet().removeAll(questCategory.quests.keySet());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsRemove() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.controllers.QuestController;
|
||||
import noppes.npcs.controllers.data.Quest;
|
||||
import noppes.npcs.controllers.data.QuestCategory;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#QUEST}.
|
||||
* Child family — does not have its own cache. UPDATE and REMOVE only.
|
||||
* Invalidation targets the parent {@link SyncType#QUEST_CATEGORY} cache.
|
||||
*/
|
||||
public class QuestSyncHandler implements SyncHandler {
|
||||
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
/**
|
||||
* QUEST does not have its own independent cache; it shares
|
||||
* the QUEST_CATEGORY parent cache.
|
||||
*/
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
// QUEST does not handle standalone RELOAD; it's part of QUEST_CATEGORY
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
|
||||
QuestCategory category = QuestController.Instance.categories.get(categoryId);
|
||||
if (category == null)
|
||||
return; // Defensive: category may have been removed
|
||||
|
||||
Quest quest = new Quest();
|
||||
quest.category = category;
|
||||
quest.readNBT(compound);
|
||||
QuestController.Instance.quests.put(quest.id, quest);
|
||||
category.quests.put(quest.id, quest);
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleRemove(int id) {
|
||||
Quest quest = QuestController.Instance.quests.remove(id);
|
||||
if (quest != null)
|
||||
quest.category.quests.remove(id);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsRemove() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Not a cached type — QUEST shares the QUEST_CATEGORY cache.
|
||||
*/
|
||||
@Override
|
||||
public boolean isCachedType() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SyncType> getInvalidationTargets(SyncType self) {
|
||||
// Child invalidates the parent cache
|
||||
Set<SyncType> set = new HashSet<>();
|
||||
set.add(SyncType.QUEST_CATEGORY);
|
||||
return set;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package kamkeel.npcs.controllers.sync.handlers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.sync.SyncHandler;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.controllers.RecipeController;
|
||||
import noppes.npcs.controllers.data.RecipeCarpentry;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Sync handler for {@link SyncType#WORKBENCH_RECIPES}.
|
||||
* RELOAD-only family — does not support individual UPDATE or REMOVE.
|
||||
* Client-side RELOAD routes through {@link RecipeController#reloadGlobalRecipes}.
|
||||
*/
|
||||
public class WorkbenchRecipeSyncHandler implements SyncHandler {
|
||||
|
||||
private static final WorkbenchRecipeSyncHandler INSTANCE = new WorkbenchRecipeSyncHandler();
|
||||
|
||||
public static WorkbenchRecipeSyncHandler getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
// ========== SERVER-SIDE ==========
|
||||
|
||||
@Override
|
||||
public NBTTagCompound serializeAll() {
|
||||
RecipeController controller = RecipeController.Instance;
|
||||
NBTTagList list = new NBTTagList();
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
for (RecipeCarpentry recipe : controller.globalRecipes.values()) {
|
||||
list.appendTag(recipe.writeNBT(false));
|
||||
}
|
||||
compound.setTag("recipes", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
// ========== CLIENT-SIDE ==========
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void clientHandleReload(NBTTagCompound fullCompound) {
|
||||
NBTTagList list = fullCompound.getTagList("recipes", 10);
|
||||
if (list == null)
|
||||
return;
|
||||
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
NBTTagCompound recipeCompound = list.getCompoundTagAt(i);
|
||||
RecipeCarpentry recipe = RecipeCarpentry.create(recipeCompound);
|
||||
recipe.readNBT(recipeCompound);
|
||||
RecipeController.syncRecipes.put(recipe.id, recipe);
|
||||
}
|
||||
|
||||
RecipeController.reloadGlobalRecipes(RecipeController.syncRecipes);
|
||||
RecipeController.syncRecipes = new HashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SyncType> getInvalidationTargets(SyncType self) {
|
||||
Set<SyncType> set = new HashSet<>();
|
||||
set.add(SyncType.WORKBENCH_RECIPES);
|
||||
return set;
|
||||
}
|
||||
|
||||
// RELOAD-only: supportsUpdate() and supportsRemove() remain false (default)
|
||||
}
|
||||
@@ -264,18 +264,18 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
|
||||
Vec3 anchorPos = AnchorPointHelper.calculateAnchorPosition(livingOwner, anchorData);
|
||||
setPosition(anchorPos.xCoord, anchorPos.yCoord, anchorPos.zCoord);
|
||||
|
||||
Entity targetEntity = getTargetEntity();
|
||||
if (targetEntity instanceof EntityLivingBase && targetEntity.isEntityAlive()) {
|
||||
EntityLivingBase target = (EntityLivingBase) targetEntity;
|
||||
double dx = target.posX - anchorPos.xCoord;
|
||||
double dy = (target.posY + target.getEyeHeight() - 0.4) - anchorPos.yCoord;
|
||||
double dz = target.posZ - anchorPos.zCoord;
|
||||
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
|
||||
if (len > 0.0001) {
|
||||
dirX = dx / len;
|
||||
dirY = dy / len;
|
||||
dirZ = dz / len;
|
||||
}
|
||||
// Aim where the owner is looking so track speed and rotation lock still apply.
|
||||
double aimX = livingOwner.posX + dirX * maxLength;
|
||||
double aimY = livingOwner.posY + livingOwner.getEyeHeight() + dirY * maxLength;
|
||||
double aimZ = livingOwner.posZ + dirZ * maxLength;
|
||||
double dx = aimX - anchorPos.xCoord;
|
||||
double dy = aimY - anchorPos.yCoord;
|
||||
double dz = aimZ - anchorPos.zCoord;
|
||||
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
|
||||
if (len > 0.0001) {
|
||||
dirX = dx / len;
|
||||
dirY = dy / len;
|
||||
dirZ = dz / len;
|
||||
}
|
||||
} else {
|
||||
Vec3 direction = Vec3.createVectorHelper(dirX, dirY, dirZ);
|
||||
|
||||
@@ -155,6 +155,8 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD
|
||||
// HAZARD-SPECIFIC PROPERTIES
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
public static final int MIN_DAMAGE_INTERVAL = 5;
|
||||
|
||||
private float damagePerSecond = 1.0f;
|
||||
private int damageInterval = 20;
|
||||
private boolean ignoreIFrames = false;
|
||||
@@ -291,7 +293,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD
|
||||
zone.shape = shape;
|
||||
zone.radius = radius;
|
||||
zone.damagePerSecond = damagePerSecond;
|
||||
zone.damageInterval = damageInterval;
|
||||
zone.damageInterval = Math.max(MIN_DAMAGE_INTERVAL, damageInterval);
|
||||
zone.ignoreIFrames = ignoreIFrames;
|
||||
zone.affectsCaster = affectsCaster;
|
||||
zone.durationTicks = durationTicks;
|
||||
@@ -309,7 +311,6 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD
|
||||
zone.effects.add(e.copy());
|
||||
}
|
||||
}
|
||||
zone.ticksSinceDamage = damageInterval;
|
||||
return zone;
|
||||
}
|
||||
|
||||
@@ -518,7 +519,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD
|
||||
if (!isInZone(entity)) continue;
|
||||
|
||||
if (damagePerSecond > 0) {
|
||||
applyDamage(entity, owner, damagePerSecond);
|
||||
applyDamage(entity, owner, damagePerSecond * (damageInterval / 20.0f));
|
||||
}
|
||||
|
||||
applyEffects(entity);
|
||||
@@ -815,7 +816,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD
|
||||
public float getDamagePerSecond() { return damagePerSecond; }
|
||||
public void setDamagePerSecond(float dps) { this.damagePerSecond = dps; }
|
||||
public int getDamageInterval() { return damageInterval; }
|
||||
public void setDamageInterval(int ticks) { this.damageInterval = ticks; }
|
||||
public void setDamageInterval(int ticks) { this.damageInterval = Math.max(MIN_DAMAGE_INTERVAL, ticks); }
|
||||
public boolean isAffectsCaster() { return affectsCaster; }
|
||||
public void setAffectsCaster(boolean affects) { this.affectsCaster = affects; }
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package kamkeel.npcs.entity;
|
||||
|
||||
import kamkeel.npcs.addon.DBCAddon;
|
||||
import kamkeel.npcs.controllers.AbilityController;
|
||||
import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper;
|
||||
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData;
|
||||
import kamkeel.npcs.network.packets.data.energy.BarrierClientSyncPacket;
|
||||
@@ -15,6 +17,7 @@ import net.minecraft.util.DamageSource;
|
||||
import net.minecraft.world.World;
|
||||
import noppes.npcs.CustomNpcs;
|
||||
import noppes.npcs.EventHooks;
|
||||
import noppes.npcs.config.ConfigMain;
|
||||
import noppes.npcs.controllers.data.MagicData;
|
||||
import noppes.npcs.controllers.data.PlayerData;
|
||||
import noppes.npcs.entity.EntityNPCInterface;
|
||||
@@ -114,6 +117,7 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility {
|
||||
protected EnergyBarrierData barrierData = new EnergyBarrierData();
|
||||
protected float currentHealth;
|
||||
protected int ticksAlive = 0;
|
||||
protected long barrierDeathTime = -1;
|
||||
|
||||
// ==================== DATA WATCHER INDICES ====================
|
||||
protected static final int DW_HEALTH_PERCENT = 21;
|
||||
@@ -436,8 +440,17 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility {
|
||||
|
||||
float damage = amount * barrierData.meleeDamageMultiplier;
|
||||
|
||||
// Apply magic interactions from attacker's magic vs barrier's magic
|
||||
Entity attacker = source.getEntity();
|
||||
|
||||
// No LivingHurtEvent fires for a barrier, so scale the hit here.
|
||||
if (attacker instanceof EntityLivingBase) {
|
||||
damage = AbilityController.Instance.fireModifyBarrierMeleeDamage(this, (EntityLivingBase) attacker, damage);
|
||||
}
|
||||
if (attacker instanceof EntityPlayer && ConfigMain.AttributesEnabled && !DBCAddon.IsAvailable()) {
|
||||
damage = AttributeAttackUtil.calculateOutgoing((EntityPlayer) attacker, damage);
|
||||
}
|
||||
|
||||
// Apply magic interactions from attacker's magic vs barrier's magic
|
||||
if (attacker != null) {
|
||||
MagicData attackerMagic = null;
|
||||
if (attacker instanceof EntityPlayer) {
|
||||
@@ -510,15 +523,13 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility {
|
||||
}
|
||||
}
|
||||
|
||||
// Duration check
|
||||
if (barrierData.useDuration && ticksAlive >= barrierData.durationTicks) {
|
||||
onBarrierDestroyed();
|
||||
this.setDead();
|
||||
return true;
|
||||
if (barrierDeathTime < 0 && !isCharging()) {
|
||||
barrierDeathTime = worldObj.getTotalWorldTime()
|
||||
+ (barrierData.useDuration ? barrierData.durationTicks : BARRIER_HARD_LIFETIME_CAP);
|
||||
}
|
||||
|
||||
// Absolute hard lifetime cap (safety net for barriers with no duration)
|
||||
if (ticksAlive > BARRIER_HARD_LIFETIME_CAP) {
|
||||
// Duration check
|
||||
if (barrierDeathTime >= 0 && worldObj.getTotalWorldTime() >= barrierDeathTime) {
|
||||
onBarrierDestroyed();
|
||||
this.setDead();
|
||||
return true;
|
||||
@@ -865,6 +876,7 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility {
|
||||
protected void writeBarrierBaseNBT(NBTTagCompound nbt) {
|
||||
writeEnergyBaseNBT(nbt);
|
||||
nbt.setInteger("TicksAlive", ticksAlive);
|
||||
nbt.setLong("BarrierDeathTime", barrierDeathTime);
|
||||
nbt.setFloat("CurrentHealth", currentHealth);
|
||||
nbt.setBoolean("Charging", charging);
|
||||
nbt.setInteger("ChargeTick", chargeTick);
|
||||
@@ -879,6 +891,7 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility {
|
||||
protected void readBarrierBaseNBT(NBTTagCompound nbt) {
|
||||
readEnergyBaseNBT(nbt);
|
||||
this.ticksAlive = nbt.getInteger("TicksAlive");
|
||||
this.barrierDeathTime = nbt.hasKey("BarrierDeathTime") ? nbt.getLong("BarrierDeathTime") : -1;
|
||||
this.currentHealth = nbt.getFloat("CurrentHealth");
|
||||
if (Float.isNaN(currentHealth) || Float.isInfinite(currentHealth) || currentHealth < 0) currentHealth = barrierData.maxHealth;
|
||||
this.charging = nbt.hasKey("Charging") && nbt.getBoolean("Charging");
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
package kamkeel.npcs.network.enums;
|
||||
|
||||
public enum EnumSyncType {
|
||||
FACTION,
|
||||
DIALOG,
|
||||
DIALOG_CATEGORY,
|
||||
QUEST,
|
||||
QUEST_CATEGORY,
|
||||
PLAYERDATA,
|
||||
MAGIC,
|
||||
MAGIC_CYCLE,
|
||||
WORKBENCH_RECIPES,
|
||||
CARPENTRY_RECIPES,
|
||||
ANVIL_RECIPES,
|
||||
CUSTOM_EFFECTS,
|
||||
CUSTOM_ABILITY,
|
||||
CHAINED_ABILITY
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package kamkeel.npcs.network.enums;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Immutable, object-based sync-type identity for the CNPC+ sync backend.
|
||||
*
|
||||
* <p>Each {@code SyncType} has a canonical namespaced string ID ({@code modid:path})
|
||||
* and is registered via the static {@link #register} factory. Built-in CNPC+
|
||||
* families are exposed as {@code public static final} constants.</p>
|
||||
*
|
||||
* <p>Identity is based on the canonical {@link #id} string, which is unique
|
||||
* across all registered types. Two references with the same {@code id}
|
||||
* are always the same object (identity == equality for registered types).</p>
|
||||
*
|
||||
* <p>The {@code ordinal} field provides a stable integer identity for
|
||||
* wire encoding during the migration period. It is assigned at registration
|
||||
* time in declaration order and must NOT be used as a protocol identifier
|
||||
* once string-on-wire migration is complete.</p>
|
||||
*/
|
||||
public final class SyncType {
|
||||
|
||||
// ──────────────────── Registry ────────────────────
|
||||
private static final Map<String, SyncType> REGISTRY = new LinkedHashMap<>();
|
||||
private static int nextOrdinal = 0;
|
||||
|
||||
// ──────────────────── CNPC+ families ────────────────────
|
||||
public static final SyncType FACTION = register("cnpc:faction");
|
||||
public static final SyncType DIALOG = register("cnpc:dialog");
|
||||
public static final SyncType DIALOG_CATEGORY = register("cnpc:dialog_category");
|
||||
public static final SyncType QUEST = register("cnpc:quest");
|
||||
public static final SyncType QUEST_CATEGORY = register("cnpc:quest_category");
|
||||
public static final SyncType PLAYERDATA = register("cnpc:playerdata");
|
||||
public static final SyncType MAGIC = register("cnpc:magic");
|
||||
public static final SyncType MAGIC_CYCLE = register("cnpc:magic_cycle");
|
||||
public static final SyncType WORKBENCH_RECIPES = register("cnpc:workbench_recipes");
|
||||
public static final SyncType CARPENTRY_RECIPES = register("cnpc:carpentry_recipes");
|
||||
public static final SyncType ANVIL_RECIPES = register("cnpc:anvil_recipes");
|
||||
public static final SyncType CUSTOM_EFFECTS = register("cnpc:custom_effects");
|
||||
public static final SyncType CUSTOM_ABILITY = register("cnpc:custom_ability");
|
||||
public static final SyncType CHAINED_ABILITY = register("cnpc:chained_ability");
|
||||
|
||||
// ──────────────────── Instance fields ────────────────────
|
||||
private final String id;
|
||||
private final int ordinal;
|
||||
|
||||
private SyncType(String id, int ordinal) {
|
||||
this.id = id;
|
||||
this.ordinal = ordinal;
|
||||
}
|
||||
|
||||
// ──────────────────── Public API ────────────────────
|
||||
|
||||
/**
|
||||
* The canonical namespaced identifier, e.g. {@code "cnpc:faction"}.
|
||||
*/
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable integer ordinal assigned at registration time.
|
||||
* Used for wire encoding during the migration period only.
|
||||
*/
|
||||
public int ordinal() {
|
||||
return ordinal;
|
||||
}
|
||||
|
||||
// ──────────────────── Registration ────────────────────
|
||||
|
||||
/**
|
||||
* Register a new {@code SyncType} with the given canonical ID.
|
||||
*
|
||||
* @param id namespaced identifier ({@code modid:path})
|
||||
* @return the newly created and registered {@code SyncType}
|
||||
* @throws IllegalArgumentException if the ID is null, empty, or lacks a colon
|
||||
* @throws IllegalStateException if a type with the same ID is already registered
|
||||
* @throws IllegalStateException if the registry has been frozen
|
||||
*/
|
||||
public static SyncType register(String id) {
|
||||
if (id == null || id.isEmpty()) throw new IllegalArgumentException("SyncType id must not be null or empty");
|
||||
if (!id.contains(":")) throw new IllegalArgumentException("SyncType id must be namespaced (modid:path): " + id);
|
||||
if (REGISTRY.containsKey(id)) throw new IllegalStateException("Duplicate SyncType registration: " + id);
|
||||
|
||||
SyncType type = new SyncType(id, nextOrdinal++);
|
||||
REGISTRY.put(id, type);
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a registered SyncType by its canonical string ID.
|
||||
*
|
||||
* @return the registered type, or {@code null} if not found
|
||||
*/
|
||||
public static SyncType byId(String id) {
|
||||
return id == null ? null : REGISTRY.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a registered SyncType by its ordinal.
|
||||
* Used during migration for decoding ordinal-based wire traffic.
|
||||
*
|
||||
* @return the registered type, or {@code null} if ordinal is out of range
|
||||
*/
|
||||
public static SyncType byOrdinal(int ordinal) {
|
||||
if (ordinal < 0) return null;
|
||||
|
||||
for (SyncType type : REGISTRY.values())
|
||||
if (type.ordinal == ordinal) return type;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all registered SyncType instances in registration order.
|
||||
*/
|
||||
public static Collection<SyncType> values() {
|
||||
return Collections.unmodifiableCollection(REGISTRY.values());
|
||||
}
|
||||
|
||||
// ──────────────────── Object overrides ────────────────────
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof SyncType)) return false;
|
||||
return id.equals(((SyncType) o).id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return id.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import kamkeel.npcs.network.PacketChannel;
|
||||
import kamkeel.npcs.network.PacketClient;
|
||||
import kamkeel.npcs.network.PacketHandler;
|
||||
import kamkeel.npcs.network.enums.EnumDataPacket;
|
||||
import kamkeel.npcs.network.enums.EnumSyncType;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import kamkeel.npcs.network.packets.player.SyncRevisionInfoPacket;
|
||||
import kamkeel.npcs.util.ByteBufUtils;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
@@ -21,19 +21,20 @@ import noppes.npcs.controllers.AuctionConfigSync;
|
||||
import noppes.npcs.controllers.ScriptConfigSync;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public final class LoginPacket extends AbstractPacket {
|
||||
public static final String packetName = "CNPC+|Login";
|
||||
|
||||
private String serverCacheKey = "";
|
||||
private final EnumMap<EnumSyncType, Integer> revisionSnapshot = new EnumMap<>(EnumSyncType.class);
|
||||
private final Map<SyncType, Integer> revisionSnapshot = new LinkedHashMap<>();
|
||||
|
||||
public LoginPacket() {
|
||||
}
|
||||
|
||||
public LoginPacket(String serverCacheKey, EnumMap<EnumSyncType, Integer> revisionSnapshot) {
|
||||
public LoginPacket(String serverCacheKey, Map<SyncType, Integer> revisionSnapshot) {
|
||||
if (serverCacheKey != null) {
|
||||
this.serverCacheKey = serverCacheKey;
|
||||
}
|
||||
@@ -58,17 +59,15 @@ public final class LoginPacket extends AbstractPacket {
|
||||
out.writeBoolean(ConfigMain.ProfilesEnabled);
|
||||
ByteBufUtils.writeString(out, serverCacheKey);
|
||||
out.writeShort(revisionSnapshot.size());
|
||||
for (Map.Entry<EnumSyncType, Integer> entry : revisionSnapshot.entrySet()) {
|
||||
for (Map.Entry<SyncType, Integer> entry : revisionSnapshot.entrySet()) {
|
||||
out.writeInt(entry.getKey().ordinal());
|
||||
out.writeInt(entry.getValue());
|
||||
}
|
||||
|
||||
// Send auction config (server-side sync)
|
||||
NBTTagCompound auctionConfig = new NBTTagCompound();
|
||||
AuctionConfigSync.writeToNBT(auctionConfig);
|
||||
ByteBufUtils.writeNBT(out, auctionConfig);
|
||||
|
||||
// Send script config (server-side sync)
|
||||
NBTTagCompound scriptConfig = new NBTTagCompound();
|
||||
ScriptConfigSync.writeToNBT(scriptConfig);
|
||||
ByteBufUtils.writeNBT(out, scriptConfig);
|
||||
@@ -82,20 +81,20 @@ public final class LoginPacket extends AbstractPacket {
|
||||
|
||||
String serverKey = ByteBufUtils.readString(in);
|
||||
int revisionCount = in.readUnsignedShort();
|
||||
EnumMap<EnumSyncType, Integer> serverRevisions = new EnumMap<>(EnumSyncType.class);
|
||||
Map<SyncType, Integer> serverRevisions = new LinkedHashMap<>();
|
||||
for (int i = 0; i < revisionCount; i++) {
|
||||
EnumSyncType type = EnumSyncType.values()[in.readInt()];
|
||||
SyncType type = SyncType.byOrdinal(in.readInt());
|
||||
int revision = in.readInt();
|
||||
serverRevisions.put(type, revision);
|
||||
if (type != null) {
|
||||
serverRevisions.put(type, revision);
|
||||
}
|
||||
}
|
||||
|
||||
ClientCacheHandler.setActiveServer(serverKey, serverRevisions);
|
||||
|
||||
// Read auction config
|
||||
NBTTagCompound auctionConfig = ByteBufUtils.readNBT(in);
|
||||
AuctionClientConfig.readFromNBT(auctionConfig);
|
||||
|
||||
// Read script config
|
||||
NBTTagCompound scriptConfig = ByteBufUtils.readNBT(in);
|
||||
ScriptClientConfig.readFromNBT(scriptConfig);
|
||||
|
||||
|
||||
+12
-9
@@ -8,24 +8,24 @@ import kamkeel.npcs.network.PacketChannel;
|
||||
import kamkeel.npcs.network.PacketHandler;
|
||||
import kamkeel.npcs.network.enums.EnumDataPacket;
|
||||
import kamkeel.npcs.util.ByteBufUtils;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.client.NoppesUtil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class PlayerUpdateSkinOverlaysPacket extends AbstractPacket {
|
||||
public static final String packetName = "Data|PlayerUpdateSkinOverlays";
|
||||
|
||||
private String playerName;
|
||||
private String playerUUID;
|
||||
private NBTTagCompound compound;
|
||||
|
||||
public PlayerUpdateSkinOverlaysPacket() {
|
||||
}
|
||||
|
||||
public PlayerUpdateSkinOverlaysPacket(String playerName, NBTTagCompound compound) {
|
||||
this.playerName = playerName;
|
||||
public PlayerUpdateSkinOverlaysPacket(UUID playerUUID, NBTTagCompound compound) {
|
||||
this.playerUUID = playerUUID == null ? "" : playerUUID.toString();
|
||||
this.compound = compound;
|
||||
}
|
||||
|
||||
@@ -41,18 +41,21 @@ public final class PlayerUpdateSkinOverlaysPacket extends AbstractPacket {
|
||||
|
||||
@Override
|
||||
public void sendData(ByteBuf out) throws IOException {
|
||||
ByteBufUtils.writeString(out, this.playerName);
|
||||
ByteBufUtils.writeString(out, this.playerUUID);
|
||||
ByteBufUtils.writeNBT(out, this.compound);
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
|
||||
String playerName = ByteBufUtils.readString(in);
|
||||
String uuid = ByteBufUtils.readString(in);
|
||||
NBTTagCompound nbt = ByteBufUtils.readNBT(in);
|
||||
EntityPlayer sendingPlayer = Minecraft.getMinecraft().theWorld.getPlayerEntityByName(playerName);
|
||||
if (sendingPlayer != null) {
|
||||
NoppesUtil.updateSkinOverlayData(sendingPlayer, nbt);
|
||||
if (uuid == null || uuid.isEmpty())
|
||||
return;
|
||||
|
||||
try {
|
||||
NoppesUtil.updateSkinOverlayData(UUID.fromString(uuid), nbt);
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,13 +9,9 @@ import kamkeel.npcs.network.PacketChannel;
|
||||
import kamkeel.npcs.network.PacketHandler;
|
||||
import kamkeel.npcs.network.enums.EnumDataPacket;
|
||||
import kamkeel.npcs.util.ByteBufUtils;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiScreen;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.client.gui.util.GuiContainerNPCInterface;
|
||||
import noppes.npcs.client.gui.util.GuiNPCInterface;
|
||||
import noppes.npcs.client.gui.util.IGuiData;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -59,15 +55,6 @@ public final class GuiDataPacket extends LargeAbstractPacket {
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
protected void handleCompleteData(ByteBuf data, EntityPlayer player) throws IOException {
|
||||
GuiScreen gui = Minecraft.getMinecraft().currentScreen;
|
||||
if (gui instanceof GuiNPCInterface && ((GuiNPCInterface) gui).hasSubGui()) {
|
||||
gui = ((GuiNPCInterface) gui).getSubGui();
|
||||
} else if (gui instanceof GuiContainerNPCInterface && ((GuiContainerNPCInterface) gui).hasSubGui()) {
|
||||
gui = ((GuiContainerNPCInterface) gui).getSubGui();
|
||||
}
|
||||
if (gui instanceof IGuiData) {
|
||||
NBTTagCompound nbt = ByteBufUtils.readBigNBT(data);
|
||||
((IGuiData) gui).setGuiData(nbt);
|
||||
}
|
||||
IGuiData.legacySetGuiData(ByteBufUtils.readBigNBT(data));
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import kamkeel.npcs.controllers.SyncController;
|
||||
import kamkeel.npcs.controllers.sync.handlers.PlayerEffectSyncHelper;
|
||||
import kamkeel.npcs.network.LargeAbstractPacket;
|
||||
import kamkeel.npcs.network.PacketChannel;
|
||||
import kamkeel.npcs.network.PacketHandler;
|
||||
@@ -54,7 +54,7 @@ public final class SyncEffectPacket extends LargeAbstractPacket {
|
||||
return;
|
||||
try {
|
||||
NBTTagCompound tag = ByteBufUtils.readBigNBT(data);
|
||||
SyncController.clientSyncEffects(tag);
|
||||
PlayerEffectSyncHelper.clientSyncEffects(tag);
|
||||
} catch (RuntimeException e) {
|
||||
LogWriter.error(String.format("Attempted to Sync Effects but it was too big"));
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import kamkeel.npcs.network.PacketChannel;
|
||||
import kamkeel.npcs.network.PacketHandler;
|
||||
import kamkeel.npcs.network.enums.EnumDataPacket;
|
||||
import kamkeel.npcs.network.enums.EnumSyncAction;
|
||||
import kamkeel.npcs.network.enums.EnumSyncType;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import kamkeel.npcs.util.ByteBufUtils;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
@@ -22,16 +22,13 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A large sync packet that sends chunked data to the client for a given SyncType
|
||||
* along with a SyncAction (RELOAD, UPDATE, REMOVE).
|
||||
*/
|
||||
public final class SyncPacket extends LargeAbstractPacket {
|
||||
|
||||
private EnumSyncType enumSyncType;
|
||||
private SyncType syncType;
|
||||
private EnumSyncAction enumSyncAction;
|
||||
private NBTTagCompound syncData;
|
||||
private int operationID;
|
||||
private String operationKey;
|
||||
private int revision = -1;
|
||||
private byte[] cachedPayload;
|
||||
private byte[][] cachedChunks;
|
||||
@@ -39,23 +36,21 @@ public final class SyncPacket extends LargeAbstractPacket {
|
||||
public SyncPacket() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new LargeSyncPacket.
|
||||
*/
|
||||
public SyncPacket(EnumSyncType enumSyncType, EnumSyncAction enumSyncAction, int catId, NBTTagCompound syncData) {
|
||||
this(enumSyncType, enumSyncAction, catId, -1, syncData);
|
||||
public SyncPacket(SyncType syncType, EnumSyncAction enumSyncAction, int catId, NBTTagCompound syncData) {
|
||||
this(syncType, enumSyncAction, catId, null, -1, syncData);
|
||||
}
|
||||
|
||||
public SyncPacket(EnumSyncType enumSyncType, EnumSyncAction enumSyncAction, int catId, int revision, NBTTagCompound syncData) {
|
||||
this.enumSyncType = enumSyncType;
|
||||
public SyncPacket(SyncType syncType, EnumSyncAction enumSyncAction, int operationId, String operationKey, int revision, NBTTagCompound syncData) {
|
||||
this.syncType = syncType;
|
||||
this.enumSyncAction = enumSyncAction;
|
||||
this.syncData = syncData;
|
||||
this.operationID = catId;
|
||||
this.operationID = operationId;
|
||||
this.operationKey = operationKey;
|
||||
this.revision = revision;
|
||||
}
|
||||
|
||||
public SyncPacket(EnumSyncType enumSyncType, SyncController.CachedSyncPayload payload) {
|
||||
this.enumSyncType = enumSyncType;
|
||||
public SyncPacket(SyncType syncType, SyncController.CachedSyncPayload payload) {
|
||||
this.syncType = syncType;
|
||||
this.enumSyncAction = EnumSyncAction.RELOAD;
|
||||
this.operationID = -1;
|
||||
this.revision = payload.getRevision();
|
||||
@@ -79,13 +74,21 @@ public final class SyncPacket extends LargeAbstractPacket {
|
||||
return cachedPayload;
|
||||
}
|
||||
|
||||
boolean hasKey = operationKey != null;
|
||||
boolean hasNbt = syncData != null;
|
||||
|
||||
ByteBuf buffer = Unpooled.buffer();
|
||||
try {
|
||||
buffer.writeInt(enumSyncType.ordinal());
|
||||
buffer.writeInt(syncType.ordinal());
|
||||
buffer.writeInt(enumSyncAction.ordinal());
|
||||
buffer.writeInt(operationID);
|
||||
buffer.writeInt(revision);
|
||||
ByteBufUtils.writeBigNBT(buffer, syncData);
|
||||
|
||||
// UPDATE/REMOVE UNIQUE FIELDS
|
||||
buffer.writeBoolean(hasKey);
|
||||
if (hasKey) ByteBufUtils.writeString(buffer, operationKey);
|
||||
buffer.writeBoolean(hasNbt);
|
||||
if (hasNbt) ByteBufUtils.writeBigNBT(buffer, syncData);
|
||||
|
||||
byte[] bytes = new byte[buffer.readableBytes()];
|
||||
buffer.readBytes(bytes);
|
||||
@@ -131,39 +134,40 @@ public final class SyncPacket extends LargeAbstractPacket {
|
||||
if (CustomNpcs.side() != Side.CLIENT)
|
||||
return;
|
||||
|
||||
// Reconstruct everything from the ByteBuf
|
||||
int syncTypeOrdinal = data.readInt();
|
||||
int syncActionOrdinal = data.readInt();
|
||||
int categoryID = data.readInt();
|
||||
int incomingRevision = data.readInt();
|
||||
operationID = data.readInt();
|
||||
revision = data.readInt();
|
||||
|
||||
EnumSyncType type = EnumSyncType.values()[syncTypeOrdinal];
|
||||
EnumSyncAction action = EnumSyncAction.values()[syncActionOrdinal];
|
||||
try {
|
||||
NBTTagCompound tag = ByteBufUtils.readBigNBT(data);
|
||||
// Now do your client-side logic (similar to your old clientSync() or clientSyncUpdate() approach)
|
||||
handleSyncPacketClient(type, action, categoryID, incomingRevision, tag);
|
||||
} catch (RuntimeException e) {
|
||||
LogWriter.error(String.format("Attempted to Sync %s but it was too big", type.toString()));
|
||||
|
||||
// These fields only exist for UPDATE/REMOVE
|
||||
if (action != EnumSyncAction.RELOAD) {
|
||||
if (data.readBoolean()) operationKey = ByteBufUtils.readString(data);
|
||||
if (data.readBoolean()) syncData = ByteBufUtils.readBigNBT(data);
|
||||
} else
|
||||
syncData = ByteBufUtils.readBigNBT(data);
|
||||
|
||||
|
||||
syncType = SyncType.byOrdinal(syncTypeOrdinal);
|
||||
if (syncType == null) {
|
||||
LogWriter.error("[SyncPacket] Unknown sync type ordinal: " + syncTypeOrdinal + "; skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
handleSync(syncType, action, operationID, operationKey, revision, syncData);
|
||||
}
|
||||
|
||||
private void handleSyncPacketClient(
|
||||
EnumSyncType enumSyncType,
|
||||
EnumSyncAction enumSyncAction,
|
||||
int id,
|
||||
int incomingRevision,
|
||||
NBTTagCompound data
|
||||
) {
|
||||
switch (enumSyncAction) {
|
||||
private void handleSync(SyncType type, EnumSyncAction action, int id, String key, int revision, NBTTagCompound data) {
|
||||
switch (action) {
|
||||
case RELOAD:
|
||||
SyncController.clientSync(enumSyncType, incomingRevision, data);
|
||||
SyncController.clientHandleAll(type, revision, data);
|
||||
break;
|
||||
case UPDATE:
|
||||
SyncController.clientUpdate(enumSyncType, id, incomingRevision, data);
|
||||
SyncController.clientHandleUpdate(type, id, key, revision, data);
|
||||
break;
|
||||
case REMOVE:
|
||||
SyncController.clientSyncRemove(enumSyncType, id, incomingRevision);
|
||||
SyncController.clientHandleRemove(type, id, key, revision);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,13 +8,13 @@ import kamkeel.npcs.network.AbstractPacket;
|
||||
import kamkeel.npcs.network.PacketChannel;
|
||||
import kamkeel.npcs.network.PacketHandler;
|
||||
import kamkeel.npcs.network.enums.EnumPlayerPacket;
|
||||
import kamkeel.npcs.network.enums.EnumSyncType;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import kamkeel.npcs.util.ByteBufUtils;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.EnumMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class SyncRevisionInfoPacket extends AbstractPacket {
|
||||
@@ -23,12 +23,12 @@ public class SyncRevisionInfoPacket extends AbstractPacket {
|
||||
|
||||
private String serverKey = "";
|
||||
private String previousServerKey = "";
|
||||
private final EnumMap<EnumSyncType, Integer> revisions = new EnumMap<>(EnumSyncType.class);
|
||||
private final Map<SyncType, Integer> revisions = new LinkedHashMap<>();
|
||||
|
||||
public SyncRevisionInfoPacket() {
|
||||
}
|
||||
|
||||
public SyncRevisionInfoPacket(String serverKey, String previousServerKey, EnumMap<EnumSyncType, Integer> revisions) {
|
||||
public SyncRevisionInfoPacket(String serverKey, String previousServerKey, Map<SyncType, Integer> revisions) {
|
||||
if (serverKey != null) {
|
||||
this.serverKey = serverKey;
|
||||
}
|
||||
@@ -56,7 +56,7 @@ public class SyncRevisionInfoPacket extends AbstractPacket {
|
||||
ByteBufUtils.writeString(out, serverKey);
|
||||
ByteBufUtils.writeString(out, previousServerKey);
|
||||
out.writeShort(revisions.size());
|
||||
for (Map.Entry<EnumSyncType, Integer> entry : revisions.entrySet()) {
|
||||
for (Map.Entry<SyncType, Integer> entry : revisions.entrySet()) {
|
||||
out.writeInt(entry.getKey().ordinal());
|
||||
out.writeInt(entry.getValue());
|
||||
}
|
||||
@@ -71,13 +71,15 @@ public class SyncRevisionInfoPacket extends AbstractPacket {
|
||||
String incomingServerKey = ByteBufUtils.readString(in);
|
||||
String incomingPreviousKey = ByteBufUtils.readString(in);
|
||||
int revisionCount = in.readUnsignedShort();
|
||||
EnumMap<EnumSyncType, Integer> incomingRevisions = new EnumMap<>(EnumSyncType.class);
|
||||
Map<SyncType, Integer> incomingRevisions = new LinkedHashMap<>();
|
||||
for (int i = 0; i < revisionCount; i++) {
|
||||
EnumSyncType type = EnumSyncType.values()[in.readInt()];
|
||||
SyncType type = SyncType.byOrdinal(in.readInt());
|
||||
int revision = in.readInt();
|
||||
incomingRevisions.put(type, revision);
|
||||
if (type != null) {
|
||||
incomingRevisions.put(type, revision);
|
||||
}
|
||||
}
|
||||
|
||||
SyncController.handleClientRevisionReport((EntityPlayerMP) player, incomingServerKey, incomingPreviousKey, incomingRevisions);
|
||||
SyncController.completeLoginRevisionHandshake((EntityPlayerMP) player, incomingServerKey, incomingPreviousKey, incomingRevisions);
|
||||
}
|
||||
}
|
||||
+1
-4
@@ -50,10 +50,7 @@ public final class AbilityHotbarSelectPacket extends AbstractPacket {
|
||||
// Deselect
|
||||
data.abilityData.setSelectedIndex(-1);
|
||||
} else {
|
||||
int index = data.abilityData.getUnlockedAbilityList().indexOf(key);
|
||||
if (index >= 0) {
|
||||
data.abilityData.setSelectedIndex(index);
|
||||
}
|
||||
data.abilityData.setSelectedIndex(data.abilityData.getUnlockedAbilityList().indexOf(key));
|
||||
}
|
||||
data.save();
|
||||
}
|
||||
|
||||
+1
-1
@@ -73,7 +73,7 @@ public final class CategoryItemsRequestPacket extends AbstractPacket {
|
||||
|
||||
// Send tag map for the items
|
||||
HashMap<String, HashSet<UUID>> tagMap = getTagMapByCat(type, categoryId);
|
||||
if (tagMap != null && !tagMap.isEmpty()) {
|
||||
if (tagMap != null) {
|
||||
TagController.sendCategoryTagMap((EntityPlayerMP) player, tagMap);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ public final class JobSpawnerAddPacket extends AbstractPacket {
|
||||
|
||||
private String selected;
|
||||
private int activeTab;
|
||||
private String folderName;
|
||||
private int slot;
|
||||
|
||||
private NBTTagCompound compound;
|
||||
@@ -39,6 +40,15 @@ public final class JobSpawnerAddPacket extends AbstractPacket {
|
||||
this.isServer = isServer;
|
||||
this.selected = selected;
|
||||
this.activeTab = activeTab;
|
||||
this.folderName = null;
|
||||
this.slot = slot;
|
||||
}
|
||||
|
||||
public JobSpawnerAddPacket(boolean isServer, String selected, String folderName, int slot) {
|
||||
this.isServer = isServer;
|
||||
this.selected = selected;
|
||||
this.activeTab = -1;
|
||||
this.folderName = folderName;
|
||||
this.slot = slot;
|
||||
}
|
||||
|
||||
@@ -75,6 +85,9 @@ public final class JobSpawnerAddPacket extends AbstractPacket {
|
||||
if (this.isServer) {
|
||||
ByteBufUtils.writeString(out, selected);
|
||||
out.writeInt(this.activeTab);
|
||||
if (this.activeTab == -1) {
|
||||
ByteBufUtils.writeString(out, folderName != null ? folderName : "");
|
||||
}
|
||||
out.writeInt(this.slot);
|
||||
} else {
|
||||
out.writeInt(this.slot);
|
||||
@@ -96,7 +109,15 @@ public final class JobSpawnerAddPacket extends AbstractPacket {
|
||||
JobSpawner job = (JobSpawner) npc.jobInterface;
|
||||
boolean useServerClone = in.readBoolean();
|
||||
if (useServerClone) {
|
||||
NBTTagCompound compound = ServerCloneController.Instance.getCloneData(null, ByteBufUtils.readString(in), in.readInt());
|
||||
String selected = ByteBufUtils.readString(in);
|
||||
int tab = in.readInt();
|
||||
NBTTagCompound compound;
|
||||
if (tab == -1) {
|
||||
String folder = ByteBufUtils.readString(in);
|
||||
compound = ServerCloneController.Instance.getCloneData(null, selected, folder);
|
||||
} else {
|
||||
compound = ServerCloneController.Instance.getCloneData(null, selected, tab);
|
||||
}
|
||||
job.setJobCompound(in.readInt(), compound);
|
||||
} else {
|
||||
job.setJobCompound(in.readInt(), ByteBufUtils.readNBT(in));
|
||||
|
||||
@@ -14,6 +14,7 @@ import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.CustomNpcsPermissions;
|
||||
import noppes.npcs.roles.RoleTrader;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@@ -63,7 +64,13 @@ public final class RoleSavePacket extends AbstractPacket {
|
||||
if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player))
|
||||
return;
|
||||
|
||||
npc.roleInterface.readFromNBT(ByteBufUtils.readNBT(in));
|
||||
NBTTagCompound roleCompound = ByteBufUtils.readNBT(in);
|
||||
if (npc.roleInterface instanceof RoleTrader) {
|
||||
// An admin edit wins over the linked market; the market is written from it afterwards.
|
||||
((RoleTrader) npc.roleInterface).readFromNBT(roleCompound, false);
|
||||
} else {
|
||||
npc.roleInterface.readFromNBT(roleCompound);
|
||||
}
|
||||
npc.updateClient = true;
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,6 @@ import io.netty.buffer.ByteBuf;
|
||||
import kamkeel.npcs.network.AbstractPacket;
|
||||
import kamkeel.npcs.network.PacketChannel;
|
||||
import kamkeel.npcs.network.PacketHandler;
|
||||
import kamkeel.npcs.network.PacketUtil;
|
||||
import kamkeel.npcs.network.enums.EnumItemPacketType;
|
||||
import kamkeel.npcs.network.enums.EnumRequestPacket;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
@@ -38,9 +36,6 @@ public final class TagsGetPacket extends AbstractPacket {
|
||||
|
||||
@Override
|
||||
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
|
||||
if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.WAND, EnumItemPacketType.CLONER))
|
||||
return;
|
||||
|
||||
NoppesUtilServer.sendTagDataAll((EntityPlayerMP) player);
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ public class Register<T> {
|
||||
protected final String namespace;
|
||||
protected final Map<String, Supplier<T>> entries = new LinkedHashMap<>();
|
||||
|
||||
private Register(String registryKey, String namespace) {
|
||||
public Register(String registryKey, String namespace) {
|
||||
this.registryKey = registryKey;
|
||||
this.namespace = namespace;
|
||||
}
|
||||
@@ -36,6 +36,31 @@ public class Register<T> {
|
||||
return factory.get();
|
||||
}
|
||||
|
||||
public Map<String, Supplier<T>> getEntries() {
|
||||
return entries;
|
||||
}
|
||||
|
||||
public void forEach(Consumer<T> action) {
|
||||
entries.values().forEach(s -> action.accept(s.get()));
|
||||
}
|
||||
|
||||
public static <T> Register<T> create(String registryKey, String namespace, String displayName) {
|
||||
registerNamespace(registryKey, namespace, displayName);
|
||||
return new Register<>(registryKey, namespace);
|
||||
}
|
||||
|
||||
public static void registerNamespace(String registryKey, String namespace, String displayName) {
|
||||
if (!REGISTERED_NAMESPACES.containsKey(registryKey))
|
||||
REGISTERED_NAMESPACES.put(registryKey, new ArrayList<>());
|
||||
|
||||
if (REGISTERED_NAMESPACES.get(registryKey).contains(namespace)) {
|
||||
LogWriter.error("REGISTER: Namespace " + namespace + " already registered for registry " + registryKey + "!");
|
||||
}
|
||||
|
||||
REGISTERED_NAMESPACES.get(registryKey).add(namespace);
|
||||
NAMESPACE_DISPLAY_NAMES.put(namespace, displayName);
|
||||
}
|
||||
|
||||
public static boolean isEmpty(String registryKey) {
|
||||
if (REGISTERED_NAMESPACES.isEmpty()) return true;
|
||||
|
||||
|
||||
@@ -786,7 +786,14 @@ public abstract class AbstractDataAbilities {
|
||||
fireTickEvent(currentAbility, target);
|
||||
|
||||
// Script may have completed/cancelled the ability during the tick event
|
||||
if (currentAbility == null || !currentAbility.isExecuting()) return;
|
||||
if (currentAbility == null) return;
|
||||
if (!currentAbility.isExecuting()) {
|
||||
// tick() can end the ability (DAZED -> IDLE)
|
||||
if (phaseChanged && currentAbility.getPhase() == AbilityPhase.IDLE) {
|
||||
handleAbilityCompletion(target);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Fire extender tick hook (e.g., per-tick resource drain)
|
||||
if (!AbilityController.Instance.fireOnAbilityTick(currentAbility, entity, target,
|
||||
|
||||
@@ -225,6 +225,9 @@ public class CommonProxy implements IGuiHandler {
|
||||
public void buildPackageIndex() {
|
||||
}
|
||||
|
||||
public void loadComplete() {
|
||||
}
|
||||
|
||||
public boolean isScriptingEnabled() {
|
||||
return ConfigScript.ScriptingEnabled;
|
||||
}
|
||||
|
||||
@@ -125,7 +125,7 @@ import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11.1")
|
||||
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11.2")
|
||||
public class CustomNpcs {
|
||||
|
||||
@SidedProxy(clientSide = "noppes.npcs.client.ClientProxy", serverSide = "noppes.npcs.CommonProxy")
|
||||
@@ -318,6 +318,9 @@ public class CustomNpcs {
|
||||
new AttributeController();
|
||||
new MagicController();
|
||||
|
||||
SyncController.register();
|
||||
|
||||
|
||||
APIRegistry.Instance.register("CNPC+ API", "https://kamkeel.github.io/CustomNPC-Plus/");
|
||||
}
|
||||
|
||||
@@ -340,6 +343,7 @@ public class CustomNpcs {
|
||||
|
||||
@EventHandler
|
||||
public void loadComplete(FMLLoadCompleteEvent ev) {
|
||||
proxy.loadComplete();
|
||||
proxy.buildPackageIndex();
|
||||
|
||||
// Load built-in animations on the client so they're available for ability preview.
|
||||
|
||||
@@ -188,22 +188,33 @@ public class DataAbilities extends AbstractDataAbilities {
|
||||
if (maxCooldown > minCooldown) {
|
||||
baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1);
|
||||
}
|
||||
cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown + ability.getCooldownTicks();
|
||||
long now = npc.worldObj.getTotalWorldTime();
|
||||
|
||||
// Additionally set per-ability cooldown if enabled
|
||||
if (ability.isPerAbilityCooldown() && ability.getCooldownTicks() > 0) {
|
||||
long endTime = npc.worldObj.getTotalWorldTime() + ability.getCooldownTicks();
|
||||
setPerAbilityCooldown(ability.getName(), endTime, ability.getCooldownTicks());
|
||||
// Global timer only paces the NPC; the ability tracks its own cooldown
|
||||
cooldownEndTime = now + baseCooldown;
|
||||
setPerAbilityCooldown(ability.getName(), now + ability.getCooldownTicks(), ability.getCooldownTicks());
|
||||
} else {
|
||||
cooldownEndTime = now + baseCooldown + ability.getCooldownTicks();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void rollChainCooldown(ChainedAbility chain) {
|
||||
int baseCooldown = minCooldown;
|
||||
if (maxCooldown > minCooldown) {
|
||||
baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1);
|
||||
long now = npc.worldObj.getTotalWorldTime();
|
||||
boolean perAbility = chain.isPerAbilityCooldown() && chain.getCooldownTicks() > 0;
|
||||
|
||||
if (!chain.isIgnoreCooldown()) {
|
||||
int baseCooldown = minCooldown;
|
||||
if (maxCooldown > minCooldown) {
|
||||
baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1);
|
||||
}
|
||||
cooldownEndTime = perAbility ? now + baseCooldown : now + baseCooldown + chain.getCooldownTicks();
|
||||
}
|
||||
|
||||
if (perAbility) {
|
||||
setPerAbilityCooldown(chain.getName(), now + chain.getCooldownTicks(), chain.getCooldownTicks());
|
||||
}
|
||||
cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown + chain.getCooldownTicks();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -471,12 +482,17 @@ public class DataAbilities extends AbstractDataAbilities {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Per-ability cooldown filter: ability may have its own independent cooldown
|
||||
// Per-ability cooldown filter: ability/chain may have its own independent cooldown
|
||||
if (!action.isChain()) {
|
||||
Ability ab = (Ability) action;
|
||||
if (ab.isPerAbilityCooldown() && isOnPerAbilityCooldown(ab.getName())) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
ChainedAbility ch = (ChainedAbility) action;
|
||||
if (ch.isPerAbilityCooldown() && isOnPerAbilityCooldown(ch.getName())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
@@ -975,6 +975,11 @@ public class EventHooks {
|
||||
return postAbilityEvent(ability, event);
|
||||
}
|
||||
|
||||
public static boolean onAbilityDefend(Ability ability, AbilityEvent.DefendEvent event) {
|
||||
if (ability == null || event == null) return false;
|
||||
return postAbilityEvent(ability, event);
|
||||
}
|
||||
|
||||
public static boolean onAbilityToggle(Ability ability, EntityLivingBase entity, int oldState, int newState) {
|
||||
if (ability == null || entity == null) return false;
|
||||
return postAbilityEvent(ability, new AbilityEvent.ToggleEvent(entity, ability, oldState, newState));
|
||||
|
||||
@@ -550,14 +550,13 @@ public class NoppesUtilPlayer {
|
||||
if (data == null)
|
||||
return false;
|
||||
|
||||
if (!data.quest.questInterface.isPartyCompleted(party))
|
||||
return false;
|
||||
|
||||
|
||||
Quest quest = data.quest;
|
||||
if (quest == null)
|
||||
return false;
|
||||
|
||||
if (!data.quest.questInterface.isPartyCompleted(party))
|
||||
return false;
|
||||
|
||||
if (data.quest.completion == EnumQuestCompletion.Instant)
|
||||
EventHooks.onPartyFinished(party, data.quest);
|
||||
|
||||
|
||||
@@ -343,11 +343,6 @@ public class NoppesUtilServer {
|
||||
sendOpenGui(player, gui, npc, 0, 0, 0);
|
||||
}
|
||||
|
||||
public static void sendOpenGuiNoDelay(EntityPlayer player,
|
||||
EnumGuiType gui, EntityNPCInterface npc) {
|
||||
sendOpenGuiNoDelay(player, gui, npc, 0, 0, 0);
|
||||
}
|
||||
|
||||
public static void sendOpenGui(final EntityPlayer player,
|
||||
final EnumGuiType gui, final EntityNPCInterface npc, final int i, final int j, final int k) {
|
||||
if (!(player instanceof EntityPlayerMP))
|
||||
@@ -369,28 +364,6 @@ public class NoppesUtilServer {
|
||||
ScrollListPacket.sendList((EntityPlayerMP) player, list, EnumScrollData.OPTIONAL);
|
||||
}
|
||||
|
||||
public static void sendOpenGuiNoDelay(final EntityPlayer player,
|
||||
final EnumGuiType gui, final EntityNPCInterface npc, final int i, final int j, final int k) {
|
||||
if (!(player instanceof EntityPlayerMP))
|
||||
return;
|
||||
|
||||
setEditingNpc(player, npc);
|
||||
sendExtraData(player, npc, gui, i, j, k);
|
||||
|
||||
if (CustomNpcs.proxy.getServerGuiElement(gui.ordinal(), player, player.worldObj, i, j, k) != null) {
|
||||
player.openGui(CustomNpcs.instance, gui.ordinal(), player.worldObj, i, j, k);
|
||||
return;
|
||||
} else {
|
||||
GuiOpenPacket.openGUI((EntityPlayerMP) player, gui, i, j, k);
|
||||
}
|
||||
ArrayList<String> list = getScrollData(player, gui, npc);
|
||||
if (list == null || list.isEmpty())
|
||||
return;
|
||||
|
||||
ScrollListPacket.sendList((EntityPlayerMP) player, list, EnumScrollData.OPTIONAL);
|
||||
}
|
||||
|
||||
|
||||
private static void sendExtraData(EntityPlayer player, EntityNPCInterface npc, EnumGuiType gui, int i, int j, int k) {
|
||||
if (gui == EnumGuiType.PlayerFollower || gui == EnumGuiType.PlayerFollowerHire || gui == EnumGuiType.PlayerTrader || gui == EnumGuiType.PlayerTransporter) {
|
||||
sendRoleData(player, npc);
|
||||
@@ -640,7 +613,7 @@ public class NoppesUtilServer {
|
||||
playerdata.save();
|
||||
}
|
||||
if (pl != null) {
|
||||
SyncController.syncPlayer((EntityPlayerMP) pl);
|
||||
SyncController.dispatchSyncForAllTypes((EntityPlayerMP) pl);
|
||||
}
|
||||
sendPlayerData(type, player, name);
|
||||
}
|
||||
@@ -1229,7 +1202,7 @@ public class NoppesUtilServer {
|
||||
playerdata.save();
|
||||
|
||||
if (pl != null) {
|
||||
SyncController.syncPlayer((EntityPlayerMP) pl);
|
||||
SyncController.dispatchSyncForAllTypes((EntityPlayerMP) pl);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1261,7 +1234,7 @@ public class NoppesUtilServer {
|
||||
|
||||
playerdata.save();
|
||||
if (pl != null) {
|
||||
SyncController.syncPlayer((EntityPlayerMP) pl);
|
||||
SyncController.dispatchSyncForAllTypes((EntityPlayerMP) pl);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,9 @@ import kamkeel.npcs.addon.DBCAddon;
|
||||
import kamkeel.npcs.controllers.AbilityController;
|
||||
import kamkeel.npcs.controllers.AttributeController;
|
||||
import kamkeel.npcs.controllers.data.attribute.tracker.PlayerAttributeTracker;
|
||||
import kamkeel.npcs.controllers.SyncController;
|
||||
import kamkeel.npcs.controllers.sync.handlers.PlayerAbilitySyncHelper;
|
||||
import kamkeel.npcs.controllers.sync.handlers.PlayerDataSyncHandler;
|
||||
import kamkeel.npcs.controllers.sync.handlers.PlayerEffectSyncHelper;
|
||||
import kamkeel.npcs.controllers.data.ability.Ability;
|
||||
import kamkeel.npcs.controllers.data.ability.type.AbilityCounter;
|
||||
import kamkeel.npcs.controllers.data.ability.type.AbilityDefend;
|
||||
@@ -141,7 +143,7 @@ public class ScriptPlayerEventHandler {
|
||||
}
|
||||
|
||||
if (playerData.updateClient) {
|
||||
SyncController.syncPlayerData((EntityPlayerMP) player, true);
|
||||
PlayerDataSyncHandler.syncPlayerData((EntityPlayerMP) player, true);
|
||||
playerData.updateClient = false;
|
||||
}
|
||||
|
||||
@@ -151,8 +153,8 @@ public class ScriptPlayerEventHandler {
|
||||
|
||||
if (player.ticksExisted % 10 == 0) {
|
||||
EntityPlayerMP mp = (EntityPlayerMP) player;
|
||||
SyncController.syncEffects(mp);
|
||||
SyncController.syncAbilityCooldowns(mp);
|
||||
PlayerEffectSyncHelper.syncEffects(mp);
|
||||
PlayerAbilitySyncHelper.syncAbilityCooldowns(mp);
|
||||
PlayerAbilitySyncPacket.sendToPlayer(mp);
|
||||
playerData.abilityData.ensureLockStateClear();
|
||||
}
|
||||
|
||||
@@ -4,13 +4,15 @@ import cpw.mods.fml.common.FMLCommonHandler;
|
||||
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import kamkeel.npcs.controllers.SyncController;
|
||||
import kamkeel.npcs.controllers.sync.handlers.CarpentryRecipeSyncHandler;
|
||||
import kamkeel.npcs.controllers.sync.handlers.WorkbenchRecipeSyncHandler;
|
||||
import kamkeel.npcs.controllers.data.energycharge.EnergyChargeTracker;
|
||||
import kamkeel.npcs.entity.EntityEnergyBarrier;
|
||||
import kamkeel.npcs.entity.EntityEnergyDome;
|
||||
import kamkeel.npcs.network.PacketHandler;
|
||||
import kamkeel.npcs.network.enums.EnumSoundOperation;
|
||||
import kamkeel.npcs.network.enums.EnumSyncAction;
|
||||
import kamkeel.npcs.network.enums.EnumSyncType;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import kamkeel.npcs.network.packets.data.ClonerPacket;
|
||||
import kamkeel.npcs.network.packets.data.MarkDataPacket;
|
||||
import kamkeel.npcs.network.packets.data.SoundManagementPacket;
|
||||
@@ -136,7 +138,7 @@ public class ServerEventsHandler {
|
||||
mounted = event.target;
|
||||
if (isRemote)
|
||||
CustomNpcs.proxy.openGui(MathHelper.floor_double(mounted.posX), MathHelper.floor_double(mounted.posY), MathHelper.floor_double(mounted.posZ), EnumGuiType.MobSpawnerMounter, event.entityPlayer);
|
||||
} else if (item.getItem() == CustomItems.wand && !isRemote && event.target instanceof EntityVillager) {
|
||||
} else if (item.getItem() == CustomItems.wand && event.target instanceof EntityVillager) {
|
||||
if (!CustomNpcsPermissions.hasPermission(event.entityPlayer, CustomNpcsPermissions.EDIT_VILLAGER))
|
||||
return;
|
||||
event.setCanceled(true);
|
||||
@@ -255,20 +257,22 @@ public class ServerEventsHandler {
|
||||
|
||||
if (block == Blocks.crafting_table && event.action == Action.RIGHT_CLICK_BLOCK && !player.worldObj.isRemote) {
|
||||
PacketHandler.Instance.sendToPlayer(new SyncPacket(
|
||||
EnumSyncType.WORKBENCH_RECIPES,
|
||||
SyncType.WORKBENCH_RECIPES,
|
||||
EnumSyncAction.RELOAD,
|
||||
-1,
|
||||
SyncController.getCurrentRevision(EnumSyncType.WORKBENCH_RECIPES),
|
||||
SyncController.workbenchNBT()
|
||||
null,
|
||||
SyncController.getCurrentServerRevision(SyncType.WORKBENCH_RECIPES),
|
||||
WorkbenchRecipeSyncHandler.getInstance().serializeAll()
|
||||
), (EntityPlayerMP) player);
|
||||
}
|
||||
if (block == CustomItems.carpentyBench && event.action == Action.RIGHT_CLICK_BLOCK && !player.worldObj.isRemote) {
|
||||
PacketHandler.Instance.sendToPlayer(new SyncPacket(
|
||||
EnumSyncType.CARPENTRY_RECIPES,
|
||||
SyncType.CARPENTRY_RECIPES,
|
||||
EnumSyncAction.RELOAD,
|
||||
-1,
|
||||
SyncController.getCurrentRevision(EnumSyncType.CARPENTRY_RECIPES),
|
||||
SyncController.carpentryNBT()
|
||||
null,
|
||||
SyncController.getCurrentServerRevision(SyncType.CARPENTRY_RECIPES),
|
||||
CarpentryRecipeSyncHandler.getInstance().serializeAll()
|
||||
), (EntityPlayerMP) player);
|
||||
}
|
||||
if ((block == CustomItems.banner || block == CustomItems.wallBanner || block == CustomItems.sign) && event.action == Action.RIGHT_CLICK_BLOCK) {
|
||||
|
||||
@@ -6,6 +6,8 @@ import cpw.mods.fml.common.gameevent.TickEvent;
|
||||
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
|
||||
import kamkeel.npcs.controllers.ProfileController;
|
||||
import kamkeel.npcs.controllers.SyncController;
|
||||
import kamkeel.npcs.controllers.sync.handlers.PlayerAbilitySyncHelper;
|
||||
import kamkeel.npcs.controllers.sync.handlers.PlayerEffectSyncHelper;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.world.WorldServer;
|
||||
import noppes.npcs.controllers.AuctionController;
|
||||
@@ -45,13 +47,12 @@ public class ServerTickHandler {
|
||||
playerData.onLogin();
|
||||
}
|
||||
|
||||
ProfileController.Instance.login(player);
|
||||
SyncController.beginLogin(player);
|
||||
SyncController.syncEffects(player);
|
||||
PlayerEffectSyncHelper.syncEffects(player);
|
||||
ScriptController.Instance.syncClientScripts(player);
|
||||
|
||||
// Sync clean ability state to the new client (after beginLogin initializes sync state)
|
||||
SyncController.syncAbilities(player);
|
||||
PlayerAbilitySyncHelper.syncAbilities(player);
|
||||
|
||||
// Send auction notifications on login
|
||||
if (AuctionController.Instance != null) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import net.minecraft.nbt.NBTBase;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagInt;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.constants.EnumPotionType;
|
||||
import noppes.npcs.controllers.data.Line;
|
||||
import noppes.npcs.controllers.data.Lines;
|
||||
import noppes.npcs.entity.EntityNPCInterface;
|
||||
@@ -23,6 +24,13 @@ public class VersionCompatibility {
|
||||
boolean aimShot = compound.getBoolean("AimWhileShooting");
|
||||
compound.setInteger("AimType", !aimShot ? 0 : 1);
|
||||
}
|
||||
|
||||
// Restore burning on Fire projectiles saved before pBurnItem existed
|
||||
if (compound.hasKey("pEffect") && !compound.hasKey("pBurnItem")) {
|
||||
if (EnumPotionType.fromOrdinal(compound.getInteger("pEffect")) == EnumPotionType.Fire) {
|
||||
compound.setBoolean("pBurnItem", true);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (npc.npcVersion < 22) {
|
||||
if (compound.hasKey("CanLeap")) {
|
||||
|
||||
@@ -10,7 +10,7 @@ public class EntityAITransform extends EntityAIBase {
|
||||
|
||||
public EntityAITransform(EntityNPCInterface npc) {
|
||||
this.npc = npc;
|
||||
setMutexBits(AiMutex.PASSIVE);
|
||||
setMutexBits(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -67,10 +67,6 @@ public class BlockBorder extends BlockContainer {
|
||||
}
|
||||
|
||||
tile.rotation = l;
|
||||
|
||||
if (par5EntityLivingBase instanceof EntityPlayer && par1World.isRemote) {
|
||||
CustomNpcs.proxy.openGui(x, y, z, EnumGuiType.Border, (EntityPlayer) par5EntityLivingBase);
|
||||
}
|
||||
}
|
||||
|
||||
private TileBorder getTile(World world, int x, int y, int z) {
|
||||
|
||||
@@ -40,7 +40,6 @@ public class BlockCampfire extends BlockLightable {
|
||||
ItemStack item = player.inventory.getCurrentItem();
|
||||
if (item == null)
|
||||
return true;
|
||||
int meta = world.getBlockMetadata(x, y, z);
|
||||
|
||||
if ((item.getItem() == Items.flint || item.getItem() == Items.flint_and_steel) && unlitBlock() == this) {
|
||||
super.onBlockActivated(world, x, y, z, player, par6, par7, par8, par9);
|
||||
|
||||
@@ -49,13 +49,6 @@ public class BlockNpcRedstone extends BlockContainer {
|
||||
par1World.notifyBlocksOfNeighborChange(par2, par3, par4 + 1, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBlockPlacedBy(World world, int i, int j, int k, EntityLivingBase entityliving, ItemStack item) {
|
||||
if (entityliving instanceof EntityPlayer && world.isRemote) {
|
||||
CustomNpcs.proxy.openGui(i, j, k, EnumGuiType.RedstoneBlock, (EntityPlayer) entityliving);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBlockDestroyedByPlayer(World par1World, int par2, int par3, int par4, int par5) {
|
||||
onBlockAdded(par1World, par2, par3, par4);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package noppes.npcs.client;
|
||||
|
||||
import kamkeel.npcs.network.enums.EnumSyncType;
|
||||
import kamkeel.npcs.network.enums.SyncType;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import noppes.npcs.client.controllers.MusicController;
|
||||
@@ -18,8 +18,8 @@ import noppes.npcs.controllers.data.PlayerData;
|
||||
import noppes.npcs.controllers.data.SkinOverlay;
|
||||
import noppes.npcs.util.CacheHashMap;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -32,14 +32,14 @@ public class ClientCacheHandler {
|
||||
|
||||
private static String activeServerKey = "";
|
||||
private static String lastServerKey = "";
|
||||
private static final Map<String, EnumMap<EnumSyncType, Integer>> clientRevisionCache = new HashMap<>();
|
||||
private static final Map<String, Map<SyncType, Integer>> clientRevisionCache = new HashMap<>();
|
||||
|
||||
public static Party party;
|
||||
|
||||
public static boolean allowProfiles = true;
|
||||
public static boolean allowParties = true;
|
||||
|
||||
public static void setActiveServer(String serverKey, EnumMap<EnumSyncType, Integer> serverRevisions) {
|
||||
public static void setActiveServer(String serverKey, Map<SyncType, Integer> serverRevisions) {
|
||||
String normalizedKey = serverKey == null ? "" : serverKey;
|
||||
String previousKey = activeServerKey == null ? "" : activeServerKey;
|
||||
lastServerKey = previousKey;
|
||||
@@ -54,9 +54,9 @@ public class ClientCacheHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
EnumMap<EnumSyncType, Integer> cached = clientRevisionCache.computeIfAbsent(
|
||||
Map<SyncType, Integer> cached = clientRevisionCache.computeIfAbsent(
|
||||
activeServerKey,
|
||||
ignored -> new EnumMap<>(EnumSyncType.class)
|
||||
ignored -> new LinkedHashMap<>()
|
||||
);
|
||||
if (serverRevisions != null && !serverRevisions.isEmpty()) {
|
||||
cached.keySet().retainAll(serverRevisions.keySet());
|
||||
@@ -67,19 +67,19 @@ public class ClientCacheHandler {
|
||||
return lastServerKey == null ? "" : lastServerKey;
|
||||
}
|
||||
|
||||
public static EnumMap<EnumSyncType, Integer> getCachedRevisionsForServer(String serverKey) {
|
||||
public static Map<SyncType, Integer> getCachedRevisionsForServer(String serverKey) {
|
||||
String key = serverKey == null ? "" : serverKey;
|
||||
if (key.isEmpty()) {
|
||||
return new EnumMap<>(EnumSyncType.class);
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
EnumMap<EnumSyncType, Integer> revisions = clientRevisionCache.get(key);
|
||||
Map<SyncType, Integer> revisions = clientRevisionCache.get(key);
|
||||
if (revisions == null) {
|
||||
return new EnumMap<>(EnumSyncType.class);
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
return new EnumMap<>(revisions);
|
||||
return new LinkedHashMap<>(revisions);
|
||||
}
|
||||
|
||||
public static void updateClientRevision(EnumSyncType type, int revision) {
|
||||
public static void updateClientRevision(SyncType type, int revision) {
|
||||
if (revision < 0) {
|
||||
return;
|
||||
}
|
||||
@@ -87,9 +87,9 @@ public class ClientCacheHandler {
|
||||
if (key.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
EnumMap<EnumSyncType, Integer> revisions = clientRevisionCache.computeIfAbsent(
|
||||
Map<SyncType, Integer> revisions = clientRevisionCache.computeIfAbsent(
|
||||
key,
|
||||
ignored -> new EnumMap<>(EnumSyncType.class)
|
||||
ignored -> new LinkedHashMap<>()
|
||||
);
|
||||
revisions.put(type, revision);
|
||||
}
|
||||
@@ -126,14 +126,11 @@ public class ClientCacheHandler {
|
||||
ClientCacheHandler.playerAnimations.clear();
|
||||
ProfileClientConfig.reset();
|
||||
|
||||
// Clear Texture Caches
|
||||
GuiSoundSelection.cachedDomains.clear();
|
||||
GuiTextureSelection.cachedTextures.clear();
|
||||
|
||||
// Clear music/bard sounds
|
||||
MusicController.Instance.stopAllSounds();
|
||||
|
||||
// Clear Quest Tracker
|
||||
HudComponent component = ClientHudManager.getInstance().getHudComponents().get(EnumHudComponent.QuestTracker);
|
||||
if (component != null) {
|
||||
component.loadData(new NBTTagCompound());
|
||||
@@ -146,7 +143,6 @@ public class ClientCacheHandler {
|
||||
ClientCacheHandler.customOverlays.clear();
|
||||
ClientCacheHandler.skinOverlays.clear();
|
||||
|
||||
// Clear Texture Caches
|
||||
GuiSoundSelection.cachedDomains.clear();
|
||||
GuiTextureSelection.cachedTextures.clear();
|
||||
}
|
||||
|
||||
@@ -344,7 +344,6 @@ public class ClientProxy extends CommonProxy {
|
||||
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(CustomItems.shortLamp), new ItemShortLampRenderer());
|
||||
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(CustomItems.tallLamp), new ItemTallLampRenderer());
|
||||
}
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
|
||||
NPCButton = new KeyBinding("NPC Inventory", Keyboard.KEY_N, "key.categories.customnpc");
|
||||
SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_GRAVE, "key.categories.customnpc");
|
||||
@@ -384,14 +383,6 @@ public class ClientProxy extends CommonProxy {
|
||||
|
||||
// Lightning effect rendering system
|
||||
MinecraftForge.EVENT_BUS.register(new LightningHandler());
|
||||
|
||||
if (ConfigClient.InventoryGuiEnabled) {
|
||||
MinecraftForge.EVENT_BUS.register(new TabRegistry());
|
||||
if (TabRegistry.getTabList().isEmpty()) {
|
||||
TabRegistry.registerTab(new InventoryTabVanilla());
|
||||
}
|
||||
TabRegistry.registerTab(new InventoryTabCustomNpc());
|
||||
}
|
||||
}
|
||||
|
||||
public FakePlayer getCommandPlayer(IWorld world) {
|
||||
@@ -720,9 +711,7 @@ public class ClientProxy extends CommonProxy {
|
||||
if (!player.worldObj.isRemote || !(guiscreen instanceof GuiScreen))
|
||||
return;
|
||||
|
||||
if (guiscreen != null) {
|
||||
minecraft.displayGuiScreen((GuiScreen) guiscreen);
|
||||
}
|
||||
minecraft.displayGuiScreen((GuiScreen) guiscreen);
|
||||
}
|
||||
|
||||
|
||||
@@ -817,8 +806,7 @@ public class ClientProxy extends CommonProxy {
|
||||
if (location == null)
|
||||
return;
|
||||
TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager();
|
||||
if (location != null)
|
||||
texturemanager.bindTexture((ResourceLocation) location);
|
||||
texturemanager.bindTexture((ResourceLocation) location);
|
||||
} catch (NullPointerException ex) {
|
||||
|
||||
} catch (ReportedException ex) {
|
||||
@@ -862,6 +850,18 @@ public class ClientProxy extends CommonProxy {
|
||||
return Minecraft.getMinecraft().currentScreen != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadComplete() {
|
||||
// Deferred from load() so TConstruct registers its tabs first
|
||||
if (ConfigClient.InventoryGuiEnabled) {
|
||||
MinecraftForge.EVENT_BUS.register(new TabRegistry());
|
||||
if (TabRegistry.getTabList().isEmpty()) {
|
||||
TabRegistry.registerTab(new InventoryTabVanilla());
|
||||
}
|
||||
TabRegistry.registerTab(new InventoryTabCustomNpc());
|
||||
}
|
||||
}
|
||||
|
||||
public void buildPackageIndex() {
|
||||
try {
|
||||
PackageFinder.init(Thread.currentThread().getContextClassLoader());
|
||||
|
||||
@@ -38,6 +38,7 @@ import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.Vector;
|
||||
|
||||
public class NoppesUtil {
|
||||
@@ -51,11 +52,15 @@ public class NoppesUtil {
|
||||
}
|
||||
|
||||
public static void updateSkinOverlayData(EntityPlayer player, NBTTagCompound compound) {
|
||||
updateSkinOverlayData(player.getUniqueID(), compound);
|
||||
}
|
||||
|
||||
public static void updateSkinOverlayData(UUID playerUUID, NBTTagCompound compound) {
|
||||
HashMap<Integer, SkinOverlay> skinOverlays = new HashMap<>();
|
||||
HashMap<Integer, SkinOverlay> oldOverlays = new HashMap<>();
|
||||
NBTTagList skinOverlayList = compound.getTagList("SkinOverlayData", 10);
|
||||
if (ClientCacheHandler.skinOverlays.containsKey(player.getUniqueID())) {
|
||||
oldOverlays = ClientCacheHandler.skinOverlays.get(player.getUniqueID());
|
||||
if (ClientCacheHandler.skinOverlays.containsKey(playerUUID)) {
|
||||
oldOverlays = ClientCacheHandler.skinOverlays.get(playerUUID);
|
||||
}
|
||||
|
||||
for (int i = 0; i < skinOverlayList.tagCount(); i++) {
|
||||
@@ -66,7 +71,7 @@ public class NoppesUtil {
|
||||
}
|
||||
skinOverlays.put(tagID, overlay);
|
||||
}
|
||||
ClientCacheHandler.skinOverlays.put(player.getUniqueID(), skinOverlays);
|
||||
ClientCacheHandler.skinOverlays.put(playerUUID, skinOverlays);
|
||||
}
|
||||
|
||||
public static void clickSound() {
|
||||
|
||||
@@ -127,7 +127,6 @@ public class GuiNpcMobSpawnerMounter extends GuiNPCInterface implements IGuiData
|
||||
return;
|
||||
}
|
||||
|
||||
ArrayList<String> list = new ArrayList<String>();
|
||||
this.list = ClientCloneController.Instance.getClones(activeTab);
|
||||
scroll.setList(getSearchList());
|
||||
}
|
||||
|
||||
@@ -8,22 +8,26 @@ import net.minecraft.nbt.NBTTagDouble;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import noppes.npcs.client.controllers.ClientCloneController;
|
||||
import noppes.npcs.client.gui.util.GuiCustomScroll;
|
||||
import noppes.npcs.client.gui.util.GuiMenuSideButton;
|
||||
import noppes.npcs.client.gui.util.GuiNpcButton;
|
||||
import noppes.npcs.client.gui.util.GuiNpcTextField;
|
||||
import noppes.npcs.client.gui.util.ICustomScrollListener;
|
||||
import noppes.npcs.client.gui.util.IGuiData;
|
||||
import noppes.npcs.client.gui.util.SubGuiInterface;
|
||||
import noppes.npcs.controllers.data.CloneFolder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiData {
|
||||
public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiData, ICustomScrollListener {
|
||||
|
||||
private GuiCustomScroll scroll;
|
||||
private GuiCustomScroll navScroll;
|
||||
private List<String> list;
|
||||
private List<String> navList = new ArrayList<String>();
|
||||
|
||||
private static String search = "";
|
||||
public int activeTab = 1;
|
||||
public String activeFolder = null;
|
||||
public boolean isServer = false;
|
||||
|
||||
public GuiNpcMobSpawnerSelector() {
|
||||
@@ -50,40 +54,62 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
|
||||
addButton(new GuiNpcButton(0, guiLeft + 171, guiTop + 80, 80, 20, "gui.done"));
|
||||
addButton(new GuiNpcButton(1, guiLeft + 171, guiTop + 103, 80, 20, "gui.cancel"));
|
||||
|
||||
addSideButton(new GuiMenuSideButton(21, guiLeft - 90, this.guiTop + 2, 90, 22, "1"));
|
||||
addSideButton(new GuiMenuSideButton(22, guiLeft - 90, this.guiTop + 23, 90, 22, "2"));
|
||||
addSideButton(new GuiMenuSideButton(23, guiLeft - 90, this.guiTop + 44, 90, 22, "3"));
|
||||
addSideButton(new GuiMenuSideButton(24, guiLeft - 90, this.guiTop + 65, 90, 22, "4"));
|
||||
addSideButton(new GuiMenuSideButton(25, guiLeft - 90, this.guiTop + 86, 90, 22, "5"));
|
||||
addSideButton(new GuiMenuSideButton(26, guiLeft - 45, this.guiTop + 107, 45, 22, "6"));
|
||||
addSideButton(new GuiMenuSideButton(27, guiLeft - 90, this.guiTop + 107, 45, 22, "7"));
|
||||
addSideButton(new GuiMenuSideButton(28, guiLeft - 45, this.guiTop + 128, 45, 22, "8"));
|
||||
addSideButton(new GuiMenuSideButton(29, guiLeft - 90, this.guiTop + 128, 45, 22, "9"));
|
||||
addSideButton(new GuiMenuSideButton(30, guiLeft - 45, this.guiTop + 149, 45, 22, "10"));
|
||||
addSideButton(new GuiMenuSideButton(31, guiLeft - 90, this.guiTop + 149, 45, 22, "11"));
|
||||
addSideButton(new GuiMenuSideButton(32, guiLeft - 45, this.guiTop + 170, 45, 22, "12"));
|
||||
addSideButton(new GuiMenuSideButton(33, guiLeft - 90, this.guiTop + 170, 45, 22, "13"));
|
||||
addSideButton(new GuiMenuSideButton(34, guiLeft - 45, this.guiTop + 191, 45, 22, "14"));
|
||||
addSideButton(new GuiMenuSideButton(35, guiLeft - 90, this.guiTop + 191, 45, 22, "15"));
|
||||
// Navigation scroll (tabs + folders) replacing hardcoded side buttons
|
||||
buildNavList();
|
||||
if (navScroll == null) {
|
||||
navScroll = new GuiCustomScroll(this, 1);
|
||||
} else {
|
||||
navScroll.clear();
|
||||
}
|
||||
navScroll.setSize(90, 210);
|
||||
navScroll.guiLeft = guiLeft - 94;
|
||||
navScroll.guiTop = guiTop + 2;
|
||||
navScroll.setList(navList);
|
||||
navScroll.setSelected(getNavSelection());
|
||||
addScroll(navScroll);
|
||||
|
||||
getSideButton(20 + activeTab).active = true;
|
||||
showClones();
|
||||
}
|
||||
|
||||
private void buildNavList() {
|
||||
navList.clear();
|
||||
for (int i = 1; i <= 15; i++) {
|
||||
navList.add("Tab " + i);
|
||||
}
|
||||
if (ClientCloneController.Instance != null) {
|
||||
for (CloneFolder folder : ClientCloneController.Instance.getFolderList()) {
|
||||
navList.add(folder.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String getNavSelection() {
|
||||
if (activeFolder != null) return activeFolder;
|
||||
if (activeTab >= 1 && activeTab <= 15) return "Tab " + activeTab;
|
||||
return "Tab 1";
|
||||
}
|
||||
|
||||
public String getSelected() {
|
||||
return scroll.getSelected();
|
||||
}
|
||||
|
||||
private void showClones() {
|
||||
|
||||
if (isServer) {
|
||||
PacketClient.sendClient(new CloneListPacket(activeTab));
|
||||
if (activeFolder != null) {
|
||||
PacketClient.sendClient(new CloneListPacket(activeFolder));
|
||||
} else {
|
||||
PacketClient.sendClient(new CloneListPacket(activeTab));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ArrayList<String> list = new ArrayList<String>();
|
||||
|
||||
this.list = new ArrayList<String>(ClientCloneController.Instance.getClones(activeTab));
|
||||
if (activeFolder != null && ClientCloneController.Instance != null) {
|
||||
this.list = new ArrayList<String>(ClientCloneController.Instance.getClones(activeFolder));
|
||||
} else if (ClientCloneController.Instance != null) {
|
||||
this.list = new ArrayList<String>(ClientCloneController.Instance.getClones(activeTab));
|
||||
} else {
|
||||
this.list = new ArrayList<String>();
|
||||
}
|
||||
scroll.setList(getSearchList());
|
||||
}
|
||||
|
||||
@@ -97,6 +123,7 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
|
||||
}
|
||||
|
||||
private List<String> getSearchList() {
|
||||
if (list == null) list = new ArrayList<String>();
|
||||
if (search.isEmpty())
|
||||
return new ArrayList<String>(list);
|
||||
List<String> list = new ArrayList<String>();
|
||||
@@ -112,8 +139,15 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
|
||||
if (sel == null)
|
||||
return null;
|
||||
|
||||
NBTTagCompound compound = ClientCloneController.Instance.getCloneData(player, sel, activeTab);
|
||||
compound.setString("ClonedName", sel);
|
||||
NBTTagCompound compound;
|
||||
if (activeFolder != null && ClientCloneController.Instance != null) {
|
||||
compound = ClientCloneController.Instance.getCloneData(player, sel, activeFolder);
|
||||
} else {
|
||||
compound = ClientCloneController.Instance.getCloneData(player, sel, activeTab);
|
||||
}
|
||||
if (compound != null) {
|
||||
compound.setString("ClonedName", sel);
|
||||
}
|
||||
return compound;
|
||||
}
|
||||
|
||||
@@ -126,9 +160,28 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
|
||||
scroll.clear();
|
||||
close();
|
||||
}
|
||||
if (id > 20) {
|
||||
activeTab = id - 20;
|
||||
initGui();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
|
||||
if (guiCustomScroll.id == 1) {
|
||||
String selected = navScroll.getSelected();
|
||||
if (selected == null) return;
|
||||
|
||||
if (selected.startsWith("Tab ")) {
|
||||
try {
|
||||
int tabNum = Integer.parseInt(selected.substring(4));
|
||||
if (tabNum >= 1 && tabNum <= 15) {
|
||||
activeTab = tabNum;
|
||||
activeFolder = null;
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
} else {
|
||||
activeFolder = selected;
|
||||
activeTab = -1;
|
||||
}
|
||||
showClones();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -112,19 +112,19 @@ public class SubGuiNpcAvailabilityDialog extends SubGuiInterface implements GuiS
|
||||
}
|
||||
if (button.id == 10) {
|
||||
slot = 1;
|
||||
setSubGui(new GuiDialogSelection(availabitily.questId));
|
||||
setSubGui(new GuiDialogSelection(availabitily.dialogId));
|
||||
}
|
||||
if (button.id == 11) {
|
||||
slot = 2;
|
||||
setSubGui(new GuiDialogSelection(availabitily.quest2Id));
|
||||
setSubGui(new GuiDialogSelection(availabitily.dialog2Id));
|
||||
}
|
||||
if (button.id == 12) {
|
||||
slot = 3;
|
||||
setSubGui(new GuiDialogSelection(availabitily.quest3Id));
|
||||
setSubGui(new GuiDialogSelection(availabitily.dialog3Id));
|
||||
}
|
||||
if (button.id == 13) {
|
||||
slot = 4;
|
||||
setSubGui(new GuiDialogSelection(availabitily.quest4Id));
|
||||
setSubGui(new GuiDialogSelection(availabitily.dialog4Id));
|
||||
}
|
||||
if (button.id == 20) {
|
||||
availabitily.dialogId = -1;
|
||||
|
||||
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user