Merge remote-tracking branch 'origin/master' into foo

This commit is contained in:
fooify 2015-11-28 09:33:47 -08:00
commit 8cdae7ce1a
581 changed files with 42710 additions and 5509 deletions

1
.gitignore vendored
View File

@ -51,3 +51,4 @@ zSotanna2
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/segments.gen
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/segments_1
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/write.lock
/Pocket

BIN
Art/MS SMoke.psd Normal file

Binary file not shown.

View File

@ -18,6 +18,9 @@
<element id="file-copy" path="$PROJECT_DIR$/Mineplex.Game.Clans/plugin.yml" />
<element id="module-output" name="Mineplex.ServerData" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/jooq-3.5.2.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/commons-dbcp2-2.0.1.jar" path-in-jar="/" />
<element id="module-output" name="Mineplex.Game.Clans.Core" />
<element id="module-output" name="Mineplex.PlayerCache" />
</root>
</artifact>
</component>

View File

@ -21,6 +21,7 @@
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/jooq-3.5.2.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/commons-dbcp2-2.0.1.jar" path-in-jar="/" />
<element id="module-output" name="Mineplex.PlayerCache" />
<element id="module-output" name="Mineplex.Game.Clans.Core" />
</root>
</artifact>
</component>

View File

@ -7,6 +7,14 @@
<option name="STATIC_FIELD_NAME_PREFIX" value="_" />
<option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="20" />
<option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="10" />
<option name="PACKAGES_TO_USE_IMPORT_ON_DEMAND">
<value>
<package name="java.awt" withSubpackages="false" static="false" />
<package name="org.jooq.impl.DSL" withSubpackages="false" static="true" />
<package name="mineplex.database.Tables" withSubpackages="false" static="true" />
<package name="javax.swing" withSubpackages="false" static="false" />
</value>
</option>
<option name="IMPORT_LAYOUT_TABLE">
<value>
<package name="javax" withSubpackages="true" static="false" />

View File

@ -5,7 +5,6 @@
<excludeFromCompile>
<directory url="file://$PROJECT_DIR$/Nautilus.Game.PvP" includeSubdirectories="true" />
<directory url="file://$PROJECT_DIR$/Mineplex.ServerMonitor" includeSubdirectories="true" />
<directory url="file://$PROJECT_DIR$/Mineplex.Game.Clans" includeSubdirectories="true" />
</excludeFromCompile>
<resourceExtensions />
<wildcardResourcePatterns>
@ -29,9 +28,7 @@
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel target="1.7">
<module name="bungee" target="1.7" />
</bytecodeTargetLevel>
<bytecodeTargetLevel target="1.7" />
</component>
<component name="JavacSettings">
<option name="GENERATE_NO_WARNINGS" value="true" />

View File

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" hash="4268976312">
<component name="DataSourceManagerImpl" format="xml" hash="2876127046">
<data-source source="LOCAL" name="Mineplex" uuid="14dfc55d-5343-47c4-ab24-76a055b8059e">
<driver-ref>mysql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>com.mysql.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://db.mineplex.com:3306</jdbc-url>
<jdbc-url>jdbc:mysql://db.mineplex.com:3306/Account</jdbc-url>
<driver-properties>
<property name="zeroDateTimeBehavior" value="convertToNull" />
<property name="tinyInt1isBit" value="false" />

View File

@ -4,7 +4,7 @@
<root url="jar://$PROJECT_DIR$/Libraries/craftbukkit.jar!/" />
</CLASSES>
<JAVADOC>
<root url="http://jd.bukkit.org/dev/apidocs/" />
<root url="https://hub.spigotmc.org/javadocs/spigot/" />
</JAVADOC>
<SOURCES>
<root url="jar://$PROJECT_DIR$/Libraries/craftbukkit.jar!/" />

View File

@ -16,7 +16,7 @@
</set>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="false" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -3,21 +3,23 @@
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Classpath.Dummy/Classpath.Dummy.iml" filepath="$PROJECT_DIR$/Classpath.Dummy/Classpath.Dummy.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/JedisTest/JedisTest.iml" filepath="$PROJECT_DIR$/JedisTest/JedisTest.iml" />
<module fileurl="file://$PROJECT_DIR$/JedisTest/JedisTest.iml" filepath="$PROJECT_DIR$/JedisTest/JedisTest.iml" group="Legacy" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Bungee.Mineplexer/Mineplex.Bungee.Mineplexer.iml" filepath="$PROJECT_DIR$/Mineplex.Bungee.Mineplexer/Mineplex.Bungee.Mineplexer.iml" group="Bungee" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Core/Mineplex.Core.iml" filepath="$PROJECT_DIR$/Mineplex.Core/Mineplex.Core.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Core.Common/Mineplex.Core.Common.iml" filepath="$PROJECT_DIR$/Mineplex.Core.Common/Mineplex.Core.Common.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Database/Mineplex.Database.iml" filepath="$PROJECT_DIR$/Mineplex.Database/Mineplex.Database.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Game.Clans/Mineplex.Game.Clans.iml" filepath="$PROJECT_DIR$/Mineplex.Game.Clans/Mineplex.Game.Clans.iml" group="Game" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Game.Clans.Core/Mineplex.Game.Clans.Core.iml" filepath="$PROJECT_DIR$/Mineplex.Game.Clans.Core/Mineplex.Game.Clans.Core.iml" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Hub/Mineplex.Hub.iml" filepath="$PROJECT_DIR$/Mineplex.Hub/Mineplex.Hub.iml" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.MapParser/Mineplex.MapParser.iml" filepath="$PROJECT_DIR$/Mineplex.MapParser/Mineplex.MapParser.iml" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Minecraft.Game.ClassCombat/Mineplex.Minecraft.Game.ClassCombat.iml" filepath="$PROJECT_DIR$/Mineplex.Minecraft.Game.ClassCombat/Mineplex.Minecraft.Game.ClassCombat.iml" group="Game" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Minecraft.Game.Core/Mineplex.Minecraft.Game.Core.iml" filepath="$PROJECT_DIR$/Mineplex.Minecraft.Game.Core/Mineplex.Minecraft.Game.Core.iml" group="Game" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.PlayerCache/Mineplex.PlayerCache.iml" filepath="$PROJECT_DIR$/Mineplex.PlayerCache/Mineplex.PlayerCache.iml" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.PlayerCache/Mineplex.PlayerCache.iml" filepath="$PROJECT_DIR$/Mineplex.PlayerCache/Mineplex.PlayerCache.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.ServerData/Mineplex.ServerData.iml" filepath="$PROJECT_DIR$/Mineplex.ServerData/Mineplex.ServerData.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.ServerMonitor/Mineplex.ServerMonitor.iml" filepath="$PROJECT_DIR$/Mineplex.ServerMonitor/Mineplex.ServerMonitor.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Votifier/Mineplex.Votifier.iml" filepath="$PROJECT_DIR$/Mineplex.Votifier/Mineplex.Votifier.iml" />
<module fileurl="file://$PROJECT_DIR$/Nautilus.Game.Arcade/Nautilus.Game.Arcade.iml" filepath="$PROJECT_DIR$/Nautilus.Game.Arcade/Nautilus.Game.Arcade.iml" group="Game" />
<module fileurl="file://$PROJECT_DIR$/Nautilus.Game.PvP/Nautilus.Game.PvP.iml" filepath="$PROJECT_DIR$/Nautilus.Game.PvP/Nautilus.Game.PvP.iml" group="Legacy" />
</modules>
</component>
</project>

View File

@ -149,6 +149,9 @@
<fileset dir="../Mineplex.Minecraft.Game.Core/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.Game.Clans.Core/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.Hub">
<include name="*.yml"/>
</fileset>
@ -189,6 +192,9 @@
<fileset dir="../Mineplex.Core.Common/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.Game.Clans.Core/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.Minecraft.Game.ClassCombat/bin">
<include name="**/*.class"/>
</fileset>

View File

@ -12,5 +12,4 @@
<orderEntry type="library" name="commons-pool2" level="project" />
<orderEntry type="library" name="commons-logging" level="project" />
</component>
</module>
</module>

View File

@ -1,328 +0,0 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.bukkit.command;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.apache.commons.lang.Validate;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.command.FormattedCommandAlias;
import org.bukkit.command.defaults.AchievementCommand;
import org.bukkit.command.defaults.BanCommand;
import org.bukkit.command.defaults.BanIpCommand;
import org.bukkit.command.defaults.BanListCommand;
import org.bukkit.command.defaults.ClearCommand;
import org.bukkit.command.defaults.DefaultGameModeCommand;
import org.bukkit.command.defaults.DeopCommand;
import org.bukkit.command.defaults.DifficultyCommand;
import org.bukkit.command.defaults.EffectCommand;
import org.bukkit.command.defaults.EnchantCommand;
import org.bukkit.command.defaults.ExpCommand;
import org.bukkit.command.defaults.GameModeCommand;
import org.bukkit.command.defaults.GameRuleCommand;
import org.bukkit.command.defaults.GiveCommand;
import org.bukkit.command.defaults.HelpCommand;
import org.bukkit.command.defaults.KickCommand;
import org.bukkit.command.defaults.KillCommand;
import org.bukkit.command.defaults.ListCommand;
import org.bukkit.command.defaults.MeCommand;
import org.bukkit.command.defaults.OpCommand;
import org.bukkit.command.defaults.PardonCommand;
import org.bukkit.command.defaults.PardonIpCommand;
import org.bukkit.command.defaults.PlaySoundCommand;
import org.bukkit.command.defaults.PluginsCommand;
import org.bukkit.command.defaults.ReloadCommand;
import org.bukkit.command.defaults.SaveCommand;
import org.bukkit.command.defaults.SaveOffCommand;
import org.bukkit.command.defaults.SaveOnCommand;
import org.bukkit.command.defaults.SayCommand;
import org.bukkit.command.defaults.ScoreboardCommand;
import org.bukkit.command.defaults.SeedCommand;
import org.bukkit.command.defaults.SetIdleTimeoutCommand;
import org.bukkit.command.defaults.SetWorldSpawnCommand;
import org.bukkit.command.defaults.SpawnpointCommand;
import org.bukkit.command.defaults.SpreadPlayersCommand;
import org.bukkit.command.defaults.StopCommand;
import org.bukkit.command.defaults.TeleportCommand;
import org.bukkit.command.defaults.TellCommand;
import org.bukkit.command.defaults.TestForCommand;
import org.bukkit.command.defaults.TimeCommand;
import org.bukkit.command.defaults.TimingsCommand;
import org.bukkit.command.defaults.ToggleDownfallCommand;
import org.bukkit.command.defaults.VanillaCommand;
import org.bukkit.command.defaults.VersionCommand;
import org.bukkit.command.defaults.WeatherCommand;
import org.bukkit.command.defaults.WhitelistCommand;
import org.bukkit.entity.Player;
import org.bukkit.event.TabCompleteEvent;
import org.bukkit.util.Java15Compat;
import org.bukkit.util.StringUtil;
public class SimpleCommandMap implements CommandMap {
private static final Pattern PATTERN_ON_SPACE = Pattern.compile(" ", 16);
protected final Map<String, Command> knownCommands = new HashMap<String, Command>();
private final Server server;
public SimpleCommandMap(Server server) {
this.server = server;
this.setDefaultCommands();
}
private void setDefaultCommands() {
this.register("bukkit", new SaveCommand());
this.register("bukkit", new SaveOnCommand());
this.register("bukkit", new SaveOffCommand());
this.register("bukkit", new StopCommand());
this.register("bukkit", new VersionCommand("version"));
this.register("bukkit", new ReloadCommand("reload"));
this.register("bukkit", new PluginsCommand("plugins"));
this.register("bukkit", new TimingsCommand("timings"));
}
public void setFallbackCommands() {
this.register("bukkit", new ListCommand());
this.register("bukkit", new OpCommand());
this.register("bukkit", new DeopCommand());
this.register("bukkit", new BanIpCommand());
this.register("bukkit", new PardonIpCommand());
this.register("bukkit", new BanCommand());
this.register("bukkit", new PardonCommand());
this.register("bukkit", new KickCommand());
this.register("bukkit", new TeleportCommand());
this.register("bukkit", new GiveCommand());
this.register("bukkit", new TimeCommand());
this.register("bukkit", new SayCommand());
this.register("bukkit", new WhitelistCommand());
this.register("bukkit", new TellCommand());
this.register("bukkit", new MeCommand());
this.register("bukkit", new KillCommand());
this.register("bukkit", new GameModeCommand());
this.register("bukkit", new HelpCommand());
this.register("bukkit", new ExpCommand());
this.register("bukkit", new ToggleDownfallCommand());
this.register("bukkit", new BanListCommand());
this.register("bukkit", new DefaultGameModeCommand());
this.register("bukkit", new SeedCommand());
this.register("bukkit", new DifficultyCommand());
this.register("bukkit", new WeatherCommand());
this.register("bukkit", new SpawnpointCommand());
this.register("bukkit", new ClearCommand());
this.register("bukkit", new GameRuleCommand());
this.register("bukkit", new EnchantCommand());
this.register("bukkit", new TestForCommand());
this.register("bukkit", new EffectCommand());
this.register("bukkit", new ScoreboardCommand());
this.register("bukkit", new PlaySoundCommand());
this.register("bukkit", new SpreadPlayersCommand());
this.register("bukkit", new SetWorldSpawnCommand());
this.register("bukkit", new SetIdleTimeoutCommand());
this.register("bukkit", new AchievementCommand());
}
public void registerAll(String fallbackPrefix, List<Command> commands) {
if(commands != null) {
Iterator var3 = commands.iterator();
while(var3.hasNext()) {
Command c = (Command)var3.next();
this.register(fallbackPrefix, c);
}
}
}
public boolean register(String fallbackPrefix, Command command) {
return this.register(command.getName(), fallbackPrefix, command);
}
public boolean register(String label, String fallbackPrefix, Command command) {
label = label.toLowerCase().trim();
fallbackPrefix = fallbackPrefix.toLowerCase().trim();
boolean registered = this.register(label, command, false, fallbackPrefix);
Iterator iterator = command.getAliases().iterator();
while(iterator.hasNext()) {
if(!this.register((String)iterator.next(), command, true, fallbackPrefix)) {
iterator.remove();
}
}
if(!registered) {
command.setLabel(fallbackPrefix + ":" + label);
}
command.register(this);
return registered;
}
private synchronized boolean register(String label, Command command, boolean isAlias, String fallbackPrefix) {
this.knownCommands.put(fallbackPrefix + ":" + label, command);
if((command instanceof VanillaCommand || isAlias) && this.knownCommands.containsKey(label)) {
return false;
} else {
boolean registered = true;
Command conflict = (Command)this.knownCommands.get(label);
if(conflict != null && conflict.getLabel().equals(label)) {
return false;
} else {
if(!isAlias) {
command.setLabel(label);
}
this.knownCommands.put(label, command);
return registered;
}
}
}
public boolean dispatch(CommandSender sender, String commandLine) throws CommandException {
String[] args = PATTERN_ON_SPACE.split(commandLine);
if(args.length == 0) {
return false;
} else {
String sentCommandLabel = args[0].toLowerCase();
Command target = this.getCommand(sentCommandLabel);
if(target == null) {
return false;
} else {
try {
target.timings.startTiming();
target.execute(sender, sentCommandLabel, (String[])Java15Compat.Arrays_copyOfRange(args, 1, args.length));
target.timings.stopTiming();
return true;
} catch (CommandException var7) {
target.timings.stopTiming();
throw var7;
} catch (Throwable var8) {
target.timings.stopTiming();
throw new CommandException("Unhandled exception executing \'" + commandLine + "\' in " + target, var8);
}
}
}
}
public synchronized void clearCommands() {
Iterator var1 = this.knownCommands.entrySet().iterator();
while(var1.hasNext()) {
Entry entry = (Entry)var1.next();
((Command)entry.getValue()).unregister(this);
}
this.knownCommands.clear();
this.setDefaultCommands();
}
public Command getCommand(String name) {
Command target = (Command)this.knownCommands.get(name.toLowerCase());
return target;
}
public List<String> tabComplete(CommandSender sender, String cmdLine) {
Validate.notNull(sender, "Sender cannot be null");
Validate.notNull(cmdLine, "Command line cannot null");
int spaceIndex = cmdLine.indexOf(32);
String argLine;
if(spaceIndex == -1) {
ArrayList commandName1 = new ArrayList();
Map target1 = this.knownCommands;
argLine = sender instanceof Player?"/":"";
Iterator args1 = target1.entrySet().iterator();
while(args1.hasNext()) {
Entry ex = (Entry)args1.next();
Command command = (Command)ex.getValue();
if(command.testPermissionSilent(sender)) {
String name = (String)ex.getKey();
if(StringUtil.startsWithIgnoreCase(name, cmdLine)) {
commandName1.add(argLine + name);
}
}
}
Collections.sort(commandName1, String.CASE_INSENSITIVE_ORDER);
return commandName1;
} else {
String commandName = cmdLine.substring(0, spaceIndex);
Command target = this.getCommand(commandName);
argLine = cmdLine.substring(spaceIndex + 1, cmdLine.length());
String[] args = PATTERN_ON_SPACE.split(argLine, -1);
TabCompleteEvent event = new TabCompleteEvent(sender, commandName, args);
if (target != null) {
try {
event.getSuggestions().addAll(target.tabComplete(sender, commandName, args));
} catch (CommandException var11) {
throw var11;
} catch (Throwable var12) {
throw new CommandException("Unhandled exception executing tab-completer for \'" + cmdLine + "\' in " + target, var12);
}
}
server.getPluginManager().callEvent(event);
return event.getSuggestions();
}
}
public Collection<Command> getCommands() {
return Collections.unmodifiableCollection(this.knownCommands.values());
}
public void registerServerAliases() {
Map values = this.server.getCommandAliases();
Iterator var2 = values.keySet().iterator();
while(var2.hasNext()) {
String alias = (String)var2.next();
if(!alias.contains(":") && !alias.contains(" ")) {
String[] commandStrings = (String[])values.get(alias);
ArrayList targets = new ArrayList();
StringBuilder bad = new StringBuilder();
String[] var7 = commandStrings;
int var8 = commandStrings.length;
for(int var9 = 0; var9 < var8; ++var9) {
String commandString = var7[var9];
String[] commandArgs = commandString.split(" ");
Command command = this.getCommand(commandArgs[0]);
if(command == null) {
if(bad.length() > 0) {
bad.append(", ");
}
bad.append(commandString);
} else {
targets.add(commandString);
}
}
if(bad.length() > 0) {
this.server.getLogger().warning("Could not register alias " + alias + " because it contains commands that do not exist: " + bad);
} else if(targets.size() > 0) {
this.knownCommands.put(alias.toLowerCase(), new FormattedCommandAlias(alias.toLowerCase(), (String[])targets.toArray(new String[targets.size()])));
} else {
this.knownCommands.remove(alias.toLowerCase());
}
} else {
this.server.getLogger().warning("Could not register alias " + alias + " because it contains illegal characters");
}
}
}
}

View File

@ -1,61 +0,0 @@
package org.bukkit.event;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.CommandSender;
public class TabCompleteEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private CommandSender _sender;
private String _command;
private String[] _args;
private List<String> _suggestions;
public TabCompleteEvent(CommandSender sender, String command, String[] args)
{
_sender = sender;
_command = command;
_args = args;
_suggestions = new ArrayList<String>();
}
public CommandSender getSender()
{
return _sender;
}
public String getCommand()
{
return _command;
}
public String[] getArgs()
{
return _args;
}
public List<String> getSuggestions()
{
return _suggestions;
}
public void setSuggestions(List<String> suggestions)
{
_suggestions = suggestions;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -1,77 +0,0 @@
package org.bukkit.scoreboard;
import java.util.Set;
import org.bukkit.OfflinePlayer;
public abstract interface Team
{
public abstract String getName()
throws IllegalStateException;
public abstract String getDisplayName()
throws IllegalStateException;
public abstract void setDisplayName(String paramString)
throws IllegalStateException, IllegalArgumentException;
public abstract String getPrefix()
throws IllegalStateException;
public abstract void setPrefix(String paramString)
throws IllegalStateException, IllegalArgumentException;
public abstract String getSuffix()
throws IllegalStateException;
public abstract void setSuffix(String paramString)
throws IllegalStateException, IllegalArgumentException;
public abstract boolean allowFriendlyFire()
throws IllegalStateException;
// Mineplex
public abstract void setNameTagVisibility(TeamNameTagVisibility visibility)
throws IllegalStateException;
public abstract void setAllowFriendlyFire(boolean paramBoolean)
throws IllegalStateException;
public abstract boolean canSeeFriendlyInvisibles()
throws IllegalStateException;
public abstract void setCanSeeFriendlyInvisibles(boolean paramBoolean)
throws IllegalStateException;
public abstract Set<OfflinePlayer> getPlayers()
throws IllegalStateException;
public abstract Set<String> getEntries()
throws IllegalStateException;
public abstract int getSize()
throws IllegalStateException;
public abstract Scoreboard getScoreboard();
public abstract void addPlayer(OfflinePlayer paramOfflinePlayer)
throws IllegalStateException, IllegalArgumentException;
public abstract void addEntry(String paramString)
throws IllegalStateException, IllegalArgumentException;
public abstract boolean removePlayer(OfflinePlayer paramOfflinePlayer)
throws IllegalStateException, IllegalArgumentException;
public abstract boolean removeEntry(String paramString)
throws IllegalStateException, IllegalArgumentException;
public abstract void unregister()
throws IllegalStateException;
public abstract boolean hasPlayer(OfflinePlayer paramOfflinePlayer)
throws IllegalArgumentException, IllegalStateException;
public abstract boolean hasEntry(String paramString)
throws IllegalArgumentException, IllegalStateException;
}

View File

@ -1,22 +0,0 @@
package org.bukkit.scoreboard;
/**
* Created by shaun on 14-10-05.
*/
public enum TeamNameTagVisibility
{
NEVER("never"), HIDE_FOR_OTHER_TEAMS("hideForOtherTeams"), HIDE_FOR_OWN_TEAM("hideForOwnTeam"), ALWAYS("always");
private String _keyword;
TeamNameTagVisibility(String keyword)
{
_keyword = keyword;
}
@Override
public String toString()
{
return _keyword;
}
}

Binary file not shown.

View File

@ -0,0 +1,57 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Byte_Array} tag.
*/
public final class ByteArrayTag extends Tag {
private final byte[] value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public ByteArrayTag(byte[] value) {
super();
this.value = value;
}
@Override
public byte[] getValue() {
return value;
}
@Override
public String toString() {
StringBuilder hex = new StringBuilder();
for (byte b : value) {
String hexDigits = Integer.toHexString(b).toUpperCase();
if (hexDigits.length() == 1) {
hex.append("0");
}
hex.append(hexDigits).append(" ");
}
return "TAG_Byte_Array(" + hex + ")";
}
}

View File

@ -0,0 +1,49 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Byte} tag.
*/
public final class ByteTag extends Tag {
private final byte value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public ByteTag(byte value) {
super();
this.value = value;
}
@Override
public Byte getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Byte(" + value + ")";
}
}

View File

