Corrected maven structure

This commit is contained in:
libraryaddict
2018-09-01 13:10:38 +12:00
parent 590061852c
commit 49c8f68911
135 changed files with 6 additions and 6 deletions

View File

@@ -0,0 +1,430 @@
package me.libraryaddict.disguise;
import me.libraryaddict.disguise.disguisetypes.*;
import me.libraryaddict.disguise.disguisetypes.TargetedDisguise.TargetType;
import me.libraryaddict.disguise.disguisetypes.watchers.AbstractHorseWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.HorseWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import me.libraryaddict.disguise.utilities.ReflectionManager;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.entity.*;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.HorseInventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class DisguiseAPI {
private static int selfDisguiseId = ReflectionManager.getNewEntityId(true);
public static Disguise getCustomDisguise(String disguiseName) {
Map.Entry<String, Disguise> entry = DisguiseConfig.getCustomDisguise(disguiseName);
if (entry == null)
return null;
return entry.getValue();
}
public static Disguise constructDisguise(Entity entity) {
return constructDisguise(entity, true, true, true);
}
public static Disguise constructDisguise(Entity entity, boolean doEquipment, boolean doSneak, boolean doSprint) {
DisguiseType disguiseType = DisguiseType.getType(entity);
Disguise disguise;
if (disguiseType.isMisc()) {
disguise = new MiscDisguise(disguiseType);
} else if (disguiseType.isMob()) {
disguise = new MobDisguise(disguiseType);
} else {
disguise = new PlayerDisguise(entity.getName());
}
FlagWatcher watcher = disguise.getWatcher();
if (entity instanceof LivingEntity) {
for (PotionEffect effect : ((LivingEntity) entity).getActivePotionEffects()) {
((LivingWatcher) watcher).addPotionEffect(effect.getType());
if (effect.getType() == PotionEffectType.INVISIBILITY) {
watcher.setInvisible(true);
} else if (effect.getType() == PotionEffectType.GLOWING) {
watcher.setGlowing(true);
}
}
}
if (entity.getFireTicks() > 0) {
watcher.setBurning(true);
}
if (doEquipment && entity instanceof LivingEntity) {
EntityEquipment equip = ((LivingEntity) entity).getEquipment();
watcher.setArmor(equip.getArmorContents());
watcher.setItemInMainHand(equip.getItemInMainHand());
if (disguiseType.getEntityType() == EntityType.HORSE) {
Horse horse = (Horse) entity;
HorseInventory horseInventory = horse.getInventory();
ItemStack saddle = horseInventory.getSaddle();
if (saddle != null && saddle.getType() == Material.SADDLE) {
((AbstractHorseWatcher) watcher).setSaddled(true);
}
if (watcher instanceof HorseWatcher)
((HorseWatcher) watcher).setHorseArmor(horseInventory.getArmor());
}
}
for (Method method : entity.getClass().getMethods()) {
if ((doSneak || !method.getName().equals("setSneaking")) &&
(doSprint || !method.getName().equals("setSprinting")) && method.getParameterTypes().length == 0 &&
method.getReturnType() != void.class) {
Class methodReturn = method.getReturnType();
if (methodReturn == float.class || methodReturn == Float.class || methodReturn == Double.class) {
methodReturn = double.class;
}
int firstCapitalMethod = firstCapital(method.getName());
if (firstCapitalMethod > 0) {
for (Method watcherMethod : watcher.getClass().getMethods()) {
if (!watcherMethod.getName().startsWith("get") && watcherMethod.getReturnType() == void.class &&
watcherMethod.getParameterTypes().length == 1) {
int firstCapitalWatcher = firstCapital(watcherMethod.getName());
if (firstCapitalWatcher > 0 && method.getName().substring(firstCapitalMethod)
.equalsIgnoreCase(watcherMethod.getName().substring(firstCapitalWatcher))) {
Class methodParam = watcherMethod.getParameterTypes()[0];
if (methodParam == float.class || methodParam == Float.class ||
methodParam == Double.class) {
methodParam = double.class;
} else if (methodParam == AnimalColor.class) {
methodParam = DyeColor.class;
}
if (methodReturn == methodParam) {
try {
Object value = method.invoke(entity);
if (value != null) {
Class toCast = watcherMethod.getParameterTypes()[0];
if (!(toCast.isInstance(value))) {
if (toCast == float.class) {
if (!(value instanceof Float)) {
double d = (Double) value;
value = (float) d;
}
} else if (toCast == double.class) {
if (!(value instanceof Double)) {
float d = (Float) value;
value = (double) d;
}
} else if (toCast == AnimalColor.class) {
value = AnimalColor.valueOf(((DyeColor) value).name());
}
}
if (value instanceof Boolean && !(Boolean) value &&
watcherMethod.getDeclaringClass() == FlagWatcher.class) {
continue;
}
}
watcherMethod.invoke(watcher, value);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
}
}
}
return disguise;
}
public static void disguiseEntity(Entity entity, Disguise disguise) {
// If they are trying to disguise a null entity or use a null disguise
// Just return.
if (entity == null || disguise == null) {
return;
}
// The event wasn't cancelled.
// If the disguise entity isn't the same as the one we are disguising
if (disguise.getEntity() != entity) {
// If the disguise entity actually exists
if (disguise.getEntity() != null) {
// Clone the disguise
disguise = disguise.clone();
}
// Set the disguise's entity
disguise.setEntity(entity);
}
// They prefer to have the opposite of whatever the view disguises option is
if (hasSelfDisguisePreference(entity) && disguise.isSelfDisguiseVisible() == DisguiseConfig.isViewDisguises())
disguise.setViewSelfDisguise(!disguise.isSelfDisguiseVisible());
disguise.startDisguise();
}
public static void disguiseIgnorePlayers(Entity entity, Disguise disguise, Collection playersToNotSeeDisguise) {
if (disguise.getEntity() != null) {
disguise = disguise.clone();
}
((TargetedDisguise) disguise).setDisguiseTarget(TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS);
for (Object obj : playersToNotSeeDisguise) {
if (obj instanceof String) {
((TargetedDisguise) disguise).addPlayer((String) obj);
} else if (obj instanceof Player) {
((TargetedDisguise) disguise).addPlayer(((Player) obj).getName());
}
}
disguiseEntity(entity, disguise);
}
@Deprecated
public static void disguiseIgnorePlayers(Entity entity, Disguise disguise, List<String> playersToNotSeeDisguise) {
disguiseIgnorePlayers(entity, disguise, (Collection) playersToNotSeeDisguise);
}
public static void disguiseIgnorePlayers(Entity entity, Disguise disguise, Player... playersToNotSeeDisguise) {
disguiseIgnorePlayers(entity, disguise, (Collection) Arrays.asList(playersToNotSeeDisguise));
}
public static void disguiseIgnorePlayers(Entity entity, Disguise disguise, String... playersToNotSeeDisguise) {
disguiseIgnorePlayers(entity, disguise, (Collection) Arrays.asList(playersToNotSeeDisguise));
}
/**
* Disguise the next entity to spawn, this means you need to spawn an entity immediately after calling this.
*
* @param disguise
* @return
*/
public static int disguiseNextEntity(Disguise disguise) {
if (disguise == null) {
return -1;
}
if (disguise.getEntity() != null || DisguiseUtilities.getDisguises().containsValue(disguise)) {
disguise = disguise.clone();
}
int id = ReflectionManager.getNewEntityId(false);
DisguiseUtilities.addFutureDisguise(id, (TargetedDisguise) disguise);
return id;
}
/**
* Disguise this entity with this disguise
*
* @param entity
* @param disguise
*/
public static void disguiseToAll(Entity entity, Disguise disguise) {
if (disguise.getEntity() != null) {
disguise = disguise.clone();
}
// You called the disguiseToAll method foolish mortal! Prepare to have your custom settings wiped!!!
((TargetedDisguise) disguise).setDisguiseTarget(TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS);
for (String observer : ((TargetedDisguise) disguise).getObservers()) {
((TargetedDisguise) disguise).removePlayer(observer);
}
disguiseEntity(entity, disguise);
}
public static void disguiseToPlayers(Entity entity, Disguise disguise, Collection playersToViewDisguise) {
if (disguise.getEntity() != null) {
disguise = disguise.clone();
}
((TargetedDisguise) disguise).setDisguiseTarget(TargetType.HIDE_DISGUISE_TO_EVERYONE_BUT_THESE_PLAYERS);
for (Object obj : playersToViewDisguise) {
if (obj instanceof String) {
((TargetedDisguise) disguise).addPlayer((String) obj);
} else if (obj instanceof Player) {
((TargetedDisguise) disguise).addPlayer(((Player) obj).getName());
}
}
disguiseEntity(entity, disguise);
}
@Deprecated
public static void disguiseToPlayers(Entity entity, Disguise disguise, List<String> playersToViewDisguise) {
disguiseToPlayers(entity, disguise, (Collection) playersToViewDisguise);
}
public static void disguiseToPlayers(Entity entity, Disguise disguise, Player... playersToViewDisguise) {
disguiseToPlayers(entity, disguise, (Collection) Arrays.asList(playersToViewDisguise));
}
public static void disguiseToPlayers(Entity entity, Disguise disguise, String... playersToViewDisguise) {
disguiseToPlayers(entity, disguise, (Collection) Arrays.asList(playersToViewDisguise));
}
private static int firstCapital(String str) {
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i))) {
return i;
}
}
return -1;
}
/**
* Get the disguise of a entity
*
* @param disguised
* @return
*/
public static Disguise getDisguise(Entity disguised) {
if (disguised == null) {
return null;
}
return DisguiseUtilities.getMainDisguise(disguised.getUniqueId());
}
/**
* Get the disguise of a entity
*
* @param observer
* @param disguised
* @return
*/
public static Disguise getDisguise(Player observer, Entity disguised) {
if (disguised == null || observer == null) {
return null;
}
return DisguiseUtilities.getDisguise(observer, disguised);
}
/**
* Get the disguises of a entity
*
* @param disguised
* @return
*/
public static Disguise[] getDisguises(Entity disguised) {
if (disguised == null) {
return null;
}
return DisguiseUtilities.getDisguises(disguised.getUniqueId());
}
public static int getSelfDisguiseId() {
return selfDisguiseId;
}
/**
* Is this entity disguised
*
* @param disguised
* @return
*/
public static boolean isDisguised(Entity disguised) {
return getDisguise(disguised) != null;
}
/**
* Is this entity disguised
*
* @param observer
* @param disguised
* @return
*/
public static boolean isDisguised(Player observer, Entity disguised) {
return getDisguise(observer, disguised) != null;
}
public static boolean isDisguiseInUse(Disguise disguise) {
return disguise.isDisguiseInUse();
}
public static boolean isSelfDisguised(Player player) {
return DisguiseUtilities.getSelfDisguised().contains(player.getUniqueId());
}
/**
* Returns true if the entitiy has /disguiseviewself toggled on.
*
* @param entity
* @return
*/
public static boolean isViewSelfToggled(Entity entity) {
return hasSelfDisguisePreference(entity) != DisguiseConfig.isViewDisguises();
}
public static boolean hasSelfDisguisePreference(Entity entity) {
return Disguise.getViewSelf().contains(entity.getUniqueId());
}
/**
* Undisguise the entity. This doesn't let you cancel the UndisguiseEvent if the entity is no longer valid. Aka
* removed from
* the world.
*
* @param entity
*/
public static void undisguiseToAll(Entity entity) {
Disguise[] disguises = getDisguises(entity);
for (Disguise disguise : disguises) {
disguise.removeDisguise();
}
}
/**
* Set whether this player can see his own disguise or not.
*
* @param entity
* @param canSeeSelfDisguises
*/
public static void setViewDisguiseToggled(Entity entity, boolean canSeeSelfDisguises) {
if (isDisguised(entity)) {
Disguise[] disguises = getDisguises(entity);
for (Disguise disguise : disguises) {
disguise.setViewSelfDisguise(canSeeSelfDisguises);
}
}
if (!canSeeSelfDisguises == DisguiseConfig.isViewDisguises()) {
if (!hasSelfDisguisePreference(entity)) {
Disguise.getViewSelf().add(entity.getUniqueId());
}
} else {
Disguise.getViewSelf().remove(entity.getUniqueId());
}
}
private DisguiseAPI() {
}
}

View File

@@ -0,0 +1,663 @@
package me.libraryaddict.disguise;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.utilities.*;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguiseParseException;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.util.HashMap;
import java.util.Map.Entry;
public class DisguiseConfig {
public static enum DisguisePushing { // This enum has a really bad name..
MODIFY_SCOREBOARD,
IGNORE_SCOREBOARD,
CREATE_SCOREBOARD;
}
private static boolean animationEnabled;
private static boolean bedEnabled;
private static boolean blowDisguisesWhenAttacking;
private static boolean blowDisguisesWhenAttacked;
private static boolean collectEnabled;
private static boolean colorizeSheep;
private static boolean colorizeWolf;
private static HashMap<String, Disguise> customDisguises = new HashMap<>();
private static boolean disableInvisibility;
private static int disguiseCloneExpire;
private static int disguiseEntityExpire;
private static boolean displayPlayerDisguisesInTab;
private static boolean entityAnimationsAdded;
private static boolean entityStatusEnabled;
private static boolean equipmentEnabled;
private static boolean hearSelfDisguise;
private static boolean hideDisguisedPlayers;
private static boolean hidingArmor;
private static boolean hidingHeldItem;
private static boolean keepDisguisePlayerDeath;
private static int maxClonedDisguises;
private static boolean maxHealthIsDisguisedEntity;
private static boolean miscDisguisesForLivingEnabled;
private static boolean modifyBoundingBox;
private static boolean movementEnabled;
private static boolean sendsEntityMetadata;
private static boolean sendVelocity;
private static boolean showNameAboveHead;
private static boolean showNameAboveHeadAlwaysVisible;
private static boolean stopShulkerDisguisesFromMoving;
private static boolean targetDisguises;
private static boolean undisguiseSwitchWorlds;
private static String updateNotificationPermission;
private static boolean viewSelfDisguise;
private static boolean witherSkullEnabled;
private static DisguisePushing disablePushing = DisguisePushing.MODIFY_SCOREBOARD;
private static boolean saveCache;
private static boolean updatePlayerCache;
private static boolean savePlayerDisguises;
private static boolean saveEntityDisguises;
private static boolean useTranslations;
private static boolean modifyCollisions;
private static boolean disableFriendlyInvisibles;
private static boolean warnScoreboardConflict;
public static Entry<String, Disguise> getCustomDisguise(String disguise) {
for (Entry<String, Disguise> entry : customDisguises.entrySet()) {
if (!entry.getKey().equalsIgnoreCase(disguise) &&
!entry.getKey().replaceAll("_", "").equalsIgnoreCase(disguise))
continue;
return entry;
}
return null;
}
public static boolean isWarnScoreboardConflict() {
return warnScoreboardConflict;
}
public static void setWarnScoreboardConflict(boolean warnConflict) {
warnScoreboardConflict = warnConflict;
}
public static boolean isModifyCollisions() {
return modifyCollisions;
}
public static boolean isDisableFriendlyInvisibles() {
return disableFriendlyInvisibles;
}
public static void setModifyCollisions(boolean isModifyCollisions) {
modifyCollisions = isModifyCollisions;
}
public static void setDisableFriendlyInvisibles(boolean isDisableFriendlyInvisibles) {
disableFriendlyInvisibles = isDisableFriendlyInvisibles;
}
public static boolean isSavePlayerDisguises() {
return savePlayerDisguises;
}
public static boolean isUseTranslations() {
return useTranslations;
}
public static void setUseTranslations(boolean setUseTranslations) {
useTranslations = setUseTranslations;
TranslateType.refreshTranslations();
}
public static boolean isSaveEntityDisguises() {
return saveEntityDisguises;
}
public static void setSavePlayerDisguises(boolean saveDisguises) {
savePlayerDisguises = saveDisguises;
}
public static void setSaveEntityDisguises(boolean saveDisguises) {
saveEntityDisguises = saveDisguises;
}
public static DisguisePushing getPushingOption() {
return disablePushing;
}
public static HashMap<String, Disguise> getCustomDisguises() {
return customDisguises;
}
public static int getDisguiseCloneExpire() {
return disguiseCloneExpire;
}
public static int getDisguiseEntityExpire() {
return disguiseEntityExpire;
}
public static int getMaxClonedDisguises() {
return maxClonedDisguises;
}
public static String getUpdateNotificationPermission() {
return updateNotificationPermission;
}
public static boolean isSaveGameProfiles() {
return saveCache;
}
public static void setSaveGameProfiles(boolean doCache) {
saveCache = doCache;
}
public static boolean isUpdateGameProfiles() {
return updatePlayerCache;
}
public static void setUpdateGameProfiles(boolean setUpdatePlayerCache) {
updatePlayerCache = setUpdatePlayerCache;
}
public static void loadConfig() {
// Always save the default config
LibsDisguises.getInstance().saveDefaultConfig();
// Redundant for the first load, however other plugins may call loadConfig() at a later stage where we
// definitely want to reload it.
LibsDisguises.getInstance().reloadConfig();
ConfigurationSection config = LibsDisguises.getInstance().getConfig();
setSoundsEnabled(config.getBoolean("DisguiseSounds"));
setVelocitySent(config.getBoolean("SendVelocity"));
setViewDisguises(
config.getBoolean("ViewSelfDisguises")); // Since we can now toggle, the view disguises listener must
// always be on
PacketsManager.setViewDisguisesListener(true);
setHearSelfDisguise(config.getBoolean("HearSelfDisguise"));
setHideArmorFromSelf(config.getBoolean("RemoveArmor"));
setHideHeldItemFromSelf(config.getBoolean("RemoveHeldItem"));
setAddEntityAnimations(config.getBoolean("AddEntityAnimations"));
setNameOfPlayerShownAboveDisguise(config.getBoolean("ShowNamesAboveDisguises"));
setNameAboveHeadAlwaysVisible(config.getBoolean("NameAboveHeadAlwaysVisible"));
setModifyBoundingBox(config.getBoolean("ModifyBoundingBox"));
setMonstersIgnoreDisguises(config.getBoolean("MonstersIgnoreDisguises"));
setDisguiseBlownWhenAttacking(
config.getBoolean("BlowDisguises", config.getBoolean("BlowDisguisesWhenAttacking")));
setDisguiseBlownWhenAttacked(
config.getBoolean("BlowDisguises", config.getBoolean("BlowDisguisesWhenAttacked")));
setKeepDisguiseOnPlayerDeath(config.getBoolean("KeepDisguises.PlayerDeath"));
setMiscDisguisesForLivingEnabled(config.getBoolean("MiscDisguisesForLiving"));
setMovementPacketsEnabled(config.getBoolean("PacketsEnabled.Movement"));
setWitherSkullPacketsEnabled(config.getBoolean("PacketsEnabled.WitherSkull"));
setEquipmentPacketsEnabled(config.getBoolean("PacketsEnabled.Equipment"));
setAnimationPacketsEnabled(config.getBoolean("PacketsEnabled.Animation"));
setBedPacketsEnabled(config.getBoolean("PacketsEnabled.Bed"));
setEntityStatusPacketsEnabled(config.getBoolean("PacketsEnabled.EntityStatus"));
setCollectPacketsEnabled(config.getBoolean("PacketsEnabled.Collect"));
setMetadataPacketsEnabled(config.getBoolean("PacketsEnabled.Metadata"));
setMaxHealthDeterminedByDisguisedEntity(config.getBoolean("MaxHealthDeterminedByEntity"));
setDisguiseEntityExpire(config.getInt("DisguiseEntityExpire"));
setDisguiseCloneExpire(config.getInt("DisguiseCloneExpire"));
setMaxClonedDisguises(config.getInt("DisguiseCloneSize"));
setSheepDyeable(config.getBoolean("DyeableSheep"));
setWolfDyeable(config.getBoolean("DyeableWolf"));
setUndisguiseOnWorldChange(config.getBoolean("UndisguiseOnWorldChange"));
setUpdateNotificationPermission(config.getString("Permission"));
setStopShulkerDisguisesFromMoving(config.getBoolean("StopShulkerDisguisesFromMoving", true));
setHideDisguisedPlayers(config.getBoolean("HideDisguisedPlayersFromTab"));
setShowDisguisedPlayersInTab(config.getBoolean("ShowPlayerDisguisesInTab"));
setDisabledInvisibility(config.getBoolean("DisableInvisibility"));
setSaveGameProfiles(config.getBoolean("SaveGameProfiles"));
setUpdateGameProfiles(config.getBoolean("UpdateGameProfiles"));
setSavePlayerDisguises(config.getBoolean("SaveDisguises.Players"));
setSaveEntityDisguises(config.getBoolean("SaveDisguises.Entities"));
setUseTranslations(config.getBoolean("Translations"));
setModifyCollisions(config.getBoolean("Scoreboard.Collisions"));
setDisableFriendlyInvisibles(config.getBoolean("Scoreboard.DisableFriendlyInvisibles"));
setWarnScoreboardConflict(config.getBoolean("Scoreboard.WarnConflict"));
if (!LibsPremium.isPremium() && (isSavePlayerDisguises() || isSaveEntityDisguises())) {
DisguiseUtilities.getLogger().warning("You must purchase the plugin to use saved disguises!");
}
try {
String option = config.getString("SelfDisguisesScoreboard", DisguisePushing.MODIFY_SCOREBOARD.name())
.toUpperCase();
if (!option.endsWith("_SCOREBOARD"))
option += "_SCOREBOARD";
disablePushing = DisguisePushing.valueOf(option);
}
catch (Exception ex) {
DisguiseUtilities.getLogger().info("Cannot parse '" + config.getString("SelfDisguisesScoreboard") +
"' to a valid option for SelfDisguisesTeam");
}
loadCustomDisguises();
int missingConfigs = 0;
for (String key : config.getDefaultSection().getKeys(true)) {
if (config.contains(key, true)) {
continue;
}
missingConfigs++;
}
if (missingConfigs > 0) {
DisguiseUtilities.getLogger().warning(
"Your config is missing " + missingConfigs + " options! Please consider regenerating your config!");
}
}
static void loadCustomDisguises() {
customDisguises.clear();
File disguisesFile = new File("plugins/LibsDisguises/disguises.yml");
if (!disguisesFile.exists())
return;
YamlConfiguration disguisesConfig = YamlConfiguration.loadConfiguration(disguisesFile);
ConfigurationSection section = disguisesConfig.getConfigurationSection("Disguises");
if (section == null) {
return;
}
int failedCustomDisguises = 0;
for (String key : section.getKeys(false)) {
String toParse = section.getString(key);
if (getCustomDisguise(toParse) != null) {
DisguiseUtilities.getLogger()
.severe("Cannot create the custom disguise '" + key + "' as there is a name conflict!");
continue;
}
try {
Disguise disguise = DisguiseParser
.parseDisguise(Bukkit.getConsoleSender(), "disguise", DisguiseParser.split(toParse),
DisguiseParser.getPermissions(Bukkit.getConsoleSender(), "disguise"));
customDisguises.put(key, disguise);
DisguiseUtilities.getLogger().info("Loaded custom disguise " + key);
}
catch (DisguiseParseException e) {
DisguiseUtilities.getLogger().severe("Error while loading custom disguise '" + key + "'" +
(e.getMessage() == null ? "" : ": " + e.getMessage()));
if (e.getMessage() == null)
e.printStackTrace();
failedCustomDisguises++;
}
catch (Exception e) {
e.printStackTrace();
}
}
if (failedCustomDisguises > 0) {
DisguiseUtilities.getLogger().severe("Failed to load " + failedCustomDisguises + " custom disguises");
}
DisguiseUtilities.getLogger().info("Loaded " + customDisguises.size() + " custom disguise" +
(customDisguises.size() == 1 ? "" : "s"));
}
public static boolean isAnimationPacketsEnabled() {
return animationEnabled;
}
public static boolean isBedPacketsEnabled() {
return bedEnabled;
}
public static boolean isCollectPacketsEnabled() {
return collectEnabled;
}
public static boolean isDisabledInvisibility() {
return disableInvisibility;
}
public static boolean isDisguiseBlownWhenAttacking() {
return blowDisguisesWhenAttacking;
}
public static boolean isDisguiseBlownWhenAttacked() {
return blowDisguisesWhenAttacked;
}
public static boolean isEntityAnimationsAdded() {
return entityAnimationsAdded;
}
public static boolean isEntityStatusPacketsEnabled() {
return entityStatusEnabled;
}
public static boolean isEquipmentPacketsEnabled() {
return equipmentEnabled;
}
public static boolean isHideDisguisedPlayers() {
return hideDisguisedPlayers;
}
/**
* Is the plugin modifying the inventory packets so that players when self disguised, do not see their armor
* floating around
*/
public static boolean isHidingArmorFromSelf() {
return hidingArmor;
}
/**
* Does the plugin appear to remove the item they are holding, to prevent a floating sword when they are viewing
* self disguise
*/
public static boolean isHidingHeldItemFromSelf() {
return hidingHeldItem;
}
public static boolean isKeepDisguiseOnPlayerDeath() {
return keepDisguisePlayerDeath;
}
public static boolean isMaxHealthDeterminedByDisguisedEntity() {
return maxHealthIsDisguisedEntity;
}
public static boolean isMetadataPacketsEnabled() {
return sendsEntityMetadata;
}
public static boolean isMiscDisguisesForLivingEnabled() {
return miscDisguisesForLivingEnabled;
}
public static boolean isModifyBoundingBox() {
return modifyBoundingBox;
}
public static boolean isMonstersIgnoreDisguises() {
return targetDisguises;
}
public static boolean isMovementPacketsEnabled() {
return movementEnabled;
}
public static boolean isNameAboveHeadAlwaysVisible() {
return showNameAboveHeadAlwaysVisible;
}
public static boolean isNameOfPlayerShownAboveDisguise() {
return showNameAboveHead;
}
public static boolean isSelfDisguisesSoundsReplaced() {
return hearSelfDisguise;
}
public static boolean isSheepDyeable() {
return colorizeSheep;
}
public static boolean isShowDisguisedPlayersInTab() {
return displayPlayerDisguisesInTab;
}
/**
* Is the sound packets caught and modified
*/
public static boolean isSoundEnabled() {
return PacketsManager.isHearDisguisesEnabled();
}
public static boolean isStopShulkerDisguisesFromMoving() {
return stopShulkerDisguisesFromMoving;
}
public static boolean isUndisguiseOnWorldChange() {
return undisguiseSwitchWorlds;
}
/**
* Is the velocity packets sent
*
* @return
*/
public static boolean isVelocitySent() {
return sendVelocity;
}
/**
* The default value if a player views his own disguise
*
* @return
*/
public static boolean isViewDisguises() {
return viewSelfDisguise;
}
public static boolean isWitherSkullPacketsEnabled() {
return witherSkullEnabled;
}
public static boolean isWolfDyeable() {
return colorizeWolf;
}
public static void setAddEntityAnimations(boolean isEntityAnimationsAdded) {
entityAnimationsAdded = isEntityAnimationsAdded;
}
public static void setAnimationPacketsEnabled(boolean enabled) {
if (enabled != isAnimationPacketsEnabled()) {
animationEnabled = enabled;
PacketsManager.setupMainPacketsListener();
}
}
public static void setBedPacketsEnabled(boolean enabled) {
if (enabled != isBedPacketsEnabled()) {
bedEnabled = enabled;
PacketsManager.setupMainPacketsListener();
}
}
public static void setCollectPacketsEnabled(boolean enabled) {
if (enabled != isCollectPacketsEnabled()) {
collectEnabled = enabled;
PacketsManager.setupMainPacketsListener();
}
}
public static void setDisabledInvisibility(boolean disableInvis) {
disableInvisibility = disableInvis;
}
public static void setDisguiseBlownWhenAttacking(boolean blowDisguise) {
blowDisguisesWhenAttacking = blowDisguise;
}
public static void setDisguiseBlownWhenAttacked(boolean blowDisguise) {
blowDisguisesWhenAttacked = blowDisguise;
}
public static void setDisguiseCloneExpire(int newExpires) {
disguiseCloneExpire = newExpires;
}
public static void setDisguiseEntityExpire(int newExpires) {
disguiseEntityExpire = newExpires;
}
public static void setEntityStatusPacketsEnabled(boolean enabled) {
if (enabled != isEntityStatusPacketsEnabled()) {
entityStatusEnabled = enabled;
PacketsManager.setupMainPacketsListener();
}
}
public static void setEquipmentPacketsEnabled(boolean enabled) {
if (enabled != isEquipmentPacketsEnabled()) {
equipmentEnabled = enabled;
PacketsManager.setupMainPacketsListener();
}
}
/**
* Can players hear their own disguises
*/
public static void setHearSelfDisguise(boolean replaceSound) {
if (hearSelfDisguise != replaceSound) {
hearSelfDisguise = replaceSound;
}
}
/**
* Set the plugin to hide self disguises armor from theirselves
*/
public static void setHideArmorFromSelf(boolean hideArmor) {
if (hidingArmor != hideArmor) {
hidingArmor = hideArmor;
PacketsManager.setInventoryListenerEnabled(isHidingHeldItemFromSelf() || isHidingArmorFromSelf());
}
}
public static void setHideDisguisedPlayers(boolean hideDisguisedPlayersInTab) {
hideDisguisedPlayers = hideDisguisedPlayersInTab;
}
/**
* Does the plugin appear to remove the item they are holding, to prevent a floating sword when they are viewing
* self disguise
*/
public static void setHideHeldItemFromSelf(boolean hideHelditem) {
if (hidingHeldItem != hideHelditem) {
hidingHeldItem = hideHelditem;
PacketsManager.setInventoryListenerEnabled(isHidingHeldItemFromSelf() || isHidingArmorFromSelf());
}
}
public static void setKeepDisguiseOnPlayerDeath(boolean keepDisguise) {
keepDisguisePlayerDeath = keepDisguise;
}
public static void setMaxClonedDisguises(int newMax) {
maxClonedDisguises = newMax;
}
public static void setMaxHealthDeterminedByDisguisedEntity(boolean isDetermined) {
maxHealthIsDisguisedEntity = isDetermined;
}
public static void setMetadataPacketsEnabled(boolean enabled) {
sendsEntityMetadata = enabled;
}
public static void setMiscDisguisesForLivingEnabled(boolean enabled) {
if (enabled != isMiscDisguisesForLivingEnabled()) {
miscDisguisesForLivingEnabled = enabled;
PacketsManager.setupMainPacketsListener();
}
}
public static void setModifyBoundingBox(boolean modifyBounding) {
modifyBoundingBox = modifyBounding;
}
public static void setMonstersIgnoreDisguises(boolean ignore) {
targetDisguises = ignore;
}
public static void setMovementPacketsEnabled(boolean enabled) {
if (enabled != isMovementPacketsEnabled()) {
movementEnabled = enabled;
PacketsManager.setupMainPacketsListener();
}
}
public static void setNameAboveHeadAlwaysVisible(boolean alwaysVisible) {
showNameAboveHeadAlwaysVisible = alwaysVisible;
}
public static void setNameOfPlayerShownAboveDisguise(boolean showNames) {
showNameAboveHead = showNames;
}
public static void setSheepDyeable(boolean color) {
colorizeSheep = color;
}
public static void setShowDisguisedPlayersInTab(boolean displayPlayerDisguisesInTablist) {
displayPlayerDisguisesInTab = displayPlayerDisguisesInTablist;
}
/**
* Set if the disguises play sounds when hurt
*/
public static void setSoundsEnabled(boolean isSoundsEnabled) {
PacketsManager.setHearDisguisesListener(isSoundsEnabled);
}
public static void setStopShulkerDisguisesFromMoving(boolean stopShulkerDisguisesFromMoving) {
DisguiseConfig.stopShulkerDisguisesFromMoving = stopShulkerDisguisesFromMoving;
}
public static void setUndisguiseOnWorldChange(boolean isUndisguise) {
undisguiseSwitchWorlds = isUndisguise;
}
public static void setUpdateNotificationPermission(String newPermission) {
updateNotificationPermission = newPermission;
}
/**
* Disable velocity packets being sent for w/e reason. Maybe you want every ounce of performance you can get?
*
* @param sendVelocityPackets
*/
public static void setVelocitySent(boolean sendVelocityPackets) {
sendVelocity = sendVelocityPackets;
}
public static void setViewDisguises(boolean seeOwnDisguise) {
viewSelfDisguise = seeOwnDisguise;
}
public static void setWitherSkullPacketsEnabled(boolean enabled) {
witherSkullEnabled = enabled;
}
public static void setWolfDyeable(boolean color) {
colorizeWolf = color;
}
private DisguiseConfig() {
}
}

View File

@@ -0,0 +1,729 @@
package me.libraryaddict.disguise;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.EnumWrappers.NativeGameMode;
import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction;
import com.comphenix.protocol.wrappers.PlayerInfoData;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.disguisetypes.PlayerDisguise;
import me.libraryaddict.disguise.disguisetypes.TargetedDisguise;
import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher;
import me.libraryaddict.disguise.utilities.DisguiseParser;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguiseParseException;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.UpdateChecker;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.scoreboard.Team;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
public class DisguiseListener implements Listener {
private String currentVersion;
private HashMap<String, Boolean[]> disguiseClone = new HashMap<>();
private HashMap<String, Disguise> disguiseEntity = new HashMap<>();
private HashMap<String, String[]> disguiseModify = new HashMap<>();
private HashMap<String, BukkitRunnable> disguiseRunnable = new HashMap<>();
private String latestVersion;
private LibsDisguises plugin;
private BukkitTask updaterTask;
public DisguiseListener(LibsDisguises libsDisguises) {
plugin = libsDisguises;
if (plugin.getConfig().getBoolean("NotifyUpdate")) {
currentVersion = plugin.getDescription().getVersion();
updaterTask = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
UpdateChecker updateChecker = new UpdateChecker();
updateChecker.checkUpdate("v" + currentVersion);
latestVersion = updateChecker.getLatestVersion();
if (latestVersion == null) {
return;
}
latestVersion = "v" + latestVersion;
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
for (Player p : Bukkit.getOnlinePlayers()) {
if (!p.hasPermission(DisguiseConfig.getUpdateNotificationPermission())) {
continue;
}
p.sendMessage(LibsMsg.UPDATE_READY.get(currentVersion, latestVersion));
}
}
});
}
catch (Exception ex) {
DisguiseUtilities.getLogger()
.warning(String.format("Failed to check for update: %s", ex.getMessage()));
}
}
}, 0, (20 * 60 * 60 * 6)); // Check every 6 hours
// 20 ticks * 60 seconds * 60 minutes * 6 hours
}
if (!DisguiseConfig.isSaveEntityDisguises())
return;
for (World world : Bukkit.getWorlds()) {
for (Entity entity : world.getEntities()) {
Disguise[] disguises = DisguiseUtilities.getSavedDisguises(entity.getUniqueId(), true);
if (disguises.length <= 0)
continue;
DisguiseUtilities.resetPluginTimer();
for (Disguise disguise : disguises) {
disguise.setEntity(entity);
disguise.startDisguise();
}
}
}
}
public void cleanup() {
for (BukkitRunnable r : disguiseRunnable.values()) {
r.cancel();
}
for (Disguise d : disguiseEntity.values()) {
d.removeDisguise();
}
disguiseClone.clear();
updaterTask.cancel();
}
private void checkPlayerCanBlowDisguise(Player player) {
Disguise[] disguises = DisguiseAPI.getDisguises(player);
if (disguises.length > 0) {
DisguiseAPI.undisguiseToAll(player);
String blown = LibsMsg.BLOWN_DISGUISE.get();
if (blown.length() > 0) {
player.sendMessage(blown);
}
}
}
private void chunkMove(Player player, Location newLoc, Location oldLoc) {
try {
// Resend the bed chunks
for (PacketContainer packet : DisguiseUtilities.getBedChunkPacket(newLoc, oldLoc)) {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false);
}
if (newLoc != null) {
for (HashSet<TargetedDisguise> list : DisguiseUtilities.getDisguises().values()) {
for (TargetedDisguise disguise : list) {
if (disguise.getEntity() == null)
continue;
if (!disguise.isPlayerDisguise())
continue;
if (!disguise.canSee(player))
continue;
if (!((PlayerDisguise) disguise).getWatcher().isSleeping())
continue;
if (!DisguiseUtilities.getPerverts(disguise).contains(player))
continue;
PacketContainer[] packets = DisguiseUtilities.getBedPackets(
disguise.getEntity() == player ? newLoc : disguise.getEntity().getLocation(), newLoc,
(PlayerDisguise) disguise);
if (disguise.getEntity() == player) {
for (PacketContainer packet : packets) {
packet.getIntegers().write(0, DisguiseAPI.getSelfDisguiseId());
}
}
for (PacketContainer packet : packets) {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
}
}
}
}
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onAttack(EntityDamageByEntityEvent event) {
if (DisguiseConfig.isDisguiseBlownWhenAttacked() && event.getEntity() instanceof Player) {
checkPlayerCanBlowDisguise((Player) event.getEntity());
}
if (DisguiseConfig.isDisguiseBlownWhenAttacking() && event.getDamager() instanceof Player) {
checkPlayerCanBlowDisguise((Player) event.getDamager());
}
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
if (!DisguiseConfig.isSaveEntityDisguises())
return;
for (Entity entity : event.getChunk().getEntities()) {
Disguise[] disguises = DisguiseAPI.getDisguises(entity);
if (disguises.length <= 0)
continue;
DisguiseUtilities.saveDisguises(entity.getUniqueId(), disguises);
}
}
@EventHandler
public void onChunkUnload(WorldUnloadEvent event) {
if (!DisguiseConfig.isSaveEntityDisguises())
return;
for (Entity entity : event.getWorld().getEntities()) {
if (entity instanceof Player)
continue;
Disguise[] disguises = DisguiseAPI.getDisguises(entity);
if (disguises.length <= 0)
continue;
DisguiseUtilities.saveDisguises(entity.getUniqueId(), disguises);
}
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
if (!DisguiseConfig.isSaveEntityDisguises())
return;
for (Entity entity : event.getChunk().getEntities()) {
Disguise[] disguises = DisguiseUtilities.getSavedDisguises(entity.getUniqueId(), true);
if (disguises.length <= 0)
continue;
DisguiseUtilities.resetPluginTimer();
for (Disguise disguise : disguises) {
disguise.setEntity(entity);
disguise.startDisguise();
}
}
}
@EventHandler
public void onWorldLoad(WorldLoadEvent event) {
if (!DisguiseConfig.isSaveEntityDisguises())
return;
for (Entity entity : event.getWorld().getEntities()) {
Disguise[] disguises = DisguiseUtilities.getSavedDisguises(entity.getUniqueId(), true);
if (disguises.length <= 0)
continue;
DisguiseUtilities.resetPluginTimer();
for (Disguise disguise : disguises) {
disguise.setEntity(entity);
disguise.startDisguise();
}
}
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Player p = event.getPlayer();
if (latestVersion != null && p.hasPermission(DisguiseConfig.getUpdateNotificationPermission())) {
p.sendMessage(LibsMsg.UPDATE_READY.get(currentVersion, latestVersion));
}
if (DisguiseConfig.isBedPacketsEnabled()) {
chunkMove(p, p.getLocation(), null);
}
if (DisguiseConfig.isSaveGameProfiles() && DisguiseConfig.isUpdateGameProfiles() &&
DisguiseUtilities.hasGameProfile(p.getName())) {
WrappedGameProfile profile = WrappedGameProfile.fromPlayer(p);
if (!profile.getProperties().isEmpty()) {
DisguiseUtilities.addGameProfile(p.getName(), profile);
}
}
if (DisguiseConfig.isSavePlayerDisguises()) {
Disguise[] disguises = DisguiseUtilities.getSavedDisguises(p.getUniqueId(), true);
if (disguises.length > 0) {
DisguiseUtilities.resetPluginTimer();
}
for (Disguise disguise : disguises) {
disguise.setEntity(p);
disguise.startDisguise();
}
}
for (HashSet<TargetedDisguise> disguiseList : DisguiseUtilities.getDisguises().values()) {
for (TargetedDisguise targetedDisguise : disguiseList) {
if (targetedDisguise.getEntity() == null)
continue;
if (!targetedDisguise.canSee(p))
continue;
if (!(targetedDisguise instanceof PlayerDisguise))
continue;
PlayerDisguise disguise = (PlayerDisguise) targetedDisguise;
if (disguise.isDisplayedInTab()) {
try {
PacketContainer addTab = new PacketContainer(PacketType.Play.Server.PLAYER_INFO);
addTab.getPlayerInfoAction().write(0, PlayerInfoAction.ADD_PLAYER);
addTab.getPlayerInfoDataLists().write(0, Collections.singletonList(
new PlayerInfoData(disguise.getGameProfile(), 0, NativeGameMode.SURVIVAL,
WrappedChatComponent.fromText(disguise.getGameProfile().getName()))));
ProtocolLibrary.getProtocolManager().sendServerPacket(p, addTab);
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
/**
* Most likely faster if we don't bother doing checks if he sees a player disguise
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onMove(PlayerMoveEvent event) {
if (DisguiseConfig.isBedPacketsEnabled()) {
Location to = event.getTo();
Location from = event.getFrom();
if (DisguiseUtilities.getChunkCord(to.getBlockX()) != DisguiseUtilities.getChunkCord(from.getBlockX()) ||
DisguiseUtilities.getChunkCord(to.getBlockZ()) !=
DisguiseUtilities.getChunkCord(from.getBlockZ())) {
chunkMove(event.getPlayer(), to, from);
}
}
if (DisguiseConfig.isStopShulkerDisguisesFromMoving()) {
Disguise disguise;
if ((disguise = DisguiseAPI.getDisguise(event.getPlayer())) != null) {
if (disguise.getType() ==
DisguiseType.SHULKER) { // Stop Shulker disguises from moving their coordinates
Location from = event.getFrom();
Location to = event.getTo();
to.setX(from.getX());
to.setZ(from.getZ());
event.setTo(to);
}
}
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
DisguiseUtilities.removeSelfDisguiseScoreboard(player);
if (!DisguiseConfig.isSavePlayerDisguises())
return;
Disguise[] disguises = DisguiseAPI.getDisguises(player);
if (disguises.length <= 0)
return;
DisguiseUtilities.saveDisguises(player.getUniqueId(), disguises);
}
@EventHandler
public void onRespawn(PlayerRespawnEvent event) {
if (DisguiseConfig.isBedPacketsEnabled()) {
final Player player = event.getPlayer();
chunkMove(event.getPlayer(), null, player.getLocation());
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
chunkMove(player, player.getLocation(), null);
}
});
}
}
@EventHandler
public void onRightClick(PlayerInteractEntityEvent event) {
Player p = event.getPlayer();
if (!disguiseEntity.containsKey(p.getName()) && !disguiseClone.containsKey(p.getName()) &&
!disguiseModify.containsKey(p.getName())) {
return;
}
event.setCancelled(true);
disguiseRunnable.remove(p.getName()).cancel();
Entity entity = event.getRightClicked();
String entityName;
if (entity instanceof Player && !disguiseClone.containsKey(p.getName())) {
entityName = entity.getName();
} else {
entityName = DisguiseType.getType(entity).toReadable();
}
if (disguiseClone.containsKey(p.getName())) {
Boolean[] options = disguiseClone.remove(p.getName());
DisguiseUtilities.createClonedDisguise(p, entity, options);
} else if (disguiseEntity.containsKey(p.getName())) {
Disguise disguise = disguiseEntity.remove(p.getName());
if (disguise != null) {
if (disguise.isMiscDisguise() && !DisguiseConfig.isMiscDisguisesForLivingEnabled() &&
entity instanceof LivingEntity) {
p.sendMessage(LibsMsg.DISABLED_LIVING_TO_MISC.get());
} else {
if (entity instanceof Player && DisguiseConfig.isNameOfPlayerShownAboveDisguise()) {
if (disguise.getWatcher() instanceof LivingWatcher) {
Team team = ((Player) entity).getScoreboard().getEntryTeam(entity.getName());
disguise.getWatcher().setCustomName(
(team == null ? "" : team.getPrefix()) + entity.getName() +
(team == null ? "" : team.getSuffix()));
if (DisguiseConfig.isNameAboveHeadAlwaysVisible()) {
disguise.getWatcher().setCustomNameVisible(true);
}
}
}
DisguiseAPI.disguiseEntity(entity, disguise);
String disguiseName;
if (disguise instanceof PlayerDisguise) {
disguiseName = ((PlayerDisguise) disguise).getName();
} else {
disguiseName = disguise.getType().toReadable();
}
// Jeez, maybe I should redo my messages here
if (disguise.isDisguiseInUse()) {
if (disguise.isPlayerDisguise()) {
if (entity instanceof Player) {
p.sendMessage(LibsMsg.LISTEN_ENTITY_PLAYER_DISG_PLAYER.get(entityName, disguiseName));
} else {
p.sendMessage(LibsMsg.LISTEN_ENTITY_ENTITY_DISG_PLAYER.get(entityName, disguiseName));
}
} else {
if (entity instanceof Player) {
p.sendMessage(LibsMsg.LISTEN_ENTITY_PLAYER_DISG_ENTITY.get(entityName, disguiseName));
} else {
p.sendMessage(LibsMsg.LISTEN_ENTITY_ENTITY_DISG_ENTITY.get(entityName, disguiseName));
}
}
} else {
if (disguise.isPlayerDisguise()) {
if (entity instanceof Player) {
p.sendMessage(
LibsMsg.LISTEN_ENTITY_PLAYER_DISG_PLAYER_FAIL.get(entityName, disguiseName));
} else {
p.sendMessage(
LibsMsg.LISTEN_ENTITY_ENTITY_DISG_PLAYER_FAIL.get(entityName, disguiseName));
}
} else {
if (entity instanceof Player) {
p.sendMessage(
LibsMsg.LISTEN_ENTITY_PLAYER_DISG_ENTITY_FAIL.get(entityName, disguiseName));
} else {
p.sendMessage(
LibsMsg.LISTEN_ENTITY_ENTITY_DISG_ENTITY_FAIL.get(entityName, disguiseName));
}
}
}
}
} else {
if (DisguiseAPI.isDisguised(entity)) {
DisguiseAPI.undisguiseToAll(entity);
if (entity instanceof Player)
p.sendMessage(LibsMsg.LISTEN_UNDISG_PLAYER.get(entityName));
else
p.sendMessage(LibsMsg.LISTEN_UNDISG_ENT.get(entityName));
} else {
if (entity instanceof Player)
p.sendMessage(LibsMsg.LISTEN_UNDISG_PLAYER_FAIL.get(entityName));
else
p.sendMessage(LibsMsg.LISTEN_UNDISG_ENT_FAIL.get(entityName));
}
}
} else if (disguiseModify.containsKey(p.getName())) {
String[] options = disguiseModify.remove(p.getName());
Disguise disguise = DisguiseAPI.getDisguise(p, entity);
if (disguise == null) {
p.sendMessage(LibsMsg.UNDISG_PLAYER_FAIL.get(entityName));
return;
}
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> perms = DisguiseParser
.getPermissions(p, "libsdisguises.disguiseentitymodify.");
if (!perms.containsKey(new DisguisePerm(disguise.getType()))) {
p.sendMessage(LibsMsg.DMODPLAYER_NOPERM.get());
return;
}
try {
DisguiseParser.callMethods(p, disguise, perms.get(new DisguisePerm(disguise.getType())),
new ArrayList<String>(), options);
p.sendMessage(LibsMsg.LISTENER_MODIFIED_DISG.get());
}
catch (DisguiseParseException ex) {
if (ex.getMessage() != null) {
p.sendMessage(ex.getMessage());
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
@EventHandler
public void onTarget(EntityTargetEvent event) {
if (DisguiseConfig.isMonstersIgnoreDisguises() && event.getTarget() != null &&
event.getTarget() instanceof Player && DisguiseAPI.isDisguised(event.getTarget())) {
switch (event.getReason()) {
case TARGET_ATTACKED_ENTITY:
case TARGET_ATTACKED_OWNER:
case OWNER_ATTACKED_TARGET:
case CUSTOM:
break;
default:
event.setCancelled(true);
break;
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onTeleport(PlayerTeleportEvent event) {
final Player player = event.getPlayer();
Location to = event.getTo();
Location from = event.getFrom();
if (DisguiseConfig.isBedPacketsEnabled()) {
if (DisguiseUtilities.getChunkCord(to.getBlockX()) != DisguiseUtilities.getChunkCord(from.getBlockX()) ||
DisguiseUtilities.getChunkCord(to.getBlockZ()) !=
DisguiseUtilities.getChunkCord(from.getBlockZ())) {
chunkMove(player, null, from);
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
chunkMove(player, player.getLocation(), null);
}
});
}
}
if (!DisguiseAPI.isDisguised(player)) {
return;
}
if (DisguiseConfig.isUndisguiseOnWorldChange() && to.getWorld() != null && from.getWorld() != null &&
to.getWorld() != from.getWorld()) {
for (Disguise disguise : DisguiseAPI.getDisguises(event.getPlayer())) {
disguise.removeDisguise();
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onVehicleEnter(VehicleEnterEvent event) {
if (event.getEntered() instanceof Player &&
DisguiseAPI.isDisguised((Player) event.getEntered(), event.getEntered())) {
DisguiseUtilities.removeSelfDisguise((Player) event.getEntered());
((Player) event.getEntered()).updateInventory();
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onVehicleLeave(VehicleExitEvent event) {
if (event.getExited() instanceof Player) {
final Disguise disguise = DisguiseAPI.getDisguise((Player) event.getExited(), event.getExited());
if (disguise != null) {
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
DisguiseUtilities.setupFakeDisguise(disguise);
((Player) disguise.getEntity()).updateInventory();
}
});
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onWorldSwitch(final PlayerChangedWorldEvent event) {
if (DisguiseConfig.isBedPacketsEnabled()) {
chunkMove(event.getPlayer(), event.getPlayer().getLocation(), null);
}
if (!DisguiseAPI.isDisguised(event.getPlayer())) {
return;
}
if (DisguiseConfig.isUndisguiseOnWorldChange()) {
for (Disguise disguise : DisguiseAPI.getDisguises(event.getPlayer())) {
disguise.removeDisguise();
}
} else {
// Stupid hack to fix worldswitch invisibility bug
final boolean viewSelfToggled = DisguiseAPI.isViewSelfToggled(event.getPlayer());
if (viewSelfToggled) {
final Disguise disguise = DisguiseAPI.getDisguise(event.getPlayer());
disguise.setViewSelfDisguise(false);
Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run() {
disguise.setViewSelfDisguise(true);
}
}, 20L); // I wish I could use lambdas here, so badly
}
}
}
public void setDisguiseClone(final String player, Boolean[] options) {
if (disguiseRunnable.containsKey(player)) {
BukkitRunnable run = disguiseRunnable.remove(player);
run.cancel();
run.run();
}
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
disguiseClone.remove(player);
disguiseRunnable.remove(player);
}
};
runnable.runTaskLater(plugin, 20 * DisguiseConfig.getDisguiseCloneExpire());
disguiseRunnable.put(player, runnable);
disguiseClone.put(player, options);
}
public void setDisguiseEntity(final String player, Disguise disguise) {
if (disguiseRunnable.containsKey(player)) {
BukkitRunnable run = disguiseRunnable.remove(player);
run.cancel();
run.run();
}
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
disguiseEntity.remove(player);
disguiseRunnable.remove(player);
}
};
runnable.runTaskLater(plugin, 20 * DisguiseConfig.getDisguiseEntityExpire());
disguiseRunnable.put(player, runnable);
disguiseEntity.put(player, disguise);
}
public void setDisguiseModify(final String player, String[] args) {
if (disguiseRunnable.containsKey(player)) {
BukkitRunnable run = disguiseRunnable.remove(player);
run.cancel();
run.run();
}
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
disguiseModify.remove(player);
disguiseRunnable.remove(player);
}
};
runnable.runTaskLater(plugin, 20 * DisguiseConfig.getDisguiseEntityExpire());
disguiseRunnable.put(player, runnable);
disguiseModify.put(player, args);
}
}

View File

@@ -0,0 +1,614 @@
package me.libraryaddict.disguise;
import com.comphenix.protocol.reflect.FieldAccessException;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import com.comphenix.protocol.wrappers.WrappedWatchableObject;
import me.libraryaddict.disguise.commands.*;
import me.libraryaddict.disguise.disguisetypes.*;
import me.libraryaddict.disguise.disguisetypes.watchers.*;
import me.libraryaddict.disguise.utilities.*;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.*;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
public class LibsDisguises extends JavaPlugin {
private static LibsDisguises instance;
private DisguiseListener listener;
@Override
public void onEnable() {
instance = this;
getLogger().info("Discovered nms version: " + ReflectionManager.getBukkitVersion());
if (!new File(getDataFolder(), "disguises.yml").exists()) {
saveResource("disguises.yml", false);
}
LibsPremium.check(getDescription().getVersion());
if (ReflectionManager.getMinecraftVersion().startsWith("1.13")) {
if (!LibsPremium.isPremium()) {
getLogger().severe("You must purchase the plugin to use 1.13!");
getLogger().severe("This will be released free two weeks after all bugs have been fixed!");
getLogger().severe("If you've already purchased the plugin, place the purchased jar inside the " +
"Lib's Disguises plugin folder");
getPluginLoader().disablePlugin(this);
return;
}
} else {
getLogger().severe("You're using the wrong version of Lib's Disguises for your server! This is " +
"intended for 1.13!");
getPluginLoader().disablePlugin(this);
return;
}
PacketsManager.init(this);
DisguiseUtilities.init(this);
registerValues();
DisguiseConfig.loadConfig();
PacketsManager.addPacketListeners();
listener = new DisguiseListener(this);
Bukkit.getPluginManager().registerEvents(listener, this);
registerCommand("disguise", new DisguiseCommand());
registerCommand("undisguise", new UndisguiseCommand());
registerCommand("disguiseplayer", new DisguisePlayerCommand());
registerCommand("undisguiseplayer", new UndisguisePlayerCommand());
registerCommand("undisguiseentity", new UndisguiseEntityCommand());
registerCommand("disguiseentity", new DisguiseEntityCommand());
registerCommand("disguiseradius", new DisguiseRadiusCommand(getConfig().getInt("DisguiseRadiusMax")));
registerCommand("undisguiseradius", new UndisguiseRadiusCommand(getConfig().getInt("UndisguiseRadiusMax")));
registerCommand("disguisehelp", new DisguiseHelpCommand());
registerCommand("disguiseclone", new DisguiseCloneCommand());
registerCommand("libsdisguises", new LibsDisguisesCommand());
registerCommand("disguiseviewself", new DisguiseViewSelfCommand());
registerCommand("disguisemodify", new DisguiseModifyCommand());
registerCommand("disguisemodifyentity", new DisguiseModifyEntityCommand());
registerCommand("disguisemodifyplayer", new DisguiseModifyPlayerCommand());
registerCommand("disguisemodifyradius",
new DisguiseModifyRadiusCommand(getConfig().getInt("DisguiseRadiusMax")));
infectWithMetrics();
}
private void infectWithMetrics() {
Metrics metrics = new Metrics(this);
final String premium = LibsPremium.isPremium() ?
getDescription().getVersion().contains("SNAPSHOT") ? "Paid Builds" : "Paid Plugin" : "Free Builds";
metrics.addCustomChart(new Metrics.SimplePie("premium") {
@Override
public String getValue() {
return premium;
}
});
metrics.addCustomChart(new Metrics.SimplePie("translations") {
@Override
public String getValue() {
return LibsPremium.isPremium() && DisguiseConfig.isUseTranslations() ? "Yes" : "No";
}
});
metrics.addCustomChart(new Metrics.SimplePie("custom_disguises") {
@Override
public String getValue() {
HashMap map = DisguiseConfig.getCustomDisguises();
return map.size() + (map.containsKey("libraryaddict") ? -1 : 0) > 0 ? "Yes" : "No";
}
});
metrics.addCustomChart(new Metrics.MultiLineChart("disguised_entities") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> hashMap) {
for (HashSet<TargetedDisguise> list : DisguiseUtilities.getDisguises().values()) {
for (Disguise disg : list) {
if (disg.getEntity() == null || !disg.isDisguiseInUse())
continue;
String name = disg.getEntity().getType().name();
hashMap.put(name, hashMap.containsKey(name) ? hashMap.get(name) + 1 : 1);
}
}
return hashMap;
}
});
metrics.addCustomChart(new Metrics.MultiLineChart("disguises_used") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> hashMap) {
for (HashSet<TargetedDisguise> list : DisguiseUtilities.getDisguises().values()) {
for (Disguise disg : list) {
if (disg.getEntity() == null || !disg.isDisguiseInUse())
continue;
String name = disg.getType().name();
hashMap.put(name, hashMap.containsKey(name) ? hashMap.get(name) + 1 : 1);
}
}
return hashMap;
}
});
metrics.addCustomChart(new Metrics.SimplePie("disguised_using") {
@Override
public String getValue() {
if (DisguiseUtilities.isPluginsUsed()) {
if (DisguiseUtilities.isCommandsUsed()) {
return "Plugins and Commands";
}
return "Plugins";
} else if (DisguiseUtilities.isCommandsUsed()) {
return "Commands";
}
return "Unknown";
}
});
metrics.addCustomChart(new Metrics.SimplePie("active_disguises") {
@Override
public String getValue() {
int disgs = 0;
for (HashSet set : DisguiseUtilities.getDisguises().values()) {
disgs += set.size();
}
if (disgs == 0)
return "0";
if (disgs <= 5)
return "1 to 5";
else if (disgs <= 15)
return "6 to 15";
else if (disgs <= 30)
return "16 to 30";
else if (disgs <= 60)
return "30 to 60";
else if (disgs <= 100)
return "60 to 100";
else if (disgs <= 200)
return "100 to 200";
return "More than 200";
}
});
metrics.addCustomChart(new Metrics.SimplePie("self_disguises") {
@Override
public String getValue() {
return DisguiseConfig.isViewDisguises() ? "Yes" : "No";
}
});
metrics.addCustomChart(new Metrics.SimplePie("spigot") {
@Override
public String getValue() {
try {
Class.forName("org.spigotmc.SpigotConfig");
return "Yes";
}
catch (Exception ex) {
return "No";
}
}
});
final boolean updates = getConfig().getBoolean("NotifyUpdate");
metrics.addCustomChart(new Metrics.SimplePie("updates") {
@Override
public String getValue() {
return updates ? "Enabled" : "Disabled";
}
});
metrics.addCustomChart(new Metrics.SimplePie("targeted_disguises") {
@Override
public String getValue() {
Collection<HashSet<TargetedDisguise>> list = DisguiseUtilities.getDisguises().values();
if (list.isEmpty())
return "Unknown";
for (HashSet<TargetedDisguise> dList : list) {
for (TargetedDisguise disg : dList) {
if (disg.getObservers().isEmpty())
continue;
return "Yes";
}
}
return "No";
}
});
}
@Override
public void onDisable() {
DisguiseUtilities.saveDisguises();
for (Player player : Bukkit.getOnlinePlayers()) {
DisguiseUtilities.removeSelfDisguiseScoreboard(player);
}
}
private void registerCommand(String commandName, CommandExecutor executioner) {
PluginCommand command = getCommand(commandName);
command.setExecutor(executioner);
if (executioner instanceof TabCompleter) {
command.setTabCompleter((TabCompleter) executioner);
}
}
/**
* Reloads the config with new config options.
*/
@Deprecated
public void reload() {
DisguiseConfig.loadConfig();
}
/**
* Here we create a nms entity for each disguise. Then grab their default values in their datawatcher. Then their
* sound volume
* for mob noises. As well as setting their watcher class and entity size.
*/
private void registerValues() {
for (DisguiseType disguiseType : DisguiseType.values()) {
if (disguiseType.getEntityType() == null) {
continue;
}
Class watcherClass;
try {
switch (disguiseType) {
case ARROW:
watcherClass = TippedArrowWatcher.class;
break;
case COD:
case SALMON:
watcherClass = FishWatcher.class;
break;
case SPECTRAL_ARROW:
watcherClass = ArrowWatcher.class;
break;
case PRIMED_TNT:
watcherClass = TNTWatcher.class;
break;
case MINECART_CHEST:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
watcherClass = MinecartWatcher.class;
break;
case SPIDER:
case CAVE_SPIDER:
watcherClass = SpiderWatcher.class;
break;
case PIG_ZOMBIE:
case HUSK:
case DROWNED:
watcherClass = ZombieWatcher.class;
break;
case MAGMA_CUBE:
watcherClass = SlimeWatcher.class;
break;
case ELDER_GUARDIAN:
watcherClass = GuardianWatcher.class;
break;
case WITHER_SKELETON:
case STRAY:
watcherClass = SkeletonWatcher.class;
break;
case ILLUSIONER:
case EVOKER:
watcherClass = IllagerWizardWatcher.class;
break;
case PUFFERFISH:
watcherClass = PufferFishWatcher.class;
break;
default:
watcherClass = Class.forName(
"me.libraryaddict.disguise.disguisetypes.watchers." + toReadable(disguiseType.name()) +
"Watcher");
break;
}
}
catch (ClassNotFoundException ex) {
// There is no explicit watcher for this entity.
Class entityClass = disguiseType.getEntityType().getEntityClass();
if (entityClass != null) {
if (Tameable.class.isAssignableFrom(entityClass)) {
watcherClass = TameableWatcher.class;
} else if (Ageable.class.isAssignableFrom(entityClass)) {
watcherClass = AgeableWatcher.class;
} else if (Creature.class.isAssignableFrom(entityClass)) {
watcherClass = InsentientWatcher.class;
} else if (LivingEntity.class.isAssignableFrom(entityClass)) {
watcherClass = LivingWatcher.class;
} else if (Fish.class.isAssignableFrom(entityClass)) {
watcherClass = FishWatcher.class;
} else {
watcherClass = FlagWatcher.class;
}
} else {
watcherClass = FlagWatcher.class; // Disguise is unknown type
}
}
if (watcherClass == null) {
getLogger().severe("Error loading " + disguiseType.name() + ", FlagWatcher not assigned");
continue;
}
disguiseType.setWatcherClass(watcherClass);
if (DisguiseValues.getDisguiseValues(disguiseType) != null) {
continue;
}
String nmsEntityName = toReadable(disguiseType.name());
Class nmsClass = ReflectionManager.getNmsClassIgnoreErrors("Entity" + nmsEntityName);
if (nmsClass == null || Modifier.isAbstract(nmsClass.getModifiers())) {
String[] split = splitReadable(disguiseType.name());
ArrayUtils.reverse(split);
nmsEntityName = StringUtils.join(split);
nmsClass = ReflectionManager.getNmsClassIgnoreErrors("Entity" + nmsEntityName);
if (nmsClass == null || Modifier.isAbstract(nmsClass.getModifiers())) {
nmsEntityName = null;
}
}
if (nmsEntityName == null) {
switch (disguiseType) {
case DONKEY:
nmsEntityName = "HorseDonkey";
break;
case ARROW:
nmsEntityName = "TippedArrow";
break;
case DROPPED_ITEM:
nmsEntityName = "Item";
break;
case FIREBALL:
nmsEntityName = "LargeFireball";
break;
case FIREWORK:
nmsEntityName = "Fireworks";
break;
case GIANT:
nmsEntityName = "GiantZombie";
break;
case HUSK:
nmsEntityName = "ZombieHusk";
break;
case ILLUSIONER:
nmsEntityName = "IllagerIllusioner";
break;
case LEASH_HITCH:
nmsEntityName = "Leash";
break;
case MINECART:
nmsEntityName = "MinecartRideable";
break;
case MINECART_COMMAND:
nmsEntityName = "MinecartCommandBlock";
break;
case MINECART_TNT:
nmsEntityName = "MinecartTNT";
break;
case MULE:
nmsEntityName = "HorseMule";
break;
case PRIMED_TNT:
nmsEntityName = "TNTPrimed";
break;
case PUFFERFISH:
nmsEntityName = "PufferFish";
break;
case SPLASH_POTION:
nmsEntityName = "Potion";
break;
case STRAY:
nmsEntityName = "SkeletonStray";
break;
case TRIDENT:
nmsEntityName = "ThrownTrident";
break;
default:
break;
}
}
try {
if (disguiseType == DisguiseType.UNKNOWN) {
DisguiseValues disguiseValues = new DisguiseValues(disguiseType, null, 0, 0);
disguiseValues.setAdultBox(new FakeBoundingBox(0, 0, 0));
DisguiseSound sound = DisguiseSound.getType(disguiseType.name());
if (sound != null) {
sound.setDamageAndIdleSoundVolume(1f);
}
continue;
}
if (nmsEntityName == null) {
getLogger().warning("Entity name not found! (" + disguiseType.name() + ")");
continue;
}
Object nmsEntity = ReflectionManager.createEntityInstance(nmsEntityName);
if (nmsEntity == null) {
getLogger().warning("Entity not found! (" + nmsEntityName + ")");
continue;
}
disguiseType.setTypeId(ReflectionManager.getEntityType(nmsEntity));
Entity bukkitEntity = ReflectionManager.getBukkitEntity(nmsEntity);
int entitySize = 0;
for (Field field : ReflectionManager.getNmsClass("Entity").getFields()) {
if (field.getType().getName().equals("EnumEntitySize")) {
Enum enumEntitySize = (Enum) field.get(nmsEntity);
entitySize = enumEntitySize.ordinal();
break;
}
}
DisguiseValues disguiseValues = new DisguiseValues(disguiseType, nmsEntity.getClass(), entitySize,
bukkitEntity instanceof Damageable ? ((Damageable) bukkitEntity).getMaxHealth() : 0);
WrappedDataWatcher watcher = WrappedDataWatcher.getEntityWatcher(bukkitEntity);
ArrayList<MetaIndex> indexes = MetaIndex.getFlags(disguiseType.getWatcherClass());
boolean loggedName = false;
for (WrappedWatchableObject watch : watcher.getWatchableObjects()) {
MetaIndex flagType = MetaIndex.getFlag(watcherClass, watch.getIndex());
if (flagType == null) {
getLogger().severe("MetaIndex not found for " + disguiseType + "! Index: " + watch.getIndex());
getLogger().severe("Value: " + watch.getRawValue() + " (" + watch.getRawValue().getClass() +
") (" + nmsEntity.getClass() + ") & " + watcherClass.getSimpleName());
continue;
}
indexes.remove(flagType);
Object ourValue = ReflectionManager.convertInvalidMeta(flagType.getDefault());
Object nmsValue = ReflectionManager.convertInvalidMeta(watch.getValue());
if (ourValue.getClass() != nmsValue.getClass()) {
if (!loggedName) {
getLogger().severe(StringUtils.repeat("=", 20));
getLogger().severe("MetaIndex mismatch! Disguise " + disguiseType + ", Entity " +
nmsEntityName);
loggedName = true;
}
getLogger().severe(StringUtils.repeat("-", 20));
getLogger().severe("Index: " + watch.getIndex() + " | " +
flagType.getFlagWatcher().getSimpleName() + " | " + MetaIndex.getName(flagType));
Object flagDefault = flagType.getDefault();
getLogger().severe("LibsDisguises: " + flagDefault + " (" + flagDefault.getClass() + ")");
getLogger().severe("LibsDisguises Converted: " + ourValue + " (" + ourValue.getClass() + ")");
getLogger().severe("Minecraft: " + watch.getRawValue() + " (" + watch.getRawValue().getClass() +
")");
getLogger().severe("Minecraft Converted: " + nmsValue + " (" + nmsValue.getClass() + ")");
getLogger().severe(StringUtils.repeat("-", 20));
}
}
for (MetaIndex index : indexes) {
getLogger().warning(
disguiseType + " has MetaIndex remaining! " + index.getFlagWatcher().getSimpleName() +
" at index " + index.getIndex());
}
DisguiseSound sound = DisguiseSound.getType(disguiseType.name());
if (sound != null) {
Float soundStrength = ReflectionManager.getSoundModifier(nmsEntity);
if (soundStrength != null) {
sound.setDamageAndIdleSoundVolume(soundStrength);
}
}
// Get the bounding box
disguiseValues.setAdultBox(ReflectionManager.getBoundingBox(bukkitEntity));
if (bukkitEntity instanceof Ageable) {
((Ageable) bukkitEntity).setBaby();
disguiseValues.setBabyBox(ReflectionManager.getBoundingBox(bukkitEntity));
} else if (bukkitEntity instanceof Zombie) {
((Zombie) bukkitEntity).setBaby(true);
disguiseValues.setBabyBox(ReflectionManager.getBoundingBox(bukkitEntity));
}
disguiseValues.setEntitySize(ReflectionManager.getSize(bukkitEntity));
}
catch (SecurityException | IllegalArgumentException | IllegalAccessException | FieldAccessException ex) {
getLogger().severe("Uh oh! Trouble while making values for the disguise " + disguiseType.name() + "!");
getLogger().severe("Before reporting this error, " +
"please make sure you are using the latest version of LibsDisguises and ProtocolLib.");
getLogger().severe("Development builds are available at (ProtocolLib) " +
"http://ci.dmulloy2.net/job/ProtocolLib/ and (LibsDisguises) https://ci.md-5" +
".net/job/LibsDisguises/");
ex.printStackTrace();
}
}
}
private String[] splitReadable(String string) {
String[] split = string.split("_");
for (int i = 0; i < split.length; i++) {
split[i] = split[i].substring(0, 1) + split[i].substring(1).toLowerCase();
}
return split;
}
private String toReadable(String string) {
return StringUtils.join(splitReadable(string));
}
public DisguiseListener getListener() {
return listener;
}
/**
* External APIs shouldn't actually need this instance. DisguiseAPI should be enough to handle most cases.
*
* @return The instance of this plugin
*/
public static LibsDisguises getInstance() {
return instance;
}
}

View File

@@ -0,0 +1,123 @@
package me.libraryaddict.disguise.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import me.libraryaddict.disguise.utilities.DisguiseParser;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
/**
* @author libraryaddict
*/
public abstract class DisguiseBaseCommand implements CommandExecutor {
protected ArrayList<String> filterTabs(ArrayList<String> list, String[] origArgs) {
if (origArgs.length == 0)
return list;
Iterator<String> itel = list.iterator();
String label = origArgs[origArgs.length - 1].toLowerCase();
while (itel.hasNext()) {
String name = itel.next();
if (name.toLowerCase().startsWith(label))
continue;
itel.remove();
}
return new ArrayList<>(new HashSet<>(list));
}
protected String getDisplayName(CommandSender player) {
Team team = ((Player) player).getScoreboard().getEntryTeam(player.getName());
return (team == null ? "" : team.getPrefix()) + player.getName() + (team == null ? "" : team.getSuffix());
}
protected ArrayList<String> getAllowedDisguises(
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> hashMap) {
ArrayList<String> allowedDisguises = new ArrayList<>();
for (DisguisePerm type : hashMap.keySet()) {
if (type.isUnknown())
continue;
allowedDisguises.add(type.toReadable().replaceAll(" ", "_"));
}
Collections.sort(allowedDisguises, String.CASE_INSENSITIVE_ORDER);
return allowedDisguises;
}
protected String[] getArgs(String[] args) {
ArrayList<String> newArgs = new ArrayList<>();
for (int i = 0; i < args.length - 1; i++) {
String s = args[i];
if (s.trim().isEmpty())
continue;
newArgs.add(s);
}
return newArgs.toArray(new String[0]);
}
public final String getPermNode() {
if (this instanceof DisguiseCommand) {
return "disguise";
} else if (this instanceof DisguiseEntityCommand) {
return "disguiseentity";
} else if (this instanceof DisguisePlayerCommand) {
return "disguiseplayer";
} else if (this instanceof DisguiseRadiusCommand) {
return "disguiseradius";
} else if (this instanceof DisguiseModifyCommand) {
return "disguisemodify";
} else if (this instanceof DisguiseModifyEntityCommand) {
return "disguisemodifyentity";
} else if (this instanceof DisguiseModifyPlayerCommand) {
return "disguisemodifyplayer";
} else if (this instanceof DisguiseModifyRadiusCommand) {
return "disguisemodifyradius";
} else {
throw new UnsupportedOperationException("Unknown disguise command, perm node not found");
}
}
protected HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> getPermissions(CommandSender sender) {
return DisguiseParser.getPermissions(sender, "libsdisguises." + getPermNode() + ".");
}
protected boolean isNumeric(String string) {
try {
Integer.parseInt(string);
return true;
}
catch (Exception ex) {
return false;
}
}
public boolean passesCheck(CommandSender sender, HashMap<ArrayList<String>, Boolean> theirPermissions,
ArrayList<String> usedOptions) {
return DisguiseParser.passesCheck(sender, theirPermissions, usedOptions);
}
protected abstract void sendCommandUsage(CommandSender sender,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map);
}

View File

@@ -0,0 +1,102 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseConfig;
import me.libraryaddict.disguise.LibsDisguises;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.TranslateType;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DisguiseCloneCommand extends DisguiseBaseCommand implements TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender.getName().equals("CONSOLE")) {
sender.sendMessage(LibsMsg.NO_CONSOLE.get());
return true;
}
if (sender.hasPermission("libsdisguises.disguise.disguiseclone")) {
boolean doEquipment = true;
boolean doSneak = false;
boolean doSprint = false;
Player player = null;
if (args.length > 0) {
player = Bukkit.getPlayerExact(args[0]);
}
for (int i = player == null ? 0 : 1; i < args.length; i++) {
String option = args[i];
if (StringUtils.startsWithIgnoreCase(option, LibsMsg.DCLONE_EQUIP.get())) {
doEquipment = false;
} else if (option.equalsIgnoreCase(LibsMsg.DCLONE_SNEAKSPRINT.get())) {
doSneak = true;
doSprint = true;
} else if (option.equalsIgnoreCase(LibsMsg.DCLONE_SNEAK.get())) {
doSneak = true;
} else if (option.equalsIgnoreCase(LibsMsg.DCLONE_SPRINT.get())) {
doSprint = true;
} else {
sender.sendMessage(LibsMsg.INVALID_CLONE.get(option));
return true;
}
}
Boolean[] options = new Boolean[]{doEquipment, doSneak, doSprint};
if (player != null) {
DisguiseUtilities.createClonedDisguise((Player) sender, player, options);
} else {
LibsDisguises.getInstance().getListener().setDisguiseClone(sender.getName(), options);
sender.sendMessage(LibsMsg.CLICK_TIMER.get(DisguiseConfig.getDisguiseCloneExpire()));
}
} else {
sender.sendMessage(LibsMsg.NO_PERM.get());
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
String[] args = getArgs(origArgs);
if (args.length == 0) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
}
tabs.add(LibsMsg.DCLONE_EQUIP.get());
tabs.add(LibsMsg.DCLONE_SNEAKSPRINT.get());
tabs.add(LibsMsg.DCLONE_SNEAK.get());
tabs.add(LibsMsg.DCLONE_SPRINT.get());
return filterTabs(tabs, origArgs);
}
/**
* Send the player the information
*/
@Override
protected void sendCommandUsage(CommandSender sender,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map) {
sender.sendMessage(LibsMsg.CLONE_HELP1.get());
sender.sendMessage(LibsMsg.CLONE_HELP2.get());
sender.sendMessage(LibsMsg.CLONE_HELP3.get());
}
}

View File

@@ -0,0 +1,195 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.DisguiseConfig;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher;
import me.libraryaddict.disguise.utilities.DisguiseParser;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguiseParseException;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers.ParamInfo;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class DisguiseCommand extends DisguiseBaseCommand implements TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Entity)) {
sender.sendMessage(LibsMsg.NO_CONSOLE.get());
return true;
}
if (args.length == 0) {
sendCommandUsage(sender, getPermissions(sender));
return true;
}
Disguise disguise;
try {
disguise = DisguiseParser
.parseDisguise(sender, getPermNode(), DisguiseParser.split(StringUtils.join(args, " ")),
getPermissions(sender));
}
catch (DisguiseParseException ex) {
if (ex.getMessage() != null) {
sender.sendMessage(ex.getMessage());
}
return true;
}
catch (Exception ex) {
ex.printStackTrace();
return true;
}
if (DisguiseConfig.isNameOfPlayerShownAboveDisguise()) {
if (disguise.getWatcher() instanceof LivingWatcher) {
disguise.getWatcher().setCustomName(getDisplayName(sender));
if (DisguiseConfig.isNameAboveHeadAlwaysVisible()) {
disguise.getWatcher().setCustomNameVisible(true);
}
}
}
disguise.setEntity((Player) sender);
if (!setViewDisguise(args)) {
// They prefer to have the opposite of whatever the view disguises option is
if (DisguiseAPI.hasSelfDisguisePreference(disguise.getEntity()) &&
disguise.isSelfDisguiseVisible() == DisguiseConfig.isViewDisguises())
disguise.setViewSelfDisguise(!disguise.isSelfDisguiseVisible());
}
disguise.startDisguise();
if (disguise.isDisguiseInUse()) {
sender.sendMessage(LibsMsg.DISGUISED.get(disguise.getType().toReadable()));
} else {
sender.sendMessage(LibsMsg.FAILED_DISGIUSE.get(disguise.getType().toReadable()));
}
return true;
}
private boolean setViewDisguise(String[] strings) {
for (String string : strings) {
if (!string.equalsIgnoreCase("setViewSelfDisguise"))
continue;
return true;
}
return false;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
String[] args = getArgs(origArgs);
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> perms = getPermissions(sender);
if (args.length == 0) {
tabs.addAll(getAllowedDisguises(perms));
} else {
DisguisePerm disguiseType = DisguiseParser.getDisguisePerm(args[0]);
if (disguiseType == null)
return filterTabs(tabs, origArgs);
// No disguisetype specificied, cannot help.
if (args.length == 1 && disguiseType.getType() == DisguiseType.PLAYER) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
} else {
ArrayList<String> usedOptions = new ArrayList<>();
for (Method method : ReflectionFlagWatchers.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
for (int i = disguiseType.getType() == DisguiseType.PLAYER ? 2 : 1; i < args.length; i++) {
String arg = args[i];
if (!method.getName().equalsIgnoreCase(arg))
continue;
usedOptions.add(arg);
}
}
if (passesCheck(sender, perms.get(disguiseType), usedOptions)) {
boolean addMethods = true;
if (args.length > 1) {
String prevArg = args[args.length - 1];
ParamInfo info = ReflectionFlagWatchers.getParamInfo(disguiseType, prevArg);
if (info != null) {
if (info.getParamClass() != boolean.class)
addMethods = false;
if (info.isEnums()) {
tabs.addAll(Arrays.asList(info.getEnums(origArgs[origArgs.length - 1])));
} else {
if (info.getParamClass() == String.class) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
}
}
}
}
if (addMethods) {
// If this is a method, add. Else if it can be a param of the previous argument, add.
for (Method method : ReflectionFlagWatchers
.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
tabs.add(method.getName());
}
}
}
}
}
return filterTabs(tabs, origArgs);
}
/**
* Send the player the information
*/
@Override
protected void sendCommandUsage(CommandSender sender,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map) {
ArrayList<String> allowedDisguises = getAllowedDisguises(map);
sender.sendMessage(LibsMsg.DISG_HELP1.get());
sender.sendMessage(LibsMsg.CAN_USE_DISGS
.get(ChatColor.GREEN + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)));
if (allowedDisguises.contains("player")) {
sender.sendMessage(LibsMsg.DISG_HELP2.get());
}
sender.sendMessage(LibsMsg.DISG_HELP3.get());
if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) {
sender.sendMessage(LibsMsg.DISG_HELP4.get());
}
}
}

