diff --git a/src/main/java/net/citizensnpcs/Citizens.java b/src/main/java/net/citizensnpcs/Citizens.java index 6f2693c94..46c124b0a 100644 --- a/src/main/java/net/citizensnpcs/Citizens.java +++ b/src/main/java/net/citizensnpcs/Citizens.java @@ -62,8 +62,8 @@ public class Citizens extends JavaPlugin implements CitizensPlugin { private CitizensNPCRegistry npcRegistry; private NPCDataStore saves; private NPCSelector selector; - private CitizensTraitFactory traitFactory; private CitizensSpeechFactory speechFactory; + private CitizensTraitFactory traitFactory; private void despawnNPCs() { Iterator itr = npcRegistry.iterator(); @@ -131,13 +131,13 @@ public class Citizens extends JavaPlugin implements CitizensPlugin { } @Override - public TraitFactory getTraitFactory() { - return traitFactory; + public SpeechFactory getSpeechFactory() { + return speechFactory; } @Override - public SpeechFactory getSpeechFactory() { - return speechFactory; + public TraitFactory getTraitFactory() { + return traitFactory; } @Override diff --git a/src/main/java/net/citizensnpcs/EventListen.java b/src/main/java/net/citizensnpcs/EventListen.java index fa6238ad7..f6d7d8740 100644 --- a/src/main/java/net/citizensnpcs/EventListen.java +++ b/src/main/java/net/citizensnpcs/EventListen.java @@ -69,21 +69,13 @@ public class EventListen implements Listener { /* * Chunk events */ - @EventHandler(ignoreCancelled = true) + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onChunkLoad(ChunkLoadEvent event) { ChunkCoord coord = toCoord(event.getChunk()); - List ids = toRespawn.get(coord); - for (int i = 0; i < ids.size(); i++) { - int id = ids.get(i); - boolean success = spawn(id); - if (!success) - continue; - ids.remove(i); - Messaging.debug("Spawned", id, "due to chunk load at [" + coord.x + "," + coord.z + "]"); - } + respawnAllFromCoord(coord); } - @EventHandler(ignoreCancelled = true) + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onChunkUnload(ChunkUnloadEvent event) { ChunkCoord coord = toCoord(event.getChunk()); Location location = new Location(null, 0, 0, 0); @@ -93,13 +85,15 @@ public class EventListen implements Listener { location = npc.getBukkitEntity().getLocation(location); boolean sameChunkCoordinates = coord.z == location.getBlockZ() >> 4 && coord.x == location.getBlockX() >> 4; if (sameChunkCoordinates && event.getWorld().equals(location.getWorld())) { - npc.despawn(DespawnReason.CHUNK_UNLOAD); - if (event.getChunk().isLoaded()) { - toRespawn.removeAll(coord); + if (!npc.despawn(DespawnReason.CHUNK_UNLOAD)) { + event.setCancelled(true); + Messaging.debug("Cancelled chunk unload at [" + coord.x + "," + coord.z + "]"); + respawnAllFromCoord(coord); return; } toRespawn.put(coord, npc.getId()); - Messaging.debug("Despawned", npc.getId(), "due to chunk unload at [" + coord.x + "," + coord.z + "]"); + Messaging.debug("Despawned id ", npc.getId(), "due to chunk unload at [" + coord.x + "," + coord.z + + "]"); } } } @@ -189,10 +183,6 @@ public class EventListen implements Listener { // undesirable as player NPCs are not real players and confuse plugins. } - /* - * Player events - */ - @EventHandler(ignoreCancelled = true) public void onPlayerCreateNPC(PlayerCreateNPCEvent event) { if (event.getCreator().hasPermission("citizens.admin.avoid-limits")) @@ -219,6 +209,10 @@ public class EventListen implements Listener { } } + /* + * Player events + */ + @EventHandler public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { NPC npc = npcRegistry.getNPC(event.getRightClicked()); @@ -232,7 +226,7 @@ public class EventListen implements Listener { Bukkit.getPluginManager().callEvent(rightClickEvent); } - @EventHandler(ignoreCancelled = true) + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerQuit(PlayerQuitEvent event) { Editor.leave(event.getPlayer()); } @@ -255,17 +249,34 @@ public class EventListen implements Listener { } } - @EventHandler(ignoreCancelled = true) + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onWorldUnload(WorldUnloadEvent event) { for (NPC npc : npcRegistry) { if (!npc.isSpawned() || !npc.getBukkitEntity().getWorld().equals(event.getWorld())) continue; storeForRespawn(npc); - npc.despawn(); + npc.despawn(DespawnReason.WORLD_UNLOAD); + if (event.isCancelled()) + return; Messaging.debug("Despawned", npc.getId() + "due to world unload at", event.getWorld().getName()); } } + private void respawnAllFromCoord(ChunkCoord coord) { + List ids = toRespawn.get(coord); + for (int i = 0; i < ids.size(); i++) { + int id = ids.get(i); + boolean success = spawn(id); + if (!success) { + Messaging.debug("Couldn't respawn id " + id + " during chunk event at [" + coord.x + "," + coord.z + + "]"); + continue; + } + ids.remove(i); + Messaging.debug("Spawned id ", id, "due to chunk event at [" + coord.x + "," + coord.z + "]"); + } + } + private boolean spawn(int id) { NPC npc = npcRegistry.getById(id); if (npc == null) diff --git a/src/main/java/net/citizensnpcs/NPCDataStore.java b/src/main/java/net/citizensnpcs/NPCDataStore.java index 103ddff43..52bc7fac9 100644 --- a/src/main/java/net/citizensnpcs/NPCDataStore.java +++ b/src/main/java/net/citizensnpcs/NPCDataStore.java @@ -28,6 +28,27 @@ public class NPCDataStore { root = saves; } + public void addPlotters(Graph graph) { + graph.addPlotter(new Plotter("Database") { + @Override + public int getValue() { + return root instanceof DatabaseStorage ? 1 : 0; + } + }); + graph.addPlotter(new Plotter("YAML") { + @Override + public int getValue() { + return root instanceof YamlStorage ? 1 : 0; + } + }); + graph.addPlotter(new Plotter("NBT") { + @Override + public int getValue() { + return root instanceof NBTStorage ? 1 : 0; + } + }); + } + public void loadInto(CitizensNPCRegistry registry) { int created = 0; for (DataKey key : root.getKey("npc").getIntegerSubKeys()) { @@ -81,16 +102,14 @@ public class NPCDataStore { String type = Setting.STORAGE_TYPE.asString(); if (type.equalsIgnoreCase("db") || type.equalsIgnoreCase("database")) { try { - saves = new DatabaseStorage(Setting.DATABASE_DRIVER.asString(), - Setting.DATABASE_URL.asString(), Setting.DATABASE_USERNAME.asString(), - Setting.DATABASE_PASSWORD.asString()); + saves = new DatabaseStorage(Setting.DATABASE_DRIVER.asString(), Setting.DATABASE_URL.asString(), + Setting.DATABASE_USERNAME.asString(), Setting.DATABASE_PASSWORD.asString()); } catch (SQLException e) { e.printStackTrace(); Messaging.logTr(Messages.DATABASE_CONNECTION_FAILED); } } else if (type.equalsIgnoreCase("nbt")) { - saves = new NBTStorage(folder + File.separator + Setting.STORAGE_FILE.asString(), - "Citizens NPC Storage"); + saves = new NBTStorage(folder + File.separator + Setting.STORAGE_FILE.asString(), "Citizens NPC Storage"); } if (saves == null) saves = new YamlStorage(new File(folder, Setting.STORAGE_FILE.asString()), "Citizens NPC Storage"); @@ -98,25 +117,4 @@ public class NPCDataStore { return null; return new NPCDataStore(saves); } - - public void addPlotters(Graph graph) { - graph.addPlotter(new Plotter("Database") { - @Override - public int getValue() { - return root instanceof DatabaseStorage ? 1 : 0; - } - }); - graph.addPlotter(new Plotter("YAML") { - @Override - public int getValue() { - return root instanceof YamlStorage ? 1 : 0; - } - }); - graph.addPlotter(new Plotter("NBT") { - @Override - public int getValue() { - return root instanceof NBTStorage ? 1 : 0; - } - }); - } } diff --git a/src/main/java/net/citizensnpcs/Settings.java b/src/main/java/net/citizensnpcs/Settings.java index 554b3eb14..711a79e1a 100644 --- a/src/main/java/net/citizensnpcs/Settings.java +++ b/src/main/java/net/citizensnpcs/Settings.java @@ -43,14 +43,16 @@ public class Settings { } public enum Setting { - CHAT_FORMAT("npc.chat.format.no-targets", "[]: "), - CHAT_FORMAT_TO_TARGET("npc.chat.format.to-target", "[] -> You: "), - CHAT_FORMAT_TO_BYSTANDERS("npc.chat.format.with-target-to-bystanders", "[] -> []: "), - CHAT_FORMAT_WITH_TARGETS_TO_BYSTANDERS("npc.chat.format.with-targets-to-bystanders", "[] -> []: "), - CHAT_RANGE("npc.chat.options.range", 5), CHAT_BYSTANDERS_HEAR_TARGETED_CHAT("npc.chat.options.bystanders-hear-targeted-chat", true), + CHAT_FORMAT("npc.chat.format.no-targets", "[]: "), + CHAT_FORMAT_TO_BYSTANDERS("npc.chat.format.with-target-to-bystanders", "[] -> []: "), + CHAT_FORMAT_TO_TARGET("npc.chat.format.to-target", "[] -> You: "), + CHAT_FORMAT_WITH_TARGETS_TO_BYSTANDERS("npc.chat.format.with-targets-to-bystanders", + "[] -> []: "), CHAT_MAX_NUMBER_OF_TARGETS("npc.chat.options.max-number-of-targets-to-show", 2), - CHAT_MULTIPLE_TARGETS_FORMAT("npc.chat.options.multiple-targets-format", "|, | & | & others"), + CHAT_MULTIPLE_TARGETS_FORMAT("npc.chat.options.multiple-targets-format", + "|, | & | & others"), + CHAT_RANGE("npc.chat.options.range", 5), DATABASE_DRIVER("storage.database.driver", ""), DATABASE_PASSWORD("storage.database.password", ""), DATABASE_URL("storage.database.url", ""), diff --git a/src/main/java/net/citizensnpcs/command/CommandContext.java b/src/main/java/net/citizensnpcs/command/CommandContext.java index 4b7a46391..af9052bbd 100644 --- a/src/main/java/net/citizensnpcs/command/CommandContext.java +++ b/src/main/java/net/citizensnpcs/command/CommandContext.java @@ -215,7 +215,7 @@ public class CommandContext { location = ((BlockCommandSender) sender).getBlock().getLocation(); return location; } - + public String[] getSlice(int index) { String[] slice = new String[args.length - index]; System.arraycopy(args, index, slice, 0, args.length - index); diff --git a/src/main/java/net/citizensnpcs/command/CommandManager.java b/src/main/java/net/citizensnpcs/command/CommandManager.java index 079f816e4..1f4745e54 100644 --- a/src/main/java/net/citizensnpcs/command/CommandManager.java +++ b/src/main/java/net/citizensnpcs/command/CommandManager.java @@ -35,8 +35,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; public class CommandManager { - private final Map, CommandAnnotationProcessor> annotationProcessors = Maps - .newHashMap(); + private final Map, CommandAnnotationProcessor> annotationProcessors = Maps.newHashMap(); /* * Mapping of commands (including aliases) with a description. Root commands @@ -77,8 +76,8 @@ public class CommandManager { * @throws CommandException * Any exceptions caused from execution of the command */ - public void execute(org.bukkit.command.Command command, String[] args, CommandSender sender, - Object... methodArgs) throws CommandException { + public void execute(org.bukkit.command.Command command, String[] args, CommandSender sender, Object... methodArgs) + throws CommandException { // must put command into split. String[] newArgs = new String[args.length + 1]; System.arraycopy(args, 0, newArgs, 1, args.length); @@ -90,8 +89,7 @@ public class CommandManager { } // Attempt to execute a command. - private void executeMethod(String[] args, CommandSender sender, Object[] methodArgs) - throws CommandException { + private void executeMethod(String[] args, CommandSender sender, Object[] methodArgs) throws CommandException { String cmdName = args[0]; String modifier = args.length > 1 ? args[1] : ""; @@ -288,8 +286,7 @@ public class CommandManager { // Returns whether a player has access to a command. private boolean hasPermission(Method method, CommandSender sender) { Command cmd = method.getAnnotation(Command.class); - if (cmd.permission().isEmpty() || hasPermission(sender, cmd.permission()) - || hasPermission(sender, "admin")) + if (cmd.permission().isEmpty() || hasPermission(sender, cmd.permission()) || hasPermission(sender, "admin")) return true; return false; diff --git a/src/main/java/net/citizensnpcs/command/RequirementsProcessor.java b/src/main/java/net/citizensnpcs/command/RequirementsProcessor.java index 60f257a0c..237ed166d 100644 --- a/src/main/java/net/citizensnpcs/command/RequirementsProcessor.java +++ b/src/main/java/net/citizensnpcs/command/RequirementsProcessor.java @@ -64,8 +64,8 @@ public class RequirementsProcessor implements CommandAnnotationProcessor { EntityType type = npc.getTrait(MobType.class).getType(); if (!types.contains(type)) { - throw new RequirementMissingException(Messaging.tr( - Messages.COMMAND_REQUIREMENTS_INVALID_MOB_TYPE, type.getName())); + throw new RequirementMissingException(Messaging.tr(Messages.COMMAND_REQUIREMENTS_INVALID_MOB_TYPE, + type.getName())); } } } diff --git a/src/main/java/net/citizensnpcs/command/command/AdminCommands.java b/src/main/java/net/citizensnpcs/command/command/AdminCommands.java index 27bc9c6f7..77a60da43 100644 --- a/src/main/java/net/citizensnpcs/command/command/AdminCommands.java +++ b/src/main/java/net/citizensnpcs/command/command/AdminCommands.java @@ -23,10 +23,8 @@ public class AdminCommands { @Command(aliases = { "citizens" }, desc = "Show basic plugin information", max = 0, permission = "admin") public void citizens(CommandContext args, CommandSender sender, NPC npc) { - Messaging.send( - sender, - " " - + StringHelper.wrapHeader("Citizens v" + plugin.getDescription().getVersion())); + Messaging.send(sender, + " " + StringHelper.wrapHeader("Citizens v" + plugin.getDescription().getVersion())); Messaging.send(sender, " <7>-- Written by fullwall and aPunch"); Messaging.send(sender, " <7>-- Source Code: http://github.com/CitizensDev"); Messaging.send(sender, " <7>-- Website: " + plugin.getDescription().getWebsite()); diff --git a/src/main/java/net/citizensnpcs/command/command/EditorCommands.java b/src/main/java/net/citizensnpcs/command/command/EditorCommands.java index c6ad6aa20..5534d9fa6 100644 --- a/src/main/java/net/citizensnpcs/command/command/EditorCommands.java +++ b/src/main/java/net/citizensnpcs/command/command/EditorCommands.java @@ -23,8 +23,8 @@ public class EditorCommands { min = 1, max = 1, permission = "npc.edit.equip") - @Requirements(selected = true, ownership = true, types = { EntityType.ENDERMAN, EntityType.PLAYER, - EntityType.PIG, EntityType.SHEEP }) + @Requirements(selected = true, ownership = true, types = { EntityType.ENDERMAN, EntityType.PLAYER, EntityType.PIG, + EntityType.SHEEP }) public void equip(CommandContext args, Player player, NPC npc) { Editor.enterOrLeave(player, new EquipmentEditor(player, npc)); } @@ -37,8 +37,8 @@ public class EditorCommands { min = 1, max = 1, permission = "npc.edit.path") - @Requirements(selected = true, ownership = true, excludedTypes = { EntityType.BLAZE, - EntityType.ENDER_DRAGON, EntityType.GHAST, EntityType.BAT, EntityType.WITHER, EntityType.SQUID }) + @Requirements(selected = true, ownership = true, excludedTypes = { EntityType.BLAZE, EntityType.ENDER_DRAGON, + EntityType.GHAST, EntityType.BAT, EntityType.WITHER, EntityType.SQUID }) public void path(CommandContext args, Player player, NPC npc) { Editor.enterOrLeave(player, npc.getTrait(Waypoints.class).getEditor(player)); } diff --git a/src/main/java/net/citizensnpcs/command/command/HelpCommands.java b/src/main/java/net/citizensnpcs/command/command/HelpCommands.java index 7bd3473b5..cf4097708 100644 --- a/src/main/java/net/citizensnpcs/command/command/HelpCommands.java +++ b/src/main/java/net/citizensnpcs/command/command/HelpCommands.java @@ -112,8 +112,7 @@ public class HelpCommands { throw new CommandException(Messages.COMMAND_PAGE_MISSING, page); } - private void sendSpecificHelp(CommandSender sender, String rootCommand, String modifier) - throws CommandException { + private void sendSpecificHelp(CommandSender sender, String rootCommand, String modifier) throws CommandException { CommandInfo info = plugin.getCommandInfo(rootCommand, modifier); if (info == null) throw new CommandException(Messages.COMMAND_MISSING, rootCommand + " " + modifier); @@ -165,7 +164,7 @@ public class HelpCommands { private static final String COMMAND_FORMAT = "<7>/%s%s <7>- %s"; private static final String format(Command command) { - return String.format(COMMAND_FORMAT, command.aliases()[0], (command.usage().isEmpty() ? "" : " " - + command.usage()), Messaging.tryTranslate(command.desc())); + return String.format(COMMAND_FORMAT, command.aliases()[0], + (command.usage().isEmpty() ? "" : " " + command.usage()), Messaging.tryTranslate(command.desc())); } } \ No newline at end of file diff --git a/src/main/java/net/citizensnpcs/command/command/ScriptCommands.java b/src/main/java/net/citizensnpcs/command/command/ScriptCommands.java index b6dbe5749..762280c10 100644 --- a/src/main/java/net/citizensnpcs/command/command/ScriptCommands.java +++ b/src/main/java/net/citizensnpcs/command/command/ScriptCommands.java @@ -30,8 +30,7 @@ public class ScriptCommands { min = 2, max = 2, permission = "script.compile") - public void runScript(final CommandContext args, final CommandSender sender, NPC npc) - throws CommandException { + public void runScript(final CommandContext args, final CommandSender sender, NPC npc) throws CommandException { File file = new File(CitizensAPI.getScriptFolder(), args.getString(1)); if (!file.exists()) throw new CommandException(Messages.SCRIPT_FILE_MISSING, args.getString(1)); diff --git a/src/main/java/net/citizensnpcs/command/command/SelectionPrompt.java b/src/main/java/net/citizensnpcs/command/command/SelectionPrompt.java index 48dd30e9a..52832733e 100644 --- a/src/main/java/net/citizensnpcs/command/command/SelectionPrompt.java +++ b/src/main/java/net/citizensnpcs/command/command/SelectionPrompt.java @@ -55,8 +55,8 @@ public class SelectionPrompt extends NumericPrompt { } public static void start(NPCSelector selector, Player player, List possible) { - final Conversation conversation = new ConversationFactory(CitizensAPI.getPlugin()) - .withLocalEcho(false).withEscapeSequence("exit").withModality(false) + final Conversation conversation = new ConversationFactory(CitizensAPI.getPlugin()).withLocalEcho(false) + .withEscapeSequence("exit").withModality(false) .withFirstPrompt(new SelectionPrompt(selector, possible)).buildConversation(player); conversation.begin(); } diff --git a/src/main/java/net/citizensnpcs/command/command/TraitCommands.java b/src/main/java/net/citizensnpcs/command/command/TraitCommands.java index e03d8f6fe..3286ad7fa 100644 --- a/src/main/java/net/citizensnpcs/command/command/TraitCommands.java +++ b/src/main/java/net/citizensnpcs/command/command/TraitCommands.java @@ -24,13 +24,8 @@ import com.google.common.collect.Lists; @Requirements(selected = true, ownership = true) public class TraitCommands { - @Command( - aliases = { "trait", "tr" }, - usage = "add [trait name]...", - desc = "Adds traits to the NPC", - modifiers = { "add", "a" }, - min = 1, - permission = "npc.trait") + @Command(aliases = { "trait", "tr" }, usage = "add [trait name]...", desc = "Adds traits to the NPC", modifiers = { + "add", "a" }, min = 1, permission = "npc.trait") public void add(CommandContext args, CommandSender sender, NPC npc) throws CommandException { List added = Lists.newArrayList(); List failed = Lists.newArrayList(); diff --git a/src/main/java/net/citizensnpcs/command/command/WaypointCommands.java b/src/main/java/net/citizensnpcs/command/command/WaypointCommands.java index c48b7b00a..aaeae9b90 100644 --- a/src/main/java/net/citizensnpcs/command/command/WaypointCommands.java +++ b/src/main/java/net/citizensnpcs/command/command/WaypointCommands.java @@ -26,8 +26,7 @@ public class WaypointCommands { min = 1, max = 1, permission = "waypoints.disableteleport") - public void disableTeleporting(CommandContext args, CommandSender sender, NPC npc) - throws CommandException { + public void disableTeleporting(CommandContext args, CommandSender sender, NPC npc) throws CommandException { npc.getNavigator().getDefaultParameters().stuckAction(null); Messaging.sendTr(sender, Messages.WAYPOINT_TELEPORTING_DISABLED); } @@ -47,8 +46,7 @@ public class WaypointCommands { if (args.hasFlag('a')) { waypoints.describeProviders(sender); } else - Messaging.sendTr(sender, Messages.CURRENT_WAYPOINT_PROVIDER, - waypoints.getCurrentProviderName()); + Messaging.sendTr(sender, Messages.CURRENT_WAYPOINT_PROVIDER, waypoints.getCurrentProviderName()); return; } boolean success = waypoints.setWaypointProvider(args.getString(1)); diff --git a/src/main/java/net/citizensnpcs/editor/EndermanEquipper.java b/src/main/java/net/citizensnpcs/editor/EndermanEquipper.java index fa2692950..53aa581fa 100644 --- a/src/main/java/net/citizensnpcs/editor/EndermanEquipper.java +++ b/src/main/java/net/citizensnpcs/editor/EndermanEquipper.java @@ -27,8 +27,7 @@ public class EndermanEquipper implements Equipper { return; } } else { - equipper.getWorld() - .dropItemNaturally(npc.getBukkitEntity().getLocation(), carried.toItemStack(1)); + equipper.getWorld().dropItemNaturally(npc.getBukkitEntity().getLocation(), carried.toItemStack(1)); ((Enderman) npc.getBukkitEntity()).setCarriedMaterial(hand.getData()); } diff --git a/src/main/java/net/citizensnpcs/editor/GenericEquipper.java b/src/main/java/net/citizensnpcs/editor/GenericEquipper.java index 5036d988e..b1d7ea9c2 100644 --- a/src/main/java/net/citizensnpcs/editor/GenericEquipper.java +++ b/src/main/java/net/citizensnpcs/editor/GenericEquipper.java @@ -56,8 +56,7 @@ public class GenericEquipper implements Equipper { case AIR: for (int i = 0; i < 5; i++) { if (trait.get(i) != null && trait.get(i).getType() != Material.AIR) { - equipper.getWorld().dropItemNaturally(toEquip.getBukkitEntity().getLocation(), - trait.get(i)); + equipper.getWorld().dropItemNaturally(toEquip.getBukkitEntity().getLocation(), trait.get(i)); trait.set(i, null); } } diff --git a/src/main/java/net/citizensnpcs/editor/SheepEquipper.java b/src/main/java/net/citizensnpcs/editor/SheepEquipper.java index 9cc2bfec9..a49881c82 100644 --- a/src/main/java/net/citizensnpcs/editor/SheepEquipper.java +++ b/src/main/java/net/citizensnpcs/editor/SheepEquipper.java @@ -26,8 +26,8 @@ public class SheepEquipper implements Equipper { DyeColor color = DyeColor.getByData((byte) (15 - hand.getData().getData())); toEquip.getTrait(WoolColor.class).setColor(color); - Messaging.sendTr(equipper, Messages.EQUIPMENT_EDITOR_SHEEP_COLOURED, toEquip.getName(), color - .name().toLowerCase().replace("_", " ")); + Messaging.sendTr(equipper, Messages.EQUIPMENT_EDITOR_SHEEP_COLOURED, toEquip.getName(), color.name() + .toLowerCase().replace("_", " ")); hand.setAmount(hand.getAmount() - 1); } else { diff --git a/src/main/java/net/citizensnpcs/npc/CitizensNPC.java b/src/main/java/net/citizensnpcs/npc/CitizensNPC.java index 09f337289..187bbde62 100644 --- a/src/main/java/net/citizensnpcs/npc/CitizensNPC.java +++ b/src/main/java/net/citizensnpcs/npc/CitizensNPC.java @@ -58,8 +58,7 @@ public class CitizensNPC extends AbstractNPC { event.setCancelled(Setting.KEEP_CHUNKS_LOADED.asBoolean()); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { - getBukkitEntity().getLocation().getChunk(); - // ensure that we are in a loaded chunk. + getBukkitEntity().getLocation().getChunk().load(); return false; } boolean keepSelected = getTrait(Spawned.class).shouldSpawn(); @@ -97,8 +96,8 @@ public class CitizensNPC extends AbstractNPC { // Load traits String traitNames = root.getString("traitnames"); - Iterable keys = traitNames.isEmpty() ? root.getRelative("traits").getSubKeys() : Iterables - .transform(Splitter.on(',').split(traitNames), new Function() { + Iterable keys = traitNames.isEmpty() ? root.getRelative("traits").getSubKeys() : Iterables.transform( + Splitter.on(',').split(traitNames), new Function() { @Override public DataKey apply(@Nullable String input) { return root.getRelative("traits." + input); @@ -196,8 +195,7 @@ public class CitizensNPC extends AbstractNPC { entityController.spawn(at, this); EntityLiving mcEntity = getHandle(); - boolean couldSpawn = !Util.isLoaded(at) ? false : mcEntity.world.addEntity(mcEntity, - SpawnReason.CUSTOM); + boolean couldSpawn = !Util.isLoaded(at) ? false : mcEntity.world.addEntity(mcEntity, SpawnReason.CUSTOM); if (!couldSpawn) { // we need to wait for a chunk load before trying to spawn mcEntity = null; @@ -213,8 +211,7 @@ public class CitizensNPC extends AbstractNPC { } NMS.setHeadYaw(mcEntity, at.getYaw()); - getBukkitEntity().setMetadata(NPC_METADATA_MARKER, - new FixedMetadataValue(CitizensAPI.getPlugin(), true)); + getBukkitEntity().setMetadata(NPC_METADATA_MARKER, new FixedMetadataValue(CitizensAPI.getPlugin(), true)); // Set the spawned state getTrait(CurrentLocation.class).setLocation(at); diff --git a/src/main/java/net/citizensnpcs/npc/EntityControllers.java b/src/main/java/net/citizensnpcs/npc/EntityControllers.java index 30ad62aef..6ad5fe27c 100644 --- a/src/main/java/net/citizensnpcs/npc/EntityControllers.java +++ b/src/main/java/net/citizensnpcs/npc/EntityControllers.java @@ -38,8 +38,8 @@ import com.google.common.collect.Maps; public class EntityControllers { - private static final Map> TYPES = Maps - .newEnumMap(EntityType.class); + private static final Map> TYPES = Maps.newEnumMap(EntityType.class); + public static EntityController createForType(EntityType type) { Class controllerClass = TYPES.get(type); if (controllerClass == null) diff --git a/src/main/java/net/citizensnpcs/npc/Template.java b/src/main/java/net/citizensnpcs/npc/Template.java index 5b1e6d330..2ecdb0966 100644 --- a/src/main/java/net/citizensnpcs/npc/Template.java +++ b/src/main/java/net/citizensnpcs/npc/Template.java @@ -102,8 +102,7 @@ public class Template { } } - private static YamlStorage templates = new YamlStorage(new File(CitizensAPI.getDataFolder(), - "templates.yml")); + private static YamlStorage templates = new YamlStorage(new File(CitizensAPI.getDataFolder(), "templates.yml")); public static Template byName(String name) { if (!templates.getKey("").keyExists(name)) diff --git a/src/main/java/net/citizensnpcs/npc/ai/AStarNavigationStrategy.java b/src/main/java/net/citizensnpcs/npc/ai/AStarNavigationStrategy.java index fa8b54695..f34a7313a 100644 --- a/src/main/java/net/citizensnpcs/npc/ai/AStarNavigationStrategy.java +++ b/src/main/java/net/citizensnpcs/npc/ai/AStarNavigationStrategy.java @@ -31,8 +31,9 @@ public class AStarNavigationStrategy extends AbstractPathStrategy { this.destination = dest; this.npc = npc; Location location = npc.getBukkitEntity().getEyeLocation(); - plan = ASTAR.runFully(new VectorGoal(dest), new VectorNode(location, new ChunkBlockSource(location, - params.range()), params.examiners()), (int) (params.range() * 10)); + plan = ASTAR.runFully(new VectorGoal(dest), + new VectorNode(location, new ChunkBlockSource(location, params.range()), params.examiners()), + (int) (params.range() * 10)); if (plan == null || plan.isComplete()) { setCancelReason(CancelReason.STUCK); } else { diff --git a/src/main/java/net/citizensnpcs/npc/ai/CitizensNavigator.java b/src/main/java/net/citizensnpcs/npc/ai/CitizensNavigator.java index c13245476..49ab21c50 100644 --- a/src/main/java/net/citizensnpcs/npc/ai/CitizensNavigator.java +++ b/src/main/java/net/citizensnpcs/npc/ai/CitizensNavigator.java @@ -23,10 +23,10 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.util.Vector; public class CitizensNavigator implements Navigator, Runnable { - private final NavigatorParameters defaultParams = new NavigatorParameters() - .baseSpeed(UNINITIALISED_SPEED).range(Setting.DEFAULT_PATHFINDING_RANGE.asFloat()) - .stationaryTicks(Setting.DEFAULT_STATIONARY_TICKS.asInt()) - .stuckAction(TeleportStuckAction.INSTANCE).examiner(new MinecraftBlockExaminer()); + private final NavigatorParameters defaultParams = new NavigatorParameters().baseSpeed(UNINITIALISED_SPEED) + .range(Setting.DEFAULT_PATHFINDING_RANGE.asFloat()) + .stationaryTicks(Setting.DEFAULT_STATIONARY_TICKS.asInt()).stuckAction(TeleportStuckAction.INSTANCE) + .examiner(new MinecraftBlockExaminer()); private PathStrategy executing; private int lastX, lastY, lastZ; private NavigatorParameters localParams = defaultParams; @@ -82,15 +82,12 @@ public class CitizensNavigator implements Navigator, Runnable { public void load(DataKey root) { defaultParams.baseSpeed((float) root.getDouble("speed", UNINITIALISED_SPEED)); - defaultParams.range((float) root.getDouble("pathfindingrange", - Setting.DEFAULT_PATHFINDING_RANGE.asFloat())); - defaultParams - .stationaryTicks(root.getInt("stationaryticks", Setting.DEFAULT_STATIONARY_TICKS.asInt())); + defaultParams.range((float) root.getDouble("pathfindingrange", Setting.DEFAULT_PATHFINDING_RANGE.asFloat())); + defaultParams.stationaryTicks(root.getInt("stationaryticks", Setting.DEFAULT_STATIONARY_TICKS.asInt())); defaultParams.speedModifier((float) root.getDouble("speedmodifier", 1F)); if (root.keyExists("avoidwater")) defaultParams.avoidWater(root.getBoolean("avoidwater")); - if (!root.getBoolean("usedefaultstuckaction") - && defaultParams.stuckAction() == TeleportStuckAction.INSTANCE) + if (!root.getBoolean("usedefaultstuckaction") && defaultParams.stuckAction() == TeleportStuckAction.INSTANCE) defaultParams.stuckAction(null); } diff --git a/src/main/java/net/citizensnpcs/npc/ai/MCTargetStrategy.java b/src/main/java/net/citizensnpcs/npc/ai/MCTargetStrategy.java index 9c7de51b0..59ca25e07 100644 --- a/src/main/java/net/citizensnpcs/npc/ai/MCTargetStrategy.java +++ b/src/main/java/net/citizensnpcs/npc/ai/MCTargetStrategy.java @@ -48,6 +48,7 @@ public class MCTargetStrategy implements PathStrategy, EntityTarget { return handle.getBukkitEntity().getLocation(HANDLE_LOCATION) .distanceSquared(target.getBukkitEntity().getLocation(TARGET_LOCATION)); } + @Override public CancelReason getCancelReason() { return cancelReason; diff --git a/src/main/java/net/citizensnpcs/npc/ai/speech/Chat.java b/src/main/java/net/citizensnpcs/npc/ai/speech/Chat.java index 34ea75409..4d476782a 100644 --- a/src/main/java/net/citizensnpcs/npc/ai/speech/Chat.java +++ b/src/main/java/net/citizensnpcs/npc/ai/speech/Chat.java @@ -17,101 +17,120 @@ import net.citizensnpcs.util.Messaging; public class Chat implements VocalChord { - public final String VOCAL_CHORD_NAME = "chat"; + public final String VOCAL_CHORD_NAME = "chat"; - @Override - public String getName() { - return VOCAL_CHORD_NAME; - } + @Override + public String getName() { + return VOCAL_CHORD_NAME; + } - @Override - public void talk(SpeechContext context) { - - // Check valid talker - if (context.getTalker() == null) return; - NPC npc = CitizensAPI.getNPCRegistry().getNPC(context.getTalker().getEntity()); - if (npc == null) return; - - // If no recipients, chat to the world with CHAT_FORMAT and CHAT_RANGE settings - if (!context.hasRecipients()) { - String text = Setting.CHAT_FORMAT.asString().replace("", npc.getName()).replace("", context.getMessage()); - talkToBystanders(npc, text, context); - return; - } + @Override + public void talk(SpeechContext context) { - // Assumed recipients at this point - else if (context.size() <= 1) { // One recipient - String text = Setting.CHAT_FORMAT_TO_TARGET.asString().replace("", npc.getName()).replace("", context.getMessage()); - String targetName = ""; - // For each recipient - for (Talkable entity : context) { - entity.talkTo(context, text, this); - targetName = entity.getName(); - } - // Check if bystanders hear targeted chat - if (!Setting.CHAT_BYSTANDERS_HEAR_TARGETED_CHAT.asBoolean()) return; - // Format message with config setting and send to bystanders - String bystanderText = Setting.CHAT_FORMAT_TO_BYSTANDERS.asString().replace("", npc.getName()).replace("", targetName).replace("", context.getMessage()); - talkToBystanders(npc, bystanderText, context); - return; - } + // Check valid talker + if (context.getTalker() == null) + return; + NPC npc = CitizensAPI.getNPCRegistry().getNPC(context.getTalker().getEntity()); + if (npc == null) + return; - else { // Multiple recipients - String text = Setting.CHAT_FORMAT_TO_TARGET.asString().replace("", npc.getName()).replace("", context.getMessage()); - List targetNames = Collections.emptyList(); - // Talk to each recipient - for (Talkable entity : context) { - entity.talkTo(context, text, this); - targetNames.add(entity.getName()); - } + // If no recipients, chat to the world with CHAT_FORMAT and CHAT_RANGE + // settings + if (!context.hasRecipients()) { + String text = Setting.CHAT_FORMAT.asString().replace("", npc.getName()) + .replace("", context.getMessage()); + talkToBystanders(npc, text, context); + return; + } - if (!Setting.CHAT_BYSTANDERS_HEAR_TARGETED_CHAT.asBoolean()) return; - String targets = ""; - int max = Setting.CHAT_MAX_NUMBER_OF_TARGETS.asInt(); - String[] format = Setting.CHAT_FORMAT_WITH_TARGETS_TO_BYSTANDERS.asString().split("\\|"); - if (format.length != 4) Messaging.log(Level.WARNING, "npc.chat.format.with-target-to-bystanders invalid!"); - if (max == 1) { - targets = format[0].replace("", targetNames.get(0)) + format[3]; - } - else if (max == 2 || targetNames.size() == 2) { - if (targetNames.size() == 2) - targets = format[0].replace("", targetNames.get(0)) + format[2].replace("", targetNames.get(1)); - else - targets = format[0].replace("", targetNames.get(0)) + format[1].replace("", targetNames.get(1)) + format[3]; - } - else if (max >= 3) { - targets = format[0].replace("", targetNames.get(0)); + // Assumed recipients at this point + else if (context.size() <= 1) { // One recipient + String text = Setting.CHAT_FORMAT_TO_TARGET.asString().replace("", npc.getName()) + .replace("", context.getMessage()); + String targetName = ""; + // For each recipient + for (Talkable entity : context) { + entity.talkTo(context, text, this); + targetName = entity.getName(); + } + // Check if bystanders hear targeted chat + if (!Setting.CHAT_BYSTANDERS_HEAR_TARGETED_CHAT.asBoolean()) + return; + // Format message with config setting and send to bystanders + String bystanderText = Setting.CHAT_FORMAT_TO_BYSTANDERS.asString().replace("", npc.getName()) + .replace("", targetName).replace("", context.getMessage()); + talkToBystanders(npc, bystanderText, context); + return; + } - int x = 1; - for (x = 1; x < max - 1; x++) { - if (targetNames.size() - 1 == x) break; - targets = targets + format[1].replace("", targetNames.get(x)); - } - if (targetNames.size() == max) - targets = targets + format[2].replace("", targetNames.get(x)); - else targets = targets + format[3]; - } - - String bystanderText = Setting.CHAT_FORMAT_WITH_TARGETS_TO_BYSTANDERS.asString().replace("", npc.getName()).replace("", targets).replace("", context.getMessage()); - talkToBystanders(npc, bystanderText, context); - } - } + else { // Multiple recipients + String text = Setting.CHAT_FORMAT_TO_TARGET.asString().replace("", npc.getName()) + .replace("", context.getMessage()); + List targetNames = Collections.emptyList(); + // Talk to each recipient + for (Talkable entity : context) { + entity.talkTo(context, text, this); + targetNames.add(entity.getName()); + } - private void talkToBystanders(NPC npc, String text, SpeechContext context) { - // Get list of nearby entities - List bystanderEntities = npc.getBukkitEntity().getNearbyEntities(Setting.CHAT_RANGE.asDouble(), Setting.CHAT_RANGE.asDouble(), Setting.CHAT_RANGE.asDouble()); - for (Entity bystander : bystanderEntities) - // Continue if a LivingEntity, which is compatible with TalkableEntity - if (bystander instanceof LivingEntity) { - // Exclude targeted recipients - if (context.hasRecipients()) { - for (Talkable target : context) - if (target.getEntity() == bystander) continue; - else new TalkableEntity((LivingEntity) bystander).talkNear(context, text, this); - } else - // Found a nearby LivingEntity, make it Talkable and talkNear it - new TalkableEntity((LivingEntity) bystander).talkNear(context, text, this); - } - } + if (!Setting.CHAT_BYSTANDERS_HEAR_TARGETED_CHAT.asBoolean()) + return; + String targets = ""; + int max = Setting.CHAT_MAX_NUMBER_OF_TARGETS.asInt(); + String[] format = Setting.CHAT_FORMAT_WITH_TARGETS_TO_BYSTANDERS.asString().split("\\|"); + if (format.length != 4) + Messaging.log(Level.WARNING, "npc.chat.format.with-target-to-bystanders invalid!"); + if (max == 1) { + targets = format[0].replace("", targetNames.get(0)) + format[3]; + } else if (max == 2 || targetNames.size() == 2) { + if (targetNames.size() == 2) + targets = format[0].replace("", targetNames.get(0)) + + format[2].replace("", targetNames.get(1)); + else + targets = format[0].replace("", targetNames.get(0)) + + format[1].replace("", targetNames.get(1)) + format[3]; + } else if (max >= 3) { + targets = format[0].replace("", targetNames.get(0)); + + int x = 1; + for (x = 1; x < max - 1; x++) { + if (targetNames.size() - 1 == x) + break; + targets = targets + format[1].replace("", targetNames.get(x)); + } + if (targetNames.size() == max) + targets = targets + format[2].replace("", targetNames.get(x)); + else + targets = targets + format[3]; + } + + String bystanderText = Setting.CHAT_FORMAT_WITH_TARGETS_TO_BYSTANDERS.asString() + .replace("", npc.getName()).replace("", targets) + .replace("", context.getMessage()); + talkToBystanders(npc, bystanderText, context); + } + } + + private void talkToBystanders(NPC npc, String text, SpeechContext context) { + // Get list of nearby entities + List bystanderEntities = npc.getBukkitEntity().getNearbyEntities(Setting.CHAT_RANGE.asDouble(), + Setting.CHAT_RANGE.asDouble(), Setting.CHAT_RANGE.asDouble()); + for (Entity bystander : bystanderEntities) + // Continue if a LivingEntity, which is compatible with + // TalkableEntity + if (bystander instanceof LivingEntity) { + // Exclude targeted recipients + if (context.hasRecipients()) { + for (Talkable target : context) + if (target.getEntity() == bystander) + continue; + else + new TalkableEntity((LivingEntity) bystander).talkNear(context, text, this); + } else + // Found a nearby LivingEntity, make it Talkable and + // talkNear it + new TalkableEntity((LivingEntity) bystander).talkNear(context, text, this); + } + } } diff --git a/src/main/java/net/citizensnpcs/npc/ai/speech/CitizensSpeechFactory.java b/src/main/java/net/citizensnpcs/npc/ai/speech/CitizensSpeechFactory.java index 1c9d4176a..27fcba703 100644 --- a/src/main/java/net/citizensnpcs/npc/ai/speech/CitizensSpeechFactory.java +++ b/src/main/java/net/citizensnpcs/npc/ai/speech/CitizensSpeechFactory.java @@ -14,66 +14,68 @@ import net.citizensnpcs.api.ai.speech.VocalChord; public class CitizensSpeechFactory implements SpeechFactory { - Map> registered = new HashMap>(); - - @Override - public VocalChord getVocalChord(Class clazz) { - // Return a new instance of the VocalChord specified - try { - return clazz.newInstance(); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - return null; - } + Map> registered = new HashMap>(); - @Override - public VocalChord getVocalChord(String name) { - // Check if VocalChord name is a registered type - if (isRegistered(name)) - // Return a new instance of the VocalChord specified - try { - return registered.get(name.toLowerCase()).newInstance(); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - return null; - } + @Override + public VocalChord getVocalChord(Class clazz) { + // Return a new instance of the VocalChord specified + try { + return clazz.newInstance(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } - @Override - public String getVocalChordName(Class clazz) { - // Get the name of a VocalChord class that has been registered - for (Entry> vocalChord : registered.entrySet()) - if (vocalChord.getValue() == clazz) return vocalChord.getKey(); - - return null; - } + @Override + public VocalChord getVocalChord(String name) { + // Check if VocalChord name is a registered type + if (isRegistered(name)) + // Return a new instance of the VocalChord specified + try { + return registered.get(name.toLowerCase()).newInstance(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } - @Override - public boolean isRegistered(String name) { - if (registered.containsKey(name.toLowerCase())) return true; - else return false; - } + @Override + public String getVocalChordName(Class clazz) { + // Get the name of a VocalChord class that has been registered + for (Entry> vocalChord : registered.entrySet()) + if (vocalChord.getValue() == clazz) + return vocalChord.getKey(); - @Override - public void register(Class clazz, String name) { + return null; + } + + @Override + public boolean isRegistered(String name) { + if (registered.containsKey(name.toLowerCase())) + return true; + else + return false; + } + + @Override + public Talkable newTalkableEntity(LivingEntity entity) { + if (entity == null) + return null; + return new TalkableEntity(entity); + } + + @Override + public void register(Class clazz, String name) { Preconditions.checkNotNull(name, "info cannot be null"); Preconditions.checkNotNull(clazz, "vocalchord cannot be null"); if (registered.containsKey(name.toLowerCase())) throw new IllegalArgumentException("vocalchord name already registered"); - registered.put(name.toLowerCase(), clazz); - } - - @Override - public Talkable newTalkableEntity(LivingEntity entity) { - if (entity == null) return null; - return new TalkableEntity(entity); - } - - + registered.put(name.toLowerCase(), clazz); + } } diff --git a/src/main/java/net/citizensnpcs/npc/ai/speech/TalkableEntity.java b/src/main/java/net/citizensnpcs/npc/ai/speech/TalkableEntity.java index f2ae0a82e..ea3e19292 100644 --- a/src/main/java/net/citizensnpcs/npc/ai/speech/TalkableEntity.java +++ b/src/main/java/net/citizensnpcs/npc/ai/speech/TalkableEntity.java @@ -15,77 +15,82 @@ import org.bukkit.entity.Player; public class TalkableEntity implements Talkable { - LivingEntity entity; - - public TalkableEntity(LivingEntity entity) { - this.entity = entity; - } - - public TalkableEntity(NPC npc) { - entity = npc.getBukkitEntity(); - } - - public TalkableEntity(Player player) { - entity = (LivingEntity) player; - } - - /** - * Used to compare a LivingEntity to this TalkableEntity - * - * @return - * 0 if the Entities are the same, 1 if they are not, -1 if - * the object compared is not a valid LivingEntity - */ - @Override - public int compareTo(Object o) { - // If not living entity, return -1 - if (!(o instanceof LivingEntity)) return -1; - // If NPC and matches, return 0 - else if (CitizensAPI.getNPCRegistry().isNPC((LivingEntity) o) - && CitizensAPI.getNPCRegistry().isNPC((LivingEntity) entity) - && CitizensAPI.getNPCRegistry().getNPC((LivingEntity) o).getId() == - CitizensAPI.getNPCRegistry().getNPC((LivingEntity) entity).getId()) - return 0; - else if ((LivingEntity) o == entity) return 0; - // Not a match, return 1 - else return 1; - } + LivingEntity entity; - @Override - public LivingEntity getEntity() { - return entity; - } - - @Override - public String getName() { - if (CitizensAPI.getNPCRegistry().isNPC(entity)) - return CitizensAPI.getNPCRegistry().getNPC(entity).getName(); - else if (entity instanceof Player) - return ((Player) entity).getName(); - else - return entity.getType().name().replace("_", " "); - } - - private void talk(String message) { - if (entity instanceof Player - && !CitizensAPI.getNPCRegistry().isNPC(entity)) - Messaging.send((Player) entity, message); - } - - @Override - public void talkNear(SpeechContext context, String text, VocalChord vocalChord) { - SpeechBystanderEvent event = new SpeechBystanderEvent(this, context, text, vocalChord); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) return; - else talk(event.getMessage()); - } + public TalkableEntity(LivingEntity entity) { + this.entity = entity; + } - @Override - public void talkTo(SpeechContext context, String text, VocalChord vocalChord) { - SpeechTargetedEvent event = new SpeechTargetedEvent(this, context, text, vocalChord); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) return; - else talk(event.getMessage()); - } + public TalkableEntity(NPC npc) { + entity = npc.getBukkitEntity(); + } + + public TalkableEntity(Player player) { + entity = (LivingEntity) player; + } + + /** + * Used to compare a LivingEntity to this TalkableEntity + * + * @return 0 if the Entities are the same, 1 if they are not, -1 if the + * object compared is not a valid LivingEntity + */ + @Override + public int compareTo(Object o) { + // If not living entity, return -1 + if (!(o instanceof LivingEntity)) + return -1; + // If NPC and matches, return 0 + else if (CitizensAPI.getNPCRegistry().isNPC((LivingEntity) o) + && CitizensAPI.getNPCRegistry().isNPC((LivingEntity) entity) + && CitizensAPI.getNPCRegistry().getNPC((LivingEntity) o).getId() == CitizensAPI.getNPCRegistry() + .getNPC((LivingEntity) entity).getId()) + return 0; + else if ((LivingEntity) o == entity) + return 0; + // Not a match, return 1 + else + return 1; + } + + @Override + public LivingEntity getEntity() { + return entity; + } + + @Override + public String getName() { + if (CitizensAPI.getNPCRegistry().isNPC(entity)) + return CitizensAPI.getNPCRegistry().getNPC(entity).getName(); + else if (entity instanceof Player) + return ((Player) entity).getName(); + else + return entity.getType().name().replace("_", " "); + } + + private void talk(String message) { + if (entity instanceof Player && !CitizensAPI.getNPCRegistry().isNPC(entity)) + Messaging.send((Player) entity, message); + } + + @Override + public void talkNear(SpeechContext context, String text, VocalChord vocalChord) { + SpeechBystanderEvent event = new SpeechBystanderEvent(this, context, text, vocalChord); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) + return; + else + talk(event.getMessage()); + } + + @Override + public void talkTo(SpeechContext context, String text, VocalChord vocalChord) { + SpeechTargetedEvent event = new SpeechTargetedEvent(this, context, text, vocalChord); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) + return; + else + talk(event.getMessage()); + } } diff --git a/src/main/java/net/citizensnpcs/npc/entity/EntityHumanNPC.java b/src/main/java/net/citizensnpcs/npc/entity/EntityHumanNPC.java index 22cf86075..1fc2c7678 100644 --- a/src/main/java/net/citizensnpcs/npc/entity/EntityHumanNPC.java +++ b/src/main/java/net/citizensnpcs/npc/entity/EntityHumanNPC.java @@ -189,8 +189,7 @@ public class EntityHumanNPC extends EntityPlayer implements NPCHolder { net.minecraft.server.v1_4_6.ItemStack previous = previousEquipment[i]; net.minecraft.server.v1_4_6.ItemStack current = getEquipment(i); if (previous != current) { - NMS.sendPacketNearby(getBukkitEntity().getLocation(), new Packet5EntityEquipment(id, i, - current)); + NMS.sendPacketNearby(getBukkitEntity().getLocation(), new Packet5EntityEquipment(id, i, current)); previousEquipment[i] = current; } } diff --git a/src/main/java/net/citizensnpcs/npc/entity/HumanController.java b/src/main/java/net/citizensnpcs/npc/entity/HumanController.java index 1388ed929..62dea7663 100644 --- a/src/main/java/net/citizensnpcs/npc/entity/HumanController.java +++ b/src/main/java/net/citizensnpcs/npc/entity/HumanController.java @@ -19,8 +19,8 @@ public class HumanController extends AbstractEntityController { @Override protected LivingEntity createEntity(final Location at, final NPC npc) { WorldServer ws = ((CraftWorld) at.getWorld()).getHandle(); - final EntityHumanNPC handle = new EntityHumanNPC(ws.getServer().getServer(), ws, - StringHelper.parseColors(npc.getFullName()), new PlayerInteractManager(ws), npc); + final EntityHumanNPC handle = new EntityHumanNPC(ws.getServer().getServer(), ws, StringHelper.parseColors(npc + .getFullName()), new PlayerInteractManager(ws), npc); handle.getBukkitEntity().teleport(at); Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), new Runnable() { @Override diff --git a/src/main/java/net/citizensnpcs/npc/network/EmptyNetHandler.java b/src/main/java/net/citizensnpcs/npc/network/EmptyNetHandler.java index 3515355b8..7c16718d7 100644 --- a/src/main/java/net/citizensnpcs/npc/network/EmptyNetHandler.java +++ b/src/main/java/net/citizensnpcs/npc/network/EmptyNetHandler.java @@ -18,8 +18,7 @@ import net.minecraft.server.v1_4_6.Packet3Chat; import net.minecraft.server.v1_4_6.Packet51MapChunk; public class EmptyNetHandler extends PlayerConnection { - public EmptyNetHandler(MinecraftServer minecraftServer, NetworkManager networkManager, - EntityPlayer entityPlayer) { + public EmptyNetHandler(MinecraftServer minecraftServer, NetworkManager networkManager, EntityPlayer entityPlayer) { super(minecraftServer, networkManager, entityPlayer); } diff --git a/src/main/java/net/citizensnpcs/npc/network/EmptyNetworkManager.java b/src/main/java/net/citizensnpcs/npc/network/EmptyNetworkManager.java index 880517470..84c1c78b7 100644 --- a/src/main/java/net/citizensnpcs/npc/network/EmptyNetworkManager.java +++ b/src/main/java/net/citizensnpcs/npc/network/EmptyNetworkManager.java @@ -11,8 +11,7 @@ import net.minecraft.server.v1_4_6.Packet; public class EmptyNetworkManager extends NetworkManager { - public EmptyNetworkManager(Socket socket, String string, Connection conn, PrivateKey key) - throws IOException { + public EmptyNetworkManager(Socket socket, String string, Connection conn, PrivateKey key) throws IOException { super(socket, string, conn, key); NMS.stopNetworkThreads(this); diff --git a/src/main/java/net/citizensnpcs/trait/Controllable.java b/src/main/java/net/citizensnpcs/trait/Controllable.java index e3ab3c8e1..0b4104373 100644 --- a/src/main/java/net/citizensnpcs/trait/Controllable.java +++ b/src/main/java/net/citizensnpcs/trait/Controllable.java @@ -202,16 +202,6 @@ public class Controllable extends Trait implements Toggleable, CommandConfigurab } } - public static interface MovementController { - void leftClick(PlayerInteractEvent event); - - void rightClick(PlayerInteractEvent event); - - void rightClickEntity(NPCRightClickEvent event); - - void run(Player rider); - } - public class GroundController implements MovementController { private void jump() { boolean allowed = getHandle().onGround; @@ -249,6 +239,16 @@ public class Controllable extends Trait implements Toggleable, CommandConfigurab private static final float JUMP_VELOCITY = 0.6F; } + public static interface MovementController { + void leftClick(PlayerInteractEvent event); + + void rightClick(PlayerInteractEvent event); + + void rightClickEntity(NPCRightClickEvent event); + + void run(Player rider); + } + private static final Map> controllerTypes = Maps .newEnumMap(EntityType.class); diff --git a/src/main/java/net/citizensnpcs/trait/Poses.java b/src/main/java/net/citizensnpcs/trait/Poses.java index 21f65fcf5..a2debd5bf 100644 --- a/src/main/java/net/citizensnpcs/trait/Poses.java +++ b/src/main/java/net/citizensnpcs/trait/Poses.java @@ -53,8 +53,7 @@ public class Poses extends Trait { paginator.addLine("Key: ID Name Pitch/Yaw"); int i = 0; for (Pose pose : poses.values()) { - String line = "" + i + " " + pose.getName() + " " + pose.getPitch() + "/" - + pose.getYaw(); + String line = "" + i + " " + pose.getName() + " " + pose.getPitch() + "/" + pose.getYaw(); paginator.addLine(line); i++; } diff --git a/src/main/java/net/citizensnpcs/trait/text/Text.java b/src/main/java/net/citizensnpcs/trait/text/Text.java index a863d2a6b..83bf1a9d1 100644 --- a/src/main/java/net/citizensnpcs/trait/text/Text.java +++ b/src/main/java/net/citizensnpcs/trait/text/Text.java @@ -11,13 +11,11 @@ import java.util.concurrent.TimeUnit; import net.citizensnpcs.Settings.Setting; import net.citizensnpcs.api.CitizensAPI; import net.citizensnpcs.api.ai.speech.SpeechContext; -import net.citizensnpcs.api.ai.speech.Talkable; import net.citizensnpcs.api.event.NPCRightClickEvent; import net.citizensnpcs.api.exception.NPCLoadException; import net.citizensnpcs.api.trait.Trait; import net.citizensnpcs.api.util.DataKey; import net.citizensnpcs.editor.Editor; -import net.citizensnpcs.npc.ai.speech.TalkableEntity; import net.citizensnpcs.trait.Toggleable; import net.citizensnpcs.util.Messages; import net.citizensnpcs.util.Messaging; @@ -65,10 +63,9 @@ public class Text extends Trait implements Runnable, Toggleable, Listener, Conve } public Editor getEditor(final Player player) { - final Conversation conversation = new ConversationFactory(plugin) - .addConversationAbandonedListener(this).withLocalEcho(false).withEscapeSequence("/npc text") - .withEscapeSequence("exit").withModality(false).withFirstPrompt(new TextStartPrompt(this)) - .buildConversation(player); + final Conversation conversation = new ConversationFactory(plugin).addConversationAbandonedListener(this) + .withLocalEcho(false).withEscapeSequence("/npc text").withEscapeSequence("exit").withModality(false) + .withFirstPrompt(new TextStartPrompt(this)).buildConversation(player); return new Editor() { @Override @@ -111,8 +108,7 @@ public class Text extends Trait implements Runnable, Toggleable, Listener, Conve public void onRightClick(NPCRightClickEvent event) { if (!event.getNPC().equals(npc)) return; - String localPattern = itemInHandPattern.equals("default") ? Setting.TALK_ITEM.asString() - : itemInHandPattern; + String localPattern = itemInHandPattern.equals("default") ? Setting.TALK_ITEM.asString() : itemInHandPattern; if (Util.matchesItemInHand(event.getClicker(), localPattern) && !shouldTalkClose()) sendText(event.getClicker()); } @@ -192,9 +188,10 @@ public class Text extends Trait implements Runnable, Toggleable, Listener, Conve currentIndex = 0; index = currentIndex++; } - + npc.getDefaultSpeechController().speak(new SpeechContext(text.get(index), player)); - // Messaging.sendWithNPC(player, Setting.CHAT_PREFIX.asString() + text.get(index), npc); + // Messaging.sendWithNPC(player, Setting.CHAT_PREFIX.asString() + + // text.get(index), npc); return true; } diff --git a/src/main/java/net/citizensnpcs/trait/text/TextEditPrompt.java b/src/main/java/net/citizensnpcs/trait/text/TextEditPrompt.java index 97fd95c97..761b319f1 100644 --- a/src/main/java/net/citizensnpcs/trait/text/TextEditPrompt.java +++ b/src/main/java/net/citizensnpcs/trait/text/TextEditPrompt.java @@ -20,8 +20,7 @@ public class TextEditPrompt extends StringPrompt { public Prompt acceptInput(ConversationContext context, String input) { int index = (Integer) context.getSessionData("index"); text.edit(index, input); - Messaging - .sendTr((CommandSender) context.getForWhom(), Messages.TEXT_EDITOR_EDITED_TEXT, index, input); + Messaging.sendTr((CommandSender) context.getForWhom(), Messages.TEXT_EDITOR_EDITED_TEXT, index, input); return new TextStartPrompt(text); } diff --git a/src/main/java/net/citizensnpcs/trait/text/TextStartPrompt.java b/src/main/java/net/citizensnpcs/trait/text/TextStartPrompt.java index 401fe38c3..4b0c4b339 100644 --- a/src/main/java/net/citizensnpcs/trait/text/TextStartPrompt.java +++ b/src/main/java/net/citizensnpcs/trait/text/TextStartPrompt.java @@ -30,8 +30,7 @@ public class TextStartPrompt extends StringPrompt { else if (input.equalsIgnoreCase("random")) Messaging.sendTr(sender, Messages.TEXT_EDITOR_RANDOM_TALKER_SET, text.toggleRandomTalker()); else if (input.equalsIgnoreCase("realistic looking")) - Messaging.sendTr(sender, Messages.TEXT_EDITOR_REALISTIC_LOOKING_SET, - text.toggleRealisticLooking()); + Messaging.sendTr(sender, Messages.TEXT_EDITOR_REALISTIC_LOOKING_SET, text.toggleRealisticLooking()); else if (input.equalsIgnoreCase("close") || input.equalsIgnoreCase("talk-close")) Messaging.sendTr(sender, Messages.TEXT_EDITOR_CLOSE_TALKER_SET, text.toggle()); else if (input.equalsIgnoreCase("range")) { diff --git a/src/main/java/net/citizensnpcs/trait/waypoint/LinearWaypointProvider.java b/src/main/java/net/citizensnpcs/trait/waypoint/LinearWaypointProvider.java index 7151f099b..61abe65ef 100644 --- a/src/main/java/net/citizensnpcs/trait/waypoint/LinearWaypointProvider.java +++ b/src/main/java/net/citizensnpcs/trait/waypoint/LinearWaypointProvider.java @@ -267,8 +267,8 @@ public class LinearWaypointProvider implements WaypointProvider { if (!event.getRightClicked().hasMetadata("waypointindex")) return; editingSlot = event.getRightClicked().getMetadata("waypointindex").get(0).asInt(); - Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_EDIT_SLOT_SET, editingSlot, - formatLoc(waypoints.get(editingSlot).getLocation())); + Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_EDIT_SLOT_SET, editingSlot, formatLoc(waypoints + .get(editingSlot).getLocation())); } @EventHandler @@ -288,8 +288,8 @@ public class LinearWaypointProvider implements WaypointProvider { editingSlot += diff > 0 ? 1 : -1; } normaliseEditingSlot(); - Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_EDIT_SLOT_SET, editingSlot, - formatLoc(waypoints.get(editingSlot).getLocation())); + Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_EDIT_SLOT_SET, editingSlot, formatLoc(waypoints + .get(editingSlot).getLocation())); } private void onWaypointsModified() { @@ -339,8 +339,8 @@ public class LinearWaypointProvider implements WaypointProvider { } private Iterator getNewIterator() { - LinearWaypointsCompleteEvent event = new LinearWaypointsCompleteEvent( - LinearWaypointProvider.this, waypoints.iterator()); + LinearWaypointsCompleteEvent event = new LinearWaypointsCompleteEvent(LinearWaypointProvider.this, + waypoints.iterator()); Bukkit.getPluginManager().callEvent(event); Iterator next = event.getNextWaypoints(); return next; diff --git a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/AnimationTriggerPrompt.java b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/AnimationTriggerPrompt.java index 7e52592bc..0dc0cbc79 100644 --- a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/AnimationTriggerPrompt.java +++ b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/AnimationTriggerPrompt.java @@ -23,8 +23,7 @@ public class AnimationTriggerPrompt extends StringPrompt implements WaypointTrig if (input.equalsIgnoreCase("back")) return (Prompt) context.getSessionData("previous"); if (input.equalsIgnoreCase("finish")) { - context.setSessionData(WaypointTriggerPrompt.CREATED_TRIGGER_KEY, - new AnimationTrigger(animations)); + context.setSessionData(WaypointTriggerPrompt.CREATED_TRIGGER_KEY, new AnimationTrigger(animations)); return (Prompt) context.getSessionData(WaypointTriggerPrompt.RETURN_PROMPT_KEY); } PlayerAnimation animation = Util.matchEnum(PlayerAnimation.values(), input); @@ -36,8 +35,7 @@ public class AnimationTriggerPrompt extends StringPrompt implements WaypointTrig @Override public String getPromptText(ConversationContext context) { - Messaging.sendTr((CommandSender) context.getForWhom(), Messages.ANIMATION_TRIGGER_PROMPT, - getValidAnimations()); + Messaging.sendTr((CommandSender) context.getForWhom(), Messages.ANIMATION_TRIGGER_PROMPT, getValidAnimations()); return ""; } diff --git a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/ChatTriggerPrompt.java b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/ChatTriggerPrompt.java index 76566b127..7b00d4de0 100644 --- a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/ChatTriggerPrompt.java +++ b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/ChatTriggerPrompt.java @@ -27,8 +27,7 @@ public class ChatTriggerPrompt extends StringPrompt implements WaypointTriggerPr Messaging.sendErrorTr((CommandSender) context.getForWhom(), Messages.WAYPOINT_TRIGGER_CHAT_INVALID_RADIUS); } catch (IndexOutOfBoundsException e) { - Messaging.sendErrorTr((CommandSender) context.getForWhom(), - Messages.WAYPOINT_TRIGGER_CHAT_NO_RADIUS); + Messaging.sendErrorTr((CommandSender) context.getForWhom(), Messages.WAYPOINT_TRIGGER_CHAT_NO_RADIUS); } return this; } diff --git a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TeleportTrigger.java b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TeleportTrigger.java index c17193c83..48a96208a 100644 --- a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TeleportTrigger.java +++ b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TeleportTrigger.java @@ -18,8 +18,8 @@ public class TeleportTrigger implements WaypointTrigger { @Override public String description() { - return String.format("Teleport to [%s, %d, %d, %d]", location.getWorld().getName(), - location.getBlockX(), location.getBlockY(), location.getBlockZ()); + return String.format("Teleport to [%s, %d, %d, %d]", location.getWorld().getName(), location.getBlockX(), + location.getBlockY(), location.getBlockZ()); } @Override diff --git a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TeleportTriggerPrompt.java b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TeleportTriggerPrompt.java index 27af848c2..ae91dbcfd 100644 --- a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TeleportTriggerPrompt.java +++ b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TeleportTriggerPrompt.java @@ -29,8 +29,7 @@ public class TeleportTriggerPrompt extends RegexPrompt implements WaypointTrigge return (Prompt) context.getSessionData("previous"); if (input.equalsIgnoreCase("here")) { Player player = (Player) context.getForWhom(); - context.setSessionData(WaypointTriggerPrompt.CREATED_TRIGGER_KEY, - new TeleportTrigger(player.getLocation())); + context.setSessionData(WaypointTriggerPrompt.CREATED_TRIGGER_KEY, new TeleportTrigger(player.getLocation())); return (Prompt) context.getSessionData(WaypointTriggerPrompt.RETURN_PROMPT_KEY); } String[] parts = Iterables.toArray(Splitter.on(':').split(input), String.class); diff --git a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerAddPrompt.java b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerAddPrompt.java index 5299ef59d..cf5f3add2 100644 --- a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerAddPrompt.java +++ b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerAddPrompt.java @@ -35,23 +35,20 @@ public class TriggerAddPrompt extends StringPrompt { @Override public String getPromptText(ConversationContext context) { - WaypointTrigger returned = (WaypointTrigger) context - .getSessionData(WaypointTriggerPrompt.CREATED_TRIGGER_KEY); + WaypointTrigger returned = (WaypointTrigger) context.getSessionData(WaypointTriggerPrompt.CREATED_TRIGGER_KEY); if (returned != null) { if (editor.getCurrentWaypoint() != null) { editor.getCurrentWaypoint().addTrigger(returned); context.setSessionData(WaypointTriggerPrompt.CREATED_TRIGGER_KEY, null); - Messaging.sendTr((CommandSender) context.getForWhom(), - Messages.WAYPOINT_TRIGGER_ADDED_SUCCESSFULLY, returned.description()); + Messaging.sendTr((CommandSender) context.getForWhom(), Messages.WAYPOINT_TRIGGER_ADDED_SUCCESSFULLY, + returned.description()); } else - Messaging.sendErrorTr((CommandSender) context.getForWhom(), - Messages.WAYPOINT_TRIGGER_EDITOR_INACTIVE); + Messaging.sendErrorTr((CommandSender) context.getForWhom(), Messages.WAYPOINT_TRIGGER_EDITOR_INACTIVE); } if (context.getSessionData("said") == Boolean.TRUE) return ""; context.setSessionData("said", true); context.setSessionData(WaypointTriggerPrompt.RETURN_PROMPT_KEY, this); - return Messaging.tr(Messages.WAYPOINT_TRIGGER_ADD_PROMPT, - WaypointTriggerRegistry.describeValidTriggerNames()); + return Messaging.tr(Messages.WAYPOINT_TRIGGER_ADD_PROMPT, WaypointTriggerRegistry.describeValidTriggerNames()); } } diff --git a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerEditPrompt.java b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerEditPrompt.java index 31c9843c2..71d921d4a 100644 --- a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerEditPrompt.java +++ b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerEditPrompt.java @@ -53,9 +53,9 @@ public class TriggerEditPrompt extends StringPrompt { } public static Conversation start(Player player, WaypointEditor editor) { - final Conversation conversation = new ConversationFactory(CitizensAPI.getPlugin()) - .withLocalEcho(false).withEscapeSequence("exit").withEscapeSequence("/npc path") - .withModality(false).withFirstPrompt(new TriggerEditPrompt(editor)).buildConversation(player); + final Conversation conversation = new ConversationFactory(CitizensAPI.getPlugin()).withLocalEcho(false) + .withEscapeSequence("exit").withEscapeSequence("/npc path").withModality(false) + .withFirstPrompt(new TriggerEditPrompt(editor)).buildConversation(player); conversation.begin(); return conversation; } diff --git a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerRemovePrompt.java b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerRemovePrompt.java index e265a098b..bd22a51e2 100644 --- a/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerRemovePrompt.java +++ b/src/main/java/net/citizensnpcs/trait/waypoint/triggers/TriggerRemovePrompt.java @@ -25,16 +25,15 @@ public class TriggerRemovePrompt extends StringPrompt { return (Prompt) context.getSessionData("previous"); } if (editor.getCurrentWaypoint() == null) { - Messaging.sendErrorTr((CommandSender) context.getForWhom(), - Messages.WAYPOINT_TRIGGER_EDITOR_INACTIVE); + Messaging.sendErrorTr((CommandSender) context.getForWhom(), Messages.WAYPOINT_TRIGGER_EDITOR_INACTIVE); return this; } int index = 0; try { index = Math.max(0, Integer.parseInt(input) - 1); } catch (NumberFormatException e) { - Messaging.sendErrorTr((CommandSender) context.getForWhom(), - Messages.WAYPOINT_TRIGGER_REMOVE_INVALID_NUMBER); + Messaging + .sendErrorTr((CommandSender) context.getForWhom(), Messages.WAYPOINT_TRIGGER_REMOVE_INVALID_NUMBER); return this; } List triggers = editor.getCurrentWaypoint().getTriggers(); @@ -43,8 +42,7 @@ public class TriggerRemovePrompt extends StringPrompt { Messages.WAYPOINT_TRIGGER_REMOVE_INDEX_OUT_OF_RANGE, triggers.size()); } else { triggers.remove(index); - Messaging.sendTr((CommandSender) context.getForWhom(), Messages.WAYPOINT_TRIGGER_REMOVE_REMOVED, - index + 1); + Messaging.sendTr((CommandSender) context.getForWhom(), Messages.WAYPOINT_TRIGGER_REMOVE_REMOVED, index + 1); } return this; } @@ -52,8 +50,7 @@ public class TriggerRemovePrompt extends StringPrompt { @Override public String getPromptText(ConversationContext context) { if (editor.getCurrentWaypoint() == null) { - Messaging.sendErrorTr((CommandSender) context.getForWhom(), - Messages.WAYPOINT_TRIGGER_EDITOR_INACTIVE); + Messaging.sendErrorTr((CommandSender) context.getForWhom(), Messages.WAYPOINT_TRIGGER_EDITOR_INACTIVE); return ""; } if (context.getSessionData("said") == Boolean.TRUE) @@ -64,8 +61,7 @@ public class TriggerRemovePrompt extends StringPrompt { for (WaypointTrigger trigger : editor.getCurrentWaypoint().getTriggers()) { root += String.format("
%d. " + trigger.description(), i++); } - Messaging - .sendTr((CommandSender) context.getForWhom(), Messages.WAYPOINT_TRIGGER_REMOVE_PROMPT + root); + Messaging.sendTr((CommandSender) context.getForWhom(), Messages.WAYPOINT_TRIGGER_REMOVE_PROMPT + root); return ""; } } diff --git a/src/main/java/net/citizensnpcs/util/Anchor.java b/src/main/java/net/citizensnpcs/util/Anchor.java index 19e2039dc..3cd716318 100644 --- a/src/main/java/net/citizensnpcs/util/Anchor.java +++ b/src/main/java/net/citizensnpcs/util/Anchor.java @@ -44,14 +44,14 @@ public class Anchor { } public String stringValue() { - return name + ";" + location.getWorld().getName() + ";" + location.getX() + ";" + location.getY() - + ";" + location.getZ(); + return name + ";" + location.getWorld().getName() + ";" + location.getX() + ";" + location.getY() + ";" + + location.getZ(); } @Override public String toString() { - return "Name: " + name + " World: " + location.getWorld().getName() + " Location: " - + location.getBlockX() + "," + location.getBlockY() + "," + location.getBlockZ(); + return "Name: " + name + " World: " + location.getWorld().getName() + " Location: " + location.getBlockX() + + "," + location.getBlockY() + "," + location.getBlockZ(); } } \ No newline at end of file diff --git a/src/main/java/net/citizensnpcs/util/NMS.java b/src/main/java/net/citizensnpcs/util/NMS.java index a8ee64c83..24c597afc 100644 --- a/src/main/java/net/citizensnpcs/util/NMS.java +++ b/src/main/java/net/citizensnpcs/util/NMS.java @@ -50,38 +50,12 @@ public class NMS { // util class } - public static void sendToOnline(Packet... packets) { - Validate.notNull(packets, "packets cannot be null"); - for (Player player : Bukkit.getOnlinePlayers()) { - if (player == null || !player.isOnline()) - continue; - for (Packet packet : packets) { - sendPacket(player, packet); - } - } - } - - public static void sendPacketNearby(Location location, Packet packet, double radius) { - radius *= radius; - final org.bukkit.World world = location.getWorld(); - for (Player ply : Bukkit.getServer().getOnlinePlayers()) { - if (ply == null || world != ply.getWorld()) { - continue; - } - if (location.distanceSquared(ply.getLocation()) > radius) { - continue; - } - sendPacket(ply, packet); - } - } - - public static void sendPacketNearby(Location location, Packet packet) { - NMS.sendPacketNearby(location, packet, 64); - } - private static final float DEFAULT_SPEED = 0.4F; + private static Map, Integer> ENTITY_CLASS_TO_INT; + private static final Map, Constructor> ENTITY_CONSTRUCTOR_CACHE = new WeakHashMap, Constructor>(); + private static Map> ENTITY_INT_TO_CLASS; private static Field GOAL_FIELD; private static Field LAND_SPEED_MODIFIER_FIELD; @@ -92,9 +66,7 @@ public class NMS { private static Set SLAB_MATERIALS = Sets.newHashSet(); private static Field SPEED_FIELD; private static Set STAIR_MATERIALS = Sets.newHashSet(); - private static Field THREAD_STOPPER; - public static void addOrRemoveFromPlayerList(LivingEntity bukkitEntity, boolean remove) { if (bukkitEntity == null) return; @@ -107,7 +79,6 @@ public class NMS { handle.world.players.add(handle); } } - public static void attack(EntityLiving handle, EntityLiving target) { int damage = handle instanceof EntityMonster ? ((EntityMonster) handle).c((Entity) target) : 2; @@ -157,8 +128,8 @@ public class NMS { } } - private static Constructor getCustomEntityConstructor(Class clazz, EntityType type) - throws SecurityException, NoSuchMethodException { + private static Constructor getCustomEntityConstructor(Class clazz, EntityType type) throws SecurityException, + NoSuchMethodException { Constructor constructor = ENTITY_CONSTRUCTOR_CACHE.get(clazz); if (constructor == null) { constructor = clazz.getConstructor(World.class); @@ -241,6 +212,35 @@ public class NMS { ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); } + public static void sendPacketNearby(Location location, Packet packet) { + NMS.sendPacketNearby(location, packet, 64); + } + + public static void sendPacketNearby(Location location, Packet packet, double radius) { + radius *= radius; + final org.bukkit.World world = location.getWorld(); + for (Player ply : Bukkit.getServer().getOnlinePlayers()) { + if (ply == null || world != ply.getWorld()) { + continue; + } + if (location.distanceSquared(ply.getLocation()) > radius) { + continue; + } + sendPacket(ply, packet); + } + } + + public static void sendToOnline(Packet... packets) { + Validate.notNull(packets, "packets cannot be null"); + for (Player player : Bukkit.getOnlinePlayers()) { + if (player == null || !player.isOnline()) + continue; + for (Packet packet : packets) { + sendPacket(player, packet); + } + } + } + public static void setDestination(LivingEntity bukkitEntity, double x, double y, double z, float speed) { ((CraftLivingEntity) bukkitEntity).getHandle().getControllerMove().a(x, y, z, speed); } diff --git a/src/main/java/net/citizensnpcs/util/Paginator.java b/src/main/java/net/citizensnpcs/util/Paginator.java index b3ecd7f23..a0c07f252 100644 --- a/src/main/java/net/citizensnpcs/util/Paginator.java +++ b/src/main/java/net/citizensnpcs/util/Paginator.java @@ -20,8 +20,7 @@ public class Paginator { } public boolean sendPage(CommandSender sender, int page) { - int pages = (int) ((lines.size() / LINES_PER_PAGE == 0) ? 1 : Math.ceil((double) lines.size() - / LINES_PER_PAGE)); + int pages = (int) ((lines.size() / LINES_PER_PAGE == 0) ? 1 : Math.ceil((double) lines.size() / LINES_PER_PAGE)); if (page < 0 || page > pages) return false; diff --git a/src/main/java/net/citizensnpcs/util/PlayerAnimation.java b/src/main/java/net/citizensnpcs/util/PlayerAnimation.java index a4460cd58..05a2dcecc 100644 --- a/src/main/java/net/citizensnpcs/util/PlayerAnimation.java +++ b/src/main/java/net/citizensnpcs/util/PlayerAnimation.java @@ -33,8 +33,8 @@ public enum PlayerAnimation { SLEEP { @Override protected void playAnimation(EntityPlayer player, int radius) { - Packet17EntityLocationAction packet = new Packet17EntityLocationAction(player, 0, - (int) player.locX, (int) player.locY, (int) player.locZ); + Packet17EntityLocationAction packet = new Packet17EntityLocationAction(player, 0, (int) player.locX, + (int) player.locY, (int) player.locZ); sendPacketNearby(packet, player, radius); } }, @@ -42,8 +42,7 @@ public enum PlayerAnimation { @Override protected void playAnimation(EntityPlayer player, int radius) { player.getBukkitEntity().setSneaking(true); - sendPacketNearby(new Packet40EntityMetadata(player.id, player.getDataWatcher(), true), player, - radius); + sendPacketNearby(new Packet40EntityMetadata(player.id, player.getDataWatcher(), true), player, radius); } }, STOP_SITTING { @@ -63,8 +62,7 @@ public enum PlayerAnimation { @Override protected void playAnimation(EntityPlayer player, int radius) { player.getBukkitEntity().setSneaking(false); - sendPacketNearby(new Packet40EntityMetadata(player.id, player.getDataWatcher(), true), player, - radius); + sendPacketNearby(new Packet40EntityMetadata(player.id, player.getDataWatcher(), true), player, radius); } }; diff --git a/src/main/java/net/citizensnpcs/util/StringHelper.java b/src/main/java/net/citizensnpcs/util/StringHelper.java index 70b5f8fc2..e9b6b3fb3 100644 --- a/src/main/java/net/citizensnpcs/util/StringHelper.java +++ b/src/main/java/net/citizensnpcs/util/StringHelper.java @@ -93,7 +93,6 @@ public class StringHelper { String colors = ""; for (ChatColor color : ChatColor.values()) colors += color.getChar(); - COLOR_MATCHER = Pattern.compile("\\<([COLORS])\\>".replace("COLORS", colors), - Pattern.CASE_INSENSITIVE); + COLOR_MATCHER = Pattern.compile("\\<([COLORS])\\>".replace("COLORS", colors), Pattern.CASE_INSENSITIVE); } } \ No newline at end of file diff --git a/src/main/java/net/citizensnpcs/util/Translator.java b/src/main/java/net/citizensnpcs/util/Translator.java index f0ed1e1f1..149a3b0d8 100644 --- a/src/main/java/net/citizensnpcs/util/Translator.java +++ b/src/main/java/net/citizensnpcs/util/Translator.java @@ -37,8 +37,8 @@ public class Translator { this.resourceFile = resourceFile; this.defaultLocale = locale; try { - preferredBundle = ResourceBundle.getBundle(PREFIX, defaultLocale, new FileClassLoader( - Translator.class.getClassLoader(), resourceFile)); + preferredBundle = ResourceBundle.getBundle(PREFIX, defaultLocale, + new FileClassLoader(Translator.class.getClassLoader(), resourceFile)); } catch (MissingResourceException e) { preferredBundle = getDefaultBundle(); Messaging.log(translate(Messages.MISSING_TRANSLATIONS, locale)); @@ -53,8 +53,8 @@ public class Translator { private ResourceBundle getBundle(Locale locale) { try { - ResourceBundle bundle = ResourceBundle.getBundle(PREFIX, locale, new FileClassLoader( - Translator.class.getClassLoader(), resourceFile)); + ResourceBundle bundle = ResourceBundle.getBundle(PREFIX, locale, + new FileClassLoader(Translator.class.getClassLoader(), resourceFile)); return bundle == null ? preferredBundle : bundle; } catch (MissingResourceException e) { return preferredBundle; @@ -275,8 +275,8 @@ public class Translator { public static String translate(String key, Locale preferredLocale, Object... msg) { if (instance == null) createInstance(); - return StringHelper.parseColors(msg.length == 0 ? instance.translate(key, preferredLocale) : instance - .format(key, preferredLocale, msg)); + return StringHelper.parseColors(msg.length == 0 ? instance.translate(key, preferredLocale) : instance.format( + key, preferredLocale, msg)); } public static String translate(String key, Object... msg) {