From b0aa11475e5f29afcaa0ba5cb33a9df0c9f1f44b Mon Sep 17 00:00:00 2001 From: Richard Date: Thu, 3 Mar 2016 22:01:19 -0300 Subject: [PATCH] Hopefuly should work fine. Updated to 1.9, moving from Reflection to a new method using and Interface with useful NMS methods (some expressions are still using Reflection). --- .classpath | 27 +- plugin.yml | 10 +- src/me/TheBukor/SkStuff/SkStuff.java | 434 +++--- .../SkStuff/effects/EffClearPathGoals.java | 106 +- .../TheBukor/SkStuff/effects/EffGZipFile.java | 105 +- .../TheBukor/SkStuff/effects/EffMakeJump.java | 100 +- .../SkStuff/effects/EffRemovePathGoal.java | 489 ++++--- .../SkStuff/effects/EffSetPathGoal.java | 1225 +++++++++-------- .../expressions/ExprEndermanBlocks.java | 326 ++--- .../SkStuff/expressions/ExprFileNBT.java | 169 +-- .../SkStuff/expressions/ExprItemNBT.java | 109 +- .../expressions/ExprNBTListContents.java | 146 +- .../SkStuff/expressions/ExprNBTListIndex.java | 153 +- .../SkStuff/expressions/ExprNBTOf.java | 299 ++-- .../SkStuff/expressions/ExprTagOf.java | 386 +++--- src/me/TheBukor/SkStuff/util/NBTUtil.java | 179 --- .../TheBukor/SkStuff/util/NMSInterface.java | 108 +- src/me/TheBukor/SkStuff/util/NMS_v1_7_R4.java | 940 +++++++------ src/me/TheBukor/SkStuff/util/NMS_v1_8_R1.java | 986 +++++++------ src/me/TheBukor/SkStuff/util/NMS_v1_8_R2.java | 997 ++++++++------ src/me/TheBukor/SkStuff/util/NMS_v1_8_R3.java | 1146 ++++++++------- src/me/TheBukor/SkStuff/util/NMS_v1_9_R1.java | 562 ++++++++ .../SkStuff/util/ReflectionUtils.java | 136 +- 23 files changed, 4900 insertions(+), 4238 deletions(-) delete mode 100644 src/me/TheBukor/SkStuff/util/NBTUtil.java create mode 100644 src/me/TheBukor/SkStuff/util/NMS_v1_9_R1.java diff --git a/.classpath b/.classpath index 229d6b7..6edceba 100644 --- a/.classpath +++ b/.classpath @@ -1,13 +1,14 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/plugin.yml b/plugin.yml index c5f377c..f97c1f9 100644 --- a/plugin.yml +++ b/plugin.yml @@ -1,6 +1,6 @@ -name: SkStuff -author: TheBukor -description: A Skript addon which adds extra functionalities such as NBT and extended WorldEdit support. -version: 1.5.1 -main: me.TheBukor.SkStuff.SkStuff +name: SkStuff +author: TheBukor +description: A Skript addon which adds extra functionalities such as NBT and extended WorldEdit support. +version: 1.6 +main: me.TheBukor.SkStuff.SkStuff softdepend: [Skript, WorldEdit] \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/SkStuff.java b/src/me/TheBukor/SkStuff/SkStuff.java index 4fda291..4a56458 100644 --- a/src/me/TheBukor/SkStuff/SkStuff.java +++ b/src/me/TheBukor/SkStuff/SkStuff.java @@ -1,219 +1,217 @@ -package me.TheBukor.SkStuff; - -import javax.annotation.Nullable; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.java.JavaPlugin; - -import com.sk89q.worldedit.EditSession; - -import ch.njol.skript.Skript; -import ch.njol.skript.classes.ClassInfo; -import ch.njol.skript.lang.ExpressionType; -import ch.njol.skript.lang.util.SimpleEvent; -import ch.njol.skript.registrations.Classes; -import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; -import me.TheBukor.SkStuff.conditions.CondSelectionContains; -import me.TheBukor.SkStuff.effects.EffClearPathGoals; -import me.TheBukor.SkStuff.effects.EffDrainLiquid; -import me.TheBukor.SkStuff.effects.EffDrawLineWE; -import me.TheBukor.SkStuff.effects.EffGZipFile; -import me.TheBukor.SkStuff.effects.EffMakeCylinder; -import me.TheBukor.SkStuff.effects.EffMakeJump; -import me.TheBukor.SkStuff.effects.EffMakePyramid; -import me.TheBukor.SkStuff.effects.EffMakeSphere; -import me.TheBukor.SkStuff.effects.EffMakeWalls; -import me.TheBukor.SkStuff.effects.EffNaturalize; -import me.TheBukor.SkStuff.effects.EffPasteSchematic; -import me.TheBukor.SkStuff.effects.EffRememberChanges; -import me.TheBukor.SkStuff.effects.EffRemovePathGoal; -import me.TheBukor.SkStuff.effects.EffReplaceBlocksWE; -import me.TheBukor.SkStuff.effects.EffSetBlocksWE; -import me.TheBukor.SkStuff.effects.EffSetPathGoal; -import me.TheBukor.SkStuff.effects.EffShowEntityEffect; -import me.TheBukor.SkStuff.effects.EffSimulateSnow; -import me.TheBukor.SkStuff.effects.EffToggleVanish; -import me.TheBukor.SkStuff.effects.EffUndoRedoSession; -import me.TheBukor.SkStuff.events.EvtWorldEditChange; -import me.TheBukor.SkStuff.events.WorldEditChangeHandler; -import me.TheBukor.SkStuff.expressions.ExprChangedBlocksSession; -import me.TheBukor.SkStuff.expressions.ExprClickedInventory; -import me.TheBukor.SkStuff.expressions.ExprEditSessionLimit; -import me.TheBukor.SkStuff.expressions.ExprEndermanBlocks; -import me.TheBukor.SkStuff.expressions.ExprFileNBT; -import me.TheBukor.SkStuff.expressions.ExprFireProof; -import me.TheBukor.SkStuff.expressions.ExprItemNBT; -import me.TheBukor.SkStuff.expressions.ExprNBTListContents; -import me.TheBukor.SkStuff.expressions.ExprNBTListIndex; -import me.TheBukor.SkStuff.expressions.ExprNBTOf; -import me.TheBukor.SkStuff.expressions.ExprNewEditSession; -import me.TheBukor.SkStuff.expressions.ExprNoClip; -import me.TheBukor.SkStuff.expressions.ExprSchematicArea; -import me.TheBukor.SkStuff.expressions.ExprSelectionArea; -import me.TheBukor.SkStuff.expressions.ExprSelectionOfPlayer; -import me.TheBukor.SkStuff.expressions.ExprSelectionPos; -import me.TheBukor.SkStuff.expressions.ExprTagOf; -import me.TheBukor.SkStuff.expressions.ExprTimespanToNumber; -import me.TheBukor.SkStuff.expressions.ExprToLowerCase; -import me.TheBukor.SkStuff.expressions.ExprToUpperCase; -import me.TheBukor.SkStuff.expressions.ExprVanishState; -import me.TheBukor.SkStuff.expressions.ExprWordsToUpperCase; -import me.TheBukor.SkStuff.util.NMSInterface; -import me.TheBukor.SkStuff.util.NMS_v1_7_R4; -import me.TheBukor.SkStuff.util.NMS_v1_8_R1; -import me.TheBukor.SkStuff.util.NMS_v1_8_R2; -import me.TheBukor.SkStuff.util.NMS_v1_8_R3; -import me.TheBukor.SkStuff.util.ReflectionUtils; - -public class SkStuff extends JavaPlugin { - private int condAmount = 0; - private int effAmount = 0; - private int evtAmount = 0; - private int exprAmount = 0; - private int typeAmount = 0; - - public static SkStuff instance; - - private static NMSInterface nmsMethods; - - public void onEnable() { - if (Bukkit.getPluginManager().getPlugin("Skript") != null && Skript.isAcceptRegistrations()) { - Skript.registerAddon(this); - getLogger().info("SkStuff " + this.getDescription().getVersion() + " has been successfully enabled!"); - - getLogger().info("Registering general non version specific stuff..."); - Skript.registerEffect(EffShowEntityEffect.class, "(display|play|show) entity effect (0¦firework[s] explo(de|sion)|1¦hurt|2¦[[iron] golem] (give|offer) (rose|poppy)|3¦[sheep] eat grass|4¦wolf shake) at %entity%"); - Skript.registerExpression(ExprToUpperCase.class, String.class, ExpressionType.SIMPLE, "%string% [converted] to [all] (cap[ital]s|upper[ ]case)", "convert %string% to [all] (cap[ital]s|upper[ ]case)", "capitalize [all] [char[acter]s (of|in)] %string%"); - Skript.registerExpression(ExprToLowerCase.class, String.class, ExpressionType.SIMPLE, "%string% [converted] to [all] lower[ ]case", "convert %string% to [all] lower[ ]case", "un[( |-)]capitalize [all] [char[acter]s (of|in)] %string%"); - Skript.registerExpression(ExprWordsToUpperCase.class, String.class, ExpressionType.SIMPLE, "(first|1st) (letter|char[acter]) (of|in) (each word|[all] words) (of|in) %string% [converted] to (cap[ital]s|upper[ ]case) (0¦|1¦ignoring [other] upper[ ]case [(char[acter]s|letters)])", "convert (first|1st) (letter|char[acter]) (of|in) (each word|[all] words) (of|in) %string% to (cap[ital]s|upper[ ]case) (0¦|1¦ignoring [other] upper[ ]case [(char[acter]s|letters)])", "capitalize (first|1st) (letter|char[acter]) (of|in) (each word|[all] words) (of|in) %string% (0¦|1¦ignoring [other] upper[ ]case [(char[acter]s|letters)])"); - Skript.registerExpression(ExprTimespanToNumber.class, Number.class, ExpressionType.SIMPLE, "%timespan% [converted] [in]to (0¦ticks|1¦sec[ond]s|2¦min[ute]s|3¦hours|4¦days)"); - Skript.registerExpression(ExprClickedInventory.class, Inventory.class, ExpressionType.SIMPLE, "[skstuff] clicked inventory"); - effAmount += 1; - exprAmount += 5; - - if (setupNMSVersion()) { - getLogger().info("Trying to register version specific stuff..."); - Skript.registerEffect(EffClearPathGoals.class, "(clear|delete) [all] pathfind[er] goals (of|from) %livingentity%"); - Skript.registerEffect(EffRemovePathGoal.class, "remove pathfind[er] goal (0¦(avoid|run away from) entit(y|ies)|1¦break door[s]|2¦breed|3¦eat grass|4¦(flee from the sun|seek shad(e|ow))|5¦float (in[side]|on) water|6¦follow (owner|tamer)|7¦follow (adult|parent)[s]|8¦(fight back|react to|target) (damager|attacker)|9¦o(c|z)elot jump on blocks|10¦leap at target|11¦look at entit(y|ies)|12¦melee attack entit(y|ies)|13¦move to[wards] target|14¦target nearest entity|15¦o(c|z)elot attack [chicken[s]]|16¦open door[s]|17¦(panic|flee)|18¦look around randomly|19¦(walk around randomly|wander)|20¦sit|21¦[creeper] (explode|inflate|swell)|22¦squid (swim|wander)|23¦shoot fireball[s]|24¦[silverfish] hide (in[side]|on) block[s]|25¦(wake other silverfish[es]|[silverfish] call (help|reinforcement|other [hidden] silverfish[es]))|26¦[enderm(a|e)n] pick[[ ]up] block[s]|27¦[enderm(a|e)n] place block[s]|28¦[enderman] attack player (staring|looking) [at eye[s]]|29¦ghast move to[wards] target|30¦ghast (idle move[ment]|wander|random fl(ight|y[ing]))|31¦(tempt to|follow players (holding|with)) [a[n]] item|32¦target [random] entity (if|when) (not tamed|untamed)|33¦guardian attack [entity]|34¦[z[ombie[ ]]pig[man]] attack [player[s]] (if|when) angry|35¦[z[ombie[ ]]pig[man]] (react to|fight back|target) (attacker|damager) (if|when) angry|36¦[rabbit] eat carrot crops|37¦[killer] rabbit [melee] attack|38¦slime [random] jump|39¦slime change (direction|facing) randomly|40¦slime (idle move[ment]|wander)) from %livingentity%"); - Skript.registerEffect(EffSetPathGoal.class, "add pathfind[er] goal [[with] priority %-integer%] (0¦(avoid|run away from) %entitydata%[, radius %-number%[, speed %-number%[, speed (if|when) (close|near) %-number%]]]|1¦break door[s]|2¦breed[,[move[ment]] speed %-number%]|3¦eat grass|4¦(flee from the sun|seek shad(e|ow))[, [move[ment]] speed %-number%]|5¦(float (in[side]|on) water|swim)|6¦follow (owner|tamer)[, speed %-number%[, min[imum] distance %-number%[, max[imum] distance %-number%]]]|7¦follow (adult|parent)[s][, [move[ment]] speed %-number%]|8¦(fight back|react to|target) (damager|attacker) [[of] type] %entitydata%[, call ([for] help|reinforcement) %-boolean%]|9¦o(c|z)elot jump on blocks[, [move[ment]] speed %-number%]|10¦leap at target[, [leap] height %-number%]|11¦look at %entitydata%[, (radius|max[imum] distance) %-number%]|12¦melee attack %entitydata%[, [move[ment]] speed %-number%[, (memorize|do('nt| not) forget) target [for [a] long[er] time] %-boolean%]]|13¦move to[wards] target[, [move[ment]] speed %-number%[, (radius|max[imum] distance) %-number%]]|14¦target nearest [entity [of] type] %entitydata%[, check sight %-boolean%]|15¦o(c|z)elot attack|16¦open door[s]|17¦(panic|flee)[, [move[ment]] speed %-number%]|18¦look around randomly|19¦(walk around randomly|wander)[, [move[ment]] speed %-number%[, min[imum] [of] %-timespan% between mov(e[ment][s]|ing)]]|20¦sit|21¦[creeper] (explode|inflate|swell)|22¦squid (swim around|wander)|23¦shoot fireball[s]|24¦[silverfish] hide (in[side]|on) block[s]|25¦((call|summon|wake) [other] [hidden] silverfish[es])|26¦[enderman] pick[[ ]up] block[s]|27¦[enderman] place block[s]|28¦[enderman] attack player (staring|looking) at [their] eye[s]]|29¦ghast move to[wards] target|30¦ghast (idle move[ment]|wander|random fl(ight|y[ing]))|31¦(tempt to|follow players (holding|with)) %-itemstack%[, [move[ment]] speed %number%[, scared of player movement %-boolean%]]|32¦target [random] %entitydata% (if|when) (not |un)tamed|33¦guardian attack [entities]|34¦[z[ombie[ ]]pig[man]] attack [player[s]] (if|when) angry|35¦[z[ombie[ ]]pig[man]] (react to|fight back|target) (attacker|damager) (if|when) angry|36¦[rabbit] eat carrot crops|37¦[killer] rabbit [melee] attack|38¦slime [random] jump|39¦slime change (direction|facing) randomly|40¦slime (idle move[ment]|wander)) to %livingentity%"); - Skript.registerEffect(EffMakeJump.class, "make %livingentities% jump", "force %livingentities% to jump"); - Skript.registerEffect(EffGZipFile.class, "create [a] gzip[ped] file [at] %string%"); - Skript.registerExpression(ExprNBTOf.class, Object.class, ExpressionType.PROPERTY, "nbt[[ ]tag[s]] of %~object%", "%~object%'s nbt[[ ]tag[s]]"); - Skript.registerExpression(ExprItemNBT.class, ItemStack.class, ExpressionType.SIMPLE, "%itemstack% with [custom] nbt[[ ]tag[s]] %string%"); - Skript.registerExpression(ExprTagOf.class, Object.class, ExpressionType.PROPERTY, "[nbt[ ]]tag %string% of [[nbt] compound] %compound%"); - Skript.registerExpression(ExprFileNBT.class, Object.class, ExpressionType.PROPERTY, "nbt[[ ]tag[s]] from [file] %string%"); - Skript.registerExpression(ExprNBTListIndex.class, Object.class, ExpressionType.PROPERTY, "[nbt[ ]list] %nbtlist% index %number%"); - Skript.registerExpression(ExprNBTListContents.class, Object.class, ExpressionType.PROPERTY, "[all] contents (of|from) [nbt[ ]list] %nbtlist%", "[nbt[ ]list] %nbtlist% contents"); - Skript.registerExpression(ExprNoClip.class, Boolean.class, ExpressionType.PROPERTY, "no[( |-)]clip (state|mode) of %entities%", "%entities%'s no[( |-)]clip (state|mode)"); - Skript.registerExpression(ExprFireProof.class, Boolean.class, ExpressionType.PROPERTY, "fire[ ]proof (state|mode) of %entities%", "%entities%'s fire[ ]proof (state|mode)"); - Skript.registerExpression(ExprEndermanBlocks.class, ItemStack.class, ExpressionType.PROPERTY, "blocks that %entity% can (carry|hold|grab|steal)"); - nmsMethods.registerCompoundClassInfo(); - nmsMethods.registerNBTListClassInfo(); - effAmount += 5; - exprAmount += 9; - typeAmount += 2; - } - if (Bukkit.getPluginManager().getPlugin("WorldEdit") != null) { - getLogger().info("WorldEdit found! Registering WorldEdit stuff..."); - Skript.registerCondition(CondSelectionContains.class, "[(world[ ]edit|we)] selection of %player% (contains|has) %location%", "%player%'s [(world[ ]edit|we)] selection (contains|has) %location%", "[(world[ ]edit|we)] selection of %player% does(n't| not) (contain|have) %location%", "%player%'s [(world[ ]edit|we)] selection does(n't| not) (contain|have) %location%"); - Skript.registerEffect(EffDrawLineWE.class, "(create|draw|make) [a[n]] (0¦(no(n|t)(-| )hollow|filled|)|1¦hollow) line from %location% to %location% (using|with) [edit[ ]session] %editsession% (using|with) [block[s]] %itemstacks% [with] thick[ness] %double%"); - Skript.registerEffect(EffUndoRedoSession.class, "(0¦undo|1¦redo) (change|edit)s (of|from) [edit[ ]session] %editsession%"); - Skript.registerEffect(EffRememberChanges.class, "make %player% (remember|be able to undo) changes (of|from) [edit[ ]session] %editsession%"); - Skript.registerEffect(EffMakeSphere.class, "(create|make) [a[n]] (0¦(no(n|t)(-| )hollow|filled|)|1¦hollow) (ellipsoid|sphere) [centered] at %location% [with] radius [of] %double%,[ ]%double%(,[ ]| and )%double% (using|with) [edit[ ]session] %editsession% (using|with) [block[s]] %itemstacks%"); - Skript.registerEffect(EffSimulateSnow.class, "(simulate snow at|place snow over) %location% (in|within) [a] radius [of] %double% (using|with) [edit[ ]session] %editsession%", "make %location% snowy (in|within) [a] radius [of] %double% (using|with) [edit[ ]session] %editsession%"); - Skript.registerEffect(EffMakePyramid.class, "(create|make) [a[n]] (0¦(no(n|t)(-| )hollow|filled|)|1¦hollow) pyramid at %location% [with] radius [of] %integer% (using|with) [edit[ ]session] %editsession% (using|with) [block[s]] %itemstacks%"); - Skript.registerEffect(EffDrainLiquid.class, "(drain|remove) [all] liquid[s] at %location% (in|within) [a] radius [of] %double% (using|with) [edit[ ]session] %editsession%"); - Skript.registerEffect(EffNaturalize.class, "naturalize ([cuboid] region|[all] blocks) (from|between) %location% (to|and) %location% (using|with) [edit[ ]session] %editsession%"); - Skript.registerEffect(EffMakeWalls.class, "(create|make) wall[s] from %location% to %location% (using|with) [edit[ ]session] %editsession% (using|with) [block[s]] %itemstacks%"); - Skript.registerEffect(EffSetBlocksWE.class, "set [all] blocks (from|between) %location% (to|and) %location% to %itemstacks% (using|with) [edit[ ]session] %editsession%"); - Skript.registerEffect(EffMakeCylinder.class, "(create|make) [a[n]] (0¦(no(n|t)(-| )hollow|filled|)|1¦hollow) cylinder at %location% [with] radius [of] %double%,[ ]%integer%(,[ ]| and )%double% (using|with) [edit[ ]session] %editsession% (using|with) [block[s]] %itemstacks%"); - Skript.registerEffect(EffReplaceBlocksWE.class, "replace [all] %itemstacks% (from|between) %location% (to|and) %location% with %itemstacks% (using|with) [edit[ ]session] %editsession%"); - Skript.registerEffect(EffPasteSchematic.class, "paste schem[atic] %string% at %location% using [edit[ ]session] %editsession% (0¦|1¦(ignor(e|ing)|without|[with] no) air)"); - Skript.registerExpression(ExprEditSessionLimit.class, Integer.class, ExpressionType.PROPERTY, "[block] limit [change] of [edit[ ]session] %editsession%"); - Skript.registerExpression(ExprChangedBlocksSession.class, Integer.class, ExpressionType.PROPERTY, "number of [all] changed blocks (in|of) [edit[ ]session] %editsession%"); - Skript.registerExpression(ExprNewEditSession.class, EditSession.class, ExpressionType.PROPERTY, "[new] edit[ ]session in [world] %world% [with] [max[imum]] [block] limit [change] [of] %integer%"); - Skript.registerExpression(ExprSelectionOfPlayer.class, Location.class, ExpressionType.PROPERTY, "[(world[ ]edit|we)] selection of %player%", "%player%'s [(world[ ]edit|we)] selection"); - Skript.registerExpression(ExprSelectionPos.class, Location.class, ExpressionType.PROPERTY, "[(world[ ]edit|we)] po(s|int)[ ](0¦1|1¦2) of %player%", "%player%'s [(world[ ]edit|we)] po(s|int)[ ](0¦1|1¦2)"); - Skript.registerExpression(ExprSelectionArea.class, Integer.class, ExpressionType.SIMPLE, "(0¦volume|1¦(x( |-)size|width)|2¦(y( |-)size|height)|3¦(z( |-)size|length)|4¦area) of [(world[ ]edit|we)] selection of %player%", "%player%'s [(world[ ]edit|we)] selection (0¦volume|1¦(x( |-)size|width)|2¦(y( |-)size|height)|3¦(z( |-)size|length)|4¦area)"); - Skript.registerExpression(ExprSchematicArea.class, Integer.class, ExpressionType.SIMPLE, "(0¦volume|1¦(x( |-)size|width)|2¦(y( |-)size|height)|3¦(z( |-)size|length)|4¦area) of schem[atic] [from] %string%"); - Classes.registerClass(new ClassInfo(EditSession.class, "editsession").name("Edit Session").user("edit ?sessions?")); - try { - Class.forName("com.sk89q.worldedit.extent.logging.AbstractLoggingExtent"); - new WorldEditChangeHandler(); - Skript.registerEvent("WorldEdit block change", SimpleEvent.class, EvtWorldEditChange.class, "world[ ]edit [block] (chang(e|ing)|edit[ing])"); - EventValues.registerEventValue(EvtWorldEditChange.class, Player.class, new Getter() { - @Override - @Nullable - public Player get(EvtWorldEditChange e) { - return EvtWorldEditChange.getPlayer(); - } - }, 0); - EventValues.registerEventValue(EvtWorldEditChange.class, Block.class, new Getter() { - @Override - @Nullable - public Block get(EvtWorldEditChange e) { - return EvtWorldEditChange.getBlock(); - } - }, 0); - evtAmount += 1; - } catch (ClassNotFoundException ex) { - Skript.error("Unable to register \"On WorldEdit block change\" event! You will need to upgrade to WorldEdit 6.0"); - return; - } - condAmount += 1; - effAmount += 13; - exprAmount += 7; - typeAmount += 1; - } - if (Bukkit.getPluginManager().getPlugin("VanishNoPacket") != null) { - getLogger().info("VanishNoPacket was found! Registering vanishing features..."); - Skript.registerEffect(EffToggleVanish.class, "toggle vanish (state|mode) of %player% (0¦|1¦(silently|quietly))", "toggle %player%'s vanish (state|mode) (0¦|1¦(silently|quietly))"); - Skript.registerExpression(ExprVanishState.class, Boolean.class, ExpressionType.PROPERTY, "vanish (state|mode) of %player%", "%player%'s vanish (state|mode)"); - effAmount += 1; - exprAmount += 1; - } - getLogger().info("Everything ready! Loaded a total of " + condAmount + " conditions, " + effAmount + " effects, " + evtAmount + "events, " + exprAmount + " expressions and " + typeAmount + " types!"); - } else { - getLogger().info("Unable to find Skript or Skript isn't accepting registrations, disabling SkStuff..."); - Bukkit.getPluginManager().disablePlugin(this);; - } - } - - private boolean setupNMSVersion() { - String version = ReflectionUtils.getVersion(); - if (version.equals("v1_7_R4.")) { - nmsMethods = new NMS_v1_7_R4(); - getLogger().info("It looks like you're running 1.7.10!"); - } else if (version.equals("v1_8_R1.")) { - nmsMethods = new NMS_v1_8_R1(); - getLogger().info("It looks like you're running 1.8.0!"); - } else if (version.equals("v1_8_R2.")) { - nmsMethods = new NMS_v1_8_R2(); - getLogger().info("It looks like you're running 1.8.3!"); - } else if (version.equals("v1_8_R3.")) { - nmsMethods = new NMS_v1_8_R3(); - getLogger().info("It looks like you're either running 1.8.7, 1.8.8 or 1.8.9!"); - } else { - getLogger().warning("It looks like you're running an unsupported server version, some features will not be available :("); - } - return nmsMethods != null; - } - - public static SkStuff getInstance() { - return instance; - } - - public static NMSInterface getNMSMethods() { - return nmsMethods; - } - - public void onDisable() { - getLogger().info("SkStuff " + this.getDescription().getVersion() + " has been successfully disabled."); - } +package me.TheBukor.SkStuff; + +import javax.annotation.Nullable; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; + +import com.sk89q.worldedit.EditSession; + +import ch.njol.skript.Skript; +import ch.njol.skript.classes.ClassInfo; +import ch.njol.skript.lang.ExpressionType; +import ch.njol.skript.lang.util.SimpleEvent; +import ch.njol.skript.registrations.Classes; +import ch.njol.skript.registrations.EventValues; +import ch.njol.skript.util.Getter; +import me.TheBukor.SkStuff.conditions.CondSelectionContains; +import me.TheBukor.SkStuff.effects.EffClearPathGoals; +import me.TheBukor.SkStuff.effects.EffDrainLiquid; +import me.TheBukor.SkStuff.effects.EffDrawLineWE; +import me.TheBukor.SkStuff.effects.EffGZipFile; +import me.TheBukor.SkStuff.effects.EffMakeCylinder; +import me.TheBukor.SkStuff.effects.EffMakeJump; +import me.TheBukor.SkStuff.effects.EffMakePyramid; +import me.TheBukor.SkStuff.effects.EffMakeSphere; +import me.TheBukor.SkStuff.effects.EffMakeWalls; +import me.TheBukor.SkStuff.effects.EffNaturalize; +import me.TheBukor.SkStuff.effects.EffPasteSchematic; +import me.TheBukor.SkStuff.effects.EffRememberChanges; +import me.TheBukor.SkStuff.effects.EffRemovePathGoal; +import me.TheBukor.SkStuff.effects.EffReplaceBlocksWE; +import me.TheBukor.SkStuff.effects.EffSetBlocksWE; +import me.TheBukor.SkStuff.effects.EffSetPathGoal; +import me.TheBukor.SkStuff.effects.EffShowEntityEffect; +import me.TheBukor.SkStuff.effects.EffSimulateSnow; +import me.TheBukor.SkStuff.effects.EffToggleVanish; +import me.TheBukor.SkStuff.effects.EffUndoRedoSession; +import me.TheBukor.SkStuff.events.EvtWorldEditChange; +import me.TheBukor.SkStuff.events.WorldEditChangeHandler; +import me.TheBukor.SkStuff.expressions.ExprChangedBlocksSession; +import me.TheBukor.SkStuff.expressions.ExprClickedInventory; +import me.TheBukor.SkStuff.expressions.ExprEditSessionLimit; +import me.TheBukor.SkStuff.expressions.ExprEndermanBlocks; +import me.TheBukor.SkStuff.expressions.ExprFileNBT; +import me.TheBukor.SkStuff.expressions.ExprFireProof; +import me.TheBukor.SkStuff.expressions.ExprItemNBT; +import me.TheBukor.SkStuff.expressions.ExprNBTListContents; +import me.TheBukor.SkStuff.expressions.ExprNBTListIndex; +import me.TheBukor.SkStuff.expressions.ExprNBTOf; +import me.TheBukor.SkStuff.expressions.ExprNewEditSession; +import me.TheBukor.SkStuff.expressions.ExprNoClip; +import me.TheBukor.SkStuff.expressions.ExprSchematicArea; +import me.TheBukor.SkStuff.expressions.ExprSelectionArea; +import me.TheBukor.SkStuff.expressions.ExprSelectionOfPlayer; +import me.TheBukor.SkStuff.expressions.ExprSelectionPos; +import me.TheBukor.SkStuff.expressions.ExprTagOf; +import me.TheBukor.SkStuff.expressions.ExprTimespanToNumber; +import me.TheBukor.SkStuff.expressions.ExprToLowerCase; +import me.TheBukor.SkStuff.expressions.ExprToUpperCase; +import me.TheBukor.SkStuff.expressions.ExprVanishState; +import me.TheBukor.SkStuff.expressions.ExprWordsToUpperCase; +import me.TheBukor.SkStuff.util.NMSInterface; +import me.TheBukor.SkStuff.util.NMS_v1_7_R4; +import me.TheBukor.SkStuff.util.NMS_v1_8_R1; +import me.TheBukor.SkStuff.util.NMS_v1_8_R2; +import me.TheBukor.SkStuff.util.NMS_v1_8_R3; +import me.TheBukor.SkStuff.util.NMS_v1_9_R1; +import me.TheBukor.SkStuff.util.ReflectionUtils; + +public class SkStuff extends JavaPlugin { + private int condAmount = 0; + private int effAmount = 0; + private int evtAmount = 0; + private int exprAmount = 0; + private int typeAmount = 0; + + private static NMSInterface nmsMethods; + + public void onEnable() { + if (Bukkit.getPluginManager().getPlugin("Skript") != null && Skript.isAcceptRegistrations()) { + Skript.registerAddon(this); + getLogger().info("SkStuff " + this.getDescription().getVersion() + " has been successfully enabled!"); + + getLogger().info("Registering general non version specific stuff..."); + Skript.registerEffect(EffShowEntityEffect.class, "(display|play|show) entity effect (0¦firework[s] explo(de|sion)|1¦hurt|2¦[[iron] golem] (give|offer) (rose|poppy)|3¦[sheep] eat grass|4¦wolf shake) at %entity%"); + Skript.registerExpression(ExprToUpperCase.class, String.class, ExpressionType.SIMPLE, "%string% [converted] to [all] (cap[ital]s|upper[ ]case)", "convert %string% to [all] (cap[ital]s|upper[ ]case)", "capitalize [all] [char[acter]s (of|in)] %string%"); + Skript.registerExpression(ExprToLowerCase.class, String.class, ExpressionType.SIMPLE, "%string% [converted] to [all] lower[ ]case", "convert %string% to [all] lower[ ]case", "un[( |-)]capitalize [all] [char[acter]s (of|in)] %string%"); + Skript.registerExpression(ExprWordsToUpperCase.class, String.class, ExpressionType.SIMPLE, "(first|1st) (letter|char[acter]) (of|in) (each word|[all] words) (of|in) %string% [converted] to (cap[ital]s|upper[ ]case) (0¦|1¦ignoring [other] upper[ ]case [(char[acter]s|letters)])", "convert (first|1st) (letter|char[acter]) (of|in) (each word|[all] words) (of|in) %string% to (cap[ital]s|upper[ ]case) (0¦|1¦ignoring [other] upper[ ]case [(char[acter]s|letters)])", "capitalize (first|1st) (letter|char[acter]) (of|in) (each word|[all] words) (of|in) %string% (0¦|1¦ignoring [other] upper[ ]case [(char[acter]s|letters)])"); + Skript.registerExpression(ExprTimespanToNumber.class, Number.class, ExpressionType.SIMPLE, "%timespan% [converted] [in]to (0¦ticks|1¦sec[ond]s|2¦min[ute]s|3¦hours|4¦days)"); + Skript.registerExpression(ExprClickedInventory.class, Inventory.class, ExpressionType.SIMPLE, "[skstuff] clicked inventory"); + effAmount += 1; + exprAmount += 5; + + if (setupNMSVersion()) { + getLogger().info("Trying to register version specific stuff..."); + Skript.registerEffect(EffClearPathGoals.class, "(clear|delete) [all] pathfind[er] goals (of|from) %livingentity%"); + Skript.registerEffect(EffRemovePathGoal.class, "remove pathfind[er] goal (0¦(avoid|run away from) entit(y|ies)|1¦break door[s]|2¦breed|3¦eat grass|4¦(flee from the sun|seek shad(e|ow))|5¦float (in[side]|on) water|6¦follow (owner|tamer)|7¦follow (adult|parent)[s]|8¦(fight back|react to|target) (damager|attacker)|9¦o(c|z)elot jump on blocks|10¦leap at target|11¦look at entit(y|ies)|12¦melee attack entit(y|ies)|13¦move to[wards] target|14¦target nearest entity|15¦o(c|z)elot attack [chicken[s]]|16¦open door[s]|17¦(panic|flee)|18¦look around randomly|19¦(walk around randomly|wander)|20¦sit|21¦[creeper] (explode|inflate|swell)|22¦squid (swim|wander)|23¦shoot fireball[s]|24¦[silverfish] hide (in[side]|on) block[s]|25¦(wake other silverfish[es]|[silverfish] call (help|reinforcement|other [hidden] silverfish[es]))|26¦[enderm(a|e)n] pick[[ ]up] block[s]|27¦[enderm(a|e)n] place block[s]|28¦[enderman] attack player (staring|looking) [at eye[s]]|29¦ghast move to[wards] target|30¦ghast (idle move[ment]|wander|random fl(ight|y[ing]))|31¦(tempt to|follow players (holding|with)) [a[n]] item|32¦target [random] entity (if|when) (not tamed|untamed)|33¦guardian attack [entity]|34¦[z[ombie[ ]]pig[man]] attack [player[s]] (if|when) angry|35¦[z[ombie[ ]]pig[man]] (react to|fight back|target) (attacker|damager) (if|when) angry|36¦[rabbit] eat carrot crops|37¦[killer] rabbit [melee] attack|38¦slime [random] jump|39¦slime change (direction|facing) randomly|40¦slime (idle move[ment]|wander)) from %livingentity%"); + Skript.registerEffect(EffSetPathGoal.class, "add pathfind[er] goal [[with] priority %-integer%] (0¦(avoid|run away from) %entitydata%[, radius %-number%[, speed %-number%[, speed (if|when) (close|near) %-number%]]]|1¦break door[s]|2¦breed[,[move[ment]] speed %-number%]|3¦eat grass|4¦(flee from the sun|seek shad(e|ow))[, [move[ment]] speed %-number%]|5¦(float (in[side]|on) water|swim)|6¦follow (owner|tamer)[, speed %-number%[, min[imum] distance %-number%[, max[imum] distance %-number%]]]|7¦follow (adult|parent)[s][, [move[ment]] speed %-number%]|8¦(fight back|react to|target) (damager|attacker) [[of] type] %entitydata%[, call ([for] help|reinforcement) %-boolean%]|9¦o(c|z)elot jump on blocks[, [move[ment]] speed %-number%]|10¦leap at target[, [leap] height %-number%]|11¦look at %entitydata%[, (radius|max[imum] distance) %-number%]|12¦melee attack %entitydata%[, [move[ment]] speed %-number%[, (memorize|do('nt| not) forget) target [for [a] long[er] time] %-boolean%]]|13¦move to[wards] target[, [move[ment]] speed %-number%[, (radius|max[imum] distance) %-number%]]|14¦target nearest [entity [of] type] %entitydata%[, check sight %-boolean%]|15¦o(c|z)elot attack|16¦open door[s]|17¦(panic|flee)[, [move[ment]] speed %-number%]|18¦look around randomly|19¦(walk around randomly|wander)[, [move[ment]] speed %-number%[, min[imum] [of] %-timespan% between mov(e[ment][s]|ing)]]|20¦sit|21¦[creeper] (explode|inflate|swell)|22¦squid (swim around|wander)|23¦shoot fireball[s]|24¦[silverfish] hide (in[side]|on) block[s]|25¦((call|summon|wake) [other] [hidden] silverfish[es])|26¦[enderman] pick[[ ]up] block[s]|27¦[enderman] place block[s]|28¦[enderman] attack player (staring|looking) at [their] eye[s]]|29¦ghast move to[wards] target|30¦ghast (idle move[ment]|wander|random fl(ight|y[ing]))|31¦(tempt to|follow players (holding|with)) %-itemstack%[, [move[ment]] speed %number%[, scared of player movement %-boolean%]]|32¦target [random] %entitydata% (if|when) (not |un)tamed|33¦guardian attack [entities]|34¦[z[ombie[ ]]pig[man]] attack [player[s]] (if|when) angry|35¦[z[ombie[ ]]pig[man]] (react to|fight back|target) (attacker|damager) (if|when) angry|36¦[rabbit] eat carrot crops|37¦[killer] rabbit [melee] attack|38¦slime [random] jump|39¦slime change (direction|facing) randomly|40¦slime (idle move[ment]|wander)) to %livingentity%"); + Skript.registerEffect(EffMakeJump.class, "make %livingentities% jump", "force %livingentities% to jump"); + Skript.registerEffect(EffGZipFile.class, "create [a] gzip[ped] file [at] [path] %string%"); + Skript.registerExpression(ExprNBTOf.class, Object.class, ExpressionType.PROPERTY, "nbt[[ ]tag[s]] of %~object%", "%~object%'s nbt[[ ]tag[s]]"); + Skript.registerExpression(ExprItemNBT.class, ItemStack.class, ExpressionType.SIMPLE, "%itemstack% with [custom] nbt[[ ]tag[s]] %string%"); + Skript.registerExpression(ExprTagOf.class, Object.class, ExpressionType.PROPERTY, "[nbt[ ]]tag %string% of [[nbt] compound] %compound%"); + Skript.registerExpression(ExprFileNBT.class, Object.class, ExpressionType.PROPERTY, "nbt[[ ]tag[s]] from [file] %string%"); + Skript.registerExpression(ExprNBTListIndex.class, Object.class, ExpressionType.PROPERTY, "[nbt[ ]list] %nbtlist% index %number%"); + Skript.registerExpression(ExprNBTListContents.class, Object.class, ExpressionType.PROPERTY, "[all] contents (of|from) [nbt[ ]list] %nbtlist%", "[nbt[ ]list] %nbtlist% contents"); + Skript.registerExpression(ExprNoClip.class, Boolean.class, ExpressionType.PROPERTY, "no[( |-)]clip (state|mode) of %entities%", "%entities%'s no[( |-)]clip (state|mode)"); + Skript.registerExpression(ExprFireProof.class, Boolean.class, ExpressionType.PROPERTY, "fire[ ]proof (state|mode) of %entities%", "%entities%'s fire[ ]proof (state|mode)"); + Skript.registerExpression(ExprEndermanBlocks.class, ItemStack.class, ExpressionType.PROPERTY, "blocks that %entity% can (carry|hold|grab|steal)"); + nmsMethods.registerCompoundClassInfo(); + nmsMethods.registerNBTListClassInfo(); + effAmount += 5; + exprAmount += 9; + typeAmount += 2; + } + if (Bukkit.getPluginManager().getPlugin("WorldEdit") != null) { + getLogger().info("WorldEdit found! Registering WorldEdit stuff..."); + Skript.registerCondition(CondSelectionContains.class, "[(world[ ]edit|we)] selection of %player% (contains|has) %location%", "%player%'s [(world[ ]edit|we)] selection (contains|has) %location%", "[(world[ ]edit|we)] selection of %player% does(n't| not) (contain|have) %location%", "%player%'s [(world[ ]edit|we)] selection does(n't| not) (contain|have) %location%"); + Skript.registerEffect(EffDrawLineWE.class, "(create|draw|make) [a[n]] (0¦(no(n|t)(-| )hollow|filled|)|1¦hollow) line from %location% to %location% (using|with) [edit[ ]session] %editsession% (using|with) [block[s]] %itemstacks% [with] thick[ness] %double%"); + Skript.registerEffect(EffUndoRedoSession.class, "(0¦undo|1¦redo) (change|edit)s (of|from) [edit[ ]session] %editsession%"); + Skript.registerEffect(EffRememberChanges.class, "make %player% (remember|be able to undo) changes (of|from) [edit[ ]session] %editsession%"); + Skript.registerEffect(EffMakeSphere.class, "(create|make) [a[n]] (0¦(no(n|t)(-| )hollow|filled|)|1¦hollow) (ellipsoid|sphere) [centered] at %location% [with] radius [of] %double%,[ ]%double%(,[ ]| and )%double% (using|with) [edit[ ]session] %editsession% (using|with) [block[s]] %itemstacks%"); + Skript.registerEffect(EffSimulateSnow.class, "(simulate snow at|place snow over) %location% (in|within) [a] radius [of] %double% (using|with) [edit[ ]session] %editsession%", "make %location% snowy (in|within) [a] radius [of] %double% (using|with) [edit[ ]session] %editsession%"); + Skript.registerEffect(EffMakePyramid.class, "(create|make) [a[n]] (0¦(no(n|t)(-| )hollow|filled|)|1¦hollow) pyramid at %location% [with] radius [of] %integer% (using|with) [edit[ ]session] %editsession% (using|with) [block[s]] %itemstacks%"); + Skript.registerEffect(EffDrainLiquid.class, "(drain|remove) [all] liquid[s] at %location% (in|within) [a] radius [of] %double% (using|with) [edit[ ]session] %editsession%"); + Skript.registerEffect(EffNaturalize.class, "naturalize ([cuboid] region|[all] blocks) (from|between) %location% (to|and) %location% (using|with) [edit[ ]session] %editsession%"); + Skript.registerEffect(EffMakeWalls.class, "(create|make) wall[s] from %location% to %location% (using|with) [edit[ ]session] %editsession% (using|with) [block[s]] %itemstacks%"); + Skript.registerEffect(EffSetBlocksWE.class, "set [all] blocks (from|between) %location% (to|and) %location% to %itemstacks% (using|with) [edit[ ]session] %editsession%"); + Skript.registerEffect(EffMakeCylinder.class, "(create|make) [a[n]] (0¦(no(n|t)(-| )hollow|filled|)|1¦hollow) cylinder at %location% [with] radius [of] %double%,[ ]%integer%(,[ ]| and )%double% (using|with) [edit[ ]session] %editsession% (using|with) [block[s]] %itemstacks%"); + Skript.registerEffect(EffReplaceBlocksWE.class, "replace [all] %itemstacks% (from|between) %location% (to|and) %location% with %itemstacks% (using|with) [edit[ ]session] %editsession%"); + Skript.registerEffect(EffPasteSchematic.class, "paste schem[atic] %string% at %location% using [edit[ ]session] %editsession% (0¦|1¦(ignor(e|ing)|without|[with] no) air)"); + Skript.registerExpression(ExprEditSessionLimit.class, Integer.class, ExpressionType.PROPERTY, "[block] limit [change] of [edit[ ]session] %editsession%"); + Skript.registerExpression(ExprChangedBlocksSession.class, Integer.class, ExpressionType.PROPERTY, "number of [all] changed blocks (in|of) [edit[ ]session] %editsession%"); + Skript.registerExpression(ExprNewEditSession.class, EditSession.class, ExpressionType.PROPERTY, "[new] edit[ ]session in [world] %world% [with] [max[imum]] [block] limit [change] [of] %integer%"); + Skript.registerExpression(ExprSelectionOfPlayer.class, Location.class, ExpressionType.PROPERTY, "[(world[ ]edit|we)] selection of %player%", "%player%'s [(world[ ]edit|we)] selection"); + Skript.registerExpression(ExprSelectionPos.class, Location.class, ExpressionType.PROPERTY, "[(world[ ]edit|we)] po(s|int)[ ](0¦1|1¦2) of %player%", "%player%'s [(world[ ]edit|we)] po(s|int)[ ](0¦1|1¦2)"); + Skript.registerExpression(ExprSelectionArea.class, Integer.class, ExpressionType.SIMPLE, "(0¦volume|1¦(x( |-)size|width)|2¦(y( |-)size|height)|3¦(z( |-)size|length)|4¦area) of [(world[ ]edit|we)] selection of %player%", "%player%'s [(world[ ]edit|we)] selection (0¦volume|1¦(x( |-)size|width)|2¦(y( |-)size|height)|3¦(z( |-)size|length)|4¦area)"); + Skript.registerExpression(ExprSchematicArea.class, Integer.class, ExpressionType.SIMPLE, "(0¦volume|1¦(x( |-)size|width)|2¦(y( |-)size|height)|3¦(z( |-)size|length)|4¦area) of schem[atic] [from] %string%"); + Classes.registerClass(new ClassInfo(EditSession.class, "editsession").name("Edit Session").user("edit ?sessions?")); + try { + Class.forName("com.sk89q.worldedit.extent.logging.AbstractLoggingExtent"); + new WorldEditChangeHandler(); + Skript.registerEvent("WorldEdit block change", SimpleEvent.class, EvtWorldEditChange.class, "world[ ]edit [block] (chang(e|ing)|edit[ing])"); + EventValues.registerEventValue(EvtWorldEditChange.class, Player.class, new Getter() { + @Override + @Nullable + public Player get(EvtWorldEditChange e) { + return EvtWorldEditChange.getPlayer(); + } + }, 0); + EventValues.registerEventValue(EvtWorldEditChange.class, Block.class, new Getter() { + @Override + @Nullable + public Block get(EvtWorldEditChange e) { + return EvtWorldEditChange.getBlock(); + } + }, 0); + evtAmount += 1; + } catch (ClassNotFoundException ex) { + Skript.error("Unable to register \"On WorldEdit block change\" event! You will need to upgrade to WorldEdit 6.0"); + return; + } + condAmount += 1; + effAmount += 13; + exprAmount += 7; + typeAmount += 1; + } + if (Bukkit.getPluginManager().getPlugin("VanishNoPacket") != null) { + getLogger().info("VanishNoPacket was found! Registering vanishing features..."); + Skript.registerEffect(EffToggleVanish.class, "toggle vanish (state|mode) of %player% (0¦|1¦(silently|quietly))", "toggle %player%'s vanish (state|mode) (0¦|1¦(silently|quietly))"); + Skript.registerExpression(ExprVanishState.class, Boolean.class, ExpressionType.PROPERTY, "vanish (state|mode) of %player%", "%player%'s vanish (state|mode)"); + effAmount += 1; + exprAmount += 1; + } + getLogger().info("Everything ready! Loaded a total of " + condAmount + " conditions, " + effAmount + " effects, " + evtAmount + "events, " + exprAmount + " expressions and " + typeAmount + " types!"); + } else { + getLogger().info("Unable to find Skript or Skript isn't accepting registrations, disabling SkStuff..."); + Bukkit.getPluginManager().disablePlugin(this);; + } + } + + private boolean setupNMSVersion() { + String version = ReflectionUtils.getVersion(); + if (version.equals("v1_7_R4.")) { + nmsMethods = new NMS_v1_7_R4(); + getLogger().info("It looks like you're running 1.7.10!"); + } else if (version.equals("v1_8_R1.")) { + nmsMethods = new NMS_v1_8_R1(); + getLogger().info("It looks like you're running 1.8.0!"); + } else if (version.equals("v1_8_R2.")) { + nmsMethods = new NMS_v1_8_R2(); + getLogger().info("It looks like you're running 1.8.3!"); + } else if (version.equals("v1_8_R3.")) { + nmsMethods = new NMS_v1_8_R3(); + getLogger().info("It looks like you're either running 1.8.7, 1.8.8 or 1.8.9!"); + } else if (version.equals("v1_9_R1.")) { + nmsMethods = new NMS_v1_9_R1(); + getLogger().info("It looks like you're running 1.9.0!"); + } else { + getLogger().warning("It looks like you're running an unsupported server version, some features will not be available :("); + } + return nmsMethods != null; + } + + public static NMSInterface getNMSMethods() { + return nmsMethods; + } + + public void onDisable() { + getLogger().info("SkStuff " + this.getDescription().getVersion() + " has been successfully disabled."); + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/effects/EffClearPathGoals.java b/src/me/TheBukor/SkStuff/effects/EffClearPathGoals.java index e6da1d0..01d5fed 100644 --- a/src/me/TheBukor/SkStuff/effects/EffClearPathGoals.java +++ b/src/me/TheBukor/SkStuff/effects/EffClearPathGoals.java @@ -1,54 +1,54 @@ -package me.TheBukor.SkStuff.effects; - -import java.util.List; - -import javax.annotation.Nullable; - -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; - -import ch.njol.skript.lang.Effect; -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Kleenean; -import me.TheBukor.SkStuff.util.ReflectionUtils; - -public class EffClearPathGoals extends Effect { - private Expression entity; - - private Class goalSelectorClass = ReflectionUtils.getNMSClass("PathfinderGoalSelector", false); - private Class insentientEnt = ReflectionUtils.getNMSClass("EntityInsentient", false); - private Class craftLivEnt = ReflectionUtils.getOBCClass("entity.CraftLivingEntity"); - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { - entity = (Expression) expr[0]; - return true; - } - - @Override - public String toString(@Nullable Event e, boolean debug) { - return "clear all pathfinder goals from " + entity.toString(e, debug); - } - - @Override - protected void execute(Event e) { - LivingEntity ent = entity.getSingle(e); - if (ent instanceof Player || ent == null) - return; - Object obcEnt = craftLivEnt.cast(ent); - try { - Object nmsEnt = insentientEnt.cast(obcEnt.getClass().getMethod("getHandle").invoke(obcEnt)); - Object goalSelector = ReflectionUtils.getField("goalSelector", insentientEnt, nmsEnt); - Object targetSelector = ReflectionUtils.getField("targetSelector", insentientEnt, nmsEnt); - ((List) ReflectionUtils.getField("b", goalSelectorClass, goalSelector)).clear(); - ((List) ReflectionUtils.getField("c", goalSelectorClass, goalSelector)).clear(); - ((List) ReflectionUtils.getField("b", goalSelectorClass, targetSelector)).clear(); - ((List) ReflectionUtils.getField("c", goalSelectorClass, targetSelector)).clear(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } +package me.TheBukor.SkStuff.effects; + +import java.util.List; + +import javax.annotation.Nullable; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; + +import ch.njol.skript.lang.Effect; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.util.Kleenean; +import me.TheBukor.SkStuff.util.ReflectionUtils; + +public class EffClearPathGoals extends Effect { + private Expression entity; + + private Class goalSelectorClass = ReflectionUtils.getNMSClass("PathfinderGoalSelector"); + private Class insentientEnt = ReflectionUtils.getNMSClass("EntityInsentient"); + private Class craftLivEnt = ReflectionUtils.getOBCClass("entity.CraftLivingEntity"); + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { + entity = (Expression) expr[0]; + return true; + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return "clear all pathfinder goals from " + entity.toString(e, debug); + } + + @Override + protected void execute(Event e) { + LivingEntity ent = entity.getSingle(e); + if (ent instanceof Player || ent == null) + return; + Object obcEnt = craftLivEnt.cast(ent); + try { + Object nmsEnt = insentientEnt.cast(obcEnt.getClass().getMethod("getHandle").invoke(obcEnt)); + Object goalSelector = ReflectionUtils.getField("goalSelector", insentientEnt, nmsEnt); + Object targetSelector = ReflectionUtils.getField("targetSelector", insentientEnt, nmsEnt); + ((List) ReflectionUtils.getField("b", goalSelectorClass, goalSelector)).clear(); + ((List) ReflectionUtils.getField("c", goalSelectorClass, goalSelector)).clear(); + ((List) ReflectionUtils.getField("b", goalSelectorClass, targetSelector)).clear(); + ((List) ReflectionUtils.getField("c", goalSelectorClass, targetSelector)).clear(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/effects/EffGZipFile.java b/src/me/TheBukor/SkStuff/effects/EffGZipFile.java index 470177a..c3f993e 100644 --- a/src/me/TheBukor/SkStuff/effects/EffGZipFile.java +++ b/src/me/TheBukor/SkStuff/effects/EffGZipFile.java @@ -1,56 +1,49 @@ -package me.TheBukor.SkStuff.effects; - -import java.io.EOFException; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.zip.GZIPOutputStream; - -import javax.annotation.Nullable; - -import org.bukkit.event.Event; - -import ch.njol.skript.lang.Effect; -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Kleenean; - -public class EffGZipFile extends Effect { - private Expression filePath; - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { - filePath = (Expression) expr[0]; - return true; - } - - @Override - public String toString(@Nullable Event e, boolean debug) { - return "create GZipped file at " + filePath.toString(e, debug); - } - - @Override - protected void execute(Event e) { - File newFile = new File(filePath.getSingle(e)); - /* - if (!newFile.exists()) { - try { - newFile.createNewFile(); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - */ - try { - new GZIPOutputStream(new FileOutputStream(newFile)).close(); - } catch (FileNotFoundException ex) { - ex.printStackTrace(); - } catch (IOException ex) { - if (!(ex instanceof EOFException)) { - ex.printStackTrace(); - } - } - } -} +package me.TheBukor.SkStuff.effects; + +import java.io.EOFException; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.GZIPOutputStream; + +import javax.annotation.Nullable; + +import org.bukkit.event.Event; + +import ch.njol.skript.lang.Effect; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.util.Kleenean; + +public class EffGZipFile extends Effect { + private Expression filePath; + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { + filePath = (Expression) expr[0]; + return true; + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return "create GZipped file at path " + filePath.toString(e, debug); + } + + @Override + protected void execute(Event e) { + File newFile = new File(filePath.getSingle(e)); + if (!newFile.exists()) { + try { + new GZIPOutputStream(new FileOutputStream(newFile)).close(); + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + } catch (IOException ex) { + if (!(ex instanceof EOFException)) { + ex.printStackTrace(); + } + } + } + } +} diff --git a/src/me/TheBukor/SkStuff/effects/EffMakeJump.java b/src/me/TheBukor/SkStuff/effects/EffMakeJump.java index b00a464..ec67b2a 100644 --- a/src/me/TheBukor/SkStuff/effects/EffMakeJump.java +++ b/src/me/TheBukor/SkStuff/effects/EffMakeJump.java @@ -1,51 +1,51 @@ -package me.TheBukor.SkStuff.effects; - -import javax.annotation.Nullable; - -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; - -import ch.njol.skript.lang.Effect; -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Kleenean; -import me.TheBukor.SkStuff.util.ReflectionUtils; - -public class EffMakeJump extends Effect { - private Expression entities; - - private Class entInsent = ReflectionUtils.getNMSClass("EntityInsentient", false); - private Class craftLivEnt = ReflectionUtils.getOBCClass("entity.CraftLivingEntity"); - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { - entities = (Expression) expr[0]; - return true; - } - - @Override - public String toString(@Nullable Event e, boolean debug) { - return "make " + entities.toString(e, debug) + " jump"; - } - - @Override - protected void execute(Event e) { - LivingEntity[] ents = entities.getAll(e); - for (Entity ent : ents) { - if (ent == null || ent instanceof Player || ent instanceof ArmorStand) - continue; - Object obcEnt = craftLivEnt.cast(ent); - try { - Object nmsEnt = entInsent.cast(obcEnt.getClass().getMethod("getHandle").invoke(obcEnt)); - Object controllerJump = nmsEnt.getClass().getMethod("getControllerJump").invoke(nmsEnt); - controllerJump.getClass().getMethod("a").invoke(controllerJump); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } +package me.TheBukor.SkStuff.effects; + +import javax.annotation.Nullable; + +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; + +import ch.njol.skript.lang.Effect; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.util.Kleenean; +import me.TheBukor.SkStuff.util.ReflectionUtils; + +public class EffMakeJump extends Effect { + private Expression entities; + + private Class entInsent = ReflectionUtils.getNMSClass("EntityInsentient"); + private Class craftLivEnt = ReflectionUtils.getOBCClass("entity.CraftLivingEntity"); + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { + entities = (Expression) expr[0]; + return true; + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return "make " + entities.toString(e, debug) + " jump"; + } + + @Override + protected void execute(Event e) { + LivingEntity[] ents = entities.getAll(e); + for (Entity ent : ents) { + if (ent == null || ent instanceof Player || ent instanceof ArmorStand) + continue; + Object obcEnt = craftLivEnt.cast(ent); + try { + Object nmsEnt = entInsent.cast(obcEnt.getClass().getMethod("getHandle").invoke(obcEnt)); + Object controllerJump = nmsEnt.getClass().getMethod("getControllerJump").invoke(nmsEnt); + controllerJump.getClass().getMethod("a").invoke(controllerJump); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/effects/EffRemovePathGoal.java b/src/me/TheBukor/SkStuff/effects/EffRemovePathGoal.java index 6281532..060382f 100644 --- a/src/me/TheBukor/SkStuff/effects/EffRemovePathGoal.java +++ b/src/me/TheBukor/SkStuff/effects/EffRemovePathGoal.java @@ -1,256 +1,235 @@ -package me.TheBukor.SkStuff.effects; - -import java.util.Iterator; -import java.util.List; - -import javax.annotation.Nullable; - -import org.bukkit.entity.Blaze; -import org.bukkit.entity.Creature; -import org.bukkit.entity.Ghast; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.entity.Rabbit; -import org.bukkit.entity.Spider; -import org.bukkit.event.Event; - -import ch.njol.skript.lang.Effect; -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Kleenean; -import me.TheBukor.SkStuff.util.ReflectionUtils; - -public class EffRemovePathGoal extends Effect { - private Expression entity; - - private int mark; - - private Class entInsent = ReflectionUtils.getNMSClass("EntityInsentient", false); - private Class craftLivEnt = ReflectionUtils.getOBCClass("entity.CraftLivingEntity"); - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { - mark = result.mark; - entity = (Expression) expr[0]; - return true; - } - - @Override - public String toString(@Nullable Event e, boolean debug) { - return "remove pathfinder goal from " + entity.toString(e, debug); - } - - @Override - protected void execute(Event e) { - LivingEntity ent = entity.getSingle(e); - if (ent instanceof Player || ent == null) - return; - Object obcEnt = craftLivEnt.cast(ent); - try { - Object nmsEnt = entInsent.cast(obcEnt.getClass().getMethod("getHandle").invoke(obcEnt)); - Object goalSelector = ReflectionUtils.getField("goalSelector", entInsent, nmsEnt); - Object targetSelector = ReflectionUtils.getField("targetSelector", entInsent, nmsEnt); - Object toRemove = null; - boolean target = false; - boolean resetGoalTarget = false; - if (mark == 0) { - if (ent instanceof Rabbit) { - Class goalRabbitAvoid = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalRabbitAvoidTarget", false); - toRemove = goalRabbitAvoid; - } else { - Class goalAvoid = ReflectionUtils.getNMSClass("PathfinderGoalAvoidTarget", false); - toRemove = goalAvoid; - } - } else if (mark == 1) { - Class goalBreakDoor = ReflectionUtils.getNMSClass("PathfinderGoalBreakDoor", false); - toRemove = goalBreakDoor; - } else if (mark == 2) { - Class goalBreed = ReflectionUtils.getNMSClass("PathfinderGoalBreed", false); - toRemove = goalBreed; - } else if (mark == 3) { - Class goalEatGrass = ReflectionUtils.getNMSClass("PathfinderGoalEatTile", false); - toRemove = goalEatGrass; - } else if (mark == 4) { - Class goalFleeSun = ReflectionUtils.getNMSClass("PathfinderGoalFleeSun", false); - toRemove = goalFleeSun; - } else if (mark == 5) { - Class goalFloat = ReflectionUtils.getNMSClass("PathfinderGoalFloat", false); - toRemove = goalFloat; - } else if (mark == 6) { - Class goalFollowOwner = ReflectionUtils.getNMSClass("PathfinderGoalFollowOwner", false); - toRemove = goalFollowOwner; - } else if (mark == 7) { - Class goalFollowAdults = ReflectionUtils.getNMSClass("PathfinderGoalFollowParent", false); - toRemove = goalFollowAdults; - } else if (mark == 8) { - target = true; - Class goalReactAttack = ReflectionUtils.getNMSClass("PathfinderGoalHurtByTarget", false); - toRemove = goalReactAttack; - } else if (mark == 9) { - Class goalJumpOnBlock = ReflectionUtils.getNMSClass("PathfinderGoalJumpOnBlock", false); - toRemove = goalJumpOnBlock; - } else if (mark == 10) { - Class goalLeapTarget = ReflectionUtils.getNMSClass("PathfinderGoalLeapAtTarget", false); - toRemove = goalLeapTarget; - } else if (mark == 11) { - Class goalLookEntities = ReflectionUtils.getNMSClass("PathfinderGoalLookAtPlayer", false); - toRemove = goalLookEntities; - } else if (mark == 12) { - if (ent instanceof Spider) { - Class goalSpiderMelee = ReflectionUtils.getNMSClass("EntitySpider$PathfinderGoalSpiderMeleeAttack", false); - toRemove = goalSpiderMelee; - } else { - Class goalMeleeAttack = ReflectionUtils.getNMSClass("PathfinderGoalMeleeAttack", false); - toRemove = goalMeleeAttack; - } - } else if (mark == 13) { - if (ent instanceof Ghast) { - Class goalGhastGotoTarget = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalMoveTowardsTarget", false); - toRemove = goalGhastGotoTarget; - } else { - Class goalGotoTarget = ReflectionUtils.getNMSClass("PathfinderGoalMoveTowardsTarget", false); - toRemove = goalGotoTarget; - } - } else if (mark == 14) { - target = true; - if (ent instanceof Spider) { - Class goalSpiderNearTarget = ReflectionUtils.getNMSClass("EntitySpider$PathfinderGoalSpiderNearestAttackableTarget", false); - toRemove = goalSpiderNearTarget; - } else { - Class goalNearTarget = ReflectionUtils.getNMSClass("PathfinderGoalNearestAttackableTarget", false); - toRemove = goalNearTarget; - } - } else if (mark == 15) { - Class goalOcelotAttack = ReflectionUtils.getNMSClass("PathfinderGoalOcelotAttack", false); - toRemove = goalOcelotAttack; - } else if (mark == 16) { - Class goalOpenDoors = ReflectionUtils.getNMSClass("PathfinderGoalOpenDoor", false); - toRemove = goalOpenDoors; - } else if (mark == 17) { - if (ent instanceof Rabbit) { - Class goalRabbitPanic = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalRabbitPanic", false); - toRemove = goalRabbitPanic; - } else { - Class goalPanic = ReflectionUtils.getNMSClass("PathfinderGoalPanic", false); - toRemove = goalPanic; - } - } else if (mark == 18) { - Class goalRandomLook = ReflectionUtils.getNMSClass("PathfinderGoalRandomLookaround", false); - toRemove = goalRandomLook; - } else if (mark == 19) { - Class goalWander = ReflectionUtils.getNMSClass("PathfinderGoalRandomStroll", false); - toRemove = goalWander; - } else if (mark == 20) { - Class goalSit = ReflectionUtils.getNMSClass("PathfinderGoalSit", false); - toRemove = goalSit; - } else if (mark == 21) { - Class goalSwell = ReflectionUtils.getNMSClass("PathfinderGoalSwell", false); - toRemove = goalSwell; - } else if (mark == 22) { - Class goalSquid = ReflectionUtils.getNMSClass("EntitySquid$PathfinderGoalSquid", false); - toRemove = goalSquid; - } else if (mark == 23) { - resetGoalTarget = true; - if (ent instanceof Blaze) { - Class goalBlazeFireball = ReflectionUtils.getNMSClass("EntityBlaze$PathfinderGoalBlazeFireball", false); - toRemove = goalBlazeFireball; - } else if (ent instanceof Ghast) { - Class goalGhastFireball = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastAttackTarget", false); - toRemove = goalGhastFireball; - } - } else if (mark == 24) { - Class goalHideInBlock = ReflectionUtils.getNMSClass("EntitySilverfish$PathfinderGoalSilverfishHideInBlock", false); - toRemove = goalHideInBlock; - } else if (mark == 25) { - Class goalWakeSilverfish = ReflectionUtils.getNMSClass("EntitySilverfish$PathfinderGoalSilverfishWakeOthers", false); - toRemove = goalWakeSilverfish; - } else if (mark == 26) { - Class goalPickBlocks = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalEndermanPickupBlock", false); - toRemove = goalPickBlocks; - } else if (mark == 27) { - Class goalPlaceBlocks = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalEndermanPlaceBlock", false); - toRemove = goalPlaceBlocks; - } else if (mark == 28) { - target = true; - Class goalAttackLooker = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalPlayerWhoLookedAtTarget", false); - toRemove = goalAttackLooker; - } else if (mark == 29) { - Class goalGhastMoveTarget = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastMoveTowardsTarget", false); - toRemove = goalGhastMoveTarget; - } else if (mark == 30) { - Class goalGhastIdleMove = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastIdleMove", false); - toRemove = goalGhastIdleMove; - } else if (mark == 31) { - Class goalTempt = ReflectionUtils.getNMSClass("PathfinderGoalTempt", false); - toRemove = goalTempt; - } else if (mark == 32) { - target = true; - Class goalTargetNonTamed = ReflectionUtils.getNMSClass("PathfinderGoalRandomTargetNonTamed", false); - toRemove = goalTargetNonTamed; - } else if (mark == 33) { - resetGoalTarget = true; - Class goalGuardianAttack = ReflectionUtils.getNMSClass("EntityGuardian$PathfinderGoalGuardianAttack", false); - toRemove = goalGuardianAttack; - } else if (mark == 34) { - target = true; - Class goalAnger = ReflectionUtils.getNMSClass("EntityPigZombie$PathfinderGoalAnger", false); - toRemove = goalAnger; - } else if (mark == 35) { - target = true; - Class goalAngerOther = ReflectionUtils.getNMSClass("EntityPigZombie$PathfinderGoalAngerOther", false); - toRemove = goalAngerOther; - } else if (mark == 36) { - Class goalEatCarrots = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalEatCarrots", false); - toRemove = goalEatCarrots; - } else if (mark == 37) { - Class goalRabbitAttack = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalKillerRabbitMeleeAttack", false); - toRemove = goalRabbitAttack; - } else if (mark == 38) { - Class goalJump = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeRandomJump", false); - toRemove = goalJump; - } else if (mark == 39) { - Class goalRandomDir = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeRandomDirection", false); - toRemove = goalRandomDir; - } else if (mark == 40) { - Class goalSlimeWander = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeIdle", false); - toRemove = goalSlimeWander; - } - if (toRemove == null) - return; - - /* "Hey, why are you setting the entity's target to null?!" - * - * For some goals (Blaze/Ghast fireball and Guardian attack), if you remove the goal while the entity is attacking, it will not stop attacking imediatelly, it will keep attacking its target. - * So there's a "bug" with this behavior, as soon as the entity's target resets (null, A.K.A ) the server crashes. Because we messed with the entity's "attack target" goal, the game - * still thinks it needs to get the target's location for some reason, and since the target is null... It throws an unhandled NPE (it never happens in Vanilla behavior), crashing the server. - * So I'm just setting the target to null before removing the goal, so it stops attacking properly, and also prevents the said crash. - */ - - if (resetGoalTarget) { - ((Creature) entity.getSingle(e)).setTarget(null); - } - - Class goalSelectorClass = ReflectionUtils.getNMSClass("PathfinderGoalSelector", false); - if (target) { //Target Selector - Iterator targets = ((List) ReflectionUtils.getField("b", goalSelectorClass, targetSelector)).iterator(); - while (targets.hasNext()) { - Object o = targets.next(); - if (ReflectionUtils.getField("a", o.getClass(), o).getClass() == toRemove) { - targets.remove(); - } - } - } else { //Goal Selector - Iterator goals = ((List) ReflectionUtils.getField("b", goalSelectorClass, goalSelector)).iterator(); - while (goals.hasNext()) { - Object o = goals.next(); - if (ReflectionUtils.getField("a", o.getClass(), o).getClass() == toRemove) { - goals.remove(); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } +package me.TheBukor.SkStuff.effects; + +import javax.annotation.Nullable; + +import org.bukkit.entity.Blaze; +import org.bukkit.entity.Creature; +import org.bukkit.entity.Ghast; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Rabbit; +import org.bukkit.entity.Spider; +import org.bukkit.event.Event; + +import ch.njol.skript.lang.Effect; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.util.Kleenean; +import me.TheBukor.SkStuff.SkStuff; +import me.TheBukor.SkStuff.util.ReflectionUtils; + +public class EffRemovePathGoal extends Effect { + private Expression entity; + + private int mark; + + private Class entInsent = ReflectionUtils.getNMSClass("EntityInsentient"); + private Class craftLivEnt = ReflectionUtils.getOBCClass("entity.CraftLivingEntity"); + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { + mark = result.mark; + entity = (Expression) expr[0]; + return true; + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return "remove pathfinder goal from " + entity.toString(e, debug); + } + + @Override + protected void execute(Event e) { + LivingEntity ent = entity.getSingle(e); + if (ent instanceof Player || ent == null) + return; + Object obcEnt = craftLivEnt.cast(ent); + try { + Object nmsEnt = entInsent.cast(obcEnt.getClass().getMethod("getHandle").invoke(obcEnt)); + Class toRemove = null; + boolean target = false; + boolean resetGoalTarget = false; + if (mark == 0) { + if (ent instanceof Rabbit) { + Class goalRabbitAvoid = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalRabbitAvoidTarget"); + toRemove = goalRabbitAvoid; + } else { + Class goalAvoid = ReflectionUtils.getNMSClass("PathfinderGoalAvoidTarget"); + toRemove = goalAvoid; + } + } else if (mark == 1) { + Class goalBreakDoor = ReflectionUtils.getNMSClass("PathfinderGoalBreakDoor"); + toRemove = goalBreakDoor; + } else if (mark == 2) { + Class goalBreed = ReflectionUtils.getNMSClass("PathfinderGoalBreed"); + toRemove = goalBreed; + } else if (mark == 3) { + Class goalEatGrass = ReflectionUtils.getNMSClass("PathfinderGoalEatTile"); + toRemove = goalEatGrass; + } else if (mark == 4) { + Class goalFleeSun = ReflectionUtils.getNMSClass("PathfinderGoalFleeSun"); + toRemove = goalFleeSun; + } else if (mark == 5) { + Class goalFloat = ReflectionUtils.getNMSClass("PathfinderGoalFloat"); + toRemove = goalFloat; + } else if (mark == 6) { + Class goalFollowOwner = ReflectionUtils.getNMSClass("PathfinderGoalFollowOwner"); + toRemove = goalFollowOwner; + } else if (mark == 7) { + Class goalFollowAdults = ReflectionUtils.getNMSClass("PathfinderGoalFollowParent"); + toRemove = goalFollowAdults; + } else if (mark == 8) { + target = true; + Class goalReactAttack = ReflectionUtils.getNMSClass("PathfinderGoalHurtByTarget"); + toRemove = goalReactAttack; + } else if (mark == 9) { + Class goalJumpOnBlock = ReflectionUtils.getNMSClass("PathfinderGoalJumpOnBlock"); + toRemove = goalJumpOnBlock; + } else if (mark == 10) { + Class goalLeapTarget = ReflectionUtils.getNMSClass("PathfinderGoalLeapAtTarget"); + toRemove = goalLeapTarget; + } else if (mark == 11) { + Class goalLookEntities = ReflectionUtils.getNMSClass("PathfinderGoalLookAtPlayer"); + toRemove = goalLookEntities; + } else if (mark == 12) { + if (ent instanceof Spider) { + Class goalSpiderMelee = ReflectionUtils.getNMSClass("EntitySpider$PathfinderGoalSpiderMeleeAttack"); + toRemove = goalSpiderMelee; + } else { + Class goalMeleeAttack = ReflectionUtils.getNMSClass("PathfinderGoalMeleeAttack"); + toRemove = goalMeleeAttack; + } + } else if (mark == 13) { + if (ent instanceof Ghast) { + Class goalGhastGotoTarget = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalMoveTowardsTarget"); + toRemove = goalGhastGotoTarget; + } else { + Class goalGotoTarget = ReflectionUtils.getNMSClass("PathfinderGoalMoveTowardsTarget"); + toRemove = goalGotoTarget; + } + } else if (mark == 14) { + target = true; + if (ent instanceof Spider) { + Class goalSpiderNearTarget = ReflectionUtils.getNMSClass("EntitySpider$PathfinderGoalSpiderNearestAttackableTarget"); + toRemove = goalSpiderNearTarget; + } else { + Class goalNearTarget = ReflectionUtils.getNMSClass("PathfinderGoalNearestAttackableTarget"); + toRemove = goalNearTarget; + } + } else if (mark == 15) { + Class goalOcelotAttack = ReflectionUtils.getNMSClass("PathfinderGoalOcelotAttack"); + toRemove = goalOcelotAttack; + } else if (mark == 16) { + Class goalOpenDoors = ReflectionUtils.getNMSClass("PathfinderGoalOpenDoor"); + toRemove = goalOpenDoors; + } else if (mark == 17) { + if (ent instanceof Rabbit) { + Class goalRabbitPanic = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalRabbitPanic"); + toRemove = goalRabbitPanic; + } else { + Class goalPanic = ReflectionUtils.getNMSClass("PathfinderGoalPanic"); + toRemove = goalPanic; + } + } else if (mark == 18) { + Class goalRandomLook = ReflectionUtils.getNMSClass("PathfinderGoalRandomLookaround"); + toRemove = goalRandomLook; + } else if (mark == 19) { + Class goalWander = ReflectionUtils.getNMSClass("PathfinderGoalRandomStroll"); + toRemove = goalWander; + } else if (mark == 20) { + Class goalSit = ReflectionUtils.getNMSClass("PathfinderGoalSit"); + toRemove = goalSit; + } else if (mark == 21) { + Class goalSwell = ReflectionUtils.getNMSClass("PathfinderGoalSwell"); + toRemove = goalSwell; + } else if (mark == 22) { + Class goalSquid = ReflectionUtils.getNMSClass("EntitySquid$PathfinderGoalSquid"); + toRemove = goalSquid; + } else if (mark == 23) { + resetGoalTarget = true; + if (ent instanceof Blaze) { + Class goalBlazeFireball = ReflectionUtils.getNMSClass("EntityBlaze$PathfinderGoalBlazeFireball"); + toRemove = goalBlazeFireball; + } else if (ent instanceof Ghast) { + Class goalGhastFireball = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastAttackTarget"); + toRemove = goalGhastFireball; + } + } else if (mark == 24) { + Class goalHideInBlock = ReflectionUtils.getNMSClass("EntitySilverfish$PathfinderGoalSilverfishHideInBlock"); + toRemove = goalHideInBlock; + } else if (mark == 25) { + Class goalWakeSilverfish = ReflectionUtils.getNMSClass("EntitySilverfish$PathfinderGoalSilverfishWakeOthers"); + toRemove = goalWakeSilverfish; + } else if (mark == 26) { + Class goalPickBlocks = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalEndermanPickupBlock"); + toRemove = goalPickBlocks; + } else if (mark == 27) { + Class goalPlaceBlocks = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalEndermanPlaceBlock"); + toRemove = goalPlaceBlocks; + } else if (mark == 28) { + target = true; + Class goalAttackLooker = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalPlayerWhoLookedAtTarget"); + toRemove = goalAttackLooker; + } else if (mark == 29) { + Class goalGhastMoveTarget = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastMoveTowardsTarget"); + toRemove = goalGhastMoveTarget; + } else if (mark == 30) { + Class goalGhastIdleMove = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastIdleMove"); + toRemove = goalGhastIdleMove; + } else if (mark == 31) { + Class goalTempt = ReflectionUtils.getNMSClass("PathfinderGoalTempt"); + toRemove = goalTempt; + } else if (mark == 32) { + target = true; + Class goalTargetNonTamed = ReflectionUtils.getNMSClass("PathfinderGoalRandomTargetNonTamed"); + toRemove = goalTargetNonTamed; + } else if (mark == 33) { + resetGoalTarget = true; + Class goalGuardianAttack = ReflectionUtils.getNMSClass("EntityGuardian$PathfinderGoalGuardianAttack"); + toRemove = goalGuardianAttack; + } else if (mark == 34) { + target = true; + Class goalAnger = ReflectionUtils.getNMSClass("EntityPigZombie$PathfinderGoalAnger"); + toRemove = goalAnger; + } else if (mark == 35) { + target = true; + Class goalAngerOther = ReflectionUtils.getNMSClass("EntityPigZombie$PathfinderGoalAngerOther"); + toRemove = goalAngerOther; + } else if (mark == 36) { + Class goalEatCarrots = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalEatCarrots"); + toRemove = goalEatCarrots; + } else if (mark == 37) { + Class goalRabbitAttack = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalKillerRabbitMeleeAttack"); + toRemove = goalRabbitAttack; + } else if (mark == 38) { + Class goalJump = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeRandomJump"); + toRemove = goalJump; + } else if (mark == 39) { + Class goalRandomDir = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeRandomDirection"); + toRemove = goalRandomDir; + } else if (mark == 40) { + Class goalSlimeWander = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeIdle"); + toRemove = goalSlimeWander; + } + if (toRemove == null) + return; + + /* "Hey, why are you setting the entity's target to null?!" + * + * For some goals (Blaze/Ghast fireball and Guardian attack), if you remove the goal while the entity is attacking, it will not stop attacking imediatelly, it will keep attacking its target. + * So there's a "bug" with this behavior, as soon as the entity's target resets (null, A.K.A ) the server crashes. Because we messed with the entity's "attack target" goal, the game + * still thinks it needs to get the target's location for some reason, and since the target is null... It throws an unhandled NPE (it never happens in Vanilla behavior), crashing the server. + * So I'm just setting the target to null before removing the goal, so it stops attacking properly, and also prevents the said crash. + */ + + if (resetGoalTarget) { + ((Creature) entity.getSingle(e)).setTarget(null); + } + + SkStuff.getNMSMethods().removePathfinderGoal(nmsEnt, toRemove, target); + } catch (Exception ex) { + ex.printStackTrace(); + } + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/effects/EffSetPathGoal.java b/src/me/TheBukor/SkStuff/effects/EffSetPathGoal.java index a4b2a4e..a072d15 100644 --- a/src/me/TheBukor/SkStuff/effects/EffSetPathGoal.java +++ b/src/me/TheBukor/SkStuff/effects/EffSetPathGoal.java @@ -1,602 +1,625 @@ -package me.TheBukor.SkStuff.effects; - -import java.lang.reflect.Constructor; - -import javax.annotation.Nullable; - -import org.bukkit.Material; -import org.bukkit.entity.Animals; -import org.bukkit.entity.Blaze; -import org.bukkit.entity.Creeper; -import org.bukkit.entity.Enderman; -import org.bukkit.entity.Ghast; -import org.bukkit.entity.Guardian; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Ocelot; -import org.bukkit.entity.PigZombie; -import org.bukkit.entity.Player; -import org.bukkit.entity.Rabbit; -import org.bukkit.entity.Silverfish; -import org.bukkit.entity.Slime; -import org.bukkit.entity.Spider; -import org.bukkit.entity.Squid; -import org.bukkit.entity.Tameable; -import org.bukkit.event.Event; -import org.bukkit.inventory.ItemStack; - -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; - -import ch.njol.skript.entity.EntityData; -import ch.njol.skript.lang.Effect; -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.util.Timespan; -import ch.njol.util.Kleenean; -import me.TheBukor.SkStuff.util.ReflectionUtils; - -public class EffSetPathGoal extends Effect { - private Expression goalPriority; - private Expression> typeToAvoid; - private Expression avoidRadius; - private Expression avoidSpeed; - private Expression avoidSpeedNear; - private Expression breedSpeed; - private Expression fleeSunSpeed; - private Expression followOwnerSpeed; - private Expression followMinDist; - private Expression followMaxDist; - private Expression followAdultsSpeed; - private Expression> typesToFightBack; - private Expression callForHelp; - private Expression jumpOnBlockSpeed; - private Expression leapHeight; - private Expression> lookType; - private Expression lookRadius; - private Expression> meleeTarget; - private Expression meleeSpeed; - private Expression meleeMemorize; - private Expression moveTargetSpeed; - private Expression moveTargetRadius; - private Expression> nearTarget; - private Expression checkSight; - private Expression panicSpeed; - private Expression randomWalkSpeed; - private Expression randomWalkInterval; - private Expression temptItem; - private Expression temptSpeed; - private Expression temptScared; - private Expression> nonTamedTarget; - private Expression entity; - - private int mark; - - private Class craftItemClass = ReflectionUtils.getOBCClass("inventory.CraftItemStack"); - private Class craftLivEnt = ReflectionUtils.getOBCClass("entity.CraftLivingEntity"); - private Class entAnimal = ReflectionUtils.getNMSClass("EntityAnimal", false); - private Class entCreature = ReflectionUtils.getNMSClass("EntityCreature", false); - private Class entInsent = ReflectionUtils.getNMSClass("EntityInsentient", false); - private Class entTameable = ReflectionUtils.getNMSClass("EntityTameableAnimal", false); - private Class nmsItemClass = ReflectionUtils.getNMSClass("Item", false); - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { - goalPriority = (Expression) expr[0]; - mark = result.mark; - if (mark == 0) { - typeToAvoid = (Expression>) expr[1]; - avoidRadius = (Expression) expr[2]; - avoidSpeed = (Expression) expr[3]; - avoidSpeedNear = (Expression) expr[4]; - } else if (mark == 2) { - breedSpeed = (Expression) expr[5]; - } else if (mark == 4) { - fleeSunSpeed = (Expression) expr[6]; - } else if (mark == 6) { - followOwnerSpeed = (Expression) expr[7]; - followMinDist = (Expression) expr[8]; - followMaxDist = (Expression) expr[9]; - } else if (mark == 7) { - followAdultsSpeed = (Expression) expr[10]; - } else if (mark == 8) { - typesToFightBack = (Expression>) expr[11]; - callForHelp = (Expression) expr[12]; - } else if (mark == 9) { - jumpOnBlockSpeed = (Expression) expr[13]; - } else if (mark == 10) { - leapHeight = (Expression) expr[14]; - } else if (mark == 11) { - lookType = (Expression>) expr[15]; - lookRadius = (Expression) expr[16]; - } else if (mark == 12) { - meleeTarget = (Expression>) expr[17]; - meleeSpeed = (Expression) expr[18]; - meleeMemorize = (Expression) expr[19]; - } else if (mark == 13) { - moveTargetSpeed = (Expression) expr[20]; - moveTargetRadius = (Expression) expr[21]; - } else if (mark == 14) { - nearTarget = (Expression>) expr[22]; - checkSight = (Expression) expr[23]; - } else if (mark == 17) { - panicSpeed = (Expression) expr[24]; - } else if (mark == 19) { - randomWalkSpeed = (Expression) expr[25]; - randomWalkInterval = (Expression) expr[26]; - } else if (mark == 31) { - temptItem = (Expression) expr[27]; - temptSpeed = (Expression) expr[28]; - temptScared = (Expression) expr[29]; - } else if (mark == 32) { - nonTamedTarget = (Expression>) expr[30]; - } - entity = (Expression) expr[31]; - return true; - } - - @Override - public String toString(@Nullable Event e, boolean debug) { - return "add pathfinder goal to" + entity.toString(e, debug); - } - - @SuppressWarnings("deprecation") - @Override - protected void execute(Event e) { - int priority = 0; - if (goalPriority != null) { - priority = goalPriority.getSingle(e).intValue(); - } else { - priority = 4; - } - if (priority < 0) { - priority = 0; - } else if (priority > 9) { - priority = 9; - } - LivingEntity ent = entity.getSingle(e); - if (ent == null ||ent instanceof Player) - return; - Object obcEnt = craftLivEnt.cast(ent); - try { - Object nmsEnt = null; - boolean target = false; - Object newGoal = null; - nmsEnt = entInsent.cast(obcEnt.getClass().getMethod("getHandle").invoke(obcEnt)); - Object goals = ReflectionUtils.getField("goalSelector", entInsent, nmsEnt); - Object targets = ReflectionUtils.getField("targetSelector", entInsent, nmsEnt); - if (mark == 0) { - float radius = 6.0F; - double spd = 1.0D; - double nearSpd = 1.2D; - if (avoidRadius != null) - radius = avoidRadius.getSingle(e).floatValue(); - if (avoidSpeed != null) - spd = avoidSpeed.getSingle(e).doubleValue(); - if (avoidSpeedNear != null) - nearSpd = avoidSpeedNear.getSingle(e).doubleValue(); - EntityData entityData; - String exprInput = typeToAvoid.toString(e, false); - if (exprInput.startsWith("the ")) { - exprInput = exprInput.substring(4); - } - entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); - if (!LivingEntity.class.isAssignableFrom(entityData.getType())) { - return; - } - String className = entityData.getType().getSimpleName(); - if (className.equals("HumanEntity")) - className = "Human"; - else if (className.equals("LivingEntity")) - className = "Living"; - className = "Entity" + className; - Class nmsClass = ReflectionUtils.getNMSClass(className, false); - if (nmsClass == null) - return; - if (ent instanceof Rabbit) { - Class goalRabbitAvoid = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalRabbitAvoidTarget", false); - newGoal = goalRabbitAvoid.getDeclaredConstructor(nmsEnt.getClass(), Class.class, float.class, double.class, double.class).newInstance(nmsEnt, nmsClass, radius, spd, nearSpd); - } else { - Class goalAvoid = ReflectionUtils.getNMSClass("PathfinderGoalAvoidTarget", false); - newGoal = goalAvoid.getConstructor(entCreature, Class.class, float.class, double.class, double.class).newInstance(nmsEnt, nmsClass, radius, spd, nearSpd); - } - } else if (mark == 1) { - Class goalBreakDoor = ReflectionUtils.getNMSClass("PathfinderGoalBreakDoor", false); - newGoal = goalBreakDoor.getConstructor(entInsent).newInstance(nmsEnt); - } else if (mark == 2) { - Class goalBreed = ReflectionUtils.getNMSClass("PathfinderGoalBreed", false); - double spd = 1.0D; - if (breedSpeed != null) - spd = breedSpeed.getSingle(e).doubleValue(); - if (!(ent instanceof Animals)) - return; - newGoal = goalBreed.getConstructor(entAnimal, double.class).newInstance(nmsEnt, spd); - } else if (mark == 3) { - Class goalEatGrass = ReflectionUtils.getNMSClass("PathfinderGoalEatTile", false); - newGoal = goalEatGrass.getConstructor(entInsent).newInstance(nmsEnt); - } else if (mark == 4) { - Class goalFleeSun = ReflectionUtils.getNMSClass("PathfinderGoalFleeSun", false); - double spd = 1.0D; - if (fleeSunSpeed != null) - spd = fleeSunSpeed.getSingle(e).doubleValue(); - newGoal = goalFleeSun.getConstructor(entCreature, double.class).newInstance(nmsEnt, spd); - } else if (mark == 5) { - Class goalFloat = ReflectionUtils.getNMSClass("PathfinderGoalFloat", false); - newGoal = goalFloat.getConstructor(entInsent).newInstance(nmsEnt); - } else if (mark == 6) { - Class goalFollowOwner = ReflectionUtils.getNMSClass("PathfinderGoalFollowOwner", false); - double spd = 1.0D; - if (followOwnerSpeed != null) - spd = followOwnerSpeed.getSingle(e).doubleValue(); - float minDist = 3.0F; - if (followMinDist != null) - minDist = followMinDist.getSingle(e).floatValue(); - float maxDist = 10.0F; - if (followMaxDist != null) - maxDist = followMaxDist.getSingle(e).floatValue(); - if (!(ent instanceof Tameable)) - return; - newGoal = goalFollowOwner.getConstructor(entTameable, double.class, float.class, float.class).newInstance(nmsEnt, spd, maxDist, minDist); - } else if (mark == 7) { - Class goalFollowAdults = ReflectionUtils.getNMSClass("PathfinderGoalFollowParent", false); - double spd = 1.0D; - if (followAdultsSpeed != null) - spd = followAdultsSpeed.getSingle(e).doubleValue(); - if (!(ent instanceof Animals)) - return; - newGoal = goalFollowAdults.getConstructor(entAnimal, double.class).newInstance(nmsEnt, spd); - } else if (mark == 8) { - target = true; - boolean callHelp = false; - Class goalReactAttack = ReflectionUtils.getNMSClass("PathfinderGoalHurtByTarget", false); - EntityData entityData; - String exprInput = typesToFightBack.toString(e, false); - if (exprInput.startsWith("the ")) { - exprInput = exprInput.substring(4); - } - entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); - if (!LivingEntity.class.isAssignableFrom(entityData.getType())) - return; - String className = entityData.getType().getSimpleName(); - if (className.equals("HumanEntity")) - className = "Human"; - else if (className.equals("LivingEntity")) - className = "Living"; - className = "Entity" + className; - Class[] nmsClass = new Class[] { ReflectionUtils.getNMSClass(className, false) }; - if (nmsClass[0] == null) - return; - if (callForHelp != null) - callHelp = callForHelp.getSingle(e); - newGoal = goalReactAttack.getConstructor(entCreature, boolean.class, Class[].class).newInstance(nmsEnt, callHelp, nmsClass); - } else if (mark == 9) { - Class goalJumpOnBlock = ReflectionUtils.getNMSClass("PathfinderGoalJumpOnBlock", false); - double spd = 1.0D; - if (jumpOnBlockSpeed != null) - spd = jumpOnBlockSpeed.getSingle(e).doubleValue(); - if (!(ent instanceof Ocelot)) - return; - newGoal = goalJumpOnBlock.getConstructor(nmsEnt.getClass(), double.class).newInstance(nmsEnt, spd); - } else if (mark == 10) { - Class goalLeapTarget = ReflectionUtils.getNMSClass("PathfinderGoalLeapAtTarget", false); - float height = 0.4F; - if (leapHeight != null) - height = leapHeight.getSingle(e).floatValue(); - newGoal = goalLeapTarget.getConstructor(entInsent, float.class).newInstance(nmsEnt, height); - } else if (mark == 11) { - Class goalLookEntities = ReflectionUtils.getNMSClass("PathfinderGoalLookAtPlayer", false); - EntityData entityData; - String exprInput = lookType.toString(e, false); - if (exprInput.startsWith("the ")) { - exprInput = exprInput.substring(4); - } - entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); - if (!LivingEntity.class.isAssignableFrom(entityData.getType())) - return; - String className = entityData.getType().getSimpleName(); - if (className.equals("HumanEntity")) - className = "Human"; - else if (className.equals("LivingEntity")) - className = "Living"; - className = "Entity" + className; - Class nmsClass = ReflectionUtils.getNMSClass(className, false); - if (nmsClass == null) - return; - float radius = 1.0F; - if (lookRadius != null) - radius = lookRadius.getSingle(e).floatValue(); - newGoal = goalLookEntities.getConstructor(entInsent, Class.class, float.class).newInstance(nmsEnt, nmsClass, radius); - } else if (mark == 12) { - EntityData entityData; - String exprInput = meleeTarget.toString(e, false); - if (exprInput.startsWith("the ")) { - exprInput = exprInput.substring(4); - } - entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); - if (!LivingEntity.class.isAssignableFrom(entityData.getType())) - return; - String className = entityData.getType().getSimpleName(); - if (className.equals("HumanEntity")) - className = "Human"; - else if (className.equals("LivingEntity")) - className = "Living"; - className = "Entity" + className; - Class nmsClass = ReflectionUtils.getNMSClass(className, false); - if (nmsClass == null) - return; - if (ent instanceof Spider) { - Class goalSpiderMelee = ReflectionUtils.getNMSClass("EntitySpider$PathfinderGoalSpiderMeleeAttack", false); - Constructor constr = goalSpiderMelee.getDeclaredConstructor(nmsEnt.getClass(), Class.class); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt, nmsClass); - } else { - Class goalMeleeAttack = ReflectionUtils.getNMSClass("PathfinderGoalMeleeAttack", false); - double spd = 1.0D; - if (meleeSpeed != null) - spd = meleeSpeed.getSingle(e).doubleValue(); - boolean memorize = false; - if (meleeMemorize != null) - memorize = meleeMemorize.getSingle(e); - newGoal = goalMeleeAttack.getConstructor(entCreature, Class.class, double.class, boolean.class).newInstance(nmsEnt, nmsClass, spd, memorize); - } - } else if (mark == 13) { - Class goalGotoTarget = ReflectionUtils.getNMSClass("PathfinderGoalMoveTowardsTarget", false); - double spd = 1.0D; - if (moveTargetSpeed != null) - spd = moveTargetSpeed.getSingle(e).doubleValue(); - float radius = 32.0F; - if (moveTargetRadius != null) - radius = moveTargetRadius.getSingle(e).floatValue(); - newGoal = goalGotoTarget.getConstructor(entCreature, double.class, float.class).newInstance(nmsEnt, spd, radius); - } else if (mark == 14) { - target = true; - boolean checkView = false; - EntityData entityData; - String exprInput = nearTarget.toString(e, false); - if (exprInput.startsWith("the ")) { - exprInput = exprInput.substring(4); - } - entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); - if (!LivingEntity.class.isAssignableFrom(entityData.getType())) - return; - String className = entityData.getType().getSimpleName(); - if (className.equals("HumanEntity")) - className = "Human"; - else if (className.equals("LivingEntity")) - className = "Living"; - className = "Entity" + className; - Class nmsClass = ReflectionUtils.getNMSClass(className, false); - if (nmsClass == null) - return; - if (ent instanceof Spider) { - Class goalSpiderNearTarget = ReflectionUtils.getNMSClass("EntitySpider$PathfinderGoalSpiderNearestAttackableTarget", false); - Constructor constr = goalSpiderNearTarget.getDeclaredConstructor(nmsEnt.getClass(), Class.class); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt, nmsClass); - } else { - if (checkSight != null) - checkView = checkSight.getSingle(e); - Class goalNearTarget = ReflectionUtils.getNMSClass("PathfinderGoalNearestAttackableTarget", false); - newGoal = goalNearTarget.getConstructor(entCreature, Class.class, boolean.class).newInstance(nmsEnt, nmsClass, checkView); - } - } else if (mark == 15) { - Class goalOcelotAttack = ReflectionUtils.getNMSClass("PathfinderGoalOcelotAttack", false); - newGoal = goalOcelotAttack.getConstructor(entInsent).newInstance(nmsEnt); - } else if (mark == 16) { - Class goalOpenDoors = ReflectionUtils.getNMSClass("PathfinderGoalOpenDoor", false); - newGoal = goalOpenDoors.getConstructor(entInsent, boolean.class).newInstance(nmsEnt, false); - } else if (mark == 17) { - double spd = 1.0D; - if (panicSpeed != null) - spd = panicSpeed.getSingle(e).doubleValue(); - if (ent instanceof Rabbit) { - Class goalRabbitPanic = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalRabbitPanic", false); - newGoal = goalRabbitPanic.getDeclaredConstructor(nmsEnt.getClass(), double.class).newInstance(nmsEnt, spd); - } else { - Class goalPanic = ReflectionUtils.getNMSClass("PathfinderGoalPanic", false); - - newGoal = goalPanic.getConstructor(entCreature, double.class).newInstance(nmsEnt, spd); - } - } else if (mark == 18) { - Class goalRandomLook = ReflectionUtils.getNMSClass("PathfinderGoalRandomLookaround", false); - newGoal = goalRandomLook.getConstructor(entInsent).newInstance(nmsEnt); - } else if (mark == 19) { - Class goalWander = ReflectionUtils.getNMSClass("PathfinderGoalRandomStroll", false); - double spd = 1.0D; - if (randomWalkSpeed != null) - spd = randomWalkSpeed.getSingle(e).doubleValue(); - int interval = 120; - if (randomWalkInterval != null) - interval = randomWalkInterval.getSingle(e).getTicks(); - newGoal = goalWander.getConstructor(entCreature, double.class, int.class).newInstance(nmsEnt, spd, interval); - } else if (mark == 20) { - Class goalSit = ReflectionUtils.getNMSClass("PathfinderGoalSit", false); - if (!(ent instanceof Tameable)) - return; - newGoal = goalSit.getConstructor(entTameable).newInstance(nmsEnt); - } else if (mark == 21) { - Class goalSwell = ReflectionUtils.getNMSClass("PathfinderGoalSwell", false); - if (!(ent instanceof Creeper)) - return; - newGoal = goalSwell.getConstructor(nmsEnt.getClass()).newInstance(nmsEnt); - } else if (mark == 22) { - Class goalSquid = ReflectionUtils.getNMSClass("EntitySquid$PathfinderGoalSquid", false); - if (!(ent instanceof Squid)) - return; - Constructor constr = goalSquid.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 23) { - if (ent instanceof Blaze) { - Class goalBlazeFireball = ReflectionUtils.getNMSClass("EntityBlaze$PathfinderGoalBlazeFireball", false); - Constructor constr = goalBlazeFireball.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (ent instanceof Ghast) { - Class goalGhastFireball = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastAttackTarget", false); - Constructor constr = goalGhastFireball.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } - } else if (mark == 24) { - Class goalHideInBlock = ReflectionUtils.getNMSClass("EntitySilverfish$PathfinderGoalSilverfishHideInBlock", false); - if (!(ent instanceof Silverfish)) - return; - Constructor constr = goalHideInBlock.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 25) { - Class goalWakeSilverfish = ReflectionUtils.getNMSClass("EntitySilverfish$PathfinderGoalSilverfishWakeOthers", false); - if (!(ent instanceof Silverfish)) - return; - Constructor constr = goalWakeSilverfish.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 26) { - Class goalPickBlocks = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalEndermanPickupBlock", false); - if (!(ent instanceof Enderman)) - return; - Constructor constr = goalPickBlocks.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 27) { - Class goalPlaceBlocks = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalEndermanPlaceBlock", false); - if (!(ent instanceof Enderman)) - return; - Constructor constr = goalPlaceBlocks.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 28) { - target = true; - Class goalAttackLooker = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalPlayerWhoLookedAtTarget", false); - if (!(ent instanceof Enderman)) - return; - Constructor constr = goalAttackLooker.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 29) { - Class goalGhastMoveTarget = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastMoveTowardsTarget", false); - if (!(ent instanceof Ghast)) - return; - Constructor constr = goalGhastMoveTarget.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 30) { - Class goalGhastIdleMove = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastIdleMove", false); - if (!(ent instanceof Ghast)) - return; - Constructor constr = goalGhastIdleMove.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 31) { - Class goalTempt = ReflectionUtils.getNMSClass("PathfinderGoalTempt", false); - ItemStack itemStack = temptItem.getSingle(e); - if (itemStack.getType() == Material.AIR || itemStack == null) - return; - Object nmsItemStack = craftItemClass.getMethod("asNMSCopy", ItemStack.class).invoke(itemStack, itemStack); - Object nmsItem = nmsItemStack.getClass().getMethod("getItem").invoke(nmsItemStack); - double spd = 1.0D; - if (temptSpeed != null) - spd = temptSpeed.getSingle(e).doubleValue(); - boolean scared = false; - if (temptScared != null) - scared = temptScared.getSingle(e); - newGoal = goalTempt.getConstructor(entCreature, double.class, nmsItemClass, boolean.class).newInstance(nmsEnt, spd, nmsItem, scared); - } else if (mark == 32) { - target = true; - Class goalTargetNonTamed = ReflectionUtils.getNMSClass("PathfinderGoalRandomTargetNonTamed", false); - if (!(ent instanceof Tameable)) - return; - EntityData entityData; - String exprInput = nonTamedTarget.toString(e, false); - if (exprInput.startsWith("the ")) { - exprInput = exprInput.substring(4); - } - entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); - if (!LivingEntity.class.isAssignableFrom(entityData.getType())) { - return; - } - String className = entityData.getType().getSimpleName(); - if (className.equals("HumanEntity")) - className = "Human"; - else if (className.equals("LivingEntity")) - className = "Living"; - className = "Entity" + className; - Class nmsClass = ReflectionUtils.getNMSClass(className, false); - if (nmsClass == null) - return; - newGoal = goalTargetNonTamed.getConstructor(entTameable, Class.class, boolean.class, Predicate.class).newInstance(nmsEnt, nmsClass, false, Predicates.alwaysTrue()); - } else if (mark == 33) { - if (!(ent instanceof Guardian)) - return; - Class goalGuardianAttack = ReflectionUtils.getNMSClass("EntityGuardian$PathfinderGoalGuardianAttack", false); - Constructor constr = goalGuardianAttack.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 34) { - if (!(ent instanceof PigZombie)) - return; - target = true; - Class goalAnger = ReflectionUtils.getNMSClass("EntityPigZombie$PathfinderGoalAnger", false); - Constructor constr = goalAnger.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 35) { - if (!(ent instanceof PigZombie)) - return; - target = true; - Class goalAngerOther = ReflectionUtils.getNMSClass("EntityPigZombie$PathfinderGoalAngerOther", false); - Constructor constr = goalAngerOther.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 36) { - if (!(ent instanceof Rabbit)) - return; - Class goalEatCarrots = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalEatCarrots", false); - Constructor constr = goalEatCarrots.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 37) { - if (!(ent instanceof Rabbit)) - return; - Class goalRabbitAttack = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalKillerRabbitMeleeAttack", false); - Constructor constr = goalRabbitAttack.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 38) { - if (!(ent instanceof Slime)) - return; - Class goalJump = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeRandomJump", false); - Constructor constr = goalJump.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 39) { - if (!(ent instanceof Slime)) - return; - Class goalRandomDir = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeRandomDirection", false); - Constructor constr = goalRandomDir.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } else if (mark == 40) { - if (!(ent instanceof Slime)) - return; - Class goalSlimeWander = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeIdle", false); - Constructor constr = goalSlimeWander.getDeclaredConstructor(nmsEnt.getClass()); - constr.setAccessible(true); - newGoal = constr.newInstance(nmsEnt); - } - if (newGoal == null) - return; - Class goal = ReflectionUtils.getNMSClass("PathfinderGoal", false); - Class goalSelector = ReflectionUtils.getNMSClass("PathfinderGoalSelector", false); - if (target) { //Target Selector - newGoal = goalSelector.getMethod("a", int.class, goal).invoke(targets, priority, newGoal); - } else { //Goal Selector - newGoal = goalSelector.getMethod("a", int.class, goal).invoke(goals, priority, newGoal); - - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } +package me.TheBukor.SkStuff.effects; + +import java.lang.reflect.Constructor; + +import javax.annotation.Nullable; + +import org.bukkit.Material; +import org.bukkit.entity.Animals; +import org.bukkit.entity.Blaze; +import org.bukkit.entity.Creeper; +import org.bukkit.entity.Enderman; +import org.bukkit.entity.Ghast; +import org.bukkit.entity.Guardian; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Ocelot; +import org.bukkit.entity.PigZombie; +import org.bukkit.entity.Player; +import org.bukkit.entity.Rabbit; +import org.bukkit.entity.Silverfish; +import org.bukkit.entity.Slime; +import org.bukkit.entity.Spider; +import org.bukkit.entity.Squid; +import org.bukkit.entity.Tameable; +import org.bukkit.event.Event; +import org.bukkit.inventory.ItemStack; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; + +import ch.njol.skript.entity.EntityData; +import ch.njol.skript.lang.Effect; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.skript.localization.Language; +import ch.njol.skript.util.Timespan; +import ch.njol.util.Kleenean; +import me.TheBukor.SkStuff.SkStuff; +import me.TheBukor.SkStuff.util.ReflectionUtils; + +public class EffSetPathGoal extends Effect { + private Expression goalPriority; + private Expression> typeToAvoid; + private Expression avoidRadius; + private Expression avoidSpeed; + private Expression avoidSpeedNear; + private Expression breedSpeed; + private Expression fleeSunSpeed; + private Expression followOwnerSpeed; + private Expression followMinDist; + private Expression followMaxDist; + private Expression followAdultsSpeed; + private Expression> typesToFightBack; + private Expression callForHelp; + private Expression jumpOnBlockSpeed; + private Expression leapHeight; + private Expression> lookType; + private Expression lookRadius; + private Expression> meleeTarget; + private Expression meleeSpeed; + private Expression meleeMemorize; + private Expression moveTargetSpeed; + private Expression moveTargetRadius; + private Expression> nearTarget; + private Expression checkSight; + private Expression panicSpeed; + private Expression randomWalkSpeed; + private Expression randomWalkInterval; + private Expression temptItem; + private Expression temptSpeed; + private Expression temptScared; + private Expression> nonTamedTarget; + private Expression entity; + + private int mark; + + private Class craftItemClass = ReflectionUtils.getOBCClass("inventory.CraftItemStack"); + private Class craftLivEnt = ReflectionUtils.getOBCClass("entity.CraftLivingEntity"); + private Class entAnimal = ReflectionUtils.getNMSClass("EntityAnimal"); + private Class entCreature = ReflectionUtils.getNMSClass("EntityCreature"); + private Class entInsent = ReflectionUtils.getNMSClass("EntityInsentient"); + private Class entTameable = ReflectionUtils.getNMSClass("EntityTameableAnimal"); + private Class nmsItemClass = ReflectionUtils.getNMSClass("Item"); + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { + goalPriority = (Expression) expr[0]; + mark = result.mark; + if (mark == 0) { + typeToAvoid = (Expression>) expr[1]; + avoidRadius = (Expression) expr[2]; + avoidSpeed = (Expression) expr[3]; + avoidSpeedNear = (Expression) expr[4]; + } else if (mark == 2) { + breedSpeed = (Expression) expr[5]; + } else if (mark == 4) { + fleeSunSpeed = (Expression) expr[6]; + } else if (mark == 6) { + followOwnerSpeed = (Expression) expr[7]; + followMinDist = (Expression) expr[8]; + followMaxDist = (Expression) expr[9]; + } else if (mark == 7) { + followAdultsSpeed = (Expression) expr[10]; + } else if (mark == 8) { + typesToFightBack = (Expression>) expr[11]; + callForHelp = (Expression) expr[12]; + } else if (mark == 9) { + jumpOnBlockSpeed = (Expression) expr[13]; + } else if (mark == 10) { + leapHeight = (Expression) expr[14]; + } else if (mark == 11) { + lookType = (Expression>) expr[15]; + lookRadius = (Expression) expr[16]; + } else if (mark == 12) { + meleeTarget = (Expression>) expr[17]; + meleeSpeed = (Expression) expr[18]; + meleeMemorize = (Expression) expr[19]; + } else if (mark == 13) { + moveTargetSpeed = (Expression) expr[20]; + moveTargetRadius = (Expression) expr[21]; + } else if (mark == 14) { + nearTarget = (Expression>) expr[22]; + checkSight = (Expression) expr[23]; + } else if (mark == 17) { + panicSpeed = (Expression) expr[24]; + } else if (mark == 19) { + randomWalkSpeed = (Expression) expr[25]; + randomWalkInterval = (Expression) expr[26]; + } else if (mark == 31) { + temptItem = (Expression) expr[27]; + temptSpeed = (Expression) expr[28]; + temptScared = (Expression) expr[29]; + } else if (mark == 32) { + nonTamedTarget = (Expression>) expr[30]; + } + entity = (Expression) expr[31]; + return true; + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return "add pathfinder goal to" + entity.toString(e, debug); + } + + @SuppressWarnings("deprecation") + @Override + protected void execute(Event e) { + int priority = 0; + if (goalPriority != null) { + priority = goalPriority.getSingle(e).intValue(); + } else { + priority = 4; + } + if (priority < 0) { + priority = 0; + } else if (priority > 9) { + priority = 9; + } + LivingEntity ent = entity.getSingle(e); + if (ent == null ||ent instanceof Player) + return; + Object obcEnt = craftLivEnt.cast(ent); + try { + Object nmsEnt = null; + boolean target = false; + Object newGoal = null; + nmsEnt = entInsent.cast(obcEnt.getClass().getMethod("getHandle").invoke(obcEnt)); + if (mark == 0) { + boolean wasLocal = Language.setUseLocal(false); + float radius = 6.0F; + double spd = 1.0D; + double nearSpd = 1.2D; + if (avoidRadius != null) + radius = avoidRadius.getSingle(e).floatValue(); + if (avoidSpeed != null) + spd = avoidSpeed.getSingle(e).doubleValue(); + if (avoidSpeedNear != null) + nearSpd = avoidSpeedNear.getSingle(e).doubleValue(); + EntityData entityData; + String exprInput = typeToAvoid.toString(e, false); + if (exprInput.startsWith("the ")) { + exprInput = exprInput.substring(4); + } + try { + entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); + } finally { + Language.setUseLocal(wasLocal); + } + if (!LivingEntity.class.isAssignableFrom(entityData.getType())) { + return; + } + String className = entityData.getType().getSimpleName(); + if (className.equals("HumanEntity")) + className = "Human"; + else if (className.equals("LivingEntity")) + className = "Living"; + className = "Entity" + className; + Class nmsClass = ReflectionUtils.getNMSClass(className); + if (nmsClass == null) + return; + if (ent instanceof Rabbit) { + Class goalRabbitAvoid = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalRabbitAvoidTarget"); + newGoal = goalRabbitAvoid.getDeclaredConstructor(nmsEnt.getClass(), Class.class, float.class, double.class, double.class).newInstance(nmsEnt, nmsClass, radius, spd, nearSpd); + } else { + Class goalAvoid = ReflectionUtils.getNMSClass("PathfinderGoalAvoidTarget"); + newGoal = goalAvoid.getConstructor(entCreature, Class.class, float.class, double.class, double.class).newInstance(nmsEnt, nmsClass, radius, spd, nearSpd); + } + } else if (mark == 1) { + Class goalBreakDoor = ReflectionUtils.getNMSClass("PathfinderGoalBreakDoor"); + newGoal = goalBreakDoor.getConstructor(entInsent).newInstance(nmsEnt); + } else if (mark == 2) { + Class goalBreed = ReflectionUtils.getNMSClass("PathfinderGoalBreed"); + double spd = 1.0D; + if (breedSpeed != null) + spd = breedSpeed.getSingle(e).doubleValue(); + if (!(ent instanceof Animals)) + return; + newGoal = goalBreed.getConstructor(entAnimal, double.class).newInstance(nmsEnt, spd); + } else if (mark == 3) { + Class goalEatGrass = ReflectionUtils.getNMSClass("PathfinderGoalEatTile"); + newGoal = goalEatGrass.getConstructor(entInsent).newInstance(nmsEnt); + } else if (mark == 4) { + Class goalFleeSun = ReflectionUtils.getNMSClass("PathfinderGoalFleeSun"); + double spd = 1.0D; + if (fleeSunSpeed != null) + spd = fleeSunSpeed.getSingle(e).doubleValue(); + newGoal = goalFleeSun.getConstructor(entCreature, double.class).newInstance(nmsEnt, spd); + } else if (mark == 5) { + Class goalFloat = ReflectionUtils.getNMSClass("PathfinderGoalFloat"); + newGoal = goalFloat.getConstructor(entInsent).newInstance(nmsEnt); + } else if (mark == 6) { + Class goalFollowOwner = ReflectionUtils.getNMSClass("PathfinderGoalFollowOwner"); + double spd = 1.0D; + if (followOwnerSpeed != null) + spd = followOwnerSpeed.getSingle(e).doubleValue(); + float minDist = 3.0F; + if (followMinDist != null) + minDist = followMinDist.getSingle(e).floatValue(); + float maxDist = 10.0F; + if (followMaxDist != null) + maxDist = followMaxDist.getSingle(e).floatValue(); + if (!(ent instanceof Tameable)) + return; + newGoal = goalFollowOwner.getConstructor(entTameable, double.class, float.class, float.class).newInstance(nmsEnt, spd, maxDist, minDist); + } else if (mark == 7) { + Class goalFollowAdults = ReflectionUtils.getNMSClass("PathfinderGoalFollowParent"); + double spd = 1.0D; + if (followAdultsSpeed != null) + spd = followAdultsSpeed.getSingle(e).doubleValue(); + if (!(ent instanceof Animals)) + return; + newGoal = goalFollowAdults.getConstructor(entAnimal, double.class).newInstance(nmsEnt, spd); + } else if (mark == 8) { + boolean wasLocal = Language.setUseLocal(false); + target = true; + boolean callHelp = false; + Class goalReactAttack = ReflectionUtils.getNMSClass("PathfinderGoalHurtByTarget"); + EntityData entityData; + String exprInput = typesToFightBack.toString(e, false); + if (exprInput.startsWith("the ")) { + exprInput = exprInput.substring(4); + } + try { + entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); + } finally { + Language.setUseLocal(wasLocal); + } + if (!LivingEntity.class.isAssignableFrom(entityData.getType())) + return; + String className = entityData.getType().getSimpleName(); + if (className.equals("HumanEntity")) + className = "Human"; + else if (className.equals("LivingEntity")) + className = "Living"; + className = "Entity" + className; + Class[] nmsClass = new Class[] { ReflectionUtils.getNMSClass(className) }; + if (nmsClass[0] == null) + return; + if (callForHelp != null) + callHelp = callForHelp.getSingle(e); + newGoal = goalReactAttack.getConstructor(entCreature, boolean.class, Class[].class).newInstance(nmsEnt, callHelp, nmsClass); + } else if (mark == 9) { + Class goalJumpOnBlock = ReflectionUtils.getNMSClass("PathfinderGoalJumpOnBlock"); + double spd = 1.0D; + if (jumpOnBlockSpeed != null) + spd = jumpOnBlockSpeed.getSingle(e).doubleValue(); + if (!(ent instanceof Ocelot)) + return; + newGoal = goalJumpOnBlock.getConstructor(nmsEnt.getClass(), double.class).newInstance(nmsEnt, spd); + } else if (mark == 10) { + Class goalLeapTarget = ReflectionUtils.getNMSClass("PathfinderGoalLeapAtTarget"); + float height = 0.4F; + if (leapHeight != null) + height = leapHeight.getSingle(e).floatValue(); + newGoal = goalLeapTarget.getConstructor(entInsent, float.class).newInstance(nmsEnt, height); + } else if (mark == 11) { + boolean wasLocal = Language.setUseLocal(false); + Class goalLookEntities = ReflectionUtils.getNMSClass("PathfinderGoalLookAtPlayer"); + EntityData entityData; + String exprInput = lookType.toString(e, false); + if (exprInput.startsWith("the ")) { + exprInput = exprInput.substring(4); + } + try { + entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); + } finally { + Language.setUseLocal(wasLocal); + } + if (!LivingEntity.class.isAssignableFrom(entityData.getType())) + return; + String className = entityData.getType().getSimpleName(); + if (className.equals("HumanEntity")) + className = "Human"; + else if (className.equals("LivingEntity")) + className = "Living"; + className = "Entity" + className; + Class nmsClass = ReflectionUtils.getNMSClass(className); + if (nmsClass == null) + return; + float radius = 1.0F; + if (lookRadius != null) + radius = lookRadius.getSingle(e).floatValue(); + newGoal = goalLookEntities.getConstructor(entInsent, Class.class, float.class).newInstance(nmsEnt, nmsClass, radius); + } else if (mark == 12) { + boolean wasLocal = Language.setUseLocal(false); + EntityData entityData; + String exprInput = meleeTarget.toString(e, false); + if (exprInput.startsWith("the ")) { + exprInput = exprInput.substring(4); + } + try { + entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); + } finally { + Language.setUseLocal(wasLocal); + } + if (!LivingEntity.class.isAssignableFrom(entityData.getType())) + return; + String className = entityData.getType().getSimpleName(); + if (className.equals("HumanEntity")) + className = "Human"; + else if (className.equals("LivingEntity")) + className = "Living"; + className = "Entity" + className; + Class nmsClass = ReflectionUtils.getNMSClass(className); + if (nmsClass == null) + return; + if (ent instanceof Spider) { + Class goalSpiderMelee = ReflectionUtils.getNMSClass("EntitySpider$PathfinderGoalSpiderMeleeAttack"); + Constructor constr = goalSpiderMelee.getDeclaredConstructor(nmsEnt.getClass(), Class.class); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt, nmsClass); + } else { + Class goalMeleeAttack = ReflectionUtils.getNMSClass("PathfinderGoalMeleeAttack"); + double spd = 1.0D; + if (meleeSpeed != null) + spd = meleeSpeed.getSingle(e).doubleValue(); + boolean memorize = false; + if (meleeMemorize != null) + memorize = meleeMemorize.getSingle(e); + newGoal = goalMeleeAttack.getConstructor(entCreature, Class.class, double.class, boolean.class).newInstance(nmsEnt, nmsClass, spd, memorize); + } + } else if (mark == 13) { + Class goalGotoTarget = ReflectionUtils.getNMSClass("PathfinderGoalMoveTowardsTarget"); + double spd = 1.0D; + if (moveTargetSpeed != null) + spd = moveTargetSpeed.getSingle(e).doubleValue(); + float radius = 32.0F; + if (moveTargetRadius != null) + radius = moveTargetRadius.getSingle(e).floatValue(); + newGoal = goalGotoTarget.getConstructor(entCreature, double.class, float.class).newInstance(nmsEnt, spd, radius); + } else if (mark == 14) { + boolean wasLocal = Language.setUseLocal(false); + target = true; + boolean checkView = false; + EntityData entityData; + String exprInput = nearTarget.toString(e, false); + if (exprInput.startsWith("the ")) { + exprInput = exprInput.substring(4); + } + try { + entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); + } finally { + Language.setUseLocal(wasLocal); + } + if (!LivingEntity.class.isAssignableFrom(entityData.getType())) + return; + String className = entityData.getType().getSimpleName(); + if (className.equals("HumanEntity")) + className = "Human"; + else if (className.equals("LivingEntity")) + className = "Living"; + className = "Entity" + className; + Class nmsClass = ReflectionUtils.getNMSClass(className); + if (nmsClass == null) + return; + if (ent instanceof Spider) { + Class goalSpiderNearTarget = ReflectionUtils.getNMSClass("EntitySpider$PathfinderGoalSpiderNearestAttackableTarget"); + Constructor constr = goalSpiderNearTarget.getDeclaredConstructor(nmsEnt.getClass(), Class.class); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt, nmsClass); + } else { + if (checkSight != null) + checkView = checkSight.getSingle(e); + Class goalNearTarget = ReflectionUtils.getNMSClass("PathfinderGoalNearestAttackableTarget"); + newGoal = goalNearTarget.getConstructor(entCreature, Class.class, boolean.class).newInstance(nmsEnt, nmsClass, checkView); + } + } else if (mark == 15) { + Class goalOcelotAttack = ReflectionUtils.getNMSClass("PathfinderGoalOcelotAttack"); + newGoal = goalOcelotAttack.getConstructor(entInsent).newInstance(nmsEnt); + } else if (mark == 16) { + Class goalOpenDoors = ReflectionUtils.getNMSClass("PathfinderGoalOpenDoor"); + newGoal = goalOpenDoors.getConstructor(entInsent, boolean.class).newInstance(nmsEnt, false); + } else if (mark == 17) { + double spd = 1.0D; + if (panicSpeed != null) + spd = panicSpeed.getSingle(e).doubleValue(); + if (ent instanceof Rabbit) { + Class goalRabbitPanic = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalRabbitPanic"); + newGoal = goalRabbitPanic.getDeclaredConstructor(nmsEnt.getClass(), double.class).newInstance(nmsEnt, spd); + } else { + Class goalPanic = ReflectionUtils.getNMSClass("PathfinderGoalPanic"); + + newGoal = goalPanic.getConstructor(entCreature, double.class).newInstance(nmsEnt, spd); + } + } else if (mark == 18) { + Class goalRandomLook = ReflectionUtils.getNMSClass("PathfinderGoalRandomLookaround"); + newGoal = goalRandomLook.getConstructor(entInsent).newInstance(nmsEnt); + } else if (mark == 19) { + Class goalWander = ReflectionUtils.getNMSClass("PathfinderGoalRandomStroll"); + double spd = 1.0D; + if (randomWalkSpeed != null) + spd = randomWalkSpeed.getSingle(e).doubleValue(); + int interval = 120; + if (randomWalkInterval != null) + interval = randomWalkInterval.getSingle(e).getTicks(); + newGoal = goalWander.getConstructor(entCreature, double.class, int.class).newInstance(nmsEnt, spd, interval); + } else if (mark == 20) { + Class goalSit = ReflectionUtils.getNMSClass("PathfinderGoalSit"); + if (!(ent instanceof Tameable)) + return; + newGoal = goalSit.getConstructor(entTameable).newInstance(nmsEnt); + } else if (mark == 21) { + Class goalSwell = ReflectionUtils.getNMSClass("PathfinderGoalSwell"); + if (!(ent instanceof Creeper)) + return; + newGoal = goalSwell.getConstructor(nmsEnt.getClass()).newInstance(nmsEnt); + } else if (mark == 22) { + Class goalSquid = ReflectionUtils.getNMSClass("EntitySquid$PathfinderGoalSquid"); + if (!(ent instanceof Squid)) + return; + Constructor constr = goalSquid.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 23) { + if (ent instanceof Blaze) { + Class goalBlazeFireball = ReflectionUtils.getNMSClass("EntityBlaze$PathfinderGoalBlazeFireball"); + Constructor constr = goalBlazeFireball.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (ent instanceof Ghast) { + Class goalGhastFireball = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastAttackTarget"); + Constructor constr = goalGhastFireball.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } + } else if (mark == 24) { + Class goalHideInBlock = ReflectionUtils.getNMSClass("EntitySilverfish$PathfinderGoalSilverfishHideInBlock"); + if (!(ent instanceof Silverfish)) + return; + Constructor constr = goalHideInBlock.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 25) { + Class goalWakeSilverfish = ReflectionUtils.getNMSClass("EntitySilverfish$PathfinderGoalSilverfishWakeOthers"); + if (!(ent instanceof Silverfish)) + return; + Constructor constr = goalWakeSilverfish.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 26) { + Class goalPickBlocks = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalEndermanPickupBlock"); + if (!(ent instanceof Enderman)) + return; + Constructor constr = goalPickBlocks.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 27) { + Class goalPlaceBlocks = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalEndermanPlaceBlock"); + if (!(ent instanceof Enderman)) + return; + Constructor constr = goalPlaceBlocks.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 28) { + target = true; + Class goalAttackLooker = ReflectionUtils.getNMSClass("EntityEnderman$PathfinderGoalPlayerWhoLookedAtTarget"); + if (!(ent instanceof Enderman)) + return; + Constructor constr = goalAttackLooker.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 29) { + Class goalGhastMoveTarget = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastMoveTowardsTarget"); + if (!(ent instanceof Ghast)) + return; + Constructor constr = goalGhastMoveTarget.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 30) { + Class goalGhastIdleMove = ReflectionUtils.getNMSClass("EntityGhast$PathfinderGoalGhastIdleMove"); + if (!(ent instanceof Ghast)) + return; + Constructor constr = goalGhastIdleMove.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 31) { + Class goalTempt = ReflectionUtils.getNMSClass("PathfinderGoalTempt"); + ItemStack itemStack = temptItem.getSingle(e); + if (itemStack.getType() == Material.AIR || itemStack == null) + return; + Object nmsItemStack = craftItemClass.getMethod("asNMSCopy", ItemStack.class).invoke(itemStack, itemStack); + Object nmsItem = nmsItemStack.getClass().getMethod("getItem").invoke(nmsItemStack); + double spd = 1.0D; + if (temptSpeed != null) + spd = temptSpeed.getSingle(e).doubleValue(); + boolean scared = false; + if (temptScared != null) + scared = temptScared.getSingle(e); + newGoal = goalTempt.getConstructor(entCreature, double.class, nmsItemClass, boolean.class).newInstance(nmsEnt, spd, nmsItem, scared); + } else if (mark == 32) { + boolean wasLocal = Language.setUseLocal(false); + target = true; + Class goalTargetNonTamed = ReflectionUtils.getNMSClass("PathfinderGoalRandomTargetNonTamed"); + if (!(ent instanceof Tameable)) + return; + EntityData entityData; + String exprInput = nonTamedTarget.toString(e, false); + if (exprInput.startsWith("the ")) { + exprInput = exprInput.substring(4); + } + try { + entityData = EntityData.parseWithoutIndefiniteArticle(exprInput); + } finally { + Language.setUseLocal(wasLocal); + } + if (!LivingEntity.class.isAssignableFrom(entityData.getType())) { + return; + } + String className = entityData.getType().getSimpleName(); + if (className.equals("HumanEntity")) + className = "Human"; + else if (className.equals("LivingEntity")) + className = "Living"; + className = "Entity" + className; + Class nmsClass = ReflectionUtils.getNMSClass(className); + if (nmsClass == null) + return; + newGoal = goalTargetNonTamed.getConstructor(entTameable, Class.class, boolean.class, Predicate.class).newInstance(nmsEnt, nmsClass, false, Predicates.alwaysTrue()); + } else if (mark == 33) { + if (!(ent instanceof Guardian)) + return; + Class goalGuardianAttack = ReflectionUtils.getNMSClass("EntityGuardian$PathfinderGoalGuardianAttack"); + Constructor constr = goalGuardianAttack.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 34) { + if (!(ent instanceof PigZombie)) + return; + target = true; + Class goalAnger = ReflectionUtils.getNMSClass("EntityPigZombie$PathfinderGoalAnger"); + Constructor constr = goalAnger.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 35) { + if (!(ent instanceof PigZombie)) + return; + target = true; + Class goalAngerOther = ReflectionUtils.getNMSClass("EntityPigZombie$PathfinderGoalAngerOther"); + Constructor constr = goalAngerOther.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 36) { + if (!(ent instanceof Rabbit)) + return; + Class goalEatCarrots = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalEatCarrots"); + Constructor constr = goalEatCarrots.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 37) { + if (!(ent instanceof Rabbit)) + return; + Class goalRabbitAttack = ReflectionUtils.getNMSClass("EntityRabbit$PathfinderGoalKillerRabbitMeleeAttack"); + Constructor constr = goalRabbitAttack.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 38) { + if (!(ent instanceof Slime)) + return; + Class goalJump = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeRandomJump"); + Constructor constr = goalJump.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 39) { + if (!(ent instanceof Slime)) + return; + Class goalRandomDir = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeRandomDirection"); + Constructor constr = goalRandomDir.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } else if (mark == 40) { + if (!(ent instanceof Slime)) + return; + Class goalSlimeWander = ReflectionUtils.getNMSClass("EntitySlime$PathfinderGoalSlimeIdle"); + Constructor constr = goalSlimeWander.getDeclaredConstructor(nmsEnt.getClass()); + constr.setAccessible(true); + newGoal = constr.newInstance(nmsEnt); + } + if (newGoal == null) + return; + SkStuff.getNMSMethods().addPathfinderGoal(nmsEnt, priority, newGoal, target); + } catch (Exception ex) { + ex.printStackTrace(); + } + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/expressions/ExprEndermanBlocks.java b/src/me/TheBukor/SkStuff/expressions/ExprEndermanBlocks.java index c4668d8..2031a3c 100644 --- a/src/me/TheBukor/SkStuff/expressions/ExprEndermanBlocks.java +++ b/src/me/TheBukor/SkStuff/expressions/ExprEndermanBlocks.java @@ -1,163 +1,163 @@ -package me.TheBukor.SkStuff.expressions; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -import javax.annotation.Nullable; - -import org.bukkit.Material; -import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; -import org.bukkit.entity.Enderman; -import org.bukkit.entity.Entity; -import org.bukkit.event.Event; -import org.bukkit.inventory.ItemStack; - -import ch.njol.skript.classes.Changer.ChangeMode; -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.lang.util.SimpleExpression; -import ch.njol.util.Kleenean; -import ch.njol.util.coll.CollectionUtils; -import me.TheBukor.SkStuff.util.ReflectionUtils; - -public class ExprEndermanBlocks extends SimpleExpression { - private Expression entity; - - private Class nmsBlockClass = ReflectionUtils.getNMSClass("Block", false); - private Class endermanClass = ReflectionUtils.getNMSClass("EntityEnderman", false); - private Class nmsIBlockData = ReflectionUtils.getNMSClass("IBlockData", false); - private Class nmsItemClass = ReflectionUtils.getNMSClass("ItemStack", false); - private Class craftEntClass = ReflectionUtils.getOBCClass("entity.CraftEntity"); - private Class craftItemClass = ReflectionUtils.getOBCClass("inventory.CraftItemStack"); - - @Override - public Class getReturnType() { - return ItemStack.class; - } - - @Override - public boolean isSingle() { - return false; - } - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { - entity = (Expression) expr[0]; - return true; - } - - @Override - public String toString(@Nullable Event e, boolean debug) { - return "blocks that " + entity.toString(e, debug) + " can carry"; - } - - @SuppressWarnings("unchecked") - @Override - @Nullable - protected ItemStack[] get(Event e) { - Entity ent = entity.getSingle(e); - if (ent == null || !(ent instanceof Enderman)) - return null; - Object nmsEnt = null; - try { - nmsEnt = craftEntClass.cast(ent).getClass().getMethod("getHandle").invoke(ent); - } catch (Exception ex) { - ex.printStackTrace(); - } - Set nmsBlocks = (Set) ReflectionUtils.getField("c", endermanClass, nmsEnt); - List items = new ArrayList(); - for (Object nmsBlock : nmsBlocks) { - Object nmsBlockData; - try { - nmsBlockData = nmsBlockClass.getMethod("getBlockData").invoke(nmsBlock); - int dataValue = (int) nmsBlockClass.getMethod("toLegacyData", nmsIBlockData).invoke(nmsBlock, - nmsBlockData); - Object nmsItem = nmsItemClass.getConstructor(nmsBlockClass, int.class, int.class).newInstance(nmsBlock, - 1, dataValue); - ItemStack bukkitItem = (ItemStack) craftItemClass.getMethod("asCraftMirror", nmsItemClass).invoke(null, - nmsItem); - items.add(bukkitItem); - } catch (Exception ex) { - ex.printStackTrace(); - ; - } - } - return Arrays.copyOf(items.toArray(), items.size(), ItemStack[].class); - } - - @SuppressWarnings({ "unused", "unchecked" }) - @Override - public void change(Event e, @Nullable Object[] delta, ChangeMode mode) { - Entity ent = entity.getSingle(e); - if (ent == null || !(ent instanceof Enderman)) - return; - Object nmsEnt = null; - try { - nmsEnt = craftEntClass.cast(ent).getClass().getMethod("getHandle").invoke(ent); - } catch (Exception ex) { - ex.printStackTrace(); - } - Set enderBlocks = (Set) ReflectionUtils.getField("c", endermanClass, nmsEnt); - if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.SET) { - ItemStack[] deltaItems = Arrays.copyOf(delta, delta.length, ItemStack[].class); - if (mode == ChangeMode.SET) { - enderBlocks.clear(); - } - for (ItemStack itemStack : deltaItems) { - if (itemStack.getType() == Material.AIR || itemStack == null) - continue; - Object nmsItemStack = CraftItemStack.asNMSCopy(itemStack); - Object nmsItem = null; - try { - nmsItem = nmsItemStack.getClass().getMethod("getItem").invoke(nmsItemStack); - } catch (Exception ex) { - ex.printStackTrace(); - } - if (mode == ChangeMode.ADD || mode == ChangeMode.SET) - enderBlocks.add(nmsItem); - else //ChangeMode.REMOVE - enderBlocks.remove(nmsItem); - } - } else if (mode == ChangeMode.RESET) { - ItemStack grass = new ItemStack(Material.GRASS); - ItemStack dirt = new ItemStack(Material.DIRT); - ItemStack sand = new ItemStack(Material.SAND); - ItemStack gravel = new ItemStack(Material.GRAVEL); - ItemStack dandelion = new ItemStack(Material.YELLOW_FLOWER); - ItemStack poppy = new ItemStack(Material.RED_ROSE); - ItemStack brownShroom = new ItemStack(Material.BROWN_MUSHROOM); - ItemStack redShroom = new ItemStack(Material.RED_MUSHROOM); - ItemStack tnt = new ItemStack(Material.TNT); - ItemStack cactus = new ItemStack(Material.CACTUS); - ItemStack clay = new ItemStack(Material.CLAY); - ItemStack pumpkin = new ItemStack(Material.PUMPKIN); - ItemStack melon = new ItemStack(Material.MELON_BLOCK); - ItemStack mycellium = new ItemStack(Material.MYCEL); - ItemStack[] defaultItems = new ItemStack[] { grass, dirt, gravel, dandelion, poppy, brownShroom, redShroom, tnt, cactus, clay, pumpkin, melon, mycellium }; - enderBlocks.clear(); - for (ItemStack itemStack : defaultItems) { - Object nmsItemStack = CraftItemStack.asNMSCopy(itemStack); - Object nmsItem = null; - try { - nmsItem = nmsItemStack.getClass().getMethod("getItem").invoke(nmsItemStack); - } catch (Exception ex) { - ex.printStackTrace(); - } - enderBlocks.add(nmsItem); - } - } - } - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.RESET|| mode == ChangeMode.SET) { - return CollectionUtils.array(ItemStack[].class); - } - return null; - } -} +package me.TheBukor.SkStuff.expressions; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import javax.annotation.Nullable; + +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; +import org.bukkit.entity.Enderman; +import org.bukkit.entity.Entity; +import org.bukkit.event.Event; +import org.bukkit.inventory.ItemStack; + +import ch.njol.skript.classes.Changer.ChangeMode; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.skript.lang.util.SimpleExpression; +import ch.njol.util.Kleenean; +import ch.njol.util.coll.CollectionUtils; +import me.TheBukor.SkStuff.util.ReflectionUtils; + +public class ExprEndermanBlocks extends SimpleExpression { + private Expression entity; + + private Class nmsBlockClass = ReflectionUtils.getNMSClass("Block"); + private Class endermanClass = ReflectionUtils.getNMSClass("EntityEnderman"); + private Class nmsIBlockData = ReflectionUtils.getNMSClass("IBlockData"); + private Class nmsItemClass = ReflectionUtils.getNMSClass("ItemStack"); + private Class craftEntClass = ReflectionUtils.getOBCClass("entity.CraftEntity"); + private Class craftItemClass = ReflectionUtils.getOBCClass("inventory.CraftItemStack"); + + @Override + public Class getReturnType() { + return ItemStack.class; + } + + @Override + public boolean isSingle() { + return false; + } + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { + entity = (Expression) expr[0]; + return true; + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return "blocks that " + entity.toString(e, debug) + " can carry"; + } + + @SuppressWarnings("unchecked") + @Override + @Nullable + protected ItemStack[] get(Event e) { + Entity ent = entity.getSingle(e); + if (ent == null || !(ent instanceof Enderman)) + return null; + Object nmsEnt = null; + try { + nmsEnt = craftEntClass.cast(ent).getClass().getMethod("getHandle").invoke(ent); + } catch (Exception ex) { + ex.printStackTrace(); + } + Set nmsBlocks = (Set) ReflectionUtils.getField("c", endermanClass, nmsEnt); + List items = new ArrayList(); + for (Object nmsBlock : nmsBlocks) { + Object nmsBlockData; + try { + nmsBlockData = nmsBlockClass.getMethod("getBlockData").invoke(nmsBlock); + int dataValue = (int) nmsBlockClass.getMethod("toLegacyData", nmsIBlockData).invoke(nmsBlock, + nmsBlockData); + Object nmsItem = nmsItemClass.getConstructor(nmsBlockClass, int.class, int.class).newInstance(nmsBlock, + 1, dataValue); + ItemStack bukkitItem = (ItemStack) craftItemClass.getMethod("asCraftMirror", nmsItemClass).invoke(null, + nmsItem); + items.add(bukkitItem); + } catch (Exception ex) { + ex.printStackTrace(); + ; + } + } + return Arrays.copyOf(items.toArray(), items.size(), ItemStack[].class); + } + + @SuppressWarnings({ "unused", "unchecked" }) + @Override + public void change(Event e, @Nullable Object[] delta, ChangeMode mode) { + Entity ent = entity.getSingle(e); + if (ent == null || !(ent instanceof Enderman)) + return; + Object nmsEnt = null; + try { + nmsEnt = craftEntClass.cast(ent).getClass().getMethod("getHandle").invoke(ent); + } catch (Exception ex) { + ex.printStackTrace(); + } + Set enderBlocks = (Set) ReflectionUtils.getField("c", endermanClass, nmsEnt); + if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.SET) { + ItemStack[] deltaItems = Arrays.copyOf(delta, delta.length, ItemStack[].class); + if (mode == ChangeMode.SET) { + enderBlocks.clear(); + } + for (ItemStack itemStack : deltaItems) { + if (itemStack.getType() == Material.AIR || itemStack == null) + continue; + Object nmsItemStack = CraftItemStack.asNMSCopy(itemStack); + Object nmsItem = null; + try { + nmsItem = nmsItemStack.getClass().getMethod("getItem").invoke(nmsItemStack); + } catch (Exception ex) { + ex.printStackTrace(); + } + if (mode == ChangeMode.ADD || mode == ChangeMode.SET) + enderBlocks.add(nmsItem); + else //ChangeMode.REMOVE + enderBlocks.remove(nmsItem); + } + } else if (mode == ChangeMode.RESET) { + ItemStack grass = new ItemStack(Material.GRASS); + ItemStack dirt = new ItemStack(Material.DIRT); + ItemStack sand = new ItemStack(Material.SAND); + ItemStack gravel = new ItemStack(Material.GRAVEL); + ItemStack dandelion = new ItemStack(Material.YELLOW_FLOWER); + ItemStack poppy = new ItemStack(Material.RED_ROSE); + ItemStack brownShroom = new ItemStack(Material.BROWN_MUSHROOM); + ItemStack redShroom = new ItemStack(Material.RED_MUSHROOM); + ItemStack tnt = new ItemStack(Material.TNT); + ItemStack cactus = new ItemStack(Material.CACTUS); + ItemStack clay = new ItemStack(Material.CLAY); + ItemStack pumpkin = new ItemStack(Material.PUMPKIN); + ItemStack melon = new ItemStack(Material.MELON_BLOCK); + ItemStack mycellium = new ItemStack(Material.MYCEL); + ItemStack[] defaultItems = new ItemStack[] { grass, dirt, gravel, dandelion, poppy, brownShroom, redShroom, tnt, cactus, clay, pumpkin, melon, mycellium }; + enderBlocks.clear(); + for (ItemStack itemStack : defaultItems) { + Object nmsItemStack = CraftItemStack.asNMSCopy(itemStack); + Object nmsItem = null; + try { + nmsItem = nmsItemStack.getClass().getMethod("getItem").invoke(nmsItemStack); + } catch (Exception ex) { + ex.printStackTrace(); + } + enderBlocks.add(nmsItem); + } + } + } + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.RESET|| mode == ChangeMode.SET) { + return CollectionUtils.array(ItemStack[].class); + } + return null; + } +} diff --git a/src/me/TheBukor/SkStuff/expressions/ExprFileNBT.java b/src/me/TheBukor/SkStuff/expressions/ExprFileNBT.java index 63995b5..08d7de4 100644 --- a/src/me/TheBukor/SkStuff/expressions/ExprFileNBT.java +++ b/src/me/TheBukor/SkStuff/expressions/ExprFileNBT.java @@ -1,85 +1,86 @@ -package me.TheBukor.SkStuff.expressions; - -import java.io.File; - -import javax.annotation.Nullable; - -import org.bukkit.event.Event; - -import ch.njol.skript.classes.Changer.ChangeMode; -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.lang.util.SimpleExpression; -import ch.njol.util.Kleenean; -import ch.njol.util.coll.CollectionUtils; -import me.TheBukor.SkStuff.SkStuff; -import me.TheBukor.SkStuff.util.ReflectionUtils; - -public class ExprFileNBT extends SimpleExpression { - private Expression input; - - private Class nbtClass = ReflectionUtils.getNMSClass("NBTTagCompound", false); - - @Override - public Class getReturnType() { - return nbtClass; - } - - @Override - public boolean isSingle() { - return true; - } - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult arg3) { - input = (Expression) expr[0]; - return true; - } - - @Override - public String toString(@Nullable Event e, boolean debug) { - return "the NBT from file " + input.toString(e, debug); - } - - @Override - @Nullable - public Object[] get(Event e) { - String fileName = input.getSingle(e); - fileName = !fileName.endsWith(".dat") ? fileName + ".dat" : fileName; - File file = new File(fileName); - if (!file.exists()) - return null; - return new Object[] { SkStuff.getNMSMethods().getFileNBT(file) }; - } - - @Override - public void change(Event e, @Nullable Object[] delta, ChangeMode mode) { - String fileName = input.getSingle(e); - fileName = !fileName.endsWith(".dat") ? fileName + ".dat" : fileName; - File file = new File(fileName); - if (!file.exists()) - return; - Object fileNBT = SkStuff.getNMSMethods().getFileNBT(file); - if (mode == ChangeMode.ADD) { - Object parsedNBT = SkStuff.getNMSMethods().parseRawNBT((String) delta[0]); - SkStuff.getNMSMethods().addToCompound(fileNBT, parsedNBT); - SkStuff.getNMSMethods().setFileNBT(file, fileNBT); - } else if (mode == ChangeMode.REMOVE) { - for (Object s : delta) { - SkStuff.getNMSMethods().removeFromCompound(fileNBT, (String) s); - } - SkStuff.getNMSMethods().setFileNBT(file, fileNBT); - } - } - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE) { - return CollectionUtils.array(String[].class); - } - return null; - } +package me.TheBukor.SkStuff.expressions; + +import java.io.File; + +import javax.annotation.Nullable; + +import org.bukkit.event.Event; + +import ch.njol.skript.classes.Changer.ChangeMode; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.skript.lang.util.SimpleExpression; +import ch.njol.util.Kleenean; +import ch.njol.util.coll.CollectionUtils; +import me.TheBukor.SkStuff.SkStuff; +import me.TheBukor.SkStuff.util.ReflectionUtils; + +public class ExprFileNBT extends SimpleExpression { + private Expression input; + + private Class nbtClass = ReflectionUtils.getNMSClass("NBTTagCompound"); + + @Override + public Class getReturnType() { + return nbtClass; + } + + @Override + public boolean isSingle() { + return true; + } + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult arg3) { + input = (Expression) expr[0]; + return true; + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return "the NBT from file " + input.toString(e, debug); + } + + @Override + @Nullable + public Object[] get(Event e) { + String fileName = input.getSingle(e); + fileName = !fileName.endsWith(".dat") ? fileName + ".dat" : fileName; + File file = new File(fileName); + if (!file.exists()) + return null; + return new Object[] { SkStuff.getNMSMethods().getFileNBT(file) }; + } + + @Override + public void change(Event e, @Nullable Object[] delta, ChangeMode mode) { + String fileName = input.getSingle(e); + fileName = !fileName.endsWith(".dat") ? fileName + ".dat" : fileName; + File file = new File(fileName); + if (!file.exists()) + return; + Object fileNBT = SkStuff.getNMSMethods().getFileNBT(file); + if (mode == ChangeMode.ADD) { + Object parsedNBT = null; + parsedNBT = SkStuff.getNMSMethods().parseRawNBT((String) delta[0]); + SkStuff.getNMSMethods().addToCompound(fileNBT, parsedNBT); + SkStuff.getNMSMethods().setFileNBT(file, fileNBT); + } else if (mode == ChangeMode.REMOVE) { + for (Object s : delta) { + SkStuff.getNMSMethods().removeFromCompound(fileNBT, (String) s); + } + SkStuff.getNMSMethods().setFileNBT(file, fileNBT); + } + } + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE) { + return CollectionUtils.array(String[].class); + } + return null; + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/expressions/ExprItemNBT.java b/src/me/TheBukor/SkStuff/expressions/ExprItemNBT.java index 703f143..cd525d5 100644 --- a/src/me/TheBukor/SkStuff/expressions/ExprItemNBT.java +++ b/src/me/TheBukor/SkStuff/expressions/ExprItemNBT.java @@ -1,55 +1,56 @@ -package me.TheBukor.SkStuff.expressions; - -import javax.annotation.Nullable; - -import org.bukkit.Material; -import org.bukkit.event.Event; -import org.bukkit.inventory.ItemStack; - -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.lang.util.SimpleExpression; -import ch.njol.util.Kleenean; -import me.TheBukor.SkStuff.SkStuff; - -public class ExprItemNBT extends SimpleExpression { - private Expression itemStack; - private Expression string; - - - @Override - public Class getReturnType() { - return ItemStack.class; - } - - @Override - public boolean isSingle() { - return true; - } - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult arg3) { - itemStack = (Expression) expr[0]; - string = (Expression) expr[1]; - return true; - } - - @Override - public String toString(@Nullable Event e, boolean debug) { - return itemStack.toString(e, debug) + " with custom NBT " + string.toString(e, debug); - } - - @Override - @Nullable - public ItemStack[] get(Event e) { - ItemStack item = itemStack.getSingle(e); - String newTags = string.getSingle(e); - if (item.getType() == Material.AIR || item == null) { - return null; - } - Object parsedNBT = SkStuff.getNMSMethods().parseRawNBT(newTags); - ItemStack newItem = SkStuff.getNMSMethods().getItemWithNBT(item, parsedNBT); - return new ItemStack[] { newItem }; - } +package me.TheBukor.SkStuff.expressions; + +import javax.annotation.Nullable; + +import org.bukkit.Material; +import org.bukkit.event.Event; +import org.bukkit.inventory.ItemStack; + +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.skript.lang.util.SimpleExpression; +import ch.njol.util.Kleenean; +import me.TheBukor.SkStuff.SkStuff; + +public class ExprItemNBT extends SimpleExpression { + private Expression itemStack; + private Expression string; + + + @Override + public Class getReturnType() { + return ItemStack.class; + } + + @Override + public boolean isSingle() { + return true; + } + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult arg3) { + itemStack = (Expression) expr[0]; + string = (Expression) expr[1]; + return true; + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return itemStack.toString(e, debug) + " with custom NBT " + string.toString(e, debug); + } + + @Override + @Nullable + public ItemStack[] get(Event e) { + ItemStack item = itemStack.getSingle(e); + String newTags = string.getSingle(e); + if (item.getType() == Material.AIR || item == null) { + return null; + } + Object parsedNBT = null; + parsedNBT = SkStuff.getNMSMethods().parseRawNBT(newTags); + ItemStack newItem = SkStuff.getNMSMethods().getItemWithNBT(item, parsedNBT); + return new ItemStack[] { newItem }; + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/expressions/ExprNBTListContents.java b/src/me/TheBukor/SkStuff/expressions/ExprNBTListContents.java index 356b82a..8fed9a5 100644 --- a/src/me/TheBukor/SkStuff/expressions/ExprNBTListContents.java +++ b/src/me/TheBukor/SkStuff/expressions/ExprNBTListContents.java @@ -1,77 +1,69 @@ -package me.TheBukor.SkStuff.expressions; - -import javax.annotation.Nullable; - -import org.bukkit.event.Event; - -//import ch.njol.skript.classes.Changer.ChangeMode; -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.lang.util.SimpleExpression; -import ch.njol.util.Kleenean; -//import ch.njol.util.coll.CollectionUtils; -import me.TheBukor.SkStuff.SkStuff; -//import me.TheBukor.SkStuff.util.ReflectionUtils; - -public class ExprNBTListContents extends SimpleExpression { - private Expression nbtList; - - //private Class nbtListClass = ReflectionUtils.getNMSClass("NBTTagList", false); - //private Class nbtClass = ReflectionUtils.getNMSClass("NBTTagCompound", false); - - @Override - public Class getReturnType() { - return Object.class; - } - - @Override - public boolean isSingle() { - return false; - } - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { - nbtList = (Expression) expr[0]; - return false; - } - - @Override - public String toString(@Nullable Event e, boolean debug) { - return "contents from NBT list " + nbtList.toString(e, debug); - } - - @Override - @Nullable - protected Object[] get(Event e) { - Object list = nbtList.getSingle(e); - SkStuff.getNMSMethods().getContents(list); - return null; - } - - /* - @Override - public void change(Event e, @Nullable Object[] delta, ChangeMode mode) { - Object list = nbtList.getSingle(e); - if (mode == ChangeMode.ADD) { - if (!(delta[0] instanceof Number || delta[0] instanceof String || nbtListClass.isAssignableFrom(delta[0].getClass()) || nbtClass.isAssignableFrom(delta[0].getClass()))) - return; //NBT can only store numbers, strings, lists or compounds. - SkStuff.getNMSMethods().addToList(list, delta[0]); - } else if (mode == ChangeMode.REMOVE) { - // TODO A method to remove a specific object from a NBT List - } else if (mode == ChangeMode.REMOVE_ALL) { - // TODO A method to remove all objects of some type from a NBT List - } - } - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.REMOVE_ALL) { - return CollectionUtils.array(Object.class); - } - return null; - } - */ -} +package me.TheBukor.SkStuff.expressions; + +import javax.annotation.Nullable; + +import org.bukkit.event.Event; + +import ch.njol.skript.classes.Changer.ChangeMode; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.skript.lang.util.SimpleExpression; +import ch.njol.util.Kleenean; +import ch.njol.util.coll.CollectionUtils; +import me.TheBukor.SkStuff.SkStuff; +import me.TheBukor.SkStuff.util.ReflectionUtils; + +public class ExprNBTListContents extends SimpleExpression { + private Expression nbtList; + + private Class nbtBaseClass = ReflectionUtils.getNMSClass("NBTBase"); + + @Override + public Class getReturnType() { + return Object.class; + } + + @Override + public boolean isSingle() { + return false; + } + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { + nbtList = (Expression) expr[0]; + return true; + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return "contents from NBT list " + nbtList.toString(e, debug); + } + + @Override + @Nullable + protected Object[] get(Event e) { + Object list = nbtList.getSingle(e); + return SkStuff.getNMSMethods().getContents(list); + } + + @Override + public void change(Event e, @Nullable Object[] delta, ChangeMode mode) { + Object list = nbtList.getSingle(e); + if (mode == ChangeMode.ADD) { + if (!(delta[0] instanceof Number || delta[0] instanceof String || nbtBaseClass.isAssignableFrom(delta[0].getClass()))) + return; //NBT can only store numbers, strings, lists or compounds. + SkStuff.getNMSMethods().addToList(list, delta[0]); + } + } + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.REMOVE_ALL) { + return CollectionUtils.array(Object.class); + } + return null; + } +} diff --git a/src/me/TheBukor/SkStuff/expressions/ExprNBTListIndex.java b/src/me/TheBukor/SkStuff/expressions/ExprNBTListIndex.java index 1e12618..7cf4395 100644 --- a/src/me/TheBukor/SkStuff/expressions/ExprNBTListIndex.java +++ b/src/me/TheBukor/SkStuff/expressions/ExprNBTListIndex.java @@ -1,77 +1,76 @@ -package me.TheBukor.SkStuff.expressions; - -import javax.annotation.Nullable; - -import org.bukkit.event.Event; - -import ch.njol.skript.classes.Changer.ChangeMode; -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.lang.util.SimpleExpression; -import ch.njol.util.Kleenean; -import ch.njol.util.coll.CollectionUtils; -import me.TheBukor.SkStuff.SkStuff; -import me.TheBukor.SkStuff.util.ReflectionUtils; - -public class ExprNBTListIndex extends SimpleExpression { - private Expression nbtList; - private Expression index; - - private Class nbtBaseClass = ReflectionUtils.getNMSClass("NBTBase", false); - - @Override - public Class getReturnType() { - return Object.class; - } - - @Override - public boolean isSingle() { - return false; - } - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { - nbtList = (Expression) expr[0]; - index = (Expression) expr[1]; - return false; - } - - @Override - public String toString(@Nullable Event e, boolean debug) { - return "NBT list" + nbtList.toString(e, debug) + " index " + index.toString(e, debug); - } - - @Override - @Nullable - protected Object[] get(Event e) { - int i = index.getSingle(e).intValue(); - Object list = nbtList.getSingle(e); - SkStuff.getNMSMethods().getIndex(list, i); - return null; - } - - @Override - public void change(Event e, @Nullable Object[] delta, ChangeMode mode) { - int i = index.getSingle(e).intValue(); - Object list = nbtList.getSingle(e); - if (mode == ChangeMode.SET) { - if (!(delta[0] instanceof Number || delta[0] instanceof String || nbtBaseClass.isAssignableFrom(delta[0].getClass()))) - //All NBTTags extends NBTBase, so it will check if delta[0] is instance of NBTTagList or NBTTagCompound, because these are the only NBTTagX classes registered in this addon. - return; //NBT can only store numbers, strings, lists or compounds. - SkStuff.getNMSMethods().setIndex(list, i, delta[0]); - } else if (mode == ChangeMode.DELETE) { - SkStuff.getNMSMethods().removeFromList(list, i); - } - } - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.SET || mode == ChangeMode.DELETE) { - return CollectionUtils.array(Object.class); - } - return null; - } -} +package me.TheBukor.SkStuff.expressions; + +import javax.annotation.Nullable; + +import org.bukkit.event.Event; + +import ch.njol.skript.classes.Changer.ChangeMode; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.skript.lang.util.SimpleExpression; +import ch.njol.util.Kleenean; +import ch.njol.util.coll.CollectionUtils; +import me.TheBukor.SkStuff.SkStuff; +import me.TheBukor.SkStuff.util.ReflectionUtils; + +public class ExprNBTListIndex extends SimpleExpression { + private Expression nbtList; + private Expression index; + + private Class nbtBaseClass = ReflectionUtils.getNMSClass("NBTBase"); + + @Override + public Class getReturnType() { + return Object.class; + } + + @Override + public boolean isSingle() { + return false; + } + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { + nbtList = (Expression) expr[0]; + index = (Expression) expr[1]; + return true; + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return "NBT list" + nbtList.toString(e, debug) + " index " + index.toString(e, debug); + } + + @Override + @Nullable + protected Object[] get(Event e) { + int i = index.getSingle(e).intValue(); + Object list = nbtList.getSingle(e); + return new Object[] { SkStuff.getNMSMethods().getIndex(list, i) }; + } + + @Override + public void change(Event e, @Nullable Object[] delta, ChangeMode mode) { + int i = index.getSingle(e).intValue(); + Object list = nbtList.getSingle(e); + if (mode == ChangeMode.SET) { + if (!(delta[0] instanceof Number || delta[0] instanceof String || nbtBaseClass.isAssignableFrom(delta[0].getClass()))) + //All NBTTags extends NBTBase, so it will check if delta[0] is instance of NBTTagList or NBTTagCompound, because these are the only NBTTagX classes registered in this addon. + return; //NBT can only store numbers, strings, lists or compounds. + SkStuff.getNMSMethods().setIndex(list, i, delta[0]); + } else if (mode == ChangeMode.DELETE) { + SkStuff.getNMSMethods().removeFromList(list, i); + } + } + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.SET || mode == ChangeMode.DELETE) { + return CollectionUtils.array(Object.class); + } + return null; + } +} diff --git a/src/me/TheBukor/SkStuff/expressions/ExprNBTOf.java b/src/me/TheBukor/SkStuff/expressions/ExprNBTOf.java index 7ba8810..0a8e353 100644 --- a/src/me/TheBukor/SkStuff/expressions/ExprNBTOf.java +++ b/src/me/TheBukor/SkStuff/expressions/ExprNBTOf.java @@ -1,145 +1,156 @@ -package me.TheBukor.SkStuff.expressions; - -import java.util.Arrays; - -import javax.annotation.Nullable; - -import org.bukkit.Bukkit; -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.event.Event; -import org.bukkit.inventory.ItemStack; - -import ch.njol.skript.ScriptLoader; -import ch.njol.skript.Skript; -import ch.njol.skript.classes.Changer.ChangeMode; -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.lang.util.SimpleExpression; -import ch.njol.skript.log.ErrorQuality; -import ch.njol.skript.util.Slot; -import ch.njol.util.Kleenean; -import ch.njol.util.coll.CollectionUtils; -import me.TheBukor.SkStuff.SkStuff; -import me.TheBukor.SkStuff.util.ReflectionUtils; - -public class ExprNBTOf extends SimpleExpression { - private Expression target; - - private Class nbtClass = ReflectionUtils.getNMSClass("NBTTagCompound", false); - - @Override - public Class getReturnType() { - return nbtClass; - } - - @Override - public boolean isSingle() { - return true; - } - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { - target = (Expression) expr[0]; - Class type = target.getReturnType(); - Class[] evts = ScriptLoader.getCurrentEvents(); - for (int i = 0; i < evts.length; i++) { - Bukkit.broadcastMessage("Event #" + i + ": \u00A7b" + evts[i].getSimpleName()); - } - Bukkit.broadcastMessage("Object type: \u00A79" + type.getSimpleName()); - if (type != Entity.class || type != Block.class || type != ItemStack.class || type != Slot.class) { - Skript.error(target.toString() + " is neither an entity, a block nor an itemstack.", ErrorQuality.SEMANTIC_ERROR); - } - return true; - } - - @Override - public String toString(@Nullable Event e, boolean debug) { - return "the NBT of " + target.toString(e, debug); - } - - @Override - @Nullable - public Object[] get(Event e) { - Object tar = target.getSingle(e); - if (tar instanceof Entity) { - return new Object[] { SkStuff.getNMSMethods().getEntityNBT((Entity) tar) }; - } else if (tar instanceof Block) { - return new Object[] { SkStuff.getNMSMethods().getTileNBT((Block) tar) }; - } else if (tar instanceof ItemStack) { - return new Object[] { SkStuff.getNMSMethods().getItemNBT((ItemStack) tar) }; - } - return null; - } - - @Override - public void change(Event e, Object[] delta, ChangeMode mode) { - Object tar = target.getSingle(e); - if (tar instanceof Entity) { - Object entNBT = SkStuff.getNMSMethods().getEntityNBT((Entity) tar); - if (mode == ChangeMode.ADD) { - Object parsedNBT = SkStuff.getNMSMethods().parseRawNBT((String) delta[0]); - SkStuff.getNMSMethods().removeFromCompound(parsedNBT, "UUIDMost", "UUIDLeast", "WorldUUDMost", "WorldUUIDLeast", "Bukkit.updateLevel"); - SkStuff.getNMSMethods().addToCompound(entNBT, parsedNBT); - SkStuff.getNMSMethods().setEntityNBT((Entity) tar, entNBT); - } else if (mode == ChangeMode.REMOVE) { - for (Object s : delta) { - if (s != "UUIDMost" || s != "UUIDLeast" || s != "WorldUUIDMost" || s != "WorldUUIDLeast" || s != "Bukkit.updateLevel") { // Prevent crucial data from being modified - SkStuff.getNMSMethods().removeFromCompound(entNBT, (String) s); - } - } - SkStuff.getNMSMethods().setEntityNBT((Entity) tar, entNBT); - } - } else if (tar instanceof Block) { - Object blockNBT = SkStuff.getNMSMethods().getTileNBT((Block) tar); - if (mode == ChangeMode.ADD) { - Object parsedNBT = SkStuff.getNMSMethods().parseRawNBT((String) delta[0]); - SkStuff.getNMSMethods().removeFromCompound(parsedNBT, "x", "y", "z", "id"); - SkStuff.getNMSMethods().addToCompound(blockNBT, parsedNBT); - SkStuff.getNMSMethods().setTileNBT((Block) tar, blockNBT); - } else if (mode == ChangeMode.REMOVE) { - for (Object s : delta) { - if (s != "x" || s != "y" || s != "z" || s != "id") { - SkStuff.getNMSMethods().removeFromCompound(blockNBT, (String) s); - } - } - SkStuff.getNMSMethods().setTileNBT((Block) tar, blockNBT); - } - } else if (tar instanceof ItemStack) { - Object itemNBT = SkStuff.getNMSMethods().getItemNBT((ItemStack) tar); - if (mode == ChangeMode.ADD) { - Object parsedNBT = SkStuff.getNMSMethods().parseRawNBT((String) delta[0]); - SkStuff.getNMSMethods().addToCompound(itemNBT, parsedNBT); - ItemStack newItem = SkStuff.getNMSMethods().getItemWithNBT((ItemStack) tar, itemNBT); - Object slot = target.getSource().getSingle(e); - if (slot instanceof Slot) { - ((Slot) slot).setItem(newItem); - } - } else if (mode == ChangeMode.REMOVE) { - String[] toRemove = Arrays.copyOf(delta, delta.length, String[].class); - SkStuff.getNMSMethods().removeFromCompound(itemNBT, toRemove); - ItemStack newItem = SkStuff.getNMSMethods().getItemWithNBT((ItemStack) tar, itemNBT); - Object slot = target.getSource().getSingle(e); - if (slot instanceof Slot) { - ((Slot) slot).setItem(newItem); - } - } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { - ItemStack newItem = SkStuff.getNMSMethods().getItemWithNBT((ItemStack) tar, null); - Object slot = target.getSource().getSingle(e); - if (slot instanceof Slot) { - ((Slot) slot).setItem(newItem); - } - } - } - } - - @SuppressWarnings("unchecked") - @Override - public Class[] acceptChange(final ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { - return CollectionUtils.array(String[].class); - } - return null; - } +package me.TheBukor.SkStuff.expressions; + +import java.util.Arrays; + +import javax.annotation.Nullable; + +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.event.Event; +import org.bukkit.inventory.ItemStack; + +import ch.njol.skript.Skript; +import ch.njol.skript.classes.Changer.ChangeMode; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.skript.lang.util.SimpleExpression; +import ch.njol.skript.log.ErrorQuality; +import ch.njol.skript.util.Slot; +import ch.njol.util.Kleenean; +import ch.njol.util.coll.CollectionUtils; +import me.TheBukor.SkStuff.SkStuff; +import me.TheBukor.SkStuff.util.ReflectionUtils; + +public class ExprNBTOf extends SimpleExpression { + private Expression target; + + private Class nbtClass = ReflectionUtils.getNMSClass("NBTTagCompound"); + + @Override + public Class getReturnType() { + return nbtClass; + } + + @Override + public boolean isSingle() { + return true; + } + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int matchedPattern, Kleenean arg2, ParseResult result) { + target = (Expression) expr[0]; + Class type = target.getReturnType(); + if (type != Entity.class || type != Block.class || type != ItemStack.class || type != Slot.class) { + Skript.error(target.toString() + " is neither an entity, a block nor an itemstack.", ErrorQuality.SEMANTIC_ERROR); + } + return true; + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return "the NBT of " + target.toString(e, debug); + } + + @Override + @Nullable + public Object[] get(Event e) { + Object tar = target.getSingle(e); + if (tar instanceof Entity) { + return new Object[] { SkStuff.getNMSMethods().getEntityNBT((Entity) tar) }; + } else if (tar instanceof Block) { + return new Object[] { SkStuff.getNMSMethods().getTileNBT((Block) tar) }; + } else if (tar instanceof ItemStack) { + return new Object[] { SkStuff.getNMSMethods().getItemNBT((ItemStack) tar) }; + } else if (tar instanceof Slot) { + return new Object[] { SkStuff.getNMSMethods().getItemNBT(((Slot) tar).getItem()) }; + } + return null; + } + + @Override + public void change(Event e, Object[] delta, ChangeMode mode) { + Object tar = target.getSingle(e); + Object parsedNBT = null; + if (delta != null) { + parsedNBT = SkStuff.getNMSMethods().parseRawNBT((String) delta[0]); + } + if (tar instanceof Entity) { + Object entNBT = SkStuff.getNMSMethods().getEntityNBT((Entity) tar); + if (mode == ChangeMode.ADD) { + SkStuff.getNMSMethods().removeFromCompound(parsedNBT, "UUIDMost", "UUIDLeast", "WorldUUDMost", "WorldUUIDLeast", "Bukkit.updateLevel"); + SkStuff.getNMSMethods().addToCompound(entNBT, parsedNBT); + SkStuff.getNMSMethods().setEntityNBT((Entity) tar, entNBT); + } else if (mode == ChangeMode.REMOVE) { + for (Object s : delta) { + if (s != "UUIDMost" || s != "UUIDLeast" || s != "WorldUUIDMost" || s != "WorldUUIDLeast" || s != "Bukkit.updateLevel") { // Prevent crucial data from being modified + SkStuff.getNMSMethods().removeFromCompound(entNBT, (String) s); + } + } + SkStuff.getNMSMethods().setEntityNBT((Entity) tar, entNBT); + } + } else if (tar instanceof Block) { + Object blockNBT = SkStuff.getNMSMethods().getTileNBT((Block) tar); + if (mode == ChangeMode.ADD) { + SkStuff.getNMSMethods().removeFromCompound(parsedNBT, "x", "y", "z", "id"); + SkStuff.getNMSMethods().addToCompound(blockNBT, parsedNBT); + SkStuff.getNMSMethods().setTileNBT((Block) tar, blockNBT); + } else if (mode == ChangeMode.REMOVE) { + for (Object s : delta) { + if (s != "x" || s != "y" || s != "z" || s != "id") { + SkStuff.getNMSMethods().removeFromCompound(blockNBT, (String) s); + } + } + SkStuff.getNMSMethods().setTileNBT((Block) tar, blockNBT); + } + } else if (tar instanceof ItemStack) { + Object itemNBT = SkStuff.getNMSMethods().getItemNBT((ItemStack) tar); + if (mode == ChangeMode.ADD) { + SkStuff.getNMSMethods().addToCompound(itemNBT, parsedNBT); + ItemStack newItem = SkStuff.getNMSMethods().getItemWithNBT((ItemStack) tar, itemNBT); + Object slot = target.getSource().getSingle(e); + if (slot instanceof Slot) { + ((Slot) slot).setItem(newItem); + } + } else if (mode == ChangeMode.REMOVE) { + String[] toRemove = Arrays.copyOf(delta, delta.length, String[].class); + SkStuff.getNMSMethods().removeFromCompound(itemNBT, toRemove); + ItemStack newItem = SkStuff.getNMSMethods().getItemWithNBT((ItemStack) tar, itemNBT); + Object slot = target.getSource().getSingle(e); + if (slot instanceof Slot) { + ((Slot) slot).setItem(newItem); + } + } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + ItemStack newItem = SkStuff.getNMSMethods().getItemWithNBT((ItemStack) tar, null); + Object slot = target.getSource().getSingle(e); + if (slot instanceof Slot) { + ((Slot) slot).setItem(newItem); + } + } + } else if (tar instanceof Slot) { + Object itemNBT = SkStuff.getNMSMethods().getItemNBT(((Slot) tar).getItem()); + if (mode == ChangeMode.ADD) { + SkStuff.getNMSMethods().addToCompound(itemNBT, parsedNBT); + ItemStack newItem = SkStuff.getNMSMethods().getItemWithNBT((ItemStack) tar, itemNBT); + ((Slot) tar).setItem(newItem); + } else if (mode == ChangeMode.REMOVE) { + String[] toRemove = Arrays.copyOf(delta, delta.length, String[].class); + SkStuff.getNMSMethods().removeFromCompound(itemNBT, toRemove); + ItemStack newItem = SkStuff.getNMSMethods().getItemWithNBT((ItemStack) tar, itemNBT); + ((Slot) tar).setItem(newItem); + } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + ItemStack newItem = SkStuff.getNMSMethods().getItemWithNBT((ItemStack) tar, null); + ((Slot) tar).setItem(newItem); + } + } + } + + @SuppressWarnings("unchecked") + @Override + public Class[] acceptChange(final ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + return CollectionUtils.array(String[].class); + } + return null; + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/expressions/ExprTagOf.java b/src/me/TheBukor/SkStuff/expressions/ExprTagOf.java index a0d2534..ff4a985 100644 --- a/src/me/TheBukor/SkStuff/expressions/ExprTagOf.java +++ b/src/me/TheBukor/SkStuff/expressions/ExprTagOf.java @@ -1,194 +1,194 @@ -package me.TheBukor.SkStuff.expressions; - -import javax.annotation.Nullable; - -import org.bukkit.event.Event; - -import ch.njol.skript.classes.Changer.ChangeMode; -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.lang.util.SimpleExpression; -import ch.njol.util.Kleenean; -import ch.njol.util.coll.CollectionUtils; -import me.TheBukor.SkStuff.util.ReflectionUtils; - -public class ExprTagOf extends SimpleExpression { - private Expression string; - private Expression compound; - - private Class nbtClass = ReflectionUtils.getNMSClass("NBTTagCompound", false); - private Class nbtBaseClass = ReflectionUtils.getNMSClass("NBTBase", false); - - @Override - public Class getReturnType() { - return Object.class; - } - @Override - public boolean isSingle() { - return true; - } - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] expr, int arg1, Kleenean arg2, ParseResult arg3) { - string = (Expression) expr[0]; - compound = (Expression) expr[1]; - return true; - } - @Override - public String toString(@Nullable Event e, boolean debug) { - return "the tag " + string.toString(e, debug) + " of compound"; - } - - @Override - @Nullable - protected Object[] get(Event e) { - Object NBT = compound.getSingle(e); - if (NBT == null || NBT.toString().equals("{}")) return null; //The NBT can be empty/inexistant for items ("{}" is an empty compound). - String stringTag = string.getSingle(e); - Object tag = null; - try { - tag = nbtClass.getMethod("get", String.class).invoke(NBT, stringTag); - } catch (Exception ex) { - ex.printStackTrace(); - } - if (tag == null) - return null; //The tag doesn't exist? Return . - Byte id = null; - try { - id = (Byte) tag.getClass().getMethod("getTypeId").invoke(tag); - } catch (Exception ex) { - ex.printStackTrace(); - } - try { - switch (id) { - case 1: - return new Byte[] { Byte.valueOf(nbtClass.getMethod("getByte", String.class).invoke(NBT, stringTag).toString()) }; - case 2: - return new Short[] { Short.valueOf(nbtClass.getMethod("getShort", String.class).invoke(NBT, stringTag).toString()) }; - case 3: - return new Integer[] { Integer.valueOf(nbtClass.getMethod("getInt", String.class).invoke(NBT, stringTag).toString()) }; - case 4: - return new Long[] { Long.valueOf(nbtClass.getMethod("getLong", String.class).invoke(NBT, stringTag).toString()) }; - case 5: - return new Float[] { Float.valueOf(nbtClass.getMethod("getFloat", String.class).invoke(NBT, stringTag).toString()) }; - case 6: - return new Double[] { Double.valueOf(nbtClass.getMethod("getDouble", String.class).invoke(NBT, stringTag).toString()) }; - case 7: //Byte array, only used in chunk files. Also doesn't have support for the MojangsonParser. - break; - case 8: - return new String[] { nbtClass.getMethod("getString", String.class).invoke(NBT, stringTag).toString() }; - case 9: - int i; - Object[] list = new Object[] { new Object() }; - for (i = 1; i <= 11; i++) { //To get a list I need to know the type of the tags it contains inside, - //since I can't predict what type the list will have, I just loop all of the IDs until I find a non-empty list. - list[0] = nbtClass.getMethod("getList", String.class, int.class).invoke(NBT, stringTag, i); //Try to get the list with the ID "loop-number". - if (!list[0].toString().equals("[]")) { //If list is not empty. - break; //Stop loop. - } - } - return list; - /* - REMOVED TEMPORARILY, HOPEFULLY THE NEW IMPLEMENTATION SHOULD WORK BETTER - int i; - Object list = null; - for (i = 1; i <= 11; i++) { //To get a list I need to know the type of the tags it contains inside, - //since I can't predict what type the list will have, I just loop all of the IDs until I find a non-empty list. - list = nbtClass.getMethod("getList", String.class, int.class).invoke(NBT, stringTag, i); //Try to get the list with the ID "loop-number". - if (!list.toString().equals("[]")) { //If list is not empty. - break; //Stop loop. - } - } - String methodName = null; - switch (NBTUtil.getContentsId(list)) { - case 5: //Float - methodName = "e"; //list.e(int) = get float from the specified index. - break; - case 6: //Double - methodName = "d"; //list.d(int) = get double from the specified index. - break; - case 8: //String - methodName = "getString"; //Self-explanatory, I guess. - break; - case 10: //Compound - methodName = "get"; //list.get(int) = get compound at the specified index. - break; - case 11: //Integer array - methodName = "c"; //Not sure if ever used, but meh. - break; - default: - break; - } - int listSize = (int) list.getClass().getMethod("size").invoke(list); - Object[] tags = new Object[listSize]; - for (i = 0; i < listSize; i++) { - Object gottenTag = list.getClass().getMethod(methodName, int.class).invoke(list, i); - tags[i] = gottenTag; - } - return tags; - */ - case 10: - return new Object[] { nbtClass.getMethod("getCompound", String.class).invoke(NBT, stringTag) }; - case 11: //Integer array, this one is only used on the chunk files (and maybe schematic files?). - return new Object[] { nbtClass.getMethod("getIntArray", String.class).invoke(NBT, stringTag).toString() }; - default: //This shouldn't happen, but it's better to have this just in case it spills errors everywhere. - break; - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - @Override - public void change(Event e, @Nullable Object[] delta, ChangeMode mode) { - Object NBT = compound.getSingle(e); - if (NBT == null) - try { - NBT = nbtClass.newInstance(); //If the NBT isn't set, create an empty one - } catch (Exception ex) { - ex.printStackTrace(); - } - String stringTag = string.getSingle(e); - if (mode == ChangeMode.SET) { - Object newValue = delta[0]; - try { - if (newValue instanceof Byte) { - nbtClass.getMethod("setByte", String.class, byte.class).invoke(NBT, stringTag, ((Byte) newValue).byteValue()); - } else if (newValue instanceof Short) { - nbtClass.getMethod("setShort", String.class, short.class).invoke(NBT, stringTag, ((Short) newValue).shortValue()); - } else if (newValue instanceof Integer) { - nbtClass.getMethod("setInt", String.class, int.class).invoke(NBT, stringTag, ((Integer) newValue).intValue()); - } else if (newValue instanceof Long) { - nbtClass.getMethod("setLong", String.class, long.class).invoke(NBT, stringTag, ((Long) newValue).longValue()); - } else if (newValue instanceof Float) { - nbtClass.getMethod("setFloat", String.class, float.class).invoke(NBT, stringTag, ((Float) newValue).floatValue()); - } else if (newValue instanceof Double) { - nbtClass.getMethod("setDouble", String.class, double.class).invoke(NBT, stringTag, ((Double) newValue).doubleValue()); - } else if (newValue instanceof String) { - nbtClass.getMethod("setString", String.class, String.class).invoke(NBT, stringTag, String.valueOf(newValue)); - } else { - return; //Something else like a list or entire compound. - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } else if (mode == ChangeMode.RESET || mode == ChangeMode.DELETE) { - try { - nbtClass.getMethod("set", String.class, nbtBaseClass).invoke(NBT, stringTag, nbtBaseClass.newInstance()); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.SET || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { - return CollectionUtils.array(Object.class); - } - return null; - } +package me.TheBukor.SkStuff.expressions; + +import javax.annotation.Nullable; + +import org.bukkit.event.Event; + +import ch.njol.skript.classes.Changer.ChangeMode; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.skript.lang.util.SimpleExpression; +import ch.njol.util.Kleenean; +import ch.njol.util.coll.CollectionUtils; +import me.TheBukor.SkStuff.util.ReflectionUtils; + +public class ExprTagOf extends SimpleExpression { + private Expression string; + private Expression compound; + + private Class nbtClass = ReflectionUtils.getNMSClass("NBTTagCompound"); + private Class nbtBaseClass = ReflectionUtils.getNMSClass("NBTBase"); + + @Override + public Class getReturnType() { + return Object.class; + } + @Override + public boolean isSingle() { + return true; + } + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] expr, int arg1, Kleenean arg2, ParseResult arg3) { + string = (Expression) expr[0]; + compound = (Expression) expr[1]; + return true; + } + @Override + public String toString(@Nullable Event e, boolean debug) { + return "the tag " + string.toString(e, debug) + " of compound"; + } + + @Override + @Nullable + protected Object[] get(Event e) { + Object NBT = compound.getSingle(e); + if (NBT == null || NBT.toString().equals("{}")) return null; //The NBT can be empty/inexistant for items ("{}" is an empty compound). + String stringTag = string.getSingle(e); + Object tag = null; + try { + tag = nbtClass.getMethod("get", String.class).invoke(NBT, stringTag); + } catch (Exception ex) { + ex.printStackTrace(); + } + if (tag == null) + return null; //The tag doesn't exist? Return . + Byte id = null; + try { + id = (Byte) tag.getClass().getMethod("getTypeId").invoke(tag); + } catch (Exception ex) { + ex.printStackTrace(); + } + try { + switch (id) { + case 1: + return new Byte[] { Byte.valueOf(nbtClass.getMethod("getByte", String.class).invoke(NBT, stringTag).toString()) }; + case 2: + return new Short[] { Short.valueOf(nbtClass.getMethod("getShort", String.class).invoke(NBT, stringTag).toString()) }; + case 3: + return new Integer[] { Integer.valueOf(nbtClass.getMethod("getInt", String.class).invoke(NBT, stringTag).toString()) }; + case 4: + return new Long[] { Long.valueOf(nbtClass.getMethod("getLong", String.class).invoke(NBT, stringTag).toString()) }; + case 5: + return new Float[] { Float.valueOf(nbtClass.getMethod("getFloat", String.class).invoke(NBT, stringTag).toString()) }; + case 6: + return new Double[] { Double.valueOf(nbtClass.getMethod("getDouble", String.class).invoke(NBT, stringTag).toString()) }; + case 7: //Byte array, only used in chunk files. Also doesn't have support for the MojangsonParser. + break; + case 8: + return new String[] { nbtClass.getMethod("getString", String.class).invoke(NBT, stringTag).toString() }; + case 9: + int i; + Object[] list = new Object[] { new Object() }; + for (i = 1; i <= 11; i++) { //To get a list I need to know the type of the tags it contains inside, + //since I can't predict what type the list will have, I just loop all of the IDs until I find a non-empty list. + list[0] = nbtClass.getMethod("getList", String.class, int.class).invoke(NBT, stringTag, i); //Try to get the list with the ID "loop-number". + if (!list[0].toString().equals("[]")) { //If list is not empty. + break; //Stop loop. + } + } + return list; + /* + REMOVED TEMPORARILY, HOPEFULLY THE NEW IMPLEMENTATION SHOULD WORK BETTER + int i; + Object list = null; + for (i = 1; i <= 11; i++) { //To get a list I need to know the type of the tags it contains inside, + //since I can't predict what type the list will have, I just loop all of the IDs until I find a non-empty list. + list = nbtClass.getMethod("getList", String.class, int.class).invoke(NBT, stringTag, i); //Try to get the list with the ID "loop-number". + if (!list.toString().equals("[]")) { //If list is not empty. + break; //Stop loop. + } + } + String methodName = null; + switch (NBTUtil.getContentsId(list)) { + case 5: //Float + methodName = "e"; //list.e(int) = get float from the specified index. + break; + case 6: //Double + methodName = "d"; //list.d(int) = get double from the specified index. + break; + case 8: //String + methodName = "getString"; //Self-explanatory, I guess. + break; + case 10: //Compound + methodName = "get"; //list.get(int) = get compound at the specified index. + break; + case 11: //Integer array + methodName = "c"; //Not sure if ever used, but meh. + break; + default: + break; + } + int listSize = (int) list.getClass().getMethod("size").invoke(list); + Object[] tags = new Object[listSize]; + for (i = 0; i < listSize; i++) { + Object gottenTag = list.getClass().getMethod(methodName, int.class).invoke(list, i); + tags[i] = gottenTag; + } + return tags; + */ + case 10: + return new Object[] { nbtClass.getMethod("getCompound", String.class).invoke(NBT, stringTag) }; + case 11: //Integer array, this one is only used on the chunk files (and maybe schematic files?). + return new Object[] { nbtClass.getMethod("getIntArray", String.class).invoke(NBT, stringTag).toString() }; + default: //This shouldn't happen, but it's better to have this just in case it spills errors everywhere. + break; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + @Override + public void change(Event e, @Nullable Object[] delta, ChangeMode mode) { + Object NBT = compound.getSingle(e); + if (NBT == null) + try { + NBT = nbtClass.newInstance(); //If the NBT isn't set, create an empty one + } catch (Exception ex) { + ex.printStackTrace(); + } + String stringTag = string.getSingle(e); + if (mode == ChangeMode.SET) { + Object newValue = delta[0]; + try { + if (newValue instanceof Byte) { + nbtClass.getMethod("setByte", String.class, byte.class).invoke(NBT, stringTag, ((Byte) newValue).byteValue()); + } else if (newValue instanceof Short) { + nbtClass.getMethod("setShort", String.class, short.class).invoke(NBT, stringTag, ((Short) newValue).shortValue()); + } else if (newValue instanceof Integer) { + nbtClass.getMethod("setInt", String.class, int.class).invoke(NBT, stringTag, ((Integer) newValue).intValue()); + } else if (newValue instanceof Long) { + nbtClass.getMethod("setLong", String.class, long.class).invoke(NBT, stringTag, ((Long) newValue).longValue()); + } else if (newValue instanceof Float) { + nbtClass.getMethod("setFloat", String.class, float.class).invoke(NBT, stringTag, ((Float) newValue).floatValue()); + } else if (newValue instanceof Double) { + nbtClass.getMethod("setDouble", String.class, double.class).invoke(NBT, stringTag, ((Double) newValue).doubleValue()); + } else if (newValue instanceof String) { + nbtClass.getMethod("setString", String.class, String.class).invoke(NBT, stringTag, String.valueOf(newValue)); + } else { + return; //Something else like a list or entire compound. + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } else if (mode == ChangeMode.RESET || mode == ChangeMode.DELETE) { + try { + nbtClass.getMethod("set", String.class, nbtBaseClass).invoke(NBT, stringTag, nbtBaseClass.newInstance()); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.SET || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + return CollectionUtils.array(Object.class); + } + return null; + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/util/NBTUtil.java b/src/me/TheBukor/SkStuff/util/NBTUtil.java deleted file mode 100644 index a40a2dd..0000000 --- a/src/me/TheBukor/SkStuff/util/NBTUtil.java +++ /dev/null @@ -1,179 +0,0 @@ -package me.TheBukor.SkStuff.util; - -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.fusesource.jansi.Ansi; - -import ch.njol.skript.Skript; - -public class NBTUtil { - private static Class nbtBaseClass = ReflectionUtils.getNMSClass("NBTBase", false); - private static Class nbtClass = ReflectionUtils.getNMSClass("NBTTagCompound", false); - private static Class nbtListClass = ReflectionUtils.getNMSClass("NBTTagList", false); - - /** - * This is actually a copy of the "a(NBTTagCompound)" method in the NBTTagCompound class. - * I needed to add this because the 1.7 and before versions of the NBTTagCompound class didn't have this method, - * so there wasn't actually a reliable way to multiple tags at once into a compound. - * For the original code for the method, check https://github.com/linouxis9/mc-dev-1.8.7/blob/master/net/minecraft/server/NBTTagCompound.java#L348 - * - * Please note that I adapted it to work using reflection. - */ - @SuppressWarnings("unchecked") - public static void addCompound(Object NBT, Object toAdd) { - if (NBT.getClass() == nbtClass && toAdd.getClass() == nbtClass) { - try { - HashMap map = (HashMap) ReflectionUtils.getField("map", nbtClass, toAdd); - Set keySet = (Set) nbtClass.getMethod("c").invoke(toAdd); - Iterator iterator = keySet.iterator(); - - while(iterator.hasNext()) { - String string = (String) iterator.next(); - Object base = nbtBaseClass.cast(map.get(string)); - if((byte) nbtBaseClass.getMethod("getTypeId").invoke(base) == 10) { - if((boolean) nbtClass.getMethod("hasKeyOfType", String.class, int.class).invoke(NBT, string, 10)) { - Object localNBT = null; - localNBT = nbtClass.getMethod("getCompound", String.class).invoke(localNBT, string); - NBTUtil.addCompound(localNBT, nbtBaseClass.cast(nbtClass)); - } else { - nbtClass.getMethod("set", String.class, nbtBaseClass).invoke(NBT, string, base.getClass().getMethod("clone").invoke(base)); - } - } else { - nbtClass.getMethod("set", String.class, nbtBaseClass).invoke(NBT, string, base.getClass().getMethod("clone").invoke(base)); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - /** - * Gets the ID of the contents inside a NBT List. - * I needed to add this because the 1.7 and before versions of the NBTTagList - * class had a different name for the method that got this value. - * 1.8 used "f()", while 1.7 used "d()". - */ - public static int getContentsId(Object list) { - if (list.getClass() == nbtListClass) { - Field type = null; - int result = 0; - try { - type = nbtListClass.getDeclaredField("type"); - type.setAccessible(true); - result = type.getInt(list); - type.setAccessible(false); - return result; - } catch (Exception ex) { - type.setAccessible(false); - ex.printStackTrace(); - } - return result; - } - return 0; - } - - /** - * Used for the "addToList()" and "setIndex()" methods if the typeId of the contents is still not defined. - */ - public static void setContentsId(Object list, int newId) { - if (list.getClass() == nbtListClass) { - Field type = null; - try { - type = nbtListClass.getDeclaredField("type"); - type.setAccessible(true); - type.set(list, newId); - type.setAccessible(false); - } catch (Exception ex) { - type.setAccessible(false); - ex.printStackTrace(); - } - } - } - - @SuppressWarnings("unchecked") - public static List getContents(Object list) { - if (list.getClass() == nbtListClass) { - List result = null; - result = (List) ReflectionUtils.getField("list", nbtListClass, list); - return result; - } - return null; - } - - /** - * Kind of a copy of the "add()" method from the NBTTagList class. - */ - public static void addToList(Object list, Object[] toAdd) { - if (list.getClass() == nbtListClass && toAdd[0].getClass() == nbtBaseClass) { - int listTypeId = NBTUtil.getContentsId(list); - int toAddId = 0; - try { - toAddId = (int) toAdd.getClass().getMethod("getTypeId").invoke(toAdd); - } catch (Exception ex) { - ex.printStackTrace(); - } - if (listTypeId == 0) { - try { - NBTUtil.setContentsId(list, toAddId); - } catch (Exception ex) { - ex.printStackTrace(); - } - } else if (listTypeId != toAddId) { - Skript.warning(Ansi.ansi().fgBright(Ansi.Color.RED) + "Adding mismatching tag types to NBT list" + Ansi.ansi().fgBright(Ansi.Color.DEFAULT)); - return; - } - - for (Object tag : toAdd) { - NBTUtil.getContents(list).add(tag); - } - } - } - - public static void removefromList(Object list, int index) { - if (list.getClass() == nbtListClass) { - if (index >= 0 && index < NBTUtil.getContents(list).size()) { - NBTUtil.getContents(list).remove(index); - } - } - } - - public static void setIndex(Object list, int index, Object toAdd) { - if (list.getClass() == nbtListClass && toAdd.getClass() == nbtBaseClass) { - if (index >= 0 && index < NBTUtil.getContents(list).size()) { - int listTypeId = NBTUtil.getContentsId(list); - int toAddId = 0; - try { - toAddId = (int) toAdd.getClass().getMethod("getTypeId").invoke(toAdd); - } catch (Exception ex) { - ex.printStackTrace(); - } - if (listTypeId == 0) { - try { - NBTUtil.setContentsId(list, toAddId); - } catch (Exception ex) { - ex.printStackTrace(); - } - } else if (listTypeId != toAddId) { - Skript.warning("Adding mismatching tag types to NBT list"); - return; - } - - NBTUtil.getContents(list).set(index, toAdd); - } - } - } - - public static Object getIndex(Object list, int index) { - if (list.getClass() == nbtListClass) { - if (index >= 0 && index < NBTUtil.getContents(list).size()) { - NBTUtil.getContents(list).get(index); - } - } - return null; - } -} \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/util/NMSInterface.java b/src/me/TheBukor/SkStuff/util/NMSInterface.java index 95fb29a..b23409c 100644 --- a/src/me/TheBukor/SkStuff/util/NMSInterface.java +++ b/src/me/TheBukor/SkStuff/util/NMSInterface.java @@ -1,52 +1,56 @@ -package me.TheBukor.SkStuff.util; - -import java.io.File; - -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.inventory.ItemStack; - -public interface NMSInterface { - - public void addToCompound(Object compound, Object toAdd); - - public void removeFromCompound(Object compound, String ... toRemove); - - public Object parseRawNBT(String rawNBT); - - public int getContentsId(Object nbtList); - - public Object[] getContents(Object nbtList); - - public void addToList(Object nbtList, Object toAdd); - - public void removeFromList(Object nbtList, int index); - - public void setIndex(Object nbtList, int index, Object toSet); - - public Object getIndex(Object nbtList, int index); - - public void removePathfinderGoal(Object entity, Class goalClass, boolean isTargetSelector); - - public void addPathfinderGoal(Object entity, int priority, Object goal, boolean isTargetSelector); - - public void registerCompoundClassInfo(); - - public void registerNBTListClassInfo(); - - public Object getEntityNBT(Entity entity); - - public Object getTileNBT(Block block); - - public Object getItemNBT(ItemStack itemStack); - - public void setEntityNBT(Entity entity, Object newCompound); - - public void setTileNBT(Block block, Object newCompound); - - public ItemStack getItemWithNBT(ItemStack itemStack, Object compound); - - public Object getFileNBT(File file); - - public void setFileNBT(File file, Object newCompound); -} +package me.TheBukor.SkStuff.util; + +import java.io.File; + +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; + +public interface NMSInterface { + + public void addToCompound(Object compound, Object toAdd); + + public void removeFromCompound(Object compound, String ... toRemove); + + public Object parseRawNBT(String rawNBT); + + public int getContentsId(Object nbtList); + + public Object[] getContents(Object nbtList); + + public void addToList(Object nbtList, Object toAdd); + + public void removeFromList(Object nbtList, int index); + + public void setIndex(Object nbtList, int index, Object toSet); + + public Object getIndex(Object nbtList, int index); + + public void removePathfinderGoal(Object entity, Class goalClass, boolean isTargetSelector); + + public void addPathfinderGoal(Object entity, int priority, Object goal, boolean isTargetSelector); + + public void registerCompoundClassInfo(); + + public void registerNBTListClassInfo(); + + public Object getEntityNBT(Entity entity); + + public Object getTileNBT(Block block); + + public Object getItemNBT(ItemStack itemStack); + + public void setEntityNBT(Entity entity, Object newCompound); + + public void setTileNBT(Block block, Object newCompound); + + public ItemStack getItemWithNBT(ItemStack itemStack, Object compound); + + public Object getFileNBT(File file); + + public void setFileNBT(File file, Object newCompound); + + public Object convertToNBT(Number number); + + public Object convertToNBT(String string); +} diff --git a/src/me/TheBukor/SkStuff/util/NMS_v1_7_R4.java b/src/me/TheBukor/SkStuff/util/NMS_v1_7_R4.java index 8836542..2ae76f0 100644 --- a/src/me/TheBukor/SkStuff/util/NMS_v1_7_R4.java +++ b/src/me/TheBukor/SkStuff/util/NMS_v1_7_R4.java @@ -1,444 +1,498 @@ -package me.TheBukor.SkStuff.util; - -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import javax.annotation.Nullable; - -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.v1_7_R4.CraftWorld; -import org.bukkit.craftbukkit.v1_7_R4.entity.CraftEntity; -import org.bukkit.craftbukkit.v1_7_R4.inventory.CraftItemStack; -import org.bukkit.entity.Entity; -import org.bukkit.inventory.ItemStack; - -import ch.njol.skript.Skript; -import ch.njol.skript.classes.Changer; -import ch.njol.skript.classes.ClassInfo; -import ch.njol.skript.classes.Parser; -import ch.njol.skript.lang.ParseContext; -import ch.njol.skript.registrations.Classes; -import ch.njol.util.coll.CollectionUtils; -import net.minecraft.server.v1_7_R4.MojangsonParser; -import net.minecraft.server.v1_7_R4.NBTBase; -import net.minecraft.server.v1_7_R4.NBTCompressedStreamTools; -import net.minecraft.server.v1_7_R4.NBTTagCompound; -import net.minecraft.server.v1_7_R4.NBTTagDouble; -import net.minecraft.server.v1_7_R4.NBTTagEnd; -import net.minecraft.server.v1_7_R4.NBTTagFloat; -import net.minecraft.server.v1_7_R4.NBTTagInt; -import net.minecraft.server.v1_7_R4.NBTTagList; -import net.minecraft.server.v1_7_R4.NBTTagString; -import net.minecraft.server.v1_7_R4.TileEntity; -import net.minecraft.server.v1_7_R4.World; - -public class NMS_v1_7_R4 implements NMSInterface { - - @SuppressWarnings("unchecked") - @Override - public void addToCompound(Object compound, Object toAdd) { - if (compound instanceof NBTTagCompound && toAdd instanceof NBTTagCompound) { - HashMap map = (HashMap) ReflectionUtils.getField("map", NBTTagCompound.class, toAdd); - Set keySet = ((NBTTagCompound) toAdd).c(); - Iterator iterator = keySet.iterator(); - - while(iterator.hasNext()) { - String string = (String) iterator.next(); - NBTBase base = (NBTBase) map.get(string); - if(base.getTypeId() == 10) { - if(((NBTTagCompound) compound).hasKeyOfType(string, 10)) { - NBTTagCompound localNBT = ((NBTTagCompound) compound).getCompound(string); - addToCompound(localNBT, (NBTTagCompound) base); - } else { - ((NBTTagCompound) compound).set(string, base.clone()); - } - } else { - ((NBTTagCompound) compound).set(string, base.clone()); - } - } - } - } - - @Override - public void removeFromCompound(Object compound, String ... toRemove) { - if (compound instanceof NBTTagCompound) { - ((NBTTagCompound) compound).remove(toRemove.toString()); //FIXME - } - } - - @Override - public Object parseRawNBT(String rawNBT) { - NBTTagCompound parsedNBT = null; - parsedNBT = (NBTTagCompound) MojangsonParser.parse(rawNBT); - return parsedNBT; - } - - @Override - public int getContentsId(Object nbtList) { - if (nbtList instanceof NBTTagList) { - return ((NBTTagList) nbtList).d(); - } - return 0; - } - - @Override - public Object[] getContents(Object nbtList) { - if (nbtList instanceof NBTTagList) { - List contents = new ArrayList(); - for (int i = 0; i < ((NBTTagList) nbtList).size(); i++) { - if (getIndex(nbtList, i) != null) { - contents.add(getIndex(nbtList, i)); - } - } - return contents.toArray(); - } - return null; - } - - @Override - public void addToList(Object nbtList, Object toAdd) { - if (nbtList instanceof NBTTagList && toAdd instanceof NBTBase) { - ((NBTTagList) nbtList).add((NBTBase) toAdd); - } - } - - @SuppressWarnings("unchecked") - @Override - public void removeFromList(Object nbtList, int index) { - if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { - List actualList = null; - actualList = (List) ReflectionUtils.getField("list", NBTTagList.class, nbtList); - actualList.remove(index); - } - } - - @SuppressWarnings("unchecked") - @Override - public void setIndex(Object nbtList, int index, Object toSet) { - if (nbtList instanceof NBTTagList && toSet instanceof NBTBase && index >= 0 && index < ((NBTTagList) nbtList).size()) { - int typeId = getContentsId(nbtList); - int toSetId = ((NBTBase) toSet).getTypeId(); - if (typeId == 0) { - ReflectionUtils.setField("type", NBTTagList.class, nbtList, toSetId); - } else if (typeId != toSetId) { - Skript.warning("Adding mismatching tag types to NBT list"); - return; - } - List actualList = null; - actualList = (List) ReflectionUtils.getField("list", NBTTagList.class, nbtList); - actualList.set(index, toSet); - } - } - - @SuppressWarnings("unchecked") - @Override - public Object getIndex(Object nbtList, int index) { - if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { - List actualList = null; - actualList = (List) ReflectionUtils.getField("list", NBTTagList.class, nbtList); - NBTBase value = (NBTBase) actualList.get(index); - if (value instanceof NBTTagEnd) - return null; - else - return value; - } - return null; - } - - @Override - public void removePathfinderGoal(Object entity, Class goalClass, boolean isTargetSelector) { - Bukkit.getLogger().warning("Sorry, Pathfinder Goals are only supported in 1.8 and above"); - } - - @Override - public void addPathfinderGoal(Object entity, int priority, Object goal, boolean isTargetSelector) { - Bukkit.getLogger().warning("Sorry, Pathfinder Goals are only supported in 1.8 and above"); - } - - @Override - public void registerCompoundClassInfo() { - Classes.registerClass(new ClassInfo(NBTTagCompound.class, "compound").user("((nbt)?( ?tag)?) ?compounds?").name("NBT Compound").changer(new Changer() { - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.SET) { - return CollectionUtils.array(String[].class, NBTTagCompound[].class); - } - return null; - } - - @Override - public void change(NBTTagCompound[] NBT, @Nullable Object[] delta, ChangeMode mode) { - if (mode == ChangeMode.SET) { - if (delta[0] instanceof NBTTagCompound) { - NBT[0] = (NBTTagCompound) delta[0]; - } else { - NBTTagCompound parsedNBT = (NBTTagCompound) parseRawNBT((String) delta[0]); - NBT[0] = parsedNBT; - } - } else if (mode == ChangeMode.ADD) { - if (delta[0] instanceof String) { - NBTTagCompound parsedNBT = (NBTTagCompound) parseRawNBT((String) delta[0]); - addToCompound(NBT[0], parsedNBT); - } else { - addToCompound(NBT[0], delta[0]); - } - } else if (mode == ChangeMode.REMOVE) { - if (delta[0] instanceof NBTTagCompound) - return; - for (Object s : delta) { - NBT[0].remove((String) s); - } - } - } - }).parser(new Parser() { - - @Override - public String getVariableNamePattern() { - return ".+"; - } - - @Override - @Nullable - public NBTTagCompound parse(String rawNBT, ParseContext context) { - if (rawNBT.startsWith("nbt:{") && rawNBT.endsWith("}")) { - rawNBT.substring(4); - NBTTagCompound NBT = (NBTTagCompound) parseRawNBT(rawNBT); - if (NBT.toString().equals("{}")) { - return null; - } - return NBT; - } - return null; - } - - @Override - public String toString(NBTTagCompound compound, int arg1) { - return compound.toString(); - } - - @Override - public String toVariableNameString(NBTTagCompound compound) { - return "nbt:" + compound.toString(); - } - })); - - } - - @Override - public void registerNBTListClassInfo() { - Classes.registerClass(new ClassInfo(NBTTagList.class, "nbtlist").user("nbt ?list ?(tag)?").name("NBT List").changer(new Changer() { - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.SET || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { - return CollectionUtils.array(Float[].class, Double[].class, String[].class, NBTTagCompound[].class, Integer[].class, NBTTagList[].class); - } - return null; - } - - @Override - public void change(NBTTagList[] nbtList, @Nullable Object[] delta, ChangeMode mode) { - int typeId = 0; - if (delta instanceof Float[]) { - typeId = 5; - } else if (delta instanceof Double[]) { - typeId = 6; - } else if (delta instanceof String[]) { - typeId = 8; - } else if (delta instanceof NBTTagList[]) { - typeId = 9; - } else if (delta instanceof NBTTagCompound[]) { - typeId = 10; - } else if (delta instanceof Integer[]) { - typeId = 11; - } else { - return; - } - if (mode == ChangeMode.SET) { - if (typeId == 9) - nbtList[0] = (NBTTagList) delta[0]; - } else if (mode == ChangeMode.ADD) { - if (getContentsId(nbtList[0]) == typeId) { - if (typeId == 5) { - NBTTagFloat floatTag = new NBTTagFloat((float) delta[0]); - addToList(nbtList[0], floatTag); - } else if (typeId == 6) { - NBTTagDouble doubleTag = new NBTTagDouble((double) delta[0]); - addToList(nbtList[0], doubleTag); - } else if (typeId == 8) { - NBTTagString stringTag = new NBTTagString((String) delta [0]); - addToList(nbtList[0], stringTag); - } else if (typeId == 10) { - addToList(nbtList[0], delta[0]); - } else if (typeId == 11) { - NBTTagInt intTag = new NBTTagInt((int) delta[0]); - addToList(nbtList[0], intTag); - } - } - } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { - nbtList[0] = new NBTTagList(); - } - } - }).parser(new Parser() { - - @Override - public String getVariableNamePattern() { - return ".+"; - } - - @Override - @Nullable - public NBTTagList parse(String ignored, ParseContext context) { - return null; - } - - @Override - public String toString(NBTTagList nbtList, int arg1) { - return nbtList.toString(); - } - - @Override - public String toVariableNameString(NBTTagList nbtList) { - return nbtList.toString(); - } - })); - } - - @Override - public Object getEntityNBT(Entity entity) { - net.minecraft.server.v1_7_R4.Entity nmsEntity = ((CraftEntity) entity).getHandle(); - NBTTagCompound NBT = new NBTTagCompound(); - nmsEntity.e(NBT); - return NBT; - } - - @Override - public Object getTileNBT(Block block) { - NBTTagCompound NBT = new NBTTagCompound(); - World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); - TileEntity tileEntity = nmsWorld.getTileEntity(block.getX(), block.getY(), block.getZ()); - if (tileEntity == null) - return null; - tileEntity.b(NBT); - return NBT; - } - - @Override - public Object getItemNBT(ItemStack itemStack) { - if (itemStack.getType() == Material.AIR) - return null; - NBTTagCompound NBT = new NBTTagCompound(); - net.minecraft.server.v1_7_R4.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); - NBT = nmsItem.getTag(); - if (NBT == null || NBT.toString().equals("{}")) //Null or empty. - return null; - return new Object[] { NBT }; - } - - @Override - public void setEntityNBT(Entity entity, Object newCompound) { - if (newCompound instanceof NBTTagCompound) { - net.minecraft.server.v1_7_R4.Entity nmsEntity = ((CraftEntity) entity).getHandle(); - nmsEntity.f((NBTTagCompound) newCompound); - } - } - - @Override - public void setTileNBT(Block block, Object newCompound) { - if (newCompound instanceof NBTTagCompound) { - World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); - TileEntity tileEntity = nmsWorld.getTileEntity(block.getX(), block.getY(), block.getZ()); - if (tileEntity == null) - return; - tileEntity.a((NBTTagCompound) newCompound); - tileEntity.update(); - nmsWorld.notify(tileEntity.x, tileEntity.y, tileEntity.z); - } - } - - @Override - public ItemStack getItemWithNBT(ItemStack itemStack, Object compound) { - if (compound instanceof NBTTagCompound) { - if (itemStack.getType() == Material.AIR || itemStack == null) - return null; - if (compound == null || compound.toString().equals("{}")) - return itemStack; - net.minecraft.server.v1_7_R4.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); - nmsItem.setTag((NBTTagCompound) compound); - ItemStack newItem = CraftItemStack.asCraftMirror(nmsItem); - return newItem; - } - return null; - } - - @Override - public Object getFileNBT(File file) { - FileInputStream fis = null; - try { - fis = new FileInputStream(file); - } catch (FileNotFoundException ex) { - return null; //File doesn't exist. - } - NBTTagCompound fileNBT = null; - try { - fileNBT = NBTCompressedStreamTools.a(fis); - fis.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - try { - fis.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - return fileNBT; - } - - @Override - public void setFileNBT(File file, Object newCompound) { - OutputStream os = null; - try { - os = new FileOutputStream(file); - } catch (FileNotFoundException ex) { - ex.printStackTrace(); - } - try { - NBTCompressedStreamTools.a((NBTTagCompound) newCompound, os); - os.close(); - } catch (Exception ex) { - if (ex instanceof EOFException) { - ; //Ignore, just end of the file - } else { - ex.printStackTrace(); - } - } finally { - try { - os.close(); - } catch (Exception ex) { - if (ex instanceof EOFException) { - ; //Ignore. - } else { - ex.printStackTrace(); - } - } - } - } +package me.TheBukor.SkStuff.util; + +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.annotation.Nullable; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_7_R4.CraftWorld; +import org.bukkit.craftbukkit.v1_7_R4.entity.CraftEntity; +import org.bukkit.craftbukkit.v1_7_R4.inventory.CraftItemStack; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; + +import ch.njol.skript.Skript; +import ch.njol.skript.classes.Changer; +import ch.njol.skript.classes.ClassInfo; +import ch.njol.skript.classes.Parser; +import ch.njol.skript.lang.ParseContext; +import ch.njol.skript.registrations.Classes; +import ch.njol.util.coll.CollectionUtils; +import net.minecraft.server.v1_7_R4.MojangsonParser; +import net.minecraft.server.v1_7_R4.NBTBase; +import net.minecraft.server.v1_7_R4.NBTCompressedStreamTools; +import net.minecraft.server.v1_7_R4.NBTTagCompound; +import net.minecraft.server.v1_7_R4.NBTTagDouble; +import net.minecraft.server.v1_7_R4.NBTTagFloat; +import net.minecraft.server.v1_7_R4.NBTTagInt; +import net.minecraft.server.v1_7_R4.NBTTagList; +import net.minecraft.server.v1_7_R4.NBTTagString; +import net.minecraft.server.v1_7_R4.TileEntity; +import net.minecraft.server.v1_7_R4.World; +import net.minecraft.server.v1_8_R3.NBTTagByte; +import net.minecraft.server.v1_8_R3.NBTTagLong; +import net.minecraft.server.v1_8_R3.NBTTagShort; + +public class NMS_v1_7_R4 implements NMSInterface { + + @SuppressWarnings("unchecked") + @Override + public void addToCompound(Object compound, Object toAdd) { + if (compound instanceof NBTTagCompound && toAdd instanceof NBTTagCompound) { + HashMap map = (HashMap) ReflectionUtils.getField("map", NBTTagCompound.class, toAdd); + Set keySet = ((NBTTagCompound) toAdd).c(); + Iterator iterator = keySet.iterator(); + + while(iterator.hasNext()) { + String string = (String) iterator.next(); + NBTBase base = (NBTBase) map.get(string); + if(base.getTypeId() == 10) { + if(((NBTTagCompound) compound).hasKeyOfType(string, 10)) { + NBTTagCompound localNBT = ((NBTTagCompound) compound).getCompound(string); + addToCompound(localNBT, (NBTTagCompound) base); + } else { + ((NBTTagCompound) compound).set(string, base.clone()); + } + } else { + ((NBTTagCompound) compound).set(string, base.clone()); + } + } + } + } + + @Override + public void removeFromCompound(Object compound, String ... toRemove) { + if (compound instanceof NBTTagCompound) { + for (String s : toRemove) { + ((NBTTagCompound) compound).remove(s); + } + } + } + + @Override + public NBTTagCompound parseRawNBT(String rawNBT) { + NBTTagCompound parsedNBT = null; + parsedNBT = (NBTTagCompound) MojangsonParser.parse(rawNBT); + return parsedNBT; + } + + @Override + public int getContentsId(Object nbtList) { + if (nbtList instanceof NBTTagList) { + return ((NBTTagList) nbtList).d(); + } + return 0; + } + + @Override + public Object[] getContents(Object nbtList) { + if (nbtList instanceof NBTTagList) { + Object[] contents = new Object[((NBTTagList) nbtList).size()]; + for (int i = 0; i < ((NBTTagList) nbtList).size(); i++) { + if (getIndex(nbtList, i) != null) { + contents[i] = getIndex(nbtList, i); + } + } + return contents; + } + return null; + } + + @Override + public void addToList(Object nbtList, Object toAdd) { + if (nbtList instanceof NBTTagList && toAdd instanceof NBTBase) { + ((NBTTagList) nbtList).add((NBTBase) toAdd); + } + } + + @SuppressWarnings("unchecked") + @Override + public void removeFromList(Object nbtList, int index) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + List actualList = null; + actualList = (List) ReflectionUtils.getField("list", NBTTagList.class, nbtList); + actualList.remove(index); + } + } + + @SuppressWarnings("unchecked") + @Override + public void setIndex(Object nbtList, int index, Object toSet) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + int typeId = getContentsId(nbtList); + NBTBase toSetNBT = null; + if (toSet instanceof NBTBase) + toSetNBT = (NBTBase) toSet; + else if (toSet instanceof Number) + toSetNBT = (NBTBase) convertToNBT((Number) toSet); + else if (toSet instanceof String) + toSetNBT = convertToNBT((String) toSet); + else + return; + int toSetId = (toSetNBT).getTypeId(); + if (typeId == 0) { + ReflectionUtils.setField("type", NBTTagList.class, nbtList, toSetId); + } else if (typeId != toSetId) { + Skript.warning("Adding mismatching tag types to NBT list"); + return; + } + List actualList = null; + actualList = (List) ReflectionUtils.getField("list", NBTTagList.class, nbtList); + actualList.set(index, toSetNBT); + } + } + + @SuppressWarnings("unchecked") + @Override + public Object getIndex(Object nbtList, int index) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + List actualList = null; + actualList = (List) ReflectionUtils.getField("list", NBTTagList.class, nbtList); + NBTBase value = (NBTBase) actualList.get(index); + return value; + } + return null; + } + + @Override + public void removePathfinderGoal(Object entity, Class goalClass, boolean isTargetSelector) { + Bukkit.getLogger().warning("Sorry, Pathfinder Goals are only supported in 1.8 and above"); + } + + @Override + public void addPathfinderGoal(Object entity, int priority, Object goal, boolean isTargetSelector) { + Bukkit.getLogger().warning("Sorry, Pathfinder Goals are only supported in 1.8 and above"); + } + + @Override + public void registerCompoundClassInfo() { + Classes.registerClass(new ClassInfo(NBTTagCompound.class, "compound").user("((nbt)?( ?tag)?) ?compounds?").name("NBT Compound").changer(new Changer() { + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.SET) { + return CollectionUtils.array(String[].class, NBTTagCompound[].class); + } + return null; + } + + @Override + public void change(NBTTagCompound[] NBT, @Nullable Object[] delta, ChangeMode mode) { + if (mode == ChangeMode.SET) { + if (delta[0] instanceof NBTTagCompound) { + NBT[0] = (NBTTagCompound) delta[0]; + } else { + NBTTagCompound parsedNBT = parseRawNBT((String) delta[0]); + NBT[0] = parsedNBT; + } + } else if (mode == ChangeMode.ADD) { + if (delta[0] instanceof String) { + NBTTagCompound parsedNBT = parseRawNBT((String) delta[0]); + addToCompound(NBT[0], parsedNBT); + } else { + addToCompound(NBT[0], delta[0]); + } + } else if (mode == ChangeMode.REMOVE) { + if (delta[0] instanceof NBTTagCompound) + return; + for (Object s : delta) { + NBT[0].remove((String) s); + } + } + } + }).parser(new Parser() { + + @Override + public String getVariableNamePattern() { + return ".+"; + } + + @Override + @Nullable + public NBTTagCompound parse(String rawNBT, ParseContext context) { + if (rawNBT.startsWith("nbt:{") && rawNBT.endsWith("}")) { + rawNBT.substring(4); + NBTTagCompound NBT = parseRawNBT(rawNBT); + if (NBT.toString().equals("{}")) { + return null; + } + return NBT; + } + return null; + } + + @Override + public String toString(NBTTagCompound compound, int arg1) { + return compound.toString(); + } + + @Override + public String toVariableNameString(NBTTagCompound compound) { + return "nbt:" + compound.toString(); + } + })); + + } + + @Override + public void registerNBTListClassInfo() { + Classes.registerClass(new ClassInfo(NBTTagList.class, "nbtlist").user("nbt ?list ?(tag)?").name("NBT List").changer(new Changer() { + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.SET || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + return CollectionUtils.array(Float[].class, Double[].class, String[].class, NBTTagCompound[].class, Integer[].class, NBTTagList[].class); + } + return null; + } + + @Override + public void change(NBTTagList[] nbtList, @Nullable Object[] delta, ChangeMode mode) { + int typeId = 0; + if (delta instanceof Float[]) { + typeId = 5; + } else if (delta instanceof Double[]) { + typeId = 6; + } else if (delta instanceof String[]) { + typeId = 8; + } else if (delta instanceof NBTTagList[]) { + typeId = 9; + } else if (delta instanceof NBTTagCompound[]) { + typeId = 10; + } else if (delta instanceof Integer[]) { + typeId = 11; + } else { + return; + } + if (mode == ChangeMode.SET) { + if (typeId == 9) + nbtList[0] = (NBTTagList) delta[0]; + } else if (mode == ChangeMode.ADD) { + if (getContentsId(nbtList[0]) == typeId) { + if (typeId == 5) { + NBTTagFloat floatTag = new NBTTagFloat((float) delta[0]); + addToList(nbtList[0], floatTag); + } else if (typeId == 6) { + NBTTagDouble doubleTag = new NBTTagDouble((double) delta[0]); + addToList(nbtList[0], doubleTag); + } else if (typeId == 8) { + NBTTagString stringTag = new NBTTagString((String) delta [0]); + addToList(nbtList[0], stringTag); + } else if (typeId == 10) { + addToList(nbtList[0], delta[0]); + } else if (typeId == 11) { + NBTTagInt intTag = new NBTTagInt((int) delta[0]); + addToList(nbtList[0], intTag); + } + } + } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + nbtList[0] = new NBTTagList(); + } + } + }).parser(new Parser() { + + @Override + public String getVariableNamePattern() { + return ".+"; + } + + @Override + @Nullable + public NBTTagList parse(String ignored, ParseContext context) { + return null; + } + + @Override + public String toString(NBTTagList nbtList, int arg1) { + return nbtList.toString(); + } + + @Override + public String toVariableNameString(NBTTagList nbtList) { + return nbtList.toString(); + } + })); + } + + @Override + public NBTTagCompound getEntityNBT(Entity entity) { + net.minecraft.server.v1_7_R4.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + NBTTagCompound NBT = new NBTTagCompound(); + nmsEntity.e(NBT); + return NBT; + } + + @Override + public NBTTagCompound getTileNBT(Block block) { + NBTTagCompound NBT = new NBTTagCompound(); + World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); + TileEntity tileEntity = nmsWorld.getTileEntity(block.getX(), block.getY(), block.getZ()); + if (tileEntity == null) + return null; + tileEntity.b(NBT); + return NBT; + } + + @Override + public NBTTagCompound getItemNBT(ItemStack itemStack) { + if (itemStack.getType() == Material.AIR) + return null; + NBTTagCompound NBT = new NBTTagCompound(); + net.minecraft.server.v1_7_R4.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); + NBT = nmsItem.getTag(); + if (NBT == null || NBT.toString().equals("{}")) //Null or empty. + return null; + return NBT; + } + + @Override + public void setEntityNBT(Entity entity, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + net.minecraft.server.v1_7_R4.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + nmsEntity.f((NBTTagCompound) newCompound); + } + } + + @Override + public void setTileNBT(Block block, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); + TileEntity tileEntity = nmsWorld.getTileEntity(block.getX(), block.getY(), block.getZ()); + if (tileEntity == null) + return; + tileEntity.a((NBTTagCompound) newCompound); + tileEntity.update(); + nmsWorld.notify(tileEntity.x, tileEntity.y, tileEntity.z); + } + } + + @Override + public ItemStack getItemWithNBT(ItemStack itemStack, Object compound) { + if (compound instanceof NBTTagCompound) { + if (itemStack.getType() == Material.AIR || itemStack == null) + return null; + if (compound == null || compound.toString().equals("{}")) + return itemStack; + net.minecraft.server.v1_7_R4.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); + nmsItem.setTag((NBTTagCompound) compound); + ItemStack newItem = CraftItemStack.asCraftMirror(nmsItem); + return newItem; + } + return null; + } + + @Override + public NBTTagCompound getFileNBT(File file) { + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + } catch (FileNotFoundException ex) { + return null; //File doesn't exist. + } + NBTTagCompound fileNBT = null; + try { + fileNBT = NBTCompressedStreamTools.a(fis); + fis.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + try { + fis.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + return fileNBT; + } + + @Override + public void setFileNBT(File file, Object newCompound) { + OutputStream os = null; + try { + os = new FileOutputStream(file); + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + } + try { + NBTCompressedStreamTools.a((NBTTagCompound) newCompound, os); + os.close(); + } catch (Exception ex) { + if (ex instanceof EOFException) { + ; //Ignore, just end of the file + } else { + ex.printStackTrace(); + } + } finally { + try { + os.close(); + } catch (Exception ex) { + if (ex instanceof EOFException) { + ; //Ignore. + } else { + ex.printStackTrace(); + } + } + } + } + + public NBTTagByte convertToNBT(byte b) { + return new NBTTagByte(b); + } + + public NBTTagShort convertToNBT(short s) { + return new NBTTagShort(s); + } + + public NBTTagInt convertToNBT(int i) { + return new NBTTagInt(i); + } + + public NBTTagLong convertToNBT(long l) { + return new NBTTagLong(l); + } + + public NBTTagFloat convertToNBT(float f) { + return new NBTTagFloat(f); + } + + public NBTTagDouble convertToNBT(double d) { + return new NBTTagDouble(d); + } + + public NBTTagString convertToNBT(String string) { + return new NBTTagString(string); + } + + @Override + public Object convertToNBT(Number number) { + if (number instanceof Byte) + return convertToNBT((byte) number); + else if (number instanceof Short) + return convertToNBT((short) number); + else if (number instanceof Integer) + return convertToNBT((int) number); + else if (number instanceof Long) + return convertToNBT((long) number); + else if (number instanceof Float) + return convertToNBT((float) number); + else if (number instanceof Double) + return convertToNBT((double) number); + return number; + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/util/NMS_v1_8_R1.java b/src/me/TheBukor/SkStuff/util/NMS_v1_8_R1.java index 116375a..d694ef8 100644 --- a/src/me/TheBukor/SkStuff/util/NMS_v1_8_R1.java +++ b/src/me/TheBukor/SkStuff/util/NMS_v1_8_R1.java @@ -1,434 +1,554 @@ -package me.TheBukor.SkStuff.util; - -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.annotation.Nullable; - -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.v1_8_R1.CraftWorld; -import org.bukkit.craftbukkit.v1_8_R1.entity.CraftEntity; -import org.bukkit.craftbukkit.v1_8_R1.inventory.CraftItemStack; -import org.bukkit.entity.Entity; -import org.bukkit.inventory.ItemStack; - -import ch.njol.skript.classes.Changer; -import ch.njol.skript.classes.ClassInfo; -import ch.njol.skript.classes.Parser; -import ch.njol.skript.lang.ParseContext; -import ch.njol.skript.registrations.Classes; -import ch.njol.util.coll.CollectionUtils; -import net.minecraft.server.v1_8_R1.BlockPosition; -import net.minecraft.server.v1_8_R1.EntityInsentient; -import net.minecraft.server.v1_8_R1.MojangsonParser; -import net.minecraft.server.v1_8_R1.NBTBase; -import net.minecraft.server.v1_8_R1.NBTCompressedStreamTools; -import net.minecraft.server.v1_8_R1.NBTTagCompound; -import net.minecraft.server.v1_8_R1.NBTTagDouble; -import net.minecraft.server.v1_8_R1.NBTTagEnd; -import net.minecraft.server.v1_8_R1.NBTTagFloat; -import net.minecraft.server.v1_8_R1.NBTTagInt; -import net.minecraft.server.v1_8_R1.NBTTagList; -import net.minecraft.server.v1_8_R1.NBTTagString; -import net.minecraft.server.v1_8_R1.PathfinderGoal; -import net.minecraft.server.v1_8_R1.PathfinderGoalSelector; -import net.minecraft.server.v1_8_R1.TileEntity; -import net.minecraft.server.v1_8_R1.World; - -public class NMS_v1_8_R1 implements NMSInterface { - - @Override - public void addToCompound(Object compound, Object toAdd) { - if (compound instanceof NBTTagCompound && toAdd instanceof NBTTagCompound) { - ((NBTTagCompound) compound).a((NBTTagCompound) toAdd); - } - } - - @Override - public void removeFromCompound(Object compound, String ... toRemove) { - if (compound instanceof NBTTagCompound) { - ((NBTTagCompound) compound).remove(toRemove.toString()); //FIXME - } - } - - @Override - public Object parseRawNBT(String rawNBT) { - NBTTagCompound parsedNBT = null; - parsedNBT = MojangsonParser.parse(rawNBT); - return parsedNBT; - } - - @Override - public int getContentsId(Object nbtList) { - if (nbtList instanceof NBTTagList) { - return ((NBTTagList) nbtList).f(); - } - return 0; - } - - @Override - public Object[] getContents(Object nbtList) { - if (nbtList instanceof NBTTagList) { - List contents = new ArrayList(); - for (int i = 0; i < ((NBTTagList) nbtList).size(); i++) { - if (getIndex(nbtList, i) != null) { - contents.add(getIndex(nbtList, i)); - } - } - return contents.toArray(); - } - return null; - } - - @Override - public void addToList(Object nbtList, Object toAdd) { - if (nbtList instanceof NBTTagList && toAdd instanceof NBTBase) { - ((NBTTagList) nbtList).add((NBTBase) toAdd); - } - } - - @Override - public void removeFromList(Object nbtList, int index) { - if (nbtList instanceof NBTTagList) { - ((NBTTagList) nbtList).a(index); - } - } - - @Override - public void setIndex(Object nbtList, int index, Object toSet) { - if (nbtList instanceof NBTTagList && toSet instanceof NBTBase) { - ((NBTTagList) nbtList).a(index, (NBTBase) toSet); - } - } - - @Override - public Object getIndex(Object nbtList, int index) { - if (nbtList instanceof NBTTagList) { - NBTBase value = ((NBTTagList) nbtList).g(index); - if (value instanceof NBTTagEnd) - return null; - else - return value; - } - return null; - } - - @Override - public void removePathfinderGoal(Object entity, Class goalClass, boolean isTargetSelector) { - if (entity instanceof EntityInsentient) { - ((EntityInsentient) entity).setGoalTarget(null); - if (isTargetSelector) { - Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).targetSelector)).iterator(); - while (goals.hasNext()) { - Object goal = goals.next(); - if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { - goals.remove(); - } - } - } else { - Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).goalSelector)).iterator(); - while (goals.hasNext()) { - Object goal = goals.next(); - if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { - goals.remove(); - } - } - } - } - } - - @Override - public void addPathfinderGoal(Object entity, int priority, Object goal, boolean isTargetSelector) { - if (entity instanceof EntityInsentient && goal instanceof PathfinderGoal) { - if (isTargetSelector) - ((EntityInsentient) entity).targetSelector.a(priority, (PathfinderGoal) goal); - else - ((EntityInsentient) entity).goalSelector.a(priority, (PathfinderGoal) goal); - } - } - - @Override - public void registerCompoundClassInfo() { - Classes.registerClass(new ClassInfo(NBTTagCompound.class, "compound").user("((nbt)?( ?tag)?) ?compounds?").name("NBT Compound").changer(new Changer() { - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.SET) { - return CollectionUtils.array(String[].class, NBTTagCompound[].class); - } - return null; - } - - @Override - public void change(NBTTagCompound[] NBT, @Nullable Object[] delta, ChangeMode mode) { - if (mode == ChangeMode.SET) { - if (delta[0] instanceof NBTTagCompound) { - NBT[0] = (NBTTagCompound) delta[0]; - } else { - NBTTagCompound parsedNBT = (NBTTagCompound) parseRawNBT((String) delta[0]); - NBT[0] = parsedNBT; - } - } else if (mode == ChangeMode.ADD) { - if (delta[0] instanceof String) { - NBTTagCompound parsedNBT = (NBTTagCompound) parseRawNBT((String) delta[0]); - addToCompound(NBT[0], parsedNBT); - } else { - addToCompound(NBT[0], delta[0]); - } - } else if (mode == ChangeMode.REMOVE) { - if (delta[0] instanceof NBTTagCompound) - return; - for (Object s : delta) { - NBT[0].remove((String) s); - } - } - } - }).parser(new Parser() { - - @Override - public String getVariableNamePattern() { - return ".+"; - } - - @Override - @Nullable - public NBTTagCompound parse(String rawNBT, ParseContext context) { - if (rawNBT.startsWith("nbt:{") && rawNBT.endsWith("}")) { - rawNBT.substring(4); - rawNBT.substring(4); - NBTTagCompound NBT = (NBTTagCompound) parseRawNBT(rawNBT); - if (NBT.toString().equals("{}")) { - return null; - } - return NBT; - } - return null; - } - - @Override - public String toString(NBTTagCompound compound, int arg1) { - return compound.toString(); - } - - @Override - public String toVariableNameString(NBTTagCompound compound) { - return "nbt:" + compound.toString(); - } - })); - - } - - @Override - public void registerNBTListClassInfo() { - Classes.registerClass(new ClassInfo(NBTTagList.class, "nbtlist").user("nbt ?list ?(tag)?").name("NBT List").changer(new Changer() { - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.SET || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { - return CollectionUtils.array(Float[].class, Double[].class, String[].class, NBTTagCompound[].class, Integer[].class, NBTTagList[].class); - } - return null; - } - - @Override - public void change(NBTTagList[] nbtList, @Nullable Object[] delta, ChangeMode mode) { - int typeId = 0; - if (delta instanceof Float[]) { - typeId = 5; - } else if (delta instanceof Double[]) { - typeId = 6; - } else if (delta instanceof String[]) { - typeId = 8; - } else if (delta instanceof NBTTagList[]) { - typeId = 9; - } else if (delta instanceof NBTTagCompound[]) { - typeId = 10; - } else if (delta instanceof Integer[]) { - typeId = 11; - } else { - return; - } - if (mode == ChangeMode.SET) { - if (typeId == 9) - nbtList[0] = (NBTTagList) delta[0]; - } else if (mode == ChangeMode.ADD) { - if (getContentsId(nbtList[0]) == typeId) { - if (typeId == 5) { - NBTTagFloat floatTag = new NBTTagFloat((float) delta[0]); - addToList(nbtList[0], floatTag); - } else if (typeId == 6) { - NBTTagDouble doubleTag = new NBTTagDouble((double) delta[0]); - addToList(nbtList[0], doubleTag); - } else if (typeId == 8) { - NBTTagString stringTag = new NBTTagString((String) delta [0]); - addToList(nbtList[0], stringTag); - } else if (typeId == 10) { - addToList(nbtList[0], delta[0]); - } else if (typeId == 11) { - NBTTagInt intTag = new NBTTagInt((int) delta[0]); - addToList(nbtList[0], intTag); - } - } - } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { - nbtList[0] = new NBTTagList(); - } - } - }).parser(new Parser() { - - @Override - public String getVariableNamePattern() { - return ".+"; - } - - @Override - @Nullable - public NBTTagList parse(String ignored, ParseContext context) { - return null; - } - - @Override - public String toString(NBTTagList nbtList, int arg1) { - return nbtList.toString(); - } - - @Override - public String toVariableNameString(NBTTagList nbtList) { - return nbtList.toString(); - } - })); - } - - @Override - public Object getEntityNBT(Entity entity) { - net.minecraft.server.v1_8_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); - NBTTagCompound NBT = new NBTTagCompound(); - nmsEntity.e(NBT); - return NBT; - } - - @Override - public Object getTileNBT(Block block) { - NBTTagCompound NBT = new NBTTagCompound(); - World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); - TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); - if (tileEntity == null) - return null; - tileEntity.b(NBT); - return NBT; - } - - @Override - public Object getItemNBT(ItemStack itemStack) { - if (itemStack.getType() == Material.AIR) - return null; - NBTTagCompound NBT = new NBTTagCompound(); - net.minecraft.server.v1_8_R1.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); - NBT = nmsItem.getTag(); - if (NBT == null || NBT.toString().equals("{}")) //Null or empty. - return null; - return new Object[] { NBT }; - } - - @Override - public void setEntityNBT(Entity entity, Object newCompound) { - if (newCompound instanceof NBTTagCompound) { - net.minecraft.server.v1_8_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); - nmsEntity.f((NBTTagCompound) newCompound); - } - } - - @Override - public void setTileNBT(Block block, Object newCompound) { - if (newCompound instanceof NBTTagCompound) { - World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); - TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); - if (tileEntity == null) - return; - tileEntity.a((NBTTagCompound) newCompound); - tileEntity.update(); - nmsWorld.notify(tileEntity.getPosition()); - } - } - - @Override - public ItemStack getItemWithNBT(ItemStack itemStack, Object compound) { - if (compound instanceof NBTTagCompound) { - if (itemStack.getType() == Material.AIR || itemStack == null) - return null; - if (compound == null || compound.toString().equals("{}")) - return itemStack; - net.minecraft.server.v1_8_R1.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); - nmsItem.setTag((NBTTagCompound) compound); - ItemStack newItem = CraftItemStack.asCraftMirror(nmsItem); - return newItem; - } - return null; - } - - @Override - public Object getFileNBT(File file) { - FileInputStream fis = null; - try { - fis = new FileInputStream(file); - } catch (FileNotFoundException ex) { - return null; //File doesn't exist. - } - NBTTagCompound fileNBT = null; - try { - fileNBT = NBTCompressedStreamTools.a(fis); - fis.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - try { - fis.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - return fileNBT; - } - - @Override - public void setFileNBT(File file, Object newCompound) { - OutputStream os = null; - try { - os = new FileOutputStream(file); - } catch (FileNotFoundException ex) { - ex.printStackTrace(); - } - try { - NBTCompressedStreamTools.a((NBTTagCompound) newCompound, os); - os.close(); - } catch (Exception ex) { - if (ex instanceof EOFException) { - ; //Ignore, just end of the file - } else { - ex.printStackTrace(); - } - } finally { - try { - os.close(); - } catch (Exception ex) { - if (ex instanceof EOFException) { - ; //Ignore. - } else { - ex.printStackTrace(); - } - } - } - } +package me.TheBukor.SkStuff.util; + +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.OutputStream; +import java.io.StreamCorruptedException; +import java.util.Iterator; +import java.util.List; + +import javax.annotation.Nullable; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_8_R1.CraftWorld; +import org.bukkit.craftbukkit.v1_8_R1.entity.CraftEntity; +import org.bukkit.craftbukkit.v1_8_R1.inventory.CraftItemStack; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; + +import ch.njol.skript.classes.Changer; +import ch.njol.skript.classes.ClassInfo; +import ch.njol.skript.classes.Parser; +import ch.njol.skript.classes.Serializer; +import ch.njol.skript.lang.ParseContext; +import ch.njol.skript.registrations.Classes; +import ch.njol.util.coll.CollectionUtils; +import ch.njol.yggdrasil.Fields; +import net.minecraft.server.v1_8_R1.BlockPosition; +import net.minecraft.server.v1_8_R1.EntityInsentient; +import net.minecraft.server.v1_8_R1.MojangsonParser; +import net.minecraft.server.v1_8_R1.NBTBase; +import net.minecraft.server.v1_8_R1.NBTCompressedStreamTools; +import net.minecraft.server.v1_8_R1.NBTTagByte; +import net.minecraft.server.v1_8_R1.NBTTagCompound; +import net.minecraft.server.v1_8_R1.NBTTagDouble; +import net.minecraft.server.v1_8_R1.NBTTagFloat; +import net.minecraft.server.v1_8_R1.NBTTagInt; +import net.minecraft.server.v1_8_R1.NBTTagList; +import net.minecraft.server.v1_8_R1.NBTTagLong; +import net.minecraft.server.v1_8_R1.NBTTagShort; +import net.minecraft.server.v1_8_R1.NBTTagString; +import net.minecraft.server.v1_8_R1.PathfinderGoal; +import net.minecraft.server.v1_8_R1.PathfinderGoalSelector; +import net.minecraft.server.v1_8_R1.TileEntity; +import net.minecraft.server.v1_8_R1.World; + +public class NMS_v1_8_R1 implements NMSInterface { + + @Override + public void addToCompound(Object compound, Object toAdd) { + if (compound instanceof NBTTagCompound && toAdd instanceof NBTTagCompound) { + ((NBTTagCompound) compound).a((NBTTagCompound) toAdd); + } + } + + @Override + public void removeFromCompound(Object compound, String ... toRemove) { + if (compound instanceof NBTTagCompound) { + for (String s : toRemove) { + ((NBTTagCompound) compound).remove(s); + } + } + } + + @Override + public NBTTagCompound parseRawNBT(String rawNBT) { + NBTTagCompound parsedNBT = null; + parsedNBT = MojangsonParser.parse(rawNBT); + return parsedNBT; + } + + @Override + public int getContentsId(Object nbtList) { + if (nbtList instanceof NBTTagList) { + return ((NBTTagList) nbtList).f(); + } + return 0; + } + + @Override + public Object[] getContents(Object nbtList) { + if (nbtList instanceof NBTTagList) { + Object[] contents = new Object[((NBTTagList) nbtList).size()]; + for (int i = 0; i < ((NBTTagList) nbtList).size(); i++) { + if (getIndex(nbtList, i) != null) { + contents[i] = getIndex(nbtList, i); + } + } + return contents; + } + return null; + } + + @Override + public void addToList(Object nbtList, Object toAdd) { + if (nbtList instanceof NBTTagList && toAdd instanceof NBTBase) { + ((NBTTagList) nbtList).add((NBTBase) toAdd); + } + } + + @Override + public void removeFromList(Object nbtList, int index) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + ((NBTTagList) nbtList).a(index); + } + } + + @Override + public void setIndex(Object nbtList, int index, Object toSet) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + if (toSet instanceof NBTBase) { + ((NBTTagList) nbtList).a(index, (NBTBase) toSet); + } else if (toSet instanceof Number) { + ((NBTTagList) nbtList).a(index, convertToNBT((Number) toSet)); + } else if (toSet instanceof String) { + ((NBTTagList) nbtList).a(index, convertToNBT((String) toSet)); + } + } + } + + @Override + public Object getIndex(Object nbtList, int index) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + NBTBase value = ((NBTTagList) nbtList).g(index); + if (value instanceof NBTTagByte) { + return ((NBTTagByte) value).f(); //Byte stored inside a NBTNumber + } else if (value instanceof NBTTagShort) { + return ((NBTTagShort) value).e(); //Short inside a NBTNumber + } else if (value instanceof NBTTagInt) { + return ((NBTTagInt) value).d(); //Integer inside a NBTNumber + } else if (value instanceof NBTTagLong) { + return ((NBTTagLong) value).c(); //Long inside a NBTNumber + } else if (value instanceof NBTTagFloat) { + return ((NBTTagFloat) value).h(); //Float inside a NBTNumber + } else if (value instanceof NBTTagDouble) { + return ((NBTTagDouble) value).g(); //Double inside a NBTNumber + } else if (value instanceof NBTTagString) { + return ((NBTTagString) value).a_(); //String inside the NBTTagString + } else if (value instanceof NBTTagList || value instanceof NBTTagCompound) { + return value; //No need to convert anything, these are registered by the addon. + } + } + return null; + } + + @Override + public void removePathfinderGoal(Object entity, Class goalClass, boolean isTargetSelector) { + if (entity instanceof EntityInsentient) { + ((EntityInsentient) entity).setGoalTarget(null); + if (isTargetSelector) { + Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).targetSelector)).iterator(); + while (goals.hasNext()) { + Object goal = goals.next(); + if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { + goals.remove(); + } + } + } else { + Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).goalSelector)).iterator(); + while (goals.hasNext()) { + Object goal = goals.next(); + if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { + goals.remove(); + } + } + } + } + } + + @Override + public void addPathfinderGoal(Object entity, int priority, Object goal, boolean isTargetSelector) { + if (entity instanceof EntityInsentient && goal instanceof PathfinderGoal) { + if (isTargetSelector) + ((EntityInsentient) entity).targetSelector.a(priority, (PathfinderGoal) goal); + else + ((EntityInsentient) entity).goalSelector.a(priority, (PathfinderGoal) goal); + } + } + + @Override + public void registerCompoundClassInfo() { + Classes.registerClass(new ClassInfo(NBTTagCompound.class, "compound").user("((nbt)?( ?tag)?) ?compounds?").name("NBT Compound").changer(new Changer() { + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.SET) { + return CollectionUtils.array(String[].class, NBTTagCompound[].class); + } + return null; + } + + @Override + public void change(NBTTagCompound[] NBT, @Nullable Object[] delta, ChangeMode mode) { + if (mode == ChangeMode.SET) { + if (delta[0] instanceof NBTTagCompound) { + NBT[0] = (NBTTagCompound) delta[0]; + } else { + NBTTagCompound parsedNBT = null; + parsedNBT = parseRawNBT((String) delta[0]); + NBT[0] = parsedNBT; + } + } else if (mode == ChangeMode.ADD) { + if (delta[0] instanceof String) { + NBTTagCompound parsedNBT = null; + parsedNBT = parseRawNBT((String) delta[0]); + addToCompound(NBT[0], parsedNBT); + } else { + addToCompound(NBT[0], delta[0]); + } + } else if (mode == ChangeMode.REMOVE) { + if (delta[0] instanceof NBTTagCompound) + return; + for (Object s : delta) { + NBT[0].remove((String) s); + } + } + } + }).parser(new Parser() { + + @Override + public String getVariableNamePattern() { + return ".+"; + } + + @Override + @Nullable + public NBTTagCompound parse(String rawNBT, ParseContext context) { + if (rawNBT.startsWith("nbt:{") && rawNBT.endsWith("}")) { + NBTTagCompound NBT = null; + NBT = parseRawNBT(rawNBT.substring(4)); + return NBT; + } + return null; + } + + @Override + public String toString(NBTTagCompound compound, int arg1) { + return compound.toString(); + } + + @Override + public String toVariableNameString(NBTTagCompound compound) { + return "nbt:" + compound.toString(); + } + }).serializer(new Serializer() { + + @Override + public Fields serialize(NBTTagCompound compound) throws NotSerializableException { + Fields f = new Fields(); + f.putObject("asString", compound.toString()); + return f; + } + + @Override + public void deserialize(NBTTagCompound compound, Fields f) throws StreamCorruptedException, NotSerializableException { + assert false; + } + + @Override + protected boolean canBeInstantiated() { + return false; + } + + @Override + protected NBTTagCompound deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { + String s = fields.getObject("asString", String.class); + NBTTagCompound compound = null; + compound = parseRawNBT(s); + return compound; + } + + @Override + @Nullable + public NBTTagCompound deserialize(String s) { + NBTTagCompound compound = null; + compound = parseRawNBT(s); + return compound; + } + + @Override + public boolean mustSyncDeserialization() { + return true; + } + })); + + } + + @Override + public void registerNBTListClassInfo() { + Classes.registerClass(new ClassInfo(NBTTagList.class, "nbtlist").user("nbt ?list ?(tag)?").name("NBT List").changer(new Changer() { + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.SET || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + return CollectionUtils.array(Float[].class, Double[].class, String[].class, NBTTagCompound[].class, Integer[].class, NBTTagList[].class); + } + return null; + } + + @Override + public void change(NBTTagList[] nbtList, @Nullable Object[] delta, ChangeMode mode) { + int typeId = 0; + if (delta instanceof Byte[]) { + typeId = 1; + } else if (delta instanceof Short[]) { + typeId = 2; + } else if (delta instanceof Integer[]) { + typeId = 3; + } else if (delta instanceof Long[]) { + typeId = 4; + } else if (delta instanceof Float[]) { + typeId = 5; + } else if (delta instanceof Double[]) { + typeId = 6; + } else if (delta instanceof String[]) { + typeId = 8; + } else if (delta instanceof NBTTagList[]) { + typeId = 9; + } else if (delta instanceof NBTTagCompound[]) { + typeId = 10; + } else { + return; + } + if (mode == ChangeMode.SET) { + if (typeId == 9) + nbtList[0] = (NBTTagList) delta[0]; + } else if (mode == ChangeMode.ADD) { + if (getContentsId(nbtList[0]) == typeId) { + if (delta[0] instanceof Number) + addToList(nbtList, convertToNBT((Number) delta[0])); + else if (delta[0] instanceof String) + addToList(nbtList, convertToNBT((String) delta[0])); + else if (delta[0] instanceof NBTTagCompound || delta[0] instanceof NBTTagList) + addToList(nbtList, delta[0]); + } + } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + nbtList[0] = new NBTTagList(); + } + } + }).parser(new Parser() { + + @Override + public String getVariableNamePattern() { + return ".+"; + } + + @Override + @Nullable + public NBTTagList parse(String listString, ParseContext context) { + if (listString.startsWith("[") && listString.endsWith("]")) { + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:[0:" + listString.substring(1) + "}"); + NBTTagList parsedList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return parsedList; + } + return null; + } + + @Override + public String toString(NBTTagList nbtList, int arg1) { + return nbtList.toString(); + } + + @Override + public String toVariableNameString(NBTTagList nbtList) { + return nbtList.toString(); + } + }).serializer(new Serializer() { + + @Override + public Fields serialize(NBTTagList nbtList) throws NotSerializableException { + Fields f = new Fields(); + f.putObject("asString", nbtList.toString()); + return f; + } + + @Override + public void deserialize(NBTTagList nbtList, Fields f) throws StreamCorruptedException, NotSerializableException { + assert false; + } + + @Override + protected boolean canBeInstantiated() { + return false; + } + + @Override + protected NBTTagList deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { + String s = fields.getObject("asString", String.class); + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:" + s + "}"); + NBTTagList nbtList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return nbtList; + } + + @Override + @Nullable + public NBTTagList deserialize(String s) { + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:" + s + "}"); + NBTTagList nbtList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return nbtList; + } + + @Override + public boolean mustSyncDeserialization() { + return true; + } + })); + } + + @Override + public NBTTagCompound getEntityNBT(Entity entity) { + net.minecraft.server.v1_8_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + NBTTagCompound NBT = new NBTTagCompound(); + nmsEntity.e(NBT); + return NBT; + } + + @Override + public NBTTagCompound getTileNBT(Block block) { + NBTTagCompound NBT = new NBTTagCompound(); + World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); + TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); + if (tileEntity == null) + return null; + tileEntity.b(NBT); + return NBT; + } + + @Override + public NBTTagCompound getItemNBT(ItemStack itemStack) { + if (itemStack.getType() == Material.AIR) + return null; + NBTTagCompound itemNBT = CraftItemStack.asNMSCopy(itemStack).getTag(); + if (String.valueOf(itemNBT).equals("{}")) + itemNBT = null; + return itemNBT; + } + + @Override + public void setEntityNBT(Entity entity, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + net.minecraft.server.v1_8_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + nmsEntity.f((NBTTagCompound) newCompound); + } + } + + @Override + public void setTileNBT(Block block, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); + TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); + if (tileEntity == null) + return; + tileEntity.a((NBTTagCompound) newCompound); + tileEntity.update(); + nmsWorld.notify(tileEntity.getPosition()); + } + } + + @Override + public ItemStack getItemWithNBT(ItemStack itemStack, Object compound) { + net.minecraft.server.v1_8_R1.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); + if (compound instanceof NBTTagCompound && itemStack != null) { + if (itemStack.getType() == Material.AIR) + return null; + if (((NBTTagCompound) compound).isEmpty()) + return itemStack; + nmsItem.setTag((NBTTagCompound) compound); + ItemStack newItem = CraftItemStack.asBukkitCopy(nmsItem); + return newItem; + } else if (compound == null) { + nmsItem.setTag(null); + ItemStack newItem = CraftItemStack.asBukkitCopy(nmsItem); + return newItem; + } + return itemStack; + } + + @Override + public NBTTagCompound getFileNBT(File file) { + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + } catch (FileNotFoundException ex) { + return null; //File doesn't exist. + } + NBTTagCompound fileNBT = null; + try { + fileNBT = NBTCompressedStreamTools.a(fis); + fis.close(); + } catch (IOException ex) { + if (ex instanceof EOFException) { + ; //Nothing. + } else { + ex.printStackTrace(); + } + } + return fileNBT; + } + + @Override + public void setFileNBT(File file, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + OutputStream os = null; + try { + os = new FileOutputStream(file); + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + } + try { + NBTCompressedStreamTools.a((NBTTagCompound) newCompound, os); + os.close(); + } catch (IOException ex) { + if (ex instanceof EOFException) { + ; //Ignore, just end of the file + } else { + ex.printStackTrace(); + } + } + } + } + + public NBTBase convertToNBT(Number number) { + if (number instanceof Byte) { + return new NBTTagByte((byte) number); + } else if (number instanceof Short) { + return new NBTTagShort((short) number); + } else if (number instanceof Integer) { + return new NBTTagInt((int) number); + } else if (number instanceof Long) { + return new NBTTagLong((long) number); + } else if (number instanceof Float) { + return new NBTTagFloat((float) number); + } else if (number instanceof Double) { + return new NBTTagDouble((double) number); + } + return null; + } + + public NBTTagString convertToNBT(String string) { + return new NBTTagString(string); + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/util/NMS_v1_8_R2.java b/src/me/TheBukor/SkStuff/util/NMS_v1_8_R2.java index b45bd96..1f0d8f3 100644 --- a/src/me/TheBukor/SkStuff/util/NMS_v1_8_R2.java +++ b/src/me/TheBukor/SkStuff/util/NMS_v1_8_R2.java @@ -1,439 +1,560 @@ -package me.TheBukor.SkStuff.util; - -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.annotation.Nullable; - -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.v1_8_R2.CraftWorld; -import org.bukkit.craftbukkit.v1_8_R2.entity.CraftEntity; -import org.bukkit.craftbukkit.v1_8_R2.inventory.CraftItemStack; -import org.bukkit.entity.Entity; -import org.bukkit.inventory.ItemStack; - -import ch.njol.skript.Skript; -import ch.njol.skript.classes.Changer; -import ch.njol.skript.classes.ClassInfo; -import ch.njol.skript.classes.Parser; -import ch.njol.skript.lang.ParseContext; -import ch.njol.skript.registrations.Classes; -import ch.njol.util.coll.CollectionUtils; -import net.minecraft.server.v1_8_R2.BlockPosition; -import net.minecraft.server.v1_8_R2.EntityInsentient; -import net.minecraft.server.v1_8_R2.MojangsonParseException; -import net.minecraft.server.v1_8_R2.MojangsonParser; -import net.minecraft.server.v1_8_R2.NBTBase; -import net.minecraft.server.v1_8_R2.NBTCompressedStreamTools; -import net.minecraft.server.v1_8_R2.NBTTagCompound; -import net.minecraft.server.v1_8_R2.NBTTagDouble; -import net.minecraft.server.v1_8_R2.NBTTagEnd; -import net.minecraft.server.v1_8_R2.NBTTagFloat; -import net.minecraft.server.v1_8_R2.NBTTagInt; -import net.minecraft.server.v1_8_R2.NBTTagList; -import net.minecraft.server.v1_8_R2.NBTTagString; -import net.minecraft.server.v1_8_R2.PathfinderGoal; -import net.minecraft.server.v1_8_R2.PathfinderGoalSelector; -import net.minecraft.server.v1_8_R2.TileEntity; -import net.minecraft.server.v1_8_R2.World; - -public class NMS_v1_8_R2 implements NMSInterface { - - @Override - public void addToCompound(Object compound, Object toAdd) { - if (compound instanceof NBTTagCompound && toAdd instanceof NBTTagCompound) { - ((NBTTagCompound) compound).a((NBTTagCompound) toAdd); - } - } - - @Override - public void removeFromCompound(Object compound, String ... toRemove) { - if (compound instanceof NBTTagCompound) { - ((NBTTagCompound) compound).remove(toRemove.toString()); //FIXME - } - } - - @Override - public Object parseRawNBT(String rawNBT) { - NBTTagCompound parsedNBT = null; - try { - parsedNBT = MojangsonParser.parse(rawNBT); - } catch (MojangsonParseException ex) { - Skript.warning("Error when parsing NBT - " + ex.getMessage()); - } - return parsedNBT; - } - - @Override - public int getContentsId(Object nbtList) { - if (nbtList instanceof NBTTagList) { - return ((NBTTagList) nbtList).f(); - } - return 0; - } - - @Override - public Object[] getContents(Object nbtList) { - if (nbtList instanceof NBTTagList) { - List contents = new ArrayList(); - for (int i = 0; i < ((NBTTagList) nbtList).size(); i++) { - if (getIndex(nbtList, i) != null) { - contents.add(getIndex(nbtList, i)); - } - } - return contents.toArray(); - } - return null; - } - - @Override - public void addToList(Object nbtList, Object toAdd) { - if (nbtList instanceof NBTTagList && toAdd instanceof NBTBase) { - ((NBTTagList) nbtList).add((NBTBase) toAdd); - } - } - - @Override - public void removeFromList(Object nbtList, int index) { - if (nbtList instanceof NBTTagList) { - ((NBTTagList) nbtList).a(index); - } - } - - @Override - public void setIndex(Object nbtList, int index, Object toSet) { - if (nbtList instanceof NBTTagList && toSet instanceof NBTBase) { - ((NBTTagList) nbtList).a(index, (NBTBase) toSet); - } - } - - @Override - public Object getIndex(Object nbtList, int index) { - if (nbtList instanceof NBTTagList) { - NBTBase value = ((NBTTagList) nbtList).g(index); - if (value instanceof NBTTagEnd) - return null; - else - return value; - } - return null; - } - - @Override - public void removePathfinderGoal(Object entity, Class goalClass, boolean isTargetSelector) { - if (entity instanceof EntityInsentient) { - ((EntityInsentient) entity).setGoalTarget(null); - if (isTargetSelector) { - Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).targetSelector)).iterator(); - while (goals.hasNext()) { - Object goal = goals.next(); - if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { - goals.remove(); - } - } - } else { - Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).goalSelector)).iterator(); - while (goals.hasNext()) { - Object goal = goals.next(); - if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { - goals.remove(); - } - } - } - } - } - - @Override - public void addPathfinderGoal(Object entity, int priority, Object goal, boolean isTargetSelector) { - if (entity instanceof EntityInsentient && goal instanceof PathfinderGoal) { - if (isTargetSelector) - ((EntityInsentient) entity).targetSelector.a(priority, (PathfinderGoal) goal); - else - ((EntityInsentient) entity).goalSelector.a(priority, (PathfinderGoal) goal); - } - } - - @Override - public void registerCompoundClassInfo() { - Classes.registerClass(new ClassInfo(NBTTagCompound.class, "compound").user("((nbt)?( ?tag)?) ?compounds?").name("NBT Compound").changer(new Changer() { - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.SET) { - return CollectionUtils.array(String[].class, NBTTagCompound[].class); - } - return null; - } - - @Override - public void change(NBTTagCompound[] NBT, @Nullable Object[] delta, ChangeMode mode) { - if (mode == ChangeMode.SET) { - if (delta[0] instanceof NBTTagCompound) { - NBT[0] = (NBTTagCompound) delta[0]; - } else { - NBTTagCompound parsedNBT = (NBTTagCompound) parseRawNBT((String) delta[0]); - NBT[0] = parsedNBT; - } - } else if (mode == ChangeMode.ADD) { - if (delta[0] instanceof String) { - NBTTagCompound parsedNBT = (NBTTagCompound) parseRawNBT((String) delta[0]); - addToCompound(NBT[0], parsedNBT); - } else { - addToCompound(NBT[0], delta[0]); - } - } else if (mode == ChangeMode.REMOVE) { - if (delta[0] instanceof NBTTagCompound) - return; - for (Object s : delta) { - NBT[0].remove((String) s); - } - } - } - }).parser(new Parser() { - - @Override - public String getVariableNamePattern() { - return ".+"; - } - - @Override - @Nullable - public NBTTagCompound parse(String rawNBT, ParseContext context) { - if (rawNBT.startsWith("nbt:{") && rawNBT.endsWith("}")) { - rawNBT.substring(4); - NBTTagCompound NBT = (NBTTagCompound) parseRawNBT(rawNBT); - if (NBT.toString().equals("{}")) { - return null; - } - return NBT; - } - return null; - } - - @Override - public String toString(NBTTagCompound compound, int arg1) { - return compound.toString(); - } - - @Override - public String toVariableNameString(NBTTagCompound compound) { - return "nbt:" + compound.toString(); - } - })); - - } - - @Override - public void registerNBTListClassInfo() { - Classes.registerClass(new ClassInfo(NBTTagList.class, "nbtlist").user("nbt ?list ?(tag)?").name("NBT List").changer(new Changer() { - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.SET || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { - return CollectionUtils.array(Float[].class, Double[].class, String[].class, NBTTagCompound[].class, Integer[].class, NBTTagList[].class); - } - return null; - } - - @Override - public void change(NBTTagList[] nbtList, @Nullable Object[] delta, ChangeMode mode) { - int typeId = 0; - if (delta instanceof Float[]) { - typeId = 5; - } else if (delta instanceof Double[]) { - typeId = 6; - } else if (delta instanceof String[]) { - typeId = 8; - } else if (delta instanceof NBTTagList[]) { - typeId = 9; - } else if (delta instanceof NBTTagCompound[]) { - typeId = 10; - } else if (delta instanceof Integer[]) { - typeId = 11; - } else { - return; - } - if (mode == ChangeMode.SET) { - if (typeId == 9) - nbtList[0] = (NBTTagList) delta[0]; - } else if (mode == ChangeMode.ADD) { - if (getContentsId(nbtList[0]) == typeId) { - if (typeId == 5) { - NBTTagFloat floatTag = new NBTTagFloat((float) delta[0]); - addToList(nbtList[0], floatTag); - } else if (typeId == 6) { - NBTTagDouble doubleTag = new NBTTagDouble((double) delta[0]); - addToList(nbtList[0], doubleTag); - } else if (typeId == 8) { - NBTTagString stringTag = new NBTTagString((String) delta [0]); - addToList(nbtList[0], stringTag); - } else if (typeId == 10) { - addToList(nbtList[0], delta[0]); - } else if (typeId == 11) { - NBTTagInt intTag = new NBTTagInt((int) delta[0]); - addToList(nbtList[0], intTag); - } - } - } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { - nbtList[0] = new NBTTagList(); - } - } - }).parser(new Parser() { - - @Override - public String getVariableNamePattern() { - return ".+"; - } - - @Override - @Nullable - public NBTTagList parse(String ignored, ParseContext context) { - return null; - } - - @Override - public String toString(NBTTagList nbtList, int arg1) { - return nbtList.toString(); - } - - @Override - public String toVariableNameString(NBTTagList nbtList) { - return nbtList.toString(); - } - })); - } - - @Override - public Object getEntityNBT(Entity entity) { - net.minecraft.server.v1_8_R2.Entity nmsEntity = ((CraftEntity) entity).getHandle(); - NBTTagCompound NBT = new NBTTagCompound(); - nmsEntity.e(NBT); - return NBT; - } - - @Override - public Object getTileNBT(Block block) { - NBTTagCompound NBT = new NBTTagCompound(); - World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); - TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); - if (tileEntity == null) - return null; - tileEntity.b(NBT); - return NBT; - } - - @Override - public Object getItemNBT(ItemStack itemStack) { - if (itemStack.getType() == Material.AIR) - return null; - NBTTagCompound NBT = new NBTTagCompound(); - net.minecraft.server.v1_8_R2.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); - NBT = nmsItem.getTag(); - if (NBT == null || NBT.toString().equals("{}")) //Null or empty. - return null; - return new Object[] { NBT }; - } - - @Override - public void setEntityNBT(Entity entity, Object newCompound) { - if (newCompound instanceof NBTTagCompound) { - net.minecraft.server.v1_8_R2.Entity nmsEntity = ((CraftEntity) entity).getHandle(); - nmsEntity.f((NBTTagCompound) newCompound); - } - } - - @Override - public void setTileNBT(Block block, Object newCompound) { - if (newCompound instanceof NBTTagCompound) { - World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); - TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); - if (tileEntity == null) - return; - tileEntity.a((NBTTagCompound) newCompound); - tileEntity.update(); - nmsWorld.notify(tileEntity.getPosition()); - } - } - - @Override - public ItemStack getItemWithNBT(ItemStack itemStack, Object compound) { - if (compound instanceof NBTTagCompound) { - if (itemStack.getType() == Material.AIR || itemStack == null) - return null; - if (compound == null || compound.toString().equals("{}")) - return itemStack; - net.minecraft.server.v1_8_R2.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); - nmsItem.setTag((NBTTagCompound) compound); - ItemStack newItem = CraftItemStack.asCraftMirror(nmsItem); - return newItem; - } - return null; - } - - @Override - public Object getFileNBT(File file) { - FileInputStream fis = null; - try { - fis = new FileInputStream(file); - } catch (FileNotFoundException ex) { - return null; //File doesn't exist. - } - NBTTagCompound fileNBT = null; - try { - fileNBT = NBTCompressedStreamTools.a(fis); - fis.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - try { - fis.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - return fileNBT; - } - - @Override - public void setFileNBT(File file, Object newCompound) { - OutputStream os = null; - try { - os = new FileOutputStream(file); - } catch (FileNotFoundException ex) { - ex.printStackTrace(); - } - try { - NBTCompressedStreamTools.a((NBTTagCompound) newCompound, os); - os.close(); - } catch (Exception ex) { - if (ex instanceof EOFException) { - ; //Ignore, just end of the file - } else { - ex.printStackTrace(); - } - } finally { - try { - os.close(); - } catch (Exception ex) { - if (ex instanceof EOFException) { - ; //Ignore. - } else { - ex.printStackTrace(); - } - } - } - } +package me.TheBukor.SkStuff.util; + +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.OutputStream; +import java.io.StreamCorruptedException; +import java.util.Iterator; +import java.util.List; + +import javax.annotation.Nullable; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_8_R2.CraftWorld; +import org.bukkit.craftbukkit.v1_8_R2.entity.CraftEntity; +import org.bukkit.craftbukkit.v1_8_R2.inventory.CraftItemStack; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; + +import ch.njol.skript.Skript; +import ch.njol.skript.classes.Changer; +import ch.njol.skript.classes.ClassInfo; +import ch.njol.skript.classes.Parser; +import ch.njol.skript.classes.Serializer; +import ch.njol.skript.lang.ParseContext; +import ch.njol.skript.registrations.Classes; +import ch.njol.util.coll.CollectionUtils; +import ch.njol.yggdrasil.Fields; +import net.minecraft.server.v1_8_R2.BlockPosition; +import net.minecraft.server.v1_8_R2.EntityInsentient; +import net.minecraft.server.v1_8_R2.MojangsonParseException; +import net.minecraft.server.v1_8_R2.MojangsonParser; +import net.minecraft.server.v1_8_R2.NBTBase; +import net.minecraft.server.v1_8_R2.NBTCompressedStreamTools; +import net.minecraft.server.v1_8_R2.NBTTagByte; +import net.minecraft.server.v1_8_R2.NBTTagCompound; +import net.minecraft.server.v1_8_R2.NBTTagDouble; +import net.minecraft.server.v1_8_R2.NBTTagFloat; +import net.minecraft.server.v1_8_R2.NBTTagInt; +import net.minecraft.server.v1_8_R2.NBTTagList; +import net.minecraft.server.v1_8_R2.NBTTagLong; +import net.minecraft.server.v1_8_R2.NBTTagShort; +import net.minecraft.server.v1_8_R2.NBTTagString; +import net.minecraft.server.v1_8_R2.PathfinderGoal; +import net.minecraft.server.v1_8_R2.PathfinderGoalSelector; +import net.minecraft.server.v1_8_R2.TileEntity; +import net.minecraft.server.v1_8_R2.World; + +public class NMS_v1_8_R2 implements NMSInterface { + + @Override + public void addToCompound(Object compound, Object toAdd) { + if (compound instanceof NBTTagCompound && toAdd instanceof NBTTagCompound) { + ((NBTTagCompound) compound).a((NBTTagCompound) toAdd); + } + } + + @Override + public void removeFromCompound(Object compound, String ... toRemove) { + if (compound instanceof NBTTagCompound) { + for (String s : toRemove) { + ((NBTTagCompound) compound).remove(s); + } + } + } + + @Override + public NBTTagCompound parseRawNBT(String rawNBT) { + NBTTagCompound parsedNBT = null; + try { + parsedNBT = MojangsonParser.parse(rawNBT); + } catch (MojangsonParseException ex) { + Skript.warning("Error when parsing NBT - " + ex.getMessage()); + } + return parsedNBT; + } + + @Override + public int getContentsId(Object nbtList) { + if (nbtList instanceof NBTTagList) { + return ((NBTTagList) nbtList).f(); + } + return 0; + } + + @Override + public Object[] getContents(Object nbtList) { + if (nbtList instanceof NBTTagList) { + Object[] contents = new Object[((NBTTagList) nbtList).size()]; + for (int i = 0; i < ((NBTTagList) nbtList).size(); i++) { + if (getIndex(nbtList, i) != null) { + contents[i] = getIndex(nbtList, i); + } + } + return contents; + } + return null; + } + + @Override + public void addToList(Object nbtList, Object toAdd) { + if (nbtList instanceof NBTTagList && toAdd instanceof NBTBase) { + ((NBTTagList) nbtList).add((NBTBase) toAdd); + } + } + + @Override + public void removeFromList(Object nbtList, int index) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + ((NBTTagList) nbtList).a(index); + } + } + + @Override + public void setIndex(Object nbtList, int index, Object toSet) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + if (toSet instanceof NBTBase) { + ((NBTTagList) nbtList).a(index, (NBTBase) toSet); + } else if (toSet instanceof Number) { + ((NBTTagList) nbtList).a(index, convertToNBT((Number) toSet)); + } else if (toSet instanceof String) { + ((NBTTagList) nbtList).a(index, convertToNBT((String) toSet)); + } + } + } + + @Override + public Object getIndex(Object nbtList, int index) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + NBTBase value = ((NBTTagList) nbtList).g(index); + if (value instanceof NBTTagByte) { + return ((NBTTagByte) value).f(); //Byte stored inside a NBTNumber + } else if (value instanceof NBTTagShort) { + return ((NBTTagShort) value).e(); //Short inside a NBTNumber + } else if (value instanceof NBTTagInt) { + return ((NBTTagInt) value).d(); //Integer inside a NBTNumber + } else if (value instanceof NBTTagLong) { + return ((NBTTagLong) value).c(); //Long inside a NBTNumber + } else if (value instanceof NBTTagFloat) { + return ((NBTTagFloat) value).h(); //Float inside a NBTNumber + } else if (value instanceof NBTTagDouble) { + return ((NBTTagDouble) value).g(); //Double inside a NBTNumber + } else if (value instanceof NBTTagString) { + return ((NBTTagString) value).a_(); //String inside the NBTTagString + } else if (value instanceof NBTTagList || value instanceof NBTTagCompound) { + return value; //No need to convert anything, these are registered by the addon. + } + } + return null; + } + + @Override + public void removePathfinderGoal(Object entity, Class goalClass, boolean isTargetSelector) { + if (entity instanceof EntityInsentient) { + ((EntityInsentient) entity).setGoalTarget(null); + if (isTargetSelector) { + Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).targetSelector)).iterator(); + while (goals.hasNext()) { + Object goal = goals.next(); + if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { + goals.remove(); + } + } + } else { + Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).goalSelector)).iterator(); + while (goals.hasNext()) { + Object goal = goals.next(); + if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { + goals.remove(); + } + } + } + } + } + + @Override + public void addPathfinderGoal(Object entity, int priority, Object goal, boolean isTargetSelector) { + if (entity instanceof EntityInsentient && goal instanceof PathfinderGoal) { + if (isTargetSelector) + ((EntityInsentient) entity).targetSelector.a(priority, (PathfinderGoal) goal); + else + ((EntityInsentient) entity).goalSelector.a(priority, (PathfinderGoal) goal); + } + } + + @Override + public void registerCompoundClassInfo() { + Classes.registerClass(new ClassInfo(NBTTagCompound.class, "compound").user("((nbt)?( ?tag)?) ?compounds?").name("NBT Compound").changer(new Changer() { + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.SET) { + return CollectionUtils.array(String[].class, NBTTagCompound[].class); + } + return null; + } + + @Override + public void change(NBTTagCompound[] NBT, @Nullable Object[] delta, ChangeMode mode) { + if (mode == ChangeMode.SET) { + if (delta[0] instanceof NBTTagCompound) { + NBT[0] = (NBTTagCompound) delta[0]; + } else { + NBTTagCompound parsedNBT = null; + parsedNBT = parseRawNBT((String) delta[0]); + NBT[0] = parsedNBT; + } + } else if (mode == ChangeMode.ADD) { + if (delta[0] instanceof String) { + NBTTagCompound parsedNBT = null; + parsedNBT = parseRawNBT((String) delta[0]); + addToCompound(NBT[0], parsedNBT); + } else { + addToCompound(NBT[0], delta[0]); + } + } else if (mode == ChangeMode.REMOVE) { + if (delta[0] instanceof NBTTagCompound) + return; + for (Object s : delta) { + NBT[0].remove((String) s); + } + } + } + }).parser(new Parser() { + + @Override + public String getVariableNamePattern() { + return ".+"; + } + + @Override + @Nullable + public NBTTagCompound parse(String rawNBT, ParseContext context) { + if (rawNBT.startsWith("nbt:{") && rawNBT.endsWith("}")) { + NBTTagCompound NBT = null; + NBT = parseRawNBT(rawNBT.substring(4)); + return NBT; + } + return null; + } + + @Override + public String toString(NBTTagCompound compound, int arg1) { + return compound.toString(); + } + + @Override + public String toVariableNameString(NBTTagCompound compound) { + return "nbt:" + compound.toString(); + } + }).serializer(new Serializer() { + + @Override + public Fields serialize(NBTTagCompound compound) throws NotSerializableException { + Fields f = new Fields(); + f.putObject("asString", compound.toString()); + return f; + } + + @Override + public void deserialize(NBTTagCompound compound, Fields f) throws StreamCorruptedException, NotSerializableException { + assert false; + } + + @Override + protected boolean canBeInstantiated() { + return false; + } + + @Override + protected NBTTagCompound deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { + String s = fields.getObject("asString", String.class); + NBTTagCompound compound = null; + compound = parseRawNBT(s); + return compound; + } + + @Override + @Nullable + public NBTTagCompound deserialize(String s) { + NBTTagCompound compound = null; + compound = parseRawNBT(s); + return compound; + } + + @Override + public boolean mustSyncDeserialization() { + return true; + } + })); + + } + + @Override + public void registerNBTListClassInfo() { + Classes.registerClass(new ClassInfo(NBTTagList.class, "nbtlist").user("nbt ?list ?(tag)?").name("NBT List").changer(new Changer() { + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.SET || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + return CollectionUtils.array(Float[].class, Double[].class, String[].class, NBTTagCompound[].class, Integer[].class, NBTTagList[].class); + } + return null; + } + + @Override + public void change(NBTTagList[] nbtList, @Nullable Object[] delta, ChangeMode mode) { + int typeId = 0; + if (delta instanceof Byte[]) { + typeId = 1; + } else if (delta instanceof Short[]) { + typeId = 2; + } else if (delta instanceof Integer[]) { + typeId = 3; + } else if (delta instanceof Long[]) { + typeId = 4; + } else if (delta instanceof Float[]) { + typeId = 5; + } else if (delta instanceof Double[]) { + typeId = 6; + } else if (delta instanceof String[]) { + typeId = 8; + } else if (delta instanceof NBTTagList[]) { + typeId = 9; + } else if (delta instanceof NBTTagCompound[]) { + typeId = 10; + } else { + return; + } + if (mode == ChangeMode.SET) { + if (typeId == 9) + nbtList[0] = (NBTTagList) delta[0]; + } else if (mode == ChangeMode.ADD) { + if (getContentsId(nbtList[0]) == typeId) { + if (delta[0] instanceof Number) + addToList(nbtList, convertToNBT((Number) delta[0])); + else if (delta[0] instanceof String) + addToList(nbtList, convertToNBT((String) delta[0])); + else if (delta[0] instanceof NBTTagCompound || delta[0] instanceof NBTTagList) + addToList(nbtList, delta[0]); + } + } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + nbtList[0] = new NBTTagList(); + } + } + }).parser(new Parser() { + + @Override + public String getVariableNamePattern() { + return ".+"; + } + + @Override + @Nullable + public NBTTagList parse(String listString, ParseContext context) { + if (listString.startsWith("[") && listString.endsWith("]")) { + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:[0:" + listString.substring(1) + "}"); + NBTTagList parsedList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return parsedList; + } + return null; + } + + @Override + public String toString(NBTTagList nbtList, int arg1) { + return nbtList.toString(); + } + + @Override + public String toVariableNameString(NBTTagList nbtList) { + return nbtList.toString(); + } + }).serializer(new Serializer() { + + @Override + public Fields serialize(NBTTagList nbtList) throws NotSerializableException { + Fields f = new Fields(); + f.putObject("asString", nbtList.toString()); + return f; + } + + @Override + public void deserialize(NBTTagList nbtList, Fields f) throws StreamCorruptedException, NotSerializableException { + assert false; + } + + @Override + protected boolean canBeInstantiated() { + return false; + } + + @Override + protected NBTTagList deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { + String s = fields.getObject("asString", String.class); + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:" + s + "}"); + NBTTagList nbtList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return nbtList; + } + + @Override + @Nullable + public NBTTagList deserialize(String s) { + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:" + s + "}"); + NBTTagList nbtList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return nbtList; + } + + @Override + public boolean mustSyncDeserialization() { + return true; + } + })); + } + + @Override + public NBTTagCompound getEntityNBT(Entity entity) { + net.minecraft.server.v1_8_R2.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + NBTTagCompound NBT = new NBTTagCompound(); + nmsEntity.e(NBT); + return NBT; + } + + @Override + public NBTTagCompound getTileNBT(Block block) { + NBTTagCompound NBT = new NBTTagCompound(); + World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); + TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); + if (tileEntity == null) + return null; + tileEntity.b(NBT); + return NBT; + } + + @Override + public NBTTagCompound getItemNBT(ItemStack itemStack) { + if (itemStack.getType() == Material.AIR) + return null; + NBTTagCompound itemNBT = CraftItemStack.asNMSCopy(itemStack).getTag(); + if (String.valueOf(itemNBT).equals("{}")) + itemNBT = null; + return itemNBT; + } + + @Override + public void setEntityNBT(Entity entity, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + net.minecraft.server.v1_8_R2.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + nmsEntity.f((NBTTagCompound) newCompound); + } + } + + @Override + public void setTileNBT(Block block, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); + TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); + if (tileEntity == null) + return; + tileEntity.a((NBTTagCompound) newCompound); + tileEntity.update(); + nmsWorld.notify(tileEntity.getPosition()); + } + } + + @Override + public ItemStack getItemWithNBT(ItemStack itemStack, Object compound) { + net.minecraft.server.v1_8_R2.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); + if (compound instanceof NBTTagCompound && itemStack != null) { + if (itemStack.getType() == Material.AIR) + return null; + if (((NBTTagCompound) compound).isEmpty()) + return itemStack; + nmsItem.setTag((NBTTagCompound) compound); + ItemStack newItem = CraftItemStack.asBukkitCopy(nmsItem); + return newItem; + } else if (compound == null) { + nmsItem.setTag(null); + ItemStack newItem = CraftItemStack.asBukkitCopy(nmsItem); + return newItem; + } + return itemStack; + } + + @Override + public NBTTagCompound getFileNBT(File file) { + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + } catch (FileNotFoundException ex) { + return null; //File doesn't exist. + } + NBTTagCompound fileNBT = null; + try { + fileNBT = NBTCompressedStreamTools.a(fis); + fis.close(); + } catch (IOException ex) { + if (ex instanceof EOFException) { + ; //Nothing. + } else { + ex.printStackTrace(); + } + } + return fileNBT; + } + + @Override + public void setFileNBT(File file, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + OutputStream os = null; + try { + os = new FileOutputStream(file); + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + } + try { + NBTCompressedStreamTools.a((NBTTagCompound) newCompound, os); + os.close(); + } catch (IOException ex) { + if (ex instanceof EOFException) { + ; //Ignore, just end of the file + } else { + ex.printStackTrace(); + } + } + } + } + + public NBTBase convertToNBT(Number number) { + if (number instanceof Byte) { + return new NBTTagByte((byte) number); + } else if (number instanceof Short) { + return new NBTTagShort((short) number); + } else if (number instanceof Integer) { + return new NBTTagInt((int) number); + } else if (number instanceof Long) { + return new NBTTagLong((long) number); + } else if (number instanceof Float) { + return new NBTTagFloat((float) number); + } else if (number instanceof Double) { + return new NBTTagDouble((double) number); + } + return null; + } + + public NBTTagString convertToNBT(String string) { + return new NBTTagString(string); + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/util/NMS_v1_8_R3.java b/src/me/TheBukor/SkStuff/util/NMS_v1_8_R3.java index f8fcdc4..aec625f 100644 --- a/src/me/TheBukor/SkStuff/util/NMS_v1_8_R3.java +++ b/src/me/TheBukor/SkStuff/util/NMS_v1_8_R3.java @@ -1,588 +1,560 @@ -package me.TheBukor.SkStuff.util; - -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.NotSerializableException; -import java.io.OutputStream; -import java.io.StreamCorruptedException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.annotation.Nullable; - -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; -import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity; -import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; -import org.bukkit.entity.Entity; -import org.bukkit.inventory.ItemStack; - -import ch.njol.skript.Skript; -import ch.njol.skript.classes.Changer; -import ch.njol.skript.classes.ClassInfo; -import ch.njol.skript.classes.Parser; -import ch.njol.skript.classes.Serializer; -import ch.njol.skript.lang.ParseContext; -import ch.njol.skript.registrations.Classes; -import ch.njol.util.coll.CollectionUtils; -import ch.njol.yggdrasil.Fields; -import net.minecraft.server.v1_8_R3.BlockPosition; -import net.minecraft.server.v1_8_R3.EntityInsentient; -import net.minecraft.server.v1_8_R3.MojangsonParseException; -import net.minecraft.server.v1_8_R3.MojangsonParser; -import net.minecraft.server.v1_8_R3.NBTBase; -import net.minecraft.server.v1_8_R3.NBTCompressedStreamTools; -import net.minecraft.server.v1_8_R3.NBTTagByte; -import net.minecraft.server.v1_8_R3.NBTTagCompound; -import net.minecraft.server.v1_8_R3.NBTTagDouble; -import net.minecraft.server.v1_8_R3.NBTTagEnd; -import net.minecraft.server.v1_8_R3.NBTTagFloat; -import net.minecraft.server.v1_8_R3.NBTTagInt; -import net.minecraft.server.v1_8_R3.NBTTagList; -import net.minecraft.server.v1_8_R3.NBTTagLong; -import net.minecraft.server.v1_8_R3.NBTTagShort; -import net.minecraft.server.v1_8_R3.NBTTagString; -import net.minecraft.server.v1_8_R3.PathfinderGoal; -import net.minecraft.server.v1_8_R3.PathfinderGoalSelector; -import net.minecraft.server.v1_8_R3.TileEntity; -import net.minecraft.server.v1_8_R3.World; - -public class NMS_v1_8_R3 implements NMSInterface { - - @Override - public void addToCompound(Object compound, Object toAdd) { - if (compound instanceof NBTTagCompound && toAdd instanceof NBTTagCompound) { - ((NBTTagCompound) compound).a((NBTTagCompound) toAdd); - } - } - - @Override - public void removeFromCompound(Object compound, String ... toRemove) { - if (compound instanceof NBTTagCompound) { - for (String s : toRemove) { - ((NBTTagCompound) compound).remove(s); - } - } - } - - @Override - public Object parseRawNBT(String rawNBT) { - NBTTagCompound parsedNBT = null; - try { - parsedNBT = MojangsonParser.parse(rawNBT); - } catch (MojangsonParseException ex) { - Skript.warning("Error when parsing NBT - " + ex.getMessage()); - } - return parsedNBT; - } - - @Override - public int getContentsId(Object nbtList) { - if (nbtList instanceof NBTTagList) { - return ((NBTTagList) nbtList).f(); - } - return 0; - } - - @Override - public Object[] getContents(Object nbtList) { - if (nbtList instanceof NBTTagList) { - List contents = new ArrayList(); - for (int i = 0; i < ((NBTTagList) nbtList).size(); i++) { - if (getIndex(nbtList, i) != null) { - contents.add(getIndex(nbtList, i)); - } - } - return contents.toArray(); - } - return null; - } - - @Override - public void addToList(Object nbtList, Object toAdd) { - if (nbtList instanceof NBTTagList && toAdd instanceof NBTBase) { - ((NBTTagList) nbtList).add((NBTBase) toAdd); - } - } - - @Override - public void removeFromList(Object nbtList, int index) { - if (nbtList instanceof NBTTagList) { - ((NBTTagList) nbtList).a(index); - } - } - - @Override - public void setIndex(Object nbtList, int index, Object toSet) { - if (nbtList instanceof NBTTagList) { - if (toSet instanceof NBTBase) { - ((NBTTagList) nbtList).a(index, (NBTBase) toSet); - } else { - if (toSet instanceof Byte) { - ((NBTTagList) nbtList).a(index, new NBTTagByte((byte) toSet)); - } else if (toSet instanceof Short) { - ((NBTTagList) nbtList).a(index, new NBTTagShort((short) toSet)); - } else if (toSet instanceof Integer) { - ((NBTTagList) nbtList).a(index, new NBTTagInt((int) toSet)); - } else if (toSet instanceof Long) { - ((NBTTagList) nbtList).a(index, new NBTTagLong((long) toSet)); - } else if (toSet instanceof Float) { - ((NBTTagList) nbtList).a(index, new NBTTagFloat((float) toSet)); - } else if (toSet instanceof Double) { - ((NBTTagList) nbtList).a(index, new NBTTagDouble((double) toSet)); - } else if (toSet instanceof String) { - ((NBTTagList) nbtList).a(index, new NBTTagString((String) toSet)); - } //No need to check for NBTTagList and NBTTagCompound, these extend NBTBase. - } - } - } - - @Override - public Object getIndex(Object nbtList, int index) { - if (nbtList instanceof NBTTagList) { - NBTBase value = ((NBTTagList) nbtList).g(index); - if (value instanceof NBTTagEnd) { - return null; - } else if (value instanceof NBTTagByte) { - return ((NBTTagByte) value).f(); //Byte stored inside a NBTNumber - } else if (value instanceof NBTTagShort) { - return ((NBTTagShort) value).e(); //Short inside a NBTNumber - } else if (value instanceof NBTTagInt) { - return ((NBTTagInt) value).d(); //Integer inside a NBTNumber - } else if (value instanceof NBTTagLong) { - return ((NBTTagLong) value).c(); //Long inside a NBTNumber - } else if (value instanceof NBTTagFloat) { - return ((NBTTagFloat) value).h(); //Float inside a NBTNumber - } else if (value instanceof NBTTagDouble) { - return ((NBTTagDouble) value).g(); //Double inside a NBTNumber - } else if (value instanceof NBTTagString) { - return ((NBTTagString) value).a_(); //String inside the NBTTagString - } else if (value instanceof NBTTagList || value instanceof NBTTagCompound) { - return value; //No need to convert anything, these are registered by the addon. - } - } - return null; - } - - @Override - public void removePathfinderGoal(Object entity, Class goalClass, boolean isTargetSelector) { - if (entity instanceof EntityInsentient) { - ((EntityInsentient) entity).setGoalTarget(null); - if (isTargetSelector) { - Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).targetSelector)).iterator(); - while (goals.hasNext()) { - Object goal = goals.next(); - if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { - goals.remove(); - } - } - } else { - Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).goalSelector)).iterator(); - while (goals.hasNext()) { - Object goal = goals.next(); - if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { - goals.remove(); - } - } - } - } - } - - @Override - public void addPathfinderGoal(Object entity, int priority, Object goal, boolean isTargetSelector) { - if (entity instanceof EntityInsentient && goal instanceof PathfinderGoal) { - if (isTargetSelector) - ((EntityInsentient) entity).targetSelector.a(priority, (PathfinderGoal) goal); - else - ((EntityInsentient) entity).goalSelector.a(priority, (PathfinderGoal) goal); - } - } - - @Override - public void registerCompoundClassInfo() { - Classes.registerClass(new ClassInfo(NBTTagCompound.class, "compound").user("((nbt)?( ?tag)?) ?compounds?").name("NBT Compound").changer(new Changer() { - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.SET) { - return CollectionUtils.array(String[].class, NBTTagCompound[].class); - } - return null; - } - - @Override - public void change(NBTTagCompound[] NBT, @Nullable Object[] delta, ChangeMode mode) { - if (mode == ChangeMode.SET) { - if (delta[0] instanceof NBTTagCompound) { - NBT[0] = (NBTTagCompound) delta[0]; - } else { - NBTTagCompound parsedNBT = (NBTTagCompound) parseRawNBT((String) delta[0]); - NBT[0] = parsedNBT; - } - } else if (mode == ChangeMode.ADD) { - if (delta[0] instanceof String) { - NBTTagCompound parsedNBT = (NBTTagCompound) parseRawNBT((String) delta[0]); - addToCompound(NBT[0], parsedNBT); - } else { - addToCompound(NBT[0], delta[0]); - } - } else if (mode == ChangeMode.REMOVE) { - if (delta[0] instanceof NBTTagCompound) - return; - for (Object s : delta) { - NBT[0].remove((String) s); - } - } - } - }).parser(new Parser() { - - @Override - public String getVariableNamePattern() { - return ".+"; - } - - @Override - @Nullable - public NBTTagCompound parse(String rawNBT, ParseContext context) { - if (rawNBT.startsWith("nbt:{") && rawNBT.endsWith("}")) { - Bukkit.broadcastMessage("rawNBT: \u00A72" + rawNBT.substring(4)); - NBTTagCompound NBT = (NBTTagCompound) parseRawNBT(rawNBT.substring(4)); - return NBT; - } - return null; - } - - @Override - public String toString(NBTTagCompound compound, int arg1) { - return compound.toString(); - } - - @Override - public String toVariableNameString(NBTTagCompound compound) { - return "nbt:" + compound.toString(); - } - }).serializer(new Serializer() { - - @Override - public Fields serialize(NBTTagCompound compound) throws NotSerializableException { - Fields f = new Fields(); - f.putObject("asString", compound.toString()); - return f; - } - - @Override - public void deserialize(NBTTagCompound compound, Fields f) throws StreamCorruptedException, NotSerializableException { - assert false; - } - - @Override - protected boolean canBeInstantiated() { - return false; - } - - @Override - protected NBTTagCompound deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { - String s = fields.getObject("asString", String.class); - NBTTagCompound compound = (NBTTagCompound) parseRawNBT(s); - return compound; - } - - @Override - @Nullable - public NBTTagCompound deserialize(String s) { - NBTTagCompound compound = (NBTTagCompound) parseRawNBT(s); - return compound; - } - - @Override - public boolean mustSyncDeserialization() { - return true; - } - })); - - } - - @Override - public void registerNBTListClassInfo() { - Classes.registerClass(new ClassInfo(NBTTagList.class, "nbtlist").user("nbt ?list ?(tag)?").name("NBT List").changer(new Changer() { - - @SuppressWarnings("unchecked") - @Override - @Nullable - public Class[] acceptChange(ChangeMode mode) { - if (mode == ChangeMode.ADD || mode == ChangeMode.SET || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { - return CollectionUtils.array(Float[].class, Double[].class, String[].class, NBTTagCompound[].class, Integer[].class, NBTTagList[].class); - } - return null; - } - - @Override - public void change(NBTTagList[] nbtList, @Nullable Object[] delta, ChangeMode mode) { - int typeId = 0; - if (delta instanceof Byte[]) { - typeId = 1; - } else if (delta instanceof Short[]) { - typeId = 2; - } else if (delta instanceof Integer[]) { - typeId = 3; - } else if (delta instanceof Long[]) { - typeId = 4; - } else if (delta instanceof Float[]) { - typeId = 5; - } else if (delta instanceof Double[]) { - typeId = 6; - } else if (delta instanceof String[]) { - typeId = 8; - } else if (delta instanceof NBTTagList[]) { - typeId = 9; - } else if (delta instanceof NBTTagCompound[]) { - typeId = 10; - } else { - return; - } - if (mode == ChangeMode.SET) { - if (typeId == 9) - nbtList[0] = (NBTTagList) delta[0]; - } else if (mode == ChangeMode.ADD) { - if (getContentsId(nbtList[0]) == typeId) { - if (typeId == 1) { - NBTTagByte byteTag = new NBTTagByte((byte) delta[0]); - addToList(nbtList[0], byteTag); - } else if (typeId == 2) { - NBTTagShort shortTag = new NBTTagShort((short) delta[0]); - addToList(nbtList[0], shortTag); - } else if (typeId == 3) { - NBTTagInt intTag = new NBTTagInt((int) delta[0]); - addToList(nbtList[0], intTag); - } else if (typeId == 4) { - NBTTagLong longTag = new NBTTagLong((long) delta[0]); - addToList(nbtList[0], longTag); - } else if (typeId == 5) { - NBTTagFloat floatTag = new NBTTagFloat((float) delta[0]); - addToList(nbtList[0], floatTag); - } else if (typeId == 6) { - NBTTagDouble doubleTag = new NBTTagDouble((double) delta[0]); - addToList(nbtList[0], doubleTag); - } else if (typeId == 8) { - NBTTagString stringTag = new NBTTagString((String) delta [0]); - addToList(nbtList[0], stringTag); - } else if (typeId == 9) { - addToList(nbtList[0], delta[0]); - } else if (typeId == 10) { - addToList(nbtList[0], delta[0]); - } - } - } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { - nbtList[0] = new NBTTagList(); - } - } - }).parser(new Parser() { - - @Override - public String getVariableNamePattern() { - return ".+"; - } - - @Override - @Nullable - public NBTTagList parse(String listString, ParseContext context) { - if (listString.startsWith("[") && listString.endsWith("]")) { - NBTTagCompound NBT = (NBTTagCompound) parseRawNBT("{SkStuffIsCool:[0:" + listString.substring(1) + "}"); - NBTTagList parsedList = (NBTTagList) NBT.get("SkStuffIsCool"); - return parsedList; - } - return null; - } - - @Override - public String toString(NBTTagList nbtList, int arg1) { - return nbtList.toString(); - } - - @Override - public String toVariableNameString(NBTTagList nbtList) { - return nbtList.toString(); - } - }).serializer(new Serializer() { - - @Override - public Fields serialize(NBTTagList nbtList) throws NotSerializableException { - Fields f = new Fields(); - f.putObject("asString", nbtList.toString()); - return f; - } - - @Override - public void deserialize(NBTTagList nbtList, Fields f) throws StreamCorruptedException, NotSerializableException { - assert false; - } - - @Override - protected boolean canBeInstantiated() { - return false; - } - - @Override - protected NBTTagList deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { - String s = fields.getObject("asString", String.class); - NBTTagCompound tempNBT = (NBTTagCompound) parseRawNBT("{SkStuffIsCool:" + s + "}"); - NBTTagList nbtList = (NBTTagList) tempNBT.get("SkStuffIsCool"); - return nbtList; - } - - @Override - @Nullable - public NBTTagList deserialize(String s) { - NBTTagCompound tempNBT = (NBTTagCompound) parseRawNBT("{SkStuffIsCool:" + s + "}"); - NBTTagList nbtList = (NBTTagList) tempNBT.get("SkStuffIsCool"); - return nbtList; - } - - @Override - public boolean mustSyncDeserialization() { - return true; - } - })); - } - - @Override - public Object getEntityNBT(Entity entity) { - net.minecraft.server.v1_8_R3.Entity nmsEntity = ((CraftEntity) entity).getHandle(); - NBTTagCompound NBT = new NBTTagCompound(); - nmsEntity.e(NBT); - return NBT; - } - - @Override - public Object getTileNBT(Block block) { - NBTTagCompound NBT = new NBTTagCompound(); - World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); - TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); - if (tileEntity == null) - return null; - tileEntity.b(NBT); - return NBT; - } - - @Override - public Object getItemNBT(ItemStack itemStack) { - if (itemStack.getType() == Material.AIR) - return null; - NBTTagCompound itemNBT = CraftItemStack.asNMSCopy(itemStack).getTag(); - Bukkit.broadcastMessage(String.valueOf(itemNBT)); - if (itemNBT.isEmpty()) - itemNBT = null; - return itemNBT; - } - - @Override - public void setEntityNBT(Entity entity, Object newCompound) { - if (newCompound instanceof NBTTagCompound) { - net.minecraft.server.v1_8_R3.Entity nmsEntity = ((CraftEntity) entity).getHandle(); - nmsEntity.f((NBTTagCompound) newCompound); - } - } - - @Override - public void setTileNBT(Block block, Object newCompound) { - if (newCompound instanceof NBTTagCompound) { - World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); - TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); - if (tileEntity == null) - return; - tileEntity.a((NBTTagCompound) newCompound); - tileEntity.update(); - nmsWorld.notify(tileEntity.getPosition()); - } - } - - @Override - public ItemStack getItemWithNBT(ItemStack itemStack, Object compound) { - net.minecraft.server.v1_8_R3.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); - if (compound instanceof NBTTagCompound && itemStack != null) { - if (itemStack.getType() == Material.AIR) - return null; - if (((NBTTagCompound) compound).isEmpty()) - return itemStack; - nmsItem.setTag((NBTTagCompound) compound); - ItemStack newItem = CraftItemStack.asBukkitCopy(nmsItem); - return newItem; - } else if (compound == null) { - nmsItem.setTag(null); - ItemStack newItem = CraftItemStack.asBukkitCopy(nmsItem); - return newItem; - } - return itemStack; - } - - @Override - public Object getFileNBT(File file) { - FileInputStream fis = null; - try { - fis = new FileInputStream(file); - } catch (FileNotFoundException ex) { - return null; //File doesn't exist. - } - NBTTagCompound fileNBT = null; - try { - fileNBT = NBTCompressedStreamTools.a(fis); - fis.close(); - } catch (IOException ex) { - if (ex instanceof EOFException) { - ; //Nothing. - } else { - ex.printStackTrace(); - } - } finally { - try { - fis.close(); - } catch (IOException ex) { - if (ex instanceof EOFException) { - ; //Ignore it! - } else { - ex.printStackTrace(); - } - } - } - return fileNBT; - } - - @Override - public void setFileNBT(File file, Object newCompound) { - OutputStream os = null; - try { - os = new FileOutputStream(file); - } catch (FileNotFoundException ex) { - ex.printStackTrace(); - } - try { - NBTCompressedStreamTools.a((NBTTagCompound) newCompound, os); - os.close(); - } catch (IOException ex) { - if (ex instanceof EOFException) { - ; //Ignore, just end of the file - } else { - ex.printStackTrace(); - } - } finally { - try { - os.close(); - } catch (IOException ex) { - if (ex instanceof EOFException) { - ; //Ignore. - } else { - ex.printStackTrace(); - } - } - } - } +package me.TheBukor.SkStuff.util; + +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.OutputStream; +import java.io.StreamCorruptedException; +import java.util.Iterator; +import java.util.List; + +import javax.annotation.Nullable; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; + +import ch.njol.skript.Skript; +import ch.njol.skript.classes.Changer; +import ch.njol.skript.classes.ClassInfo; +import ch.njol.skript.classes.Parser; +import ch.njol.skript.classes.Serializer; +import ch.njol.skript.lang.ParseContext; +import ch.njol.skript.registrations.Classes; +import ch.njol.util.coll.CollectionUtils; +import ch.njol.yggdrasil.Fields; +import net.minecraft.server.v1_8_R3.BlockPosition; +import net.minecraft.server.v1_8_R3.EntityInsentient; +import net.minecraft.server.v1_8_R3.MojangsonParseException; +import net.minecraft.server.v1_8_R3.MojangsonParser; +import net.minecraft.server.v1_8_R3.NBTBase; +import net.minecraft.server.v1_8_R3.NBTCompressedStreamTools; +import net.minecraft.server.v1_8_R3.NBTTagByte; +import net.minecraft.server.v1_8_R3.NBTTagCompound; +import net.minecraft.server.v1_8_R3.NBTTagDouble; +import net.minecraft.server.v1_8_R3.NBTTagFloat; +import net.minecraft.server.v1_8_R3.NBTTagInt; +import net.minecraft.server.v1_8_R3.NBTTagList; +import net.minecraft.server.v1_8_R3.NBTTagLong; +import net.minecraft.server.v1_8_R3.NBTTagShort; +import net.minecraft.server.v1_8_R3.NBTTagString; +import net.minecraft.server.v1_8_R3.PathfinderGoal; +import net.minecraft.server.v1_8_R3.PathfinderGoalSelector; +import net.minecraft.server.v1_8_R3.TileEntity; +import net.minecraft.server.v1_8_R3.World; + +public class NMS_v1_8_R3 implements NMSInterface { + + @Override + public void addToCompound(Object compound, Object toAdd) { + if (compound instanceof NBTTagCompound && toAdd instanceof NBTTagCompound) { + ((NBTTagCompound) compound).a((NBTTagCompound) toAdd); + } + } + + @Override + public void removeFromCompound(Object compound, String ... toRemove) { + if (compound instanceof NBTTagCompound) { + for (String s : toRemove) { + ((NBTTagCompound) compound).remove(s); + } + } + } + + @Override + public NBTTagCompound parseRawNBT(String rawNBT) { + NBTTagCompound parsedNBT = null; + try { + parsedNBT = MojangsonParser.parse(rawNBT); + } catch (MojangsonParseException ex) { + Skript.warning("Error when parsing NBT - " + ex.getMessage()); + } + return parsedNBT; + } + + @Override + public int getContentsId(Object nbtList) { + if (nbtList instanceof NBTTagList) { + return ((NBTTagList) nbtList).f(); + } + return 0; + } + + @Override + public Object[] getContents(Object nbtList) { + if (nbtList instanceof NBTTagList) { + Object[] contents = new Object[((NBTTagList) nbtList).size()]; + for (int i = 0; i < ((NBTTagList) nbtList).size(); i++) { + if (getIndex(nbtList, i) != null) { + contents[i] = getIndex(nbtList, i); + } + } + return contents; + } + return null; + } + + @Override + public void addToList(Object nbtList, Object toAdd) { + if (nbtList instanceof NBTTagList && toAdd instanceof NBTBase) { + ((NBTTagList) nbtList).add((NBTBase) toAdd); + } + } + + @Override + public void removeFromList(Object nbtList, int index) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + ((NBTTagList) nbtList).a(index); + } + } + + @Override + public void setIndex(Object nbtList, int index, Object toSet) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + if (toSet instanceof NBTBase) { + ((NBTTagList) nbtList).a(index, (NBTBase) toSet); + } else if (toSet instanceof Number) { + ((NBTTagList) nbtList).a(index, convertToNBT((Number) toSet)); + } else if (toSet instanceof String) { + ((NBTTagList) nbtList).a(index, convertToNBT((String) toSet)); + } + } + } + + @Override + public Object getIndex(Object nbtList, int index) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + NBTBase value = ((NBTTagList) nbtList).g(index); + if (value instanceof NBTTagByte) { + return ((NBTTagByte) value).f(); //Byte stored inside a NBTNumber + } else if (value instanceof NBTTagShort) { + return ((NBTTagShort) value).e(); //Short inside a NBTNumber + } else if (value instanceof NBTTagInt) { + return ((NBTTagInt) value).d(); //Integer inside a NBTNumber + } else if (value instanceof NBTTagLong) { + return ((NBTTagLong) value).c(); //Long inside a NBTNumber + } else if (value instanceof NBTTagFloat) { + return ((NBTTagFloat) value).h(); //Float inside a NBTNumber + } else if (value instanceof NBTTagDouble) { + return ((NBTTagDouble) value).g(); //Double inside a NBTNumber + } else if (value instanceof NBTTagString) { + return ((NBTTagString) value).a_(); //String inside the NBTTagString + } else if (value instanceof NBTTagList || value instanceof NBTTagCompound) { + return value; //No need to convert anything, these are registered by the addon. + } + } + return null; + } + + @Override + public void removePathfinderGoal(Object entity, Class goalClass, boolean isTargetSelector) { + if (entity instanceof EntityInsentient) { + ((EntityInsentient) entity).setGoalTarget(null); + if (isTargetSelector) { + Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).targetSelector)).iterator(); + while (goals.hasNext()) { + Object goal = goals.next(); + if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { + goals.remove(); + } + } + } else { + Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).goalSelector)).iterator(); + while (goals.hasNext()) { + Object goal = goals.next(); + if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { + goals.remove(); + } + } + } + } + } + + @Override + public void addPathfinderGoal(Object entity, int priority, Object goal, boolean isTargetSelector) { + if (entity instanceof EntityInsentient && goal instanceof PathfinderGoal) { + if (isTargetSelector) + ((EntityInsentient) entity).targetSelector.a(priority, (PathfinderGoal) goal); + else + ((EntityInsentient) entity).goalSelector.a(priority, (PathfinderGoal) goal); + } + } + + @Override + public void registerCompoundClassInfo() { + Classes.registerClass(new ClassInfo(NBTTagCompound.class, "compound").user("((nbt)?( ?tag)?) ?compounds?").name("NBT Compound").changer(new Changer() { + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.SET) { + return CollectionUtils.array(String[].class, NBTTagCompound[].class); + } + return null; + } + + @Override + public void change(NBTTagCompound[] NBT, @Nullable Object[] delta, ChangeMode mode) { + if (mode == ChangeMode.SET) { + if (delta[0] instanceof NBTTagCompound) { + NBT[0] = (NBTTagCompound) delta[0]; + } else { + NBTTagCompound parsedNBT = null; + parsedNBT = parseRawNBT((String) delta[0]); + NBT[0] = parsedNBT; + } + } else if (mode == ChangeMode.ADD) { + if (delta[0] instanceof String) { + NBTTagCompound parsedNBT = null; + parsedNBT = parseRawNBT((String) delta[0]); + addToCompound(NBT[0], parsedNBT); + } else { + addToCompound(NBT[0], delta[0]); + } + } else if (mode == ChangeMode.REMOVE) { + if (delta[0] instanceof NBTTagCompound) + return; + for (Object s : delta) { + NBT[0].remove((String) s); + } + } + } + }).parser(new Parser() { + + @Override + public String getVariableNamePattern() { + return ".+"; + } + + @Override + @Nullable + public NBTTagCompound parse(String rawNBT, ParseContext context) { + if (rawNBT.startsWith("nbt:{") && rawNBT.endsWith("}")) { + NBTTagCompound NBT = null; + NBT = parseRawNBT(rawNBT.substring(4)); + return NBT; + } + return null; + } + + @Override + public String toString(NBTTagCompound compound, int arg1) { + return compound.toString(); + } + + @Override + public String toVariableNameString(NBTTagCompound compound) { + return "nbt:" + compound.toString(); + } + }).serializer(new Serializer() { + + @Override + public Fields serialize(NBTTagCompound compound) throws NotSerializableException { + Fields f = new Fields(); + f.putObject("asString", compound.toString()); + return f; + } + + @Override + public void deserialize(NBTTagCompound compound, Fields f) throws StreamCorruptedException, NotSerializableException { + assert false; + } + + @Override + protected boolean canBeInstantiated() { + return false; + } + + @Override + protected NBTTagCompound deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { + String s = fields.getObject("asString", String.class); + NBTTagCompound compound = null; + compound = parseRawNBT(s); + return compound; + } + + @Override + @Nullable + public NBTTagCompound deserialize(String s) { + NBTTagCompound compound = null; + compound = parseRawNBT(s); + return compound; + } + + @Override + public boolean mustSyncDeserialization() { + return true; + } + })); + + } + + @Override + public void registerNBTListClassInfo() { + Classes.registerClass(new ClassInfo(NBTTagList.class, "nbtlist").user("nbt ?list ?(tag)?").name("NBT List").changer(new Changer() { + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.SET || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + return CollectionUtils.array(Float[].class, Double[].class, String[].class, NBTTagCompound[].class, Integer[].class, NBTTagList[].class); + } + return null; + } + + @Override + public void change(NBTTagList[] nbtList, @Nullable Object[] delta, ChangeMode mode) { + int typeId = 0; + if (delta instanceof Byte[]) { + typeId = 1; + } else if (delta instanceof Short[]) { + typeId = 2; + } else if (delta instanceof Integer[]) { + typeId = 3; + } else if (delta instanceof Long[]) { + typeId = 4; + } else if (delta instanceof Float[]) { + typeId = 5; + } else if (delta instanceof Double[]) { + typeId = 6; + } else if (delta instanceof String[]) { + typeId = 8; + } else if (delta instanceof NBTTagList[]) { + typeId = 9; + } else if (delta instanceof NBTTagCompound[]) { + typeId = 10; + } else { + return; + } + if (mode == ChangeMode.SET) { + if (typeId == 9) + nbtList[0] = (NBTTagList) delta[0]; + } else if (mode == ChangeMode.ADD) { + if (getContentsId(nbtList[0]) == typeId) { + if (delta[0] instanceof Number) + addToList(nbtList, convertToNBT((Number) delta[0])); + else if (delta[0] instanceof String) + addToList(nbtList, convertToNBT((String) delta[0])); + else if (delta[0] instanceof NBTTagCompound || delta[0] instanceof NBTTagList) + addToList(nbtList, delta[0]); + } + } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + nbtList[0] = new NBTTagList(); + } + } + }).parser(new Parser() { + + @Override + public String getVariableNamePattern() { + return ".+"; + } + + @Override + @Nullable + public NBTTagList parse(String listString, ParseContext context) { + if (listString.startsWith("[") && listString.endsWith("]")) { + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:[0:" + listString.substring(1) + "}"); + NBTTagList parsedList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return parsedList; + } + return null; + } + + @Override + public String toString(NBTTagList nbtList, int arg1) { + return nbtList.toString(); + } + + @Override + public String toVariableNameString(NBTTagList nbtList) { + return nbtList.toString(); + } + }).serializer(new Serializer() { + + @Override + public Fields serialize(NBTTagList nbtList) throws NotSerializableException { + Fields f = new Fields(); + f.putObject("asString", nbtList.toString()); + return f; + } + + @Override + public void deserialize(NBTTagList nbtList, Fields f) throws StreamCorruptedException, NotSerializableException { + assert false; + } + + @Override + protected boolean canBeInstantiated() { + return false; + } + + @Override + protected NBTTagList deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { + String s = fields.getObject("asString", String.class); + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:" + s + "}"); + NBTTagList nbtList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return nbtList; + } + + @Override + @Nullable + public NBTTagList deserialize(String s) { + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:" + s + "}"); + NBTTagList nbtList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return nbtList; + } + + @Override + public boolean mustSyncDeserialization() { + return true; + } + })); + } + + @Override + public NBTTagCompound getEntityNBT(Entity entity) { + net.minecraft.server.v1_8_R3.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + NBTTagCompound NBT = new NBTTagCompound(); + nmsEntity.e(NBT); + return NBT; + } + + @Override + public NBTTagCompound getTileNBT(Block block) { + NBTTagCompound NBT = new NBTTagCompound(); + World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); + TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); + if (tileEntity == null) + return null; + tileEntity.b(NBT); + return NBT; + } + + @Override + public NBTTagCompound getItemNBT(ItemStack itemStack) { + if (itemStack.getType() == Material.AIR) + return null; + NBTTagCompound itemNBT = CraftItemStack.asNMSCopy(itemStack).getTag(); + if (String.valueOf(itemNBT).equals("{}")) + itemNBT = null; + return itemNBT; + } + + @Override + public void setEntityNBT(Entity entity, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + net.minecraft.server.v1_8_R3.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + nmsEntity.f((NBTTagCompound) newCompound); + } + } + + @Override + public void setTileNBT(Block block, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); + TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); + if (tileEntity == null) + return; + tileEntity.a((NBTTagCompound) newCompound); + tileEntity.update(); + nmsWorld.notify(tileEntity.getPosition()); + } + } + + @Override + public ItemStack getItemWithNBT(ItemStack itemStack, Object compound) { + net.minecraft.server.v1_8_R3.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); + if (compound instanceof NBTTagCompound && itemStack != null) { + if (itemStack.getType() == Material.AIR) + return null; + if (((NBTTagCompound) compound).isEmpty()) + return itemStack; + nmsItem.setTag((NBTTagCompound) compound); + ItemStack newItem = CraftItemStack.asBukkitCopy(nmsItem); + return newItem; + } else if (compound == null) { + nmsItem.setTag(null); + ItemStack newItem = CraftItemStack.asBukkitCopy(nmsItem); + return newItem; + } + return itemStack; + } + + @Override + public NBTTagCompound getFileNBT(File file) { + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + } catch (FileNotFoundException ex) { + return null; //File doesn't exist. + } + NBTTagCompound fileNBT = null; + try { + fileNBT = NBTCompressedStreamTools.a(fis); + fis.close(); + } catch (IOException ex) { + if (ex instanceof EOFException) { + ; //Nothing. + } else { + ex.printStackTrace(); + } + } + return fileNBT; + } + + @Override + public void setFileNBT(File file, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + OutputStream os = null; + try { + os = new FileOutputStream(file); + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + } + try { + NBTCompressedStreamTools.a((NBTTagCompound) newCompound, os); + os.close(); + } catch (IOException ex) { + if (ex instanceof EOFException) { + ; //Ignore, just end of the file + } else { + ex.printStackTrace(); + } + } + } + } + + public NBTBase convertToNBT(Number number) { + if (number instanceof Byte) { + return new NBTTagByte((byte) number); + } else if (number instanceof Short) { + return new NBTTagShort((short) number); + } else if (number instanceof Integer) { + return new NBTTagInt((int) number); + } else if (number instanceof Long) { + return new NBTTagLong((long) number); + } else if (number instanceof Float) { + return new NBTTagFloat((float) number); + } else if (number instanceof Double) { + return new NBTTagDouble((double) number); + } + return null; + } + + public NBTTagString convertToNBT(String string) { + return new NBTTagString(string); + } } \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/util/NMS_v1_9_R1.java b/src/me/TheBukor/SkStuff/util/NMS_v1_9_R1.java new file mode 100644 index 0000000..887dd9b --- /dev/null +++ b/src/me/TheBukor/SkStuff/util/NMS_v1_9_R1.java @@ -0,0 +1,562 @@ +package me.TheBukor.SkStuff.util; + +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.OutputStream; +import java.io.StreamCorruptedException; +import java.util.Iterator; +import java.util.List; + +import javax.annotation.Nullable; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_9_R1.CraftWorld; +import org.bukkit.craftbukkit.v1_9_R1.entity.CraftEntity; +import org.bukkit.craftbukkit.v1_9_R1.inventory.CraftItemStack; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; + +import ch.njol.skript.Skript; +import ch.njol.skript.classes.Changer; +import ch.njol.skript.classes.ClassInfo; +import ch.njol.skript.classes.Parser; +import ch.njol.skript.classes.Serializer; +import ch.njol.skript.lang.ParseContext; +import ch.njol.skript.registrations.Classes; +import ch.njol.util.coll.CollectionUtils; +import ch.njol.yggdrasil.Fields; +import net.minecraft.server.v1_9_R1.BlockPosition; +import net.minecraft.server.v1_9_R1.EntityInsentient; +import net.minecraft.server.v1_9_R1.IBlockData; +import net.minecraft.server.v1_9_R1.MojangsonParseException; +import net.minecraft.server.v1_9_R1.MojangsonParser; +import net.minecraft.server.v1_9_R1.NBTBase; +import net.minecraft.server.v1_9_R1.NBTCompressedStreamTools; +import net.minecraft.server.v1_9_R1.NBTTagByte; +import net.minecraft.server.v1_9_R1.NBTTagCompound; +import net.minecraft.server.v1_9_R1.NBTTagDouble; +import net.minecraft.server.v1_9_R1.NBTTagFloat; +import net.minecraft.server.v1_9_R1.NBTTagInt; +import net.minecraft.server.v1_9_R1.NBTTagList; +import net.minecraft.server.v1_9_R1.NBTTagLong; +import net.minecraft.server.v1_9_R1.NBTTagShort; +import net.minecraft.server.v1_9_R1.NBTTagString; +import net.minecraft.server.v1_9_R1.PathfinderGoal; +import net.minecraft.server.v1_9_R1.PathfinderGoalSelector; +import net.minecraft.server.v1_9_R1.TileEntity; +import net.minecraft.server.v1_9_R1.World; + +public class NMS_v1_9_R1 implements NMSInterface { + + @Override + public void addToCompound(Object compound, Object toAdd) { + if (compound instanceof NBTTagCompound && toAdd instanceof NBTTagCompound) { + ((NBTTagCompound) compound).a((NBTTagCompound) toAdd); + } + } + + @Override + public void removeFromCompound(Object compound, String ... toRemove) { + if (compound instanceof NBTTagCompound) { + for (String s : toRemove) { + ((NBTTagCompound) compound).remove(s); + } + } + } + + @Override + public NBTTagCompound parseRawNBT(String rawNBT) { + NBTTagCompound parsedNBT = null; + try { + parsedNBT = MojangsonParser.parse(rawNBT); + } catch (MojangsonParseException ex) { + Skript.warning("Error when parsing NBT - " + ex.getMessage()); + } + return parsedNBT; + } + + @Override + public int getContentsId(Object nbtList) { + if (nbtList instanceof NBTTagList) { + return ((NBTTagList) nbtList).d(); + } + return 0; + } + + @Override + public Object[] getContents(Object nbtList) { + if (nbtList instanceof NBTTagList) { + Object[] contents = new Object[((NBTTagList) nbtList).size()]; + for (int i = 0; i < ((NBTTagList) nbtList).size(); i++) { + if (getIndex(nbtList, i) != null) { + contents[i] = getIndex(nbtList, i); + } + } + return contents; + } + return null; + } + + @Override + public void addToList(Object nbtList, Object toAdd) { + if (nbtList instanceof NBTTagList && toAdd instanceof NBTBase) { + ((NBTTagList) nbtList).add((NBTBase) toAdd); + } + } + + @Override + public void removeFromList(Object nbtList, int index) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + ((NBTTagList) nbtList).remove(index); + } + } + + @Override + public void setIndex(Object nbtList, int index, Object toSet) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + if (toSet instanceof NBTBase) { + ((NBTTagList) nbtList).a(index, (NBTBase) toSet); + } else if (toSet instanceof Number) { + ((NBTTagList) nbtList).a(index, convertToNBT((Number) toSet)); + } else if (toSet instanceof String) { + ((NBTTagList) nbtList).a(index, convertToNBT((String) toSet)); + } + } + } + + @Override + public Object getIndex(Object nbtList, int index) { + if (nbtList instanceof NBTTagList && index >= 0 && index < ((NBTTagList) nbtList).size()) { + NBTBase value = ((NBTTagList) nbtList).h(index); + if (value instanceof NBTTagByte) { + return ((NBTTagByte) value).f(); //Byte stored inside a NBTNumber + } else if (value instanceof NBTTagShort) { + return ((NBTTagShort) value).e(); //Short inside a NBTNumber + } else if (value instanceof NBTTagInt) { + return ((NBTTagInt) value).d(); //Integer inside a NBTNumber + } else if (value instanceof NBTTagLong) { + return ((NBTTagLong) value).c(); //Long inside a NBTNumber + } else if (value instanceof NBTTagFloat) { + return ((NBTTagFloat) value).h(); //Float inside a NBTNumber + } else if (value instanceof NBTTagDouble) { + return ((NBTTagDouble) value).g(); //Double inside a NBTNumber + } else if (value instanceof NBTTagString) { + return ((NBTTagString) value).a_(); //String inside the NBTTagString + } else if (value instanceof NBTTagList || value instanceof NBTTagCompound) { + return value; //No need to convert anything, these are registered by the addon. + } + } + return null; + } + + @Override + public void removePathfinderGoal(Object entity, Class goalClass, boolean isTargetSelector) { + if (entity instanceof EntityInsentient) { + ((EntityInsentient) entity).setGoalTarget(null); + if (isTargetSelector) { + Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).targetSelector)).iterator(); + while (goals.hasNext()) { + Object goal = goals.next(); + if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { + goals.remove(); + } + } + } else { + Iterator goals = ((List) ReflectionUtils.getField("b", PathfinderGoalSelector.class, ((EntityInsentient) entity).goalSelector)).iterator(); + while (goals.hasNext()) { + Object goal = goals.next(); + if (ReflectionUtils.getField("a", goal.getClass(), goal).getClass() == goalClass) { + goals.remove(); + } + } + } + } + } + + @Override + public void addPathfinderGoal(Object entity, int priority, Object goal, boolean isTargetSelector) { + if (entity instanceof EntityInsentient && goal instanceof PathfinderGoal) { + if (isTargetSelector) + ((EntityInsentient) entity).targetSelector.a(priority, (PathfinderGoal) goal); + else + ((EntityInsentient) entity).goalSelector.a(priority, (PathfinderGoal) goal); + } + } + + @Override + public void registerCompoundClassInfo() { + Classes.registerClass(new ClassInfo(NBTTagCompound.class, "compound").user("((nbt)?( ?tag)?) ?compounds?").name("NBT Compound").changer(new Changer() { + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.REMOVE || mode == ChangeMode.SET) { + return CollectionUtils.array(String[].class, NBTTagCompound[].class); + } + return null; + } + + @Override + public void change(NBTTagCompound[] NBT, @Nullable Object[] delta, ChangeMode mode) { + if (mode == ChangeMode.SET) { + if (delta[0] instanceof NBTTagCompound) { + NBT[0] = (NBTTagCompound) delta[0]; + } else { + NBTTagCompound parsedNBT = null; + parsedNBT = parseRawNBT((String) delta[0]); + NBT[0] = parsedNBT; + } + } else if (mode == ChangeMode.ADD) { + if (delta[0] instanceof String) { + NBTTagCompound parsedNBT = null; + parsedNBT = parseRawNBT((String) delta[0]); + addToCompound(NBT[0], parsedNBT); + } else { + addToCompound(NBT[0], delta[0]); + } + } else if (mode == ChangeMode.REMOVE) { + if (delta[0] instanceof NBTTagCompound) + return; + for (Object s : delta) { + NBT[0].remove((String) s); + } + } + } + }).parser(new Parser() { + + @Override + public String getVariableNamePattern() { + return ".+"; + } + + @Override + @Nullable + public NBTTagCompound parse(String rawNBT, ParseContext context) { + if (rawNBT.startsWith("nbt:{") && rawNBT.endsWith("}")) { + NBTTagCompound NBT = null; + NBT = parseRawNBT(rawNBT.substring(4)); + return NBT; + } + return null; + } + + @Override + public String toString(NBTTagCompound compound, int arg1) { + return compound.toString(); + } + + @Override + public String toVariableNameString(NBTTagCompound compound) { + return "nbt:" + compound.toString(); + } + }).serializer(new Serializer() { + + @Override + public Fields serialize(NBTTagCompound compound) throws NotSerializableException { + Fields f = new Fields(); + f.putObject("asString", compound.toString()); + return f; + } + + @Override + public void deserialize(NBTTagCompound compound, Fields f) throws StreamCorruptedException, NotSerializableException { + assert false; + } + + @Override + protected boolean canBeInstantiated() { + return false; + } + + @Override + protected NBTTagCompound deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { + String s = fields.getObject("asString", String.class); + NBTTagCompound compound = null; + compound = parseRawNBT(s); + return compound; + } + + @Override + @Nullable + public NBTTagCompound deserialize(String s) { + NBTTagCompound compound = null; + compound = parseRawNBT(s); + return compound; + } + + @Override + public boolean mustSyncDeserialization() { + return true; + } + })); + + } + + @Override + public void registerNBTListClassInfo() { + Classes.registerClass(new ClassInfo(NBTTagList.class, "nbtlist").user("nbt ?list ?(tag)?").name("NBT List").changer(new Changer() { + + @SuppressWarnings("unchecked") + @Override + @Nullable + public Class[] acceptChange(ChangeMode mode) { + if (mode == ChangeMode.ADD || mode == ChangeMode.SET || mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + return CollectionUtils.array(Float[].class, Double[].class, String[].class, NBTTagCompound[].class, Integer[].class, NBTTagList[].class); + } + return null; + } + + @Override + public void change(NBTTagList[] nbtList, @Nullable Object[] delta, ChangeMode mode) { + int typeId = 0; + if (delta instanceof Byte[]) { + typeId = 1; + } else if (delta instanceof Short[]) { + typeId = 2; + } else if (delta instanceof Integer[]) { + typeId = 3; + } else if (delta instanceof Long[]) { + typeId = 4; + } else if (delta instanceof Float[]) { + typeId = 5; + } else if (delta instanceof Double[]) { + typeId = 6; + } else if (delta instanceof String[]) { + typeId = 8; + } else if (delta instanceof NBTTagList[]) { + typeId = 9; + } else if (delta instanceof NBTTagCompound[]) { + typeId = 10; + } else { + return; + } + if (mode == ChangeMode.SET) { + if (typeId == 9) + nbtList[0] = (NBTTagList) delta[0]; + } else if (mode == ChangeMode.ADD) { + if (getContentsId(nbtList[0]) == typeId) { + if (delta[0] instanceof Number) + addToList(nbtList, convertToNBT((Number) delta[0])); + else if (delta[0] instanceof String) + addToList(nbtList, convertToNBT((String) delta[0])); + else if (delta[0] instanceof NBTTagCompound || delta[0] instanceof NBTTagList) + addToList(nbtList, delta[0]); + } + } else if (mode == ChangeMode.DELETE || mode == ChangeMode.RESET) { + nbtList[0] = new NBTTagList(); + } + } + }).parser(new Parser() { + + @Override + public String getVariableNamePattern() { + return ".+"; + } + + @Override + @Nullable + public NBTTagList parse(String listString, ParseContext context) { + if (listString.startsWith("[") && listString.endsWith("]")) { + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:[0:" + listString.substring(1) + "}"); + NBTTagList parsedList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return parsedList; + } + return null; + } + + @Override + public String toString(NBTTagList nbtList, int arg1) { + return nbtList.toString(); + } + + @Override + public String toVariableNameString(NBTTagList nbtList) { + return nbtList.toString(); + } + }).serializer(new Serializer() { + + @Override + public Fields serialize(NBTTagList nbtList) throws NotSerializableException { + Fields f = new Fields(); + f.putObject("asString", nbtList.toString()); + return f; + } + + @Override + public void deserialize(NBTTagList nbtList, Fields f) throws StreamCorruptedException, NotSerializableException { + assert false; + } + + @Override + protected boolean canBeInstantiated() { + return false; + } + + @Override + protected NBTTagList deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { + String s = fields.getObject("asString", String.class); + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:" + s + "}"); + NBTTagList nbtList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return nbtList; + } + + @Override + @Nullable + public NBTTagList deserialize(String s) { + NBTTagCompound tempNBT = null; + tempNBT = parseRawNBT("{SkStuffIsCool:" + s + "}"); + NBTTagList nbtList = (NBTTagList) tempNBT.get("SkStuffIsCool"); + return nbtList; + } + + @Override + public boolean mustSyncDeserialization() { + return true; + } + })); + } + + @Override + public NBTTagCompound getEntityNBT(Entity entity) { + net.minecraft.server.v1_9_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + NBTTagCompound NBT = new NBTTagCompound(); + nmsEntity.e(NBT); + return NBT; + } + + @Override + public NBTTagCompound getTileNBT(Block block) { + NBTTagCompound NBT = new NBTTagCompound(); + World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); + TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); + if (tileEntity == null) + return null; + tileEntity.save(NBT); + return NBT; + } + + @Override + public NBTTagCompound getItemNBT(ItemStack itemStack) { + if (itemStack.getType() == Material.AIR) + return null; + NBTTagCompound itemNBT = CraftItemStack.asNMSCopy(itemStack).getTag(); + if (String.valueOf(itemNBT).equals("{}")) + itemNBT = null; + return itemNBT; + } + + @Override + public void setEntityNBT(Entity entity, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + net.minecraft.server.v1_9_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + nmsEntity.f((NBTTagCompound) newCompound); + } + } + + @Override + public void setTileNBT(Block block, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + World nmsWorld = ((CraftWorld) block.getWorld()).getHandle(); + TileEntity tileEntity = nmsWorld.getTileEntity(new BlockPosition(block.getX(), block.getY(), block.getZ())); + if (tileEntity == null) + return; + tileEntity.a((NBTTagCompound) newCompound); + tileEntity.update(); + IBlockData tileEntType = nmsWorld.getType(new BlockPosition(block.getX(), block.getY(), block.getZ())); + nmsWorld.notify(tileEntity.getPosition(), tileEntType, tileEntType, 3); + } + } + + @Override + public ItemStack getItemWithNBT(ItemStack itemStack, Object compound) { + net.minecraft.server.v1_9_R1.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack); + if (compound instanceof NBTTagCompound && itemStack != null) { + if (itemStack.getType() == Material.AIR) + return null; + if (((NBTTagCompound) compound).isEmpty()) + return itemStack; + nmsItem.setTag((NBTTagCompound) compound); + ItemStack newItem = CraftItemStack.asBukkitCopy(nmsItem); + return newItem; + } else if (compound == null) { + nmsItem.setTag(null); + ItemStack newItem = CraftItemStack.asBukkitCopy(nmsItem); + return newItem; + } + return itemStack; + } + + @Override + public NBTTagCompound getFileNBT(File file) { + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + } catch (FileNotFoundException ex) { + return null; //File doesn't exist. + } + NBTTagCompound fileNBT = null; + try { + fileNBT = NBTCompressedStreamTools.a(fis); + fis.close(); + } catch (IOException ex) { + if (ex instanceof EOFException) { + ; //Nothing. + } else { + ex.printStackTrace(); + } + } + return fileNBT; + } + + @Override + public void setFileNBT(File file, Object newCompound) { + if (newCompound instanceof NBTTagCompound) { + OutputStream os = null; + try { + os = new FileOutputStream(file); + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + } + try { + NBTCompressedStreamTools.a((NBTTagCompound) newCompound, os); + os.close(); + } catch (IOException ex) { + if (ex instanceof EOFException) { + ; //Ignore, just end of the file + } else { + ex.printStackTrace(); + } + } + } + } + + public NBTBase convertToNBT(Number number) { + if (number instanceof Byte) { + return new NBTTagByte((byte) number); + } else if (number instanceof Short) { + return new NBTTagShort((short) number); + } else if (number instanceof Integer) { + return new NBTTagInt((int) number); + } else if (number instanceof Long) { + return new NBTTagLong((long) number); + } else if (number instanceof Float) { + return new NBTTagFloat((float) number); + } else if (number instanceof Double) { + return new NBTTagDouble((double) number); + } + return null; + } + + public NBTTagString convertToNBT(String string) { + return new NBTTagString(string); + } +} \ No newline at end of file diff --git a/src/me/TheBukor/SkStuff/util/ReflectionUtils.java b/src/me/TheBukor/SkStuff/util/ReflectionUtils.java index 495de15..379a179 100644 --- a/src/me/TheBukor/SkStuff/util/ReflectionUtils.java +++ b/src/me/TheBukor/SkStuff/util/ReflectionUtils.java @@ -1,64 +1,74 @@ -package me.TheBukor.SkStuff.util; - -import java.lang.reflect.Field; - -import org.bukkit.Bukkit; - -public class ReflectionUtils { - - public static Class getNMSClass(String classString, boolean isArray) { - String version = getVersion(); - String name = "net.minecraft.server." + version + classString; - if (isArray) - name = "[L" + name + ";"; - Class nmsClass = null; - try { - nmsClass = Class.forName(name); - } catch (ClassNotFoundException ex) { - Bukkit.getLogger().warning("Unable to get NMS class \'" + name + "\'! You are probably running an unsupported version!"); - return null; - } - return nmsClass; - } - - public static Class getOBCClass(String classString) { - String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3] + "."; - String name = "org.bukkit.craftbukkit." + version + classString; - Class obcClass = null; - try { - obcClass = Class.forName(name); - } catch (ClassNotFoundException ex) { - Bukkit.getLogger().warning("Unable to get OBC class \'" + name + "\'! You are probably running an unsupported version!"); - return null; - } - return obcClass; - } - - public static Object getField(String field, Class clazz, Object object) { - Field f = null; - Object obj = null; - try { - f = clazz.getDeclaredField(field); - f.setAccessible(true); - obj = f.get(object); - } catch (Exception ex) { - ex.printStackTrace(); - } - return obj; - } - - public static void setField(String field, Class clazz, Object object, Object toSet) { - Field f = null; - try { - f = clazz.getDeclaredField(field); - f.setAccessible(true); - f.set(object, toSet); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static String getVersion() { - return Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3] + "."; - } +package me.TheBukor.SkStuff.util; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; + +import org.bukkit.Bukkit; + +public class ReflectionUtils { + + public static Class getNMSClass(String classString) { + String version = getVersion(); + String name = "net.minecraft.server." + version + classString; + Class nmsClass = null; + try { + nmsClass = Class.forName(name); + } catch (ClassNotFoundException ex) { + Bukkit.getLogger().warning("Unable to get NMS class \'" + name + "\'! You are probably running an unsupported version!"); + return null; + } + return nmsClass; + } + + public static Class getOBCClass(String classString) { + String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3] + "."; + String name = "org.bukkit.craftbukkit." + version + classString; + Class obcClass = null; + try { + obcClass = Class.forName(name); + } catch (ClassNotFoundException ex) { + Bukkit.getLogger().warning("Unable to get OBC class \'" + name + "\'! You are probably running an unsupported version!"); + return null; + } + return obcClass; + } + + public static Object getField(String field, Class clazz, Object object) { + Field f = null; + Object obj = null; + try { + f = clazz.getDeclaredField(field); + f.setAccessible(true); + obj = f.get(object); + } catch (Exception ex) { + ex.printStackTrace(); + } + return obj; + } + + public static void setField(String field, Class clazz, Object object, Object toSet) { + Field f = null; + try { + f = clazz.getDeclaredField(field); + f.setAccessible(true); + f.set(object, toSet); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Constructor getConstructor(String constructor, Class clazz, Object object, Class ... params) { + Constructor constr = null; + try { + constr = clazz.getDeclaredConstructor(params); + constr.setAccessible(true); + } catch (Exception ex) { + ex.printStackTrace(); + } + return constr; + } + + public static String getVersion() { + return Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3] + "."; + } } \ No newline at end of file