View File

@@ -0,0 +1,175 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseConfig;
import me.libraryaddict.disguise.LibsDisguises;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.utilities.DisguiseParser;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguiseParseException;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers.ParamInfo;
import me.libraryaddict.disguise.utilities.TranslateType;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DisguiseEntityCommand extends DisguiseBaseCommand implements TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(LibsMsg.NO_CONSOLE.get());
return true;
}
if (getPermissions(sender).isEmpty()) {
sender.sendMessage(LibsMsg.NO_PERM.get());
return true;
}
if (args.length == 0) {
sendCommandUsage(sender, getPermissions(sender));
return true;
}
Disguise disguise;
try {
disguise = DisguiseParser.parseDisguise(sender, getPermNode(), DisguiseParser.split(StringUtils.join(args, " ")), getPermissions(sender));
}
catch (DisguiseParseException ex) {
if (ex.getMessage() != null) {
sender.sendMessage(ex.getMessage());
}
return true;
}
catch (IllegalAccessException | InvocationTargetException ex) {
ex.printStackTrace();
return true;
}
LibsDisguises.getInstance().getListener().setDisguiseEntity(sender.getName(), disguise);
sender.sendMessage(
LibsMsg.DISG_ENT_CLICK.get(DisguiseConfig.getDisguiseEntityExpire(), disguise.getType().toReadable()));
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
if (!(sender instanceof Player)) {
return tabs;
}
String[] args = getArgs(origArgs);
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> perms = getPermissions(sender);
if (args.length == 0) {
for (String type : getAllowedDisguises(perms)) {
tabs.add(type);
}
} else {
DisguisePerm disguiseType = DisguiseParser.getDisguisePerm(args[0]);
if (disguiseType == null)
return filterTabs(tabs, origArgs);
if (args.length == 1 && disguiseType.getType() == DisguiseType.PLAYER) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
} else {
ArrayList<String> usedOptions = new ArrayList<>();
for (Method method : ReflectionFlagWatchers.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
for (int i = disguiseType.getType() == DisguiseType.PLAYER ? 2 : 1; i < args.length; i++) {
String arg = args[i];
if (!method.getName().equalsIgnoreCase(arg))
continue;
usedOptions.add(arg);
}
}
if (passesCheck(sender, perms.get(disguiseType), usedOptions)) {
boolean addMethods = true;
if (args.length > 1) {
String prevArg = args[args.length - 1];
ParamInfo info = ReflectionFlagWatchers.getParamInfo(disguiseType, prevArg);
if (info != null) {
if (info.getParamClass() != boolean.class)
addMethods = false;
if (info.isEnums()) {
for (String e : info.getEnums(origArgs[origArgs.length - 1])) {
tabs.add(e);
}
} else {
if (info.getParamClass() == String.class) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
}
}
}
}
if (addMethods) {
// If this is a method, add. Else if it can be a param of the previous argument, add.
for (Method method : ReflectionFlagWatchers
.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
tabs.add(method.getName());
}
}
}
}
}
return filterTabs(tabs, origArgs);
}
/**
* Send the player the information
*
* @param sender
* @param map
*/
@Override
protected void sendCommandUsage(CommandSender sender,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map) {
ArrayList<String> allowedDisguises = getAllowedDisguises(map);
sender.sendMessage(LibsMsg.DISG_ENT_HELP1.get());
sender.sendMessage(LibsMsg.CAN_USE_DISGS
.get(ChatColor.GREEN + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)));
if (allowedDisguises.contains("player")) {
sender.sendMessage(LibsMsg.DISG_ENT_HELP3.get());
}
sender.sendMessage(LibsMsg.DISG_ENT_HELP4.get());
if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) {
sender.sendMessage(LibsMsg.DISG_ENT_HELP5.get());
}
}
}