@ -0,0 +1,420 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The {@code TAG_Compound} tag.
*/
public final class CompoundTag extends Tag {
private final Map<String, Tag> value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public CompoundTag(Map<String, Tag> value) {
super();
this.value = Collections.unmodifiableMap(value);
}
/**
* Returns whether this compound tag contains the given key.
*
* @param key the given key
* @return true if the tag contains the given key
*/
public boolean containsKey(String key) {
return value.containsKey(key);
}
@Override
public Map<String, Tag> getValue() {
return value;
}
/**
* Return a new compound tag with the given values.
*
* @param value the value
* @return the new compound tag
*/
public CompoundTag setValue(Map<String, Tag> value) {
return new CompoundTag(value);
}
/**
* Create a compound tag builder.
*
* @return the builder
*/
public CompoundTagBuilder createBuilder() {
return new CompoundTagBuilder(new HashMap<String, Tag>(value));
}
/**
* Get a byte array named with the given key.
*
* <p>If the key does not exist or its value is not a byte array tag,
* then an empty byte array will be returned.</p>
*
* @param key the key
* @return a byte array
*/
public byte[] getByteArray(String key) {
Tag tag = value.get(key);
if (tag instanceof ByteArrayTag) {
return ((ByteArrayTag) tag).getValue();
} else {
return new byte[0];
}
}
/**
* Get a byte named with the given key.
*
* <p>If the key does not exist or its value is not a byte tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a byte
*/
public byte getByte(String key) {
Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else {
return (byte) 0;
}
}
/**
* Get a double named with the given key.
*
* <p>If the key does not exist or its value is not a double tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a double
*/
public double getDouble(String key) {
Tag tag = value.get(key);
if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a double named with the given key, even if it's another
* type of number.
*
* <p>If the key does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a double
*/
public double asDouble(String key) {
Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a float named with the given key.
*
* <p>If the key does not exist or its value is not a float tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a float
*/
public float getFloat(String key) {
Tag tag = value.get(key);
if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a {@code int[]} named with the given key.
*
* <p>If the key does not exist or its value is not an int array tag,
* then an empty array will be returned.</p>
*
* @param key the key
* @return an int array
*/
public int[] getIntArray(String key) {
Tag tag = value.get(key);
if (tag instanceof IntArrayTag) {
return ((IntArrayTag) tag).getValue();
} else {
return new int[0];
}
}
/**
* Get an int named with the given key.
*
* <p>If the key does not exist or its value is not an int tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return an int
*/
public int getInt(String key) {
Tag tag = value.get(key);
if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get an int named with the given key, even if it's another
* type of number.
*
* <p>If the key does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return an int
*/
public int asInt(String key) {
Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue().intValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().intValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().intValue();
} else {
return 0;
}
}
/**
* Get a list of tags named with the given key.
*
* <p>If the key does not exist or its value is not a list tag,
* then an empty list will be returned.</p>
*
* @param key the key
* @return a list of tags
*/
public List<Tag> getList(String key) {
Tag tag = value.get(key);
if (tag instanceof ListTag) {
return ((ListTag) tag).getValue();
} else {
return Collections.emptyList();
}
}
/**
* Get a {@code TagList} named with the given key.
*
* <p>If the key does not exist or its value is not a list tag,
* then an empty tag list will be returned.</p>
*
* @param key the key
* @return a tag list instance
*/
public ListTag getListTag(String key) {
Tag tag = value.get(key);
if (tag instanceof ListTag) {
return (ListTag) tag;
} else {
return new ListTag(StringTag.class, Collections.<Tag>emptyList());
}
}
/**
* Get a list of tags named with the given key.
*
* <p>If the key does not exist or its value is not a list tag,
* then an empty list will be returned. If the given key references
* a list but the list of of a different type, then an empty
* list will also be returned.</p>
*
* @param key the key
* @param listType the class of the contained type
* @return a list of tags
* @param <T> the type of list
*/
@SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(String key, Class<T> listType) {
Tag tag = value.get(key);
if (tag instanceof ListTag) {
ListTag listTag = (ListTag) tag;
if (listTag.getType().equals(listType)) {
return (List<T>) listTag.getValue();
} else {
return Collections.emptyList();
}
} else {
return Collections.emptyList();
}
}
/**
* Get a long named with the given key.
*
* <p>If the key does not exist or its value is not a long tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a long
*/
public long getLong(String key) {
Tag tag = value.get(key);
if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else {
return 0L;
}
}
/**
* Get a long named with the given key, even if it's another
* type of number.
*
* <p>If the key does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a long
*/
public long asLong(String key) {
Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().longValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().longValue();
} else {
return 0L;
}
}
/**
* Get a short named with the given key.
*
* <p>If the key does not exist or its value is not a short tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a short
*/
public short getShort(String key) {
Tag tag = value.get(key);
if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a string named with the given key.
*
* <p>If the key does not exist or its value is not a string tag,
* then {@code ""} will be returned.</p>
*
* @param key the key
* @return a string
*/
public String getString(String key) {
Tag tag = value.get(key);
if (tag instanceof StringTag) {
return ((StringTag) tag).getValue();
} else {
return "";
}
}
@Override
public String toString() {
StringBuilder bldr = new StringBuilder();
bldr.append("TAG_Compound").append(": ").append(value.size()).append(" entries\r\n{\r\n");
for (Map.Entry<String, Tag> entry : value.entrySet()) {
bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
}
bldr.append("}");
return bldr.toString();
}
}

View File

@ -0,0 +1,204 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.util.HashMap;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Helps create compound tags.
*/
public class CompoundTagBuilder {
private final Map<String, Tag> entries;
/**
* Create a new instance.
*/
CompoundTagBuilder() {
this.entries = new HashMap<String, Tag>();
}
/**
* Create a new instance and use the given map (which will be modified).
*
* @param value the value
*/
CompoundTagBuilder(Map<String, Tag> value) {
checkNotNull(value);
this.entries = value;
}
/**
* Put the given key and tag into the compound tag.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder put(String key, Tag value) {
checkNotNull(key);
checkNotNull(value);
entries.put(key, value);
return this;
}
/**
* Put the given key and value into the compound tag as a
* {@code ByteArrayTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putByteArray(String key, byte[] value) {
return put(key, new ByteArrayTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code ByteTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putByte(String key, byte value) {
return put(key, new ByteTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code DoubleTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putDouble(String key, double value) {
return put(key, new DoubleTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code FloatTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putFloat(String key, float value) {
return put(key, new FloatTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code IntArrayTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putIntArray(String key, int[] value) {
return put(key, new IntArrayTag(value));
}
/**
* Put the given key and value into the compound tag as an {@code IntTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putInt(String key, int value) {
return put(key, new IntTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code LongTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putLong(String key, long value) {
return put(key, new LongTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code ShortTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putShort(String key, short value) {
return put(key, new ShortTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code StringTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putString(String key, String value) {
return put(key, new StringTag(value));
}
/**
* Put all the entries from the given map into this map.
*
* @param value the map of tags
* @return this object
*/
public CompoundTagBuilder putAll(Map<String, ? extends Tag> value) {
checkNotNull(value);
for (Map.Entry<String, ? extends Tag> entry : value.entrySet()) {
put(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Build an unnamed compound tag with this builder's entries.
*
* @return the new compound tag
*/
public CompoundTag build() {
return new CompoundTag(new HashMap<String, Tag>(entries));
}
/**
* Create a new builder instance.
*
* @return a new builder
*/
public static CompoundTagBuilder create() {
return new CompoundTagBuilder();
}
}

View File

@ -0,0 +1,50 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Double} tag.
*
*/
public final class DoubleTag extends Tag {
private final double value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public DoubleTag(double value) {
super();
this.value = value;
}
@Override
public Double getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Double(" + value + ")";
}
}

View File

@ -0,0 +1,37 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_End} tag.
*/
public final class EndTag extends Tag {
@Override
public Object getValue() {
return null;
}
@Override
public String toString() {
return "TAG_End";
}
}

View File

@ -0,0 +1,49 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Float} tag.
*/
public final class FloatTag extends Tag {
private final float value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public FloatTag(float value) {
super();
this.value = value;
}
@Override
public Float getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Float(" + value + ")";
}
}

View File

@ -0,0 +1,60 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_Int_Array} tag.
*/
public final class IntArrayTag extends Tag {
private final int[] value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public IntArrayTag(int[] value) {
super();
checkNotNull(value);
this.value = value;
}
@Override
public int[] getValue() {
return value;
}
@Override
public String toString() {
StringBuilder hex = new StringBuilder();
for (int b : value) {
String hexDigits = Integer.toHexString(b).toUpperCase();
if (hexDigits.length() == 1) {
hex.append("0");
}
hex.append(hexDigits).append(" ");
}
return "TAG_Int_Array(" + hex + ")";
}
}

View File

@ -0,0 +1,49 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Int} tag.
*/
public final class IntTag extends Tag {
private final int value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public IntTag(int value) {
super();
this.value = value;
}
@Override
public Integer getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Int(" + value + ")";
}
}

View File

@ -0,0 +1,431 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_List} tag.
*/
public final class ListTag extends Tag {
private final Class<? extends Tag> type;
private final List<Tag> value;
/**
* Creates the tag with an empty name.
*
* @param type the type of tag
* @param value the value of the tag
*/
public ListTag(Class<? extends Tag> type, List<? extends Tag> value) {
super();
checkNotNull(value);
this.type = type;
this.value = Collections.unmodifiableList(value);
}
/**
* Gets the type of item in this list.
*
* @return The type of item in this list.
*/
public Class<? extends Tag> getType() {
return type;
}
@Override
public List<Tag> getValue() {
return value;
}
/**
* Create a new list tag with this tag's name and type.
*
* @param list the new list
* @return a new list tag
*/
public ListTag setValue(List<Tag> list) {
return new ListTag(getType(), list);
}
/**
* Get the tag if it exists at the given index.
*
* @param index the index
* @return the tag or null
*/
@Nullable
public Tag getIfExists(int index) {
try {
return value.get(index);
} catch (NoSuchElementException e) {
return null;
}
}
/**
* Get a byte array named with the given index.
*
* <p>If the index does not exist or its value is not a byte array tag,
* then an empty byte array will be returned.</p>
*
* @param index the index
* @return a byte array
*/
public byte[] getByteArray(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ByteArrayTag) {
return ((ByteArrayTag) tag).getValue();
} else {
return new byte[0];
}
}
/**
* Get a byte named with the given index.
*
* <p>If the index does not exist or its value is not a byte tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a byte
*/
public byte getByte(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else {
return (byte) 0;
}
}
/**
* Get a double named with the given index.
*
* <p>If the index does not exist or its value is not a double tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a double
*/
public double getDouble(int index) {
Tag tag = getIfExists(index);
if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a double named with the given index, even if it's another
* type of number.
*
* <p>If the index does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a double
*/
public double asDouble(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a float named with the given index.
*
* <p>If the index does not exist or its value is not a float tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a float
*/
public float getFloat(int index) {
Tag tag = getIfExists(index);
if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a {@code int[]} named with the given index.
*
* <p>If the index does not exist or its value is not an int array tag,
* then an empty array will be returned.</p>
*
* @param index the index
* @return an int array
*/
public int[] getIntArray(int index) {
Tag tag = getIfExists(index);
if (tag instanceof IntArrayTag) {
return ((IntArrayTag) tag).getValue();
} else {
return new int[0];
}
}
/**
* Get an int named with the given index.
*
* <p>If the index does not exist or its value is not an int tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return an int
*/
public int getInt(int index) {
Tag tag = getIfExists(index);
if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get an int named with the given index, even if it's another
* type of number.
*
* <p>If the index does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return an int
*/
public int asInt(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue().intValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().intValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().intValue();
} else {
return 0;
}
}
/**
* Get a list of tags named with the given index.
*
* <p>If the index does not exist or its value is not a list tag,
* then an empty list will be returned.</p>
*
* @param index the index
* @return a list of tags
*/
public List<Tag> getList(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ListTag) {
return ((ListTag) tag).getValue();
} else {
return Collections.emptyList();
}
}
/**
* Get a {@code TagList} named with the given index.
*
* <p>If the index does not exist or its value is not a list tag,
* then an empty tag list will be returned.</p>
*
* @param index the index
* @return a tag list instance
*/
public ListTag getListTag(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ListTag) {
return (ListTag) tag;
} else {
return new ListTag(StringTag.class, Collections.<Tag>emptyList());
}
}
/**
* Get a list of tags named with the given index.
*
* <p>If the index does not exist or its value is not a list tag,
* then an empty list will be returned. If the given index references
* a list but the list of of a different type, then an empty
* list will also be returned.</p>
*
* @param index the index
* @param listType the class of the contained type
* @return a list of tags
* @param <T> the NBT type
*/
@SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(int index, Class<T> listType) {
Tag tag = getIfExists(index);
if (tag instanceof ListTag) {
ListTag listTag = (ListTag) tag;
if (listTag.getType().equals(listType)) {
return (List<T>) listTag.getValue();
} else {
return Collections.emptyList();
}
} else {
return Collections.emptyList();
}
}
/**
* Get a long named with the given index.
*
* <p>If the index does not exist or its value is not a long tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a long
*/
public long getLong(int index) {
Tag tag = getIfExists(index);
if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else {
return 0L;
}
}
/**
* Get a long named with the given index, even if it's another
* type of number.
*
* <p>If the index does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a long
*/
public long asLong(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().longValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().longValue();
} else {
return 0;
}
}
/**
* Get a short named with the given index.
*
* <p>If the index does not exist or its value is not a short tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a short
*/
public short getShort(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a string named with the given index.
*
* <p>If the index does not exist or its value is not a string tag,
* then {@code ""} will be returned.</p>
*
* @param index the index
* @return a string
*/
public String getString(int index) {
Tag tag = getIfExists(index);
if (tag instanceof StringTag) {
return ((StringTag) tag).getValue();
} else {
return "";
}
}
@Override
public String toString() {
StringBuilder bldr = new StringBuilder();
bldr.append("TAG_List").append(": ").append(value.size()).append(" entries of type ").append(NBTUtils.getTypeName(type)).append("\r\n{\r\n");
for (Tag t : value) {
bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
}
bldr.append("}");
return bldr.toString();
}
}

View File

@ -0,0 +1,119 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Helps create list tags.
*/
public class ListTagBuilder {
private final Class<? extends Tag> type;
private final List<Tag> entries;
/**
* Create a new instance.
*
* @param type of tag contained in this list
*/
ListTagBuilder(Class<? extends Tag> type) {
checkNotNull(type);
this.type = type;
this.entries = new ArrayList<Tag>();
}
/**
* Add the given tag.
*
* @param value the tag
* @return this object
*/
public ListTagBuilder add(Tag value) {
checkNotNull(value);
if (!type.isInstance(value)) {
throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + type.getCanonicalName());
}
entries.add(value);
return this;
}
/**
* Add all the tags in the given list.
*
* @param value a list of tags
* @return this object
*/
public ListTagBuilder addAll(Collection<? extends Tag> value) {
checkNotNull(value);
for (Tag v : value) {
add(v);
}
return this;
}
/**
* Build an unnamed list tag with this builder's entries.
*
* @return the new list tag
*/
public ListTag build() {
return new ListTag(type, new ArrayList<Tag>(entries));
}
/**
* Create a new builder instance.
*
* @return a new builder
*/
public static ListTagBuilder create(Class<? extends Tag> type) {
return new ListTagBuilder(type);
}
/**
* Create a new builder instance.
*
* @return a new builder
*/
public static <T extends Tag> ListTagBuilder createWith(T ... entries) {
checkNotNull(entries);
if (entries.length == 0) {
throw new IllegalArgumentException("This method needs an array of at least one entry");
}
Class<? extends Tag> type = entries[0].getClass();
for (int i = 1; i < entries.length; i++) {
if (!type.isInstance(entries[i])) {
throw new IllegalArgumentException("An array of different tag types was provided");
}
}
ListTagBuilder builder = new ListTagBuilder(type);
builder.addAll(Arrays.asList(entries));
return builder;
}
}

View File

@ -0,0 +1,50 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Long} tag.
*
*/
public final class LongTag extends Tag {
private final long value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public LongTag(long value) {
super();
this.value = value;
}
@Override
public Long getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Long(" + value + ")";
}
}

View File

@ -0,0 +1,81 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.nio.charset.Charset;
/**
* A class which holds constant values.
*/
public final class NBTConstants {
public static final Charset CHARSET = Charset.forName("UTF-8");
public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2,
TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6,
TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9,
TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11;
/**
* Default private constructor.
*/
private NBTConstants() {
}
/**
* Convert a type ID to its corresponding {@link Tag} class.
*
* @param id type ID
* @return tag class
* @throws IllegalArgumentException thrown if the tag ID is not valid
*/
public static Class<? extends Tag> getClassFromType(int id) {
switch (id) {
case TYPE_END:
return EndTag.class;
case TYPE_BYTE:
return ByteTag.class;
case TYPE_SHORT:
return ShortTag.class;
case TYPE_INT:
return IntTag.class;
case TYPE_LONG:
return LongTag.class;
case TYPE_FLOAT:
return FloatTag.class;
case TYPE_DOUBLE:
return DoubleTag.class;
case TYPE_BYTE_ARRAY:
return ByteArrayTag.class;
case TYPE_STRING:
return StringTag.class;
case TYPE_LIST:
return ListTag.class;
case TYPE_COMPOUND:
return CompoundTag.class;
case TYPE_INT_ARRAY:
return IntArrayTag.class;
default:
throw new IllegalArgumentException("Unknown tag type ID of " + id);
}
}
}

View File

@ -0,0 +1,171 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class reads <strong>NBT</strong>, or <strong>Named Binary Tag</strong>
* streams, and produces an object graph of subclasses of the {@code Tag}
* object.
*
* <p>The NBT format was created by Markus Persson, and the specification may be
* found at <a href="http://www.minecraft.net/docs/NBT.txt">
* http://www.minecraft.net/docs/NBT.txt</a>.</p>
*/
public final class NBTInputStream implements Closeable {
private final DataInputStream is;
/**
* Creates a new {@code NBTInputStream}, which will source its data
* from the specified input stream.
*
* @param is the input stream
* @throws IOException if an I/O error occurs
*/
public NBTInputStream(InputStream is) throws IOException {
this.is = new DataInputStream(is);
}
/**
* Reads an NBT tag from the stream.
*
* @return The tag that was read.
* @throws IOException if an I/O error occurs.
*/
public NamedTag readNamedTag() throws IOException {
return readNamedTag(0);
}
/**
* Reads an NBT from the stream.
*
* @param depth the depth of this tag
* @return The tag that was read.
* @throws IOException if an I/O error occurs.
*/
private NamedTag readNamedTag(int depth) throws IOException {
int type = is.readByte() & 0xFF;
String name;
if (type != NBTConstants.TYPE_END) {
int nameLength = is.readShort() & 0xFFFF;
byte[] nameBytes = new byte[nameLength];
is.readFully(nameBytes);
name = new String(nameBytes, NBTConstants.CHARSET);
} else {
name = "";
}
return new NamedTag(name, readTagPayload(type, depth));
}
/**
* Reads the payload of a tag given the type.
*
* @param type the type
* @param depth the depth
* @return the tag
* @throws IOException if an I/O error occurs.
*/
private Tag readTagPayload(int type, int depth) throws IOException {
switch (type) {
case NBTConstants.TYPE_END:
if (depth == 0) {
throw new IOException(
"TAG_End found without a TAG_Compound/TAG_List tag preceding it.");
} else {
return new EndTag();
}
case NBTConstants.TYPE_BYTE:
return new ByteTag(is.readByte());
case NBTConstants.TYPE_SHORT:
return new ShortTag(is.readShort());
case NBTConstants.TYPE_INT:
return new IntTag(is.readInt());
case NBTConstants.TYPE_LONG:
return new LongTag(is.readLong());
case NBTConstants.TYPE_FLOAT:
return new FloatTag(is.readFloat());
case NBTConstants.TYPE_DOUBLE:
return new DoubleTag(is.readDouble());
case NBTConstants.TYPE_BYTE_ARRAY:
int length = is.readInt();
byte[] bytes = new byte[length];
is.readFully(bytes);
return new ByteArrayTag(bytes);
case NBTConstants.TYPE_STRING:
length = is.readShort();
bytes = new byte[length];
is.readFully(bytes);
return new StringTag(new String(bytes, NBTConstants.CHARSET));
case NBTConstants.TYPE_LIST:
int childType = is.readByte();
length = is.readInt();
List<Tag> tagList = new ArrayList<Tag>();
for (int i = 0; i < length; ++i) {
Tag tag = readTagPayload(childType, depth + 1);
if (tag instanceof EndTag) {
throw new IOException("TAG_End not permitted in a list.");
}
tagList.add(tag);
}
return new ListTag(NBTUtils.getTypeClass(childType), tagList);
case NBTConstants.TYPE_COMPOUND:
Map<String, Tag> tagMap = new HashMap<String, Tag>();
while (true) {
NamedTag namedTag = readNamedTag(depth + 1);
Tag tag = namedTag.getTag();
if (tag instanceof EndTag) {
break;
} else {
tagMap.put(namedTag.getName(), tag);
}
}
return new CompoundTag(tagMap);
case NBTConstants.TYPE_INT_ARRAY:
length = is.readInt();
int[] data = new int[length];
for (int i = 0; i < length; i++) {
data[i] = is.readInt();
}
return new IntArrayTag(data);
default:
throw new IOException("Invalid tag type: " + type + ".");
}
}
@Override
public void close() throws IOException {
is.close();
}
}

View File

@ -0,0 +1,294 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* This class writes <strong>NBT</strong>, or <strong>Named Binary Tag</strong>
* {@code Tag} objects to an underlying {@code OutputStream}.
*
* <p>The NBT format was created by Markus Persson, and the specification may be
* found at <a href="http://www.minecraft.net/docs/NBT.txt">
* http://www.minecraft.net/docs/NBT.txt</a>.</p>
*/
public final class NBTOutputStream implements Closeable {
/**
* The output stream.
*/
private final DataOutputStream os;
/**
* Creates a new {@code NBTOutputStream}, which will write data to the
* specified underlying output stream.
*
* @param os
* The output stream.
* @throws IOException
* if an I/O error occurs.
*/
public NBTOutputStream(OutputStream os) throws IOException {
this.os = new DataOutputStream(os);
}
/**
* Writes a tag.
*
* @param tag
* The tag to write.
* @throws IOException
* if an I/O error occurs.
*/
public void writeNamedTag(String name, Tag tag) throws IOException {
checkNotNull(name);
checkNotNull(tag);
int type = NBTUtils.getTypeCode(tag.getClass());
byte[] nameBytes = name.getBytes(NBTConstants.CHARSET);
os.writeByte(type);
os.writeShort(nameBytes.length);
os.write(nameBytes);
if (type == NBTConstants.TYPE_END) {
throw new IOException("Named TAG_End not permitted.");
}
writeTagPayload(tag);
}
/**
* Writes tag payload.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeTagPayload(Tag tag) throws IOException {
int type = NBTUtils.getTypeCode(tag.getClass());
switch (type) {
case NBTConstants.TYPE_END:
writeEndTagPayload((EndTag) tag);
break;
case NBTConstants.TYPE_BYTE:
writeByteTagPayload((ByteTag) tag);
break;
case NBTConstants.TYPE_SHORT:
writeShortTagPayload((ShortTag) tag);
break;
case NBTConstants.TYPE_INT:
writeIntTagPayload((IntTag) tag);
break;
case NBTConstants.TYPE_LONG:
writeLongTagPayload((LongTag) tag);
break;
case NBTConstants.TYPE_FLOAT:
writeFloatTagPayload((FloatTag) tag);
break;
case NBTConstants.TYPE_DOUBLE:
writeDoubleTagPayload((DoubleTag) tag);
break;
case NBTConstants.TYPE_BYTE_ARRAY:
writeByteArrayTagPayload((ByteArrayTag) tag);
break;
case NBTConstants.TYPE_STRING:
writeStringTagPayload((StringTag) tag);
break;
case NBTConstants.TYPE_LIST:
writeListTagPayload((ListTag) tag);
break;
case NBTConstants.TYPE_COMPOUND:
writeCompoundTagPayload((CompoundTag) tag);
break;
case NBTConstants.TYPE_INT_ARRAY:
writeIntArrayTagPayload((IntArrayTag) tag);
break;
default:
throw new IOException("Invalid tag type: " + type + ".");
}
}
/**
* Writes a {@code TAG_Byte} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeByteTagPayload(ByteTag tag) throws IOException {
os.writeByte(tag.getValue());
}
/**
* Writes a {@code TAG_Byte_Array} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeByteArrayTagPayload(ByteArrayTag tag) throws IOException {
byte[] bytes = tag.getValue();
os.writeInt(bytes.length);
os.write(bytes);
}
/**
* Writes a {@code TAG_Compound} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeCompoundTagPayload(CompoundTag tag) throws IOException {
for (Map.Entry<String, Tag> entry : tag.getValue().entrySet()) {
writeNamedTag(entry.getKey(), entry.getValue());
}
os.writeByte((byte) 0); // end tag - better way?
}
/**
* Writes a {@code TAG_List} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeListTagPayload(ListTag tag) throws IOException {
Class<? extends Tag> clazz = tag.getType();
List<Tag> tags = tag.getValue();
int size = tags.size();
os.writeByte(NBTUtils.getTypeCode(clazz));
os.writeInt(size);
for (Tag tag1 : tags) {
writeTagPayload(tag1);
}
}
/**
* Writes a {@code TAG_String} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeStringTagPayload(StringTag tag) throws IOException {
byte[] bytes = tag.getValue().getBytes(NBTConstants.CHARSET);
os.writeShort(bytes.length);
os.write(bytes);
}
/**
* Writes a {@code TAG_Double} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeDoubleTagPayload(DoubleTag tag) throws IOException {
os.writeDouble(tag.getValue());
}
/**
* Writes a {@code TAG_Float} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeFloatTagPayload(FloatTag tag) throws IOException {
os.writeFloat(tag.getValue());
}
/**
* Writes a {@code TAG_Long} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeLongTagPayload(LongTag tag) throws IOException {
os.writeLong(tag.getValue());
}
/**
* Writes a {@code TAG_Int} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeIntTagPayload(IntTag tag) throws IOException {
os.writeInt(tag.getValue());
}
/**
* Writes a {@code TAG_Short} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeShortTagPayload(ShortTag tag) throws IOException {
os.writeShort(tag.getValue());
}
/**
* Writes a {@code TAG_Empty} tag.
*
* @param tag the tag
*/
private void writeEndTagPayload(EndTag tag) {
/* empty */
}
private void writeIntArrayTagPayload(IntArrayTag tag) throws IOException {
int[] data = tag.getValue();
os.writeInt(data.length);
for (int aData : data) {
os.writeInt(aData);
}
}
@Override
public void close() throws IOException {
os.close();
}
}