View File

@@ -0,0 +1,194 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher;
import me.libraryaddict.disguise.utilities.DisguiseParser;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers.ParamInfo;
import me.libraryaddict.disguise.utilities.TranslateType;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class DisguiseHelpCommand extends DisguiseBaseCommand implements TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
for (String node : new String[]{"disguise", "disguiseradius", "disguiseentity", "disguiseplayer"}) {
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> permMap = DisguiseParser
.getPermissions(sender, "libsdisguises." + node + ".");
if (!permMap.isEmpty()) {
if (args.length == 0) {
sendCommandUsage(sender, null);
return true;
} else {
ParamInfo help = null;
for (ParamInfo s : ReflectionFlagWatchers.getParamInfos()) {
String name = s.getName().replaceAll(" ", "");
if (args[0].equalsIgnoreCase(name) || args[0].equalsIgnoreCase(name + "s")) {
help = s;
break;
}
}
if (help != null) {
if (help.isEnums()) {
sender.sendMessage(LibsMsg.DHELP_HELP4.get(help.getName(),
StringUtils.join(help.getEnums(""), LibsMsg.DHELP_HELP4_SEPERATOR.get())));
} else {
sender.sendMessage(LibsMsg.DHELP_HELP5.get(help.getName(), help.getDescription()));
}
return true;
}
DisguisePerm type = DisguiseParser.getDisguisePerm(args[0]);
if (type == null) {
sender.sendMessage(LibsMsg.DHELP_CANTFIND.get(args[0]));
return true;
}
if (!permMap.containsKey(type)) {
sender.sendMessage(LibsMsg.NO_PERM_DISGUISE.get());
return true;
}
ArrayList<String> methods = new ArrayList<>();
HashMap<String, ChatColor> map = new HashMap<>();
Class watcher = type.getWatcherClass();
int ignored = 0;
try {
for (Method method : ReflectionFlagWatchers.getDisguiseWatcherMethods(watcher)) {
if (args.length < 2 || !args[1].equalsIgnoreCase(LibsMsg.DHELP_SHOW.get())) {
boolean allowed = false;
for (ArrayList<String> key : permMap.get(type).keySet()) {
if (permMap.get(type).get(key)) {
if (key.contains("*") || key.contains(method.getName().toLowerCase())) {
allowed = true;
break;
}
} else if (!key.contains(method.getName().toLowerCase())) {
allowed = true;
break;
}
}
if (!allowed) {
ignored++;
continue;
}
}
Class c = method.getParameterTypes()[0];
ParamInfo info = ReflectionFlagWatchers.getParamInfo(c);
if (info == null)
continue;
ChatColor methodColor = ChatColor.YELLOW;
Class<?> declaring = method.getDeclaringClass();
if (declaring == LivingWatcher.class) {
methodColor = ChatColor.AQUA;
} else if (!(FlagWatcher.class.isAssignableFrom(declaring)) ||
declaring == FlagWatcher.class) {
methodColor = ChatColor.GRAY;
}
String str =
TranslateType.DISGUISE_OPTIONS.get(method.getName()) + ChatColor.DARK_RED + "(" +
ChatColor.GREEN + info.getName() + ChatColor.DARK_RED + ")";
map.put(str, methodColor);
methods.add(str);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
Collections.sort(methods, String.CASE_INSENSITIVE_ORDER);
for (int i = 0; i < methods.size(); i++) {
methods.set(i, map.get(methods.get(i)) + methods.get(i));
}
if (methods.isEmpty()) {
methods.add(LibsMsg.DHELP_NO_OPTIONS.get());
}
sender.sendMessage(LibsMsg.DHELP_OPTIONS.get(ChatColor.DARK_RED + type.toReadable(),
StringUtils.join(methods, ChatColor.DARK_RED + ", ")));
if (ignored > 0) {
sender.sendMessage(LibsMsg.NO_PERMS_USE_OPTIONS.get(ignored));
}
return true;
}
}
}
sender.sendMessage(LibsMsg.NO_PERM.get());
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
String[] args = getArgs(origArgs);
for (String node : new String[]{"disguise", "disguiseradius", "disguiseentity", "disguiseplayer"}) {
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> perms = DisguiseParser
.getPermissions(sender, "libsdisguises." + node + ".");
if (args.length == 0) {
for (DisguisePerm type : perms.keySet()) {
if (type.isUnknown())
continue;
tabs.add(type.toReadable().replaceAll(" ", "_"));
}
for (ParamInfo s : ReflectionFlagWatchers.getParamInfos()) {
tabs.add(s.getName().replaceAll(" ", ""));
}
} else if (DisguiseParser.getDisguisePerm(args[0]) == null) {
tabs.add(LibsMsg.DHELP_SHOW.get());
}
}
return filterTabs(tabs, origArgs);
}
/**
* Send the player the information
*/
@Override
protected void sendCommandUsage(CommandSender sender,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map) {
sender.sendMessage(LibsMsg.DHELP_HELP1.get());
sender.sendMessage(LibsMsg.DHELP_HELP2.get());
for (ParamInfo s : ReflectionFlagWatchers.getParamInfos()) {
sender.sendMessage(LibsMsg.DHELP_HELP3.get(s.getName().replaceAll(" ", ""), s.getDescription()));
}
}
}

View File

@@ -0,0 +1,161 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.utilities.DisguiseParser;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguiseParseException;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers.ParamInfo;
import me.libraryaddict.disguise.utilities.TranslateType;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class DisguiseModifyCommand extends DisguiseBaseCommand implements TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Entity)) {
sender.sendMessage(LibsMsg.NO_CONSOLE.get());
return true;
}
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map = getPermissions(sender);
if (map.isEmpty()) {
sender.sendMessage(LibsMsg.NO_PERM.get());
return true;
}
if (args.length == 0) {
sendCommandUsage(sender, getPermissions(sender));
return true;
}
Disguise disguise = DisguiseAPI.getDisguise((Player) sender, (Entity) sender);
if (disguise == null) {
sender.sendMessage(LibsMsg.NOT_DISGUISED.get());
return true;
}
if (!map.containsKey(new DisguisePerm(disguise.getType()))) {
sender.sendMessage(LibsMsg.DMODIFY_NO_PERM.get());
return true;
}
try {
DisguiseParser
.callMethods(sender, disguise, getPermissions(sender).get(new DisguisePerm(disguise.getType())),
new ArrayList<String>(), DisguiseParser.split(StringUtils.join(args, " ")));
}
catch (DisguiseParseException ex) {
if (ex.getMessage() != null) {
sender.sendMessage(ex.getMessage());
}
return true;
}
catch (Exception ex) {
ex.printStackTrace();
return true;
}
sender.sendMessage(LibsMsg.DMODIFY_MODIFIED.get());
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
if (!(sender instanceof Player))
return tabs;
Disguise disguise = DisguiseAPI.getDisguise((Player) sender, (Entity) sender);
if (disguise == null)
return tabs;
String[] args = getArgs(origArgs);
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> perms = getPermissions(sender);
DisguisePerm disguiseType = new DisguisePerm(disguise.getType());
ArrayList<String> usedOptions = new ArrayList<>();
for (Method method : ReflectionFlagWatchers.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
for (int i = disguiseType.getType() == DisguiseType.PLAYER ? 2 : 1; i < args.length; i++) {
String arg = args[i];
if (!method.getName().equalsIgnoreCase(arg))
continue;
usedOptions.add(arg);
}
}
if (passesCheck(sender, perms.get(disguiseType), usedOptions)) {
boolean addMethods = true;
if (args.length > 0) {
String prevArg = args[args.length - 1];
ParamInfo info = ReflectionFlagWatchers.getParamInfo(disguiseType, prevArg);
if (info != null) {
if (info.getParamClass() != boolean.class) {
addMethods = false;
}
if (info.isEnums()) {
tabs.addAll(Arrays.asList(info.getEnums(origArgs[origArgs.length - 1])));
} else {
if (info.getParamClass() == String.class) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
}
}
}
}
if (addMethods) {
// If this is a method, add. Else if it can be a param of the previous argument, add.
for (Method method : ReflectionFlagWatchers.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
tabs.add(method.getName());
}
}
}
return filterTabs(tabs, origArgs);
}
/**
* Send the player the information
*/
@Override
protected void sendCommandUsage(CommandSender sender,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map) {
ArrayList<String> allowedDisguises = getAllowedDisguises(map);
sender.sendMessage(LibsMsg.DMODIFY_HELP3.get());
sender.sendMessage(LibsMsg.DMODIFY_HELP3.get());
sender.sendMessage(LibsMsg.DMODIFY_HELP3
.get(ChatColor.GREEN + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)));
}
}

View File

@@ -0,0 +1,118 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseConfig;
import me.libraryaddict.disguise.LibsDisguises;
import me.libraryaddict.disguise.utilities.DisguiseParser;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers.ParamInfo;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class DisguiseModifyEntityCommand extends DisguiseBaseCommand implements TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(LibsMsg.NO_CONSOLE.get());
return true;
}
if (getPermissions(sender).isEmpty()) {
sender.sendMessage(LibsMsg.NO_PERM.get());
return true;
}
if (args.length == 0) {
sendCommandUsage(sender, getPermissions(sender));
return true;
}
// TODO Validate if any disguises have this arg
LibsDisguises.getInstance().getListener().setDisguiseModify(sender.getName(), DisguiseParser
.split(StringUtils.join(args, " ")));
sender.sendMessage(LibsMsg.DMODIFYENT_CLICK.get(DisguiseConfig.getDisguiseEntityExpire()));
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
if (!(sender instanceof Player)) {
return tabs;
}
String[] args = getArgs(origArgs);
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> perms = getPermissions(sender);
if (perms.isEmpty())
return tabs;
for (DisguisePerm perm : perms.keySet()) {
boolean addMethods = true;
if (args.length > 0) {
String prevArg = args[args.length - 1];
ParamInfo info = ReflectionFlagWatchers.getParamInfo(perm.getType(), prevArg);
if (info != null) {
if (info.getParamClass() != boolean.class) {
addMethods = false;
}
if (info.isEnums()) {
tabs.addAll(Arrays.asList(info.getEnums(origArgs[origArgs.length - 1])));
} else {
if (info.getParamClass() == String.class) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
}
}
}
}
if (addMethods) {
// If this is a method, add. Else if it can be a param of the previous argument, add.
for (Method method : ReflectionFlagWatchers
.getDisguiseWatcherMethods(perm.getType().getWatcherClass())) {
tabs.add(method.getName());
}
}
}
return filterTabs(tabs, origArgs);
}
/**
* Send the player the information
*
* @param sender
* @param map
*/
@Override
protected void sendCommandUsage(CommandSender sender,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map) {
ArrayList<String> allowedDisguises = getAllowedDisguises(map);
sender.sendMessage(LibsMsg.DMODENT_HELP1.get());
sender.sendMessage(LibsMsg.DMODIFY_HELP3
.get(ChatColor.GREEN + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)));
}
}

View File

@@ -0,0 +1,195 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.utilities.DisguiseParser;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguiseParseException;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers.ParamInfo;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DisguiseModifyPlayerCommand extends DisguiseBaseCommand implements TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map = getPermissions(sender);
if (map.isEmpty()) {
sender.sendMessage(LibsMsg.NO_PERM.get());
return true;
}
if (args.length == 0) {
sendCommandUsage(sender, map);
return true;
}
Player player = Bukkit.getPlayer(args[0]);
if (player == null) {
sender.sendMessage(LibsMsg.CANNOT_FIND_PLAYER.get(args[0]));
return true;
}
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
if (newArgs.length == 0) {
sendCommandUsage(sender, map);
return true;
}
Disguise disguise = null;
if (sender instanceof Player)
disguise = DisguiseAPI.getDisguise((Player) sender, player);
if (disguise == null)
disguise = DisguiseAPI.getDisguise(player);
if (disguise == null) {
sender.sendMessage(LibsMsg.DMODPLAYER_NODISGUISE.get(player.getName()));
return true;
}
if (!map.containsKey(new DisguisePerm(disguise.getType()))) {
sender.sendMessage(LibsMsg.DMODPLAYER_NOPERM.get());
return true;
}
try {
DisguiseParser.callMethods(sender, disguise, map.get(new DisguisePerm(disguise.getType())),
new ArrayList<String>(), DisguiseParser.split(StringUtils.join(newArgs, " ")));
}
catch (DisguiseParseException ex) {
if (ex.getMessage() != null) {
sender.sendMessage(ex.getMessage());
}
return true;
}
catch (Exception ex) {
ex.printStackTrace();
return true;
}
sender.sendMessage(LibsMsg.DMODPLAYER_MODIFIED.get(player.getName()));
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
String[] args = getArgs(origArgs);
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> perms = getPermissions(sender);
if (perms.isEmpty())
return tabs;
if (args.length == 0) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
} else {
Player player = Bukkit.getPlayer(args[0]);
if (player == null) {
sender.sendMessage(LibsMsg.CANNOT_FIND_PLAYER.get(args[0]));
return tabs;
}
Disguise disguise = null;
if (sender instanceof Player)
disguise = DisguiseAPI.getDisguise((Player) sender, player);
if (disguise == null)
disguise = DisguiseAPI.getDisguise(player);
if (disguise == null) {
sender.sendMessage(LibsMsg.DMODPLAYER_NODISGUISE.get(player.getName()));
return tabs;
}
DisguisePerm disguiseType = new DisguisePerm(disguise.getType());
ArrayList<String> usedOptions = new ArrayList<>();
for (Method method : ReflectionFlagWatchers.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
for (int i = 1; i < args.length; i++) {
String arg = args[i];
if (!method.getName().equalsIgnoreCase(arg))
continue;
usedOptions.add(arg);
}
}
if (passesCheck(sender, perms.get(disguiseType), usedOptions)) {
boolean addMethods = true;
if (args.length > 1) {
String prevArg = args[args.length - 1];
ParamInfo info = ReflectionFlagWatchers.getParamInfo(disguiseType, prevArg);
if (info != null) {
if (info.getParamClass() != boolean.class)
addMethods = false;
if (info.isEnums()) {
for (String e : info.getEnums(origArgs[origArgs.length - 1])) {
tabs.add(e);
}
} else {
if (info.getParamClass() == String.class) {
for (Player p : Bukkit.getOnlinePlayers()) {
tabs.add(p.getName());
}
}
}
}
}
if (addMethods) {
// If this is a method, add. Else if it can be a param of the previous argument, add.
for (Method method : ReflectionFlagWatchers
.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
tabs.add(method.getName());
}
}
}
}
return filterTabs(tabs, origArgs);
}
/**
* Send the player the information
*/
@Override
protected void sendCommandUsage(CommandSender sender,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map) {
ArrayList<String> allowedDisguises = getAllowedDisguises(map);
sender.sendMessage(LibsMsg.DMODPLAYER_HELP1.get());
sender.sendMessage(LibsMsg.DMODIFY_HELP3
.get(ChatColor.GREEN + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)));
}
}

View File

@@ -0,0 +1,294 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.utilities.*;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguiseParseException;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers.ParamInfo;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import java.lang.reflect.Method;
import java.util.*;
public class DisguiseModifyRadiusCommand extends DisguiseBaseCommand implements TabCompleter {
private int maxRadius = 30;
public DisguiseModifyRadiusCommand(int maxRadius) {
this.maxRadius = maxRadius;
}
private Collection<Entity> getNearbyEntities(CommandSender sender, int radius) {
Location center;
if (sender instanceof Player) {
center = ((Player) sender).getLocation();
} else {
center = ((BlockCommandSender) sender).getBlock().getLocation().add(0.5, 0, 0.5);
}
return center.getWorld().getNearbyEntities(center, radius, radius, radius);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender.getName().equals("CONSOLE")) {
sender.sendMessage(LibsMsg.NO_CONSOLE.get());
return true;
}
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map = getPermissions(sender);
if (map.isEmpty()) {
sender.sendMessage(LibsMsg.NO_PERM.get());
return true;
}
if (args.length == 0) {
sendCommandUsage(sender, map);
return true;
}
if (args[0].equalsIgnoreCase(TranslateType.DISGUISES.get("DisguiseType")) || args[0]
.equalsIgnoreCase(TranslateType.DISGUISES.get("DisguiseType") + "s")) {
ArrayList<String> classes = new ArrayList<>();
for (DisguiseType type : DisguiseType.values()) {
classes.add(type.toReadable());
}
Collections.sort(classes);
sender.sendMessage(LibsMsg.DMODRADIUS_USABLE
.get(ChatColor.GREEN + StringUtils.join(classes, ChatColor.DARK_GREEN + ", " + ChatColor.GREEN)));
return true;
}
DisguiseType baseType = null;
int starting = 0;
if (!isNumeric(args[0])) {
for (DisguiseType t : DisguiseType.values()) {
if (t.toReadable().replaceAll(" ", "").equalsIgnoreCase(args[0].replaceAll("_", ""))) {
baseType = t;
starting = 1;
break;
}
}
if (baseType == null) {
sender.sendMessage(LibsMsg.DMODRADIUS_UNRECOGNIZED.get(args[0]));
return true;
}
}
if (args.length == starting + 1) {
sender.sendMessage(
(starting == 0 ? LibsMsg.DMODRADIUS_NEEDOPTIONS : LibsMsg.DMODRADIUS_NEEDOPTIONS_ENTITY).get());
return true;
} else if (args.length < 2) {
sender.sendMessage(LibsMsg.DMODRADIUS_NEEDOPTIONS.get());
return true;
}
if (!isNumeric(args[starting])) {
sender.sendMessage(LibsMsg.NOT_NUMBER.get(args[starting]));
return true;
}
int radius = Integer.parseInt(args[starting]);
if (radius > maxRadius) {
sender.sendMessage(LibsMsg.LIMITED_RADIUS.get(maxRadius));
radius = maxRadius;
}
String[] newArgs = new String[args.length - (starting + 1)];
System.arraycopy(args, starting + 1, newArgs, 0, newArgs.length);
if (newArgs.length == 0) {
sendCommandUsage(sender, map);
return true;
}
// Time to use it!
int modifiedDisguises = 0;
int noPermission = 0;
for (Entity entity : getNearbyEntities(sender, radius)) {
if (entity == sender) {
continue;
}
if (baseType != null && !baseType.name().equalsIgnoreCase(entity.getType().name())) {
continue;
}
Disguise disguise;
if (sender instanceof Player)
disguise = DisguiseAPI.getDisguise((Player) sender, entity);
else
disguise = DisguiseAPI.getDisguise(entity);
if (!map.containsKey(new DisguisePerm(disguise.getType()))) {
noPermission++;
continue;
}
try {
DisguiseParser.callMethods(sender, disguise, map.get(new DisguisePerm(disguise.getType())),
new ArrayList<String>(), DisguiseParser.split(StringUtils.join(newArgs, " ")));
modifiedDisguises++;
}
catch (DisguiseParseException ex) {
if (ex.getMessage() != null) {
sender.sendMessage(ex.getMessage());
}
return true;
}
catch (Exception ex) {
ex.printStackTrace();
return true;
}
}
if (noPermission > 0) {
sender.sendMessage(LibsMsg.DMODRADIUS_NOPERM.get(noPermission));
}
if (modifiedDisguises > 0) {
sender.sendMessage(LibsMsg.DMODRADIUS.get(modifiedDisguises));
} else {
sender.sendMessage(LibsMsg.DMODRADIUS_NOENTS.get());
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
String[] args = getArgs(origArgs);
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> perms = getPermissions(sender);
if (args.length == 0) {
for (DisguiseType type : DisguiseType.values()) {
tabs.add(type.toReadable().replaceAll(" ", "_"));
}
return filterTabs(tabs, origArgs);
}
int starting = 0;
if (!isNumeric(args[0])) {
for (DisguiseType t : DisguiseType.values()) {
if (t.toReadable().replaceAll(" ", "").equalsIgnoreCase(args[0].replaceAll("_", ""))) {
starting = 2;
break;
}
}
// Not a valid radius
if (starting == 1 || args.length == 1 || !isNumeric(args[1]))
return filterTabs(tabs, origArgs);
}
if (!isNumeric(args[starting])) {
return filterTabs(tabs, origArgs);
}
int radius = Integer.parseInt(args[starting]);
if (radius > maxRadius) {
sender.sendMessage(LibsMsg.LIMITED_RADIUS.get(maxRadius));
radius = maxRadius;
}
ArrayList<String> usedOptions = new ArrayList<>();
for (Entity entity : getNearbyEntities(sender, radius)) {
Disguise disguise = DisguiseAPI.getDisguise(entity);
if (disguise == null)
continue;
DisguiseType disguiseType = disguise.getType();
for (Method method : ReflectionFlagWatchers.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
for (String arg : args) {
if (!method.getName().equalsIgnoreCase(arg) || usedOptions.contains(arg))
continue;
usedOptions.add(arg);
}
}
if (passesCheck(sender, perms.get(new DisguisePerm(disguiseType)), usedOptions)) {
boolean addMethods = true;
if (args.length > 1 + starting) {
String prevArg = args[args.length - 1];
ParamInfo info = ReflectionFlagWatchers.getParamInfo(disguiseType, prevArg);
if (info != null) {
if (info.getParamClass() != boolean.class)
addMethods = false;
if (info.isEnums()) {
tabs.addAll(Arrays.asList(info.getEnums(origArgs[origArgs.length - 1])));
} else {
if (info.getParamClass() == String.class) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
}
}
}
}
if (addMethods) {
// If this is a method, add. Else if it can be a param of the previous argument, add.
for (Method method : ReflectionFlagWatchers
.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
tabs.add(method.getName());
}
}
}
}
return filterTabs(tabs, origArgs);
}
/**
* Send the player the information
*/
@Override
protected void sendCommandUsage(CommandSender sender,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map) {
ArrayList<String> allowedDisguises = getAllowedDisguises(map);
sender.sendMessage(LibsMsg.DMODRADIUS_HELP1.get(maxRadius));
sender.sendMessage(LibsMsg.DMODIFY_HELP3
.get(ChatColor.GREEN + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)));
sender.sendMessage(LibsMsg.DMODRADIUS_HELP2.get());
sender.sendMessage(LibsMsg.DMODRADIUS_HELP3.get());
}
}

View File

@@ -0,0 +1,236 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.DisguiseConfig;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher;
import me.libraryaddict.disguise.utilities.DisguiseParser;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguiseParseException;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers.ParamInfo;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.lang.reflect.Method;
import java.util.*;
public class DisguisePlayerCommand extends DisguiseBaseCommand implements TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map = getPermissions(sender);
if (map.isEmpty()) {
sender.sendMessage(LibsMsg.NO_PERM.get());
return true;
}
if (args.length == 0) {
sendCommandUsage(sender, map);
return true;
}
if (args.length == 1) {
sender.sendMessage(LibsMsg.DPLAYER_SUPPLY.get());
return true;
}
Entity player = Bukkit.getPlayer(args[0]);
if (player == null) {
if (args[0].contains("-")) {
try {
player = Bukkit.getEntity(UUID.fromString(args[0]));
}
catch (Exception ignored) {
}
}
}
if (player == null) {
sender.sendMessage(LibsMsg.CANNOT_FIND_PLAYER.get(args[0]));
return true;
}
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
if (newArgs.length == 0) {
sendCommandUsage(sender, map);
return true;
}
Disguise disguise;
try {
disguise = DisguiseParser
.parseDisguise(sender, getPermNode(), DisguiseParser.split(StringUtils.join(newArgs, " ")), map);
}
catch (DisguiseParseException ex) {
if (ex.getMessage() != null) {
sender.sendMessage(ex.getMessage());
}
return true;
}
catch (Exception ex) {
ex.printStackTrace();
return true;
}
if (disguise.isMiscDisguise() && !DisguiseConfig.isMiscDisguisesForLivingEnabled()) {
sender.sendMessage(LibsMsg.DISABLED_LIVING_TO_MISC.get());
return true;
}
if (DisguiseConfig.isNameOfPlayerShownAboveDisguise()) {
if (disguise.getWatcher() instanceof LivingWatcher) {
disguise.getWatcher().setCustomName(getDisplayName(player));
if (DisguiseConfig.isNameAboveHeadAlwaysVisible()) {
disguise.getWatcher().setCustomNameVisible(true);
}
}
}
disguise.setEntity(player);
if (!setViewDisguise(args)) {
// They prefer to have the opposite of whatever the view disguises option is
if (DisguiseAPI.hasSelfDisguisePreference(disguise.getEntity()) &&
disguise.isSelfDisguiseVisible() == DisguiseConfig.isViewDisguises())
disguise.setViewSelfDisguise(!disguise.isSelfDisguiseVisible());
}
disguise.startDisguise();
if (disguise.isDisguiseInUse()) {
sender.sendMessage(LibsMsg.DISG_PLAYER_AS_DISG
.get(player instanceof Player ? player.getName() : DisguiseType.getType(player).toReadable(),
disguise.getType().toReadable()));
} else {
sender.sendMessage(LibsMsg.DISG_PLAYER_AS_DISG_FAIL
.get(player instanceof Player ? player.getName() : DisguiseType.getType(player).toReadable(),
disguise.getType().toReadable()));
}
return true;
}
private boolean setViewDisguise(String[] strings) {
for (String string : strings) {
if (!string.equalsIgnoreCase("setViewSelfDisguise"))
continue;
return true;
}
return false;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
String[] args = getArgs(origArgs);
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> perms = getPermissions(sender);
if (args.length == 0) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
} else if (args.length == 1) {
tabs.addAll(getAllowedDisguises(perms));
} else {
DisguisePerm disguiseType = DisguiseParser.getDisguisePerm(args[1]);
if (disguiseType == null)
return filterTabs(tabs, origArgs);
if (args.length == 2 && disguiseType.getType() == DisguiseType.PLAYER) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
} else {
ArrayList<String> usedOptions = new ArrayList<>();
for (Method method : ReflectionFlagWatchers.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
for (int i = disguiseType.getType() == DisguiseType.PLAYER ? 3 : 2; i < args.length; i++) {
String arg = args[i];
if (!method.getName().equalsIgnoreCase(arg))
continue;
usedOptions.add(arg);
}
}
if (passesCheck(sender, perms.get(disguiseType), usedOptions)) {
boolean addMethods = true;
if (args.length > 2) {
String prevArg = args[args.length - 1];
ParamInfo info = ReflectionFlagWatchers.getParamInfo(disguiseType, prevArg);
if (info != null) {
if (info.getParamClass() != boolean.class)
addMethods = false;
if (info.isEnums()) {
tabs.addAll(Arrays.asList(info.getEnums(origArgs[origArgs.length - 1])));
} else {
if (info.getParamClass() == String.class) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
}
}
}
}
if (addMethods) {
// If this is a method, add. Else if it can be a param of the previous argument, add.
for (Method method : ReflectionFlagWatchers
.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
tabs.add(method.getName());
}
}
}
}
}
return filterTabs(tabs, origArgs);
}
/**
* Send the player the information
*/
@Override
protected void sendCommandUsage(CommandSender sender,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map) {
ArrayList<String> allowedDisguises = getAllowedDisguises(map);
sender.sendMessage(LibsMsg.D_HELP1.get());
sender.sendMessage(LibsMsg.CAN_USE_DISGS
.get(ChatColor.GREEN + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)));
if (allowedDisguises.contains("player")) {
sender.sendMessage(LibsMsg.D_HELP3.get());
}
sender.sendMessage(LibsMsg.D_HELP4.get());
if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) {
sender.sendMessage(LibsMsg.D_HELP5.get());
}
}
}

View File

@@ -0,0 +1,346 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.DisguiseConfig;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher;
import me.libraryaddict.disguise.utilities.*;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguiseParseException;
import me.libraryaddict.disguise.utilities.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.ReflectionFlagWatchers.ParamInfo;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import java.lang.reflect.Method;
import java.util.*;
public class DisguiseRadiusCommand extends DisguiseBaseCommand implements TabCompleter {
private int maxRadius = 30;
private ArrayList<Class<? extends Entity>> validClasses = new ArrayList<>();
public DisguiseRadiusCommand(int maxRadius) {
this.maxRadius = maxRadius;
for (Class c : ClassGetter.getClassesForPackage("org.bukkit.entity")) {
if (c != Entity.class && Entity.class.isAssignableFrom(c) && c.getAnnotation(Deprecated.class) == null) {
validClasses.add(c);
}
}
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender.getName().equals("CONSOLE")) {
sender.sendMessage(LibsMsg.NO_CONSOLE.get());
return true;
}
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map = getPermissions(sender);
if (map.isEmpty()) {
sender.sendMessage(LibsMsg.NO_PERM.get());
return true;
}
if (args.length == 0) {
sendCommandUsage(sender, map);
return true;
}
if (args[0].equalsIgnoreCase(TranslateType.DISGUISES.get("EntityType")) ||
args[0].equalsIgnoreCase(TranslateType.DISGUISES.get("EntityType") + "s")) {
ArrayList<String> classes = new ArrayList<>();
for (Class c : validClasses) {
classes.add(TranslateType.DISGUISES.get(c.getSimpleName()));
}
Collections.sort(classes);
sender.sendMessage(LibsMsg.DRADIUS_ENTITIES
.get(ChatColor.GREEN + StringUtils.join(classes, ChatColor.DARK_GREEN + ", " + ChatColor.GREEN)));
return true;
}
Class entityClass = Entity.class;
EntityType type = null;
int starting = 0;
if (!isNumeric(args[0])) {
for (Class c : validClasses) {
if (TranslateType.DISGUISES.get(c.getSimpleName()).equalsIgnoreCase(args[0])) {
entityClass = c;
starting = 1;
break;
}
}
if (starting == 0) {
try {
type = EntityType.valueOf(args[0].toUpperCase());
}
catch (Exception ignored) {
}
if (type == null) {
sender.sendMessage(LibsMsg.DMODRADIUS_UNRECOGNIZED.get(args[0]));
return true;
}
}
}
if (args.length == starting + 1) {
sender.sendMessage(
(starting == 0 ? LibsMsg.DRADIUS_NEEDOPTIONS : LibsMsg.DRADIUS_NEEDOPTIONS_ENTITY).get());
return true;
} else if (args.length < 2) {
sender.sendMessage(LibsMsg.DRADIUS_NEEDOPTIONS.get());
return true;
}
if (!isNumeric(args[starting])) {
sender.sendMessage(LibsMsg.NOT_NUMBER.get(args[starting]));
return true;
}
int radius = Integer.parseInt(args[starting]);
if (radius > maxRadius) {
sender.sendMessage(LibsMsg.LIMITED_RADIUS.get(maxRadius));
radius = maxRadius;
}
String[] newArgs = new String[args.length - (starting + 1)];
System.arraycopy(args, starting + 1, newArgs, 0, newArgs.length);
Disguise disguise;
if (newArgs.length == 0) {
sendCommandUsage(sender, map);
return true;
}
try {
disguise = DisguiseParser
.parseDisguise(sender, getPermNode(), DisguiseParser.split(StringUtils.join(newArgs, " ")), map);
}
catch (DisguiseParseException ex) {
if (ex.getMessage() != null) {
sender.sendMessage(ex.getMessage());
}
return true;
}
catch (Exception ex) {
ex.printStackTrace();
return true;
}
// Time to use it!
int disguisedEntitys = 0;
int miscDisguises = 0;
Location center;
if (sender instanceof Player) {
center = ((Player) sender).getLocation();
} else {
center = ((BlockCommandSender) sender).getBlock().getLocation().add(0.5, 0, 0.5);
}
for (Entity entity : center.getWorld().getNearbyEntities(center, radius, radius, radius)) {
if (entity == sender) {
continue;
}
if (type != null ? entity.getType() == type : entityClass.isAssignableFrom(entity.getClass())) {
if (disguise.isMiscDisguise() && !DisguiseConfig.isMiscDisguisesForLivingEnabled() &&
entity instanceof LivingEntity) {
miscDisguises++;
continue;
}
disguise = disguise.clone();
if (entity instanceof Player && DisguiseConfig.isNameOfPlayerShownAboveDisguise()) {
if (disguise.getWatcher() instanceof LivingWatcher) {
disguise.getWatcher().setCustomName(getDisplayName(entity));
if (DisguiseConfig.isNameAboveHeadAlwaysVisible()) {
disguise.getWatcher().setCustomNameVisible(true);
}
}
}
disguise.setEntity(entity);
if (!setViewDisguise(args)) {
// They prefer to have the opposite of whatever the view disguises option is
if (DisguiseAPI.hasSelfDisguisePreference(disguise.getEntity()) &&
disguise.isSelfDisguiseVisible() == DisguiseConfig.isViewDisguises())
disguise.setViewSelfDisguise(!disguise.isSelfDisguiseVisible());
}
disguise.startDisguise();
DisguiseAPI.disguiseEntity(entity, disguise);
if (disguise.isDisguiseInUse()) {
disguisedEntitys++;
}
}
}
if (disguisedEntitys > 0) {
sender.sendMessage(LibsMsg.DISRADIUS.get(disguisedEntitys));
} else {
sender.sendMessage(LibsMsg.DISRADIUS_FAIL.get());
}
if (miscDisguises > 0) {
sender.sendMessage(LibsMsg.DRADIUS_MISCDISG.get(miscDisguises));
}
return true;
}
private boolean setViewDisguise(String[] strings) {
for (String string : strings) {
if (!string.equalsIgnoreCase("setViewSelfDisguise"))
continue;
return true;
}
return false;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
String[] args = getArgs(origArgs);
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> perms = getPermissions(sender);
if (args.length == 0) {
for (Class<? extends Entity> entityClass : validClasses) {
tabs.add(TranslateType.DISGUISES.get(entityClass.getSimpleName()));
}
return filterTabs(tabs, origArgs);
}
int starting = 1;
if (!isNumeric(args[0])) {
for (Class c : validClasses) {
if (!TranslateType.DISGUISES.get(c.getSimpleName()).equalsIgnoreCase(args[0]))
continue;
starting = 2;
break;
}
// Not a valid radius
if (starting == 1 || args.length == 1 || !isNumeric(args[1]))
return filterTabs(tabs, origArgs);
}
if (args.length == starting) {
tabs.addAll(getAllowedDisguises(perms));
} else {
DisguisePerm disguiseType = DisguiseParser.getDisguisePerm(args[starting]);
if (disguiseType == null)
return filterTabs(tabs, origArgs);
if (args.length == 1 + starting && disguiseType.getType() == DisguiseType.PLAYER) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
} else {
ArrayList<String> usedOptions = new ArrayList<>();
for (Method method : ReflectionFlagWatchers.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
for (int i = disguiseType.getType() == DisguiseType.PLAYER ? starting + 2 : starting + 1;
i < args.length; i++) {
String arg = args[i];
if (!method.getName().equalsIgnoreCase(arg))
continue;
usedOptions.add(arg);
}
}
if (passesCheck(sender, perms.get(disguiseType), usedOptions)) {
boolean addMethods = true;
if (args.length > 1 + starting) {
String prevArg = args[args.length - 1];
ParamInfo info = ReflectionFlagWatchers.getParamInfo(disguiseType, prevArg);
if (info != null) {
if (info.getParamClass() != boolean.class)
addMethods = false;
if (info.isEnums()) {
tabs.addAll(Arrays.asList(info.getEnums(origArgs[origArgs.length - 1])));
} else {
if (info.getParamClass() == String.class) {
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
}
}
}
}
if (addMethods) {
// If this is a method, add. Else if it can be a param of the previous argument, add.
for (Method method : ReflectionFlagWatchers
.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
tabs.add(method.getName());
}
}
}
}
}
return filterTabs(tabs, origArgs);
}
/**
* Send the player the information
*/
@Override
protected void sendCommandUsage(CommandSender sender,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map) {
ArrayList<String> allowedDisguises = getAllowedDisguises(map);
sender.sendMessage(LibsMsg.DRADIUS_HELP1.get(maxRadius));
sender.sendMessage(LibsMsg.CAN_USE_DISGS
.get(ChatColor.GREEN + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)));
if (allowedDisguises.contains("player")) {
sender.sendMessage(LibsMsg.DRADIUS_HELP3.get());
}
sender.sendMessage(LibsMsg.DRADIUS_HELP4.get());
if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) {
sender.sendMessage(LibsMsg.DRADIUS_HELP5.get());
}
sender.sendMessage(LibsMsg.DRADIUS_HELP6.get());
}
}

View File

@@ -0,0 +1,36 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.TranslateType;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* @author Navid
*/
public class DisguiseViewSelfCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender.getName().equals("CONSOLE")) {
sender.sendMessage(LibsMsg.NO_CONSOLE.get());
return true;
}
Player player = (Player) sender;
if (DisguiseAPI.isViewSelfToggled(player)) {
DisguiseAPI.setViewDisguiseToggled(player, false);
sender.sendMessage(LibsMsg.VIEW_SELF_OFF.get());
} else {
DisguiseAPI.setViewDisguiseToggled(player, true);
sender.sendMessage(LibsMsg.VIEW_SELF_ON.get());
}
return true;
}
}

View File

@@ -0,0 +1,91 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseConfig;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.LibsPremium;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class LibsDisguisesCommand implements CommandExecutor, TabCompleter {
protected ArrayList<String> filterTabs(ArrayList<String> list, String[] origArgs) {
if (origArgs.length == 0)
return list;
Iterator<String> itel = list.iterator();
String label = origArgs[origArgs.length - 1].toLowerCase();
while (itel.hasNext()) {
String name = itel.next();
if (name.toLowerCase().startsWith(label))
continue;
itel.remove();
}
return list;
}
protected String[] getArgs(String[] args) {
ArrayList<String> newArgs = new ArrayList<>();
for (int i = 0; i < args.length - 1; i++) {
String s = args[i];
if (s.trim().isEmpty())
continue;
newArgs.add(s);
}
return newArgs.toArray(new String[0]);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length == 0) {
sender.sendMessage(ChatColor.DARK_GREEN + "This server is running " + "Lib's Disguises v" +
Bukkit.getPluginManager().getPlugin("LibsDisguises").getDescription().getVersion() +
" by libraryaddict, formerly maintained " + "by Byteflux and NavidK0." +
(sender.hasPermission("libsdisguises.reload") ?
"\nUse " + ChatColor.GREEN + "/libsdisguises " + "reload" + ChatColor.DARK_GREEN +
" to reload the config. All disguises will be blown by doing this" + "." : ""));
if (LibsPremium.isPremium()) {
sender.sendMessage(ChatColor.DARK_GREEN + "This server supports the plugin developer!");
}
} else if (args.length > 0) {
if (sender.hasPermission("libsdisguises.reload")) {
if (args[0].equalsIgnoreCase("reload")) {
DisguiseConfig.loadConfig();
sender.sendMessage(LibsMsg.RELOADED_CONFIG.get());
return true;
} else {
sender.sendMessage(LibsMsg.LIBS_RELOAD_WRONG.get());
}
} else {
sender.sendMessage(LibsMsg.NO_PERM.get());
}
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
String[] args = getArgs(origArgs);
if (args.length == 0)
tabs.add("Reload");
return filterTabs(tabs, origArgs);
}
}

View File

@@ -0,0 +1,35 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.TranslateType;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
public class UndisguiseCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender.getName().equals("CONSOLE")) {
sender.sendMessage(LibsMsg.NO_CONSOLE.get());
return true;
}
if (sender.hasPermission("libsdisguises.undisguise")) {
if (DisguiseAPI.isDisguised((Entity) sender)) {
DisguiseAPI.undisguiseToAll((Player) sender);
sender.sendMessage(LibsMsg.UNDISG.get());
} else {
sender.sendMessage(LibsMsg.NOT_DISGUISED.get());
}
} else {
sender.sendMessage(LibsMsg.NO_PERM.get());
}
return true;
}
}

View File

@@ -0,0 +1,27 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.LibsDisguises;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.TranslateType;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class UndisguiseEntityCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender.getName().equals("CONSOLE")) {
sender.sendMessage(LibsMsg.NO_CONSOLE.get());
return true;
}
if (sender.hasPermission("libsdisguises.undisguiseentity")) {
LibsDisguises.getInstance().getListener().setDisguiseEntity(sender.getName(), null);
sender.sendMessage(LibsMsg.UND_ENTITY.get());
} else {
sender.sendMessage(LibsMsg.NO_PERM.get());
}
return true;
}
}

View File

@@ -0,0 +1,107 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.utilities.LibsMsg;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
public class UndisguisePlayerCommand implements CommandExecutor, TabCompleter {
protected ArrayList<String> filterTabs(ArrayList<String> list, String[] origArgs) {
if (origArgs.length == 0)
return list;
Iterator<String> itel = list.iterator();
String label = origArgs[origArgs.length - 1].toLowerCase();
while (itel.hasNext()) {
String name = itel.next();
if (name.toLowerCase().startsWith(label))
continue;
itel.remove();
}
return list;
}
protected String[] getArgs(String[] args) {
ArrayList<String> newArgs = new ArrayList<>();
for (int i = 0; i < args.length - 1; i++) {
String s = args[i];
if (s.trim().isEmpty())
continue;
newArgs.add(s);
}
return newArgs.toArray(new String[0]);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender.hasPermission("libsdisguises.undisguiseplayer")) {
if (args.length > 0) {
Entity p = Bukkit.getPlayer(args[0]);
if (p == null) {
if (p == null) {
if (args[0].contains("-")) {
try {
p = Bukkit.getEntity(UUID.fromString(args[0]));
}
catch (Exception ignored) {
}
}
}
}
if (p != null) {
if (DisguiseAPI.isDisguised(p)) {
DisguiseAPI.undisguiseToAll(p);
sender.sendMessage(LibsMsg.UNDISG_PLAYER
.get(p instanceof Player ? p.getName() : DisguiseType.getType(p).toReadable()));
} else {
sender.sendMessage(LibsMsg.UNDISG_PLAYER_FAIL
.get(p instanceof Player ? p.getName() : DisguiseType.getType(p).toReadable()));
}
} else {
sender.sendMessage(LibsMsg.CANNOT_FIND_PLAYER.get(args[0]));
}
} else {
sender.sendMessage(LibsMsg.UNDISG_PLAYER_HELP.get());
}
} else {
sender.sendMessage(LibsMsg.NO_PERM.get());
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] origArgs) {
ArrayList<String> tabs = new ArrayList<>();
String[] args = getArgs(origArgs);
if (args.length != 0)
return filterTabs(tabs, origArgs);
for (Player player : Bukkit.getOnlinePlayers()) {
tabs.add(player.getName());
}
return filterTabs(tabs, origArgs);
}
}

View File

@@ -0,0 +1,68 @@
package me.libraryaddict.disguise.commands;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.TranslateType;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
public class UndisguiseRadiusCommand implements CommandExecutor {
private int maxRadius = 30;
public UndisguiseRadiusCommand(int maxRadius) {
this.maxRadius = maxRadius;
}
private boolean isNumeric(String string) {
try {
Integer.parseInt(string);
return true;
}
catch (Exception ex) {
return false;
}
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender.getName().equals("CONSOLE")) {
sender.sendMessage(LibsMsg.NO_CONSOLE.get());
return true;
}
if (sender.hasPermission("libsdisguises.undisguiseradius")) {
int radius = maxRadius;
if (args.length > 0) {
if (!isNumeric(args[0])) {
sender.sendMessage(LibsMsg.NOT_NUMBER.get(args[0]));
return true;
}
radius = Integer.parseInt(args[0]);
if (radius > maxRadius) {
sender.sendMessage(LibsMsg.LIMITED_RADIUS.get(maxRadius));
radius = maxRadius;
}
}
int disguisedEntitys = 0;
for (Entity entity : ((Player) sender).getNearbyEntities(radius, radius, radius)) {
if (entity == sender) {
continue;
}
if (DisguiseAPI.isDisguised(entity)) {
DisguiseAPI.undisguiseToAll(entity);
disguisedEntitys++;
}
}
sender.sendMessage(LibsMsg.UNDISRADIUS.get(disguisedEntitys));
} else {
sender.sendMessage(LibsMsg.NO_PERM.get());
}
return true;
}
}

View File

@@ -0,0 +1,35 @@
package me.libraryaddict.disguise.disguisetypes;
public enum AnimalColor
{
BLACK(15), BLUE(11), BROWN(12), CYAN(9), GRAY(7), GREEN(13), LIGHT_BLUE(3), LIME(5), MAGENTA(2), ORANGE(1), PINK(6), PURPLE(
10), RED(14), SILVER(8), WHITE(0), YELLOW(4);
public static AnimalColor getColor(int nmsId)
{
for (AnimalColor color : values())
{
if (color.getId() == nmsId)
{
return color;
}
}
return null;
}
private int value;
AnimalColor(int newValue)
{
value = newValue;
}
/**
* The color ID as defined by nms internals.
*/
public int getId()
{
return value;
}
}

View File