View File

@ -0,0 +1,170 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.util.Map;
/**
* A class which contains NBT-related utility methods.
*
*/
public final class NBTUtils {
/**
* Default private constructor.
*/
private NBTUtils() {
}
/**
* Gets the type name of a tag.
*
* @param clazz the tag class
* @return The type name.
*/
public static String getTypeName(Class<? extends Tag> clazz) {
if (clazz.equals(ByteArrayTag.class)) {
return "TAG_Byte_Array";
} else if (clazz.equals(ByteTag.class)) {
return "TAG_Byte";
} else if (clazz.equals(CompoundTag.class)) {
return "TAG_Compound";
} else if (clazz.equals(DoubleTag.class)) {
return "TAG_Double";
} else if (clazz.equals(EndTag.class)) {
return "TAG_End";
} else if (clazz.equals(FloatTag.class)) {
return "TAG_Float";
} else if (clazz.equals(IntTag.class)) {
return "TAG_Int";
} else if (clazz.equals(ListTag.class)) {
return "TAG_List";
} else if (clazz.equals(LongTag.class)) {
return "TAG_Long";
} else if (clazz.equals(ShortTag.class)) {
return "TAG_Short";
} else if (clazz.equals(StringTag.class)) {
return "TAG_String";
} else if (clazz.equals(IntArrayTag.class)) {
return "TAG_Int_Array";
} else {
throw new IllegalArgumentException("Invalid tag classs ("
+ clazz.getName() + ").");
}
}
/**
* Gets the type code of a tag class.
*
* @param clazz the tag class
* @return The type code.
* @throws IllegalArgumentException if the tag class is invalid.
*/
public static int getTypeCode(Class<? extends Tag> clazz) {
if (clazz.equals(ByteArrayTag.class)) {
return NBTConstants.TYPE_BYTE_ARRAY;
} else if (clazz.equals(ByteTag.class)) {
return NBTConstants.TYPE_BYTE;
} else if (clazz.equals(CompoundTag.class)) {
return NBTConstants.TYPE_COMPOUND;
} else if (clazz.equals(DoubleTag.class)) {
return NBTConstants.TYPE_DOUBLE;
} else if (clazz.equals(EndTag.class)) {
return NBTConstants.TYPE_END;
} else if (clazz.equals(FloatTag.class)) {
return NBTConstants.TYPE_FLOAT;
} else if (clazz.equals(IntTag.class)) {
return NBTConstants.TYPE_INT;
} else if (clazz.equals(ListTag.class)) {
return NBTConstants.TYPE_LIST;
} else if (clazz.equals(LongTag.class)) {
return NBTConstants.TYPE_LONG;
} else if (clazz.equals(ShortTag.class)) {
return NBTConstants.TYPE_SHORT;
} else if (clazz.equals(StringTag.class)) {
return NBTConstants.TYPE_STRING;
} else if (clazz.equals(IntArrayTag.class)) {
return NBTConstants.TYPE_INT_ARRAY;
} else {
throw new IllegalArgumentException("Invalid tag classs ("
+ clazz.getName() + ").");
}
}
/**
* Gets the class of a type of tag.
*
* @param type the type
* @return The class.
* @throws IllegalArgumentException if the tag type is invalid.
*/
public static Class<? extends Tag> getTypeClass(int type) {
switch (type) {
case NBTConstants.TYPE_END:
return EndTag.class;
case NBTConstants.TYPE_BYTE:
return ByteTag.class;
case NBTConstants.TYPE_SHORT:
return ShortTag.class;
case NBTConstants.TYPE_INT:
return IntTag.class;
case NBTConstants.TYPE_LONG:
return LongTag.class;
case NBTConstants.TYPE_FLOAT:
return FloatTag.class;
case NBTConstants.TYPE_DOUBLE:
return DoubleTag.class;
case NBTConstants.TYPE_BYTE_ARRAY:
return ByteArrayTag.class;
case NBTConstants.TYPE_STRING:
return StringTag.class;
case NBTConstants.TYPE_LIST:
return ListTag.class;
case NBTConstants.TYPE_COMPOUND:
return CompoundTag.class;
case NBTConstants.TYPE_INT_ARRAY:
return IntArrayTag.class;
default:
throw new IllegalArgumentException("Invalid tag type : " + type
+ ".");
}
}
/**
* Get child tag of a NBT structure.
*
* @param items the map to read from
* @param key the key to look for
* @param expected the expected NBT class type
* @return child tag
* @throws IllegalArgumentException
*/
public static <T extends Tag> T getChildTag(Map<String, Tag> items, String key, Class<T> expected) throws IllegalArgumentException {
if (!items.containsKey(key)) {
throw new IllegalArgumentException("Missing a \"" + key + "\" tag");
}
Tag tag = items.get(key);
if (!expected.isInstance(tag)) {
throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName());
}
return expected.cast(tag);
}
}

View File

@ -0,0 +1,63 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A tag that has a name.
*/
public class NamedTag {
private final String name;
private final Tag tag;
/**
* Create a new named tag.
*
* @param name the name
* @param tag the tag
*/
public NamedTag(String name, Tag tag) {
checkNotNull(name);
checkNotNull(tag);
this.name = name;
this.tag = tag;
}
/**
* Get the name of the tag.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Get the tag.
*
* @return the tag
*/
public Tag getTag() {
return tag;
}
}

View File

@ -0,0 +1,49 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Short} tag.
*/
public final class ShortTag extends Tag {
private final short value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public ShortTag(short value) {
super();
this.value = value;
}
@Override
public Short getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Short(" + value + ")";
}
}

View File

@ -0,0 +1,52 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_String} tag.
*/
public final class StringTag extends Tag {
private final String value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public StringTag(String value) {
super();
checkNotNull(value);
this.value = value;
}
@Override
public String getValue() {
return value;
}
@Override
public String toString() {
return "TAG_String(" + value + ")";
}
}

View File

@ -0,0 +1,34 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* Represents a NBT tag.
*/
public abstract class Tag {
/**
* Gets the value of this tag.
*
* @return the value
*/
public abstract Object getValue();
}

View File

@ -6,8 +6,9 @@ public enum CurrencyType
{
Tokens(" Tokens", Material.EMERALD),
Coins(" Coins", Material.DOUBLE_PLANT),
Gems(" Gems", Material.EMERALD);
Gems(" Gems", Material.EMERALD),
Gold(" Gold", Material.GOLD_NUGGET);
private String _prefix;
private Material _displayMaterial;

View File

@ -1,4 +1,4 @@
package mineplex.core.data;
package mineplex.core.common.block;
import org.bukkit.block.Block;
import org.bukkit.Material;

View File

@ -0,0 +1,104 @@
package mineplex.core.common.block.schematic;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
public class Schematic
{
private final short _width;
private final short _height;
private final short _length;
private final short[] _blocks;
private final byte[] _blockData;
public Schematic(short width, short height, short length, short[] blocks, byte[] blockData)
{
_width = width;
_height = height;
_length = length;
_blocks = blocks;
_blockData = blockData;
}
public void paste(Location originLocation)
{
int startX = originLocation.getBlockX();
int startY = originLocation.getBlockY();
int startZ = originLocation.getBlockZ();
for (int x = 0; x < _width; x++)
{
for (int y = 0; y < _height; y++)
{
for (int z = 0; z < _length; z++)
{
int index = getIndex(x, y, z);
Block block = originLocation.getWorld().getBlockAt(startX + x, startY + y, startZ + z);
// some blocks were giving me negative id's in the schematic (like stairs)
// not sure why but the math.abs is my simple fix
int materialId = Math.abs(_blocks[index]);
Material material = Material.getMaterial(materialId);
if (material == null)
{
System.out.println(materialId + " data: " + _blockData[index]);
continue;
}
block.setTypeIdAndData(materialId, _blockData[index], false);
}
}
}
}
public int getSize()
{
return _blocks.length;
}
public int getIndex(int x, int y, int z)
{
return y * _width * _length + z * _width + x;
}
public short getBlock(int x, int y, int z)
{
return _blocks[getIndex(x, y, z)];
}
public byte getData(int x, int y, int z)
{
return _blockData[getIndex(x, y, z)];
}
public short getWidth()
{
return _width;
}
public short getHeight()
{
return _height;
}
public short getLength()
{
return _length;
}
public short[] getBlocks()
{
return _blocks;
}
public byte[] getBlockData()
{
return _blockData;
}
@Override
public String toString()
{
return String.format("width: %d, length: %d, height: %d, blockLength: %d, blockDataLength: %d", _width, _length, _height, _blocks.length, _blockData.length);
}
}

View File

@ -0,0 +1,120 @@
package mineplex.core.common.block.schematic;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import mineplex.core.common.block.BlockData;
import mineplex.core.common.util.Callback;
public class SchematicRunnable implements Runnable
{
private JavaPlugin _plugin;
private boolean _started;
private BukkitTask _task;
private List<BlockData> _changedBlocks;
private Callback<List<BlockData>> _callback;
private Schematic _schematic;
private Block _startBlock;
private int _currentX = 0;
private int _currentY = 0;
private int _currentZ = 0;
private int _blocksPerTick = 1000;
public SchematicRunnable(JavaPlugin plugin, Schematic schematic, Block startBlock, Callback<List<BlockData>> callback)
{
_plugin = plugin;
_changedBlocks = new ArrayList<BlockData>(schematic.getSize());
_started = false;
_callback = callback;
_schematic = schematic;
_startBlock = startBlock;
}
public void start()
{
if (!_started)
{
_task = Bukkit.getScheduler().runTaskTimer(_plugin, this, 1, 1);
_started = true;
}
}
public void pause()
{
if (_started)
{
_task.cancel();
_started = false;
}
}
public void setBlocksPerTick(int blocksPerTick)
{
_blocksPerTick = blocksPerTick;
}
@Override
public void run()
{
for (int i = 0; i < _blocksPerTick; i++)
{
setBlock(_startBlock.getRelative(_currentX, _currentY, _currentZ), _currentX, _currentY, _currentZ);
_currentX++;
if (_currentX >= _schematic.getWidth())
{
_currentX = 0;
_currentZ++;
if (_currentZ >= _schematic.getLength())
{
_currentZ = 0;
_currentY++;
if (_currentY >= _schematic.getHeight())
{
// We are done
System.out.println("Finished importing schematic with setblockrunnable!");
if (_callback != null)
_callback.run(_changedBlocks);
_task.cancel();
return;
}
}
}
}
}
private void setBlock(Block block, int x, int y, int z)
{
int materialId = _schematic.getBlock(x, y, z);
byte data = _schematic.getData(x, y, z);
Material material = Material.getMaterial(materialId);
if (material == null)
{
System.out.println("Failed to find material with id: " + materialId);
return;
}
if (block.getTypeId() == materialId && block.getData() == data)
return;
BlockData blockData = new BlockData(block);
_changedBlocks.add(blockData);
block.setTypeIdAndData(materialId, data, false);
}
}

View File

@ -0,0 +1,76 @@
package mineplex.core.common.block.schematic;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import com.java.sk89q.jnbt.ByteArrayTag;
import com.java.sk89q.jnbt.CompoundTag;
import com.java.sk89q.jnbt.NBTInputStream;
import com.java.sk89q.jnbt.NamedTag;
import com.java.sk89q.jnbt.ShortTag;
import com.java.sk89q.jnbt.Tag;
public class UtilSchematic
{
public static Schematic loadSchematic(File file) throws IOException
{
FileInputStream fis = new FileInputStream(file);
NBTInputStream nbtStream = new NBTInputStream(new GZIPInputStream(fis));
NamedTag rootTag = nbtStream.readNamedTag();
nbtStream.close();
if (!rootTag.getName().equals("Schematic"))
return null;
CompoundTag schematicTag = (CompoundTag) rootTag.getTag();
Map<String, Tag> schematic = schematicTag.getValue();
short width = getChildTag(schematic, "Width", ShortTag.class).getValue();
short height = getChildTag(schematic, "Height", ShortTag.class).getValue();
short length = getChildTag(schematic, "Length", ShortTag.class).getValue();
byte[] blockId = getChildTag(schematic, "Blocks", ByteArrayTag.class).getValue();
byte[] addId = new byte[0];
short[] blocks = new short[blockId.length];
byte[] blockData = getChildTag(schematic, "Data", ByteArrayTag.class).getValue();
if (schematic.containsKey("AddBlocks"))
{
addId = getChildTag(schematic, "AddBlocks", ByteArrayTag.class).getValue();
}
for (int index = 0; index < blockId.length; index++)
{
if ((index >> 1) >= addId.length)
blocks[index] = (short) (blockId[index] & 0xFF);
else
{
if ((index & 1) == 0)
blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (blockId[index] & 0xFF));
else
blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (blockId[index] & 0xFF));
}
}
return new Schematic(width, height, length, blocks, blockData);
}
private static <T extends Tag> T getChildTag(Map<String, Tag> items, String key, Class<T> expected)
{
Tag tag = items.get(key);
return expected.cast(tag);
}
public static void main(String[] args) throws IOException
{
File file = new File("test.schematic");
System.out.println(file.getAbsoluteFile());
Schematic m = UtilSchematic.loadSchematic(file);
System.out.println(m);
}
}

View File

@ -0,0 +1,78 @@
package mineplex.core.common.player;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
public class PlayerSnapshot
{
private Location _location;
private ItemStack[] _armor;
private ItemStack[] _items;
private double _health;
private int _hunger;
private float _saturation;
private float _exhaustion;
private int _experience;
private Vector _velocity;
private PlayerSnapshot(Location location, ItemStack[] armor, ItemStack[] items, double health, int hunger, float saturation, float exhaustion, int experience, Vector velocity)
{
_location = location;
_armor = armor;
_items = items;
_health = health;
_hunger = hunger;
_saturation = saturation;
_exhaustion = exhaustion;
_experience = experience;
_velocity = velocity;
}
public void applySnapshot(Player player)
{
player.teleport(_location);
player.getInventory().setArmorContents(_armor);
player.getInventory().setContents(_items);
player.setHealth(_health);
player.setFoodLevel(_hunger);
player.setSaturation(_saturation);
player.setExhaustion(_exhaustion);
player.setVelocity(_velocity);
player.setTotalExperience(_experience);
}
public static PlayerSnapshot getSnapshot(Player player)
{
Location location = player.getLocation();
// Inventory
ItemStack[] bArmor = player.getInventory().getArmorContents();
ItemStack[] armor = new ItemStack[bArmor.length];
for (int i = 0; i < bArmor.length; i++)
{
armor[i] = bArmor[i];
}
ItemStack[] bItems = player.getInventory().getContents();
ItemStack[] items = new ItemStack[bItems.length];
for (int i = 0; i < bItems.length; i++)
{
items[i] = bItems[i];
}
// Health
double health = player.getHealth();
int hunger = player.getFoodLevel();
float saturation = player.getSaturation();
float exhaustion = player.getExhaustion();
int experience = player.getTotalExperience();
Vector velocity = player.getVelocity();
return new PlayerSnapshot(location, armor, items, health, hunger, saturation, exhaustion, experience, velocity);
}
}

View File

@ -10,6 +10,7 @@ public class C
public static String BoldStrike = "§l§m";
public static String Line = "§n";
public static String Italics = "§o";
public static String Reset = "§r";
public static String cAqua = "" + ChatColor.AQUA;
public static String cBlack = "" + ChatColor.BLACK;
@ -87,22 +88,26 @@ public class C
public static String chat = "" + ChatColor.WHITE;
public static String xBorderlands = "" + ChatColor.GOLD;
public static String xWilderness = "" + ChatColor.YELLOW;
public static String xWilderness = "" + ChatColor.GRAY;
public static String xMid = "" + ChatColor.WHITE;
public static String xNone = "" + ChatColor.GRAY;
public static ChatColor xNone = ChatColor.YELLOW;
public static ChatColor xAdmin = ChatColor.WHITE;
public static ChatColor xSafe = ChatColor.AQUA;
public static ChatColor xNeutral = ChatColor.YELLOW;
public static ChatColor xSelf = ChatColor.AQUA;
public static ChatColor xAlly = ChatColor.GREEN;
public static ChatColor xEnemy = ChatColor.YELLOW;
public static ChatColor xWar = ChatColor.RED;
public static ChatColor xEnemy = ChatColor.RED;
public static ChatColor xWarWinning = ChatColor.LIGHT_PURPLE;
public static ChatColor xWarLosing = ChatColor.RED;
public static ChatColor xPillage = ChatColor.LIGHT_PURPLE;
public static ChatColor xdNeutral = ChatColor.GOLD;
public static ChatColor xdSelf = ChatColor.DARK_AQUA;
public static ChatColor xdAlly = ChatColor.DARK_GREEN;
public static ChatColor xdEnemy = ChatColor.GOLD;
public static ChatColor xdWar = ChatColor.DARK_RED;
public static ChatColor xdEnemy = ChatColor.DARK_RED;
public static ChatColor xdWarWinning = ChatColor.DARK_PURPLE;
public static ChatColor xdWarLosing = ChatColor.DARK_RED;
public static ChatColor xdPillage = ChatColor.DARK_PURPLE;
}

View File

@ -1,6 +1,8 @@
package mineplex.core.common.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
@ -8,17 +10,26 @@ import java.util.TreeSet;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector;
import net.minecraft.server.v1_8_R3.EnumDirection;
public class UtilAlg
{
{
public static TreeSet<String> sortKey(Set<String> toSort)
{
TreeSet<String> sortedSet = new TreeSet<String>();
for (String cur : toSort)
return sortSet(toSort, null);
}
public static <T> TreeSet<T> sortSet(Collection<T> toSort, Comparator<T> comparator)
{
TreeSet<T> sortedSet = new TreeSet<T>(comparator);
for (T cur : toSort)
sortedSet.add(cur);
return sortedSet;
}
@ -39,7 +50,7 @@ public class UtilAlg
public static Vector getTrajectory(Vector from, Vector to)
{
return to.subtract(from).normalize();
return to.clone().subtract(from).normalize();
}
public static Vector getTrajectory2d(Entity from, Entity to)
@ -54,7 +65,7 @@ public class UtilAlg
public static Vector getTrajectory2d(Vector from, Vector to)
{
return to.subtract(from).setY(0).normalize();
return to.clone().subtract(from).setY(0).normalize();
}
public static boolean HasSight(Location from, Player to)
@ -407,6 +418,55 @@ public class UtilAlg
return bestLoc;
}
public static Vector calculateVelocity(Vector from, Vector to, double heightGain, Entity entity)
{
if (entity instanceof LivingEntity)
{
return calculateVelocity(from, to, heightGain, 1.15);
}
else
{
return calculateVelocity(from, to, heightGain, 0.115);
}
}
public static Vector calculateVelocity(Vector from, Vector to, double heightGain)
{
return calculateVelocity(from, to, heightGain, 0.115);
}
public static Vector calculateVelocity(Vector from, Vector to, double heightGain, double gravity)
{
// Block locations
int endGain = to.getBlockY() - from.getBlockY();
double dx1 = to.getBlockX() - from.getBlockX();
double dz1 = to.getBlockZ() - from.getBlockZ();
double horizDist = Math.sqrt(dx1 * dx1 + dz1 * dz1);
// Height gain
double maxGain = heightGain > (endGain + heightGain) ? heightGain : (endGain + heightGain);
// Solve quadratic equation for velocity
double a = -horizDist * horizDist / (4 * maxGain);
double b = horizDist;
double c = -endGain;
double slope = -b / (2 * a) - Math.sqrt(b * b - 4 * a * c) / (2 * a);
// Vertical velocity
double vy = Math.sqrt(maxGain * gravity);
// Horizontal velocity
double vh = vy / slope;
// Calculate horizontal direction
int dx = to.getBlockX() - from.getBlockX();
int dz = to.getBlockZ() - from.getBlockZ();
double mag = Math.sqrt(dx * dx + dz * dz);
double dirx = dx / mag;
double dirz = dz / mag;
// Horizontal velocity components
double vx = vh * dirx;
double vz = vh * dirz;
return new Vector(vx, vy, vz);
}
public static Location getNearestCornerLocation(Location near, Block block)
{
ArrayList<Location> corners = new ArrayList<Location>();
@ -439,4 +499,15 @@ public class UtilAlg
return value;
}
public static EulerAngle vectorToEuler(Vector vector)
{
//JUST MAKE SURE THE ARMOR STAND ISNT ROTATED.
return new EulerAngle(
Math.toRadians(UtilAlg.GetPitch(vector)),
Math.toRadians(UtilAlg.GetYaw(vector)),
0);
}
}

View File