@@ -0,0 +1,861 @@
package me.libraryaddict.disguise.disguisetypes;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.PacketType.Play.Server;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.reflect.StructureModifier;
import com.comphenix.protocol.wrappers.EnumWrappers.NativeGameMode;
import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction;
import com.comphenix.protocol.wrappers.PlayerInfoData;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.DisguiseConfig;
import me.libraryaddict.disguise.LibsDisguises;
import me.libraryaddict.disguise.disguisetypes.TargetedDisguise.TargetType;
import me.libraryaddict.disguise.disguisetypes.watchers.AgeableWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.BatWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.ZombieWatcher;
import me.libraryaddict.disguise.events.DisguiseEvent;
import me.libraryaddict.disguise.events.UndisguiseEvent;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import me.libraryaddict.disguise.utilities.PacketsManager;
import me.libraryaddict.disguise.utilities.ReflectionManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public abstract class Disguise {
private static List<UUID> viewSelf = new ArrayList<>();
/**
* Returns the list of people who have /disguiseViewSelf toggled on
*
* @return
*/
public static List<UUID> getViewSelf() {
return viewSelf;
}
private transient boolean disguiseInUse;
private DisguiseType disguiseType;
private transient Entity entity;
private boolean hearSelfDisguise = DisguiseConfig.isSelfDisguisesSoundsReplaced();
private boolean hideArmorFromSelf = DisguiseConfig.isHidingArmorFromSelf();
private boolean hideHeldItemFromSelf = DisguiseConfig.isHidingHeldItemFromSelf();
private boolean keepDisguisePlayerDeath = DisguiseConfig.isKeepDisguiseOnPlayerDeath();
private boolean modifyBoundingBox = DisguiseConfig.isModifyBoundingBox();
private boolean playerHiddenFromTab = DisguiseConfig.isHideDisguisedPlayers();
private boolean replaceSounds = DisguiseConfig.isSoundEnabled();
private boolean showName;
private transient BukkitTask task;
private Runnable velocityRunnable;
private boolean velocitySent = DisguiseConfig.isVelocitySent();
private boolean viewSelfDisguise = DisguiseConfig.isViewDisguises();
private FlagWatcher watcher;
public Disguise(DisguiseType disguiseType) {
this.disguiseType = disguiseType;
}
@Override
public abstract Disguise clone();
/**
* Seems I do this method so I can make cleaner constructors on disguises..
*/
protected void createDisguise() {
if (getType().getEntityType() == null) {
throw new RuntimeException("DisguiseType " + getType() +
" was used in a futile attempt to construct a disguise, but this Minecraft version does not have " +
"that entity");
}
// Get if they are a adult now..
boolean isAdult = true;
if (isMobDisguise()) {
isAdult = ((MobDisguise) this).isAdult();
}
if (getWatcher() == null) {
try {
// Construct the FlagWatcher from the stored class
setWatcher(getType().getWatcherClass().getConstructor(Disguise.class).newInstance(this));
}
catch (Exception e) {
e.printStackTrace();
}
} else {
getWatcher().setDisguise((TargetedDisguise) this);
}
// Set the disguise if its a baby or not
if (!isAdult) {
if (getWatcher() instanceof AgeableWatcher) {
((AgeableWatcher) getWatcher()).setBaby(true);
} else if (getWatcher() instanceof ZombieWatcher) {
((ZombieWatcher) getWatcher()).setBaby(true);
}
}
}
private void createRunnable() {
final boolean alwaysSendVelocity;
switch (getType()) {
case EGG:
case ENDER_PEARL:
case BAT:
case EXPERIENCE_ORB:
case FIREBALL:
case SMALL_FIREBALL:
case SNOWBALL:
case SPLASH_POTION:
case THROWN_EXP_BOTTLE:
case WITHER_SKULL:
case FIREWORK:
alwaysSendVelocity = true;
break;
default:
alwaysSendVelocity = false;
break;
}
double velocitySpeed = 0.0005;
switch (getType()) {
case FIREWORK:
velocitySpeed = -0.040;
break;
case WITHER_SKULL:
velocitySpeed = 0.000001D;
break;
case ARROW:
case TIPPED_ARROW:
case SPECTRAL_ARROW:
case BOAT:
case ENDER_CRYSTAL:
case ENDER_DRAGON:
case GHAST:
case ITEM_FRAME:
case MINECART:
case MINECART_CHEST:
case MINECART_COMMAND:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
case PAINTING:
case PLAYER:
case SQUID:
velocitySpeed = 0;
break;
case DROPPED_ITEM:
case PRIMED_TNT:
case WITHER:
case FALLING_BLOCK:
velocitySpeed = 0.04;
break;
case EXPERIENCE_ORB:
velocitySpeed = 0.0221;
break;
case SPIDER:
case BAT:
case CAVE_SPIDER:
velocitySpeed = 0.004;
break;
default:
break;
}
final double vectorY = velocitySpeed;
final TargetedDisguise disguise = (TargetedDisguise) this;
// A scheduler to clean up any unused disguises.
velocityRunnable = new Runnable() {
private int blockX, blockY, blockZ, facing;
private int deadTicks = 0;
private int refreshDisguise = 0;
@Override
public void run() {
// If entity is no longer valid. Remove it.
if (getEntity() instanceof Player && !((Player) getEntity()).isOnline())
removeDisguise();
else if (!getEntity().isValid()) {
// If it has been dead for 30+ ticks
// This is to ensure that this disguise isn't removed while clients think its the real entity
// The delay is because if it sends the destroy entity packets straight away, then it means no
// death animation
// This is probably still a problem for wither and enderdragon deaths.
if (deadTicks++ > (getType() == DisguiseType.ENDER_DRAGON ? 200 : 20)) {
deadTicks = 0;
if (isRemoveDisguiseOnDeath()) {
removeDisguise();
}
}
} else {
deadTicks = 0;
// If the disguise type is tnt, we need to resend the entity packet else it will turn invisible
if (getType() == DisguiseType.FIREWORK) {
refreshDisguise++;
if (refreshDisguise == 40) {
refreshDisguise = 0;
DisguiseUtilities.refreshTrackers(disguise);
}
} else if (getType() == DisguiseType.EVOKER_FANGS) {
refreshDisguise++;
if (refreshDisguise == 23) {
refreshDisguise = 0;
DisguiseUtilities.refreshTrackers(disguise);
}
} else if (getType() == DisguiseType.ITEM_FRAME) {
Location loc = getEntity().getLocation();
int newFacing = (((int) loc.getYaw() + 720 + 45) / 90) % 4;
if (loc.getBlockX() != blockX || loc.getBlockY() != blockY || loc.getBlockZ() != blockZ ||
newFacing != facing) {
blockX = loc.getBlockX();
blockY = loc.getBlockY();
blockZ = loc.getBlockZ();
facing = newFacing;
DisguiseUtilities.refreshTrackers(disguise);
}
}
if (isModifyBoundingBox()) {
DisguiseUtilities.doBoundingBox(disguise);
}
if (getType() == DisguiseType.BAT && !((BatWatcher) getWatcher()).isHanging()) {
return;
}
// If the vectorY isn't 0. Cos if it is. Then it doesn't want to send any vectors.
// If this disguise has velocity sending enabled and the entity is flying.
if (isVelocitySent() && vectorY != 0 && (alwaysSendVelocity || !getEntity().isOnGround())) {
Vector vector = getEntity().getVelocity();
// If the entity doesn't have velocity changes already - You know. I really can't wrap my
// head about the
// if statement.
// But it doesn't seem to do anything wrong..
if (vector.getY() != 0 &&
!(vector.getY() < 0 && alwaysSendVelocity && getEntity().isOnGround())) {
return;
}
// If disguise isn't a experience orb, or the entity isn't standing on the ground
if (getType() != DisguiseType.EXPERIENCE_ORB || !getEntity().isOnGround()) {
PacketContainer lookPacket = null;
if (getType() == DisguiseType.WITHER_SKULL &&
DisguiseConfig.isWitherSkullPacketsEnabled()) {
lookPacket = new PacketContainer(Server.ENTITY_LOOK);
StructureModifier<Object> mods = lookPacket.getModifier();
lookPacket.getIntegers().write(0, getEntity().getEntityId());
Location loc = getEntity().getLocation();
mods.write(4, PacketsManager.getYaw(getType(), getEntity().getType(),
(byte) Math.floor(loc.getYaw() * 256.0F / 360.0F)));
mods.write(5, PacketsManager
.getPitch(getType(), DisguiseType.getType(getEntity().getType()),
(byte) Math.floor(loc.getPitch() * 256.0F / 360.0F)));
if (isSelfDisguiseVisible() && getEntity() instanceof Player) {
PacketContainer selfLookPacket = lookPacket.shallowClone();
selfLookPacket.getIntegers().write(0, DisguiseAPI.getSelfDisguiseId());
try {
ProtocolLibrary.getProtocolManager()
.sendServerPacket((Player) getEntity(), selfLookPacket, false);
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
try {
PacketContainer velocityPacket = new PacketContainer(Server.ENTITY_VELOCITY);
StructureModifier<Integer> mods = velocityPacket.getIntegers();
mods.write(1, (int) (vector.getX() * 8000));
mods.write(3, (int) (vector.getZ() * 8000));
for (Player player : DisguiseUtilities.getPerverts(disguise)) {
if (getEntity() == player) {
if (!isSelfDisguiseVisible()) {
continue;
}
mods.write(0, DisguiseAPI.getSelfDisguiseId());
} else {
mods.write(0, getEntity().getEntityId());
}
mods.write(2,
(int) (8000D * (vectorY * ReflectionManager.getPing(player)) * 0.069D));
if (lookPacket != null && player != getEntity()) {
ProtocolLibrary.getProtocolManager()
.sendServerPacket(player, lookPacket, false);
}
ProtocolLibrary.getProtocolManager()
.sendServerPacket(player, velocityPacket.shallowClone(), false);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
// If we need to send a packet to update the exp position as it likes to gravitate client
// sided to
// players.
}
if (getType() == DisguiseType.EXPERIENCE_ORB) {
PacketContainer packet = new PacketContainer(Server.REL_ENTITY_MOVE);
packet.getIntegers().write(0, getEntity().getEntityId());
try {
for (Player player : DisguiseUtilities.getPerverts(disguise)) {
if (getEntity() != player) {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false);
} else if (isSelfDisguiseVisible()) {
PacketContainer selfPacket = packet.shallowClone();
selfPacket.getModifier().write(0, DisguiseAPI.getSelfDisguiseId());
try {
ProtocolLibrary.getProtocolManager()
.sendServerPacket((Player) getEntity(), selfPacket, false);
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
};
}
/**
* Get the disguised entity
*
* @return entity
*/
public Entity getEntity() {
return entity;
}
/**
* Get the disguise type
*
* @return disguiseType
*/
public DisguiseType getType() {
return disguiseType;
}
/**
* Get the flag watcher
*
* @return flagWatcher
*/
public FlagWatcher getWatcher() {
return watcher;
}
/**
* In use doesn't mean that this disguise is active. It means that Lib's Disguises still stores a reference to
* the disguise.
* getEntity() can still return null if this disguise is active after despawn, logout, etc.
*
* @return isDisguiseInUse
*/
public boolean isDisguiseInUse() {
return disguiseInUse;
}
/**
* Will a disguised player appear in tab
*/
public boolean isHidePlayer() {
return playerHiddenFromTab;
}
public boolean isHidingArmorFromSelf() {
return hideArmorFromSelf;
}
public boolean isHidingHeldItemFromSelf() {
return hideHeldItemFromSelf;
}
public boolean isKeepDisguiseOnPlayerDeath() {
return this.keepDisguisePlayerDeath;
}
public boolean isMiscDisguise() {
return false;
}
public boolean isMobDisguise() {
return false;
}
public boolean isModifyBoundingBox() {
return modifyBoundingBox;
}
public boolean isPlayerDisguise() {
return false;
}
/**
* Internal use
*/
public boolean isRemoveDisguiseOnDeath() {
return getEntity() == null ||
(getEntity() instanceof Player ? !isKeepDisguiseOnPlayerDeath() : getEntity().isDead());
}
public boolean isSelfDisguiseSoundsReplaced() {
return hearSelfDisguise;
}
/**
* Can the disguised view himself as the disguise
*
* @return viewSelfDisguise
*/
public boolean isSelfDisguiseVisible() {
return viewSelfDisguise;
}
/**
* Returns true if the entity's name is showing through the disguise
*
* @return
*/
public boolean isShowName() {
return showName;
}
public boolean isSoundsReplaced() {
return replaceSounds;
}
public boolean isVelocitySent() {
return velocitySent;
}
/**
* Removes the disguise and undisguises the entity if its using this disguise.
*
* @return removeDiguise
*/
public boolean removeDisguise() {
if (!isDisguiseInUse())
return false;
UndisguiseEvent event = new UndisguiseEvent(entity, this);
Bukkit.getPluginManager().callEvent(event);
// If this disguise is not in use, and the entity isnt a player that's offline
if (event.isCancelled() && (!(getEntity() instanceof Player) || ((Player) getEntity()).isOnline()))
return false;
disguiseInUse = false;
if (task != null) {
task.cancel();
task = null;
}
// If this disguise has a entity set
if (getEntity() != null) {
if (this instanceof PlayerDisguise) {
PlayerDisguise disguise = (PlayerDisguise) this;
if (disguise.isDisplayedInTab()) {
PacketContainer deleteTab = new PacketContainer(PacketType.Play.Server.PLAYER_INFO);
deleteTab.getPlayerInfoAction().write(0, PlayerInfoAction.REMOVE_PLAYER);
deleteTab.getPlayerInfoDataLists().write(0, Collections.singletonList(
new PlayerInfoData(disguise.getGameProfile(), 0, NativeGameMode.SURVIVAL,
WrappedChatComponent.fromText(disguise.getName()))));
try {
for (Player player : Bukkit.getOnlinePlayers()) {
if (!((TargetedDisguise) this).canSee(player) ||
(!isSelfDisguiseVisible() && getEntity() == player))
continue;
ProtocolLibrary.getProtocolManager().sendServerPacket(player, deleteTab);
}
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
// If this disguise is active
// Remove the disguise from the current disguises.
if (DisguiseUtilities.removeDisguise((TargetedDisguise) this)) {
if (getEntity() instanceof Player) {
DisguiseUtilities.removeSelfDisguise((Player) getEntity());
}
// Better refresh the entity to undisguise it
if (getEntity().isValid()) {
DisguiseUtilities.refreshTrackers((TargetedDisguise) this);
} else {
DisguiseUtilities.destroyEntity((TargetedDisguise) this);
}
}
if (isHidePlayer() && getEntity() instanceof Player && ((Player) getEntity()).isOnline()) {
PlayerInfoData playerInfo = new PlayerInfoData(ReflectionManager.getGameProfile((Player) getEntity()),
0, NativeGameMode.fromBukkit(((Player) getEntity()).getGameMode()),
WrappedChatComponent.fromText(DisguiseUtilities.getPlayerListName((Player) getEntity())));
PacketContainer addTab = new PacketContainer(PacketType.Play.Server.PLAYER_INFO);
addTab.getPlayerInfoAction().write(0, PlayerInfoAction.ADD_PLAYER);
addTab.getPlayerInfoDataLists().write(0, Collections.singletonList(playerInfo));
try {
for (Player player : Bukkit.getOnlinePlayers()) {
if (!((TargetedDisguise) this).canSee(player) ||
(!isSelfDisguiseVisible() && getEntity() == player))
continue;
ProtocolLibrary.getProtocolManager().sendServerPacket(player, addTab);
}
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} else {
// Loop through the disguises because it could be used with a unknown entity id.
HashMap<Integer, HashSet<TargetedDisguise>> future = DisguiseUtilities.getFutureDisguises();
Iterator<Integer> itel = DisguiseUtilities.getFutureDisguises().keySet().iterator();
while (itel.hasNext()) {
int id = itel.next();
if (future.get(id).remove(this) && future.get(id).isEmpty()) {
itel.remove();
}
}
}
return true;
}
/**
* Set the entity of the disguise. Only used for internal things.
*
* @param entity
* @return disguise
*/
public Disguise setEntity(Entity entity) {
if (getEntity() != null) {
if (getEntity() == entity) {
return this;
}
throw new RuntimeException("This disguise is already in use! Try .clone()");
}
if (isMiscDisguise() && !DisguiseConfig.isMiscDisguisesForLivingEnabled() && entity instanceof LivingEntity) {
throw new RuntimeException(
"Cannot disguise a living entity with a misc disguise. Reenable MiscDisguisesForLiving in the " +
"config to do this");
}
this.entity = entity;
if (entity != null) {
setupWatcher();
}
return this;
}
public Disguise setHearSelfDisguise(boolean hearSelfDisguise) {
this.hearSelfDisguise = hearSelfDisguise;
return this;
}
public Disguise setHideArmorFromSelf(boolean hideArmor) {
this.hideArmorFromSelf = hideArmor;
if (getEntity() instanceof Player) {
((Player) getEntity()).updateInventory();
}
return this;
}
public Disguise setHideHeldItemFromSelf(boolean hideHeldItem) {
this.hideHeldItemFromSelf = hideHeldItem;
if (getEntity() instanceof Player) {
((Player) getEntity()).updateInventory();
}
return this;
}
public void setHidePlayer(boolean hidePlayerInTab) {
if (isDisguiseInUse())
throw new IllegalStateException("Cannot set this while disguise is in use!"); // Cos I'm lazy
playerHiddenFromTab = hidePlayerInTab;
}
public Disguise setKeepDisguiseOnPlayerDeath(boolean keepDisguise) {
this.keepDisguisePlayerDeath = keepDisguise;
return this;
}
public Disguise setModifyBoundingBox(boolean modifyBox) {
if (((TargetedDisguise) this).getDisguiseTarget() != TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS) {
throw new RuntimeException("Cannot modify the bounding box of a disguise which is not TargetType" +
".SHOW_TO_EVERYONE_BUT_THESE_PLAYERS");
}
if (isModifyBoundingBox() != modifyBox) {
this.modifyBoundingBox = modifyBox;
if (DisguiseUtilities.isDisguiseInUse(this)) {
DisguiseUtilities.doBoundingBox((TargetedDisguise) this);
}
}
return this;
}
public Disguise setReplaceSounds(boolean areSoundsReplaced) {
replaceSounds = areSoundsReplaced;
return this;
}
public Disguise setShowName(boolean showName) {
this.showName = showName;
return this;
}
/**
* Sets up the FlagWatcher with the entityclass, it creates all the data it needs to prevent conflicts when
* sending the
* datawatcher.
*/
private void setupWatcher() {
ArrayList<MetaIndex> disguiseFlags = MetaIndex.getFlags(getType().getWatcherClass());
ArrayList<MetaIndex> entityFlags = MetaIndex
.getFlags(DisguiseType.getType(getEntity().getType()).getWatcherClass());
for (MetaIndex flag : entityFlags) {
if (disguiseFlags.contains(flag))
continue;
MetaIndex backup = null;
for (MetaIndex flagType : disguiseFlags) {
if (flagType.getIndex() == flag.getIndex())
backup = flagType;
}
getWatcher().setBackupValue(flag, backup == null ? null : backup.getDefault());
}
getWatcher().setNoGravity(true);
}
public Disguise setVelocitySent(boolean sendVelocity) {
this.velocitySent = sendVelocity;
return this;
}
/**
* Can the disguised view himself as the disguise
*
* @param viewSelfDisguise
* @return
*/
public Disguise setViewSelfDisguise(boolean viewSelfDisguise) {
if (isSelfDisguiseVisible() != viewSelfDisguise) {
this.viewSelfDisguise = viewSelfDisguise;
if (getEntity() != null && getEntity() instanceof Player) {
if (DisguiseAPI.getDisguise((Player) getEntity(), getEntity()) == this) {
if (isSelfDisguiseVisible()) {
DisguiseUtilities.setupFakeDisguise(this);
} else {
DisguiseUtilities.removeSelfDisguise((Player) getEntity());
}
}
}
}
return this;
}
public Disguise setWatcher(FlagWatcher newWatcher) {
if (!getType().getWatcherClass().isInstance(newWatcher)) {
throw new IllegalArgumentException(newWatcher.getClass().getSimpleName() + " is not a instance of " +
getType().getWatcherClass().getSimpleName() + " for DisguiseType " + getType().name());
}
watcher = newWatcher;
if (getEntity() != null) {
setupWatcher();
}
return this;
}
public boolean startDisguise() {
if (isDisguiseInUse()) {
return false;
}
if (getEntity() == null) {
throw new RuntimeException("No entity is assigned to this disguise!");
}
DisguiseUtilities.setPluginsUsed();
// Fire a disguise event
DisguiseEvent event = new DisguiseEvent(entity, this);
Bukkit.getPluginManager().
callEvent(event);
// If they cancelled this disguise event. No idea why.
// Just return.
if (event.isCancelled()) {
return false;
}
disguiseInUse = true;
if (velocityRunnable == null) {
createRunnable();
}
task = Bukkit.getScheduler().
runTaskTimer(LibsDisguises.getInstance(), velocityRunnable, 1, 1);
if (this instanceof PlayerDisguise) {
PlayerDisguise disguise = (PlayerDisguise) this;
if (disguise.isDisplayedInTab()) {
PacketContainer addTab = new PacketContainer(PacketType.Play.Server.PLAYER_INFO);
addTab.getPlayerInfoAction().write(0, PlayerInfoAction.ADD_PLAYER);
addTab.getPlayerInfoDataLists().write(0, Collections.singletonList(
new PlayerInfoData(disguise.getGameProfile(), 0, NativeGameMode.SURVIVAL,
WrappedChatComponent.fromText(disguise.getName()))));
try {
for (Player player : Bukkit.getOnlinePlayers()) {
if (!((TargetedDisguise) this).canSee(player) ||
(!isSelfDisguiseVisible() && getEntity() == player))
continue;
ProtocolLibrary.getProtocolManager().sendServerPacket(player, addTab);
}
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
// Stick the disguise in the disguises bin
DisguiseUtilities.addDisguise(entity.getUniqueId(), (TargetedDisguise) this);
if (isSelfDisguiseVisible() && getEntity() instanceof Player) {
DisguiseUtilities.removeSelfDisguise((Player) getEntity());
}
// Resend the disguised entity's packet
DisguiseUtilities.refreshTrackers((TargetedDisguise) this);
// If he is a player, then self disguise himself
Bukkit.getScheduler().
scheduleSyncDelayedTask(LibsDisguises.getInstance(), new Runnable() {
@Override
public void run() {
DisguiseUtilities.setupFakeDisguise(Disguise.this);
}
}, 2);
if (isHidePlayer() && getEntity() instanceof Player) {
PacketContainer addTab = new PacketContainer(PacketType.Play.Server.PLAYER_INFO);
addTab.getPlayerInfoAction().write(0, PlayerInfoAction.REMOVE_PLAYER);
addTab.getPlayerInfoDataLists().write(0, Collections.singletonList(
new PlayerInfoData(ReflectionManager.getGameProfile((Player) getEntity()), 0,
NativeGameMode.SURVIVAL, WrappedChatComponent.fromText(""))));
try {
for (Player player : Bukkit.getOnlinePlayers()) {
if (!((TargetedDisguise) this).canSee(player) ||
(!isSelfDisguiseVisible() && getEntity() == player))
continue;
ProtocolLibrary.getProtocolManager().sendServerPacket(player, addTab);
}
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return true;
}
public boolean stopDisguise() {
return removeDisguise();
}
}

View File

@@ -0,0 +1,325 @@
package me.libraryaddict.disguise.disguisetypes;
import me.libraryaddict.disguise.utilities.TranslateType;
import org.apache.commons.lang.StringUtils;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
public enum DisguiseType {
AREA_EFFECT_CLOUD(3, 0),
ARMOR_STAND(78),
ARROW(60, 0),
BAT,
BLAZE,
BOAT(1),
CAVE_SPIDER,
CHICKEN,
COD,
COW,
CREEPER,
DOLPHIN,
DONKEY,
DRAGON_FIREBALL(93),
DROWNED,
DROPPED_ITEM(2, 1),
EGG(62),
ELDER_GUARDIAN,
ENDER_CRYSTAL(51),
ENDER_DRAGON,
ENDER_PEARL(65),
ENDER_SIGNAL(72),
ENDERMAN,
ENDERMITE,
EVOKER,
EVOKER_FANGS(79),
EXPERIENCE_ORB,
FALLING_BLOCK(70, 1),
FIREBALL(63),
FIREWORK(76),
FISHING_HOOK(90),
GHAST,
GIANT,
GUARDIAN,
HORSE,
HUSK,
ILLUSIONER,
IRON_GOLEM,
ITEM_FRAME(71),
LLAMA,
LLAMA_SPIT(68),
LEASH_HITCH(77),
MAGMA_CUBE,
MINECART(10),
MINECART_CHEST(10, 1),
MINECART_COMMAND(10, 6),
MINECART_FURNACE(10, 2),
MINECART_HOPPER(10, 5),
MINECART_MOB_SPAWNER(10, 4),
MINECART_TNT(10, 3),
MULE,
MUSHROOM_COW,
OCELOT,
PAINTING,
PARROT,
PHANTOM,
PIG,
PIG_ZOMBIE,
PLAYER,
POLAR_BEAR,
PRIMED_TNT(50),
PUFFERFISH,
RABBIT,
SALMON,
SHEEP,
SHULKER,
SHULKER_BULLET(67),
SILVERFISH,
SKELETON,
SKELETON_HORSE,
SLIME,
SMALL_FIREBALL(63),
SNOWBALL(61),
SNOWMAN,
SPECTRAL_ARROW(91),
SPIDER,
SPLASH_POTION(73, 0),
SQUID,
STRAY,
THROWN_EXP_BOTTLE(75),
TIPPED_ARROW(60),
TRIDENT(94, 0),
TROPICAL_FISH,
TURTLE,
ZOMBIE_HORSE,
UNKNOWN,
VEX,
VILLAGER,
VINDICATOR,
WITCH,
WITHER,
WITHER_SKELETON,
WITHER_SKULL(66),
WOLF,
ZOMBIE,
ZOMBIE_VILLAGER;
static {
for (DisguiseType type : values()) {
String name = type.name();
type.setEntityType(EntityType.valueOf(name));
}
}
public static DisguiseType getType(Entity entity) {
DisguiseType disguiseType = getType(entity.getType());
return disguiseType;
}
public static DisguiseType getType(EntityType entityType) {
try {
return valueOf(entityType.name().toUpperCase());
}
catch (Throwable ex) {
return DisguiseType.UNKNOWN;
}
}
private EntityType entityType;
private int objectId = -1, defaultData = 0;
private int typeId;
private Class<? extends FlagWatcher> watcherClass;
DisguiseType(int... ints) {
for (int i = 0; i < ints.length; i++) {
int value = ints[i];
switch (i) {
case 0:
objectId = value;
break;
case 1:
defaultData = value;
break;
default:
break;
}
}
}
public int getDefaultData() {
return defaultData;
}
public Class<? extends Entity> getEntityClass() {
if (entityType != null && getEntityType().getEntityClass() != null) {
return getEntityType().getEntityClass();
}
return Entity.class;
}
public EntityType getEntityType() {
return entityType;
}
/**
* The object type send in packets when spawning a misc entity. Otherwise, -1.
*
* @return
*/
public int getObjectId() {
return objectId;
}
/**
* The TYPE id of this entity. Different from the Object Id send in spawn packets when spawning miscs.
*
* @return
*/
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public Class<? extends FlagWatcher> getWatcherClass() {
return watcherClass;
}
public boolean isMisc() {
return getEntityType() != null && !getEntityType().isAlive();
}
public boolean isMob() {
return getEntityType() != null && getEntityType().isAlive() && !isPlayer();
}
public boolean isPlayer() {
return this == DisguiseType.PLAYER;
}
public boolean isUnknown() {
return this == DisguiseType.UNKNOWN;
}
private void setEntityType(EntityType entityType) {
this.entityType = entityType;
}
public void setWatcherClass(Class<? extends FlagWatcher> c) {
watcherClass = c;
}
public String toReadable() {
String[] split = name().split("_");
for (int i = 0; i < split.length; i++) {
split[i] = split[i].substring(0, 1) + split[i].substring(1).toLowerCase();
}
return TranslateType.DISGUISES.get(StringUtils.join(split, " "));
}
}

View File

@@ -0,0 +1,562 @@
package me.libraryaddict.disguise.disguisetypes;
import com.comphenix.protocol.PacketType.Play.Server;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.reflect.StructureModifier;
import com.comphenix.protocol.wrappers.ComponentConverter;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import com.comphenix.protocol.wrappers.WrappedWatchableObject;
import com.google.common.base.Strings;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.DisguiseConfig;
import me.libraryaddict.disguise.LibsDisguises;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import me.libraryaddict.disguise.utilities.ReflectionManager;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class FlagWatcher {
private boolean addEntityAnimations = DisguiseConfig.isEntityAnimationsAdded();
/**
* These are the entity values I need to add else it could crash them..
*/
private HashMap<Integer, Object> backupEntityValues = new HashMap<>();
private transient TargetedDisguise disguise;
private HashMap<Integer, Object> entityValues = new HashMap<>();
private LibsEquipment equipment;
private boolean hasDied;
private boolean[] modifiedEntityAnimations = new boolean[8];
private transient List<WrappedWatchableObject> watchableObjects;
public FlagWatcher(Disguise disguise) {
this.disguise = (TargetedDisguise) disguise;
this.setData(MetaIndex.ENTITY_AIR_TICKS, 0);
equipment = new LibsEquipment(this);
}
private byte addEntityAnimations(byte originalValue, byte entityValue) {
for (int i = 0; i < 6; i++) {
if ((entityValue & 1 << i) != 0 && !modifiedEntityAnimations[i]) {
originalValue = (byte) (originalValue | 1 << i);
}
}
return originalValue;
}
public FlagWatcher clone(Disguise owningDisguise) {
FlagWatcher cloned;
try {
cloned = getClass().getConstructor(Disguise.class).newInstance(getDisguise());
}
catch (Exception e) {
e.printStackTrace();
cloned = new FlagWatcher(getDisguise());
}
cloned.entityValues = (HashMap<Integer, Object>) entityValues.clone();
cloned.equipment = equipment.clone(cloned);
cloned.modifiedEntityAnimations = Arrays.copyOf(modifiedEntityAnimations, modifiedEntityAnimations.length);
cloned.addEntityAnimations = addEntityAnimations;
return cloned;
}
public List<WrappedWatchableObject> convert(List<WrappedWatchableObject> list) {
List<WrappedWatchableObject> newList = new ArrayList<>();
HashSet<Integer> sentValues = new HashSet<>();
boolean sendAllCustom = false;
for (WrappedWatchableObject watch : list) {
int id = watch.getIndex();
sentValues.add(id);
// Its sending the air metadata. This is the least commonly sent metadata which all entitys still share.
// I send my custom values if I see this!
if (id == MetaIndex.ENTITY_AIR_TICKS.getIndex()) {
sendAllCustom = true;
}
Object value = null;
if (entityValues.containsKey(id)) {
if (entityValues.get(id) == null) {
continue;
}
value = entityValues.get(id);
} else if (backupEntityValues.containsKey(id)) {
if (backupEntityValues.get(id) == null) {
continue;
}
value = backupEntityValues.get(id);
}
if (value != null) {
if (isEntityAnimationsAdded() && id == 0) {
value = addEntityAnimations((byte) value, (byte) watch.getValue());
}
boolean isDirty = watch.getDirtyState();
watch = ReflectionManager.createWatchable(id, value);
if (watch == null)
continue;
if (!isDirty) {
watch.setDirtyState(false);
}
} else {
boolean isDirty = watch.getDirtyState();
watch = ReflectionManager.createWatchable(id, watch.getValue());
if (watch == null)
continue;
if (!isDirty) {
watch.setDirtyState(false);
}
}
newList.add(watch);
}
if (sendAllCustom) {
// Its sending the entire meta data. Better add the custom meta
for (Integer id : entityValues.keySet()) {
if (sentValues.contains(id)) {
continue;
}
Object value = entityValues.get(id);
if (value == null) {
continue;
}
WrappedWatchableObject watch = ReflectionManager.createWatchable(id, value);
if (watch == null)
continue;
newList.add(watch);
}
}
// Here we check for if there is a health packet that says they died.
if (getDisguise().isSelfDisguiseVisible() && getDisguise().getEntity() != null &&
getDisguise().getEntity() instanceof Player) {
for (WrappedWatchableObject watch : newList) {
// Its a health packet
if (watch.getIndex() == 6) {
Object value = watch.getValue();
if (value instanceof Float) {
float newHealth = (Float) value;
if (newHealth > 0 && hasDied) {
hasDied = false;
Bukkit.getScheduler()
.scheduleSyncDelayedTask(LibsDisguises.getInstance(), () -> {
try {
DisguiseUtilities.sendSelfDisguise((Player) getDisguise().getEntity(),
getDisguise());
}
catch (Exception ex) {
ex.printStackTrace();
}
}, 2);
} else if (newHealth <= 0 && !hasDied) {
hasDied = true;
}
}
}
}
}
return newList;
}
public ItemStack[] getArmor() {
return getEquipment().getArmorContents();
}
public String getCustomName() {
Optional<WrappedChatComponent> optional = getData(MetaIndex.ENTITY_CUSTOM_NAME);
if (optional.isPresent()) {
BaseComponent[] base = ComponentConverter.fromWrapper(optional.get());
return TextComponent.toLegacyText(base);
}
return null;
}
protected TargetedDisguise getDisguise() {
return disguise;
}
private boolean getEntityFlag(int byteValue) {
return (getData(MetaIndex.ENTITY_META) & 1 << byteValue) != 0;
}
public EntityEquipment getEquipment() {
return equipment;
}
public ItemStack getItemInMainHand() {
return equipment.getItemInMainHand();
}
public ItemStack getItemInOffHand() {
return equipment.getItemInOffHand();
}
public ItemStack getItemStack(EquipmentSlot slot) {
return equipment.getItem(slot);
}
protected <Y> Y getData(MetaIndex<Y> flagType) {
if (flagType == null)
return null;
if (entityValues.containsKey(flagType.getIndex())) {
return (Y) entityValues.get(flagType.getIndex());
}
return flagType.getDefault();
}
public List<WrappedWatchableObject> getWatchableObjects() {
if (watchableObjects == null) {
rebuildWatchableObjects();
}
return watchableObjects;
}
public boolean hasCustomName() {
return getCustomName() != null;
}
protected boolean hasValue(MetaIndex no) {
if (no == null)
return false;
return entityValues.containsKey(no.getIndex());
}
public boolean isBurning() {
return getEntityFlag(0);
}
public boolean isCustomNameVisible() {
return getData(MetaIndex.ENTITY_CUSTOM_NAME_VISIBLE);
}
public boolean isEntityAnimationsAdded() {
return addEntityAnimations;
}
public boolean isFlyingWithElytra() {
return getEntityFlag(7);
}
public boolean isGlowing() {
return getEntityFlag(6);
}
public boolean isInvisible() {
return getEntityFlag(5);
}
public boolean isNoGravity() {
return getData(MetaIndex.ENTITY_NO_GRAVITY);
}
public boolean isRightClicking() {
return getEntityFlag(4);
}
public boolean isSneaking() {
return getEntityFlag(1);
}
public boolean isSprinting() {
return getEntityFlag(3);
}
public void rebuildWatchableObjects() {
watchableObjects = new ArrayList<>();
for (int i = 0; i <= 31; i++) {
WrappedWatchableObject watchable;
if (entityValues.containsKey(i) && entityValues.get(i) != null) {
watchable = ReflectionManager.createWatchable(i, entityValues.get(i));
} else if (backupEntityValues.containsKey(i) && backupEntityValues.get(i) != null) {
watchable = ReflectionManager.createWatchable(i, backupEntityValues.get(i));
} else {
continue;
}
if (watchable == null)
continue;
watchableObjects.add(watchable);
}
}
protected void sendData(MetaIndex... dataValues) {
if (!DisguiseAPI.isDisguiseInUse(getDisguise()) || getDisguise().getWatcher() != this) {
return;
}
List<WrappedWatchableObject> list = new ArrayList<>();
for (MetaIndex data : dataValues) {
if (data == null)
continue;
if (!entityValues.containsKey(data.getIndex()) || entityValues.get(data.getIndex()) == null) {
continue;
}
Object value = entityValues.get(data.getIndex());
if (isEntityAnimationsAdded() && DisguiseConfig.isMetadataPacketsEnabled() &&
data == MetaIndex.ENTITY_META) {
value = addEntityAnimations((byte) value,
WrappedDataWatcher.getEntityWatcher(disguise.getEntity()).getByte(0));
}
WrappedWatchableObject watch = ReflectionManager.createWatchable(data.getIndex(), value);
if (watch == null)
continue;
list.add(watch);
}
if (!list.isEmpty()) {
PacketContainer packet = new PacketContainer(Server.ENTITY_METADATA);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, getDisguise().getEntity().getEntityId());
packet.getWatchableCollectionModifier().write(0, list);
for (Player player : DisguiseUtilities.getPerverts(getDisguise())) {
try {
if (player == getDisguise().getEntity()) {
PacketContainer temp = packet.shallowClone();
temp.getIntegers().write(0, DisguiseAPI.getSelfDisguiseId());
ProtocolLibrary.getProtocolManager().sendServerPacket(player, temp);
} else {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
}
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
public void setAddEntityAnimations(boolean isEntityAnimationsAdded) {
addEntityAnimations = isEntityAnimationsAdded;
}
public void setArmor(ItemStack[] items) {
getEquipment().setArmorContents(items);
}
protected void setBackupValue(MetaIndex no, Object value) {
if (no == null)
return;
backupEntityValues.put(no.getIndex(), value);
}
public void setBurning(boolean setBurning) {
setEntityFlag(0, setBurning);
sendData(MetaIndex.ENTITY_META);
}
public void setCustomName(String name) {
if (Strings.isNullOrEmpty(name)) {
setData(MetaIndex.ENTITY_CUSTOM_NAME, Optional.empty());
} else {
if (name.length() > 64) {
name = name.substring(0, 64);
}
setData(MetaIndex.ENTITY_CUSTOM_NAME, Optional.of(WrappedChatComponent.fromText(name)));
}
sendData(MetaIndex.ENTITY_CUSTOM_NAME);
}
public void setCustomNameVisible(boolean display) {
setData(MetaIndex.ENTITY_CUSTOM_NAME_VISIBLE, display);
sendData(MetaIndex.ENTITY_CUSTOM_NAME_VISIBLE);
}
private void setEntityFlag(int byteValue, boolean flag) {
modifiedEntityAnimations[byteValue] = true;
byte b0 = getData(MetaIndex.ENTITY_META);
if (flag) {
setData(MetaIndex.ENTITY_META, (byte) (b0 | 1 << byteValue));
} else {
setData(MetaIndex.ENTITY_META, (byte) (b0 & ~(1 << byteValue)));
}
}
public void setFlyingWithElytra(boolean flying) {
setEntityFlag(7, flying);
sendData(MetaIndex.ENTITY_META);
}
public void setGlowing(boolean glowing) {
setEntityFlag(6, glowing);
sendData(MetaIndex.ENTITY_META);
}
public void setInvisible(boolean setInvis) {
setEntityFlag(5, setInvis);
sendData(MetaIndex.ENTITY_META);
}
/**
* Don't use this, use setItemInMainHand instead
*
* @param itemstack
*/
@Deprecated
public void setItemInHand(ItemStack itemstack) {
setItemInMainHand(itemstack);
}
public void setItemInMainHand(ItemStack itemstack) {
setItemStack(EquipmentSlot.HAND, itemstack);
}
public void setItemInOffHand(ItemStack itemstack) {
setItemStack(EquipmentSlot.OFF_HAND, itemstack);
}
public void setItemStack(EquipmentSlot slot, ItemStack itemStack) {
equipment.setItem(slot, itemStack);
}
protected void sendItemStack(EquipmentSlot slot, ItemStack itemStack) {
if (!DisguiseAPI.isDisguiseInUse(getDisguise()) || getDisguise().getWatcher() != this ||
getDisguise().getEntity() == null)
return;
if (itemStack == null && getDisguise().getEntity() instanceof LivingEntity) {
EntityEquipment equip = ((LivingEntity) getDisguise().getEntity()).getEquipment();
switch (slot) {
case HAND:
itemStack = equip.getItemInMainHand();
break;
case OFF_HAND:
itemStack = equip.getItemInOffHand();
break;
case HEAD:
itemStack = equip.getHelmet();
break;
case CHEST:
itemStack = equip.getChestplate();
break;
case LEGS:
itemStack = equip.getLeggings();
break;
case FEET:
itemStack = equip.getBoots();
break;
default:
break;
}
}
Object itemToSend = ReflectionManager.getNmsItem(itemStack);
PacketContainer packet = new PacketContainer(Server.ENTITY_EQUIPMENT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, getDisguise().getEntity().getEntityId());
mods.write(1, ReflectionManager.createEnumItemSlot(slot));
mods.write(2, itemToSend);
for (Player player : DisguiseUtilities.getPerverts(getDisguise())) {
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
public void setNoGravity(boolean noGravity) {
setData(MetaIndex.ENTITY_NO_GRAVITY, noGravity);
sendData(MetaIndex.ENTITY_NO_GRAVITY);
}
public void setRightClicking(boolean setRightClicking) {
setEntityFlag(4, setRightClicking);
sendData(MetaIndex.ENTITY_META);
}
public void setSneaking(boolean setSneaking) {
setEntityFlag(1, setSneaking);
sendData(MetaIndex.ENTITY_META);
}
public void setSprinting(boolean setSprinting) {
setEntityFlag(3, setSprinting);
sendData(MetaIndex.ENTITY_META);
}
protected <Y> void setData(MetaIndex<Y> id, Y value) {
if (id == null)
return;
if (value == null && id.getDefault() instanceof ItemStack)
throw new IllegalArgumentException("Cannot use null ItemStacks");
entityValues.put(id.getIndex(), value);
if (!DisguiseConfig.isMetadataPacketsEnabled()) {
rebuildWatchableObjects();
}
}
protected void setDisguise(TargetedDisguise disguise) {
this.disguise = disguise;
equipment.setFlagWatcher(this);
}
}

View File

@@ -0,0 +1,210 @@
package me.libraryaddict.disguise.disguisetypes; // Its here so I can make use of flagWatcher.sendItemStack() which is protected
import org.bukkit.entity.Entity;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import java.io.Serializable;
public class LibsEquipment implements EntityEquipment {
private ItemStack[] equipment = new ItemStack[EquipmentSlot.values().length];
private transient FlagWatcher flagWatcher;
public LibsEquipment(FlagWatcher flagWatcher) {
this.flagWatcher = flagWatcher;
}
protected void setFlagWatcher(FlagWatcher flagWatcher) {
this.flagWatcher = flagWatcher;
}
public LibsEquipment clone(FlagWatcher flagWatcher) {
LibsEquipment newEquip = new LibsEquipment(flagWatcher);
for (int i = 0; i < equipment.length; i++) {
ItemStack item = equipment[i];
if (item == null)
continue;
newEquip.equipment[i] = item.clone();
}
return newEquip;
}
public ItemStack getItem(EquipmentSlot slot) {
return equipment[slot.ordinal()];
}
public void setItem(EquipmentSlot slot, ItemStack item) {
if (getItem(slot) == item)
return;
equipment[slot.ordinal()] = item;
flagWatcher.sendItemStack(slot, item);
}
public ItemStack getItemInMainHand() {
return getItem(EquipmentSlot.HAND);
}
public void setItemInMainHand(ItemStack item) {
setItem(EquipmentSlot.HAND, item);
}
public ItemStack getItemInOffHand() {
return getItem(EquipmentSlot.OFF_HAND);
}
public void setItemInOffHand(ItemStack item) {
setItem(EquipmentSlot.OFF_HAND, item);
}
@Override
public ItemStack getItemInHand() {
return getItem(EquipmentSlot.HAND);
}
@Override
public void setItemInHand(ItemStack stack) {
setItem(EquipmentSlot.HAND, stack);
}
@Override
public ItemStack getHelmet() {
return getItem(EquipmentSlot.HEAD);
}
@Override
public void setHelmet(ItemStack helmet) {
setItem(EquipmentSlot.HEAD, helmet);
}
@Override
public ItemStack getChestplate() {
return getItem(EquipmentSlot.CHEST);
}
@Override
public void setChestplate(ItemStack chestplate) {
setItem(EquipmentSlot.CHEST, chestplate);
}
@Override
public ItemStack getLeggings() {
return getItem(EquipmentSlot.LEGS);
}
@Override
public void setLeggings(ItemStack leggings) {
setItem(EquipmentSlot.LEGS, leggings);
}
@Override
public ItemStack getBoots() {
return getItem(EquipmentSlot.FEET);
}
@Override
public void setBoots(ItemStack boots) {
setItem(EquipmentSlot.FEET, boots);
}
@Override
public ItemStack[] getArmorContents() {
return new ItemStack[]{getBoots(), getLeggings(), getChestplate(), getHelmet()};
}
@Override
public void setArmorContents(ItemStack[] items) {
setBoots(items[0]);
setLeggings(items[1]);
setChestplate(items[2]);
setHelmet(items[3]);
}
@Override
public void clear() {
setBoots(null);
setLeggings(null);
setChestplate(null);
setHelmet(null);
}
@Override
public float getItemInHandDropChance() {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public void setItemInHandDropChance(float chance) {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public float getItemInMainHandDropChance() {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public void setItemInMainHandDropChance(float chance) {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public float getItemInOffHandDropChance() {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public void setItemInOffHandDropChance(float chance) {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public float getHelmetDropChance() {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public void setHelmetDropChance(float chance) {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public float getChestplateDropChance() {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public void setChestplateDropChance(float chance) {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public float getLeggingsDropChance() {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public void setLeggingsDropChance(float chance) {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public float getBootsDropChance() {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public void setBootsDropChance(float chance) {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
@Override
public Entity getHolder() {
throw new UnsupportedOperationException("This is not supported on a disguise");
}
}

View File

@@ -0,0 +1,592 @@
package me.libraryaddict.disguise.disguisetypes;
import com.comphenix.protocol.wrappers.BlockPosition;
import com.comphenix.protocol.wrappers.EnumWrappers.Direction;
import com.comphenix.protocol.wrappers.Vector3F;
import com.comphenix.protocol.wrappers.WrappedBlockData;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import com.comphenix.protocol.wrappers.nbt.NbtBase;
import com.comphenix.protocol.wrappers.nbt.NbtFactory;
import com.comphenix.protocol.wrappers.nbt.NbtType;
import me.libraryaddict.disguise.disguisetypes.watchers.*;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Field;
import java.util.*;
import java.util.Map.Entry;
public class MetaIndex<Y> {
private static MetaIndex[] _values = new MetaIndex[0];
public static MetaIndex<Boolean> AGEABLE_BABY = new MetaIndex<>(AgeableWatcher.class, 0, false);
public static MetaIndex<Integer> AREA_EFFECT_CLOUD_COLOR = new MetaIndex<>(AreaEffectCloudWatcher.class, 1,
Color.BLACK.asRGB());
public static MetaIndex<Boolean> AREA_EFFECT_IGNORE_RADIUS = new MetaIndex<>(AreaEffectCloudWatcher.class, 2,
false);
public static MetaIndex<Particle> AREA_EFFECT_PARTICLE = new MetaIndex<>(AreaEffectCloudWatcher.class, 3,
Particle.SPELL_MOB);
public static MetaIndex<Float> AREA_EFFECT_RADIUS = new MetaIndex<>(AreaEffectCloudWatcher.class, 0, 3F);
public static MetaIndex<Vector3F> ARMORSTAND_BODY = new MetaIndex<>(ArmorStandWatcher.class, 2,
new Vector3F(0, 0, 0));
public static MetaIndex<Vector3F> ARMORSTAND_HEAD = new MetaIndex<>(ArmorStandWatcher.class, 1,
new Vector3F(0, 0, 0));
public static MetaIndex<Vector3F> ARMORSTAND_LEFT_ARM = new MetaIndex<>(ArmorStandWatcher.class, 3,
new Vector3F(-10, 0, -10));
public static MetaIndex<Vector3F> ARMORSTAND_LEFT_LEG = new MetaIndex<>(ArmorStandWatcher.class, 5,
new Vector3F(-1, 0, -1));
public static MetaIndex<Byte> ARMORSTAND_META = new MetaIndex<>(ArmorStandWatcher.class, 0, (byte) 0);
public static MetaIndex<Vector3F> ARMORSTAND_RIGHT_ARM = new MetaIndex<>(ArmorStandWatcher.class, 4,
new Vector3F(-15, 0, 10));
public static MetaIndex<Vector3F> ARMORSTAND_RIGHT_LEG = new MetaIndex<>(ArmorStandWatcher.class, 6,
new Vector3F(1, 0, 1));
public static MetaIndex<Byte> ARROW_CRITICAL = new MetaIndex<>(ArrowWatcher.class, 0, (byte) 0);
public static MetaIndex<Optional<UUID>> ARROW_UUID = new MetaIndex<>(ArrowWatcher.class, 1, Optional.empty());
public static MetaIndex<Byte> BAT_HANGING = new MetaIndex<>(BatWatcher.class, 0, (byte) 1);
public static MetaIndex<Byte> BLAZE_BLAZING = new MetaIndex<>(BlazeWatcher.class, 0, (byte) 0);
public static MetaIndex<Float> BOAT_DAMAGE = new MetaIndex<>(BoatWatcher.class, 2, 0F);
public static MetaIndex<Integer> BOAT_DIRECTION = new MetaIndex<>(BoatWatcher.class, 1, 1);
public static MetaIndex<Integer> BOAT_LAST_HIT = new MetaIndex<>(BoatWatcher.class, 0, 0);
public static MetaIndex<Boolean> BOAT_LEFT_PADDLING = new MetaIndex<>(BoatWatcher.class, 5, false);
public static MetaIndex<Boolean> BOAT_RIGHT_PADDLING = new MetaIndex<>(BoatWatcher.class, 4, false);
public static MetaIndex<Integer> BOAT_TYPE = new MetaIndex<>(BoatWatcher.class, 3, 0);
public static MetaIndex<Integer> BOAT_SHAKE = new MetaIndex<>(BoatWatcher.class, 6, 0);
public static MetaIndex<Boolean> CREEPER_IGNITED = new MetaIndex<>(CreeperWatcher.class, 2, false);
public static MetaIndex<Boolean> CREEPER_POWERED = new MetaIndex<>(CreeperWatcher.class, 1, false);
public static MetaIndex<Integer> CREEPER_STATE = new MetaIndex<>(CreeperWatcher.class, 0, -1);
public static MetaIndex<BlockPosition> DOLPHIN_TREASURE_POS = new MetaIndex<>(DolphinWatcher.class, 0,
BlockPosition.ORIGIN);
public static MetaIndex<Boolean> DOLPHIN_HAS_FISH = new MetaIndex<>(DolphinWatcher.class, 1, false);
public static MetaIndex<Integer> DOLPHIN_BREATH = new MetaIndex<>(DolphinWatcher.class, 2, 2400);
public static MetaIndex<ItemStack> DROPPED_ITEM = new MetaIndex<>(DroppedItemWatcher.class, 0,
new ItemStack(Material.AIR));
public static MetaIndex<Optional<BlockPosition>> ENDER_CRYSTAL_BEAM = new MetaIndex<>(EnderCrystalWatcher.class, 0,
Optional.empty());
public static MetaIndex<Boolean> ENDER_CRYSTAL_PLATE = new MetaIndex<>(EnderCrystalWatcher.class, 1, true);
public static MetaIndex<Integer> ENDER_DRAGON_PHASE = new MetaIndex<>(EnderDragonWatcher.class, 0, 10);
public static MetaIndex<Boolean> ENDERMAN_AGRESSIVE = new MetaIndex<>(EndermanWatcher.class, 1, false);
public static MetaIndex<Optional<WrappedBlockData>> ENDERMAN_ITEM = new MetaIndex<>(EndermanWatcher.class, 0,
Optional.empty());
public static MetaIndex<Integer> ENTITY_AIR_TICKS = new MetaIndex<>(FlagWatcher.class, 1, 300);
public static MetaIndex<Optional<WrappedChatComponent>> ENTITY_CUSTOM_NAME = new MetaIndex<>(FlagWatcher.class, 2,
Optional.empty());
public static MetaIndex<Boolean> ENTITY_CUSTOM_NAME_VISIBLE = new MetaIndex<>(FlagWatcher.class, 3, false);
public static MetaIndex<Byte> ENTITY_META = new MetaIndex<>(FlagWatcher.class, 0, (byte) 0);
public static MetaIndex<Boolean> ENTITY_NO_GRAVITY = new MetaIndex<>(FlagWatcher.class, 5, false);
public static MetaIndex<Boolean> ENTITY_SILENT = new MetaIndex<>(FlagWatcher.class, 4, false);
public static MetaIndex<BlockPosition> FALLING_BLOCK_POSITION = new MetaIndex<>(FallingBlockWatcher.class, 0,
BlockPosition.ORIGIN);
public static MetaIndex<ItemStack> FIREWORK_ITEM = new MetaIndex<>(FireworkWatcher.class, 0,
new ItemStack(Material.FIREWORK_ROCKET));
public static MetaIndex<Boolean> FISH_FROM_BUCKET = new MetaIndex<>(FishWatcher.class, 0, false);
public static MetaIndex<Integer> FIREWORK_ATTACHED_ENTITY = new MetaIndex<>(FireworkWatcher.class, 1, 0);
public static MetaIndex<Integer> FISHING_HOOK_HOOKED = new MetaIndex<>(FishingHookWatcher.class, 0, 0);
public static MetaIndex<Boolean> GHAST_AGRESSIVE = new MetaIndex<>(GhastWatcher.class, 0, false);
public static MetaIndex<Boolean> GUARDIAN_RETRACT_SPIKES = new MetaIndex<>(GuardianWatcher.class, 0, false);
public static MetaIndex<Integer> GUARDIAN_TARGET = new MetaIndex<>(GuardianWatcher.class, 1, 0);
public static MetaIndex<Integer> HORSE_ARMOR = new MetaIndex<>(HorseWatcher.class, 1, 0);
public static MetaIndex<Boolean> HORSE_CHESTED_CARRYING_CHEST = new MetaIndex<>(ChestedHorseWatcher.class, 0,
false);
public static MetaIndex<Integer> HORSE_COLOR = new MetaIndex<>(HorseWatcher.class, 0, 0);
public static MetaIndex<Byte> HORSE_META = new MetaIndex<>(AbstractHorseWatcher.class, 0, (byte) 0);
public static MetaIndex<Optional<UUID>> HORSE_OWNER = new MetaIndex<>(AbstractHorseWatcher.class, 1,
Optional.empty());
public static MetaIndex<Byte> ILLAGER_META = new MetaIndex<>(IllagerWatcher.class, 0, (byte) 0);
public static MetaIndex<Byte> ILLAGER_SPELL_TICKS = new MetaIndex<>(IllagerWizardWatcher.class, 0, (byte) 0);
public static MetaIndex<Byte> INSENTIENT_META = new MetaIndex<>(InsentientWatcher.class, 0, (byte) 0);
public static MetaIndex<Byte> IRON_GOLEM_PLAYER_CREATED = new MetaIndex<>(IronGolemWatcher.class, 0, (byte) 0);
public static MetaIndex<ItemStack> ITEMFRAME_ITEM = new MetaIndex<>(ItemFrameWatcher.class, 0,
new ItemStack(Material.AIR));
public static MetaIndex<Integer> ITEMFRAME_ROTATION = new MetaIndex<>(ItemFrameWatcher.class, 1, 0);
public static MetaIndex<Integer> LIVING_ARROWS = new MetaIndex<>(LivingWatcher.class, 4, 0);
public static MetaIndex<Byte> LIVING_HAND = new MetaIndex<>(LivingWatcher.class, 0, (byte) 0);
public static MetaIndex<Float> LIVING_HEALTH = new MetaIndex<>(LivingWatcher.class, 1, 1F);
public static MetaIndex<Boolean> LIVING_POTION_AMBIENT = new MetaIndex<>(LivingWatcher.class, 3, false);
public static MetaIndex<Integer> LIVING_POTIONS = new MetaIndex<>(LivingWatcher.class, 2, 0);
public static MetaIndex<Integer> LLAMA_CARPET = new MetaIndex<>(LlamaWatcher.class, 1, -1);
public static MetaIndex<Integer> LLAMA_COLOR = new MetaIndex<>(LlamaWatcher.class, 2, 0);
public static MetaIndex<Integer> LLAMA_STRENGTH = new MetaIndex<>(LlamaWatcher.class, 0, 0);
public static MetaIndex<Integer> MINECART_BLOCK = new MetaIndex<>(MinecartWatcher.class, 3, 0);
public static MetaIndex<Boolean> MINECART_BLOCK_VISIBLE = new MetaIndex<>(MinecartWatcher.class, 5, false);
public static MetaIndex<Integer> MINECART_BLOCK_Y = new MetaIndex<>(MinecartWatcher.class, 4, 6);
public static MetaIndex<Integer> MINECART_SHAKING_DIRECTION = new MetaIndex<>(MinecartWatcher.class, 1, 1);
public static MetaIndex<Float> MINECART_SHAKING_MULITPLIER = new MetaIndex<>(MinecartWatcher.class, 2, 0F);
public static MetaIndex<Integer> MINECART_SHAKING_POWER = new MetaIndex<>(MinecartWatcher.class, 0, 0);
public static MetaIndex<String> MINECART_COMMAND_STRING = new MetaIndex<>(MinecartCommandWatcher.class, 0, "");
public static MetaIndex<WrappedChatComponent> MINECART_COMMAND_LAST_OUTPUT = new MetaIndex<>(
MinecartCommandWatcher.class, 1, WrappedChatComponent.fromText(""));
public static MetaIndex<Boolean> MINECART_FURANCE_FUELED = new MetaIndex<>(MinecartFurnaceWatcher.class, 0, false);
public static MetaIndex<Integer> OCELOT_TYPE = new MetaIndex<>(OcelotWatcher.class, 0, 0);
public static MetaIndex<Integer> PARROT_VARIANT = new MetaIndex<>(ParrotWatcher.class, 0, 0);
public static MetaIndex<Integer> PHANTOM_SIZE = new MetaIndex<>(PhantomWatcher.class, 0, 0);
public static MetaIndex<Boolean> PIG_SADDLED = new MetaIndex<>(PigWatcher.class, 0, false);
public static MetaIndex<Integer> PIG_BOOST = new MetaIndex<>(PigWatcher.class, 1, 0);
public static MetaIndex<Float> PLAYER_ABSORPTION = new MetaIndex<>(PlayerWatcher.class, 0, 0F);
public static MetaIndex<Byte> PLAYER_HAND = new MetaIndex<>(PlayerWatcher.class, 3, (byte) 0);
public static MetaIndex<Integer> PLAYER_SCORE = new MetaIndex<>(PlayerWatcher.class, 1, 0);
public static MetaIndex<Byte> PLAYER_SKIN = new MetaIndex<>(PlayerWatcher.class, 2, (byte) 127);
public static MetaIndex<NbtBase> PLAYER_LEFT_SHOULDER_ENTITY = new MetaIndex<>(PlayerWatcher.class, 4,
NbtFactory.ofWrapper(NbtType.TAG_COMPOUND, "None"));
public static MetaIndex<NbtBase> PLAYER_RIGHT_SHOULDER_ENTITY = new MetaIndex<>(PlayerWatcher.class, 5,
NbtFactory.ofWrapper(NbtType.TAG_COMPOUND, "None"));
public static MetaIndex<Boolean> POLAR_BEAR_STANDING = new MetaIndex<>(PolarBearWatcher.class, 0, false);
public static MetaIndex<Integer> PUFFERFISH_PUFF_STATE = new MetaIndex<>(PufferFishWatcher.class, 0, 0);
public static MetaIndex<Integer> RABBIT_TYPE = new MetaIndex<>(RabbitWatcher.class, 0, 0);
public static MetaIndex<Byte> SHEEP_WOOL = new MetaIndex<>(SheepWatcher.class, 0, (byte) 0);
public static MetaIndex<Optional<BlockPosition>> SHULKER_ATTACHED = new MetaIndex<>(ShulkerWatcher.class, 1,
Optional.empty());
public static MetaIndex<Byte> SHULKER_COLOR = new MetaIndex<>(ShulkerWatcher.class, 3, (byte) 16);
public static MetaIndex<Direction> SHULKER_FACING = new MetaIndex<>(ShulkerWatcher.class, 0, Direction.DOWN);
public static MetaIndex<Byte> SHULKER_PEEKING = new MetaIndex<>(ShulkerWatcher.class, 2, (byte) 0);
public static MetaIndex<Boolean> SKELETON_SWING_ARMS = new MetaIndex<>(SkeletonWatcher.class, 0, false);
public static MetaIndex<Integer> SLIME_SIZE = new MetaIndex<>(SlimeWatcher.class, 0, 1);
public static MetaIndex<Byte> SNOWMAN_DERP = new MetaIndex<>(SnowmanWatcher.class, 0, (byte) 16);
public static MetaIndex<Byte> SPIDER_CLIMB = new MetaIndex<>(SpiderWatcher.class, 0, (byte) 0);
public static MetaIndex<ItemStack> SPLASH_POTION_ITEM = new MetaIndex<>(SplashPotionWatcher.class, 0,
new ItemStack(Material.SPLASH_POTION));
public static MetaIndex<Byte> TAMEABLE_META = new MetaIndex<>(TameableWatcher.class, 0, (byte) 0);
public static MetaIndex<Optional<UUID>> TAMEABLE_OWNER = new MetaIndex<>(TameableWatcher.class, 1,
Optional.empty());
public static MetaIndex<Integer> TIPPED_ARROW_COLOR = new MetaIndex<>(TippedArrowWatcher.class, 0, -1);
public static MetaIndex<Integer> TNT_FUSE_TICKS = new MetaIndex<>(TNTWatcher.class, 0, Integer.MAX_VALUE);
public static MetaIndex<Byte> TRIDENT_ENCHANTS = new MetaIndex<>(TridentWatcher.class, 0, (byte) 0);
public static MetaIndex<Integer> TROPICAL_FISH_VARIANT = new MetaIndex<>(TropicalFishWatcher.class, 0, 0);
public static MetaIndex<BlockPosition> TURTLE_HOME_POSITION = new MetaIndex<>(TurtleWatcher.class, 0,
BlockPosition.ORIGIN);
public static MetaIndex<Boolean> TURTLE_HAS_EGG = new MetaIndex<>(TurtleWatcher.class, 1, false);
public static MetaIndex<Boolean> TURTLE_UNKNOWN_3 = new MetaIndex<>(TurtleWatcher.class, 2, false);
public static MetaIndex<BlockPosition> TURTLE_TRAVEL_POSITION = new MetaIndex<>(TurtleWatcher.class, 3,
BlockPosition.ORIGIN);
public static MetaIndex<Boolean> TURTLE_UNKNOWN_1 = new MetaIndex<>(TurtleWatcher.class, 4, false);
public static MetaIndex<Boolean> TURTLE_UNKNOWN_2 = new MetaIndex<>(TurtleWatcher.class, 5, false);
public static MetaIndex<Byte> VEX_ANGRY = new MetaIndex<>(VexWatcher.class, 0, (byte) 0);
public static MetaIndex<Integer> VILLAGER_PROFESSION = new MetaIndex<>(VillagerWatcher.class, 0, 0);
public static MetaIndex<Boolean> WITCH_AGGRESSIVE = new MetaIndex<>(WitchWatcher.class, 0, false);
public static MetaIndex<Integer> WITHER_INVUL = new MetaIndex<>(WitherWatcher.class, 3, 0);
public static MetaIndex<Integer> WITHER_TARGET_1 = new MetaIndex<>(WitherWatcher.class, 0, 0);
public static MetaIndex<Integer> WITHER_TARGET_2 = new MetaIndex<>(WitherWatcher.class, 1, 0);
public static MetaIndex<Integer> WITHER_TARGET_3 = new MetaIndex<>(WitherWatcher.class, 2, 0);
public static MetaIndex<Boolean> WITHER_SKULL_BLUE = new MetaIndex<>(WitherSkullWatcher.class, 0, false);
public static MetaIndex<Boolean> WOLF_BEGGING = new MetaIndex<>(WolfWatcher.class, 1, false);
public static MetaIndex<Integer> WOLF_COLLAR = new MetaIndex<>(WolfWatcher.class, 2, 14);
public static MetaIndex<Float> WOLF_DAMAGE = new MetaIndex<>(WolfWatcher.class, 0, 1F);
public static MetaIndex<Boolean> ZOMBIE_AGGRESSIVE = new MetaIndex<>(ZombieWatcher.class, 2, false);
public static MetaIndex<Boolean> ZOMBIE_BABY = new MetaIndex<>(ZombieWatcher.class, 0, false);
public static MetaIndex<Boolean> ZOMBIE_CONVERTING_DROWNED = new MetaIndex<>(ZombieWatcher.class, 3, false);
public static MetaIndex<Integer> ZOMBIE_PLACEHOLDER = new MetaIndex<>(ZombieWatcher.class, 1, 0);
public static MetaIndex<Integer> ZOMBIE_VILLAGER_PROFESSION = new MetaIndex<>(ZombieVillagerWatcher.class, 1, 0);
public static MetaIndex<Boolean> ZOMBIE_VILLAGER_SHAKING = new MetaIndex<>(ZombieVillagerWatcher.class, 0, false);
static {
setValues();
orderMetaIndexes();
}
@Deprecated
private static void eliminateBlankIndexes() {
ArrayList<Entry<Class, ArrayList<MetaIndex>>> list = new ArrayList<>();
for (MetaIndex index : values()) {
Entry<Class, ArrayList<MetaIndex>> entry = null;
for (Entry e : list) {
if (e.getKey() != index.getFlagWatcher())
continue;
entry = e;
break;
}
if (entry == null) {
entry = new AbstractMap.SimpleEntry(index.getFlagWatcher(), new ArrayList<MetaIndex>());
list.add(entry);
}
entry.getValue().add(index);
}
for (Entry<Class, ArrayList<MetaIndex>> entry : list) {
entry.getValue().sort(Comparator.comparingInt(MetaIndex::getIndex));
for (MetaIndex ind : entry.getValue()) {
ind._index = entry.getValue().indexOf(ind);
}
}
}
private static void orderMetaIndexes() {
for (MetaIndex flagType : values()) {
if (flagType.getFlagWatcher() == FlagWatcher.class)
continue;
flagType._index += getNoIndexes(flagType.getFlagWatcher().getSuperclass());
}
}
public static void validateMetadata() {
// Simple verification for the dev that he's setting up the FlagType's properly.
// All flag types should be from 0 to <Max Number> with no empty numbers.
// All flag types should never occur twice.
HashMap<Class, Integer> maxValues = new HashMap<>();
for (MetaIndex type : values()) {
if (maxValues.containsKey(type.getFlagWatcher()) && maxValues.get(type.getFlagWatcher()) > type.getIndex())
continue;
maxValues.put(type.getFlagWatcher(), type.getIndex());
}
for (Entry<Class, Integer> entry : maxValues.entrySet()) {
loop:
for (int i = 0; i < entry.getValue(); i++) {
MetaIndex found = null;
for (MetaIndex type : values()) {
if (type.getIndex() != i)
continue;
if (!type.getFlagWatcher().isAssignableFrom(entry.getKey()))
continue;
if (found != null) {
DisguiseUtilities.getLogger().severe(entry.getKey().getSimpleName() +
" has multiple FlagType's registered for the index " + i + " (" +
type.getFlagWatcher().getSimpleName() + ", " + found.getFlagWatcher().getSimpleName() +
")");
continue loop;
}
found = type;
}
if (found != null)
continue;
DisguiseUtilities.getLogger()
.severe(entry.getKey().getSimpleName() + " has no FlagType registered for the index " + i);
}
}
}
@Deprecated
public static void printMetadata() {
ArrayList<String> toPrint = new ArrayList<>();
try {
for (Field field : MetaIndex.class.getFields()) {
if (field.getType() != MetaIndex.class)
continue;
MetaIndex index = (MetaIndex) field.get(null);
toPrint.add(
index.getFlagWatcher().getSimpleName() + " " + field.getName() + " " + index.getIndex() + " " +
index.getDefault().getClass().getSimpleName());
}
}
catch (Exception ex) {
ex.printStackTrace();
}
toPrint.sort(String.CASE_INSENSITIVE_ORDER);
for (String s : toPrint) {
DisguiseUtilities.getLogger().info(s);
}
}
public static MetaIndex getFlag(Class<? extends FlagWatcher> watcherClass, int flagNo) {
for (MetaIndex type : values()) {
if (type.getIndex() != flagNo)
continue;
if (!type.getFlagWatcher().isAssignableFrom(watcherClass))
continue;
return type;
}
return null;
}
public static ArrayList<MetaIndex> getFlags(Class<? extends FlagWatcher> watcherClass) {
ArrayList<MetaIndex> list = new ArrayList<>();
for (MetaIndex type : values()) {
if (type == null || !type.getFlagWatcher().isAssignableFrom(watcherClass))
continue;
list.add(type);
}
list.sort(Comparator.comparingInt(MetaIndex::getIndex));
return list;
}
private static int getNoIndexes(Class c) {
int found = 0;
for (MetaIndex type : values()) {
if (type.getFlagWatcher() != c)
continue;
found++;
}
if (c != FlagWatcher.class) {
found += getNoIndexes(c.getSuperclass());
}
return found;
}
public static MetaIndex[] values() {
return _values;
}
@Deprecated
public static String getName(MetaIndex metaIndex) {
try {
for (Field field : MetaIndex.class.getFields()) {
if (field.get(null) != metaIndex) {
continue;
}
return field.getName();
}
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static void addMetaIndexes(MetaIndex... metaIndexes) {
_values = Arrays.copyOf(values(), values().length + metaIndexes.length);
for (int i = values().length - metaIndexes.length, a = 0; i < values().length; i++, a++) {
MetaIndex index = metaIndexes[a];
ArrayList<MetaIndex> list = getFlags(index.getFlagWatcher());
for (int b = index.getIndex(); b < list.size(); b++) {
list.get(b)._index++;
}
for (MetaIndex metaIndex : values()) {
if (metaIndex == null || metaIndex.getFlagWatcher() != index.getFlagWatcher() ||
metaIndex.getIndex() != index.getIndex()) {
continue;
}
DisguiseUtilities.getLogger()
.severe("MetaIndex " + metaIndex.getFlagWatcher().getSimpleName() + " at index " +
metaIndex.getIndex() + " has already registered this! (" + metaIndex.getDefault() +
"," + index.getDefault() + ")");
}
values()[i] = metaIndexes[a];
}
}
public static void setValues() {
try {
_values = new MetaIndex[0];
for (Field field : MetaIndex.class.getFields()) {
if (field.getType() != MetaIndex.class)
continue;
MetaIndex index = (MetaIndex) field.get(null);
if (index == null)
continue;
_values = Arrays.copyOf(_values, _values.length + 1);
_values[_values.length - 1] = index;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns true if success, false if the field doesn't exist
*/
public static boolean setMetaIndex(String name, MetaIndex metaIndex) {
try {
Field field = MetaIndex.class.getField(name);
MetaIndex index = (MetaIndex) field.get(null);
field.set(null, metaIndex);
}
catch (NoSuchFieldException ex) {
return false;
}
catch (Exception ex) {
ex.printStackTrace();
}
return true;
}
private Y _defaultValue;
private int _index;
private Class<? extends FlagWatcher> _watcher;
public MetaIndex(Class<? extends FlagWatcher> watcher, int index, Y defaultValue) {
_index = index;
_watcher = watcher;
_defaultValue = defaultValue;
}
public Y getDefault() {
return _defaultValue;
}
public Class<? extends FlagWatcher> getFlagWatcher() {
return _watcher;
}
public int getIndex() {
return _index;
}
}

View File

@@ -0,0 +1,220 @@
package me.libraryaddict.disguise.disguisetypes;
import me.libraryaddict.disguise.disguisetypes.watchers.DroppedItemWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.FallingBlockWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.PaintingWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.SplashPotionWatcher;
import org.bukkit.Art;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.security.InvalidParameterException;
public class MiscDisguise extends TargetedDisguise {
private int id = -1, data = 0;
public MiscDisguise(DisguiseType disguiseType) {
this(disguiseType, -1, disguiseType.getDefaultData());
}
public MiscDisguise(Material material, int data) {
super(DisguiseType.DROPPED_ITEM);
apply(0, 0, new ItemStack(material, 1, (short) data));
}
public MiscDisguise(ItemStack itemStack) {
super(DisguiseType.DROPPED_ITEM);
apply(0, 0, itemStack);
}
public MiscDisguise(DisguiseType disguiseType, int id) {
this(disguiseType, id, disguiseType.getDefaultData());
}
public MiscDisguise(DisguiseType disguiseType, int id, int data) {
super(disguiseType);
if (!disguiseType.isMisc()) {
throw new InvalidParameterException(
"Expected a non-living DisguiseType while constructing MiscDisguise. Received " + disguiseType +
" instead. Please use " + (disguiseType.isPlayer() ? "PlayerDisguise" : "MobDisguise") +
" instead");
}
apply(id, data, new ItemStack(Material.STONE));
}
private void apply(int id, int data, ItemStack itemStack) {
createDisguise();
this.id = getType().getTypeId();
this.data = getType().getDefaultData();
switch (getType()) {
// The only disguises which should use a custom data.
case PAINTING:
((PaintingWatcher) getWatcher()).setArt(Art.values()[Math.max(0, id) % Art.values().length]);
break;
case FALLING_BLOCK:
((FallingBlockWatcher) getWatcher()).setBlock(itemStack);
break;
case SPLASH_POTION:
((SplashPotionWatcher) getWatcher()).setPotionId(Math.max(0, id));
break;
case DROPPED_ITEM:
((DroppedItemWatcher) getWatcher()).setItemStack(itemStack);
break;
case FISHING_HOOK: // Entity ID of whoever is holding fishing rod
case ARROW: // Entity ID of shooter. Used for "Is he on this scoreboard team and do I render it moving
// through his body?"
case TIPPED_ARROW:
case SPECTRAL_ARROW:
case SMALL_FIREBALL: // Unknown. Uses entity id of shooter. 0 if no shooter
case FIREBALL: // Unknown. Uses entity id of shooter. 0 if no shooter
case WITHER_SKULL: // Unknown. Uses entity id of shooter. 0 if no shooter
case TRIDENT: // Unknown. Uses 1 + (entityId of target, or shooter)
this.data = id;
break;
default:
break;
}
}
@Override
public MiscDisguise addPlayer(Player player) {
return (MiscDisguise) super.addPlayer(player);
}
@Override
public MiscDisguise addPlayer(String playername) {
return (MiscDisguise) super.addPlayer(playername);
}
@Override
public MiscDisguise clone() {
MiscDisguise disguise = new MiscDisguise(getType(), getData());
disguise.setReplaceSounds(isSoundsReplaced());
disguise.setViewSelfDisguise(isSelfDisguiseVisible());
disguise.setHearSelfDisguise(isSelfDisguiseSoundsReplaced());
disguise.setHideArmorFromSelf(isHidingArmorFromSelf());
disguise.setHideHeldItemFromSelf(isHidingHeldItemFromSelf());
disguise.setVelocitySent(isVelocitySent());
disguise.setModifyBoundingBox(isModifyBoundingBox());
if (getWatcher() != null) {
disguise.setWatcher(getWatcher().clone(disguise));
}
return disguise;
}
/**
* This is the getId of everything but falling block.
*/
public int getData() {
switch (getType()) {
case FALLING_BLOCK:
return (int) ((FallingBlockWatcher) getWatcher()).getBlock().getDurability();
case PAINTING:
return ((PaintingWatcher) getWatcher()).getArt().getId();
case SPLASH_POTION:
return ((SplashPotionWatcher) getWatcher()).getPotionId();
default:
return data;
}
}
/**
* Only falling block should use this
*/
public int getId() {
if (getType() == DisguiseType.FALLING_BLOCK) {
return ((FallingBlockWatcher) getWatcher()).getBlock().getType().ordinal();
}
return id;
}
@Override
public boolean isMiscDisguise() {
return true;
}
@Override
public MiscDisguise removePlayer(Player player) {
return (MiscDisguise) super.removePlayer(player);
}
@Override
public MiscDisguise removePlayer(String playername) {
return (MiscDisguise) super.removePlayer(playername);
}
@Override
public MiscDisguise setDisguiseTarget(TargetType newTargetType) {
return (MiscDisguise) super.setDisguiseTarget(newTargetType);
}
@Override
public MiscDisguise setEntity(Entity entity) {
return (MiscDisguise) super.setEntity(entity);
}
@Override
public MiscDisguise setHearSelfDisguise(boolean hearSelfDisguise) {
return (MiscDisguise) super.setHearSelfDisguise(hearSelfDisguise);
}
@Override
public MiscDisguise setHideArmorFromSelf(boolean hideArmor) {
return (MiscDisguise) super.setHideArmorFromSelf(hideArmor);
}
@Override
public MiscDisguise setHideHeldItemFromSelf(boolean hideHeldItem) {
return (MiscDisguise) super.setHideHeldItemFromSelf(hideHeldItem);
}
@Override
public MiscDisguise setKeepDisguiseOnPlayerDeath(boolean keepDisguise) {
return (MiscDisguise) super.setKeepDisguiseOnPlayerDeath(keepDisguise);
}
@Override
public MiscDisguise setModifyBoundingBox(boolean modifyBox) {
return (MiscDisguise) super.setModifyBoundingBox(modifyBox);
}
@Override
public MiscDisguise setReplaceSounds(boolean areSoundsReplaced) {
return (MiscDisguise) super.setReplaceSounds(areSoundsReplaced);
}
@Override
public MiscDisguise setVelocitySent(boolean sendVelocity) {
return (MiscDisguise) super.setVelocitySent(sendVelocity);
}
@Override
public MiscDisguise setViewSelfDisguise(boolean viewSelfDisguise) {
return (MiscDisguise) super.setViewSelfDisguise(viewSelfDisguise);
}
@Override
public MiscDisguise setWatcher(FlagWatcher newWatcher) {
return (MiscDisguise) super.setWatcher(newWatcher);
}
@Override
public MiscDisguise silentlyAddPlayer(String playername) {
return (MiscDisguise) super.silentlyAddPlayer(playername);
}
@Override
public MiscDisguise silentlyRemovePlayer(String playername) {
return (MiscDisguise) super.silentlyRemovePlayer(playername);
}
}

View File

@@ -0,0 +1,160 @@
package me.libraryaddict.disguise.disguisetypes;
import java.security.InvalidParameterException;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import me.libraryaddict.disguise.disguisetypes.watchers.AgeableWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.ZombieWatcher;
public class MobDisguise extends TargetedDisguise {
private boolean isAdult;
public MobDisguise(DisguiseType disguiseType) {
this(disguiseType, true);
}
public MobDisguise(DisguiseType disguiseType, boolean isAdult) {
super(disguiseType);
if (!disguiseType.isMob()) {
throw new InvalidParameterException(
"Expected a living DisguiseType while constructing MobDisguise. Received " + disguiseType + " instead. Please use " + (
disguiseType.isPlayer() ? "PlayerDisguise" : "MiscDisguise") + " instead");
}
this.isAdult = isAdult;
createDisguise();
}
@Override
public MobDisguise addPlayer(Player player) {
return (MobDisguise) super.addPlayer(player);
}
@Override
public MobDisguise addPlayer(String playername) {
return (MobDisguise) super.addPlayer(playername);
}
@Override
public MobDisguise clone() {
MobDisguise disguise = new MobDisguise(getType(), isAdult());
disguise.setReplaceSounds(isSoundsReplaced());
disguise.setViewSelfDisguise(isSelfDisguiseVisible());
disguise.setHearSelfDisguise(isSelfDisguiseSoundsReplaced());
disguise.setHideArmorFromSelf(isHidingArmorFromSelf());
disguise.setHideHeldItemFromSelf(isHidingHeldItemFromSelf());
disguise.setVelocitySent(isVelocitySent());
disguise.setModifyBoundingBox(isModifyBoundingBox());
if (getWatcher() != null) {
disguise.setWatcher(getWatcher().clone(disguise));
}
return disguise;
}
public boolean doesDisguiseAge() {
return getWatcher() != null && (getWatcher() instanceof AgeableWatcher || getWatcher() instanceof ZombieWatcher);
}
@Override
public LivingWatcher getWatcher() {
return (LivingWatcher) super.getWatcher();
}
public boolean isAdult() {
if (getWatcher() != null) {
if (getWatcher() instanceof AgeableWatcher) {
return ((AgeableWatcher) getWatcher()).isAdult();
} else if (getWatcher() instanceof ZombieWatcher) {
return ((ZombieWatcher) getWatcher()).isAdult();
}
return true;
}
return isAdult;
}
@Override
public boolean isMobDisguise() {
return true;
}
@Override
public MobDisguise removePlayer(Player player) {
return (MobDisguise) super.removePlayer(player);
}
@Override
public MobDisguise removePlayer(String playername) {
return (MobDisguise) super.removePlayer(playername);
}
@Override
public MobDisguise setDisguiseTarget(TargetType newTargetType) {
return (MobDisguise) super.setDisguiseTarget(newTargetType);
}
@Override
public MobDisguise setEntity(Entity entity) {
return (MobDisguise) super.setEntity(entity);
}
@Override
public MobDisguise setHearSelfDisguise(boolean hearSelfDisguise) {
return (MobDisguise) super.setHearSelfDisguise(hearSelfDisguise);
}
@Override
public MobDisguise setHideArmorFromSelf(boolean hideArmor) {
return (MobDisguise) super.setHideArmorFromSelf(hideArmor);
}
@Override
public MobDisguise setHideHeldItemFromSelf(boolean hideHeldItem) {
return (MobDisguise) super.setHideHeldItemFromSelf(hideHeldItem);
}
@Override
public MobDisguise setKeepDisguiseOnPlayerDeath(boolean keepDisguise) {
return (MobDisguise) super.setKeepDisguiseOnPlayerDeath(keepDisguise);
}
@Override
public MobDisguise setModifyBoundingBox(boolean modifyBox) {
return (MobDisguise) super.setModifyBoundingBox(modifyBox);
}
@Override
public MobDisguise setReplaceSounds(boolean areSoundsReplaced) {
return (MobDisguise) super.setReplaceSounds(areSoundsReplaced);
}
@Override
public MobDisguise setVelocitySent(boolean sendVelocity) {
return (MobDisguise) super.setVelocitySent(sendVelocity);
}
@Override
public MobDisguise setViewSelfDisguise(boolean viewSelfDisguise) {
return (MobDisguise) super.setViewSelfDisguise(viewSelfDisguise);
}
@Override
public MobDisguise setWatcher(FlagWatcher newWatcher) {
return (MobDisguise) super.setWatcher(newWatcher);
}
@Override
public MobDisguise silentlyAddPlayer(String playername) {
return (MobDisguise) super.silentlyAddPlayer(playername);
}
@Override
public MobDisguise silentlyRemovePlayer(String playername) {
return (MobDisguise) super.silentlyRemovePlayer(playername);
}
}

View File

@@ -0,0 +1,356 @@
package me.libraryaddict.disguise.disguisetypes;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.EnumWrappers.NativeGameMode;
import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction;
import com.comphenix.protocol.wrappers.PlayerInfoData;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import me.libraryaddict.disguise.LibsDisguises;
import me.libraryaddict.disguise.disguisetypes.watchers.PlayerWatcher;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import me.libraryaddict.disguise.utilities.LibsProfileLookup;
import me.libraryaddict.disguise.utilities.ReflectionManager;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.UUID;
public class PlayerDisguise extends TargetedDisguise {
private transient LibsProfileLookup currentLookup;
private WrappedGameProfile gameProfile;
private String playerName;
private String skinToUse;
private UUID uuid = UUID.randomUUID();
private PlayerDisguise() {
super(DisguiseType.PLAYER);
}
public PlayerDisguise(Player player) {
this(ReflectionManager.getGameProfile(player));
}
public PlayerDisguise(Player player, Player skinToUse) {
this(ReflectionManager.getGameProfile(player), ReflectionManager.getGameProfile(skinToUse));
}
public PlayerDisguise(String name) {
this();
setName(name);
setSkin(name);
createDisguise();
}
public PlayerDisguise(String name, String skinToUse) {
this();
setName(name);
setSkin(skinToUse);
createDisguise();
}
public PlayerDisguise(WrappedGameProfile gameProfile) {
this();
setName(gameProfile.getName());
this.gameProfile = ReflectionManager.getGameProfileWithThisSkin(uuid, gameProfile.getName(), gameProfile);
createDisguise();
}
public PlayerDisguise(WrappedGameProfile gameProfile, WrappedGameProfile skinToUse) {
this();
setName(gameProfile.getName());
this.gameProfile = ReflectionManager.getGameProfile(uuid, gameProfile.getName());
setSkin(skinToUse);
createDisguise();
}
public UUID getUUID() {
return uuid;
}
@Override
public PlayerDisguise addPlayer(Player player) {
return (PlayerDisguise) super.addPlayer(player);
}
@Override
public PlayerDisguise addPlayer(String playername) {
return (PlayerDisguise) super.addPlayer(playername);
}
@Override
public PlayerDisguise clone() {
PlayerDisguise disguise = new PlayerDisguise();
disguise.playerName = getName();
if (currentLookup == null && gameProfile != null) {
disguise.skinToUse = getSkin();
disguise.gameProfile = ReflectionManager
.getGameProfileWithThisSkin(disguise.uuid, getGameProfile().getName(), getGameProfile());
} else {
disguise.setSkin(getSkin());
}
disguise.setReplaceSounds(isSoundsReplaced());
disguise.setViewSelfDisguise(isSelfDisguiseVisible());
disguise.setHearSelfDisguise(isSelfDisguiseSoundsReplaced());
disguise.setHideArmorFromSelf(isHidingArmorFromSelf());
disguise.setHideHeldItemFromSelf(isHidingHeldItemFromSelf());
disguise.setVelocitySent(isVelocitySent());
disguise.setModifyBoundingBox(isModifyBoundingBox());
if (getWatcher() != null) {
disguise.setWatcher(getWatcher().clone(disguise));
}
disguise.createDisguise();
return disguise;
}
public WrappedGameProfile getGameProfile() {
if (gameProfile == null) {
if (getSkin() != null) {
gameProfile = ReflectionManager.getGameProfile(uuid, getName());
} else {
gameProfile = ReflectionManager
.getGameProfileWithThisSkin(uuid, getName(), DisguiseUtilities.getProfileFromMojang(this));
}
}
return gameProfile;
}
public String getName() {
return playerName;
}
public String getSkin() {
return skinToUse;
}
@Override
public PlayerWatcher getWatcher() {
return (PlayerWatcher) super.getWatcher();
}
public boolean isDisplayedInTab() {
return getWatcher().isDisplayedInTab();
}
@Override
public boolean isPlayerDisguise() {
return true;
}
@Override
public PlayerDisguise removePlayer(Player player) {
return (PlayerDisguise) super.removePlayer(player);
}
@Override
public PlayerDisguise removePlayer(String playername) {
return (PlayerDisguise) super.removePlayer(playername);
}
@Override
public PlayerDisguise setDisguiseTarget(TargetType newTargetType) {
return (PlayerDisguise) super.setDisguiseTarget(newTargetType);
}
public void setDisplayedInTab(boolean showPlayerInTab) {
getWatcher().setDisplayedInTab(showPlayerInTab);
}
@Override
public PlayerDisguise setEntity(Entity entity) {
return (PlayerDisguise) super.setEntity(entity);
}
public void setGameProfile(WrappedGameProfile gameProfile) {
this.gameProfile = ReflectionManager.getGameProfileWithThisSkin(uuid, gameProfile.getName(), gameProfile);
}
@Override
public PlayerDisguise setHearSelfDisguise(boolean hearSelfDisguise) {
return (PlayerDisguise) super.setHearSelfDisguise(hearSelfDisguise);
}
@Override
public PlayerDisguise setHideArmorFromSelf(boolean hideArmor) {
return (PlayerDisguise) super.setHideArmorFromSelf(hideArmor);
}
@Override
public PlayerDisguise setHideHeldItemFromSelf(boolean hideHeldItem) {
return (PlayerDisguise) super.setHideHeldItemFromSelf(hideHeldItem);
}
@Override
public PlayerDisguise setKeepDisguiseOnPlayerDeath(boolean keepDisguise) {
return (PlayerDisguise) super.setKeepDisguiseOnPlayerDeath(keepDisguise);
}
@Override
public PlayerDisguise setModifyBoundingBox(boolean modifyBox) {
return (PlayerDisguise) super.setModifyBoundingBox(modifyBox);
}
private void setName(String name) {
if (name.length() > 16) {
name = name.substring(0, 16);
}
playerName = name;
}
@Override
public PlayerDisguise setReplaceSounds(boolean areSoundsReplaced) {
return (PlayerDisguise) super.setReplaceSounds(areSoundsReplaced);
}
@Override
public boolean startDisguise() {
if (!isDisguiseInUse() && skinToUse != null && gameProfile == null) {
currentLookup = new LibsProfileLookup() {
@Override
public void onLookup(WrappedGameProfile gameProfile) {
if (currentLookup != this || gameProfile == null)
return;
setSkin(gameProfile);
currentLookup = null;
}
};
WrappedGameProfile gameProfile = DisguiseUtilities.getProfileFromMojang(this.skinToUse, currentLookup,
LibsDisguises.getInstance().getConfig().getBoolean("ContactMojangServers", true));
if (gameProfile != null) {
setSkin(gameProfile);
}
}
return super.startDisguise();
}
public PlayerDisguise setSkin(String newSkin) {
if (newSkin != null && newSkin.length() > 50) {
try {
return setSkin(DisguiseUtilities.getGson().fromJson(newSkin, WrappedGameProfile.class));
}
catch (Exception ex) {
throw new IllegalArgumentException(String.format(
"The skin %s is too long to be a playername, but cannot be parsed to a GameProfile!", newSkin));
}
}
skinToUse = newSkin;
if (newSkin == null) {
currentLookup = null;
gameProfile = null;
} else {
if (newSkin.length() > 16) {
skinToUse = newSkin.substring(0, 16);
}
}
return this;
}
/**
* Set the GameProfile, without tampering.
*
* @param gameProfile GameProfile
* @return
*/
public PlayerDisguise setSkin(WrappedGameProfile gameProfile) {
if (gameProfile == null) {
this.gameProfile = null;
this.skinToUse = null;
return this;
}
Validate.notEmpty(gameProfile.getName(), "Name must be set");
currentLookup = null;
this.skinToUse = gameProfile.getName();
this.gameProfile = ReflectionManager.getGameProfileWithThisSkin(uuid, getName(), gameProfile);
if (DisguiseUtilities.isDisguiseInUse(this)) {
if (isDisplayedInTab()) {
PacketContainer addTab = new PacketContainer(PacketType.Play.Server.PLAYER_INFO);
addTab.getPlayerInfoAction().write(0, PlayerInfoAction.ADD_PLAYER);
addTab.getPlayerInfoDataLists().write(0, Arrays.asList(
new PlayerInfoData(getGameProfile(), 0, NativeGameMode.SURVIVAL,
WrappedChatComponent.fromText(getName()))));
PacketContainer deleteTab = addTab.shallowClone();
deleteTab.getPlayerInfoAction().write(0, PlayerInfoAction.REMOVE_PLAYER);
try {
for (Player player : Bukkit.getOnlinePlayers()) {
if (!canSee(player))
continue;
ProtocolLibrary.getProtocolManager().sendServerPacket(player, deleteTab);
ProtocolLibrary.getProtocolManager().sendServerPacket(player, addTab);
}
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
DisguiseUtilities.refreshTrackers(this);
}
return this;
}
@Override
public PlayerDisguise setVelocitySent(boolean sendVelocity) {
return (PlayerDisguise) super.setVelocitySent(sendVelocity);
}
@Override
public PlayerDisguise setViewSelfDisguise(boolean viewSelfDisguise) {
return (PlayerDisguise) super.setViewSelfDisguise(viewSelfDisguise);
}
@Override
public PlayerDisguise setWatcher(FlagWatcher newWatcher) {
return (PlayerDisguise) super.setWatcher(newWatcher);
}
@Override
public PlayerDisguise silentlyAddPlayer(String playername) {
return (PlayerDisguise) super.silentlyAddPlayer(playername);
}
@Override
public PlayerDisguise silentlyRemovePlayer(String playername) {
return (PlayerDisguise) super.silentlyRemovePlayer(playername);
}
}

View File

@@ -0,0 +1,25 @@
package me.libraryaddict.disguise.disguisetypes;
public enum RabbitType {
BLACK(2), BROWN(0), GOLD(4), KILLER_BUNNY(99), PATCHES(3), PEPPER(5), WHITE(1);
public static RabbitType getType(int id) {
for (RabbitType type : values()) {
if (type.getTypeId() == id) {
return type;
}
}
return null;
}
private int type;
private RabbitType(int type) {
this.type = type;
}
public int getTypeId() {
return type;
}
}

View File

@@ -0,0 +1,165 @@
package me.libraryaddict.disguise.disguisetypes;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.EnumWrappers.NativeGameMode;
import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction;
import com.comphenix.protocol.wrappers.PlayerInfoData;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import me.libraryaddict.disguise.utilities.ReflectionManager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public abstract class TargetedDisguise extends Disguise {
public TargetedDisguise(DisguiseType disguiseType) {
super(disguiseType);
}
public enum TargetType {
HIDE_DISGUISE_TO_EVERYONE_BUT_THESE_PLAYERS,
SHOW_TO_EVERYONE_BUT_THESE_PLAYERS
}
private ArrayList<String> disguiseViewers = new ArrayList<>();
private TargetType targetType = TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS;
public TargetedDisguise addPlayer(Player player) {
addPlayer(player.getName());
return this;
}
public TargetedDisguise addPlayer(String playername) {
if (!disguiseViewers.contains(playername)) {
disguiseViewers.add(playername);
if (DisguiseAPI.isDisguiseInUse(this)) {
DisguiseUtilities.checkConflicts(this, playername);
DisguiseUtilities.refreshTracker(this, playername);
if (isHidePlayer() && getEntity() instanceof Player) {
try {
Player player = Bukkit.getPlayerExact(playername);
if (player != null) {
PacketContainer deleteTab = new PacketContainer(PacketType.Play.Server.PLAYER_INFO);
deleteTab.getPlayerInfoAction().write(0,
canSee(player) ? PlayerInfoAction.REMOVE_PLAYER : PlayerInfoAction.ADD_PLAYER);
deleteTab.getPlayerInfoDataLists().write(0, Arrays.asList(
new PlayerInfoData(ReflectionManager.getGameProfile((Player) getEntity()), 0,
NativeGameMode.SURVIVAL, WrappedChatComponent
.fromText(DisguiseUtilities.getPlayerListName((Player) getEntity())))));
ProtocolLibrary.getProtocolManager().sendServerPacket(player, deleteTab);
}
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
return this;
}
public boolean canSee(Player player) {
return canSee(player.getName());
}
public boolean canSee(String playername) {
boolean hasPlayer = disguiseViewers.contains(playername);
if (targetType == TargetType.SHOW_TO_EVERYONE_BUT_THESE_PLAYERS) {
return !hasPlayer;
}
return hasPlayer;
}
public TargetType getDisguiseTarget() {
return targetType;
}
public List<String> getObservers() {
return Collections.unmodifiableList(disguiseViewers);
}
public TargetedDisguise removePlayer(Player player) {
removePlayer(player.getName());
return this;
}
public TargetedDisguise removePlayer(String playername) {
if (disguiseViewers.contains(playername)) {
disguiseViewers.remove(playername);
if (DisguiseAPI.isDisguiseInUse(this)) {
DisguiseUtilities.checkConflicts(this, playername);
DisguiseUtilities.refreshTracker(this, playername);
if (isHidePlayer() && getEntity() instanceof Player) {
try {
Player player = Bukkit.getPlayerExact(playername);
if (player != null) {
PacketContainer deleteTab = new PacketContainer(PacketType.Play.Server.PLAYER_INFO);
deleteTab.getPlayerInfoAction().write(0,
canSee(player) ? PlayerInfoAction.ADD_PLAYER : PlayerInfoAction.REMOVE_PLAYER);
deleteTab.getPlayerInfoDataLists().write(0, Arrays.asList(
new PlayerInfoData(ReflectionManager.getGameProfile((Player) getEntity()), 0,
NativeGameMode.SURVIVAL, WrappedChatComponent
.fromText(DisguiseUtilities.getPlayerListName((Player) getEntity())))));
ProtocolLibrary.getProtocolManager().sendServerPacket(player, deleteTab);
}
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
return this;
}
public TargetedDisguise setDisguiseTarget(TargetType newTargetType) {
if (DisguiseUtilities.isDisguiseInUse(this)) {
throw new RuntimeException("Cannot set the disguise target after the entity has been disguised");
}
targetType = newTargetType;
return this;
}
public TargetedDisguise silentlyAddPlayer(String playername) {
if (!disguiseViewers.contains(playername)) {
disguiseViewers.add(playername);
}
return this;
}
public TargetedDisguise silentlyRemovePlayer(String playername) {
if (disguiseViewers.contains(playername)) {
disguiseViewers.remove(playername);
}
return this;
}
}

View File

@@ -0,0 +1,100 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import java.util.Optional;
import java.util.UUID;
public abstract class AbstractHorseWatcher extends AgeableWatcher {
public AbstractHorseWatcher(Disguise disguise) {
super(disguise);
}
public Optional<UUID> getOwner() {
return getData(MetaIndex.HORSE_OWNER);
}
public boolean hasChest() {
return isHorseFlag(8);
}
public boolean isBreedable() {
return isHorseFlag(16);
}
public boolean isGrazing() {
return isHorseFlag(32);
}
public boolean isMouthOpen() {
return isHorseFlag(128);
}
public boolean isRearing() {
return isHorseFlag(64);
}
public boolean isSaddled() {
return isHorseFlag(4);
}
public boolean isTamed() {
return isHorseFlag(2);
}
private boolean isHorseFlag(int i) {
return (getHorseFlag() & i) != 0;
}
private byte getHorseFlag() {
return getData(MetaIndex.HORSE_META);
}
public void setCanBreed(boolean breed) {
setHorseFlag(16, breed);
}
public void setCarryingChest(boolean chest) {
setHorseFlag(8, chest);
}
private void setHorseFlag(int i, boolean flag) {
byte j = getData(MetaIndex.HORSE_META);
if (flag) {
setData(MetaIndex.HORSE_META, (byte) (j | i));
}
else {
setData(MetaIndex.HORSE_META, (byte) (j & ~i));
}
sendData(MetaIndex.HORSE_META);
}
public void setGrazing(boolean grazing) {
setHorseFlag(32, grazing);
}
public void setMouthOpen(boolean mouthOpen) {
setHorseFlag(128, mouthOpen);
}
public void setOwner(UUID uuid) {
setData(MetaIndex.HORSE_OWNER, Optional.of(uuid));
sendData(MetaIndex.HORSE_OWNER);
}
public void setRearing(boolean rear) {
setHorseFlag(64, rear);
}
public void setSaddled(boolean saddled) {
setHorseFlag(4, saddled);
}
public void setTamed(boolean tamed) {
setHorseFlag(2, tamed);
}
}

View File

@@ -0,0 +1,38 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class AgeableWatcher extends InsentientWatcher
{
public AgeableWatcher(Disguise disguise)
{
super(disguise);
}
public boolean isAdult()
{
return !isBaby();
}
public boolean isBaby()
{
return getData(MetaIndex.AGEABLE_BABY);
}
public void setAdult()
{
setBaby(false);
}
public void setBaby()
{
setBaby(true);
}
public void setBaby(boolean isBaby)
{
setData(MetaIndex.AGEABLE_BABY, isBaby);
sendData(MetaIndex.AGEABLE_BABY);
}
}

View File

@@ -0,0 +1,60 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import org.apache.commons.lang.math.RandomUtils;
import org.bukkit.Color;
import org.bukkit.Particle;
/**
* @author Navid
*/
public class AreaEffectCloudWatcher extends FlagWatcher {
public AreaEffectCloudWatcher(Disguise disguise) {
super(disguise);
setColor(Color.fromRGB(RandomUtils.nextInt(256), RandomUtils.nextInt(256), RandomUtils.nextInt(256)));
}
public float getRadius() {
return getData(MetaIndex.AREA_EFFECT_RADIUS);
}
public void setRadius(float radius) {
if (radius > 30)
radius = 30;
setData(MetaIndex.AREA_EFFECT_RADIUS, radius);
sendData(MetaIndex.AREA_EFFECT_RADIUS);
}
public Color getColor() {
int color = getData(MetaIndex.AREA_EFFECT_CLOUD_COLOR);
return Color.fromRGB(color);
}
public void setColor(Color color) {
setData(MetaIndex.AREA_EFFECT_CLOUD_COLOR, color.asRGB());
sendData(MetaIndex.AREA_EFFECT_CLOUD_COLOR);
}
public boolean isIgnoreRadius() {
return getData(MetaIndex.AREA_EFFECT_IGNORE_RADIUS);
}
public void setIgnoreRadius(boolean ignore) {
setData(MetaIndex.AREA_EFFECT_IGNORE_RADIUS, ignore);
sendData(MetaIndex.AREA_EFFECT_IGNORE_RADIUS);
}
public void setParticleType(Particle particle) {
setData(MetaIndex.AREA_EFFECT_PARTICLE, particle);
sendData(MetaIndex.AREA_EFFECT_PARTICLE);
}
public Particle getParticleType() {
return getData(MetaIndex.AREA_EFFECT_PARTICLE);
}
}

View File

@@ -0,0 +1,170 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.util.EulerAngle;
import com.comphenix.protocol.wrappers.Vector3F;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class ArmorStandWatcher extends LivingWatcher
{
public ArmorStandWatcher(Disguise disguise)
{
super(disguise);
}
private boolean getArmorStandFlag(int value)
{
return (getData(MetaIndex.ARMORSTAND_META) & value) != 0;
}
public EulerAngle getBody()
{
return getPose(MetaIndex.ARMORSTAND_BODY);
}
public EulerAngle getHead()
{
return getPose(MetaIndex.ARMORSTAND_HEAD);
}
public EulerAngle getLeftArm()
{
return getPose(MetaIndex.ARMORSTAND_LEFT_ARM);
}
public EulerAngle getLeftLeg()
{
return getPose(MetaIndex.ARMORSTAND_LEFT_LEG);
}
private EulerAngle getPose(MetaIndex<Vector3F> type)
{
if (!hasValue(type))
return new EulerAngle(0, 0, 0);
Vector3F vec = getData(type);
return new EulerAngle(vec.getX(), vec.getY(), vec.getZ());
}
public EulerAngle getRightArm()
{
return getPose(MetaIndex.ARMORSTAND_RIGHT_ARM);
}
public EulerAngle getRightLeg()
{
return getPose(MetaIndex.ARMORSTAND_RIGHT_LEG);
}
public boolean isMarker()
{
return getArmorStandFlag(10);
}
public boolean isNoBasePlate()
{
return getArmorStandFlag(8);
}
public boolean isNoGravity()
{
return getArmorStandFlag(2);
}
public boolean isShowArms()
{
return getArmorStandFlag(4);
}
public boolean isSmall()
{
return getArmorStandFlag(1);
}
private void setArmorStandFlag(int value, boolean isTrue)
{
byte b1 = (byte) getData(MetaIndex.ARMORSTAND_META);
if (isTrue)
{
b1 = (byte) (b1 | value);
}
else
{
b1 = (byte) (b1 & value);
}
setData(MetaIndex.ARMORSTAND_META, b1);
sendData(MetaIndex.ARMORSTAND_META);
}
public void setBody(EulerAngle vector)
{
setPose(MetaIndex.ARMORSTAND_BODY, vector);
}
public void setHead(EulerAngle vector)
{
setPose(MetaIndex.ARMORSTAND_HEAD, vector);
}
public void setLeftArm(EulerAngle vector)
{
setPose(MetaIndex.ARMORSTAND_LEFT_ARM, vector);
}
public void setLeftLeg(EulerAngle vector)
{
setPose(MetaIndex.ARMORSTAND_LEFT_LEG, vector);
}
public void setMarker(boolean isMarker)
{
setArmorStandFlag(10, isMarker);
sendData(MetaIndex.ARMORSTAND_META);
}
public void setNoBasePlate(boolean noBasePlate)
{
setArmorStandFlag(8, noBasePlate);
sendData(MetaIndex.ARMORSTAND_META);
}
public void setNoGravity(boolean noGravity)
{
setArmorStandFlag(2, noGravity);
sendData(MetaIndex.ARMORSTAND_META);
}
private void setPose(MetaIndex<Vector3F> type, EulerAngle vector)
{
setData(type, new Vector3F((float) vector.getX(), (float) vector.getY(), (float) vector.getZ()));
sendData(type);
}
public void setRightArm(EulerAngle vector)
{
setPose(MetaIndex.ARMORSTAND_RIGHT_ARM, vector);
}
public void setRightLeg(EulerAngle vector)
{
setPose(MetaIndex.ARMORSTAND_RIGHT_LEG, vector);
}
public void setShowArms(boolean showArms)
{
setArmorStandFlag(4, showArms);
sendData(MetaIndex.ARMORSTAND_META);
}
public void setSmall(boolean isSmall)
{
setArmorStandFlag(1, isSmall);
sendData(MetaIndex.ARMORSTAND_META);
}
}

View File

@@ -0,0 +1,20 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class ArrowWatcher extends FlagWatcher {
public ArrowWatcher(Disguise disguise) {
super(disguise);
}
public boolean isCritical() {
return getData(MetaIndex.ARROW_CRITICAL) == 1;
}
public void setCritical(boolean critical) {
setData(MetaIndex.ARROW_CRITICAL, (byte) (critical ? 1 : 0));
sendData(MetaIndex.ARROW_CRITICAL);
}
}

View File

@@ -0,0 +1,26 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class BatWatcher extends InsentientWatcher
{
public BatWatcher(Disguise disguise)
{
super(disguise);
setHanging(false);
}
public boolean isHanging()
{
return ((byte) getData(MetaIndex.BAT_HANGING)) == 1;
}
public void setHanging(boolean hanging)
{
setData(MetaIndex.BAT_HANGING, hanging ? (byte) 1 : (byte) 0);
sendData(MetaIndex.BAT_HANGING);
}
}

View File

@@ -0,0 +1,24 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class BlazeWatcher extends InsentientWatcher
{
public BlazeWatcher(Disguise disguise)
{
super(disguise);
}
public boolean isBlazing()
{
return getData(MetaIndex.BLAZE_BLAZING) == 1;
}
public void setBlazing(boolean isBlazing)
{
setData(MetaIndex.BLAZE_BLAZING, (byte) (isBlazing ? 1 : 0));
sendData(MetaIndex.BLAZE_BLAZING);
}
}

View File

@@ -0,0 +1,59 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import org.bukkit.TreeSpecies;
public class BoatWatcher extends FlagWatcher {
public BoatWatcher(Disguise disguise) {
super(disguise);
setBoatType(TreeSpecies.GENERIC);
}
public float getDamage() {
return getData(MetaIndex.BOAT_DAMAGE);
}
public void setDamage(float dmg) {
setData(MetaIndex.BOAT_DAMAGE, dmg);
sendData(MetaIndex.BOAT_DAMAGE);
}
public void setRightPaddling(boolean rightPaddling) {
setData(MetaIndex.BOAT_RIGHT_PADDLING, rightPaddling);
sendData(MetaIndex.BOAT_RIGHT_PADDLING);
}
public void setLeftPaddling(boolean leftPaddling) {
setData(MetaIndex.BOAT_LEFT_PADDLING, leftPaddling);
sendData(MetaIndex.BOAT_LEFT_PADDLING);
}
public boolean isRightPaddling() {
return getData(MetaIndex.BOAT_RIGHT_PADDLING);
}
public boolean isLeftPaddling() {
return getData(MetaIndex.BOAT_LEFT_PADDLING);
}
public void setBoatType(TreeSpecies boatType) {
setData(MetaIndex.BOAT_TYPE, (int) boatType.getData());
sendData(MetaIndex.BOAT_TYPE);
}
public void setBoatShake(int number) {
setData(MetaIndex.BOAT_SHAKE, number);
sendData(MetaIndex.BOAT_SHAKE);
}
public int getBoatShake() {
return getData(MetaIndex.BOAT_SHAKE);
}
public TreeSpecies getBoatType() {
return TreeSpecies.getByData(getData(MetaIndex.BOAT_TYPE).byteValue());
}
}

View File

@@ -0,0 +1,20 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class ChestedHorseWatcher extends AbstractHorseWatcher {
public ChestedHorseWatcher(Disguise disguise) {
super(disguise);
}
public void setCarryingChest(boolean carryingChest) {
setData(MetaIndex.HORSE_CHESTED_CARRYING_CHEST, carryingChest);
sendData(MetaIndex.HORSE_CHESTED_CARRYING_CHEST);
}
public boolean isCarryingChest() {
return getData(MetaIndex.HORSE_CHESTED_CARRYING_CHEST);
}
}

View File

@@ -0,0 +1,36 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class CreeperWatcher extends InsentientWatcher
{
public CreeperWatcher(Disguise disguise)
{
super(disguise);
}
public boolean isIgnited()
{
return (boolean) getData(MetaIndex.CREEPER_IGNITED);
}
public boolean isPowered()
{
return (boolean) getData(MetaIndex.CREEPER_POWERED);
}
public void setIgnited(boolean ignited)
{
setData(MetaIndex.CREEPER_IGNITED, ignited);
sendData(MetaIndex.CREEPER_IGNITED);
}
public void setPowered(boolean powered)
{
setData(MetaIndex.CREEPER_POWERED, powered);
sendData(MetaIndex.CREEPER_POWERED);
}
}

View File

@@ -0,0 +1,12 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
/**
* Created by libraryaddict on 6/08/2018.
*/
public class DolphinWatcher extends InsentientWatcher {
public DolphinWatcher(Disguise disguise) {
super(disguise);
}
}

View File

@@ -0,0 +1,11 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
public class DonkeyWatcher extends ChestedHorseWatcher {
public DonkeyWatcher(Disguise disguise) {
super(disguise);
}
}

View File

@@ -0,0 +1,22 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.inventory.ItemStack;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
public class DroppedItemWatcher extends FlagWatcher {
public DroppedItemWatcher(Disguise disguise) {
super(disguise);
}
public ItemStack getItemStack() {
return getData(MetaIndex.DROPPED_ITEM);
}
public void setItemStack(ItemStack item) {
setData(MetaIndex.DROPPED_ITEM, item);
sendData(MetaIndex.DROPPED_ITEM);
}
}

View File

@@ -0,0 +1,42 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import com.comphenix.protocol.wrappers.BlockPosition;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import java.util.Optional;
/**
* @author Navid
*/
public class EnderCrystalWatcher extends FlagWatcher
{
public EnderCrystalWatcher(Disguise disguise)
{
super(disguise);
}
public void setBeamTarget(BlockPosition position)
{
setData(MetaIndex.ENDER_CRYSTAL_BEAM, Optional.of(position));
sendData(MetaIndex.ENDER_CRYSTAL_BEAM);
}
public Optional<BlockPosition> getBeamTarget()
{
return getData(MetaIndex.ENDER_CRYSTAL_BEAM);
}
public void setShowBottom(boolean bool)
{
setData(MetaIndex.ENDER_CRYSTAL_PLATE, bool);
sendData(MetaIndex.ENDER_CRYSTAL_PLATE);
}
public boolean isShowBottom()
{
return getData(MetaIndex.ENDER_CRYSTAL_PLATE);
}
}

View File

@@ -0,0 +1,27 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
/**
* @author Navid
*/
public class EnderDragonWatcher extends InsentientWatcher
{
public EnderDragonWatcher(Disguise disguise)
{
super(disguise);
}
public int getPhase()
{
return getData(MetaIndex.ENDER_DRAGON_PHASE);
}
public void setPhase(int phase)
{
setData(MetaIndex.ENDER_DRAGON_PHASE, phase);
sendData(MetaIndex.ENDER_DRAGON_PHASE);
}
}

View File

@@ -0,0 +1,60 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import com.comphenix.protocol.wrappers.WrappedBlockData;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.util.Optional;
public class EndermanWatcher extends InsentientWatcher {
public EndermanWatcher(Disguise disguise) {
super(disguise);
}
@Override
public ItemStack getItemInMainHand() {
Optional<WrappedBlockData> value = getData(MetaIndex.ENDERMAN_ITEM);
if (value.isPresent()) {
WrappedBlockData pair = value.get();
Material id = pair.getType();
int data = pair.getData();
return new ItemStack(id, 1, (short) data);
} else {
return null;
}
}
@Override
public void setItemInMainHand(ItemStack itemstack) {
setItemInMainHand(itemstack.getType(), itemstack.getDurability());
}
public void setItemInMainHand(Material type) {
setItemInMainHand(type, 0);
}
public void setItemInMainHand(Material type, int data) {
Optional<WrappedBlockData> optional;
if (type == null)
optional = Optional.empty();
else
optional = Optional.of(WrappedBlockData.createData(type, data));
setData(MetaIndex.ENDERMAN_ITEM, optional);
}
public boolean isAggressive() {
return getData(MetaIndex.ENDERMAN_AGRESSIVE);
}
public void setAggressive(boolean isAggressive) {
setData(MetaIndex.ENDERMAN_AGRESSIVE, isAggressive);
sendData(MetaIndex.ENDERMAN_AGRESSIVE);
}
}

View File

@@ -0,0 +1,41 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
public class FallingBlockWatcher extends FlagWatcher {
private ItemStack block;
public FallingBlockWatcher(Disguise disguise) {
super(disguise);
}
@Override
public FallingBlockWatcher clone(Disguise disguise) {
FallingBlockWatcher watcher = (FallingBlockWatcher) super.clone(disguise);
watcher.setBlock(getBlock());
return watcher;
}
public ItemStack getBlock() {
return block;
}
public void setBlock(ItemStack block) {
this.block = block;
if (block == null || block.getType() == null || block.getType() == Material.AIR) {
block.setType(Material.STONE);
}
if (DisguiseAPI.isDisguiseInUse(getDisguise()) && getDisguise().getWatcher() == this) {
DisguiseUtilities.refreshTrackers(getDisguise());
}
}
}

View File

@@ -0,0 +1,43 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
public class FireworkWatcher extends FlagWatcher {
public FireworkWatcher(Disguise disguise) {
super(disguise);
}
public ItemStack getFirework() {
if (getData(MetaIndex.FIREWORK_ITEM) == null) {
return new ItemStack(Material.AIR);
}
return (ItemStack) getData(MetaIndex.FIREWORK_ITEM);
}
public void setFirework(ItemStack newItem) {
if (newItem == null) {
newItem = new ItemStack(Material.AIR);
}
newItem = newItem.clone();
newItem.setAmount(1);
setData(MetaIndex.FIREWORK_ITEM, newItem);
sendData(MetaIndex.FIREWORK_ITEM);
}
public void setAttachedEntity(int entityId) {
setData(MetaIndex.FIREWORK_ATTACHED_ENTITY, entityId);
sendData(MetaIndex.FIREWORK_ATTACHED_ENTITY);
}
public int getAttachedEntity() {
return getData(MetaIndex.FIREWORK_ATTACHED_ENTITY);
}
}

View File

@@ -0,0 +1,13 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
/**
* Created by libraryaddict on 6/08/2018.
*/
public class FishWatcher extends InsentientWatcher {
public FishWatcher(Disguise disguise) {
super(disguise);
}
}

View File

@@ -0,0 +1,29 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
public class FishingHookWatcher extends FlagWatcher
{
public FishingHookWatcher(Disguise disguise)
{
super(disguise);
}
public void setHooked(int hookedId)
{
setData(MetaIndex.FISHING_HOOK_HOOKED, hookedId + 1);
sendData(MetaIndex.FISHING_HOOK_HOOKED);
}
public int getHooked()
{
int hooked = getData(MetaIndex.FISHING_HOOK_HOOKED);
if (hooked > 0)
hooked--;
return hooked;
}
}

View File

@@ -0,0 +1,25 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class GhastWatcher extends InsentientWatcher
{
public GhastWatcher(Disguise disguise)
{
super(disguise);
}
public boolean isAggressive()
{
return getData(MetaIndex.GHAST_AGRESSIVE);
}
public void setAggressive(boolean isAggressive)
{
setData(MetaIndex.GHAST_AGRESSIVE, isAggressive);
sendData(MetaIndex.GHAST_AGRESSIVE);
}
}

View File

@@ -0,0 +1,62 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class GuardianWatcher extends InsentientWatcher {
public GuardianWatcher(Disguise disguise) {
super(disguise);
}
/**
* Is this guardian targetting someone?
*
* @return
*/
public boolean isTarget() {
return ((int) getData(MetaIndex.GUARDIAN_TARGET)) != 0;
}
/**
* Shoot a beam at the given entityId.
*
* @param entityId
*/
public void setTarget(int entityId) {
setData(MetaIndex.GUARDIAN_TARGET, entityId);
sendData(MetaIndex.GUARDIAN_TARGET);
}
public void setTarget(Entity entity) {
setTarget(entity == null ? 0 : entity.getEntityId());
}
/**
* Shoot a beam at the given player name.
*
* @param playername
*/
public void setTarget(String playername) {
Player player = Bukkit.getPlayer(playername);
if (player == null)
return;
setData(MetaIndex.GUARDIAN_TARGET, player.getEntityId());
sendData(MetaIndex.GUARDIAN_TARGET);
}
public boolean isRetractingSpikes() {
return getData(MetaIndex.GUARDIAN_RETRACT_SPIKES);
}
public void setRetractingSpikes(boolean isRetracting) {
setData(MetaIndex.GUARDIAN_RETRACT_SPIKES, isRetracting);
sendData(MetaIndex.GUARDIAN_RETRACT_SPIKES);
}
}

View File

@@ -0,0 +1,84 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.Material;
import org.bukkit.entity.Horse.Color;
import org.bukkit.entity.Horse.Style;
import org.bukkit.inventory.ItemStack;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
public class HorseWatcher extends AbstractHorseWatcher {
public HorseWatcher(Disguise disguise) {
super(disguise);
setStyle(Style.values()[DisguiseUtilities.random.nextInt(Style.values().length)]);
setColor(Color.values()[DisguiseUtilities.random.nextInt(Color.values().length)]);
}
public Color getColor() {
return Color.values()[((Integer) getData(MetaIndex.HORSE_COLOR) & 0xFF)];
}
public ItemStack getHorseArmor() {
int horseValue = getHorseArmorAsInt();
switch (horseValue) {
case 1:
return new ItemStack(Material.IRON_HORSE_ARMOR);
case 2:
return new ItemStack(Material.GOLDEN_HORSE_ARMOR);
case 3:
return new ItemStack(Material.DIAMOND_HORSE_ARMOR);
default:
break;
}
return null;
}
public Style getStyle() {
return Style.values()[(getData(MetaIndex.HORSE_COLOR) >>> 8)];
}
public void setColor(Color color) {
setData(MetaIndex.HORSE_COLOR, color.ordinal() & 0xFF | getStyle().ordinal() << 8);
sendData(MetaIndex.HORSE_COLOR);
}
protected int getHorseArmorAsInt() {
return getData(MetaIndex.HORSE_ARMOR);
}
protected void setHorseArmor(int armor) {
setData(MetaIndex.HORSE_ARMOR, armor);
sendData(MetaIndex.HORSE_ARMOR);
}
public void setStyle(Style style) {
setData(MetaIndex.HORSE_COLOR, getColor().ordinal() & 0xFF | style.ordinal() << 8);
sendData(MetaIndex.HORSE_COLOR);
}
public void setHorseArmor(ItemStack item) {
int value = 0;
if (item != null) {
Material mat = item.getType();
if (mat == Material.IRON_HORSE_ARMOR) {
value = 1;
}
else if (mat == Material.GOLDEN_HORSE_ARMOR) {
value = 2;
}
else if (mat == Material.DIAMOND_HORSE_ARMOR) {
value = 3;
}
}
setHorseArmor(value);
}
}

View File

@@ -0,0 +1,12 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
/**
* Created by libraryaddict on 9/06/2017.
*/
public class IllagerWatcher extends InsentientWatcher {
public IllagerWatcher(Disguise disguise) {
super(disguise);
}
}

View File

@@ -0,0 +1,20 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class IllagerWizardWatcher extends IllagerWatcher {
public IllagerWizardWatcher(Disguise disguise) {
super(disguise);
}
public void setSpellTicks(int spellTicks) {
setData(MetaIndex.ILLAGER_SPELL_TICKS, (byte) spellTicks);
sendData(MetaIndex.ILLAGER_SPELL_TICKS);
}
public int getSpellTicks() {
return getData(MetaIndex.ILLAGER_SPELL_TICKS);
}
}

View File

@@ -0,0 +1,44 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.inventory.MainHand;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class InsentientWatcher extends LivingWatcher {
public InsentientWatcher(Disguise disguise) {
super(disguise);
}
public void setMainHand(MainHand mainHand) {
setInsentientFlag(2, mainHand == MainHand.RIGHT);
sendData(MetaIndex.INSENTIENT_META);
}
public MainHand getMainHand() {
return getInsentientFlag(2) ? MainHand.RIGHT : MainHand.LEFT;
}
public boolean isAI() {
return getInsentientFlag(1);
}
public void setAI(boolean ai) {
setInsentientFlag(1, ai);
sendData(MetaIndex.INSENTIENT_META);
}
private void setInsentientFlag(int i, boolean flag) {
byte b0 = (byte) getData(MetaIndex.INSENTIENT_META);
if (flag) {
setData(MetaIndex.INSENTIENT_META, (byte) (b0 | 1 << i));
} else {
setData(MetaIndex.INSENTIENT_META, (byte) (b0 & (~1 << i)));
}
}
private boolean getInsentientFlag(int i) {
return ((byte) getData(MetaIndex.INSENTIENT_META) & 1 << i) != 0;
}
}

View File

@@ -0,0 +1,12 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
public class IronGolemWatcher extends InsentientWatcher
{
public IronGolemWatcher(Disguise disguise)
{
super(disguise);
}
}

View File

@@ -0,0 +1,44 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
public class ItemFrameWatcher extends FlagWatcher {
public ItemFrameWatcher(Disguise disguise) {
super(disguise);
}
public ItemStack getItem() {
if (getData(MetaIndex.ITEMFRAME_ITEM) == null) {
return new ItemStack(Material.AIR);
}
return (ItemStack) getData(MetaIndex.ITEMFRAME_ITEM);
}
public int getRotation() {
return getData(MetaIndex.ITEMFRAME_ROTATION);
}
public void setItem(ItemStack newItem) {
if (newItem == null) {
newItem = new ItemStack(Material.AIR);
}
newItem = newItem.clone();
newItem.setAmount(1);
setData(MetaIndex.ITEMFRAME_ITEM, newItem);
sendData(MetaIndex.ITEMFRAME_ITEM);
}
public void setRotation(int rotation) {
setData(MetaIndex.ITEMFRAME_ROTATION, rotation % 4);
sendData(MetaIndex.ITEMFRAME_ROTATION);
}
}

View File

@@ -0,0 +1,178 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import com.comphenix.protocol.PacketType.Play.Server;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedAttribute;
import com.comphenix.protocol.wrappers.WrappedAttribute.Builder;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import org.bukkit.Color;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class LivingWatcher extends FlagWatcher {
private double maxHealth;
private boolean maxHealthSet;
private HashSet<String> potionEffects = new HashSet<>();
public LivingWatcher(Disguise disguise) {
super(disguise);
}
@Override
public LivingWatcher clone(Disguise disguise) {
LivingWatcher clone = (LivingWatcher) super.clone(disguise);
clone.potionEffects = (HashSet<String>) potionEffects.clone();
clone.maxHealth = maxHealth;
clone.maxHealthSet = maxHealthSet;
return clone;
}
public float getHealth() {
return getData(MetaIndex.LIVING_HEALTH);
}
public double getMaxHealth() {
return maxHealth;
}
public boolean isPotionParticlesAmbient() {
return getData(MetaIndex.LIVING_POTION_AMBIENT);
}
public Color getParticlesColor() {
int color = getData(MetaIndex.LIVING_POTIONS);
return Color.fromRGB(color);
}
public void setParticlesColor(Color color) {
potionEffects.clear();
setData(MetaIndex.LIVING_POTIONS, color.asRGB());
sendData(MetaIndex.LIVING_POTIONS);
}
private int getPotions() {
if (potionEffects.isEmpty()) {
return 0;
}
ArrayList<Color> colors = new ArrayList<>();
for (String typeId : potionEffects) {
PotionEffectType type = PotionEffectType.getByName(typeId);
if (type == null) {
continue;
}
Color color = type.getColor();
if (color == null) {
continue;
}
colors.add(color);
}
if (colors.isEmpty()) {
return 0;
}
Color color = colors.remove(0);
return color.mixColors(colors.toArray(new Color[0])).asRGB();
}
public boolean hasPotionEffect(PotionEffectType type) {
return potionEffects.contains(type.getName());
}
public boolean isMaxHealthSet() {
return maxHealthSet;
}
public void addPotionEffect(PotionEffectType potionEffect) {
if (!hasPotionEffect(potionEffect)) {
potionEffects.add(potionEffect.getName());
}
sendPotionEffects();
}
public void removePotionEffect(PotionEffectType potionEffect) {
if (hasPotionEffect(potionEffect)) {
potionEffects.remove(potionEffect.getId());
}
sendPotionEffects();
}
public void setPotionParticlesAmbient(boolean particles) {
setData(MetaIndex.LIVING_POTION_AMBIENT, particles);
sendData(MetaIndex.LIVING_POTION_AMBIENT);
}
private void sendPotionEffects() {
setData(MetaIndex.LIVING_POTIONS, getPotions());
sendData(MetaIndex.LIVING_POTIONS);
}
public void setHealth(float health) {
setData(MetaIndex.LIVING_HEALTH, health);
sendData(MetaIndex.LIVING_HEALTH);
}
public int getArrowsSticking() {
return getData(MetaIndex.LIVING_ARROWS);
}
public void setArrowsSticking(int arrowsNo) {
setData(MetaIndex.LIVING_ARROWS, Math.max(0, Math.min(127, arrowsNo)));
sendData(MetaIndex.LIVING_ARROWS);
}
public void setMaxHealth(double newHealth) {
this.maxHealth = newHealth;
this.maxHealthSet = true;
if (DisguiseAPI.isDisguiseInUse(getDisguise()) && getDisguise().getWatcher() == this) {
PacketContainer packet = new PacketContainer(Server.UPDATE_ATTRIBUTES);
List<WrappedAttribute> attributes = new ArrayList<>();
Builder builder;
builder = WrappedAttribute.newBuilder();
builder.attributeKey("generic.maxHealth");
builder.baseValue(getMaxHealth());
builder.packet(packet);
attributes.add(builder.build());
Entity entity = getDisguise().getEntity();
packet.getIntegers().write(0, entity.getEntityId());
packet.getAttributeCollectionModifier().write(0, attributes);
for (Player player : DisguiseUtilities.getPerverts(getDisguise())) {
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false);
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}

View File

@@ -0,0 +1,42 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.entity.Llama;
import me.libraryaddict.disguise.disguisetypes.AnimalColor;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class LlamaWatcher extends ChestedHorseWatcher {
public LlamaWatcher(Disguise disguise) {
super(disguise);
}
public void setColor(Llama.Color color) {
setData(MetaIndex.LLAMA_COLOR, color.ordinal());
sendData(MetaIndex.LLAMA_COLOR);
}
public Llama.Color getColor() {
return Llama.Color.values()[getData(MetaIndex.LLAMA_COLOR)];
}
public void setCarpet(AnimalColor color) {
setData(MetaIndex.LLAMA_CARPET, color.getId());
sendData(MetaIndex.LLAMA_CARPET);
}
public AnimalColor getCarpet() {
return AnimalColor.getColor(getData(MetaIndex.LLAMA_CARPET));
}
public void setStrength(int strength) {
setData(MetaIndex.LLAMA_STRENGTH, strength);
sendData(MetaIndex.LLAMA_STRENGTH);
}
public int getStrength() {
return getData(MetaIndex.LLAMA_STRENGTH);
}
}

View File

@@ -0,0 +1,12 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
/**
* Created by libraryaddict on 6/08/2018.
*/
public class MinecartCommandWatcher extends MinecartWatcher {
public MinecartCommandWatcher(Disguise disguise) {
super(disguise);
}
}

View File

@@ -0,0 +1,22 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
/**
* Created by libraryaddict on 6/08/2018.
*/
public class MinecartFurnaceWatcher extends MinecartWatcher {
public MinecartFurnaceWatcher(Disguise disguise) {
super(disguise);
}
public boolean isFueled() {
return getData(MetaIndex.MINECART_FURANCE_FUELED);
}
public void setFueled(boolean fueled) {
setData(MetaIndex.MINECART_FURANCE_FUELED, fueled);
sendData(MetaIndex.MINECART_FURANCE_FUELED);
}
}

View File

@@ -0,0 +1,44 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.utilities.ReflectionManager;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public class MinecartWatcher extends FlagWatcher {
public MinecartWatcher(Disguise disguise) {
super(disguise);
}
public ItemStack getBlockInCart() {
return ReflectionManager.getItemStackByCombinedId(getData(MetaIndex.MINECART_BLOCK));
}
public int getBlockYOffset() {
return getData(MetaIndex.MINECART_BLOCK_Y);
}
public boolean isViewBlockInCart() {
return getData(MetaIndex.MINECART_BLOCK_VISIBLE);
}
public void setBlockInCart(ItemStack item) {
setData(MetaIndex.MINECART_BLOCK, ReflectionManager.getCombinedIdByItemStack(item));
setData(MetaIndex.MINECART_BLOCK_VISIBLE, item != null && item.getType() != Material.AIR);
sendData(MetaIndex.MINECART_BLOCK, MetaIndex.MINECART_BLOCK_VISIBLE);
}
public void setBlockOffset(int i) {
setData(MetaIndex.MINECART_BLOCK_Y, i);
sendData(MetaIndex.MINECART_BLOCK_Y);
}
public void setViewBlockInCart(boolean viewBlock) {
setData(MetaIndex.MINECART_BLOCK_VISIBLE, viewBlock);
sendData(MetaIndex.MINECART_BLOCK_VISIBLE);
}
}

View File

@@ -0,0 +1,11 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
public class MuleWatcher extends ChestedHorseWatcher {
public MuleWatcher(Disguise disguise) {
super(disguise);
}
}

View File

@@ -0,0 +1,27 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.entity.Ocelot;
import org.bukkit.entity.Ocelot.Type;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class OcelotWatcher extends TameableWatcher
{
public OcelotWatcher(Disguise disguise)
{
super(disguise);
}
public Type getType()
{
return Ocelot.Type.getType(getData(MetaIndex.OCELOT_TYPE));
}
public void setType(Type newType)
{
setData(MetaIndex.OCELOT_TYPE, newType.getId());
sendData(MetaIndex.OCELOT_TYPE);
}
}

View File

@@ -0,0 +1,43 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.Art;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
public class PaintingWatcher extends FlagWatcher
{
private Art painting;
public PaintingWatcher(Disguise disguise)
{
super(disguise);
}
@Override
public PaintingWatcher clone(Disguise disguise)
{
PaintingWatcher watcher = (PaintingWatcher) super.clone(disguise);
watcher.setArt(getArt());
return watcher;
}
public Art getArt()
{
return painting;
}
public void setArt(Art newPainting)
{
this.painting = newPainting;
if (getDisguise().getEntity() != null && getDisguise().getWatcher() == this)
{
DisguiseUtilities.refreshTrackers(getDisguise());
}
}
}

View File

@@ -0,0 +1,23 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import org.bukkit.entity.Parrot;
/**
* Created by libraryaddict on 9/06/2017.
*/
public class ParrotWatcher extends TameableWatcher {
public ParrotWatcher(Disguise disguise) {
super(disguise);
}
public Parrot.Variant getVariant() {
return Parrot.Variant.values()[getData(MetaIndex.PARROT_VARIANT)];
}
public void setVariant(Parrot.Variant variant) {
setData(MetaIndex.PARROT_VARIANT, variant.ordinal());
sendData(MetaIndex.PARROT_VARIANT);
}
}

View File

@@ -0,0 +1,22 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
/**
* Created by libraryaddict on 6/08/2018.
*/
public class PhantomWatcher extends InsentientWatcher {
public PhantomWatcher(Disguise disguise) {
super(disguise);
}
public void setSize(int size) {
setData(MetaIndex.PHANTOM_SIZE, Math.min(Math.max(size, -50), 50));
sendData(MetaIndex.PHANTOM_SIZE);
}
public int getSize() {
return getData(MetaIndex.PHANTOM_SIZE);
}
}

View File

@@ -0,0 +1,20 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class PigWatcher extends AgeableWatcher {
public PigWatcher(Disguise disguise) {
super(disguise);
}
public boolean isSaddled() {
return getData(MetaIndex.PIG_SADDLED);
}
public void setSaddled(boolean isSaddled) {
setData(MetaIndex.PIG_SADDLED, isSaddled);
sendData(MetaIndex.PIG_SADDLED);
}
}

View File

@@ -0,0 +1,237 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.inventory.MainHand;
import com.comphenix.protocol.PacketType.Play.Server;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.reflect.StructureModifier;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.DisguiseConfig;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.disguisetypes.PlayerDisguise;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
public class PlayerWatcher extends LivingWatcher {
private boolean isInBed;
private BlockFace sleepingDirection;
private boolean alwaysShowInTab = DisguiseConfig.isShowDisguisedPlayersInTab();
public PlayerWatcher(Disguise disguise) {
super(disguise);
setData(MetaIndex.PLAYER_SKIN, MetaIndex.PLAYER_SKIN.getDefault());
}
public boolean isDisplayedInTab() {
return alwaysShowInTab;
}
public void setDisplayedInTab(boolean showPlayerInTab) {
if (getDisguise().isDisguiseInUse())
throw new IllegalStateException("Cannot set this while disguise is in use!");
alwaysShowInTab = showPlayerInTab;
}
@Override
public PlayerWatcher clone(Disguise disguise) {
PlayerWatcher watcher = (PlayerWatcher) super.clone(disguise);
watcher.isInBed = isInBed;
watcher.sleepingDirection = sleepingDirection;
watcher.alwaysShowInTab = alwaysShowInTab;
return watcher;
}
public void setMainHand(MainHand mainHand) {
setData(MetaIndex.PLAYER_HAND, (byte) mainHand.ordinal());
sendData(MetaIndex.PLAYER_HAND);
}
public MainHand getMainHand() {
return MainHand.values()[getData(MetaIndex.PLAYER_HAND)];
}
public BlockFace getSleepingDirection() {
if (sleepingDirection == null) {
if (this.getDisguise().getEntity() != null && isSleeping()) {
this.sleepingDirection = BlockFace.values()[Math
.round(this.getDisguise().getEntity().getLocation().getYaw() / 90F) & 0x3];
} else {
return BlockFace.EAST;
}
}
return sleepingDirection;
}
// Bit 0 (0x01): Cape enabled
// Bit 1 (0x02): Jacket enabled
// Bit 2 (0x04): Left Sleeve enabled
// Bit 3 (0x08): Right Sleeve enabled
// Bit 4 (0x10): Left Pants Leg enabled
// Bit 5 (0x20): Right Pants Leg enabled
// Bit 6 (0x40): Hat enabled
private boolean isSkinFlag(int i) {
return ((byte) getData(MetaIndex.PLAYER_SKIN) & 1 << i) != 0;
}
public boolean isCapeEnabled() {
return isSkinFlag(1);
}
public boolean isJackedEnabled() {
return isSkinFlag(2);
}
public boolean isLeftSleeveEnabled() {
return isSkinFlag(3);
}
public boolean isRightSleeveEnabled() {
return isSkinFlag(4);
}
public boolean isLeftPantsEnabled() {
return isSkinFlag(5);
}
public boolean isRightPantsEnabled() {
return isSkinFlag(6);
}
public boolean isHatEnabled() {
return isSkinFlag(7);
}
public void setCapeEnabled(boolean enabled) {
setSkinFlags(1, enabled);
sendData(MetaIndex.PLAYER_SKIN);
}
public void setJacketEnabled(boolean enabled) {
setSkinFlags(2, enabled);
sendData(MetaIndex.PLAYER_SKIN);
}
public void setLeftSleeveEnabled(boolean enabled) {
setSkinFlags(3, enabled);
sendData(MetaIndex.PLAYER_SKIN);
}
public void setRightSleeveEnabled(boolean enabled) {
setSkinFlags(4, enabled);
sendData(MetaIndex.PLAYER_SKIN);
}
public void setLeftPantsEnabled(boolean enabled) {
setSkinFlags(5, enabled);
sendData(MetaIndex.PLAYER_SKIN);
}
public void setRightPantsEnabled(boolean enabled) {
setSkinFlags(6, enabled);
sendData(MetaIndex.PLAYER_SKIN);
}
public void setHatEnabled(boolean enabled) {
setSkinFlags(7, enabled);
sendData(MetaIndex.PLAYER_SKIN);
}
public boolean isSleeping() {
return isInBed;
}
public void setSkin(String playerName) {
((PlayerDisguise) getDisguise()).setSkin(playerName);
}
public void setSkin(WrappedGameProfile profile) {
((PlayerDisguise) getDisguise()).setSkin(profile);
}
public void setSleeping(BlockFace sleepingDirection) {
setSleeping(true, sleepingDirection);
}
public void setSleeping(boolean sleep) {
setSleeping(sleep, null);
}
/**
* If no BlockFace is supplied. It grabs it from the entities facing direction if applicable.
*
* @param sleeping
* @param sleepingDirection
*/
public void setSleeping(boolean sleeping, BlockFace sleepingDirection) {
if (sleepingDirection != null) {
this.sleepingDirection = BlockFace.values()[sleepingDirection.ordinal() % 4];
}
isInBed = sleeping;
if (DisguiseConfig.isBedPacketsEnabled() && DisguiseUtilities.isDisguiseInUse(getDisguise())) {
try {
if (isSleeping()) {
for (Player player : DisguiseUtilities.getPerverts(getDisguise())) {
PacketContainer[] packets = DisguiseUtilities
.getBedPackets(getDisguise().getEntity().getLocation(), player.getLocation(),
(PlayerDisguise) getDisguise());
if (getDisguise().getEntity() == player) {
for (PacketContainer packet : packets) {
packet = packet.shallowClone();
packet.getIntegers().write(0, DisguiseAPI.getSelfDisguiseId());
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
}
} else {
for (PacketContainer packet : packets) {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
}
}
}
} else {
PacketContainer packet = new PacketContainer(Server.ANIMATION);
StructureModifier<Integer> mods = packet.getIntegers();
mods.write(0, getDisguise().getEntity().getEntityId());
mods.write(1, 3);
for (Player player : DisguiseUtilities.getPerverts(getDisguise())) {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
private void setSkinFlags(int i, boolean flag) {
byte b0 = (byte) getData(MetaIndex.PLAYER_SKIN);
if (flag) {
setData(MetaIndex.PLAYER_SKIN, (byte) (b0 | 1 << i));
} else {
setData(MetaIndex.PLAYER_SKIN, (byte) (b0 & (~1 << i)));
}
}
}

View File

@@ -0,0 +1,23 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class PolarBearWatcher extends AgeableWatcher
{
public PolarBearWatcher(Disguise disguise)
{
super(disguise);
}
public void setStanding(boolean standing)
{
setData(MetaIndex.POLAR_BEAR_STANDING, standing);
sendData(MetaIndex.POLAR_BEAR_STANDING);
}
public boolean isStanding()
{
return getData(MetaIndex.POLAR_BEAR_STANDING);
}
}

View File

@@ -0,0 +1,22 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
/**
* Created by libraryaddict on 6/08/2018.
*/
public class PufferFishWatcher extends FishWatcher {
public PufferFishWatcher(Disguise disguise) {
super(disguise);
}
public void setPuffState(int puffState) {
setData(MetaIndex.PUFFERFISH_PUFF_STATE, Math.min(Math.max(puffState, 0), 2));
sendData(MetaIndex.PUFFERFISH_PUFF_STATE);
}
public int getPuffState() {
return getData(MetaIndex.PUFFERFISH_PUFF_STATE);
}
}

View File

@@ -0,0 +1,28 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.disguisetypes.RabbitType;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
public class RabbitWatcher extends AgeableWatcher
{
public RabbitWatcher(Disguise disguise)
{
super(disguise);
setType(RabbitType.values()[DisguiseUtilities.random.nextInt(RabbitType.values().length)]);
}
public RabbitType getType()
{
return RabbitType.getType((int) getData(MetaIndex.RABBIT_TYPE));
}
public void setType(RabbitType type)
{
setData(MetaIndex.RABBIT_TYPE, type.getTypeId());
sendData(MetaIndex.RABBIT_TYPE);
}
}

View File

@@ -0,0 +1,45 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.DyeColor;
import me.libraryaddict.disguise.disguisetypes.AnimalColor;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class SheepWatcher extends AgeableWatcher {
public SheepWatcher(Disguise disguise) {
super(disguise);
}
public AnimalColor getColor() {
return AnimalColor.getColor(((int) getData(MetaIndex.SHEEP_WOOL) & 15));
}
public boolean isSheared() {
return (getData(MetaIndex.SHEEP_WOOL) & 16) != 0;
}
public void setColor(AnimalColor color) {
setColor(DyeColor.getByWoolData((byte) color.getId()));
}
public void setColor(DyeColor color) {
byte b0 = getData(MetaIndex.SHEEP_WOOL);
setData(MetaIndex.SHEEP_WOOL, (byte) (b0 & 240 | color.getWoolData() & 15));
sendData(MetaIndex.SHEEP_WOOL);
}
public void setSheared(boolean flag) {
byte b0 = getData(MetaIndex.SHEEP_WOOL);
if (flag) {
setData(MetaIndex.SHEEP_WOOL, (byte) (b0 | 16));
} else {
setData(MetaIndex.SHEEP_WOOL, (byte) (b0 & -17));
}
sendData(MetaIndex.SHEEP_WOOL);
}
}

View File

@@ -0,0 +1,58 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import com.comphenix.protocol.wrappers.BlockPosition;
import com.comphenix.protocol.wrappers.EnumWrappers.Direction;
import me.libraryaddict.disguise.disguisetypes.AnimalColor;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import org.bukkit.block.BlockFace;
import java.util.Optional;
/**
* @author Navid
*/
public class ShulkerWatcher extends InsentientWatcher {
public ShulkerWatcher(Disguise disguise) {
super(disguise);
}
public BlockFace getFacingDirection() {
return BlockFace.valueOf(getData(MetaIndex.SHULKER_FACING).name());
}
public void setFacingDirection(BlockFace face) {
setData(MetaIndex.SHULKER_FACING, Direction.valueOf(face.name()));
sendData(MetaIndex.SHULKER_FACING);
}
public BlockPosition getAttachmentPosition() {
return getData(MetaIndex.SHULKER_ATTACHED).get();
}
public void setAttachmentPosition(BlockPosition pos) {
setData(MetaIndex.SHULKER_ATTACHED, Optional.of(pos));
sendData(MetaIndex.SHULKER_ATTACHED);
}
public int getShieldHeight() {
return getData(MetaIndex.SHULKER_PEEKING);
}
public void setShieldHeight(int newHeight) {
if (newHeight < 0)
newHeight = 0;
if (newHeight > 127)
newHeight = 127;
setData(MetaIndex.SHULKER_PEEKING, (byte) newHeight);
sendData(MetaIndex.SHULKER_PEEKING);
}
public void setColor(AnimalColor color) {
setData(MetaIndex.SHULKER_COLOR, (byte) color.getId());
sendData(MetaIndex.SHULKER_COLOR);
}
}

View File

@@ -0,0 +1,11 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
public class SkeletonHorseWatcher extends AbstractHorseWatcher {
public SkeletonHorseWatcher(Disguise disguise) {
super(disguise);
}
}

View File

@@ -0,0 +1,22 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
/**
* @author Navid
*/
public class SkeletonWatcher extends InsentientWatcher {
public SkeletonWatcher(Disguise disguise) {
super(disguise);
}
public void setSwingArms(boolean swingingArms) {
setData(MetaIndex.SKELETON_SWING_ARMS, swingingArms);
sendData(MetaIndex.SKELETON_SWING_ARMS);
}
public boolean isSwingArms() {
return getData(MetaIndex.SKELETON_SWING_ARMS);
}
}

View File

@@ -0,0 +1,28 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
public class SlimeWatcher extends InsentientWatcher {
public SlimeWatcher(Disguise disguise) {
super(disguise);
setSize(DisguiseUtilities.random.nextInt(4) + 1);
}
public int getSize() {
return (int) getData(MetaIndex.SLIME_SIZE);
}
public void setSize(int size) {
if (size < 1) {
size = 1;
} else if (size > 50) {
size = 50;
}
setData(MetaIndex.SLIME_SIZE, size);
sendData(MetaIndex.SLIME_SIZE);
}
}

View File

@@ -0,0 +1,19 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class SnowmanWatcher extends InsentientWatcher {
public SnowmanWatcher(Disguise disguise) {
super(disguise);
}
public void setDerp(boolean derp) {
setData(MetaIndex.SNOWMAN_DERP, (byte) (derp ? 0 : 16));
sendData(MetaIndex.SNOWMAN_DERP);
}
public boolean isDerp() {
return getData(MetaIndex.SNOWMAN_DERP) == 0;
}
}

View File

@@ -0,0 +1,23 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class SpiderWatcher extends InsentientWatcher
{
public SpiderWatcher(Disguise disguise)
{
super(disguise);
}
public void setClimbing(boolean climbing)
{
setData(MetaIndex.SPIDER_CLIMB, (byte) (climbing ? 1 : 0));
sendData(MetaIndex.SPIDER_CLIMB);
}
public boolean isClimbing()
{
return getData(MetaIndex.SPIDER_CLIMB) == (byte) 1;
}
}

View File

@@ -0,0 +1,46 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.inventory.ItemStack;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
public class SplashPotionWatcher extends FlagWatcher {
private int potionId;
public SplashPotionWatcher(Disguise disguise) {
super(disguise);
}
@Override
public SplashPotionWatcher clone(Disguise disguise) {
SplashPotionWatcher watcher = (SplashPotionWatcher) super.clone(disguise);
watcher.setPotionId(getPotionId());
return watcher;
}
public int getPotionId() {
return potionId;
}
public void setSplashPotion(ItemStack item) {
setData(MetaIndex.SPLASH_POTION_ITEM, item);
sendData(MetaIndex.SPLASH_POTION_ITEM);
}
public ItemStack getSplashPotion() {
return getData(MetaIndex.SPLASH_POTION_ITEM);
}
public void setPotionId(int newPotionId) {
this.potionId = newPotionId;
if (getDisguise().getEntity() != null && getDisguise().getWatcher() == this) {
DisguiseUtilities.refreshTrackers(getDisguise());
}
}
}

View File

@@ -0,0 +1,11 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
public class SquidWatcher extends InsentientWatcher
{
public SquidWatcher(Disguise disguise)
{
super(disguise);
}
}

View File

@@ -0,0 +1,12 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
public class TNTWatcher extends FlagWatcher
{
public TNTWatcher(Disguise disguise)
{
super(disguise);
}
}

View File

@@ -0,0 +1,68 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import java.util.Optional;
import java.util.UUID;
public class TameableWatcher extends AgeableWatcher
{
public TameableWatcher(Disguise disguise)
{
super(disguise);
}
public Optional<UUID> getOwner()
{
return getData(MetaIndex.TAMEABLE_OWNER);
}
public boolean isSitting()
{
return isTameableFlag(1);
}
public boolean isTamed()
{
return isTameableFlag(4);
}
protected boolean isTameableFlag(int no)
{
return ((byte) getData(MetaIndex.TAMEABLE_META) & no) != 0;
}
protected void setTameableFlag(int no, boolean flag)
{
byte value = (byte) getData(MetaIndex.TAMEABLE_META);
if (flag)
{
setData(MetaIndex.TAMEABLE_META, (byte) (value | no));
}
else
{
setData(MetaIndex.TAMEABLE_META, (byte) (value & -(no + 1)));
}
sendData(MetaIndex.TAMEABLE_META);
}
public void setOwner(UUID owner)
{
setData(MetaIndex.TAMEABLE_OWNER, Optional.of(owner));
sendData(MetaIndex.TAMEABLE_OWNER);
}
public void setSitting(boolean sitting)
{
setTameableFlag(1, sitting);
}
public void setTamed(boolean tamed)
{
setTameableFlag(4, tamed);
}
}

View File

@@ -0,0 +1,31 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import org.apache.commons.lang.math.RandomUtils;
import org.bukkit.Color;
/**
* @author Navid
*/
public class TippedArrowWatcher extends ArrowWatcher {
public TippedArrowWatcher(Disguise disguise) {
super(disguise);
if (getDisguise().getType() != DisguiseType.ARROW) {
setColor(Color.fromRGB(RandomUtils.nextInt(256), RandomUtils.nextInt(256), RandomUtils.nextInt(256)));
}
}
public Color getColor() {
int color = getData(MetaIndex.TIPPED_ARROW_COLOR);
return Color.fromRGB(color);
}
public void setColor(Color color) {
setData(MetaIndex.TIPPED_ARROW_COLOR, color.asRGB());
sendData(MetaIndex.TIPPED_ARROW_COLOR);
}
}

View File

@@ -0,0 +1,12 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
/**
* Created by libraryaddict on 6/08/2018.
*/
public class TridentWatcher extends ArrowWatcher {
public TridentWatcher(Disguise disguise) {
super(disguise);
}
}

View File

@@ -0,0 +1,109 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import org.bukkit.DyeColor;
import org.bukkit.entity.TropicalFish;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by libraryaddict on 6/08/2018.
*/
public class TropicalFishWatcher extends FishWatcher {
private enum CraftPattern {
KOB("KOB", 0, 0, false),
SUNSTREAK("SUNSTREAK", 1, 1, false),
SNOOPER("SNOOPER", 2, 2, false),
DASHER("DASHER", 3, 3, false),
BRINELY("BRINELY", 4, 4, false),
SPOTTY("SPOTTY", 5, 5, false),
FLOPPER("FLOPPER", 6, 0, true),
STRIPEY("STRIPEY", 7, 1, true),
GLITTER("GLITTER", 8, 2, true),
BLOCKFISH("BLOCKFISH", 9, 3, true),
BETTY("BETTY", 10, 4, true),
CLAYFISH("CLAYFISH", 11, 5, true);
private final int variant;
private final boolean large;
private static final Map<Integer, TropicalFish.Pattern> BY_DATA;
static {
BY_DATA = new HashMap<>();
CraftPattern[] values;
for (int length = (values = values()).length, i = 0; i < length; ++i) {
final CraftPattern type = values[i];
CraftPattern.BY_DATA.put(type.getDataValue(), TropicalFish.Pattern.values()[type.ordinal()]);
}
}
static TropicalFish.Pattern fromData(final int data) {
return CraftPattern.BY_DATA.get(data);
}
CraftPattern(final String s, final int n, final int variant, final boolean large) {
this.variant = variant;
this.large = large;
}
public int getDataValue() {
return this.variant << 8 | (this.large ? 1 : 0);
}
}
public TropicalFishWatcher(Disguise disguise) {
super(disguise);
Random random = new Random();
int n = random.nextInt(2);
int n2 = random.nextInt(6);
int n3 = random.nextInt(15);
int n4 = random.nextInt(15);
this.setVariant(n | n2 << 8 | n3 << 16 | n4 << 24);
}
public DyeColor getPatternColor() {
return DyeColor.getByWoolData((byte) (getVariant() >> 24 & 0xFF));
}
public void setPatternColor(DyeColor dyeColor) {
setVariant(getData(dyeColor, getBodyColor(), getPattern()));
}
private int getData(final DyeColor patternColor, final DyeColor bodyColor, final TropicalFish.Pattern type) {
return patternColor.getWoolData() << 24 | bodyColor.getWoolData() << 16 |
CraftPattern.values()[type.ordinal()].getDataValue();
}
public DyeColor getBodyColor() {
return DyeColor.getByWoolData((byte) (getVariant() >> 16 & 0xFF));
}
public void setBodyColor(DyeColor dyeColor) {
setVariant(getData(dyeColor, dyeColor, getPattern()));
}
public TropicalFish.Pattern getPattern() {
return CraftPattern.fromData(getVariant() & 0xFFFF);
}
public void setPattern(TropicalFish.Pattern pattern) {
setVariant(getData(getPatternColor(), getBodyColor(), pattern));
}
@Deprecated
public int getVariant() {
return getData(MetaIndex.TROPICAL_FISH_VARIANT);
}
@Deprecated
public void setVariant(int variant) {
setData(MetaIndex.TROPICAL_FISH_VARIANT, variant);
sendData(MetaIndex.TROPICAL_FISH_VARIANT);
}
}

View File

@@ -0,0 +1,22 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
/**
* Created by libraryaddict on 6/08/2018.
*/
public class TurtleWatcher extends AgeableWatcher {
public TurtleWatcher(Disguise disguise) {
super(disguise);
}
public void setEgg(boolean egg) {
setData(MetaIndex.TURTLE_HAS_EGG, egg);
sendData(MetaIndex.TURTLE_HAS_EGG);
}
public boolean isEgg() {
return getData(MetaIndex.TURTLE_HAS_EGG);
}
}

View File

@@ -0,0 +1,21 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class VexWatcher extends InsentientWatcher {
public VexWatcher(Disguise disguise) {
super(disguise);
}
public void setAngry(boolean angry) {
setData(MetaIndex.VEX_ANGRY, (byte) (angry ? 1 : 0));
sendData(MetaIndex.VEX_ANGRY);
}
public boolean isAngry() {
return getData(MetaIndex.VEX_ANGRY) == 1;
}
}

View File

@@ -0,0 +1,28 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import org.bukkit.entity.Villager.Profession;
public class VillagerWatcher extends AgeableWatcher {
public VillagerWatcher(Disguise disguise) {
super(disguise);
setProfession(Profession.values()[DisguiseUtilities.random.nextInt(Profession.values().length)]);
}
public Profession getProfession() {
return Profession.values()[getData(MetaIndex.VILLAGER_PROFESSION) + 1];
}
@Deprecated
public void setProfession(int professionId) {
setData(MetaIndex.VILLAGER_PROFESSION, professionId);
sendData(MetaIndex.VILLAGER_PROFESSION);
}
public void setProfession(Profession newProfession) {
setProfession(newProfession.ordinal() - 1);
}
}

View File

@@ -0,0 +1,17 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class VindicatorWatcher extends IllagerWatcher {
public VindicatorWatcher(Disguise disguise) {
super(disguise);
}
public void setJohnny(boolean isJohnny) {
setData(MetaIndex.ILLAGER_META, (byte) (isJohnny ? 1 : 0));
sendData(MetaIndex.ILLAGER_META);
}
}

View File

@@ -0,0 +1,28 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
/**
* @author Navid
*/
public class WitchWatcher extends InsentientWatcher
{
public WitchWatcher(Disguise disguise)
{
super(disguise);
}
public boolean isAggressive()
{
return (boolean) getData(MetaIndex.WITCH_AGGRESSIVE);
}
public void setAggressive(boolean aggressive)
{
setData(MetaIndex.WITCH_AGGRESSIVE, aggressive);
sendData(MetaIndex.WITCH_AGGRESSIVE);
}
}

View File

@@ -0,0 +1,26 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
public class WitherSkullWatcher extends FlagWatcher
{
public WitherSkullWatcher(Disguise disguise)
{
super(disguise);
}
public boolean isBlue()
{
return (boolean) getData(MetaIndex.WITHER_SKULL_BLUE);
}
public void setBlue(boolean blue)
{
setData(MetaIndex.WITHER_SKULL_BLUE, blue);
sendData(MetaIndex.WITHER_SKULL_BLUE);
}
}

View File

@@ -0,0 +1,58 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import java.security.InvalidParameterException;
import org.bukkit.ChatColor;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class WitherWatcher extends InsentientWatcher
{
public WitherWatcher(Disguise disguise)
{
super(disguise);
}
/**
* Returns the amount of time this Wither is invulnerable for
*
* @return
*/
public int getInvulnerability()
{
return (int) getData(MetaIndex.WITHER_INVUL);
}
public int[] getTargets()
{
return new int[]
{
getData(MetaIndex.WITHER_TARGET_1), getData(MetaIndex.WITHER_TARGET_2), getData(MetaIndex.WITHER_TARGET_3)
};
}
/**
* Sets the amount of time this Wither is invulnerable for
*/
public void setInvulnerability(int invulnerability)
{
setData(MetaIndex.WITHER_INVUL, invulnerability);
sendData(MetaIndex.WITHER_INVUL);
}
public void setTargets(int... targets)
{
if (targets.length != 3)
{
throw new InvalidParameterException(
ChatColor.RED + "Expected 3 numbers for wither setTargets. Received " + targets.length);
}
setData(MetaIndex.WITHER_TARGET_1, targets[0]);
setData(MetaIndex.WITHER_TARGET_2, targets[1]);
setData(MetaIndex.WITHER_TARGET_3, targets[2]);
sendData(MetaIndex.WITHER_TARGET_1, MetaIndex.WITHER_TARGET_2, MetaIndex.WITHER_TARGET_3);
}
}

View File

@@ -0,0 +1,85 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import org.bukkit.DyeColor;
import me.libraryaddict.disguise.disguisetypes.AnimalColor;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class WolfWatcher extends TameableWatcher
{
public WolfWatcher(Disguise disguise)
{
super(disguise);
}
public AnimalColor getCollarColor()
{
return AnimalColor.getColor(getData(MetaIndex.WOLF_COLLAR));
}
/**
* Used for tail rotation.
*
* @return
*/
public float getDamageTaken()
{
return (float) getData(MetaIndex.WOLF_DAMAGE);
}
/**
* Used for tail rotation.
*
* @param damage
*/
public void setDamageTaken(float damage)
{
setData(MetaIndex.WOLF_DAMAGE, damage);
sendData(MetaIndex.WOLF_DAMAGE);
}
public boolean isBegging()
{
return (boolean) getData(MetaIndex.WOLF_BEGGING);
}
public void setBegging(boolean begging)
{
setData(MetaIndex.WOLF_BEGGING, begging);
sendData(MetaIndex.WOLF_BEGGING);
}
public boolean isAngry()
{
return isTameableFlag(2);
}
public void setAngry(boolean angry)
{
setTameableFlag(2, angry);
}
public void setCollarColor(AnimalColor color)
{
setCollarColor(DyeColor.getByWoolData((byte) color.getId()));
}
public void setCollarColor(DyeColor newColor)
{
if (!isTamed())
{
setTamed(true);
}
if (newColor.getWoolData() == getCollarColor().getId())
{
return;
}
setData(MetaIndex.WOLF_COLLAR, (int) newColor.getDyeData());
sendData(MetaIndex.WOLF_COLLAR);
}
}

View File

@@ -0,0 +1,11 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
public class ZombieHorseWatcher extends AbstractHorseWatcher {
public ZombieHorseWatcher(Disguise disguise) {
super(disguise);
}
}

View File

@@ -0,0 +1,59 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
import org.bukkit.entity.Villager.Profession;
public class ZombieVillagerWatcher extends ZombieWatcher {
public ZombieVillagerWatcher(Disguise disguise) {
super(disguise);
}
public boolean isShaking() {
return getData(MetaIndex.ZOMBIE_VILLAGER_SHAKING);
}
/**
* Is this zombie a villager?
*
* @return
*/
public boolean isVillager() {
return ((int) getData(MetaIndex.ZOMBIE_VILLAGER_PROFESSION)) != 0;
}
public void setShaking(boolean shaking) {
setData(MetaIndex.ZOMBIE_VILLAGER_SHAKING, shaking);
sendData(MetaIndex.ZOMBIE_VILLAGER_SHAKING);
}
/**
* Only returns a valid value if this zombie is a villager.
*
* @return
*/
public Profession getProfession() {
return Profession.values()[getData(MetaIndex.ZOMBIE_VILLAGER_PROFESSION) + 1];
}
/**
* Sets the profession of this zombie, in turn turning it into a Zombie Villager
*
* @param id
*/
@Deprecated
public void setProfession(int id) {
setData(MetaIndex.ZOMBIE_VILLAGER_PROFESSION, id);
sendData(MetaIndex.ZOMBIE_VILLAGER_PROFESSION);
}
/**
* Sets the profession of this zombie, in turn turning it into a Zombie Villager
*
* @param profession
*/
public void setProfession(Profession profession) {
setProfession(profession.ordinal() - 1);
}
}

View File

@@ -0,0 +1,50 @@
package me.libraryaddict.disguise.disguisetypes.watchers;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.MetaIndex;
public class ZombieWatcher extends InsentientWatcher {
public ZombieWatcher(Disguise disguise) {
super(disguise);
}
public boolean isAdult() {
return !isBaby();
}
public boolean isBaby() {
return getData(MetaIndex.ZOMBIE_BABY);
}
public boolean isAggressive() {
return (boolean) getData(MetaIndex.ZOMBIE_AGGRESSIVE);
}
public void setAdult() {
setBaby(false);
}
public void setBaby() {
setBaby(true);
}
public void setBaby(boolean baby) {
setData(MetaIndex.ZOMBIE_BABY, baby);
sendData(MetaIndex.ZOMBIE_BABY);
}
public void setAggressive(boolean handsup) {
setData(MetaIndex.ZOMBIE_AGGRESSIVE, handsup);
sendData(MetaIndex.ZOMBIE_AGGRESSIVE);
}
public boolean isConverting() {
return getData(MetaIndex.ZOMBIE_CONVERTING_DROWNED);
}
public void setConverting(boolean converting) {
setData(MetaIndex.ZOMBIE_CONVERTING_DROWNED, converting);
sendData(MetaIndex.ZOMBIE_CONVERTING_DROWNED);
}
}

Some files were not shown because too many files have changed in this diff Show More