@ -4,65 +4,78 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import net.minecraft.server.v1_8_R3.BlockPosition;
import net.minecraft.server.v1_8_R3.Blocks;
import net.minecraft.server.v1_8_R3.MathHelper;
import net.minecraft.server.v1_8_R3.WorldServer;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Bed;
import net.minecraft.server.v1_8_R3.BlockPosition;
import net.minecraft.server.v1_8_R3.Blocks;
import net.minecraft.server.v1_8_R3.EnumDirection;
import net.minecraft.server.v1_8_R3.MathHelper;
import net.minecraft.server.v1_8_R3.WorldServer;
public class UtilBlock
{
public static void main(String[] args) {
for (Material m : Material.values()) {
public static void main(String[] args)
{
for (Material m : Material.values())
{
boolean thisSolid = fullSolid(m.getId());
boolean solid = m.isSolid();
if (thisSolid != solid) {
if (thisSolid != solid)
{
StringBuilder sb = new StringBuilder();
sb.append("Failed: ");
sb.append(m.name());
int amount = 40 - sb.length();
for (int i = 0; i < amount; i++) {
for (int i = 0; i < amount; i++)
{
sb.append(" ");
}
sb.append(thisSolid);
System.out.println(sb);
}
}
System.out.println("done!");
}
/**
* A list of blocks that are usable
*/
public static HashSet<Byte> blockUseSet = new HashSet<Byte>();
/**
* A list of blocks that are always solid and can be stood on
*/
public static HashSet<Byte> fullSolid = new HashSet<Byte>();
/**
* A list of blocks that are non-solid, but can't be moved through. Eg lily,
* fence gate, portal
*/
public static HashSet<Byte> blockPassSet = new HashSet<Byte>();
/**
* A list of blocks that offer zero resistance (long grass, torch, flower)
*/
public static HashSet<Byte> blockAirFoliageSet = new HashSet<Byte>();
/**
* A list of blocks that are usable
*/
public static HashSet<Byte> blockUseSet = new HashSet<Byte>();
/**
* A list of blocks that are always solid and can be stood on
*/
public static HashSet<Byte> fullSolid = new HashSet<Byte>();
/**
* A list of blocks that are non-solid, but can't be moved through. Eg lily, fence gate, portal
*/
public static HashSet<Byte> blockPassSet = new HashSet<Byte>();
/**
* A list of blocks that offer zero resistance (long grass, torch, flower)
*/
public static HashSet<Byte> blockAirFoliageSet = new HashSet<Byte>();
static {
/**
* All horizontal diections [north, east, south, west]
*/
public static HashSet<BlockFace> horizontals = new HashSet<>();
static
{
blockAirFoliageSet.add((byte) Material.AIR.getId());
blockAirFoliageSet.add((byte) Material.SAPLING.getId());
blockAirFoliageSet.add((byte) Material.LONG_GRASS.getId());
@ -83,7 +96,7 @@ public class UtilBlock
blockAirFoliageSet.add((byte) Material.DOUBLE_PLANT.getId());
blockAirFoliageSet.add((byte) Material.STANDING_BANNER.getId());
blockAirFoliageSet.add((byte) Material.WALL_BANNER.getId());
blockPassSet.add((byte) Material.AIR.getId());
blockPassSet.add((byte) Material.SAPLING.getId());
blockPassSet.add((byte) Material.WATER.getId());
@ -141,7 +154,7 @@ public class UtilBlock
blockPassSet.add((byte) Material.STAINED_GLASS_PANE.getId());
blockPassSet.add((byte) Material.IRON_TRAPDOOR.getId());
blockPassSet.add((byte) Material.DAYLIGHT_DETECTOR_INVERTED.getId());
blockPassSet.add((byte) Material.BIRCH_FENCE_GATE.getId());
blockPassSet.add((byte) Material.JUNGLE_FENCE_GATE.getId());
blockPassSet.add((byte) Material.DARK_OAK_FENCE_GATE.getId());
@ -151,13 +164,13 @@ public class UtilBlock
blockPassSet.add((byte) Material.JUNGLE_FENCE.getId());
blockPassSet.add((byte) Material.DARK_OAK_FENCE.getId());
blockPassSet.add((byte) Material.ACACIA_FENCE.getId());
blockPassSet.add((byte) Material.SPRUCE_DOOR.getId());
blockPassSet.add((byte) Material.BIRCH_DOOR.getId());
blockPassSet.add((byte) Material.JUNGLE_DOOR.getId());
blockPassSet.add((byte) Material.ACACIA_DOOR.getId());
blockPassSet.add((byte) Material.DARK_OAK_DOOR.getId());
fullSolid.add((byte) Material.STONE.getId());
fullSolid.add((byte) Material.GRASS.getId());
fullSolid.add((byte) Material.DIRT.getId());
@ -239,7 +252,7 @@ public class UtilBlock
fullSolid.add((byte) Material.PACKED_ICE.getId());
fullSolid.add((byte) Material.RED_SANDSTONE.getId());
fullSolid.add((byte) Material.DOUBLE_STONE_SLAB2.getId());
blockUseSet.add((byte) Material.DISPENSER.getId());
blockUseSet.add((byte) Material.BED_BLOCK.getId());
blockUseSet.add((byte) Material.PISTON_BASE.getId());
@ -265,7 +278,7 @@ public class UtilBlock
blockUseSet.add((byte) Material.TRAPPED_CHEST.getId());
blockUseSet.add((byte) Material.HOPPER.getId());
blockUseSet.add((byte) Material.DROPPER.getId());
blockUseSet.add((byte) Material.BIRCH_FENCE_GATE.getId());
blockUseSet.add((byte) Material.JUNGLE_FENCE_GATE.getId());
blockUseSet.add((byte) Material.DARK_OAK_FENCE_GATE.getId());
@ -275,189 +288,192 @@ public class UtilBlock
blockUseSet.add((byte) Material.JUNGLE_FENCE.getId());
blockUseSet.add((byte) Material.DARK_OAK_FENCE.getId());
blockUseSet.add((byte) Material.ACACIA_FENCE.getId());
blockUseSet.add((byte) Material.SPRUCE_DOOR.getId());
blockUseSet.add((byte) Material.BIRCH_DOOR.getId());
blockUseSet.add((byte) Material.JUNGLE_DOOR.getId());
blockUseSet.add((byte) Material.ACACIA_DOOR.getId());
blockUseSet.add((byte) Material.DARK_OAK_DOOR.getId());
}
horizontals.add(BlockFace.NORTH);
horizontals.add(BlockFace.EAST);
horizontals.add(BlockFace.SOUTH);
horizontals.add(BlockFace.WEST);
}
public static boolean solid(Block block)
{
if (block == null) return false;
if (block == null) return false;
return solid(block.getTypeId());
}
public static boolean solid(int block)
{
return solid((byte)block);
return solid((byte) block);
}
public static boolean solid(byte block)
{
return !blockPassSet.contains(block);
}
public static boolean airFoliage(Block block)
{
if (block == null) return false;
if (block == null) return false;
return airFoliage(block.getTypeId());
}
public static boolean airFoliage(int block)
{
return airFoliage((byte)block);
return airFoliage((byte) block);
}
public static boolean airFoliage(byte block)
{
return blockAirFoliageSet.contains(block);
}
public static boolean fullSolid(Block block)
{
if (block == null)
return false;
if (block == null) return false;
return fullSolid(block.getTypeId());
}
public static boolean fullSolid(int block)
{
return fullSolid((byte)block);
return fullSolid((byte) block);
}
public static boolean fullSolid(byte block)
{
return fullSolid.contains(block);
}
public static boolean usable(Block block)
{
if (block == null)
return false;
if (block == null) return false;
return usable(block.getTypeId());
}
public static boolean usable(int block)
{
return usable((byte)block);
return usable((byte) block);
}
public static boolean usable(byte block)
{
return blockUseSet.contains(block);
}
public static HashMap<Block, Double> getInRadius(Location loc, double dR)
{
return getInRadius(loc, dR, 9999);
}
public static HashMap<Block, Double> getInRadius(Location loc, double dR, double maxHeight)
{
HashMap<Block, Double> blockList = new HashMap<Block, Double>();
int iR = (int)dR + 1;
for (int x=-iR ; x <= iR ; x++)
for (int z=-iR ; z <= iR ; z++)
for (int y=-iR ; y <= iR ; y++)
int iR = (int) dR + 1;
for (int x = -iR; x <= iR; x++)
for (int z = -iR; z <= iR; z++)
for (int y = -iR; y <= iR; y++)
{
if (Math.abs(y) > maxHeight)
continue;
Block curBlock = loc.getWorld().getBlockAt((int)(loc.getX()+x), (int)(loc.getY()+y), (int)(loc.getZ()+z));
if (Math.abs(y) > maxHeight) continue;
Block curBlock = loc.getWorld().getBlockAt((int) (loc.getX() + x), (int) (loc.getY() + y), (int) (loc.getZ() + z));
double offset = UtilMath.offset(loc, curBlock.getLocation().add(0.5, 0.5, 0.5));;
if (offset <= dR)
blockList.put(curBlock, 1 - (offset/dR));
if (offset <= dR) blockList.put(curBlock, 1 - (offset / dR));
}
return blockList;
}
public static HashMap<Block, Double> getInRadius(Block block, double dR)
{
return getInRadius(block, dR, false);
}
public static HashMap<Block, Double> getInRadius(Block block, double dR, boolean hollow)
{
HashMap<Block, Double> blockList = new HashMap<Block, Double>();
int iR = (int)dR + 1;
for (int x=-iR ; x <= iR ; x++)
for (int z=-iR ; z <= iR ; z++)
for (int y=-iR ; y <= iR ; y++)
int iR = (int) dR + 1;
for (int x = -iR; x <= iR; x++)
for (int z = -iR; z <= iR; z++)
for (int y = -iR; y <= iR; y++)
{
Block curBlock = block.getRelative(x, y, z);
double offset = UtilMath.offset(block.getLocation(), curBlock.getLocation());
if (offset <= dR && !(hollow && offset < dR - 1))
{
blockList.put(curBlock, 1 - (offset / dR));
}
}
return blockList;
}
public static ArrayList<Block> getInSquare(Block block, double dR)
{
ArrayList<Block> blockList = new ArrayList<Block>();
int iR = (int)dR + 1;
for (int x=-iR ; x <= iR ; x++)
for (int z=-iR ; z <= iR ; z++)
for (int y=-iR ; y <= iR ; y++)
int iR = (int) dR + 1;
for (int x = -iR; x <= iR; x++)
for (int z = -iR; z <= iR; z++)
for (int y = -iR; y <= iR; y++)
{
blockList.add(block.getRelative(x, y, z));
}
return blockList;
}
public static boolean isBlock(ItemStack item)
public static boolean isBlock(ItemStack item)
{
if (item == null)
return false;
if (item == null) return false;
return item.getTypeId() > 0 && item.getTypeId() < 256;
}
public static Block getHighest(World world, int x, int z)
{
return getHighest(world, x, z, null);
}
public static Block getHighest(World world, int x, int z, HashSet<Material> ignore)
{
Block block = world.getHighestBlockAt(x, z);
//Shuffle Down
while (block.getY() > 0 &&
(
airFoliage(block) ||
block.getType() == Material.LEAVES ||
(ignore != null && ignore.contains(block.getType()))
))
// Shuffle Down
while (block.getY() > 0 && (airFoliage(block) || block.getType() == Material.LEAVES || block.getType() == Material.LEAVES_2 || (ignore != null && ignore.contains(block.getType()))))
{
block = block.getRelative(BlockFace.DOWN);
}
return block.getRelative(BlockFace.UP);
return block.getRelative(BlockFace.UP);
}
/**
*
* @param location of explosion
* @param strength of explosion
* @param damageBlocksEqually - Treat all blocks as durability of dirt
* @param ensureDestruction - Ensure that the closest blocks are destroyed at least
* @param ensureDestruction - Ensure that the closest blocks are destroyed
* at least
* @return
*/
public static ArrayList<Block> getExplosionBlocks(Location location, float strength, boolean damageBlocksEqually)
{
ArrayList<Block> toExplode = new ArrayList<Block>();
WorldServer world = ((CraftWorld) location.getWorld()).getHandle();
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 16; j++)
@ -470,37 +486,36 @@ public class UtilBlock
double d4 = j / (16 - 1.0F) * 2.0F - 1.0F;
double d5 = k / (16 - 1.0F) * 2.0F - 1.0F;
double d6 = Math.sqrt(d3 * d3 + d4 * d4 + d5 * d5);
d3 /= d6;
d4 /= d6;
d5 /= d6;
float f1 = strength * (0.7F + UtilMath.random.nextFloat() * 0.6F);
double d0 = location.getX();
double d1 = location.getY();
double d2 = location.getZ();
for (float f2 = 0.3F; f1 > 0.0F; f1 -= f2 * 0.75F)
{
int l = MathHelper.floor(d0);
int i1 = MathHelper.floor(d1);
int j1 = MathHelper.floor(d2);
Block block = location.getWorld().getBlockAt(l, i1, j1);
if (block.getType() != Material.AIR)
{
Blocks.DIRT.a((net.minecraft.server.v1_8_R3.Entity) null);
float f3 = (damageBlocksEqually ? Blocks.DIRT : world.getType(new BlockPosition(block.getX(), block.getY(),
block.getZ())).getBlock()).a((net.minecraft.server.v1_8_R3.Entity) null);
float f3 = (damageBlocksEqually ? Blocks.DIRT : world.getType(new BlockPosition(block.getX(), block.getY(), block.getZ())).getBlock()).a((net.minecraft.server.v1_8_R3.Entity) null);
f1 -= (f3 + 0.3F) * f2;
}
if ((f1 > 0.0F) && (i1 < 256) && (i1 >= 0))
{
toExplode.add(block);
}
d0 += d3 * f2;
d1 += d4 * f2;
d2 += d5 * f2;
@ -512,20 +527,19 @@ public class UtilBlock
return toExplode;
}
public static ArrayList<Block> getSurrounding(Block block, boolean diagonals)
public static ArrayList<Block> getSurrounding(Block block, boolean diagonals)
{
ArrayList<Block> blocks = new ArrayList<Block>();
if (diagonals)
{
for (int x=-1 ; x<= 1 ; x++)
for (int y=-1 ; y<= 1 ; y++)
for (int z=-1 ; z<= 1 ; z++)
for (int x = -1; x <= 1; x++)
for (int y = -1; y <= 1; y++)
for (int z = -1; z <= 1; z++)
{
if (x == 0 && y == 0 && z == 0)
continue;
if (x == 0 && y == 0 && z == 0) continue;
blocks.add(block.getRelative(x, y, z));
}
}
@ -538,23 +552,24 @@ public class UtilBlock
blocks.add(block.getRelative(BlockFace.EAST));
blocks.add(block.getRelative(BlockFace.WEST));
}
return blocks;
}
public static boolean isVisible(Block block)
{
for (Block other : UtilBlock.getSurrounding(block, false))
{
if (!other.getType().isOccluding())
if (!other.getType().isOccluding())
{
return true;
}
}
return false;
}
public static ArrayList<Block> getInBoundingBox(Location a, Location b)
public static ArrayList<Block> getInBoundingBox(Location a, Location b)
{
return getInBoundingBox(a, b, true);
}
@ -563,65 +578,269 @@ public class UtilBlock
{
ArrayList<Block> blocks = new ArrayList<Block>();
for (int x=Math.min(a.getBlockX(), b.getBlockX()) ; x<=Math.max(a.getBlockX(), b.getBlockX()) ; x++)
for (int y=Math.min(a.getBlockY(), b.getBlockY()) ; y<=Math.max(a.getBlockY(), b.getBlockY()) ; y++)
for (int z=Math.min(a.getBlockZ(), b.getBlockZ()) ; z<=Math.max(a.getBlockZ(), b.getBlockZ()) ; z++)
for (int x = Math.min(a.getBlockX(), b.getBlockX()); x <= Math.max(a.getBlockX(), b.getBlockX()); x++)
for (int y = Math.min(a.getBlockY(), b.getBlockY()); y <= Math.max(a.getBlockY(), b.getBlockY()); y++)
for (int z = Math.min(a.getBlockZ(), b.getBlockZ()); z <= Math.max(a.getBlockZ(), b.getBlockZ()); z++)
{
Block block = a.getWorld().getBlockAt(x,y,z);
Block block = a.getWorld().getBlockAt(x, y, z);
if(ignoreAir)
if (ignoreAir)
{
if (block.getType() != Material.AIR)
blocks.add(block);
if (block.getType() != Material.AIR) blocks.add(block);
}
else blocks.add(block);
else
blocks.add(block);
}
return blocks;
}
public static int getStepSoundId(Block block)
{
if (block.getTypeId() != 35 && block.getTypeId() != 159 && block.getTypeId() != 160)
return block.getTypeId();
if (block.getTypeId() != 35 && block.getTypeId() != 159 && block.getTypeId() != 160) return block.getTypeId();
switch (block.getData())
{
case 0:
return block.getTypeId();
case 1:
return 172;
case 2:
return 87;
case 3:
return 79;
case 4:
return 41;
case 5:
return 133;
case 6:
return 45;
case 7:
return 16;
case 8:
return 13;
case 9:
return 56;
case 10:
return 110;
case 11:
return 22;
case 12:
return 3;
case 13:
return 31;
case 14:
return 152;
case 15:
return 173;
default:
return block.getTypeId();
case 0:
return block.getTypeId();
case 1:
return 172;
case 2:
return 87;
case 3:
return 79;
case 4:
return 41;
case 5:
return 133;
case 6:
return 45;
case 7:
return 16;
case 8:
return 13;
case 9:
return 56;
case 10:
return 110;
case 11:
return 22;
case 12:
return 3;
case 13:
return 31;
case 14:
return 152;
case 15:
return 173;
default:
return block.getTypeId();
}
}
/**
* The location specified is the location of the foot block of the bed.
* <p>
* ex:
* <p>
* placeBed(location[0,0,0], NORTH);
* <p>
* will result in two blocks appearing, at location[0,0,0](foot block) and
* location[0,0,-1](head block (pillow))
* <p>
* allowFloating defines whether or not the bed is allowed to float (over
* water, lava, air, and anything other blocks that do not have bounds)
* <p>
* if force is set to true, then the bed will be placed even if there are
* blocks obstructing it, on the other hand, if force is false, then the bed
* will only be placed if there is air in the location specified.
*/
public static boolean placeBed(Location location, BlockFace direction, boolean allowFloating, boolean force)
{
if (!horizontals.contains(direction))
{
return false;
}
if (location == null)
{
return false;
}
if (location.getY() <= 0)
{
return false;
}
if (!allowFloating && UtilItem.isBoundless(location.getBlock().getRelative(BlockFace.DOWN).getType()))
{
return false;
}
BlockState head = location.getBlock().getRelative(direction).getState();
BlockState foot = location.getBlock().getState();
if (!force && (!UtilItem.isBoundless(head.getType()) || !UtilItem.isBoundless(foot.getType())))
{
return false;
}
System.out.println("<-bed-> head & foot are air");
head.setType(Material.BED_BLOCK);
foot.setType(Material.BED_BLOCK);
Bed bedHead = (Bed) head.getData();
Bed bedFoot = (Bed) foot.getData();
bedHead.setHeadOfBed(true);
bedFoot.setHeadOfBed(false);
bedHead.setFacingDirection(direction);
bedFoot.setFacingDirection(direction);
head.setData(bedHead);
foot.setData(bedFoot);
head.update(true, false);
foot.update(true, false);
System.out.println("<-bed-> alls guude");
return head.getBlock().getType().equals(Material.BED_BLOCK) && foot.getBlock().getType().equals(Material.BED_BLOCK);
}
public static boolean deleteBed(Location loc)
{
if (loc == null)
{
return false;
}
if (loc.getY() <= 0)
{
return false;
}
if (!loc.getBlock().getType().equals(Material.BED_BLOCK))
{
return false;
}
BlockState head = getBedHead(loc.getBlock()).getState();
BlockState foot = getBedFoot(loc.getBlock()).getState();
head.setType(Material.AIR);
head.setRawData((byte) 0);
foot.setType(Material.AIR);
foot.setRawData((byte) 0);
return head.update(true, false) && foot.update(true, false);
}
private static Block getBedHead(Block bed)
{
if (bed == null)
{
return null;
}
if (!bed.getType().equals(Material.BED_BLOCK))
{
return null;
}
if (getBed(bed).isHeadOfBed())
{
return bed;
}
else
{
return bed.getRelative(getBed(bed).getFacing()).getType().equals(Material.BED_BLOCK) ? bed.getRelative(getBed(bed).getFacing()) : null;
}
}
private static Block getBedFoot(Block bed)
{
if (bed == null)
{
return null;
}
if (!bed.getType().equals(Material.BED_BLOCK))
{
return null;
}
if (!getBed(bed).isHeadOfBed())
{
return bed;
}
else
{
return bed.getRelative(getBed(bed).getFacing().getOppositeFace()).getType().equals(Material.BED_BLOCK) ? bed.getRelative(getBed(bed).getFacing().getOppositeFace()) : null;
}
}
private static Bed getBed(Block bed)
{
if (bed == null)
{
return null;
}
if (!bed.getType().equals(Material.BED_BLOCK))
{
return null;
}
return (Bed) bed.getState().getData();
}
public static boolean isValidBed(Location bed)
{
if (bed == null)
{
return false;
}
if (bed.getY() <= 0)
{
return false;
}
if (!bed.getBlock().getType().equals(Material.BED_BLOCK))
{
return false;
}
return getBedHead(bed.getBlock()) != null && getBedFoot(bed.getBlock()) != null;
}
public static HashSet<Block> findConnectedBlocks(Block block, HashSet<Block> blocks, int limit)
{
if (blocks == null)
blocks = new HashSet<Block>();
//This is incase you recursively check an entire MC world
if (blocks.size() >= limit)
return blocks;
//Mark current node as searched
blocks.add(block);
//Search the node
for (Block neighbour : UtilBlock.getSurrounding(block, false))
{
if (neighbour.getType() == Material.AIR)
continue;
//If neighbour hasn't been searched, recursively search it!
if (!blocks.contains(neighbour))
findConnectedBlocks(neighbour, blocks, limit);
}
return blocks;
}
}

View File

@ -531,10 +531,27 @@ public class UtilEnt
}
public static boolean isGrounded(Entity ent)
{
if(!(ent instanceof Player)) {
return ent.isOnGround();
}
AxisAlignedBB box = ((CraftEntity)ent).getHandle().getBoundingBox().shrink(0.05, 0, 0.05);
Location bottom_corner_1 = new Location(ent.getWorld(), box.a, ent.getLocation().getY()-0.05, box.c);
Location bottom_corner_2 = new Location(ent.getWorld(), box.d, ent.getLocation().getY()-0.05, box.f);
for(Block b : UtilBlock.getInBoundingBox(bottom_corner_1, bottom_corner_2)){
if(UtilBlock.solid(b)) return true;
}
return false;
}
public static boolean isGrounded(Entity ent, Location loc)
{
AxisAlignedBB box = ((CraftEntity)ent).getHandle().getBoundingBox();
Location bottom_corner_1 = new Location(ent.getWorld(), box.a, ent.getLocation().getY()-0.1, box.c);
Location bottom_corner_2 = new Location(ent.getWorld(), box.d, ent.getLocation().getY()-0.1, box.f);
Location bottom_corner_1 = new Location(ent.getWorld(), box.a, loc.getY()-0.1, box.c);
Location bottom_corner_2 = new Location(ent.getWorld(), box.d, loc.getY()-0.1, box.f);
for(Block b : UtilBlock.getInBoundingBox(bottom_corner_1, bottom_corner_2)){
if(UtilBlock.solid(b)) return true;
@ -639,6 +656,11 @@ public class UtilEnt
return CreatureLook(ent, UtilAlg.GetPitch(vec), UtilAlg.GetYaw(vec));
}
public static boolean CreatureLook(Entity ent, Vector target)
{
return CreatureLook(ent, UtilAlg.GetPitch(target), UtilAlg.GetYaw(target));
}
public static void setFakeHead(Entity ent, boolean fakeHead)
{
net.minecraft.server.v1_8_R3.Entity ec = ((CraftEntity) ent).getHandle();

View File

@ -16,7 +16,8 @@ public class UtilEvent
L_BLOCK,
R,
R_AIR,
R_BLOCK
R_BLOCK,
ANY
}
public static boolean isAction(PlayerInteractEvent event, ActionType action)
@ -39,6 +40,9 @@ public class UtilEvent
if (action == ActionType.R_BLOCK)
return (event.getAction() == Action.RIGHT_CLICK_BLOCK);
if (action == ActionType.ANY)
return event.getAction() != Action.PHYSICAL;
return false;
}

View File

@ -0,0 +1,310 @@
package mineplex.core.common.util;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class UtilFile
{
public static void writePlainFile(File file, String text) throws FileNotFoundException
{
PrintWriter writer = new PrintWriter(file);
writer.print(text);
writer.close();
}
/**
* Will read the specified file, and return the contents, or a null value,
* if an exception is thrown. Will handle all exceptions, and simply ignore
* them and return null. No stack trace printed or anything.
*/
public static String readIgnoreErrors(File file)
{
try
{
return readToStr(file);
}
catch (IOException exception)
{
return null;
}
}
public static String readToStr(File file) throws IOException
{
return new String(readAllBytes(file));
}
public static byte[] readAllBytes(File file) throws IOException
{
return Files.readAllBytes(Paths.get(file.toURI()));
}
public static void writePlainFile(String file, String text) throws FileNotFoundException
{
writePlainFile(new File(file), text);
}
/**
* Will read the specified file, and return the contents, or a null value,
* if an exception is thrown. Will handle all exceptions, and simply ignore
* them and return null. No stack trace printed or anything.
*/
public static String readIgnoreErrors(String file)
{
return readIgnoreErrors(new File(file));
}
public static String readToStr(String file) throws IOException
{
return readToStr(new File(file));
}
public static byte[] readAllBytes(String file) throws IOException
{
return readAllBytes(new File(file));
}
public static void writeDataFile(File file, DataFileChunk... chunks) throws IOException
{
DataOutputStream stream = new DataOutputStream(new FileOutputStream(file));
for (DataFileChunk chunk : chunks)
{
chunk.writeTo(stream);
}
stream.close();
}
public static DataFileReader beginReading(String file) throws FileNotFoundException
{
return beginReading(new File(file));
}
public static DataFileReader beginReading(File file) throws FileNotFoundException
{
return new DataFileReader(file);
}
public static void writeDataFile(String file, DataFileChunk... chunks) throws IOException
{
writeDataFile(new File(file), chunks);
}
public static class DataFileChunk
{
private ChunkType _type;
private Object _value;
public DataFileChunk(ChunkType type, Object value)
{
if (type == null)
{
throw new RuntimeException("ChunkType can NOT be null.");
}
_type = type;
if (!_type.isValid(value))
{
throw new RuntimeException("Invalid value provided for the specified ChunkType.");
}
_value = value;
}
public void writeTo(DataOutputStream stream) throws IOException
{
_type.writeTo(stream, _value);
}
}
public static enum ChunkType
{
STRING(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
String str = (String) value;
INTEGER.writeTo(stream, str.length());
for (char b : str.toCharArray())
{
CHAR.writeTo(stream, b);
}
}
public boolean isValid(Object value)
{
return value.getClass().equals(String.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
int length = (int) INTEGER.readFrom(stream);
StringBuilder string = new StringBuilder();
for (int i = 0; i < length; i++)
{
string.append(CHAR.readFrom(stream));
}
return string.toString();
}
}),
DOUBLE(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
double number = (double) value;
stream.writeDouble(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Double.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readDouble();
}
}),
INTEGER(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
int number = (int) value;
stream.writeInt(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Integer.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readInt();
}
}),
BYTE(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
byte number = (byte) value;
stream.writeByte(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Byte.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readByte();
}
}),
CHAR(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
char number = (char) value;
stream.writeChar(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Character.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readChar();
}
}),
LONG(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
long number = (long) value;
stream.writeLong(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Long.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readLong();
}
});
private ChunkImpl _impl;
ChunkType(ChunkImpl impl)
{
_impl = impl;
}
protected void writeTo(DataOutputStream stream, Object value) throws IOException
{
_impl.writeTo(stream, value);
}
protected boolean isValid(Object value)
{
return value != null && _impl.isValid(value);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return _impl.readFrom(stream);
}
}
public static class DataFileReader
{
private DataInputStream _stream;
public DataFileReader(File file) throws FileNotFoundException
{
_stream = new DataInputStream(new FileInputStream(file));
}
public Object readChunk(ChunkType type) throws IOException
{
return type.readFrom(_stream);
}
public void close() throws IOException
{
_stream.close();
}
}
protected interface ChunkImpl
{
void writeTo(DataOutputStream stream, Object value) throws IOException;
Object readFrom(DataInputStream stream) throws IOException;
boolean isValid(Object value);
}
}

View File

@ -13,7 +13,44 @@ public class UtilGear
private static HashSet<Material> pickSet = new HashSet<Material>();
private static HashSet<Material> diamondSet = new HashSet<Material>();
private static HashSet<Material> goldSet = new HashSet<Material>();
private static HashSet<Material> _armorSet = new HashSet<Material>();
public static boolean isArmor(ItemStack item)
{
if (item == null)
return false;
if (_armorSet.isEmpty())
{
_armorSet.add(Material.LEATHER_HELMET);
_armorSet.add(Material.LEATHER_CHESTPLATE);
_armorSet.add(Material.LEATHER_LEGGINGS);
_armorSet.add(Material.LEATHER_BOOTS);
_armorSet.add(Material.GOLD_HELMET);
_armorSet.add(Material.GOLD_CHESTPLATE);
_armorSet.add(Material.GOLD_LEGGINGS);
_armorSet.add(Material.GOLD_BOOTS);
_armorSet.add(Material.CHAINMAIL_HELMET);
_armorSet.add(Material.CHAINMAIL_CHESTPLATE);
_armorSet.add(Material.CHAINMAIL_LEGGINGS);
_armorSet.add(Material.CHAINMAIL_BOOTS);
_armorSet.add(Material.IRON_HELMET);
_armorSet.add(Material.IRON_CHESTPLATE);
_armorSet.add(Material.IRON_LEGGINGS);
_armorSet.add(Material.IRON_BOOTS);
_armorSet.add(Material.DIAMOND_HELMET);
_armorSet.add(Material.DIAMOND_CHESTPLATE);
_armorSet.add(Material.DIAMOND_LEGGINGS);
_armorSet.add(Material.DIAMOND_BOOTS);
}
return _armorSet.contains(item.getType());
}
public static boolean isAxe(ItemStack item)
{
if (item == null)
@ -126,6 +163,10 @@ public class UtilGear
{
goldSet.add(Material.GOLD_SWORD);
goldSet.add(Material.GOLD_AXE);
goldSet.add(Material.GOLD_HELMET);
goldSet.add(Material.GOLD_CHESTPLATE);
goldSet.add(Material.GOLD_LEGGINGS);
goldSet.add(Material.GOLD_BOOTS);
}
return goldSet.contains(item.getType());

View File

@ -2,7 +2,7 @@ package mineplex.core.common.util;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
import java.util.Random;
@ -12,31 +12,36 @@ import org.bukkit.util.Vector;
public class UtilMath
{
public static double trim(int degree, double d)
public static double trim(int degree, double d)
{
String format = "#.#";
for (int i=1 ; i<degree ; i++)
for (int i = 1; i < degree; i++)
format += "#";
DecimalFormatSymbols symb = new DecimalFormatSymbols(Locale.US);
DecimalFormat twoDForm = new DecimalFormat(format, symb);
return Double.valueOf(twoDForm.format(d));
}
public static Random random = new Random();
public static int r(int i)
public static int r(int i)
{
return random.nextInt(i);
}
public static double offset2d(Entity a, Entity b)
public static int rRange(int min, int max)
{
return min + r(1 + max - min);
}
public static double offset2d(Entity a, Entity b)
{
return offset2d(a.getLocation().toVector(), b.getLocation().toVector());
}
public static double offset2d(Location a, Location b)
public static double offset2d(Location a, Location b)
{
return offset2d(a.toVector(), b.toVector());
}
@ -48,48 +53,67 @@ public class UtilMath
return a.subtract(b).length();
}
public static double offset(Entity a, Entity b)
public static double offset(Entity a, Entity b)
{
return offset(a.getLocation().toVector(), b.getLocation().toVector());
}
public static double offset(Location a, Location b)
public static double offset(Location a, Location b)
{
return offset(a.toVector(), b.toVector());
}
public static double offset(Vector a, Vector b)
{
return a.subtract(b).length();
return a.clone().subtract(b).length();
}
public static double offsetSquared(Entity a, Entity b)
{
return offsetSquared(a.getLocation(), b.getLocation());
}
public static double offsetSquared(Location a, Location b)
{
return offsetSquared(a.toVector(), b.toVector());
}
public static double offsetSquared(Vector a, Vector b)
{
return a.distanceSquared(b);
}
public static double rr(double d, boolean bidirectional)
{
if (bidirectional)
return Math.random() * (2 * d) - d;
if (bidirectional) return Math.random() * (2 * d) - d;
return Math.random() * d;
}
public static <T> T randomElement(T[] array) {
if (array.length == 0)
return null;
public static <T> T randomElement(T[] array)
{
if (array.length == 0) return null;
return array[random.nextInt(array.length)];
}
public static <T> T randomElement(List<T> list)
{
if (list.isEmpty()) return null;
return list.get(random.nextInt(list.size()));
}
public static double clamp(double num, double min, double max)
{
return num < min ? min : (num > max ? max : num);
}
public static long clamp(long num, long min, long max)
{
return num < min ? min : (num > max ? max : num);
}
public static int clamp(int num, int min, int max)
{
return num < min ? min : (num > max ? max : num);
}
}

View File

@ -1,14 +1,12 @@
package mineplex.core.common.util;
import java.lang.reflect.Field;
import mineplex.core.common.util.UtilParticle.ViewDist;
import net.minecraft.server.v1_8_R3.EnumParticle;
import net.minecraft.server.v1_8_R3.PacketPlayOutWorldParticles;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import net.minecraft.server.v1_8_R3.EnumParticle;
import net.minecraft.server.v1_8_R3.PacketPlayOutWorldParticles;
public class UtilParticle
{
@ -95,7 +93,7 @@ public class UtilParticle
LARGE_EXPLODE(EnumParticle.EXPLOSION_LARGE, "largeexplode", "Explosion", Material.FIREBALL, (byte) 0),
LARGE_SMOKE(EnumParticle.SMOKE_LARGE, "largesmoke", "Black Smoke", Material.INK_SACK, (byte) 0),
SMOKE(EnumParticle.SMOKE_NORMAL, "smoke", "Smoke", Material.INK_SACK, (byte) 0),
LAVA(EnumParticle.LAVA, "lava", "Lava Debris", Material.LAVA, (byte) 0),
@ -242,7 +240,29 @@ public class UtilParticle
return packet;
}
public static void PlayParticle(ParticleType type,Location location, float offsetX, float offsetY,
float offsetZ, float speed, int count, ViewDist dist)
{
PlayParticle(type, location, offsetX, offsetY, offsetZ, speed, count, dist, UtilServer.getPlayers());
}
public static void PlayParticleToAll(ParticleType type, Location location, Vector offset, float speed, int count, ViewDist dist)
{
PlayParticle(type, location, (float) offset.getX(), (float) offset.getY(), (float) offset.getZ(), speed, count, dist, UtilServer.getPlayers());
}
public static void PlayParticle(ParticleType type, Location location, Vector offset, float speed, int count, ViewDist dist, Player... players)
{
PlayParticle(type, location, (float) offset.getX(), (float) offset.getY(), (float) offset.getZ(), speed, count, dist, players);
}
public static void PlayParticleToAll(ParticleType type, Location location, float offsetX, float offsetY, float offsetZ,
float speed, int count, ViewDist dist)
{
PlayParticle(type.particleName, location, offsetX, offsetY, offsetZ, speed, count, dist, UtilServer.getPlayers());
}
public static void PlayParticle(ParticleType type, Location location, float offsetX, float offsetY, float offsetZ,
float speed, int count, ViewDist dist, Player... players)
{

View File

@ -4,13 +4,12 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import net.minecraft.server.v1_8_R3.EntityPlayer;
import net.minecraft.server.v1_8_R3.Packet;
import net.minecraft.server.v1_8_R3.PlayerConnection;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity;
@ -21,10 +20,23 @@ import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.potion.PotionEffect;
import org.bukkit.util.Vector;
import net.minecraft.server.v1_8_R3.EntityPlayer;
import net.minecraft.server.v1_8_R3.Packet;
import net.minecraft.server.v1_8_R3.PlayerConnection;
public class UtilPlayer
{
private static Random RANDOM = new Random();
// A mapping of player names (Keys) to the system time when they last changed active Hotbar Slot
private static Map<String, Long> _hotbarUpdates = new HashMap<String, Long>();
// The amount of time (in milliseconds) after changin hotbars that you can block
public static final long BLOCKING_HOTBAR_DELAY = 100;
private static boolean hasIntersection(Vector3D p1, Vector3D p2, Vector3D min, Vector3D max)
{
final double epsilon = 0.0001f;
@ -154,6 +166,30 @@ public class UtilPlayer
return hit;
}
/**
* @param player - the player to be checked for blocking status
* @return true, if the {@code player} is blocking and has not recently
* changed hotbar slots (within {@value BLOCKING_HOTBAR_DELAY} milliseconds), false otherwise.
*/
public static boolean isBlocking(Player player)
{
String name = player.getName();
long lastUpdate = _hotbarUpdates.containsKey(name) ? _hotbarUpdates.get(name) : 0;;
long duration = System.currentTimeMillis() - lastUpdate;
return player.isBlocking();// && UtilItem.isSword(player.getItemInHand())
//&& duration >= BLOCKING_HOTBAR_DELAY;
}
/**
* Mark the {@code player} as having changed hotbar slots.
* @param player - the player to be marked
*/
public static void onHotbarChange(Player player)
{
_hotbarUpdates.put(player.getName(), System.currentTimeMillis());
}
/**
* AviodAllies doesn't work. Leaving as a param as it sounds like something you may want in the future.
*/
@ -392,7 +428,12 @@ public class UtilPlayer
return matchList;
}
public static LinkedList<Player> getNearby(Location loc, double maxDist)
public static List<Player> getNearby(Location loc, double maxDist)
{
return getNearby(loc, maxDist, false);
}
public static List<Player> getNearby(Location loc, double maxDist, boolean onlySurvival)
{
LinkedList<Player> nearbyMap = new LinkedList<Player>();
@ -404,8 +445,10 @@ public class UtilPlayer
if (cur.isDead())
continue;
double dist = loc.toVector().subtract(cur.getLocation().toVector()).length();
if (onlySurvival && cur.getGameMode() != GameMode.SURVIVAL)
continue;
double dist = loc.distance(cur.getLocation());
if (dist > maxDist)
continue;
@ -453,7 +496,7 @@ public class UtilPlayer
return best;
}
public static Player getClosest(Location loc, Entity ignore)
public static Player getClosest(Location loc, Entity... ignore)
{
Player best = null;
double bestDist = 0;
@ -466,8 +509,14 @@ public class UtilPlayer
if (cur.isDead())
continue;
if (ignore != null && ignore.equals(cur))
continue;
if (ignore != null)
{
for (int i = 0; i < ignore.length; i++)
{
if (cur.equals(ignore[i]))
continue;
}
}
double dist = UtilMath.offset(cur.getLocation(), loc);
@ -498,6 +547,14 @@ public class UtilPlayer
if (log)
System.out.println("Kicked Client [" + player.getName() + "] for [" + module + " - " + message + "]");
}
public static void kick(Collection<Player> players, String module, String message, boolean log)
{
for (Player player : players)
{
kick(player, module, message, log);
}
}
public static HashMap<Player, Double> getInRadius(Location loc, double dR)
{
@ -527,7 +584,7 @@ public class UtilPlayer
continue;
//Get lower offset (eye to eye, eye to feet)
double offset = Math.min(UtilMath.offset(player.getEyeLocation(), cur.getEyeLocation()),
double offset = Math.min(UtilMath.offset(player.getEyeLocation(), cur.getEyeLocation()),
UtilMath.offset(player.getEyeLocation(), cur.getLocation()));
if (offset < distance && UtilAlg.isTargetInPlayerPyramid(player, cur, angleLimit))
@ -590,6 +647,23 @@ public class UtilPlayer
return (((CraftEntity) player).getHandle().getDataWatcher().getByte(0) & 1 << 4) != 0;
}
public static void clearInventory(Player player)
{
player.getInventory().clear();
player.getInventory().setHelmet(null);
player.getInventory().setChestplate(null);
player.getInventory().setLeggings(null);
player.getInventory().setBoots(null);
}
public static void clearPotionEffects(Player player)
{
for (PotionEffect effect : player.getActivePotionEffects())
{
player.removePotionEffect(effect.getType());
}
}
public static void sendPacket(Player player, Packet... packets)
{
PlayerConnection connection = ((CraftPlayer) player).getHandle().playerConnection;
@ -603,6 +677,18 @@ public class UtilPlayer
}
}
/**
* Get a random player within maxDist of the target location
* @param location The center location to look for the player
* @param maxDist The max distance from location that the player can be
* @return A random player that is within maxDist of location, or null if no players apply
*/
public static Player getRandomTarget(Location location, double maxDist)
{
List<Player> nearby = getNearby(location, maxDist, true);
return nearby.size() > 0 ? nearby.get(RANDOM.nextInt(nearby.size())) : null;
}
public static boolean isSpectator(Entity player)
{
if (player instanceof Player)

View File

@ -1,5 +1,11 @@
package mineplex.core.common.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.Sound;
@ -12,6 +18,25 @@ public class UtilServer
return getServer().getOnlinePlayers().toArray(new Player[0]);
}
public static List<Player> getSortedPlayers()
{
return getSortedPlayers(new Comparator<Player>()
{
@Override
public int compare(Player o1, Player o2)
{
return o1.getName().compareTo(o2.getName());
}
});
}
public static List<Player> getSortedPlayers(Comparator<Player> comparator)
{
ArrayList<Player> players = new ArrayList<Player>(getServer().getOnlinePlayers());
Collections.sort(players, comparator);
return players;
}
public static Server getServer()
{
return Bukkit.getServer();
@ -23,6 +48,12 @@ public class UtilServer
UtilPlayer.message(cur, message);
}
public static void broadcast(LinkedList<String> messages)
{
for (Player cur : getPlayers())
UtilPlayer.message(cur, messages);
}
public static void broadcastSpecial(String event, String message)
{
for (Player cur : getPlayers())

View File

@ -1,6 +1,13 @@
package mineplex.core.common.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
public class UtilSkull
{
@ -25,6 +32,19 @@ public class UtilSkull
return 3;
}
public static ItemStack getPlayerHead(String playerName, String itemName, List<String> itemLore)
{
boolean displayHead = !playerName.isEmpty();
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) 0, displayHead ? (byte) 3 : 0);
SkullMeta meta = ((SkullMeta) skull.getItemMeta());
if (displayHead)
meta.setOwner(playerName);
meta.setDisplayName(itemName);
meta.setLore(itemLore);
skull.setItemMeta(meta);
return skull;
}
public static boolean isPlayerHead(byte data)
{
return data == 3;

View File

@ -3,6 +3,7 @@ package mineplex.core.common.util;
import java.util.Collection;
import org.apache.commons.lang.WordUtils;
import org.bukkit.Material;
public class UtilText {
public static <T> String listToString(Collection<T> inputList, boolean comma) {
@ -95,4 +96,14 @@ public class UtilText {
public static String[] wrap(String text, int lineLength, boolean wrapLongerWords) {
return WordUtils.wrap(text, lineLength, "\00D0", wrapLongerWords).split("\00D0");
}
public static String repeat(String txt, int times)
{
return new String(new byte[times]).replace("\0", txt);
}
public static boolean plural(int x){
return x <= 0 ? true : x > 1;
}
}

View File

@ -44,12 +44,33 @@ public class UtilTime
public enum TimeUnit
{
FIT,
DAYS,
HOURS,
MINUTES,
SECONDS,
MILLISECONDS
FIT(1),
DAYS(86400000),
HOURS(3600000),
MINUTES(60000),
SECONDS(1000),
MILLISECONDS(1);
private long _ms;
TimeUnit(long ms)
{
_ms = ms;
}
public long getMilliseconds()
{
return _ms;
}
}
/**
* Convert from one TimeUnit to a different one
*/
public static long convert(long time, TimeUnit from, TimeUnit to)
{
long milleseconds = time * from.getMilliseconds();
return milleseconds / to.getMilliseconds();
}
public static String since(long epoch)
@ -103,7 +124,7 @@ public class UtilTime
if (type == TimeUnit.DAYS) text = (num = UtilMath.trim(trim, time / 86400000d)) + " Day";
else if (type == TimeUnit.HOURS) text = (num = UtilMath.trim(trim, time / 3600000d)) + " Hour";
else if (type == TimeUnit.MINUTES) text = (num = UtilMath.trim(trim, time / 60000d)) + " Minute";
else if (type == TimeUnit.SECONDS) text = (int) (num = (int) UtilMath.trim(trim, time / 1000d)) + " Second";
else if (type == TimeUnit.SECONDS) text = (int) (num = (int) UtilMath.trim(trim, time / 1000d)) + " Second";
else text = (int) (num = (int) UtilMath.trim(trim, time)) + " Millisecond";
}
else

View File

@ -0,0 +1,36 @@
package mineplex.core.common.util;
public class UtilUI
{
public static int[] getIndicesFor(int items, int startingLine, int newLinePadding)
{
return getIndicesFor(items, startingLine, 5, newLinePadding);
}
public static int[] getIndicesFor(int items, int startingLine)
{
return getIndicesFor(items, startingLine, 5, 0);
}
public static int[] getIndicesFor(int items, int startingLine, int itemsPerLine, int newLinePadding)
{
itemsPerLine = UtilMath.clamp(itemsPerLine, 1, 5);
int[] indices = new int[items];
int lines = (int) Math.ceil(items / ((double) itemsPerLine));
for (int line = 0; line < lines; line++)
{
int itemsInCurLine = line == lines - 1 ? items - (line * itemsPerLine) : itemsPerLine;
int startIndex = (startingLine * 9) + ((newLinePadding * 9) * line) + 9 * line - itemsInCurLine + 5;
for (int item = 0; item < itemsInCurLine; item++)
{
indices[(line * itemsPerLine) + item] = startIndex + (item * 2);
}
}
return indices;
}
}

View File

@ -7,6 +7,7 @@ import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.util.Vector;
public class UtilWorld
@ -45,7 +46,55 @@ public class UtilWorld
return null;
}
}
public static String blockToStr(Block block)
{
if (block == null)
return "";
return block.getWorld().getName() + "," +
block.getX() + "," +
block.getY() + "," +
block.getZ();
}
public static String blockToStrClean(Block block)
{
if (block == null)
return "";
return "(" + block.getX() + "," +
block.getY() + "," +
block.getZ() + ")";
}
public static Block strToBlock(String string)
{
if (string.length() == 0)
return null;
String[] parts = string.split(",");
try
{
for (World cur : UtilServer.getServer().getWorlds())
{
if (cur.getName().equalsIgnoreCase(parts[0]))
{
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
return cur.getBlockAt(x, y, z);
}
}
}
catch (Exception e)
{
}
return null;
}
public static String locToStr(Location loc)
{
if (loc == null)
@ -65,6 +114,14 @@ public class UtilWorld
return "(" + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ() + ")";
}
public static String vecToStrClean(Vector loc)
{
if (loc == null)
return "Null";
return "(" + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ")";
}
public static Location strToLoc(String string)
{
if (string.length() == 0)

View File

@ -13,12 +13,12 @@
<orderEntry type="library" name="jedis" level="project" />
<orderEntry type="library" name="commons-pool2" level="project" />
<orderEntry type="module" module-name="Mineplex.Core.Common" />
<orderEntry type="module" module-name="Classpath.Dummy" />
<orderEntry type="module" module-name="Mineplex.ServerData" />
<orderEntry type="library" name="craftbukkit" level="project" />
<orderEntry type="module" module-name="Mineplex.Database" />
<orderEntry type="library" name="jooq" level="project" />
<orderEntry type="library" name="commons-dbcp2" level="project" />
<orderEntry type="module" module-name="Classpath.Dummy" />
<orderEntry type="library" name="NoCheatPlus" level="project" />
<orderEntry type="module" module-name="Mineplex.PlayerCache" />
</component>

View File

@ -300,7 +300,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
{ // Lets delete it
int id = _entityMap.get(owner.getName()).get(metaPacket.a);
UtilPlayer.sendPacket(owner, new PacketPlayOutEntityDestroy(new int[]
verifier.bypassProcess(new PacketPlayOutEntityDestroy(new int[]
{
id
}));

View File

@ -34,6 +34,7 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
@ -47,7 +48,7 @@ public class CoreClientManager extends MiniPlugin
private AccountRepository _repository;
private NautHashMap<String, CoreClient> _clientList;
private HashSet<String> _duplicateLoginGlitchPreventionList;
private NautHashMap<String, ILoginProcessor> _loginProcessors = new NautHashMap<String, ILoginProcessor>();
private LinkedList<IQuerylessLoginProcessor> _querylessLoginProcessors = new LinkedList<IQuerylessLoginProcessor>();
@ -572,4 +573,10 @@ public class CoreClientManager extends MiniPlugin
return client.GetRank().has(rank);
}
public int getCachedClientAccountId(UUID uuid)
{
PlayerInfo playerInfo = PlayerCache.getInstance().getPlayer(uuid);
return playerInfo == null ? -1 : playerInfo.getAccountId();
}
}

View File

@ -10,4 +10,4 @@ public interface ILoginProcessor
void processLoginResultSet(String playerName, int accountId, ResultSet resultSet) throws SQLException;
String getQuery(int accountId, String uuid, String name);
}
}

View File

@ -277,7 +277,7 @@ public enum Achievement
//Champions
CHAMPIONS_WINS("Champion", 600,
new String[]{"Champions Domination.Wins", "Champions TDM.Wins", "Champions Capture the Flag.Wins"},
new String[]{"Champions Domination.Wins", "Champions TDM.Wins", "Champions CTF.Wins"},
new String[]{"Win 80 games of Dominate, TDM, or CTF"},
new int[]{80},
AchievementCategory.CHAMPIONS),
@ -295,43 +295,43 @@ public enum Achievement
AchievementCategory.CHAMPIONS),
CHAMPIONS_ASSASSINATION("Assassination", 1000,
new String[]{"Champions Domination.Assassination", "Champions TDM.Assassination", "Champions Capture the Flag.Assassination"},
new String[]{"Champions Domination.Assassination", "Champions TDM.Assassination", "Champions CTF.Assassination"},
new String[]{"Kill 40 players with Backstab without", "taking any damage from them"},
new int[]{40},
AchievementCategory.CHAMPIONS),
CHAMPIONS_MASS_ELECTROCUTION("Mass Electrocution", 1200,
new String[]{"Champions Domination.MassElectrocution", "Champions TDM.MassElectrocution", "Champions Capture the Flag.MassElectrocution"},
new String[]{"Champions Domination.MassElectrocution", "Champions TDM.MassElectrocution", "Champions CTF.MassElectrocution"},
new String[]{"Hit 4 enemies with a Lightning Orb"},
new int[]{1},
AchievementCategory.CHAMPIONS),
CHAMPIONS_THE_LONGEST_SHOT("The Longest Shot", 1200,
new String[]{"Champions Domination.TheLongestShot", "Champions TDM.TheLongestShot", "Champions Capture the Flag.TheLongestShot"},
new String[]{"Champions Domination.TheLongestShot", "Champions TDM.TheLongestShot", "Champions CTF.TheLongestShot"},
new String[]{"Kill someone using Longshot who", "is over 64 Blocks away from you"},
new int[]{1},
AchievementCategory.CHAMPIONS),
CHAMPIONS_EARTHQUAKE("Earthquake", 1200,
new String[]{"Champions Domination.Earthquake", "Champions TDM.Earthquake", "Champions Capture the Flag.Earthquake"},
new String[]{"Champions Domination.Earthquake", "Champions TDM.Earthquake", "Champions CTF.Earthquake"},
new String[]{"Launch 5 enemies using Seismic Slam"},
new int[]{1},
AchievementCategory.CHAMPIONS),
CHAMPIONS_CAPTURES("Sticky Fingers", 2500,
new String[]{"Champions Capture the Flag.Captures"},
new String[]{"Champions CTF.Captures"},
new String[]{"Capture the Enemy Flag 20 times"},
new int[]{20},
AchievementCategory.CHAMPIONS),
CHAMPIONS_CLUTCH("Clutch", 600,
new String[]{"Champions Capture the Flag.Clutch"},
new String[]{"Champions CTF.Clutch"},
new String[]{"Kill the Enemy Flag Carrier in Sudden Death"},
new int[]{1},
AchievementCategory.CHAMPIONS),
CHAMPIONS_SPECIAL_WIN("Champion of Champions", 3000,
new String[]{"Champions Capture the Flag.SpecialWin"},
new String[]{"Champions CTF.SpecialWin"},
new String[]{"Win the game with 5 more captures than the other team"},
new int[]{1},
AchievementCategory.CHAMPIONS),

View File

@ -78,7 +78,7 @@ public enum AchievementCategory
new StatDisplay[] { StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.GEMS_EARNED },
Material.BOOK_AND_QUILL, 0, GameCategory.CLASSICS, "Extra Tools Kit"),
CHAMPIONS("Champions", new String[] {"Champions Domination", "Champions TDM", "Champions Capture the Flag"},
CHAMPIONS("Champions", new String[] {"Champions Domination", "Champions TDM", "Champions CTF"},
new StatDisplay[] { StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.KILLS, StatDisplay.DEATHS, StatDisplay.GEMS_EARNED, new StatDisplay("Flags Captured", "Captures") },
Material.BEACON, 0, GameCategory.CHAMPIONS, "Extra Class Skills"),

View File

@ -0,0 +1,75 @@
package mineplex.core.blockrestore;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import mineplex.core.common.block.BlockData;
public class BlockDataRunnable implements Runnable
{
private JavaPlugin _plugin;
private boolean _started;
private BukkitTask _task;
private List<BlockData> _changedBlocks;
private Runnable _onComplete;
private int _blocksPerTick;
private Iterator<BlockData> _blockIterator;
public BlockDataRunnable(JavaPlugin plugin, Iterator<BlockData> blockIterator, int blocksPerTick, Runnable onComplete)
{
_plugin = plugin;
_changedBlocks = new ArrayList<BlockData>();
_started = false;
_blocksPerTick = blocksPerTick;
_onComplete = onComplete;
_blockIterator = blockIterator;
}
public void start()
{
if (!_started)
{
_task = Bukkit.getScheduler().runTaskTimer(_plugin, this, 1, 1);
_started = true;
}
}
public void pause()
{
if (_started)
{
_task.cancel();
_started = false;
}
}
public void setBlocksPerTick(int blocksPerTick)
{
_blocksPerTick = blocksPerTick;
}
@Override
public void run()
{
for (int i = 0; i < _blocksPerTick; i++)
{
if (_blockIterator.hasNext())
{
BlockData data = _blockIterator.next();
data.restore();
}
else
{
// We are done
_task.cancel();
_onComplete.run();
return;
}
}
}
}

View File

@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import mineplex.core.MiniPlugin;
import mineplex.core.updater.event.UpdateEvent;
@ -26,28 +27,40 @@ import org.bukkit.plugin.java.JavaPlugin;
public class BlockRestore extends MiniPlugin
{
private HashMap<Block, BlockRestoreData> _blocks = new HashMap<Block, BlockRestoreData>();
private LinkedList<BlockRestoreMap> _restoreMaps;
public BlockRestore(JavaPlugin plugin)
{
super("Block Restore", plugin);
_restoreMaps = new LinkedList<BlockRestoreMap>();
}
@EventHandler(priority=EventPriority.LOW)
public void BlockBreak(BlockBreakEvent event)
public void blockBreak(BlockBreakEvent event)
{
if (Contains(event.getBlock()))
if (contains(event.getBlock()))
{
BlockRestoreData data = _blocks.get(event.getBlock());
if (data != null && data.isRestoreOnBreak())
{
_blocks.remove(event.getBlock());
data.restore();
}
event.setCancelled(true);
}
}
@EventHandler(priority=EventPriority.LOW)
public void blockPlace(BlockPlaceEvent event)
{
if (contains(event.getBlockPlaced()))
event.setCancelled(true);
}
@EventHandler(priority=EventPriority.LOW)
public void BlockPlace(BlockPlaceEvent event)
{
if (Contains(event.getBlockPlaced()))
event.setCancelled(true);
}
@EventHandler(priority=EventPriority.LOW)
public void Piston(BlockPistonExtendEvent event)
public void piston(BlockPistonExtendEvent event)
{
if (event.isCancelled())
return;
@ -60,7 +73,7 @@ public class BlockRestore extends MiniPlugin
if (push.getType() == Material.AIR)
return;
if (Contains(push))
if (contains(push))
{
push.getWorld().playEffect(push.getLocation(), Effect.STEP_SOUND, push.getTypeId());
event.setCancelled(true);
@ -70,7 +83,7 @@ public class BlockRestore extends MiniPlugin
}
@EventHandler
public void ExpireBlocks(UpdateEvent event)
public void expireBlocks(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK)
return;
@ -86,15 +99,16 @@ public class BlockRestore extends MiniPlugin
_blocks.remove(cur);
}
public void Restore(Block block)
public boolean restore(Block block)
{
if (!Contains(block))
return;
if (!contains(block))
return false;
_blocks.remove(block).restore();
return true;
}
public void RestoreAll()
public void restoreAll()
{
for (BlockRestoreData data : _blocks.values())
data.restore();
@ -102,7 +116,7 @@ public class BlockRestore extends MiniPlugin
_blocks.clear();
}
public HashSet<Location> RestoreBlockAround(Material type, Location location, int radius)
public HashSet<Location> restoreBlockAround(Material type, Location location, int radius)
{
HashSet<Location> restored = new HashSet<Location>();
@ -128,27 +142,36 @@ public class BlockRestore extends MiniPlugin
return restored;
}
public void Add(Block block, int toID, byte toData, long expireTime)
public void add(Block block, int toID, byte toData, long expireTime)
{
Add(block, toID, toData, block.getTypeId(), block.getData(), expireTime);
}
public void Add(Block block, int toID, byte toData, int fromID, byte fromData, long expireTime)
{
if (!Contains(block)) GetBlocks().put(block, new BlockRestoreData(block, toID, toData, fromID, fromData, expireTime, 0));
else GetData(block).update(toID, toData, expireTime);
add(block, toID, toData, expireTime, false);
}
public void Snow(Block block, byte heightAdd, byte heightMax, long expireTime, long meltDelay, int heightJumps)
public void add(Block block, int toID, byte toData, long expireTime, boolean restoreOnBreak)
{
add(block, toID, toData, block.getTypeId(), block.getData(), expireTime, restoreOnBreak);
}
public void add(Block block, int toID, byte toData, int fromID, byte fromData, long expireTime)
{
add(block, toID, toData, fromID, fromData, expireTime, false);
}
public void add(Block block, int toID, byte toData, int fromID, byte fromData, long expireTime, boolean restoreOnBreak)
{
if (!contains(block)) getBlocks().put(block, new BlockRestoreData(block, toID, toData, fromID, fromData, expireTime, 0, restoreOnBreak));
else getData(block).update(toID, toData, expireTime);
}
public void snow(Block block, byte heightAdd, byte heightMax, long expireTime, long meltDelay, int heightJumps)
{
//Fill Above
if (((block.getTypeId() == 78 && block.getData() >= (byte)7) || block.getTypeId() == 80) && GetData(block) != null)
if (((block.getTypeId() == 78 && block.getData() >= (byte)7) || block.getTypeId() == 80) && getData(block) != null)
{
GetData(block).update(78, heightAdd, expireTime, meltDelay);
getData(block).update(78, heightAdd, expireTime, meltDelay);
if (heightJumps > 0) Snow(block.getRelative(BlockFace.UP), heightAdd, heightMax, expireTime, meltDelay, heightJumps-1);
if (heightJumps == -1) Snow(block.getRelative(BlockFace.UP), heightAdd, heightMax, expireTime, meltDelay, -1);
if (heightJumps > 0) snow(block.getRelative(BlockFace.UP), heightAdd, heightMax, expireTime, meltDelay, heightJumps - 1);
if (heightJumps == -1) snow(block.getRelative(BlockFace.UP), heightAdd, heightMax, expireTime, meltDelay, -1);
return;
}
@ -188,30 +211,59 @@ public class BlockRestore extends MiniPlugin
heightAdd = 0;
//Snow
if (!Contains(block))
GetBlocks().put(block, new BlockRestoreData(block, 78, (byte)Math.max(0, heightAdd-1), block.getTypeId(), block.getData(), expireTime, meltDelay));
if (!contains(block))
getBlocks().put(block, new BlockRestoreData(block, 78, (byte) Math.max(0, heightAdd - 1), block.getTypeId(), block.getData(), expireTime, meltDelay, false));
else
GetData(block).update(78, heightAdd, expireTime, meltDelay);
getData(block).update(78, heightAdd, expireTime, meltDelay);
}
public boolean Contains(Block block)
public boolean contains(Block block)
{
if (GetBlocks().containsKey(block))
if (getBlocks().containsKey(block))
return true;
for (BlockRestoreMap restoreMap : _restoreMaps)
{
if (restoreMap.contains(block))
return true;
}
return false;
}
public BlockRestoreData GetData(Block block)
public BlockRestoreData getData(Block block)
{
if (_blocks.containsKey(block))
return _blocks.get(block);
return null;
}
public HashMap<Block, BlockRestoreData> GetBlocks()
public HashMap<Block, BlockRestoreData> getBlocks()
{
return _blocks;
}
public BlockRestoreMap createMap()
{
BlockRestoreMap map = new BlockRestoreMap(this);
_restoreMaps.add(map);
return map;
}
protected void removeMap(BlockRestoreMap blockRestore)
{
_restoreMaps.remove(blockRestore);
}
@Override
public void disable()
{
// Clear all restore maps
for (BlockRestoreMap restoreMap : _restoreMaps)
{
restoreMap.restoreInstant();
}
restoreAll();
}
}

View File

@ -25,7 +25,9 @@ public class BlockRestoreData
protected HashMap<Location, Byte> _pad = new HashMap<Location, Byte>();
public BlockRestoreData(Block block, int toID, byte toData, int fromID, byte fromData, long expireDelay, long meltDelay)
protected boolean _restoreOnBreak;
public BlockRestoreData(Block block, int toID, byte toData, int fromID, byte fromData, long expireDelay, long meltDelay, boolean restoreOnBreak)
{
_block = block;
@ -41,6 +43,8 @@ public class BlockRestoreData
_meltDelay = meltDelay;
_meltLast = System.currentTimeMillis();
_restoreOnBreak = restoreOnBreak;
//Set
set();
}
@ -151,6 +155,11 @@ public class BlockRestoreData
_block.setTypeIdAndData(_toID, _toData, true);
}
public boolean isRestoreOnBreak()
{
return _restoreOnBreak;
}
public void restore()
{
_block.setTypeIdAndData(_fromID, _fromData, true);

View File

@ -0,0 +1,181 @@
package mineplex.core.blockrestore;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import org.bukkit.Material;
import org.bukkit.block.Block;
import mineplex.core.common.block.BlockData;
public class BlockRestoreMap
{
private BlockRestore _blockRestore;
// The rate at which we restore blocks
private int _blocksPerTick;
// Easy access to all the blocks we have modified
private HashSet<Block> _changedBlocks;
// A hashmap for each level, so we can quickly restore top down
private HashMap<Block, BlockData>[] _blocks;
protected BlockRestoreMap(BlockRestore blockRestore)
{
this(blockRestore, 50);
}
protected BlockRestoreMap(BlockRestore blockRestore, int blocksPerTick)
{
_blockRestore = blockRestore;
_blocksPerTick = blocksPerTick;
_changedBlocks = new HashSet<Block>();
_blocks = new HashMap[256];
// Populate Array
for (int i = 0; i < 256; i++)
{
_blocks[i] = new HashMap<Block, BlockData>();
}
}
public void addBlockData(BlockData blockData)
{
Block block = blockData.Block;
if (!_blocks[block.getY()].containsKey(block))
_blocks[block.getY()].put(block, blockData);
_changedBlocks.add(blockData.Block);
}
public void set(Block block, Material material)
{
set(block, material, (byte) 0);
}
public void set(Block block, Material material, byte toData)
{
set(block, material.getId(), toData);
}
public void set(Block block, int toId, byte toData)
{
addBlockData(new BlockData(block));
block.setTypeIdAndData(toId, toData, false);
}
public boolean contains(Block block)
{
return _changedBlocks.contains(block);
}
public HashSet<Block> getChangedBlocks()
{
return _changedBlocks;
}
/**
* Restore all the blocks changed in this BlockRestoreMap
* NOTE: You should not use the same BlockRestoreMap instance after you run restore.
* You must initialize a new BlockRestoreMap from BlockRestore
*/
public void restore()
{
// The idea behind this is that the runnable will restore blocks over time
// If the server happens to shutdown while the runnable is running, we will still
// restore all our blocks with restoreInstant (as called by BlockRestore)
BlockDataRunnable runnable = new BlockDataRunnable(_blockRestore.getPlugin(), new RestoreIterator(), _blocksPerTick, new Runnable()
{
@Override
public void run()
{
clearMaps();
_blockRestore.removeMap(BlockRestoreMap.this);
}
});
runnable.start();
}
private void clearMaps()
{
for (int i = 0; i < 256; i++)
{
_blocks[i].clear();
}
_changedBlocks.clear();
}
public void restoreInstant()
{
for (int i = 0; i < 256; i++)
{
HashMap<Block, BlockData> map = _blocks[i];
for (BlockData data : map.values())
{
data.restore();
}
}
clearMaps();
}
public int getBlocksPerTick()
{
return _blocksPerTick;
}
public void setBlocksPerTick(int blocksPerTick)
{
_blocksPerTick = blocksPerTick;
}
private class RestoreIterator implements Iterator<BlockData>
{
private Iterator<BlockData> _currentIterator;
private int _currentIndex;
public RestoreIterator()
{
_currentIndex = 255;
updateIterator();
}
private void updateIterator()
{
_currentIterator = _blocks[_currentIndex].values().iterator();
}
@Override
public boolean hasNext()
{
while (!_currentIterator.hasNext() && _currentIndex > 0)
{
_currentIndex--;
updateIterator();
}
return _currentIterator.hasNext();
}
@Override
public BlockData next()
{
while (!_currentIterator.hasNext() && _currentIndex > 0)
{
_currentIndex--;
updateIterator();
}
return _currentIterator.next();
}
@Override
public void remove()
{
_currentIterator.remove();
}
}
}

View File

@ -732,7 +732,7 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
if (gold > 0)
{
UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(gold + " Gold")));
_donationManager.RewardGold(new Callback<Boolean>()
_donationManager.rewardGold(new Callback<Boolean>()
{
@Override
public void run(Boolean data)

View File

@ -76,7 +76,7 @@ public abstract class CommandBase<PluginType extends MiniPlugin> implements ICom
return null;
}
protected List<String> getMatches(String start, List<String> possibleMatches)
protected List<String> getMatches(String start, Collection<String> possibleMatches)
{
List<String> matches = new ArrayList<String>();

View File

@ -83,7 +83,7 @@ public class Creature extends MiniPlugin
return;
}
CreatureSpawnCustomEvent customEvent = new CreatureSpawnCustomEvent(event.getLocation());
CreatureSpawnCustomEvent customEvent = new CreatureSpawnCustomEvent(event.getLocation(), event.getSpawnReason());
_plugin.getServer().getPluginManager().callEvent(customEvent);

View File

@ -4,6 +4,7 @@ import org.bukkit.Location;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
public class CreatureSpawnCustomEvent extends Event implements Cancellable
{
@ -11,10 +12,12 @@ public class CreatureSpawnCustomEvent extends Event implements Cancellable
private boolean _cancelled = false;
private Location _location;
private SpawnReason _reason;
public CreatureSpawnCustomEvent(Location location)
public CreatureSpawnCustomEvent(Location location, SpawnReason reason)
{
_location = location;
_reason = reason;
}
public HandlerList getHandlers()
@ -43,4 +46,9 @@ public class CreatureSpawnCustomEvent extends Event implements Cancellable
{
return _location;
}
public SpawnReason getReason()
{
return _reason;
}
}

View File

@ -1,5 +1,6 @@
package mineplex.core.database;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -46,7 +47,7 @@ public abstract class RepositoryBase implements Listener
public void run()
{
initialize();
update();
update();
}
});
@ -69,7 +70,7 @@ public abstract class RepositoryBase implements Listener
{
return DSL.using(DBPool.ACCOUNT, SQLDialect.MYSQL);
}
/**
* Requirements: {@link Connection}s must be closed after usage so they may be returned to the pool!
* @see Connection#close()
@ -88,7 +89,7 @@ public abstract class RepositoryBase implements Listener
return null;
}
}
/**
* Execute a query against the repository.
* @param query - the concatenated query to execute in string form.

View File

@ -607,6 +607,22 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
{
entry.getKey().setEntity(entity);
boolean cancel = entry.getValue().length == 0;
for (Player player : entry.getValue())
{
if (player == owner)
{
cancel = true;
break;
}
}
if (cancel)
{
packetInfo.setCancelled(true);
}
disguise(entry.getKey(), false, entry.getValue());
}
}
@ -1046,8 +1062,12 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
_movePacketMap.remove(entity.getEntityId());
_moveTempMap.remove(entity.getEntityId());
_blockedNames.remove(((Player) entity).getName());
if (entity instanceof Player)
{
_blockedNames.remove(((Player) entity).getName());
}
refreshTrackers(entity, players.toArray(new Player[0]));
if (_bedPackets && disguise instanceof DisguisePlayer && ((DisguisePlayer) disguise).getSleepingDirection() != null)

View File

@ -0,0 +1,37 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.EntityType;
public class DisguiseCaveSpider extends DisguiseMonster
{
public DisguiseCaveSpider(org.bukkit.entity.Entity entity)
{
super(EntityType.CAVE_SPIDER, entity);
DataWatcher.a(16, new Byte((byte) 0));
}
public boolean bT()
{
return (DataWatcher.getByte(16) & 0x01) != 0;
}
public void a(boolean flag)
{
byte b0 = DataWatcher.getByte(16);
if (flag)
b0 = (byte) (b0 | 0x1);
else
b0 = (byte) (b0 & 0xFFFFFFFE);
DataWatcher.watch(16, Byte.valueOf(b0));
}
protected String getHurtSound()
{
return "mob.spider.say";
}
}

View File

@ -0,0 +1,38 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseGuardian extends DisguiseCreature
{
public DisguiseGuardian(org.bukkit.entity.Entity entity)
{
super(EntityType.GUARDIAN, entity);
DataWatcher.a(16, 0);
DataWatcher.a(17, 0);
}
public void setTarget(int target)
{
DataWatcher.watch(17, target);
}
public void setElder(boolean elder)
{
DataWatcher.watch(16, Integer.valueOf(DataWatcher.getInt(16) | 4));
}
public boolean isElder()
{
return (this.DataWatcher.getInt(16) & 4) != 0;
}
protected String getHurtSound()
{
if (isElder())
{
return "mob.guardian.elder.hit";
}
return "mob.guardian.hit";
}
}

View File

@ -44,6 +44,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
@Override
public void addCommands()
{
// TODO: Re-add commands? Where are command implementations, seen as missing at the moment.
addCommand(new GemCommand(this));
addCommand(new CoinCommand(this));
addCommand(new GoldCommand(this));
@ -62,7 +63,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
//_repository.updateGemsAndCoins(uuid, Get(token.Name).GetGems(), Get(token.Name).getCoins());
}
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final int accountId, final String packageName, final boolean coinPurchase, final int cost, boolean oneTimePurchase)
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final int accountId, final String packageName, final CurrencyType currencyType, final int cost, boolean oneTimePurchase)
{
final Donor donor = Bukkit.getPlayerExact(name) != null ? Get(name) : null;
@ -86,14 +87,14 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
if (donor != null)
{
donor.AddUnknownSalesPackagesOwned(packageName);
donor.DeductCost(cost, coinPurchase ? CurrencyType.Coins : CurrencyType.Gems);
donor.DeductCost(cost, currencyType);
}
}
if (callback != null)
callback.run(response);
}
}, name, accountId, packageName, coinPurchase, cost);
}, name, accountId, packageName, currencyType, cost);
}
public void PurchaseKnownSalesPackage(final Callback<TransactionResponse> callback, final String name, final UUID uuid, final int cost, final int salesPackageId)
@ -295,12 +296,17 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
_coinQueue.clear();
}
public void RewardGold(Callback<Boolean> callback, String caller, String name, int accountId, int amount)
public void rewardGold(Callback<Boolean> callback, String caller, Player player, int amount)
{
RewardGold(callback, caller, name, accountId, amount, true);
rewardGold(callback, caller, player.getName(), ClientManager.Get(player).getAccountId(), amount);
}
public void rewardGold(Callback<Boolean> callback, String caller, String name, int accountId, int amount)
{
rewardGold(callback, caller, name, accountId, amount, true);
}
public void RewardGold(final Callback<Boolean> callback, final String caller, final String name, final int accountId, final int amount, final boolean updateTotal)
public void rewardGold(final Callback<Boolean> callback, final String caller, final String name, final int accountId, final int amount, final boolean updateTotal)
{
_repository.rewardGold(new Callback<Boolean>()
{
@ -324,7 +330,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
}
if (callback != null)
callback.run(true);
callback.run(success);
}
}, caller, name, accountId, amount);
}
@ -349,37 +355,55 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
}
@EventHandler
public void UpdateGoldQueue(UpdateEvent event)
public void updateGoldQueue(UpdateEvent event)
{
if (event.getType() != UpdateType.SLOWER)
return;
for (Player player : _goldQueue.keySet())
{
String caller = null;
int total = 0;
for (String curCaller : _goldQueue.get(player).keySet())
{
caller = curCaller;
total += _goldQueue.get(player).get(curCaller);
}
if (caller == null)
continue;
//Actually Add Gold
RewardGold(null, caller, player.getName(), ClientManager.Get(player).getAccountId(), total, false);
System.out.println("Queue Added [" + player + "] with Gold [" + total + "] for [" + caller + "]");
//Clean
_goldQueue.get(player).clear();
updateGoldQueue(null, player);
}
//Clean
_goldQueue.clear();
}
public void updateGoldQueue(final Callback<Boolean> callback, final Player player)
{
String tempCaller = null;
int tempTotal = 0;
for (String curCaller : _goldQueue.get(player).keySet())
{
tempCaller = curCaller;
tempTotal += _goldQueue.get(player).get(curCaller);
}
final String caller = tempCaller;
final int total = tempTotal;
if (caller == null)
return;
if (player.isOnline() && player.isValid())
rewardGold(callback, caller, player.getName(), ClientManager.Get(player).getAccountId(), total, false);
else
{
Bukkit.getServer().getScheduler().runTaskAsynchronously(getPlugin(), new Runnable()
{
public void run()
{
rewardGold(callback, caller, player.getName(), PlayerCache.getInstance().getPlayer(player.getUniqueId()).getAccountId(), total, false);
}
});
}
System.out.println("Queue Added [" + player + "] with Gold [" + total + "] for [" + caller + "]");
//Clean
_goldQueue.get(player).clear();
}
public void applyKits(String playerName)
{

View File

@ -77,6 +77,10 @@ public class Donor
_coins -= cost;
_update = true;
break;
case Gold:
_gold -= cost;
_update = true;
break;
default:
break;
}
@ -90,6 +94,8 @@ public class Donor
return _gems;
case Coins:
return _coins;
case Gold:
return _gold;
case Tokens:
return 0;
default:
@ -145,7 +151,8 @@ public class Donor
public void addGold(int amount)
{
_gold += amount;
_gold = Math.max(0, _gold + amount);
}
public List<CoinTransactionToken> getCoinTransactions()

View File

@ -73,7 +73,7 @@ public class GoldCommand extends CommandBase<DonationManager>
private void rewardGold(final Player caller, final Player target, final String targetName, final int accountId, final int gold)
{
Plugin.RewardGold(new Callback<Boolean>()
Plugin.rewardGold(new Callback<Boolean>()
{
public void run(Boolean completed)
{

View File

@ -1,11 +1,15 @@
package mineplex.core.donation.repository;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.common.CurrencyType;
import mineplex.core.common.util.Callback;
import mineplex.core.database.DBPool;
import mineplex.core.database.DatabaseRunnable;
@ -69,12 +73,12 @@ public class DonationRepository extends RepositoryBase
}), "Error purchasing known sales package in DonationRepository : ");
}
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final int accountId, final String packageName, final boolean coinPurchase, final int cost)
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final int accountId, final String packageName, final CurrencyType currencyType, final int cost)
{
final UnknownPurchaseToken token = new UnknownPurchaseToken();
token.AccountName = name;
token.SalesPackageName = packageName;
token.CoinPurchase = coinPurchase;
token.CoinPurchase = currencyType == CurrencyType.Coins;
token.Cost = cost;
token.Premium = false;
@ -84,11 +88,15 @@ public class DonationRepository extends RepositoryBase
{
if (response == TransactionResponse.Success)
{
if (coinPurchase)
if (currencyType == CurrencyType.Coins)
{
executeUpdate(UPDATE_ACCOUNT_COINS, new ColumnInt("coins", -cost), new ColumnInt("id", accountId));
//executeUpdate(INSERT_COIN_TRANSACTION, new ColumnInt("id", accountId), new ColumnVarChar("reason", 100, "Purchased " + packageName), new ColumnInt("coins", -cost));
}
else if (currencyType == CurrencyType.Gold)
{
executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", -cost), new ColumnInt("id", accountId));
}
}
Bukkit.getServer().getScheduler().runTask(Plugin, new Runnable()
@ -185,16 +193,12 @@ public class DonationRepository extends RepositoryBase
{
public void run()
{
if (executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", gold), new ColumnInt("id", accountId)) < 1)
{
callback.run(false);
}
else
callback.run(true);
boolean success = executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", gold), new ColumnInt("id", accountId)) > 0;
callback.run(success);
}
}), "Error updating player gold amount in DonationRepository : ");
}
@Override
protected void initialize()
{

View File

@ -29,6 +29,7 @@ import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
@ -134,7 +135,7 @@ public class Explosion extends MiniPlugin
else
{
int heightDiff = cur.getLocation().getBlockY() - event.getEntity().getLocation().getBlockY();
_blockRestore.Add(cur, 0, (byte)0, (long) (20000 + (heightDiff*3000) + Math.random()*2900));
_blockRestore.add(cur, 0, (byte) 0, (long) (20000 + (heightDiff * 3000) + Math.random() * 2900));
}
}
@ -175,6 +176,7 @@ public class Explosion extends MiniPlugin
if (Math.random() > Math.min(0.975, chance))
{
FallingBlock fall = cur.getWorld().spawnFallingBlock(cur.getLocation().add(0.5, 0.5, 0.5), blocks.get(cur).getKey(), blocks.get(cur).getValue());
fall.setDropItem(false);
Vector vec = UtilAlg.getTrajectory(fEnt, fall);
if (vec.getY() < 0) vec.setY(vec.getY() * -1);
@ -207,6 +209,13 @@ public class Explosion extends MiniPlugin
}, 1);
}
@EventHandler
public void ExplosionChangeBlock(EntityChangeBlockEvent event)
{
if (_explosionBlocks.contains(event.getEntity()))
event.setCancelled(true);
}
@EventHandler
public void ExplosionBlockUpdate(UpdateEvent event)
{
@ -239,7 +248,7 @@ public class Explosion extends MiniPlugin
{
if (_temporaryDebris)
{
_blockRestore.Add(block, cur.getBlockId(), cur.getBlockData(), 10000);
_blockRestore.add(block, cur.getBlockId(), cur.getBlockData(), 10000);
}
else
{
@ -256,14 +265,6 @@ public class Explosion extends MiniPlugin
}
}
@EventHandler
public void ExplosionItemSpawn(ItemSpawnEvent event)
{
for (FallingBlock block : _explosionBlocks)
if (UtilMath.offset(event.getEntity().getLocation(), block.getLocation()) < 1)
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOW)
public void ExplosionBlocks(EntityExplodeEvent event)
{
@ -347,6 +348,7 @@ public class Explosion extends MiniPlugin
if (Math.random() > Math.min(0.98, chance))
{
FallingBlock fall = cur.getWorld().spawnFallingBlock(cur.getLocation().add(0.5, 0.5, 0.5), blocks.get(cur).getKey(), blocks.get(cur).getValue());
fall.setDropItem(false);
Vector vec = UtilAlg.getTrajectory(fLoc, fall.getLocation());
if (vec.getY() < 0) vec.setY(vec.getY() * -1);

View File

@ -164,7 +164,7 @@ public class ItemPaintbrush extends ItemGadget
continue;
//Color
Manager.getBlockRestore().Add(block, 35, _brushColor.get(player.getName()), 30000);
Manager.getBlockRestore().add(block, 35, _brushColor.get(player.getName()), 30000);
//Join Dots
if (_brushPrevious.containsKey(player.getName()))
@ -178,7 +178,7 @@ public class ItemPaintbrush extends ItemGadget
if (fixBlock.getType() != Material.WOOL)
continue;
Manager.getBlockRestore().Add(fixBlock, 35, _brushColor.get(player.getName()), 30000);
Manager.getBlockRestore().add(fixBlock, 35, _brushColor.get(player.getName()), 30000);
}
}

View File

@ -61,7 +61,7 @@ public class ItemTNT extends ItemGadget
if (!_tnt.remove(event.getEntity()))
return;
HashMap<Player, Double> players = UtilPlayer.getInRadius(event.getLocation(), 10);
HashMap<Player, Double> players = UtilPlayer.getInRadius(event.getLocation(), 8);
for (Player player : players.keySet())
{
if (Manager.collideEvent(this, player))

View File

@ -1,35 +1,241 @@
package mineplex.core.gadget.gadgets;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Zombie;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.util.Vector;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.MapUtil;
import mineplex.core.common.util.UtilAction;
import mineplex.core.common.util.UtilAlg;
import mineplex.core.common.util.UtilEnt;
import mineplex.core.common.util.UtilEvent;
import mineplex.core.common.util.UtilParticle;
import mineplex.core.common.util.UtilParticle.ParticleType;
import mineplex.core.common.util.UtilParticle.ViewDist;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilEvent.ActionType;
import mineplex.core.disguise.disguises.DisguiseBase;
import mineplex.core.disguise.disguises.DisguiseGuardian;
import mineplex.core.gadget.GadgetManager;
import mineplex.core.gadget.types.MorphGadget;
import mineplex.core.recharge.Recharge;
import mineplex.core.recharge.RechargedEvent;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
public class MorphTitan extends MorphGadget
{
private HashMap<Player, ArmorStand> _targets = new HashMap<Player, ArmorStand>();
public MorphTitan(GadgetManager manager)
{
super(manager, "Titanic Morph", new String[]
super(manager, "Elder Guardian Morph", new String[]
{
C.cWhite + "Coming Soon...",
C.cWhite + "From the depths of the sea, the",
C.cWhite + "Elder Guardian posseses powers",
C.cWhite + "more amazing than any seen before!",
" ",
C.cRed + "Unlocked with Titan Rank",
},
-1,
Material.INK_SACK, (byte)8);
Material.PRISMARINE_SHARD, (byte)0);
}
@Override
public void EnableCustom(Player player)
{
this.ApplyArmor(player);
DisguiseGuardian disguise = new DisguiseGuardian(player);
disguise.setName(player.getName(), Manager.getClientManager().Get(player).GetRank());
disguise.setCustomNameVisible(true);
disguise.setElder(true);
Manager.getDisguiseManager().disguise(disguise);
}
@Override
public void DisableCustom(Player player)
{
this.RemoveArmor(player);
Manager.getDisguiseManager().undisguise(player);
player.setAllowFlight(false);
player.setFlying(false);
Entity ent = _targets.remove(player);
if (ent != null)
ent.remove();
}
@EventHandler
public void lazer(PlayerInteractEvent event)
{
Player player = event.getPlayer();
if (!IsActive(player))
return;
if (!UtilEvent.isAction(event, ActionType.L))
return;
if (!Recharge.Instance.use(player, "Guardians Laser", 4000, true, false))
return;
DisguiseBase base = Manager.getDisguiseManager().getDisguise(player);
if (base == null || !(base instanceof DisguiseGuardian))
return;
DisguiseGuardian disguise = (DisguiseGuardian)base;
HashSet<Material> ignore = new HashSet<Material>();
ignore.add(Material.AIR);
Location loc = player.getTargetBlock(ignore, 64).getLocation().add(0.5, 0.5, 0.5);
ArmorStand stand = loc.getWorld().spawn(loc, ArmorStand.class);
stand.setVisible(false);
stand.setGhost(true);
stand.setGravity(false);
_targets.put(player, stand);
disguise.setTarget(stand.getEntityId());
Manager.getDisguiseManager().updateDisguise(disguise);
//Fake Head
UtilEnt.setFakeHead(player, true);
Recharge.Instance.useForce(player, GetName() + " FakeHead", 2000);
}
@EventHandler
public void lazerEnd(RechargedEvent event)
{
if (event.GetAbility().equals(GetName() + " FakeHead"))
{
UtilEnt.setFakeHead(event.GetPlayer(), false);
//Explode
ArmorStand stand = _targets.remove(event.GetPlayer());
if (stand != null)
{
UtilParticle.PlayParticle(ParticleType.HUGE_EXPLOSION, stand.getLocation(), 3f, 3f, 3f, 0, 32, ViewDist.MAX, UtilServer.getPlayers());
HashMap<LivingEntity, Double> players = UtilEnt.getInRadius(stand.getLocation(), 12);
for (Entity ent : players.keySet())
{
if (ent instanceof Player)
if (Manager.collideEvent(this, (Player)ent))
continue;
double mult = players.get(ent);
//Knockback
UtilAction.velocity(ent, UtilAlg.getTrajectory(stand.getLocation(), ent.getLocation()), 4 * mult, false, 0, 1 + 3 * mult, 10, true);
}
//Sound
stand.getWorld().playSound(stand.getLocation(), Sound.ZOMBIE_REMEDY, 6f, 0.75f);
stand.remove();
}
//Disguise
DisguiseBase base = Manager.getDisguiseManager().getDisguise(event.GetPlayer());
if (base == null || !(base instanceof DisguiseGuardian))
return;
DisguiseGuardian disguise = (DisguiseGuardian)base;
disguise.setTarget(0);
Manager.getDisguiseManager().updateDisguise(disguise);
}
}
@EventHandler
public void selfParticles(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK)
return;
for (Player player : _targets.keySet())
{
Vector dir = UtilAlg.getTrajectory( player.getLocation().add(0, 1.5, 0), _targets.get(player).getLocation());
dir.multiply(8);
UtilParticle.PlayParticle(ParticleType.MAGIC_CRIT,
player.getLocation().add(0, 1.5, 0),
(float)dir.getX(),
(float)dir.getY(),
(float)dir.getZ(),
1, 0, ViewDist.LONG, UtilServer.getPlayers());
player.playSound(player.getLocation(), Sound.FIREWORK_TWINKLE2, 2f, 2f);
}
}
@EventHandler
public void flight(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK)
return;
for (Player player : GetActive())
{
if (UtilPlayer.isSpectator(player))
continue;
player.setAllowFlight(true);
player.setFlying(true);
if (UtilEnt.isGrounded(player))
UtilAction.velocity(player, new Vector(0,1,0));
}
}
@EventHandler
public void titanOwner(PlayerJoinEvent event)
{
if (Manager.getClientManager().Get(event.getPlayer()).GetRank().has(Rank.TITAN))
{
Manager.getDonationManager().Get(event.getPlayer().getName()).AddUnknownSalesPackagesOwned(GetName());
}
}
@EventHandler
public void clean(UpdateEvent event)
{
if (event.getType() != UpdateType.SLOW)
return;
Iterator<Player> playerIter = _targets.keySet().iterator();
while (playerIter.hasNext())
{
Player player = playerIter.next();
if (!player.isOnline())
{
Entity ent = _targets.get(player);
ent.remove();
playerIter.remove();
}
}
}
}

View File

@ -94,7 +94,7 @@ public class ParticleBlizzard extends ParticleGadget
if (!event.getPlayer().isFlying())
if (IsActive(event.getPlayer()))
UtilParticle.PlayParticle(ParticleType.SNOW_SHOVEL, event.getPlayer().getLocation(), 0f, 0f, 0f, 0.6f, 100,
ViewDist.NORMAL, UtilServer.getPlayers());
ViewDist.LONGER, UtilServer.getPlayers());
}
@EventHandler
@ -122,7 +122,7 @@ public class ParticleBlizzard extends ParticleGadget
return;
UtilParticle.PlayParticle(ParticleType.SNOW_SHOVEL, event.getEntity().getLocation(), 0f, 0f, 0f, 0.4f, 12,
ViewDist.NORMAL, UtilServer.getPlayers());
ViewDist.LONGER, UtilServer.getPlayers());
}
@EventHandler
@ -142,7 +142,7 @@ public class ParticleBlizzard extends ParticleGadget
else
{
UtilParticle.PlayParticle(ParticleType.SNOW_SHOVEL, arrow.getLocation(), 0f, 0f, 0f, 0f, 1,
ViewDist.NORMAL, UtilServer.getPlayers());
ViewDist.LONGER, UtilServer.getPlayers());
}
}
}

View File

@ -1,22 +1,202 @@
package mineplex.core.gadget.gadgets;
import org.bukkit.Material;
import java.util.HashSet;
import java.util.Iterator;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerToggleFlightEvent;
import org.bukkit.util.Vector;
import mineplex.core.blood.BloodEvent;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.gadget.types.ParticleGadget;
import mineplex.core.common.util.UtilParticle;
import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilParticle.ParticleType;
import mineplex.core.common.util.UtilParticle.ViewDist;
import mineplex.core.gadget.GadgetManager;
import mineplex.core.gadget.types.ParticleGadget;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
public class ParticleTitan extends ParticleGadget
{
private HashSet<Arrow> _arrows = new HashSet<Arrow>();
private int _tick;
public ParticleTitan(GadgetManager manager)
{
super(manager, "Titanic Particle", new String[]
super(manager, "Flame of the Titans", new String[]
{
C.cWhite + "Coming Soon...",
C.cWhite + "These flames are said to be the",
C.cWhite + "souls of an lost civilisation of",
C.cWhite + "Titans, forgotten by time.",
" ",
C.cRed + "Unlocked with Titan Rank",
},
-1,
Material.INK_SACK, (byte)8);
-2,
Material.FIREBALL, (byte)0);
}
@EventHandler
public void onUpdate(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK)
return;
_tick++;
_tick = _tick%620;
for(Player player : GetActive())
{
if (!shouldDisplay(player))
continue;
double total = 3;
double step = (1/total)*Math.PI*2;
double offset1 = (step/20)*_tick%20;
double offset2 = (step/31)*_tick%31;
double r = 3;
boolean redstone = false;
if(Manager.isMoving(player))
r = 0.5;
for(int i = 0; i < total; i++)
{
double rad = step*i + offset1;
double x = Math.sin(rad);
double y = 0;
double z = Math.cos(rad);
Vector v = new Vector(x,y,z).normalize();
v.multiply(r);
Location loc = player.getLocation();
loc.add(0, 0.1, 0);
loc.add(v);
if(redstone) UtilParticle.PlayParticleToAll(ParticleType.RED_DUST, loc, 1, 0, 0, 1, 0, ViewDist.NORMAL);
v.multiply(-1);
UtilParticle.PlayParticleToAll(ParticleType.FLAME, loc, v, 0.05f, 0, ViewDist.NORMAL);
rad = -(step*i + offset2);
x = Math.sin(rad);
z = Math.cos(rad);
v = new Vector(x,y,z).normalize();
v.multiply(r);
loc = player.getLocation();
loc.add(0, 0.1, 0);
loc.add(v);
if(redstone) UtilParticle.PlayParticleToAll(ParticleType.RED_DUST, loc, 1, 0, 0, 1, 0, ViewDist.NORMAL);
v.multiply(-1);
UtilParticle.PlayParticleToAll(ParticleType.FLAME, loc, v, 0.05f, 0, ViewDist.NORMAL);
}
}
}
@EventHandler
public void jump(PlayerToggleFlightEvent event)
{
if (!shouldDisplay(event.getPlayer()))
return;
if (!event.getPlayer().isFlying())
if (IsActive(event.getPlayer()))
{
UtilParticle.PlayParticle(ParticleType.LAVA, event.getPlayer().getLocation(), 0f, 0f, 0f, 0.2f, 40,
ViewDist.NORMAL, UtilServer.getPlayers());
}
}
@EventHandler
public void arrow(ProjectileLaunchEvent event)
{
if (Manager.hideParticles())
return;
if (event.getEntity() instanceof Arrow)
{
if (event.getEntity().getShooter() != null)
{
if (GetActive().contains(event.getEntity().getShooter()))
{
_arrows.add((Arrow)event.getEntity());
}
}
}
}
@EventHandler
public void arrow(ProjectileHitEvent event)
{
if (!_arrows.remove(event.getEntity()))
return;
UtilParticle.PlayParticle(ParticleType.LAVA, event.getEntity().getLocation(), 0f, 0f, 0f, 0f, 24,
ViewDist.LONGER, UtilServer.getPlayers());
}
@EventHandler
public void arrowClean(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK)
return;
for (Iterator<Arrow> arrowIterator = _arrows.iterator(); arrowIterator.hasNext();)
{
Arrow arrow = arrowIterator.next();
if (arrow.isDead() || !arrow.isValid() || arrow.isOnGround())
{
arrowIterator.remove();
}
else
{
UtilParticle.PlayParticle(ParticleType.FLAME, arrow.getLocation(), 0f, 0f, 0f, 0f, 1,
ViewDist.LONGER, UtilServer.getPlayers());
}
}
}
@EventHandler
public void death(BloodEvent event)
{
if (event.getPlayer() == null)
return;
if (!IsActive(event.getPlayer()))
return;
if (!shouldDisplay(event.getPlayer()))
return;
event.setItem(Material.FIREBALL, (byte)0);
}
@EventHandler
public void legendOwner(PlayerJoinEvent event)
{
if (Manager.getClientManager().Get(event.getPlayer()).GetRank().has(Rank.TITAN))
{
Manager.getDonationManager().Get(event.getPlayer().getName()).AddUnknownSalesPackagesOwned(GetName());
}
}
}

View File

@ -8,6 +8,7 @@ public enum GameDisplay
//Mini
BaconBrawl("Bacon Brawl", Material.PORK, (byte)0, GameCategory.ARCADE, 1),
Barbarians("A Barbarians Life", Material.WOOD_AXE, (byte)0, GameCategory.EXTRA, 2),
BossBattles("Boss Battles", Material.SKULL_ITEM, (byte) 0, GameCategory.EVENT, 55),
Bridge("The Bridges", Material.IRON_PICKAXE, (byte)0, GameCategory.SURVIVAL, 3),
CastleSiege("Castle Siege", Material.DIAMOND_CHESTPLATE, (byte)0, GameCategory.CLASSICS, 4),
ChampionsDominate("Champions Domination", "Champions", Material.BEACON, (byte)0, GameCategory.CHAMPIONS, 6),

View File

@ -2,11 +2,8 @@ package mineplex.core.hologram;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
@ -34,7 +31,7 @@ public class Hologram
/**
* 1.7 packets uses both EntityIDs while 1.8 uses only the first.
*/
private ArrayList<Entry<Integer, Integer>> _entityIds = new ArrayList<Entry<Integer, Integer>>();
private ArrayList<Integer> _entityIds = new ArrayList<Integer>();
private Entity _followEntity;
private HologramManager _hologramManager;
private String[] _hologramText = new String[0];
@ -53,6 +50,7 @@ public class Hologram
private int _viewDistance = 70;
protected Vector relativeToEntity;
private boolean _hideBoundingBox;
private HologramInteraction _interaction;
public Hologram(HologramManager hologramManager, Location location, String... text)
{
@ -61,6 +59,18 @@ public class Hologram
setText(text);
}
public Hologram setInteraction(HologramInteraction interact)
{
_interaction = interact;
return this;
}
public HologramInteraction getInteraction()
{
return _interaction;
}
/**
* Adds the player to the Hologram to be effected by Whitelist or Blacklist
*/
@ -151,6 +161,7 @@ public class Hologram
nearbyPlayers.add(player);
}
}
return nearbyPlayers;
}
@ -229,9 +240,7 @@ public class Hologram
for (int i = 0; i < _entityIds.size(); i++)
{
Entry<Integer, Integer> entry = _entityIds.get(i);
entityIds1_8[i] = entry.getKey();
entityIds1_8[i] = _entityIds.get(i);
}
_destroy1_8 = new PacketPlayOutEntityDestroy(entityIds1_8);
@ -247,7 +256,7 @@ public class Hologram
for (int i = _entityIds.size(); i < _hologramText.length; i++)
{
_entityIds.add(new HashMap.SimpleEntry(UtilEnt.getNewEntityId(), UtilEnt.getNewEntityId()));
_entityIds.add(UtilEnt.getNewEntityId());
}
}
else
@ -261,9 +270,7 @@ public class Hologram
}
for (int textRow = 0; textRow < _hologramText.length; textRow++)
{
Entry<Integer, Integer> entityIds = this._entityIds.get(textRow);
Packet[] packets1_8 = makeSpawnPackets1_8(textRow, entityIds.getKey(), _hologramText[textRow]);
Packet[] packets1_8 = makeSpawnPackets1_8(textRow, _entityIds.get(textRow), _hologramText[textRow]);
for (int i = 0; i < packets1_8.length; i++)
{
@ -326,8 +333,7 @@ public class Hologram
public Hologram setFollowEntity(Entity entityToFollow)
{
_followEntity = entityToFollow;
relativeToEntity = entityToFollow == null ? null : this._location.clone().subtract(entityToFollow.getLocation())
.toVector();
relativeToEntity = entityToFollow == null ? null : _location.clone().subtract(entityToFollow.getLocation()).toVector();
return this;
}
@ -340,7 +346,7 @@ public class Hologram
*/
public Hologram setHologramTarget(HologramTarget newTarget)
{
this._target = newTarget;
_target = newTarget;
return this;
}
@ -405,11 +411,11 @@ public class Hologram
if (x >= -128 && x <= 127 && y >= -128 && y <= 127 && z >= -128 && z <= 127)
{
_lastMovement.subtract(new Vector(x / 32D, y / 32D, z / 32D));
for (Entry<Integer, Integer> entityId : this._entityIds)
for (Integer entityId : _entityIds)
{
PacketPlayOutEntity.PacketPlayOutRelEntityMove relMove = new PacketPlayOutEntity.PacketPlayOutRelEntityMove();
relMove.a = entityId.getKey();
relMove.a = entityId;
relMove.b = (byte) x;
relMove.c = (byte) y;
relMove.d = (byte) z;
@ -425,13 +431,12 @@ public class Hologram
_lastMovement = new Vector(newLocation.getX() - (x / 32D), 0, newLocation.getZ() - (z / 32D));
for (Entry<Integer, Integer> entityId : this._entityIds)
for (Integer entityId : _entityIds)
{
PacketPlayOutEntityTeleport teleportPacket = new PacketPlayOutEntityTeleport();
teleportPacket.a = entityId.getKey();
teleportPacket.a = entityId;
teleportPacket.b = x;
teleportPacket.c = (int) Math
.floor((oldLocation.getY() + (-2.1) + ((double) i * 0.285)) * 32);
teleportPacket.c = (int) Math.floor((oldLocation.getY() + (-2.1) + ((double) i * 0.285)) * 32);
teleportPacket.d = z;
packets1_8[i] = teleportPacket;
@ -458,6 +463,11 @@ public class Hologram
return this;
}
public boolean isEntityId(int entityId)
{
return _entityIds.contains(entityId);
}
/**
* Set the hologram text
*/
@ -491,28 +501,28 @@ public class Hologram
{
// Add entity id and send spawn packets
// You add a entity id because the new hologram needs
Entry<Integer, Integer> entry = new HashMap.SimpleEntry(UtilEnt.getNewEntityId(), UtilEnt.getNewEntityId());
_entityIds.add(entry);
int entityId = UtilEnt.getNewEntityId();
_entityIds.add(entityId);
packets1_8.addAll(Arrays.asList(makeSpawnPackets1_8(i, entry.getKey(), newText[i])));
packets1_8.addAll(Arrays.asList(makeSpawnPackets1_8(i, entityId, newText[i])));
}
// If less lines than previously
else if (i >= newText.length)
{
// Remove entity id and send destroy packets
Entry<Integer, Integer> entry = _entityIds.remove(newText.length);
Integer entityId = _entityIds.remove(newText.length);
destroy1_8 = Arrays.copyOf(destroy1_8, destroy1_8.length + 1);
destroy1_8[destroy1_8.length - 1] = entry.getKey();
destroy1_8[destroy1_8.length - 1] = entityId;
}
else if (!newText[i].equals(_hologramText[i]))
{
// Send update metadata packets
Entry<Integer, Integer> entry = _entityIds.get(i);
Integer entityId = _entityIds.get(i);
PacketPlayOutEntityMetadata metadata1_8 = new PacketPlayOutEntityMetadata();
metadata1_8.a = entry.getKey();
metadata1_8.a = entityId;
DataWatcher watcher1_8 = new DataWatcher(null);
@ -552,7 +562,7 @@ public class Hologram
*/
public Hologram setViewDistance(int newDistance)
{
this._viewDistance = newDistance;
_viewDistance = newDistance;
return setLocation(getLocation());
}
@ -593,6 +603,7 @@ public class Hologram
_playersTracking.clear();
_lastMovement = null;
}
return this;
}

View File

@ -0,0 +1,9 @@
package mineplex.core.hologram;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
public interface HologramInteraction
{
public void onClick(Player player, ClickType clickType);
}

View File

@ -5,90 +5,106 @@ import java.util.Iterator;
import java.util.List;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.packethandler.IPacketHandler;
import mineplex.core.packethandler.PacketHandler;
import mineplex.core.packethandler.PacketInfo;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import net.minecraft.server.v1_8_R3.Packet;
import net.minecraft.server.v1_8_R3.PacketPlayInUseEntity;
import net.minecraft.server.v1_8_R3.PacketPlayInUseEntity.EnumEntityUseAction;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
public class HologramManager implements Listener
public class HologramManager implements Listener, IPacketHandler
{
private ArrayList<Hologram> _activeHolograms = new ArrayList<Hologram>();
private ArrayList<Hologram> _activeHolograms = new ArrayList<Hologram>();
public HologramManager(JavaPlugin arcadeManager)
{
Bukkit.getPluginManager().registerEvents(this, arcadeManager);
}
public HologramManager(JavaPlugin arcadeManager, PacketHandler packetHandler)
{
Bukkit.getPluginManager().registerEvents(this, arcadeManager);
packetHandler.addPacketHandler(this, true, PacketPlayInUseEntity.class);
}
void addHologram(Hologram hologram)
{
_activeHolograms.add(hologram);
}
void addHologram(Hologram hologram)
{
_activeHolograms.add(hologram);
}
void removeHologram(Hologram hologram)
{
_activeHolograms.remove(hologram);
}
void removeHologram(Hologram hologram)
{
_activeHolograms.remove(hologram);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onTick(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK || _activeHolograms.isEmpty())
return;
List<World> worlds = Bukkit.getWorlds();
Iterator<Hologram> itel = _activeHolograms.iterator();
while (itel.hasNext())
{
Hologram hologram = itel.next();
if (!worlds.contains(hologram.getLocation().getWorld()))
{
itel.remove();
hologram.stop();
}
else
{
if (hologram.getEntityFollowing() != null)
{
Entity following = hologram.getEntityFollowing();
if (hologram.isRemoveOnEntityDeath() && !following.isValid())
{
itel.remove();
hologram.stop();
continue;
}
if (!hologram.relativeToEntity.equals(following.getLocation().subtract(hologram.getLocation()).toVector()))
{
// And we do this so in the rare offchance it changes by a decimal. It doesn't start turning wonky.
Vector vec = hologram.relativeToEntity.clone();
hologram.setLocation(following.getLocation().add(hologram.relativeToEntity));
hologram.relativeToEntity = vec;
continue; // No need to do the rest of the code as setLocation does it.
}
}
ArrayList<Player> canSee = hologram.getNearbyPlayers();
Iterator<Player> itel2 = hologram.getPlayersTracking().iterator();
while (itel2.hasNext())
{
Player player = itel2.next();
if (!canSee.contains(player))
{
itel2.remove();
if (player.getWorld() == hologram.getLocation().getWorld())
{
UtilPlayer.sendPacket(player, hologram.getDestroyPacket());
}
}
}
for (Player player : canSee)
@EventHandler(priority = EventPriority.LOWEST)
public void onTick(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK || _activeHolograms.isEmpty())
return;
List<World> worlds = Bukkit.getWorlds();
Iterator<Hologram> itel = _activeHolograms.iterator();
while (itel.hasNext())
{
Hologram hologram = itel.next();
if (!worlds.contains(hologram.getLocation().getWorld()))
{
itel.remove();
hologram.stop();
}
else
{
if (hologram.getEntityFollowing() != null)
{
Entity following = hologram.getEntityFollowing();
if (hologram.isRemoveOnEntityDeath() && !following.isValid())
{
itel.remove();
hologram.stop();
continue;
}
if (!hologram.relativeToEntity.equals(following.getLocation().subtract(hologram.getLocation()).toVector()))
{
// And we do this so in the rare offchance it changes by a decimal. It doesn't start turning wonky.
Vector vec = hologram.relativeToEntity.clone();
hologram.setLocation(following.getLocation().add(hologram.relativeToEntity));
hologram.relativeToEntity = vec;
continue; // No need to do the rest of the code as setLocation does it.
}
}
ArrayList<Player> canSee = hologram.getNearbyPlayers();
Iterator<Player> itel2 = hologram.getPlayersTracking().iterator();
while (itel2.hasNext())
{
Player player = itel2.next();
if (!canSee.contains(player))
{
itel2.remove();
if (player.getWorld() == hologram.getLocation().getWorld())
{
UtilPlayer.sendPacket(player, hologram.getDestroyPacket());
}
}
}
for (Player player : canSee)
{
if (!hologram.getPlayersTracking().contains(player))
{
@ -96,8 +112,28 @@ public class HologramManager implements Listener
UtilPlayer.sendPacket(player, hologram.getSpawnPackets());
}
}
}
}
}
}
}
}
}
@Override
public void handle(PacketInfo packetInfo)
{
PacketPlayInUseEntity packetPlayIn = (PacketPlayInUseEntity) packetInfo.getPacket();
for (Hologram hologram : _activeHolograms)
{
if (!hologram.isEntityId(packetPlayIn.a))
continue;
if (hologram.getInteraction() != null)
{
hologram.getInteraction().onClick(packetInfo.getPlayer(),
packetPlayIn.action == EnumEntityUseAction.ATTACK ? ClickType.LEFT : ClickType.RIGHT);
}
break;
}
}
}

View File

@ -708,6 +708,11 @@ public class ItemStackFactory extends MiniPlugin
return CreateStack(type.getId(), data, amount, (short)0, name, new String[] {}, null);
}
public ItemStack CreateStack(Material type, byte data, int amount, String name, boolean unbreakable)
{
return CreateStack(type.getId(), data, amount, (short)0, name, new String[] {}, null, unbreakable);
}
public ItemStack CreateStack(int id, byte data, int amount, String name)
{
return CreateStack(id, data, amount, (short)0, name, new String[] {}, null);
@ -763,6 +768,11 @@ public class ItemStackFactory extends MiniPlugin
return CreateStack(type.getId(), data, amount, (short)0, name, ArrayToList(lore), owner);
}
public ItemStack CreateStack(Material type, byte data, int amount, String name, String[] lore, String owner, boolean unbreakable)
{
return CreateStack(type.getId(), data, amount, (short)0, name, ArrayToList(lore), owner, unbreakable);
}
public ItemStack CreateStack(int id, byte data, int amount, String name, String[] lore, String owner)
{
return CreateStack(id, data, amount, (short)0, name, ArrayToList(lore), owner);
@ -778,15 +788,26 @@ public class ItemStackFactory extends MiniPlugin
return CreateStack(id, data, amount, damage, name, ArrayToList(lore), owner);
}
public ItemStack CreateStack(int id, byte data, int amount, short damage, String name, String[] lore, String owner, boolean unbreakable)
{
return CreateStack(id, data, amount, damage, name, ArrayToList(lore), owner, unbreakable);
}
public ItemStack CreateStack(Material type, byte data, int amount, short damage, String name, List<String> lore, String owner)
{
return CreateStack(type.getId(), data, amount, damage, name, lore, owner);
}
public ItemStack CreateStack(int id, byte data, int amount, short damage, String name, List<String> lore, String owner)
{
return CreateStack(id, data, amount, damage, name, lore, owner, true);
}
//XXX Owner Variant End
@SuppressWarnings("deprecation")
public ItemStack CreateStack(int id, byte data, int amount, short damage, String name, List<String> lore, String owner)
public ItemStack CreateStack(int id, byte data, int amount, short damage, String name, List<String> lore, String owner, boolean unbreakable)
{
ItemStack stack;
if (data == 0)
@ -855,16 +876,45 @@ public class ItemStackFactory extends MiniPlugin
stack.setItemMeta(itemMeta);
//Unbreakable
if (stack.getType().getMaxDurability() > 1)
if (unbreakable)
{
ItemMeta meta = stack.getItemMeta();
meta.spigot().setUnbreakable(true);
stack.setItemMeta(meta);
if (stack.getType().getMaxDurability() > 1)
{
ItemMeta meta = stack.getItemMeta();
meta.spigot().setUnbreakable(true);
stack.setItemMeta(meta);
}
}
return stack;
}
public void addOwnerLore(ItemStack item, String owner)
{
if (owner != null)
{
ItemMeta itemMeta = item.getItemMeta();
String[] tokens = owner.split(" ");
String[] ownerLore = new String[tokens.length + 2];
ownerLore[0] = C.cGray + "Owner: " + C.cAqua + tokens[0];
if (ownerLore.length >= 3)
ownerLore[1] = C.cGray + "Source: " + C.cAqua + tokens[1];
ownerLore[ownerLore.length - 2] = C.cGray + "Created: " + C.cAqua + UtilTime.date();
ownerLore[ownerLore.length - 1] = "";
if (itemMeta.getLore() != null) itemMeta.setLore(CombineLore(itemMeta.getLore(), ArrayToList(ownerLore)));
else itemMeta.setLore(ArrayToList(ownerLore));
item.setItemMeta(itemMeta);
}
}
private List<String> CombineLore(List<String> A, List<String> B)
{
for (String b : B)

View File

@ -97,11 +97,11 @@ public class LagMeter extends MiniPlugin
_count++;
if (System.currentTimeMillis() - _start > 60000)
if (System.currentTimeMillis() - _start > 30000)
{
if (_timingsRunning)
{
if (_ticksPerSecond > 15 || System.currentTimeMillis() - _timingsStarted > 60000)
if (System.currentTimeMillis() - _timingsStarted > 30000)
{
getPlugin().getServer().dispatchCommand(Bukkit.getConsoleSender(), "timings paste");
_timingsRunning = false;

View File

@ -54,6 +54,7 @@ public abstract class Mount<T> extends SalesPackageBase implements Listener
Manager.setActive(player, this);
EnableCustom(player);
}
public abstract void EnableCustom(Player player);
public abstract void Disable(Player player);

View File

@ -1,8 +1,19 @@
package mineplex.core.mount.types;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.vehicle.VehicleDamageEvent;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilAction;
import mineplex.core.common.util.UtilAlg;
import mineplex.core.common.util.UtilEnt;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.mount.Mount;
@ -11,6 +22,7 @@ import mineplex.core.recharge.Recharge;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
@ -110,12 +122,9 @@ public class MountCart extends Mount<Minecart>
if (cart.getPassenger() == null)
continue;
if (!((CraftMinecart) cart).getHandle().onGround)
if (!UtilEnt.isGrounded(cart))
continue;
// if (!UtilEnt.isGrounded(cart))
// continue;
if (!(cart.getPassenger() instanceof Player))
continue;

View File

@ -1,27 +1,139 @@
package mineplex.core.mount.types;
import java.util.HashMap;
import org.bukkit.Material;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Horse.Color;
import org.bukkit.entity.Horse.Style;
import org.bukkit.entity.Horse.Variant;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.mount.HorseMount;
import mineplex.core.mount.Mount;
import mineplex.core.mount.MountManager;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
public class MountTitan extends HorseMount
public class MountTitan extends Mount<MountTitanData>
{
public MountTitan(MountManager manager)
public MountTitan(MountManager manager)
{
super(manager, "Titanic Mount", new String[]
super(manager, "Molten Snake", Material.MAGMA_CREAM, (byte)0, new String[]
{
C.cWhite + "Coming Soon...",
C.cWhite + "Deep under the earths surface, there",
C.cWhite + "exists a mythical species of Molten",
C.cWhite + "Snakes. This one will serve you eternally.",
" ",
C.cRed + "Unlocked with Titan Rank",
},
Material.INK_SACK,
(byte)8,
-1,
Color.BLACK, Style.BLACK_DOTS, Variant.UNDEAD_HORSE, 0.8, null);
}, -1);
}
@Override
public void EnableCustom(Player player)
{
player.leaveVehicle();
player.eject();
//Remove other mounts
Manager.DeregisterAll(player);
//Inform
UtilPlayer.message(player, F.main("Mount", "You spawned " + F.elem(GetName()) + "."));
//Store
_active.put(player, new MountTitanData(player, GetName()));
}
@Override
public void Disable(Player player)
{
MountTitanData data = _active.remove(player);
if (data != null)
{
data.clean();
//Inform
UtilPlayer.message(player, F.main("Mount", "You despawned " + F.elem(GetName()) + "."));
Manager.removeActive(player);
}
}
@EventHandler
public void update(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK)
return;
for (MountTitanData data : _active.values())
{
data.update();
}
}
@EventHandler
public void interactMount(PlayerInteractEntityEvent event)
{
if (event.getRightClicked() == null)
return;
if (!GetActive().containsKey(event.getPlayer()))
return;
if (!GetActive().get(event.getPlayer()).ownsMount(event.getPlayer()))
{
UtilPlayer.message(event.getPlayer(), F.main("Mount", "This is not your Mount!"));
return;
}
event.getPlayer().leaveVehicle();
event.getPlayer().eject();
GetActive().get(event.getPlayer()).mount(event.getPlayer(), event.getRightClicked());
}
@EventHandler
public void target(EntityTargetEvent event)
{
if (!(event.getEntity() instanceof Player))
return;
if (!GetActive().containsKey(event.getTarget()))
return;
if (!GetActive().get(event.getTarget()).ownsMount((Player)event.getEntity()))
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST)
public void target(EntityDamageEvent event)
{
for (MountTitanData data : _active.values())
{
if (data.ownsEntity(event.getEntity()))
event.setCancelled(true);
}
}
@EventHandler
public void titanOwner(PlayerJoinEvent event)
{
if (Manager.getClientManager().Get(event.getPlayer()).GetRank().has(Rank.TITAN))
{
Manager.getDonationManager().Get(event.getPlayer().getName()).AddUnknownSalesPackagesOwned(GetName());
}
}
}

View File

@ -0,0 +1,146 @@
package mineplex.core.mount.types;
import java.util.ArrayList;
import mineplex.core.common.util.UtilAlg;
import mineplex.core.common.util.UtilEnt;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.UtilPlayer;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.MagmaCube;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector;
public class MountTitanData
{
private String _owner;
private Slime _head;
private ArrayList<ArmorStand> _nodes;
public MountTitanData(Player player, String name)
{
_owner = player.getName();
Location loc = player.getLocation();
loc.setPitch(0);
loc.setYaw(0);
//Nodes
_nodes = new ArrayList<ArmorStand>();
for (int i=0 ; i<30 ; i++)
{
ArmorStand node = loc.getWorld().spawn(loc, ArmorStand.class);
node.setVisible(false);
node.setGravity(false);
node.setGhost(true);
node.setHelmet(new ItemStack(Material.NETHERRACK));
UtilEnt.setFakeHead(node, true);
_nodes.add(node);
}
//Head
_head = player.getWorld().spawn(loc, MagmaCube.class);
_head.setSize(2);
UtilEnt.ghost(_head, true, false);
_head.setCustomName(player.getName() + "'s " + name);
}
public void mount(Player player, Entity entity)
{
if (_head.equals(entity) || _nodes.contains(entity))
_head.setPassenger(player);
}
public void update()
{
//Head
if (_head.getPassenger() != null)
_head.setVelocity(_head.getPassenger().getLocation().getDirection().multiply(0.8).add(new Vector(0,0.2,0)));
Location infront = _head.getLocation().add(0, -1.5, 0);
//Move
for (int i=0 ; i<30 ; i++)
{
ArmorStand node = _nodes.get(i);
Location old = node.getLocation();
infront.setPitch(node.getLocation().getPitch());
infront.setYaw(node.getLocation().getYaw());
//Move
if (i == 0)
node.teleport(infront);
else if (UtilMath.offset(node.getLocation(), infront) > 0.6)
node.teleport(infront.add(UtilAlg.getTrajectory(infront, node.getLocation()).multiply(0.6)));
//Rotation
Vector vector = UtilAlg.getTrajectory(old, node.getLocation());
node.setHeadPose(new EulerAngle(
Math.toRadians(UtilAlg.GetPitch(vector)),
Math.toRadians(UtilAlg.GetYaw(vector)),
0));
infront = node.getLocation();
}
//Shuffle In
if (_head.getPassenger() == null)
{
for (int i=_nodes.size()-1 ; i>=0 ; i--)
{
ArmorStand node = _nodes.get(i);
if (i>0)
infront = _nodes.get(i-1).getLocation();
else
infront = _head.getLocation().add(0, -1.5, 0);
infront.setPitch(node.getLocation().getPitch());
infront.setYaw(node.getLocation().getYaw());
node.teleport(infront);
}
}
}
public void clean()
{
_head.remove();
for (ArmorStand stand : _nodes)
stand.remove();
}
public boolean ownsMount(Player player)
{
return _owner.equals(player.getName());
}
public boolean ownsEntity(Entity ent)
{
return (_head.equals(ent) || _nodes.contains(ent));
}
}

View File

@ -174,8 +174,7 @@ public class NpcManager extends MiniPlugin
public Npc getNpcByEntity(Entity entity)
{
if (entity == null)
return null;
if (entity == null) return null;
return getNpcByEntityUUID(entity.getUniqueId());
}

View File

@ -13,7 +13,7 @@ public class AddCommand extends CommandBase<NpcManager>
{
public AddCommand(NpcManager plugin)
{
super(plugin, Rank.DEVELOPER, "add");
super(plugin, Rank.JNR_DEV, "add");
}
@Override

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