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

This commit is contained in:
xGamingDudex 2015-11-28 14:05:20 +01:00
commit 24dee651da
538 changed files with 41462 additions and 5305 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.gen
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/segments_1 /.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/segments_1
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/write.lock /.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/write.lock
/Pocket

View File

@ -18,6 +18,9 @@
<element id="file-copy" path="$PROJECT_DIR$/Mineplex.Game.Clans/plugin.yml" /> <element id="file-copy" path="$PROJECT_DIR$/Mineplex.Game.Clans/plugin.yml" />
<element id="module-output" name="Mineplex.ServerData" /> <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/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> </root>
</artifact> </artifact>
</component> </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/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="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.PlayerCache" />
<element id="module-output" name="Mineplex.Game.Clans.Core" />
</root> </root>
</artifact> </artifact>
</component> </component>

View File

@ -7,6 +7,14 @@
<option name="STATIC_FIELD_NAME_PREFIX" value="_" /> <option name="STATIC_FIELD_NAME_PREFIX" value="_" />
<option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="20" /> <option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="20" />
<option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="10" /> <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"> <option name="IMPORT_LAYOUT_TABLE">
<value> <value>
<package name="javax" withSubpackages="true" static="false" /> <package name="javax" withSubpackages="true" static="false" />

View File

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

View File

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <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"> <data-source source="LOCAL" name="Mineplex" uuid="14dfc55d-5343-47c4-ab24-76a055b8059e">
<driver-ref>mysql</driver-ref> <driver-ref>mysql</driver-ref>
<synchronize>true</synchronize> <synchronize>true</synchronize>
<jdbc-driver>com.mysql.jdbc.Driver</jdbc-driver> <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> <driver-properties>
<property name="zeroDateTimeBehavior" value="convertToNull" /> <property name="zeroDateTimeBehavior" value="convertToNull" />
<property name="tinyInt1isBit" value="false" /> <property name="tinyInt1isBit" value="false" />

View File

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

View File

@ -16,7 +16,7 @@
</set> </set>
</option> </option>
</component> </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" /> <output url="file://$PROJECT_DIR$/out" />
</component> </component>
</project> </project>

View File

@ -3,21 +3,23 @@
<component name="ProjectModuleManager"> <component name="ProjectModuleManager">
<modules> <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$/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.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/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.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.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/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.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.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.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.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.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.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$/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.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> </modules>
</component> </component>
</project> </project>

View File

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

View File

@ -13,4 +13,3 @@
<orderEntry type="library" name="commons-logging" level="project" /> <orderEntry type="library" name="commons-logging" level="project" />
</component> </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;
}
}

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,7 +6,8 @@ public enum CurrencyType
{ {
Tokens(" Tokens", Material.EMERALD), Tokens(" Tokens", Material.EMERALD),
Coins(" Coins", Material.DOUBLE_PLANT), Coins(" Coins", Material.DOUBLE_PLANT),
Gems(" Gems", Material.EMERALD); Gems(" Gems", Material.EMERALD),
Gold(" Gold", Material.GOLD_NUGGET);
private String _prefix; private String _prefix;
private Material _displayMaterial; 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.block.Block;
import org.bukkit.Material; 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 BoldStrike = "§l§m";
public static String Line = "§n"; public static String Line = "§n";
public static String Italics = "§o"; public static String Italics = "§o";
public static String Reset = "§r";
public static String cAqua = "" + ChatColor.AQUA; public static String cAqua = "" + ChatColor.AQUA;
public static String cBlack = "" + ChatColor.BLACK; public static String cBlack = "" + ChatColor.BLACK;
@ -87,22 +88,26 @@ public class C
public static String chat = "" + ChatColor.WHITE; public static String chat = "" + ChatColor.WHITE;
public static String xBorderlands = "" + ChatColor.GOLD; 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 xMid = "" + ChatColor.WHITE;
public static String xNone = "" + ChatColor.GRAY; public static ChatColor xNone = ChatColor.YELLOW;
public static ChatColor xAdmin = ChatColor.WHITE; public static ChatColor xAdmin = ChatColor.WHITE;
public static ChatColor xSafe = ChatColor.AQUA; public static ChatColor xSafe = ChatColor.AQUA;
public static ChatColor xNeutral = ChatColor.YELLOW;
public static ChatColor xSelf = ChatColor.AQUA; public static ChatColor xSelf = ChatColor.AQUA;
public static ChatColor xAlly = ChatColor.GREEN; public static ChatColor xAlly = ChatColor.GREEN;
public static ChatColor xEnemy = ChatColor.YELLOW; public static ChatColor xEnemy = ChatColor.RED;
public static ChatColor xWar = 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 xPillage = ChatColor.LIGHT_PURPLE;
public static ChatColor xdNeutral = ChatColor.GOLD;
public static ChatColor xdSelf = ChatColor.DARK_AQUA; public static ChatColor xdSelf = ChatColor.DARK_AQUA;
public static ChatColor xdAlly = ChatColor.DARK_GREEN; public static ChatColor xdAlly = ChatColor.DARK_GREEN;
public static ChatColor xdEnemy = ChatColor.GOLD; public static ChatColor xdEnemy = ChatColor.DARK_RED;
public static ChatColor xdWar = ChatColor.DARK_RED; public static ChatColor xdWarWinning = ChatColor.DARK_PURPLE;
public static ChatColor xdWarLosing = ChatColor.DARK_RED;
public static ChatColor xdPillage = ChatColor.DARK_PURPLE; public static ChatColor xdPillage = ChatColor.DARK_PURPLE;
} }

View File

@ -1,6 +1,8 @@
package mineplex.core.common.util; package mineplex.core.common.util;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
@ -8,16 +10,24 @@ import java.util.TreeSet;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.EulerAngle; import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
import net.minecraft.server.v1_8_R3.EnumDirection;
public class UtilAlg public class UtilAlg
{ {
public static TreeSet<String> sortKey(Set<String> toSort) public static TreeSet<String> sortKey(Set<String> toSort)
{ {
TreeSet<String> sortedSet = new TreeSet<String>(); return sortSet(toSort, null);
for (String cur : toSort) }
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); sortedSet.add(cur);
return sortedSet; return sortedSet;
@ -40,7 +50,7 @@ public class UtilAlg
public static Vector getTrajectory(Vector from, Vector to) 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) public static Vector getTrajectory2d(Entity from, Entity to)
@ -55,7 +65,7 @@ public class UtilAlg
public static Vector getTrajectory2d(Vector from, Vector to) 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) public static boolean HasSight(Location from, Player to)
@ -408,6 +418,55 @@ public class UtilAlg
return bestLoc; 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) public static Location getNearestCornerLocation(Location near, Block block)
{ {
ArrayList<Location> corners = new ArrayList<Location>(); ArrayList<Location> corners = new ArrayList<Location>();
@ -441,8 +500,14 @@ public class UtilAlg
return value; return value;
} }
public static EulerAngle vectorToEuler(Vector vector) public static EulerAngle vectorToEuler(Vector vector)
{ {
return new EulerAngle(Math.toRadians(GetPitch(vector)), Math.toRadians(GetYaw(vector)), 0); //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,34 +4,41 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; 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.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.inventory.ItemStack; 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 class UtilBlock
{ {
public static void main(String[] args) { public static void main(String[] args)
{
for (Material m : Material.values()) { for (Material m : Material.values())
{
boolean thisSolid = fullSolid(m.getId()); boolean thisSolid = fullSolid(m.getId());
boolean solid = m.isSolid(); boolean solid = m.isSolid();
if (thisSolid != solid) { if (thisSolid != solid)
{
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Failed: "); sb.append("Failed: ");
sb.append(m.name()); sb.append(m.name());
int amount = 40 - sb.length(); int amount = 40 - sb.length();
for (int i = 0; i < amount; i++) { for (int i = 0; i < amount; i++)
{
sb.append(" "); sb.append(" ");
} }
sb.append(thisSolid); sb.append(thisSolid);
@ -43,7 +50,6 @@ public class UtilBlock
} }
/** /**
* A list of blocks that are usable * A list of blocks that are usable
*/ */
@ -53,7 +59,8 @@ public class UtilBlock
*/ */
public static HashSet<Byte> fullSolid = new HashSet<Byte>(); 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 * 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>(); public static HashSet<Byte> blockPassSet = new HashSet<Byte>();
/** /**
@ -61,7 +68,13 @@ public class UtilBlock
*/ */
public static HashSet<Byte> blockAirFoliageSet = new HashSet<Byte>(); 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.AIR.getId());
blockAirFoliageSet.add((byte) Material.SAPLING.getId()); blockAirFoliageSet.add((byte) Material.SAPLING.getId());
@ -281,6 +294,11 @@ public class UtilBlock
blockUseSet.add((byte) Material.JUNGLE_DOOR.getId()); blockUseSet.add((byte) Material.JUNGLE_DOOR.getId());
blockUseSet.add((byte) Material.ACACIA_DOOR.getId()); blockUseSet.add((byte) Material.ACACIA_DOOR.getId());
blockUseSet.add((byte) Material.DARK_OAK_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) public static boolean solid(Block block)
@ -288,10 +306,12 @@ public class UtilBlock
if (block == null) return false; if (block == null) return false;
return solid(block.getTypeId()); return solid(block.getTypeId());
} }
public static boolean solid(int block) public static boolean solid(int block)
{ {
return solid((byte)block); return solid((byte) block);
} }
public static boolean solid(byte block) public static boolean solid(byte block)
{ {
return !blockPassSet.contains(block); return !blockPassSet.contains(block);
@ -302,10 +322,12 @@ public class UtilBlock
if (block == null) return false; if (block == null) return false;
return airFoliage(block.getTypeId()); return airFoliage(block.getTypeId());
} }
public static boolean airFoliage(int block) public static boolean airFoliage(int block)
{ {
return airFoliage((byte)block); return airFoliage((byte) block);
} }
public static boolean airFoliage(byte block) public static boolean airFoliage(byte block)
{ {
return blockAirFoliageSet.contains(block); return blockAirFoliageSet.contains(block);
@ -313,15 +335,16 @@ public class UtilBlock
public static boolean fullSolid(Block block) public static boolean fullSolid(Block block)
{ {
if (block == null) if (block == null) return false;
return false;
return fullSolid(block.getTypeId()); return fullSolid(block.getTypeId());
} }
public static boolean fullSolid(int block) public static boolean fullSolid(int block)
{ {
return fullSolid((byte)block); return fullSolid((byte) block);
} }
public static boolean fullSolid(byte block) public static boolean fullSolid(byte block)
{ {
return fullSolid.contains(block); return fullSolid.contains(block);
@ -329,15 +352,16 @@ public class UtilBlock
public static boolean usable(Block block) public static boolean usable(Block block)
{ {
if (block == null) if (block == null) return false;
return false;
return usable(block.getTypeId()); return usable(block.getTypeId());
} }
public static boolean usable(int block) public static boolean usable(int block)
{ {
return usable((byte)block); return usable((byte) block);
} }
public static boolean usable(byte block) public static boolean usable(byte block)
{ {
return blockUseSet.contains(block); return blockUseSet.contains(block);
@ -351,27 +375,24 @@ public class UtilBlock
public static HashMap<Block, Double> getInRadius(Location loc, double dR, double maxHeight) public static HashMap<Block, Double> getInRadius(Location loc, double dR, double maxHeight)
{ {
HashMap<Block, Double> blockList = new HashMap<Block, Double>(); HashMap<Block, Double> blockList = new HashMap<Block, Double>();
int iR = (int)dR + 1; int iR = (int) dR + 1;
for (int x=-iR ; x <= iR ; x++) for (int x = -iR; x <= iR; x++)
for (int z=-iR ; z <= iR ; z++) for (int z = -iR; z <= iR; z++)
for (int y=-iR ; y <= iR ; y++) for (int y = -iR; y <= iR; y++)
{ {
if (Math.abs(y) > maxHeight) if (Math.abs(y) > maxHeight) continue;
continue;
Block curBlock = loc.getWorld().getBlockAt((int)(loc.getX()+x), (int)(loc.getY()+y), (int)(loc.getZ()+z)); 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));; double offset = UtilMath.offset(loc, curBlock.getLocation().add(0.5, 0.5, 0.5));;
if (offset <= dR) if (offset <= dR) blockList.put(curBlock, 1 - (offset / dR));
blockList.put(curBlock, 1 - (offset/dR));
} }
return blockList; return blockList;
} }
public static HashMap<Block, Double> getInRadius(Block block, double dR) public static HashMap<Block, Double> getInRadius(Block block, double dR)
{ {
return getInRadius(block, dR, false); return getInRadius(block, dR, false);
@ -380,11 +401,11 @@ public class UtilBlock
public static HashMap<Block, Double> getInRadius(Block block, double dR, boolean hollow) public static HashMap<Block, Double> getInRadius(Block block, double dR, boolean hollow)
{ {
HashMap<Block, Double> blockList = new HashMap<Block, Double>(); HashMap<Block, Double> blockList = new HashMap<Block, Double>();
int iR = (int)dR + 1; int iR = (int) dR + 1;
for (int x=-iR ; x <= iR ; x++) for (int x = -iR; x <= iR; x++)
for (int z=-iR ; z <= iR ; z++) for (int z = -iR; z <= iR; z++)
for (int y=-iR ; y <= iR ; y++) for (int y = -iR; y <= iR; y++)
{ {
Block curBlock = block.getRelative(x, y, z); Block curBlock = block.getRelative(x, y, z);
@ -402,11 +423,11 @@ public class UtilBlock
public static ArrayList<Block> getInSquare(Block block, double dR) public static ArrayList<Block> getInSquare(Block block, double dR)
{ {
ArrayList<Block> blockList = new ArrayList<Block>(); ArrayList<Block> blockList = new ArrayList<Block>();
int iR = (int)dR + 1; int iR = (int) dR + 1;
for (int x=-iR ; x <= iR ; x++) for (int x = -iR; x <= iR; x++)
for (int z=-iR ; z <= iR ; z++) for (int z = -iR; z <= iR; z++)
for (int y=-iR ; y <= iR ; y++) for (int y = -iR; y <= iR; y++)
{ {
blockList.add(block.getRelative(x, y, z)); blockList.add(block.getRelative(x, y, z));
} }
@ -416,8 +437,7 @@ public class UtilBlock
public static boolean isBlock(ItemStack item) public static boolean isBlock(ItemStack item)
{ {
if (item == null) if (item == null) return false;
return false;
return item.getTypeId() > 0 && item.getTypeId() < 256; return item.getTypeId() > 0 && item.getTypeId() < 256;
} }
@ -431,13 +451,8 @@ public class UtilBlock
{ {
Block block = world.getHighestBlockAt(x, z); Block block = world.getHighestBlockAt(x, z);
//Shuffle Down // Shuffle Down
while (block.getY() > 0 && while (block.getY() > 0 && (airFoliage(block) || block.getType() == Material.LEAVES || block.getType() == Material.LEAVES_2 || (ignore != null && ignore.contains(block.getType()))))
(
airFoliage(block) ||
block.getType() == Material.LEAVES ||
(ignore != null && ignore.contains(block.getType()))
))
{ {
block = block.getRelative(BlockFace.DOWN); block = block.getRelative(BlockFace.DOWN);
} }
@ -450,7 +465,8 @@ public class UtilBlock
* @param location of explosion * @param location of explosion
* @param strength of explosion * @param strength of explosion
* @param damageBlocksEqually - Treat all blocks as durability of dirt * @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 * @return
*/ */
public static ArrayList<Block> getExplosionBlocks(Location location, float strength, boolean damageBlocksEqually) public static ArrayList<Block> getExplosionBlocks(Location location, float strength, boolean damageBlocksEqually)
@ -490,8 +506,7 @@ public class UtilBlock
if (block.getType() != Material.AIR) if (block.getType() != Material.AIR)
{ {
Blocks.DIRT.a((net.minecraft.server.v1_8_R3.Entity) null); Blocks.DIRT.a((net.minecraft.server.v1_8_R3.Entity) null);
float f3 = (damageBlocksEqually ? Blocks.DIRT : world.getType(new BlockPosition(block.getX(), block.getY(), 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);
block.getZ())).getBlock()).a((net.minecraft.server.v1_8_R3.Entity) null);
f1 -= (f3 + 0.3F) * f2; f1 -= (f3 + 0.3F) * f2;
} }
@ -519,12 +534,11 @@ public class UtilBlock
if (diagonals) if (diagonals)
{ {
for (int x=-1 ; x<= 1 ; x++) for (int x = -1; x <= 1; x++)
for (int y=-1 ; y<= 1 ; y++) for (int y = -1; y <= 1; y++)
for (int z=-1 ; z<= 1 ; z++) for (int z = -1; z <= 1; z++)
{ {
if (x == 0 && y == 0 && z == 0) if (x == 0 && y == 0 && z == 0) continue;
continue;
blocks.add(block.getRelative(x, y, z)); blocks.add(block.getRelative(x, y, z));
} }
@ -554,6 +568,7 @@ public class UtilBlock
return false; 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); return getInBoundingBox(a, b, true);
@ -563,18 +578,18 @@ public class UtilBlock
{ {
ArrayList<Block> blocks = new ArrayList<Block>(); 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 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 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 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) if (block.getType() != Material.AIR) blocks.add(block);
blocks.add(block);
} }
else blocks.add(block); else
blocks.add(block);
} }
return blocks; return blocks;
@ -582,8 +597,7 @@ public class UtilBlock
public static int getStepSoundId(Block block) public static int getStepSoundId(Block block)
{ {
if (block.getTypeId() != 35 && block.getTypeId() != 159 && block.getTypeId() != 160) if (block.getTypeId() != 35 && block.getTypeId() != 159 && block.getTypeId() != 160) return block.getTypeId();
return block.getTypeId();
switch (block.getData()) switch (block.getData())
{ {
@ -625,6 +639,185 @@ public class UtilBlock
} }
} }
/**
* 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) public static HashSet<Block> findConnectedBlocks(Block block, HashSet<Block> blocks, int limit)
{ {
if (blocks == null) if (blocks == null)

View File

@ -547,6 +547,18 @@ public class UtilEnt
return false; 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, 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;
}
return false;
}
public static void PlayDamageSound(LivingEntity damagee) public static void PlayDamageSound(LivingEntity damagee)
{ {
Sound sound = Sound.HURT_FLESH; Sound sound = Sound.HURT_FLESH;

View File

@ -16,7 +16,8 @@ public class UtilEvent
L_BLOCK, L_BLOCK,
R, R,
R_AIR, R_AIR,
R_BLOCK R_BLOCK,
ANY
} }
public static boolean isAction(PlayerInteractEvent event, ActionType action) public static boolean isAction(PlayerInteractEvent event, ActionType action)
@ -39,6 +40,9 @@ public class UtilEvent
if (action == ActionType.R_BLOCK) if (action == ActionType.R_BLOCK)
return (event.getAction() == Action.RIGHT_CLICK_BLOCK); return (event.getAction() == Action.RIGHT_CLICK_BLOCK);
if (action == ActionType.ANY)
return event.getAction() != Action.PHYSICAL;
return false; 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,6 +13,43 @@ public class UtilGear
private static HashSet<Material> pickSet = new HashSet<Material>(); private static HashSet<Material> pickSet = new HashSet<Material>();
private static HashSet<Material> diamondSet = new HashSet<Material>(); private static HashSet<Material> diamondSet = new HashSet<Material>();
private static HashSet<Material> goldSet = 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) public static boolean isAxe(ItemStack item)
{ {
@ -126,6 +163,10 @@ public class UtilGear
{ {
goldSet.add(Material.GOLD_SWORD); goldSet.add(Material.GOLD_SWORD);
goldSet.add(Material.GOLD_AXE); 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()); return goldSet.contains(item.getType());

View File

@ -2,7 +2,7 @@ package mineplex.core.common.util;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols; import java.text.DecimalFormatSymbols;
import java.text.NumberFormat; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Random; import java.util.Random;
@ -16,7 +16,7 @@ public class UtilMath
{ {
String format = "#.#"; String format = "#.#";
for (int i=1 ; i<degree ; i++) for (int i = 1; i < degree; i++)
format += "#"; format += "#";
DecimalFormatSymbols symb = new DecimalFormatSymbols(Locale.US); DecimalFormatSymbols symb = new DecimalFormatSymbols(Locale.US);
@ -24,13 +24,18 @@ public class UtilMath
return Double.valueOf(twoDForm.format(d)); return Double.valueOf(twoDForm.format(d));
} }
public static Random random = new Random(); public static Random random = new Random();
public static int r(int i) public static int r(int i)
{ {
return random.nextInt(i); return random.nextInt(i);
} }
public static int rRange(int min, int max)
{
return min + r(1 + max - min);
}
public static double offset2d(Entity a, Entity b) public static double offset2d(Entity a, Entity b)
{ {
return offset2d(a.getLocation().toVector(), b.getLocation().toVector()); return offset2d(a.getLocation().toVector(), b.getLocation().toVector());
@ -60,7 +65,7 @@ public class UtilMath
public static double offset(Vector a, Vector b) 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) public static double offsetSquared(Entity a, Entity b)
@ -80,16 +85,35 @@ public class UtilMath
public static double rr(double d, boolean bidirectional) public static double rr(double d, boolean bidirectional)
{ {
if (bidirectional) if (bidirectional) return Math.random() * (2 * d) - d;
return Math.random() * (2 * d) - d;
return Math.random() * d; return Math.random() * d;
} }
public static <T> T randomElement(T[] array) { public static <T> T randomElement(T[] array)
if (array.length == 0) {
return null; if (array.length == 0) return null;
return array[random.nextInt(array.length)]; 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

@ -241,6 +241,12 @@ public class UtilParticle
return packet; 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) 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()); PlayParticle(type, location, (float) offset.getX(), (float) offset.getY(), (float) offset.getZ(), speed, count, dist, UtilServer.getPlayers());

View File

@ -4,13 +4,12 @@ import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID; 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.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity; 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.entity.Player;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.InventoryView;
import org.bukkit.potion.PotionEffect;
import org.bukkit.util.Vector; 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 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) private static boolean hasIntersection(Vector3D p1, Vector3D p2, Vector3D min, Vector3D max)
{ {
final double epsilon = 0.0001f; final double epsilon = 0.0001f;
@ -154,6 +166,30 @@ public class UtilPlayer
return hit; 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. * 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; 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>(); LinkedList<Player> nearbyMap = new LinkedList<Player>();
@ -404,8 +445,10 @@ public class UtilPlayer
if (cur.isDead()) if (cur.isDead())
continue; 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) if (dist > maxDist)
continue; continue;
@ -453,7 +496,7 @@ public class UtilPlayer
return best; return best;
} }
public static Player getClosest(Location loc, Entity ignore) public static Player getClosest(Location loc, Entity... ignore)
{ {
Player best = null; Player best = null;
double bestDist = 0; double bestDist = 0;
@ -466,8 +509,14 @@ public class UtilPlayer
if (cur.isDead()) if (cur.isDead())
continue; continue;
if (ignore != null && ignore.equals(cur)) if (ignore != null)
{
for (int i = 0; i < ignore.length; i++)
{
if (cur.equals(ignore[i]))
continue; continue;
}
}
double dist = UtilMath.offset(cur.getLocation(), loc); double dist = UtilMath.offset(cur.getLocation(), loc);
@ -499,6 +548,14 @@ public class UtilPlayer
System.out.println("Kicked Client [" + player.getName() + "] for [" + module + " - " + message + "]"); 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) public static HashMap<Player, Double> getInRadius(Location loc, double dR)
{ {
HashMap<Player, Double> players = new HashMap<Player, Double>(); HashMap<Player, Double> players = new HashMap<Player, Double>();
@ -590,6 +647,23 @@ public class UtilPlayer
return (((CraftEntity) player).getHandle().getDataWatcher().getByte(0) & 1 << 4) != 0; 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) public static void sendPacket(Player player, Packet... packets)
{ {
PlayerConnection connection = ((CraftPlayer) player).getHandle().playerConnection; 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) public static boolean isSpectator(Entity player)
{ {
if (player instanceof Player) if (player instanceof Player)

View File

@ -1,5 +1,11 @@
package mineplex.core.common.util; 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.Bukkit;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.Sound; import org.bukkit.Sound;
@ -12,6 +18,25 @@ public class UtilServer
return getServer().getOnlinePlayers().toArray(new Player[0]); 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() public static Server getServer()
{ {
return Bukkit.getServer(); return Bukkit.getServer();
@ -23,6 +48,12 @@ public class UtilServer
UtilPlayer.message(cur, message); 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) public static void broadcastSpecial(String event, String message)
{ {
for (Player cur : getPlayers()) for (Player cur : getPlayers())

View File

@ -1,6 +1,13 @@
package mineplex.core.common.util; 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.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
public class UtilSkull public class UtilSkull
{ {
@ -25,6 +32,19 @@ public class UtilSkull
return 3; 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) public static boolean isPlayerHead(byte data)
{ {
return data == 3; return data == 3;

View File

@ -3,6 +3,7 @@ package mineplex.core.common.util;
import java.util.Collection; import java.util.Collection;
import org.apache.commons.lang.WordUtils; import org.apache.commons.lang.WordUtils;
import org.bukkit.Material;
public class UtilText { public class UtilText {
public static <T> String listToString(Collection<T> inputList, boolean comma) { 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) { public static String[] wrap(String text, int lineLength, boolean wrapLongerWords) {
return WordUtils.wrap(text, lineLength, "\00D0", wrapLongerWords).split("\00D0"); 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 public enum TimeUnit
{ {
FIT, FIT(1),
DAYS, DAYS(86400000),
HOURS, HOURS(3600000),
MINUTES, MINUTES(60000),
SECONDS, SECONDS(1000),
MILLISECONDS 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) public static String since(long epoch)

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.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.World.Environment; import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
public class UtilWorld public class UtilWorld
@ -46,6 +47,54 @@ public class UtilWorld
} }
} }
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) public static String locToStr(Location loc)
{ {
if (loc == null) if (loc == null)
@ -65,6 +114,14 @@ public class UtilWorld
return "(" + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ() + ")"; 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) public static Location strToLoc(String string)
{ {
if (string.length() == 0) if (string.length() == 0)

View File

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

View File

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

View File

@ -34,6 +34,7 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result; import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
@ -572,4 +573,10 @@ public class CoreClientManager extends MiniPlugin
return client.GetRank().has(rank); return client.GetRank().has(rank);
} }
public int getCachedClientAccountId(UUID uuid)
{
PlayerInfo playerInfo = PlayerCache.getInstance().getPlayer(uuid);
return playerInfo == null ? -1 : playerInfo.getAccountId();
}
} }

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.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList;
import mineplex.core.MiniPlugin; import mineplex.core.MiniPlugin;
import mineplex.core.updater.event.UpdateEvent; import mineplex.core.updater.event.UpdateEvent;
@ -26,28 +27,40 @@ import org.bukkit.plugin.java.JavaPlugin;
public class BlockRestore extends MiniPlugin public class BlockRestore extends MiniPlugin
{ {
private HashMap<Block, BlockRestoreData> _blocks = new HashMap<Block, BlockRestoreData>(); private HashMap<Block, BlockRestoreData> _blocks = new HashMap<Block, BlockRestoreData>();
private LinkedList<BlockRestoreMap> _restoreMaps;
public BlockRestore(JavaPlugin plugin) public BlockRestore(JavaPlugin plugin)
{ {
super("Block Restore", plugin); super("Block Restore", plugin);
_restoreMaps = new LinkedList<BlockRestoreMap>();
} }
@EventHandler(priority=EventPriority.LOW) @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); event.setCancelled(true);
} }
@EventHandler(priority=EventPriority.LOW) @EventHandler(priority=EventPriority.LOW)
public void BlockPlace(BlockPlaceEvent event) public void piston(BlockPistonExtendEvent event)
{
if (Contains(event.getBlockPlaced()))
event.setCancelled(true);
}
@EventHandler(priority=EventPriority.LOW)
public void Piston(BlockPistonExtendEvent event)
{ {
if (event.isCancelled()) if (event.isCancelled())
return; return;
@ -60,7 +73,7 @@ public class BlockRestore extends MiniPlugin
if (push.getType() == Material.AIR) if (push.getType() == Material.AIR)
return; return;
if (Contains(push)) if (contains(push))
{ {
push.getWorld().playEffect(push.getLocation(), Effect.STEP_SOUND, push.getTypeId()); push.getWorld().playEffect(push.getLocation(), Effect.STEP_SOUND, push.getTypeId());
event.setCancelled(true); event.setCancelled(true);
@ -70,7 +83,7 @@ public class BlockRestore extends MiniPlugin
} }
@EventHandler @EventHandler
public void ExpireBlocks(UpdateEvent event) public void expireBlocks(UpdateEvent event)
{ {
if (event.getType() != UpdateType.TICK) if (event.getType() != UpdateType.TICK)
return; return;
@ -86,15 +99,16 @@ public class BlockRestore extends MiniPlugin
_blocks.remove(cur); _blocks.remove(cur);
} }
public void Restore(Block block) public boolean restore(Block block)
{ {
if (!Contains(block)) if (!contains(block))
return; return false;
_blocks.remove(block).restore(); _blocks.remove(block).restore();
return true;
} }
public void RestoreAll() public void restoreAll()
{ {
for (BlockRestoreData data : _blocks.values()) for (BlockRestoreData data : _blocks.values())
data.restore(); data.restore();
@ -102,7 +116,7 @@ public class BlockRestore extends MiniPlugin
_blocks.clear(); _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>(); HashSet<Location> restored = new HashSet<Location>();
@ -128,27 +142,36 @@ public class BlockRestore extends MiniPlugin
return restored; 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); add(block, toID, toData, expireTime, false);
} }
public void Add(Block block, int toID, byte toData, int fromID, byte fromData, long expireTime) public void add(Block block, int toID, byte toData, long expireTime, boolean restoreOnBreak)
{ {
if (!Contains(block)) GetBlocks().put(block, new BlockRestoreData(block, toID, toData, fromID, fromData, expireTime, 0)); add(block, toID, toData, block.getTypeId(), block.getData(), expireTime, restoreOnBreak);
else GetData(block).update(toID, toData, expireTime);
} }
public void Snow(Block block, byte heightAdd, byte heightMax, long expireTime, long meltDelay, int heightJumps) 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 //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 > 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 == -1) snow(block.getRelative(BlockFace.UP), heightAdd, heightMax, expireTime, meltDelay, -1);
return; return;
} }
@ -188,30 +211,59 @@ public class BlockRestore extends MiniPlugin
heightAdd = 0; heightAdd = 0;
//Snow //Snow
if (!Contains(block)) if (!contains(block))
GetBlocks().put(block, new BlockRestoreData(block, 78, (byte)Math.max(0, heightAdd-1), block.getTypeId(), block.getData(), expireTime, meltDelay)); getBlocks().put(block, new BlockRestoreData(block, 78, (byte) Math.max(0, heightAdd - 1), block.getTypeId(), block.getData(), expireTime, meltDelay, false));
else 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; return true;
for (BlockRestoreMap restoreMap : _restoreMaps)
{
if (restoreMap.contains(block))
return true;
}
return false; return false;
} }
public BlockRestoreData GetData(Block block) public BlockRestoreData getData(Block block)
{ {
if (_blocks.containsKey(block)) if (_blocks.containsKey(block))
return _blocks.get(block); return _blocks.get(block);
return null; return null;
} }
public HashMap<Block, BlockRestoreData> GetBlocks() public HashMap<Block, BlockRestoreData> getBlocks()
{ {
return _blocks; 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>(); 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; _block = block;
@ -41,6 +43,8 @@ public class BlockRestoreData
_meltDelay = meltDelay; _meltDelay = meltDelay;
_meltLast = System.currentTimeMillis(); _meltLast = System.currentTimeMillis();
_restoreOnBreak = restoreOnBreak;
//Set //Set
set(); set();
} }
@ -151,6 +155,11 @@ public class BlockRestoreData
_block.setTypeIdAndData(_toID, _toData, true); _block.setTypeIdAndData(_toID, _toData, true);
} }
public boolean isRestoreOnBreak()
{
return _restoreOnBreak;
}
public void restore() public void restore()
{ {
_block.setTypeIdAndData(_fromID, _fromData, true); _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) if (gold > 0)
{ {
UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(gold + " Gold"))); UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(gold + " Gold")));
_donationManager.RewardGold(new Callback<Boolean>() _donationManager.rewardGold(new Callback<Boolean>()
{ {
@Override @Override
public void run(Boolean data) public void run(Boolean data)

View File

@ -76,7 +76,7 @@ public abstract class CommandBase<PluginType extends MiniPlugin> implements ICom
return null; 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>(); List<String> matches = new ArrayList<String>();

View File

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

View File

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

View File

@ -1,5 +1,6 @@
package mineplex.core.database; package mineplex.core.database;
import java.sql.CallableStatement;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;

View File

@ -607,6 +607,22 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
{ {
entry.getKey().setEntity(entity); 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()); disguise(entry.getKey(), false, entry.getValue());
} }
} }
@ -1046,7 +1062,11 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
_movePacketMap.remove(entity.getEntityId()); _movePacketMap.remove(entity.getEntityId());
_moveTempMap.remove(entity.getEntityId()); _moveTempMap.remove(entity.getEntityId());
if (entity instanceof Player)
{
_blockedNames.remove(((Player) entity).getName()); _blockedNames.remove(((Player) entity).getName());
}
refreshTrackers(entity, players.toArray(new Player[0])); refreshTrackers(entity, players.toArray(new Player[0]));

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

@ -44,6 +44,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
@Override @Override
public void addCommands() public void addCommands()
{ {
// TODO: Re-add commands? Where are command implementations, seen as missing at the moment.
addCommand(new GemCommand(this)); addCommand(new GemCommand(this));
addCommand(new CoinCommand(this)); addCommand(new CoinCommand(this));
addCommand(new GoldCommand(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()); //_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; final Donor donor = Bukkit.getPlayerExact(name) != null ? Get(name) : null;
@ -86,14 +87,14 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
if (donor != null) if (donor != null)
{ {
donor.AddUnknownSalesPackagesOwned(packageName); donor.AddUnknownSalesPackagesOwned(packageName);
donor.DeductCost(cost, coinPurchase ? CurrencyType.Coins : CurrencyType.Gems); donor.DeductCost(cost, currencyType);
} }
} }
if (callback != null) if (callback != null)
callback.run(response); 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) 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(); _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(final Callback<Boolean> callback, final String caller, final String name, final int accountId, final int amount, final boolean updateTotal) 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)
{ {
_repository.rewardGold(new Callback<Boolean>() _repository.rewardGold(new Callback<Boolean>()
{ {
@ -324,7 +330,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
} }
if (callback != null) if (callback != null)
callback.run(true); callback.run(success);
} }
}, caller, name, accountId, amount); }, caller, name, accountId, amount);
} }
@ -349,27 +355,49 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
} }
@EventHandler @EventHandler
public void UpdateGoldQueue(UpdateEvent event) public void updateGoldQueue(UpdateEvent event)
{ {
if (event.getType() != UpdateType.SLOWER) if (event.getType() != UpdateType.SLOWER)
return; return;
for (Player player : _goldQueue.keySet()) for (Player player : _goldQueue.keySet())
{ {
String caller = null; updateGoldQueue(null, player);
int total = 0; }
//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()) for (String curCaller : _goldQueue.get(player).keySet())
{ {
caller = curCaller; tempCaller = curCaller;
total += _goldQueue.get(player).get(curCaller); tempTotal += _goldQueue.get(player).get(curCaller);
} }
if (caller == null) final String caller = tempCaller;
continue; final int total = tempTotal;
//Actually Add Gold if (caller == null)
RewardGold(null, caller, player.getName(), ClientManager.Get(player).getAccountId(), total, false); 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 + "]"); System.out.println("Queue Added [" + player + "] with Gold [" + total + "] for [" + caller + "]");
@ -377,10 +405,6 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
_goldQueue.get(player).clear(); _goldQueue.get(player).clear();
} }
//Clean
_goldQueue.clear();
}
public void applyKits(String playerName) public void applyKits(String playerName)
{ {
_repository.applyKits(playerName); _repository.applyKits(playerName);

View File

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

View File

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

View File

@ -29,6 +29,7 @@ import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed; import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.ItemSpawnEvent; import org.bukkit.event.entity.ItemSpawnEvent;
@ -134,7 +135,7 @@ public class Explosion extends MiniPlugin
else else
{ {
int heightDiff = cur.getLocation().getBlockY() - event.getEntity().getLocation().getBlockY(); 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)) 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()); 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); Vector vec = UtilAlg.getTrajectory(fEnt, fall);
if (vec.getY() < 0) vec.setY(vec.getY() * -1); if (vec.getY() < 0) vec.setY(vec.getY() * -1);
@ -207,6 +209,13 @@ public class Explosion extends MiniPlugin
}, 1); }, 1);
} }
@EventHandler
public void ExplosionChangeBlock(EntityChangeBlockEvent event)
{
if (_explosionBlocks.contains(event.getEntity()))
event.setCancelled(true);
}
@EventHandler @EventHandler
public void ExplosionBlockUpdate(UpdateEvent event) public void ExplosionBlockUpdate(UpdateEvent event)
{ {
@ -239,7 +248,7 @@ public class Explosion extends MiniPlugin
{ {
if (_temporaryDebris) if (_temporaryDebris)
{ {
_blockRestore.Add(block, cur.getBlockId(), cur.getBlockData(), 10000); _blockRestore.add(block, cur.getBlockId(), cur.getBlockData(), 10000);
} }
else 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) @EventHandler(priority = EventPriority.LOW)
public void ExplosionBlocks(EntityExplodeEvent event) public void ExplosionBlocks(EntityExplodeEvent event)
{ {
@ -347,6 +348,7 @@ public class Explosion extends MiniPlugin
if (Math.random() > Math.min(0.98, chance)) 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()); 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()); Vector vec = UtilAlg.getTrajectory(fLoc, fall.getLocation());
if (vec.getY() < 0) vec.setY(vec.getY() * -1); if (vec.getY() < 0) vec.setY(vec.getY() * -1);

View File

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

View File

@ -46,7 +46,9 @@ public class MorphTitan extends MorphGadget
{ {
super(manager, "Elder Guardian Morph", new String[] super(manager, "Elder Guardian Morph", new String[]
{ {
C.cWhite + "From deep withinsdngsg", 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", C.cRed + "Unlocked with Titan Rank",
}, },
@ -208,9 +210,9 @@ public class MorphTitan extends MorphGadget
@EventHandler @EventHandler
public void titanOwner(PlayerJoinEvent event) public void titanOwner(PlayerJoinEvent event)
{ {
// if (Manager.getClientManager().Get(event.getPlayer()).GetRank().has(Rank.TITAN)) if (Manager.getClientManager().Get(event.getPlayer()).GetRank().has(Rank.TITAN))
// { {
// Manager.getDonationManager().Get(event.getPlayer().getName()).AddUnknownSalesPackagesOwned(GetName()); Manager.getDonationManager().Get(event.getPlayer().getName()).AddUnknownSalesPackagesOwned(GetName());
// } }
} }
} }

View File

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

View File

@ -1,13 +1,24 @@
package mineplex.core.gadget.gadgets; package mineplex.core.gadget.gadgets;
import java.util.HashSet;
import java.util.Iterator;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; 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 org.bukkit.util.Vector;
import mineplex.core.blood.BloodEvent;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C; import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilParticle; 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.ParticleType;
import mineplex.core.common.util.UtilParticle.ViewDist; import mineplex.core.common.util.UtilParticle.ViewDist;
import mineplex.core.gadget.GadgetManager; import mineplex.core.gadget.GadgetManager;
@ -17,35 +28,38 @@ import mineplex.core.updater.event.UpdateEvent;
public class ParticleTitan extends ParticleGadget public class ParticleTitan extends ParticleGadget
{ {
private HashSet<Arrow> _arrows = new HashSet<Arrow>();
private int _tick; private int _tick;
public ParticleTitan(GadgetManager manager) 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", C.cRed + "Unlocked with Titan Rank",
}, },
// Price for debuging purposes -2,
10, Material.FIREBALL, (byte)0);
Material.INK_SACK, (byte)8);
} }
@EventHandler @EventHandler
public void onUpdate(UpdateEvent event) public void onUpdate(UpdateEvent event)
{ {
if (event.getType() != UpdateType.TICK) if (event.getType() != UpdateType.TICK)
{
return; return;
}
_tick++; _tick++;
_tick = _tick%620; _tick = _tick%620;
for(Player player : GetActive()) for(Player player : GetActive())
{ {
if (!shouldDisplay(player)) continue; if (!shouldDisplay(player))
continue;
double total = 3; double total = 3;
double step = (1/total)*Math.PI*2; double step = (1/total)*Math.PI*2;
@ -55,7 +69,8 @@ public class ParticleTitan extends ParticleGadget
double r = 3; double r = 3;
boolean redstone = false; boolean redstone = false;
if(Manager.isMoving(player)) r = 0.5; if(Manager.isMoving(player))
r = 0.5;
for(int i = 0; i < total; i++) for(int i = 0; i < total; i++)
{ {
@ -95,4 +110,93 @@ public class ParticleTitan extends ParticleGadget
} }
} }
} }
@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 //Mini
BaconBrawl("Bacon Brawl", Material.PORK, (byte)0, GameCategory.ARCADE, 1), BaconBrawl("Bacon Brawl", Material.PORK, (byte)0, GameCategory.ARCADE, 1),
Barbarians("A Barbarians Life", Material.WOOD_AXE, (byte)0, GameCategory.EXTRA, 2), 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), Bridge("The Bridges", Material.IRON_PICKAXE, (byte)0, GameCategory.SURVIVAL, 3),
CastleSiege("Castle Siege", Material.DIAMOND_CHESTPLATE, (byte)0, GameCategory.CLASSICS, 4), CastleSiege("Castle Siege", Material.DIAMOND_CHESTPLATE, (byte)0, GameCategory.CLASSICS, 4),
ChampionsDominate("Champions Domination", "Champions", Material.BEACON, (byte)0, GameCategory.CHAMPIONS, 6), ChampionsDominate("Champions Domination", "Champions", Material.BEACON, (byte)0, GameCategory.CHAMPIONS, 6),

View File

@ -708,6 +708,11 @@ public class ItemStackFactory extends MiniPlugin
return CreateStack(type.getId(), data, amount, (short)0, name, new String[] {}, null); 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) public ItemStack CreateStack(int id, byte data, int amount, String name)
{ {
return CreateStack(id, data, amount, (short)0, name, new String[] {}, null); 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); 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) 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); 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); 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) 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); 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 //XXX Owner Variant End
@SuppressWarnings("deprecation") @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; ItemStack stack;
if (data == 0) if (data == 0)
@ -855,16 +876,45 @@ public class ItemStackFactory extends MiniPlugin
stack.setItemMeta(itemMeta); stack.setItemMeta(itemMeta);
//Unbreakable //Unbreakable
if (unbreakable)
{
if (stack.getType().getMaxDurability() > 1) if (stack.getType().getMaxDurability() > 1)
{ {
ItemMeta meta = stack.getItemMeta(); ItemMeta meta = stack.getItemMeta();
meta.spigot().setUnbreakable(true); meta.spigot().setUnbreakable(true);
stack.setItemMeta(meta); stack.setItemMeta(meta);
} }
}
return stack; 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) private List<String> CombineLore(List<String> A, List<String> B)
{ {
for (String b : B) for (String b : B)

View File

@ -10,7 +10,10 @@ import org.bukkit.entity.Horse.Style;
import org.bukkit.entity.Horse.Variant; import org.bukkit.entity.Horse.Variant;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; 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.entity.EntityTargetEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
@ -28,11 +31,11 @@ public class MountTitan extends Mount<MountTitanData>
{ {
public MountTitan(MountManager manager) public MountTitan(MountManager manager)
{ {
super(manager, "Molten Snake", Material.REDSTONE_BLOCK, (byte)0, new String[] super(manager, "Molten Snake", Material.MAGMA_CREAM, (byte)0, new String[]
{ {
C.cWhite + "From the distant ether realm,", C.cWhite + "Deep under the earths surface, there",
C.cWhite + "this prized dragon is said to", C.cWhite + "exists a mythical species of Molten",
C.cWhite + "obey only true Heroes!", C.cWhite + "Snakes. This one will serve you eternally.",
" ", " ",
C.cRed + "Unlocked with Titan Rank", C.cRed + "Unlocked with Titan Rank",
}, -1); }, -1);
@ -115,12 +118,22 @@ public class MountTitan extends Mount<MountTitanData>
event.setCancelled(true); 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 @EventHandler
public void titanOwner(PlayerJoinEvent event) public void titanOwner(PlayerJoinEvent event)
{ {
// if (Manager.getClientManager().Get(event.getPlayer()).GetRank().has(Rank.TITAN)) if (Manager.getClientManager().Get(event.getPlayer()).GetRank().has(Rank.TITAN))
// { {
// Manager.getDonationManager().Get(event.getPlayer().getName()).AddUnknownSalesPackagesOwned(GetName()); Manager.getDonationManager().Get(event.getPlayer().getName()).AddUnknownSalesPackagesOwned(GetName());
// } }
} }
} }

View File

@ -1,3 +1,5 @@
package mineplex.core.mount.types; package mineplex.core.mount.types;
import java.util.ArrayList; import java.util.ArrayList;
@ -5,19 +7,15 @@ import java.util.ArrayList;
import mineplex.core.common.util.UtilAlg; import mineplex.core.common.util.UtilAlg;
import mineplex.core.common.util.UtilEnt; import mineplex.core.common.util.UtilEnt;
import mineplex.core.common.util.UtilMath; import mineplex.core.common.util.UtilMath;
import mineplex.core.disguise.DisguiseManager; import mineplex.core.common.util.UtilPlayer;
import mineplex.core.disguise.disguises.DisguiseGuardian;
import mineplex.core.disguise.disguises.DisguiseMagmaCube;
import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftLivingEntity;
import org.bukkit.entity.ArmorStand; import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.MagmaCube;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.util.EulerAngle; import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
@ -26,47 +24,42 @@ public class MountTitanData
{ {
private String _owner; private String _owner;
private LivingEntity _head; private Slime _head;
private ArrayList<ArmorStand> _nodes; private ArrayList<ArmorStand> _nodes;
public MountTitanData(DisguiseManager disguiseManager, Player player, String name) public MountTitanData(Player player, String name)
{ {
_owner = player.getName(); _owner = player.getName();
// Nodes Location loc = player.getLocation();
loc.setPitch(0);
loc.setYaw(0);
//Nodes
_nodes = new ArrayList<ArmorStand>(); _nodes = new ArrayList<ArmorStand>();
Location loc = player.getLocation(); for (int i=0 ; i<30 ; i++)
loc.setYaw(0);
loc.setPitch(0);
for (int i = 0; i < 30; i++)
{ {
ArmorStand node = player.getWorld().spawn(loc, ArmorStand.class); ArmorStand node = loc.getWorld().spawn(loc, ArmorStand.class);
node.setVisible(false); node.setVisible(false);
node.setGravity(false); node.setGravity(false);
node.setGhost(true);
node.setHelmet(new ItemStack(Material.REDSTONE_BLOCK)); node.setHelmet(new ItemStack(Material.NETHERRACK));
UtilEnt.setFakeHead(node, true);
_nodes.add(node); _nodes.add(node);
} }
// Head //Head
_head = (LivingEntity) player.getWorld().spawnEntity(loc, EntityType.BAT); _head = player.getWorld().spawn(loc, MagmaCube.class);
UtilEnt.Vegetate(_head, true); _head.setSize(2);
UtilEnt.silence(_head, true); UtilEnt.ghost(_head, true, false);
UtilEnt.setFakeHead(_head, true);
_head.setCustomName(player.getName() + "'s " + name); _head.setCustomName(player.getName() + "'s " + name);
((CraftLivingEntity) _head).getHandle().setMineplexInvisible(true);
DisguiseMagmaCube disguise = new DisguiseMagmaCube(_head);
disguise.SetSize(2);
disguiseManager.disguise(disguise);
} }
public void mount(Player player, Entity entity) public void mount(Player player, Entity entity)
@ -77,92 +70,61 @@ public class MountTitanData
public void update() public void update()
{ {
// Head //Head
if (_head.getPassenger() != null) if (_head.getPassenger() != null)
{ _head.setVelocity(_head.getPassenger().getLocation().getDirection().multiply(0.8).add(new Vector(0,0.2,0)));
_head.setVelocity(_head.getPassenger().getLocation().getDirection().add(new Vector(0, 0.2, 0)));
UtilEnt.CreatureLook(_head, _head.getPassenger().getLocation().getDirection()); Location infront = _head.getLocation().add(0, -1.5, 0);
}
else
{
Player player = Bukkit.getPlayerExact(_owner);
if (player != null) //Move
{ for (int i=0 ; i<30 ; i++)
Vector moving = null;
if (UtilMath.offset(player, _head) > 12)
{
moving = _head.getLocation().getDirection().normalize();
Vector vec = moving.clone().subtract(UtilAlg.getTrajectory(player, _head)).normalize();
vec.setY(-vec.getY());
moving.add(vec.multiply(0.15));
}
else
{
moving = _head.getLocation().getDirection();
moving.setX(moving.getX() + UtilMath.rr(0.1, true));
moving.setY(moving.getY() + UtilMath.rr(0.3, true));
moving.setZ(moving.getZ() + UtilMath.rr(0.1, true));
}
moving.normalize().multiply(0.5);
UtilEnt.CreatureLook(_head, moving);
_head.setVelocity(moving);
}
}
Location infront = _head.getLocation().add(0, -1.3, 0);
infront.setYaw(0);
infront.setPitch(0);
// Move
for (int i = 0; i < 30; i++)
{ {
ArmorStand node = _nodes.get(i); ArmorStand node = _nodes.get(i);
Location loc = node.getLocation(); Location old = node.getLocation();
// Move infront.setPitch(node.getLocation().getPitch());
infront.setYaw(node.getLocation().getYaw());
//Move
if (i == 0) if (i == 0)
node.teleport(infront); node.teleport(infront);
else if (UtilMath.offset(node.getLocation(), infront) > 0.5) else if (UtilMath.offset(node.getLocation(), infront) > 0.6)
node.teleport(infront.add(UtilAlg.getTrajectory(infront, node.getLocation()).multiply(0.5))); node.teleport(infront.add(UtilAlg.getTrajectory(infront, node.getLocation()).multiply(0.6)));
// Rotation //Rotation
node.setHeadPose(UtilAlg.vectorToEuler(UtilAlg.getTrajectory(node.getLocation(), loc))); 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(); infront = node.getLocation();
} }
// Shuffle In
//Shuffle In
if (_head.getPassenger() == null) if (_head.getPassenger() == null)
{ {
for (int i = _nodes.size() - 1; i >= 0; i--) for (int i=_nodes.size()-1 ; i>=0 ; i--)
{ {
ArmorStand node = _nodes.get(i); ArmorStand node = _nodes.get(i);
Location loc = node.getLocation(); if (i>0)
infront = _nodes.get(i-1).getLocation();
if (i > 0)
infront = _nodes.get(i - 1).getLocation();
else else
infront = _head.getLocation().add(0, -1.3, 0); infront = _head.getLocation().add(0, -1.5, 0);
infront.setPitch(node.getLocation().getPitch());
infront.setYaw(node.getLocation().getYaw());
node.teleport(infront); node.teleport(infront);
}
}
}
node.setHeadPose(new EulerAngle(0, -UtilAlg.GetYaw(UtilAlg.getTrajectory(node.getLocation(), loc)), 0));
// node.setHeadPose(UtilAlg.vectorToEuler(UtilAlg.getTrajectory(node.getLocation(), loc)));
}
}
}
public void clean() public void clean()
{ {
@ -176,4 +138,9 @@ public class MountTitanData
{ {
return _owner.equals(player.getName()); 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) public Npc getNpcByEntity(Entity entity)
{ {
if (entity == null) if (entity == null) return null;
return null;
return getNpcByEntityUUID(entity.getUniqueId()); return getNpcByEntityUUID(entity.getUniqueId());
} }

View File

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

View File

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

View File

@ -10,7 +10,7 @@ public class NpcCommand extends MultiCommandBase<NpcManager>
{ {
public NpcCommand(NpcManager plugin) public NpcCommand(NpcManager plugin)
{ {
super(plugin, Rank.DEVELOPER, new Rank[] {Rank.JNR_DEV}, "npc"); super(plugin, Rank.JNR_DEV, "npc");
AddCommand(new AddCommand(plugin)); AddCommand(new AddCommand(plugin));
AddCommand(new DeleteCommand(plugin)); AddCommand(new DeleteCommand(plugin));

View File

@ -56,7 +56,7 @@ public class PacketHandler extends MiniPlugin
{ {
if (!_packetHandlers.containsKey(packetInfo.getPacket().getClass())) if (!_packetHandlers.containsKey(packetInfo.getPacket().getClass()))
{ {
// aSystem.err.print("Received packet " + packetInfo.getPacket().getClass() + " but am not listening for it!"); System.err.print("Received packet " + packetInfo.getPacket().getClass() + " but am not listening for it!");
return true; return true;
} }
@ -79,6 +79,7 @@ public class PacketHandler extends MiniPlugin
public void onPlayerQuit(PlayerQuitEvent event) public void onPlayerQuit(PlayerQuitEvent event)
{ {
((CraftPlayer) event.getPlayer()).getHandle().playerConnection.PacketVerifier.setPacketVerifier(null); ((CraftPlayer) event.getPlayer()).getHandle().playerConnection.PacketVerifier.setPacketVerifier(null);
_playerVerifierMap.remove(event.getPlayer());
} }
public PacketVerifier getPacketVerifier(Player player) public PacketVerifier getPacketVerifier(Player player)

View File

@ -86,6 +86,9 @@ public class PartyManager extends MiniPlugin
@EventHandler @EventHandler
public void serverTransfer(ServerTransferEvent event) public void serverTransfer(ServerTransferEvent event)
{ {
if (event.isDraggedByParty())
return;
Party party = _partyLeaderMap.get(event.getPlayer().getName()); Party party = _partyLeaderMap.get(event.getPlayer().getName());
if (party != null) if (party != null)
@ -100,7 +103,7 @@ public class PartyManager extends MiniPlugin
{ {
if (player != event.getPlayer()) if (player != event.getPlayer())
{ {
_portal.sendPlayerToServer(player, event.getServer(), false); _portal.sendPlayerToServer(player, event.getServer(), true);
} }
} }
} }

View File

@ -167,8 +167,8 @@ public class PetManager extends MiniClientPlugin<PetClient>
if (rank.has(Rank.TITAN)) if (rank.has(Rank.TITAN))
{ {
// if (!Get(p).GetPets().containsKey(EntityType.SKELETON)) if (!Get(p).GetPets().containsKey(EntityType.SKELETON))
// Get(p).GetPets().put(EntityType.SKELETON, "Guardian"); Get(p).GetPets().put(EntityType.SKELETON, "Guardian");
} }
} }

View File

@ -80,19 +80,16 @@ public class Portal extends MiniPlugin
public void sendPlayerToServer(Player player, String serverName) public void sendPlayerToServer(Player player, String serverName)
{ {
sendPlayerToServer(player, serverName, true); sendPlayerToServer(player, serverName, false);
} }
public void sendPlayerToServer(final Player player, final String serverName, boolean callEvent) public void sendPlayerToServer(final Player player, final String serverName, boolean draggedByParty)
{ {
if (_connectingPlayers.contains(player.getName())) if (_connectingPlayers.contains(player.getName()))
return; return;
if (callEvent) ServerTransferEvent event = new ServerTransferEvent(player, serverName, draggedByParty);
{
ServerTransferEvent event = new ServerTransferEvent(player, serverName);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
}
final boolean override = serverName.equalsIgnoreCase("Lobby"); final boolean override = serverName.equalsIgnoreCase("Lobby");
final Rank playerRank = _clientManager.Get(player).GetRank(); final Rank playerRank = _clientManager.Get(player).GetRank();

View File

@ -10,11 +10,18 @@ public class ServerTransferEvent extends Event
private static final HandlerList _handlers = new HandlerList(); private static final HandlerList _handlers = new HandlerList();
private Player _player; private Player _player;
private String _server; private String _server;
private boolean _draggedByParty;
public ServerTransferEvent(Player player, String server) public ServerTransferEvent(Player player, String server, boolean draggedByParty)
{ {
_player = player; _player = player;
_server = server; _server = server;
_draggedByParty = draggedByParty;
}
public boolean isDraggedByParty()
{
return _draggedByParty;
} }
public HandlerList getHandlers() public HandlerList getHandlers()

View File

@ -13,6 +13,7 @@ import mineplex.core.common.util.UtilInv;
import mineplex.core.donation.DonationManager; import mineplex.core.donation.DonationManager;
import mineplex.core.itemstack.ItemStackFactory; import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.preferences.command.PreferencesCommand; import mineplex.core.preferences.command.PreferencesCommand;
import mineplex.core.preferences.ui.ExclusivePreferencesShop;
import mineplex.core.preferences.ui.PreferencesShop; import mineplex.core.preferences.ui.PreferencesShop;
import mineplex.core.updater.UpdateType; import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent; import mineplex.core.updater.event.UpdateEvent;
@ -32,6 +33,7 @@ public class PreferencesManager extends MiniDbClientPlugin<UserPreferences>
{ {
private PreferencesRepository _repository; private PreferencesRepository _repository;
private PreferencesShop _shop; private PreferencesShop _shop;
private ExclusivePreferencesShop _exclusiveShop;
private NautHashMap<String, UserPreferences> _saveBuffer = new NautHashMap<String, UserPreferences>(); private NautHashMap<String, UserPreferences> _saveBuffer = new NautHashMap<String, UserPreferences>();
@ -42,7 +44,10 @@ public class PreferencesManager extends MiniDbClientPlugin<UserPreferences>
super("Preferences", plugin, clientManager); super("Preferences", plugin, clientManager);
_repository = new PreferencesRepository(plugin); _repository = new PreferencesRepository(plugin);
_shop = new PreferencesShop(this, clientManager, donationManager); _exclusiveShop = new ExclusivePreferencesShop(this, clientManager, donationManager);
_shop = new PreferencesShop(this, clientManager, donationManager, _exclusiveShop);
_exclusiveShop.setPreferencesShop(_shop);
addCommand(new PreferencesCommand(this)); addCommand(new PreferencesCommand(this));
} }
@ -131,6 +136,6 @@ public class PreferencesManager extends MiniDbClientPlugin<UserPreferences>
@Override @Override
public String getQuery(int accountId, String uuid, String name) public String getQuery(int accountId, String uuid, String name)
{ {
return "SELECT games, visibility, showChat, friendChat, privateMessaging, partyRequests, invisibility, forcefield, showMacReports, ignoreVelocity, pendingFriendRequests, friendDisplayInventoryUI FROM accountPreferences WHERE accountPreferences.uuid = '" + uuid + "' LIMIT 1;"; return "SELECT games, visibility, showChat, friendChat, privateMessaging, partyRequests, invisibility, forcefield, showMacReports, ignoreVelocity, pendingFriendRequests, friendDisplayInventoryUI, clanTips FROM accountPreferences WHERE accountPreferences.uuid = '" + uuid + "' LIMIT 1;";
} }
} }

View File

@ -15,9 +15,16 @@ import mineplex.core.database.column.ColumnVarChar;
public class PreferencesRepository extends RepositoryBase public class PreferencesRepository extends RepositoryBase
{ {
//private static String CREATE_ACCOUNT_TABLE = "CREATE TABLE IF NOT EXISTS accountPreferences (id INT NOT NULL AUTO_INCREMENT, uuid VARCHAR(256), games BOOL NOT NULL DEFAULT 1, visibility BOOL NOT NULL DEFAULT 1, showChat BOOL NOT NULL DEFAULT 1, friendChat BOOL NOT NULL DEFAULT 1, privateMessaging BOOL NOT NULL DEFAULT 1, partyRequests BOOL NOT NULL DEFAULT 0, invisibility BOOL NOT NULL DEFAULT 0, forcefield BOOL NOT NULL DEFAULT 0, showMacReports BOOL NOT NULL DEFAULT 0, ignoreVelocity BOOL NOT NULL DEFAULT 0, PRIMARY KEY (id), UNIQUE INDEX uuid_index (uuid));"; // private static String CREATE_ACCOUNT_TABLE = "CREATE TABLE IF NOT EXISTS
// accountPreferences (id INT NOT NULL AUTO_INCREMENT, uuid VARCHAR(256),
// games BOOL NOT NULL DEFAULT 1, visibility BOOL NOT NULL DEFAULT 1,
// showChat BOOL NOT NULL DEFAULT 1, friendChat BOOL NOT NULL DEFAULT 1,
// privateMessaging BOOL NOT NULL DEFAULT 1, partyRequests BOOL NOT NULL
// DEFAULT 0, invisibility BOOL NOT NULL DEFAULT 0, forcefield BOOL NOT NULL
// DEFAULT 0, showMacReports BOOL NOT NULL DEFAULT 0, ignoreVelocity BOOL
// NOT NULL DEFAULT 0, PRIMARY KEY (id), UNIQUE INDEX uuid_index (uuid));";
private static String INSERT_ACCOUNT = "INSERT INTO accountPreferences (uuid) VALUES (?) ON DUPLICATE KEY UPDATE uuid=uuid;"; private static String INSERT_ACCOUNT = "INSERT INTO accountPreferences (uuid) VALUES (?) ON DUPLICATE KEY UPDATE uuid=uuid;";
private static String UPDATE_ACCOUNT_PREFERENCES = "UPDATE accountPreferences SET games = ?, visibility = ?, showChat = ?, friendChat = ?, privateMessaging = ?, partyRequests = ?, invisibility = ?, forcefield = ?, showMacReports = ?, ignoreVelocity = ?, pendingFriendRequests = ?, friendDisplayInventoryUI = ? WHERE uuid=?;"; private static String UPDATE_ACCOUNT_PREFERENCES = "UPDATE accountPreferences SET games = ?, visibility = ?, showChat = ?, friendChat = ?, privateMessaging = ?, partyRequests = ?, invisibility = ?, forcefield = ?, showMacReports = ?, ignoreVelocity = ?, pendingFriendRequests = ?, friendDisplayInventoryUI = ?, clanTips = ? WHERE uuid=?;";
public PreferencesRepository(JavaPlugin plugin) public PreferencesRepository(JavaPlugin plugin)
{ {
@ -27,7 +34,7 @@ public class PreferencesRepository extends RepositoryBase
@Override @Override
protected void initialize() protected void initialize()
{ {
//executeUpdate(CREATE_ACCOUNT_TABLE); // executeUpdate(CREATE_ACCOUNT_TABLE);
} }
@Override @Override
@ -37,11 +44,7 @@ public class PreferencesRepository extends RepositoryBase
public void saveUserPreferences(NautHashMap<String, UserPreferences> preferences) public void saveUserPreferences(NautHashMap<String, UserPreferences> preferences)
{ {
try try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_ACCOUNT_PREFERENCES);)
(
Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_ACCOUNT_PREFERENCES);
)
{ {
for (Entry<String, UserPreferences> entry : preferences.entrySet()) for (Entry<String, UserPreferences> entry : preferences.entrySet())
{ {
@ -57,7 +60,9 @@ public class PreferencesRepository extends RepositoryBase
preparedStatement.setBoolean(10, entry.getValue().IgnoreVelocity); preparedStatement.setBoolean(10, entry.getValue().IgnoreVelocity);
preparedStatement.setBoolean(11, entry.getValue().PendingFriendRequests); preparedStatement.setBoolean(11, entry.getValue().PendingFriendRequests);
preparedStatement.setBoolean(12, entry.getValue().friendDisplayInventoryUI); preparedStatement.setBoolean(12, entry.getValue().friendDisplayInventoryUI);
preparedStatement.setString(13, entry.getKey()); preparedStatement.setBoolean(13, entry.getValue().ClanTips);
System.out.println(">> " + entry.getValue().ClanTips);
preparedStatement.setString(14, entry.getKey());
preparedStatement.addBatch(); preparedStatement.addBatch();
} }
@ -83,7 +88,9 @@ public class PreferencesRepository extends RepositoryBase
preparedStatement.setBoolean(10, entry.getValue().IgnoreVelocity); preparedStatement.setBoolean(10, entry.getValue().IgnoreVelocity);
preparedStatement.setBoolean(11, entry.getValue().PendingFriendRequests); preparedStatement.setBoolean(11, entry.getValue().PendingFriendRequests);
preparedStatement.setBoolean(12, entry.getValue().friendDisplayInventoryUI); preparedStatement.setBoolean(12, entry.getValue().friendDisplayInventoryUI);
preparedStatement.setString(13, entry.getKey()); preparedStatement.setBoolean(13, entry.getValue().ClanTips);
System.out.println(">> " + entry.getValue().ClanTips);
preparedStatement.setString(14, entry.getKey());
preparedStatement.execute(); preparedStatement.execute();
} }
@ -114,6 +121,8 @@ public class PreferencesRepository extends RepositoryBase
preferences.IgnoreVelocity = resultSet.getBoolean(10); preferences.IgnoreVelocity = resultSet.getBoolean(10);
preferences.PendingFriendRequests = resultSet.getBoolean(11); preferences.PendingFriendRequests = resultSet.getBoolean(11);
preferences.friendDisplayInventoryUI = resultSet.getBoolean(12); preferences.friendDisplayInventoryUI = resultSet.getBoolean(12);
preferences.ClanTips = resultSet.getBoolean(13);
System.out.println("<< " + resultSet.getBoolean(13));
} }
return preferences; return preferences;

View File

@ -15,4 +15,5 @@ public class UserPreferences
public boolean IgnoreVelocity = false; public boolean IgnoreVelocity = false;
public boolean PendingFriendRequests = true; public boolean PendingFriendRequests = true;
public boolean friendDisplayInventoryUI = true; public boolean friendDisplayInventoryUI = true;
public boolean ClanTips = true;
} }

View File

@ -0,0 +1,194 @@
package mineplex.core.preferences.ui;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import mineplex.core.account.CoreClientManager;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilUI;
import mineplex.core.donation.DonationManager;
import mineplex.core.preferences.PreferencesManager;
import mineplex.core.preferences.UserPreferences;
import mineplex.core.shop.item.IButton;
import mineplex.core.shop.item.ShopItem;
import mineplex.core.shop.page.ShopPageBase;
public class ExclusivePreferencesPage extends ShopPageBase<PreferencesManager, ExclusivePreferencesShop>
{
private IButton _toggleHubInvisibility;
private IButton _toggleHubForcefield;
private IButton _toggleHubIgnoreVelocity;
private IButton _toggleMacReports;
private boolean _hubInvisibilityToggled;
private boolean _hubForcefieldToggled;
private boolean _hubIgnoreVelocityToggled;
private boolean _macReportsToggled;
private PreferencesShop _preferencesShop;
public ExclusivePreferencesPage(PreferencesManager plugin, ExclusivePreferencesShop shop, CoreClientManager clientManager, DonationManager donationManager, String name, Player player, PreferencesShop preferencesShop)
{
super(plugin, shop, clientManager, donationManager, name, player, 54);
_preferencesShop = preferencesShop;
createButtons();
buildPage();
}
private void createButtons()
{
_toggleHubInvisibility = new IButton()
{
@Override
public void onClick(Player player, ClickType clickType)
{
toggleHubInvisibility(player);
}
};
_toggleHubForcefield = new IButton()
{
@Override
public void onClick(Player player, ClickType clickType)
{
toggleHubForcefield(player);
}
};
_toggleMacReports = new IButton()
{
@Override
public void onClick(Player player, ClickType clickType)
{
toggleMacReports(player);
}
};
_toggleHubIgnoreVelocity = new IButton()
{
@Override
public void onClick(Player player, ClickType clickType)
{
toggleHubIgnoreVelocity(player);
}
};
}
@Override
public void playerClosed()
{
super.playerClosed();
if (preferencesChanged())
{
getPlugin().savePreferences(getPlayer());
}
}
@Override
protected void buildPage()
{
clear();
UserPreferences userPreferences = getPlugin().Get(getPlayer());
Rank rank = getClientManager().Get(getPlayer()).GetRank();
addButton(45, new ShopItem(Material.REDSTONE_COMPARATOR, (byte) 0, C.cAqua + "/prefs", new String[] { C.cGold + "Return back to the regular preferences" }, 1, false, false), new IButton()
{
@Override
public void onClick(Player player, ClickType clickType)
{
player.closeInventory();
_preferencesShop.attemptShopOpen(player);
}
});
if (rank.has(Rank.ADMIN) || rank == Rank.JNR_DEV)
{
int[] indices = UtilUI.getIndicesFor(4, 0, 2);
buildPreference(indices[0], Material.NETHER_STAR, "Hub Invisibility", userPreferences.Invisibility, _toggleHubInvisibility);
buildPreference(indices[1], Material.SLIME_BALL, "Hub Forcefield", userPreferences.HubForcefield, _toggleHubForcefield);
buildPreference(indices[2], Material.PAPER, "Mac Reports", userPreferences.ShowMacReports, _toggleMacReports);
buildPreference(indices[3], Material.SADDLE, "Hub Ignore Velocity", userPreferences.IgnoreVelocity, _toggleHubIgnoreVelocity);
}
else if (rank.has(Rank.MODERATOR))
{
int[] indices = UtilUI.getIndicesFor(3, 0, 2);
buildPreference(indices[0], Material.NETHER_STAR, "Hub Invisibility", userPreferences.Invisibility, _toggleHubInvisibility);
buildPreference(indices[1], Material.PAPER, "Mac Reports", userPreferences.ShowMacReports, _toggleMacReports);
buildPreference(indices[2], Material.SADDLE, "Hub Ignore Velocity", userPreferences.IgnoreVelocity, _toggleHubIgnoreVelocity);
}
else if (rank == Rank.YOUTUBE || rank == Rank.TWITCH)
{
int[] indices = UtilUI.getIndicesFor(3, 0, 2);
buildPreference(indices[0], Material.NETHER_STAR, "Hub Invisibility & Flight", userPreferences.Invisibility, _toggleHubInvisibility);
buildPreference(indices[1], Material.SLIME_BALL, "Hub Forcefield", userPreferences.HubForcefield, _toggleHubForcefield);
buildPreference(indices[2], Material.SADDLE, "Hub Ignore Velocity", userPreferences.IgnoreVelocity, _toggleHubIgnoreVelocity);
}
}
private void toggleHubForcefield(org.bukkit.entity.Player player)
{
getPlugin().Get(player).HubForcefield = !getPlugin().Get(player).HubForcefield;
_hubForcefieldToggled = !_hubForcefieldToggled;
buildPage();
}
private void toggleHubInvisibility(org.bukkit.entity.Player player)
{
getPlugin().Get(player).Invisibility = !getPlugin().Get(player).Invisibility;
// Dont save for Mod/SnrMod - prevents them just being invis 24/7
if (getPlugin().Get(player).Invisibility)
{
if (getClient().GetRank().has(Rank.ADMIN) || getClient().GetRank() == Rank.YOUTUBE || getClient().GetRank() == Rank.YOUTUBE_SMALL || getClient().GetRank() == Rank.TWITCH)
{
_hubInvisibilityToggled = !_hubInvisibilityToggled;
}
}
player.setFlying(false);
player.setAllowFlight(false);
buildPage();
}
private void toggleMacReports(org.bukkit.entity.Player player)
{
getPlugin().Get(player).ShowMacReports = !getPlugin().Get(player).ShowMacReports;
_macReportsToggled = !_macReportsToggled;
buildPage();
}
private void toggleHubIgnoreVelocity(org.bukkit.entity.Player player)
{
getPlugin().Get(player).IgnoreVelocity = !getPlugin().Get(player).IgnoreVelocity;
_hubIgnoreVelocityToggled = !_hubIgnoreVelocityToggled;
buildPage();
}
private void buildPreference(int index, Material material, String name, boolean preference, IButton button)
{
buildPreference(index, material, (byte) 0, name, preference, button);
}
private void buildPreference(int index, Material material, byte data, String name, boolean preference, IButton button)
{
String[] description = new String[] { "" + (preference ? ChatColor.GREEN + "Enabled" : ChatColor.RED + "Disabled"), ChatColor.RED + " ", ChatColor.RESET + "Click to " + (preference ? "Disable" : "Enable") };
addButton(index, new ShopItem(material, data, (preference ? ChatColor.GREEN : ChatColor.RED) + name, description, 1, false, false), button);
addButton(index + 9, new ShopItem(Material.INK_SACK, (preference ? (byte) 10 : (byte) 8), (preference ? ChatColor.GREEN : ChatColor.RED) + name, description, 1, false, false), button);
}
public boolean preferencesChanged()
{
return _hubInvisibilityToggled || _macReportsToggled || _hubInvisibilityToggled || _hubForcefieldToggled;
}
}

View File

@ -0,0 +1,29 @@
package mineplex.core.preferences.ui;
import org.bukkit.entity.Player;
import mineplex.core.account.CoreClientManager;
import mineplex.core.preferences.PreferencesManager;
import mineplex.core.shop.ShopBase;
import mineplex.core.shop.page.ShopPageBase;
public class ExclusivePreferencesShop extends ShopBase<PreferencesManager>
{
private PreferencesShop _preferencesShop;
public ExclusivePreferencesShop(PreferencesManager plugin, CoreClientManager clientManager, mineplex.core.donation.DonationManager donationManager)
{
super(plugin, clientManager, donationManager, "Exclusive Preferences");
}
public void setPreferencesShop(PreferencesShop preferencesShop)
{
_preferencesShop = preferencesShop;
}
@Override
protected ShopPageBase<PreferencesManager, ? extends ShopBase<PreferencesManager>> buildPagesFor(Player player)
{
return new ExclusivePreferencesPage(getPlugin(), this, getClientManager(), getDonationManager(), "Exclusive Preferences", player, _preferencesShop);
}
}

View File

@ -7,6 +7,8 @@ import org.bukkit.event.inventory.ClickType;
import mineplex.core.account.CoreClientManager; import mineplex.core.account.CoreClientManager;
import mineplex.core.common.Rank; import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilUI;
import mineplex.core.donation.DonationManager; import mineplex.core.donation.DonationManager;
import mineplex.core.preferences.PreferencesManager; import mineplex.core.preferences.PreferencesManager;
import mineplex.core.preferences.UserPreferences; import mineplex.core.preferences.UserPreferences;
@ -22,10 +24,7 @@ public class PreferencesPage extends ShopPageBase<PreferencesManager, Preference
private IButton _togglePrivateChat; private IButton _togglePrivateChat;
private IButton _toggleHubPartyRequests; private IButton _toggleHubPartyRequests;
private IButton _togglePendingFriendRequests; private IButton _togglePendingFriendRequests;
private IButton _toggleHubInvisibility; private IButton _toggleClanTips;
private IButton _toggleHubForcefield;
private IButton _toggleHubIgnoreVelocity;
private IButton _toggleMacReports;
private boolean _hubGamesToggled; private boolean _hubGamesToggled;
private boolean _hubPlayersToggled; private boolean _hubPlayersToggled;
@ -33,15 +32,16 @@ public class PreferencesPage extends ShopPageBase<PreferencesManager, Preference
private boolean _hubPrivateChatToggled; private boolean _hubPrivateChatToggled;
private boolean _hubPartyRequestsToggled; private boolean _hubPartyRequestsToggled;
private boolean _pendingFriendRequestsToggled; private boolean _pendingFriendRequestsToggled;
private boolean _hubInvisibilityToggled; private boolean _clanTipsToggled;
private boolean _hubForcefieldToggled;
private boolean _macReportsToggled;
private boolean _hubIgnoreVelocityToggled;
public PreferencesPage(PreferencesManager plugin, PreferencesShop shop, CoreClientManager clientManager, DonationManager donationManager, String name, Player player) private ExclusivePreferencesShop _exclusiveShop;
public PreferencesPage(PreferencesManager plugin, PreferencesShop shop, CoreClientManager clientManager, DonationManager donationManager, String name, Player player, ExclusivePreferencesShop exclusiveShop)
{ {
super(plugin, shop, clientManager, donationManager, name, player, 54); super(plugin, shop, clientManager, donationManager, name, player, 54);
_exclusiveShop = exclusiveShop;
createButtons(); createButtons();
buildPage(); buildPage();
} }
@ -56,6 +56,14 @@ public class PreferencesPage extends ShopPageBase<PreferencesManager, Preference
toggleHubGames(player); toggleHubGames(player);
} }
}; };
_toggleClanTips = new IButton()
{
@Override
public void onClick(Player player, ClickType clickType)
{
toggleClanTips(player);
}
};
_toggleHubPlayers = new IButton() _toggleHubPlayers = new IButton()
{ {
@ -101,149 +109,63 @@ public class PreferencesPage extends ShopPageBase<PreferencesManager, Preference
togglePendingFriendRequests(player); togglePendingFriendRequests(player);
} }
}; };
_toggleHubInvisibility = new IButton()
{
@Override
public void onClick(Player player, ClickType clickType)
{
toggleHubInvisibility(player);
}
};
_toggleHubForcefield = new IButton()
{
@Override
public void onClick(Player player, ClickType clickType)
{
toggleHubForcefield(player);
}
};
_toggleMacReports = new IButton()
{
@Override
public void onClick(Player player, ClickType clickType)
{
toggleMacReports(player);
}
};
_toggleHubIgnoreVelocity = new IButton()
{
@Override
public void onClick(Player player, ClickType clickType)
{
toggleHubIgnoreVelocity(player);
}
};
} }
private void buildPreference(int index, Material material, String name, boolean preference, IButton button) private void toggleHubPartyRequests(Player player)
{
buildPreference(index, material, (byte)0, name, preference, button);
}
private void buildPreference(int index, Material material, byte data, String name, boolean preference, IButton button)
{
String[] description = new String[] {
"" + (preference ? ChatColor.GREEN + "Enabled" : ChatColor.RED + "Disabled"),
ChatColor.RED + " ",
ChatColor.RESET + "Click to " + (preference ? "Disable" : "Enable") };
addButton(index, new ShopItem(material, data, (preference ? ChatColor.GREEN : ChatColor.RED) + name, description, 1, false, false), button);
addButton(index + 9, new ShopItem(Material.INK_SACK, (preference ? (byte) 10 : (byte) 8), (preference ? ChatColor.GREEN : ChatColor.RED) + name, description, 1, false, false), button);
}
protected void toggleHubForcefield(org.bukkit.entity.Player player)
{
getPlugin().Get(player).HubForcefield = !getPlugin().Get(player).HubForcefield;
_hubForcefieldToggled = !_hubForcefieldToggled;
buildPage();
}
protected void toggleHubInvisibility(org.bukkit.entity.Player player)
{
getPlugin().Get(player).Invisibility = !getPlugin().Get(player).Invisibility;
//Dont save for Mod/SnrMod - prevents them just being invis 24/7
if (getPlugin().Get(player).Invisibility)
{
if (getClient().GetRank().has(Rank.ADMIN) ||
getClient().GetRank() == Rank.YOUTUBE ||
getClient().GetRank() == Rank.YOUTUBE_SMALL ||
getClient().GetRank() == Rank.TWITCH)
{
_hubInvisibilityToggled = !_hubInvisibilityToggled;
}
}
player.setFlying(false);
player.setAllowFlight(false);
buildPage();
}
protected void toggleHubPartyRequests(org.bukkit.entity.Player player)
{ {
getPlugin().Get(player).PartyRequests = !getPlugin().Get(player).PartyRequests; getPlugin().Get(player).PartyRequests = !getPlugin().Get(player).PartyRequests;
_hubPartyRequestsToggled = !_hubPartyRequestsToggled; _hubPartyRequestsToggled = !_hubPartyRequestsToggled;
buildPage(); buildPage();
} }
protected void togglePendingFriendRequests(org.bukkit.entity.Player player) private void togglePendingFriendRequests(Player player)
{ {
getPlugin().Get(player).PendingFriendRequests = !getPlugin().Get(player).PendingFriendRequests; getPlugin().Get(player).PendingFriendRequests = !getPlugin().Get(player).PendingFriendRequests;
_pendingFriendRequestsToggled = !_pendingFriendRequestsToggled; _pendingFriendRequestsToggled = !_pendingFriendRequestsToggled;
buildPage(); buildPage();
} }
protected void togglePrivateChat(org.bukkit.entity.Player player) private void togglePrivateChat(Player player)
{ {
getPlugin().Get(player).PrivateMessaging = !getPlugin().Get(player).PrivateMessaging; getPlugin().Get(player).PrivateMessaging = !getPlugin().Get(player).PrivateMessaging;
_hubPrivateChatToggled = !_hubPrivateChatToggled; _hubPrivateChatToggled = !_hubPrivateChatToggled;
buildPage(); buildPage();
} }
protected void toggleChat(org.bukkit.entity.Player player) private void toggleChat(Player player)
{ {
getPlugin().Get(player).ShowChat = !getPlugin().Get(player).ShowChat; getPlugin().Get(player).ShowChat = !getPlugin().Get(player).ShowChat;
_hubChatToggled = !_hubChatToggled; _hubChatToggled = !_hubChatToggled;
buildPage(); buildPage();
} }
protected void toggleHubPlayers(org.bukkit.entity.Player player) private void toggleHubPlayers(Player player)
{ {
getPlugin().Get(player).ShowPlayers = !getPlugin().Get(player).ShowPlayers; getPlugin().Get(player).ShowPlayers = !getPlugin().Get(player).ShowPlayers;
_hubPlayersToggled = !_hubPlayersToggled; _hubPlayersToggled = !_hubPlayersToggled;
buildPage(); buildPage();
} }
protected void toggleHubGames(org.bukkit.entity.Player player) private void toggleClanTips(Player player)
{
getPlugin().Get(player).ClanTips = !getPlugin().Get(player).ClanTips;
_clanTipsToggled = !_clanTipsToggled;
buildPage();
}
private void toggleHubGames(Player player)
{ {
getPlugin().Get(player).HubGames = !getPlugin().Get(player).HubGames; getPlugin().Get(player).HubGames = !getPlugin().Get(player).HubGames;
_hubGamesToggled = !_hubGamesToggled; _hubGamesToggled = !_hubGamesToggled;
buildPage(); buildPage();
} }
protected void toggleMacReports(org.bukkit.entity.Player player)
{
getPlugin().Get(player).ShowMacReports = !getPlugin().Get(player).ShowMacReports;
_macReportsToggled = !_macReportsToggled;
buildPage();
}
protected void toggleHubIgnoreVelocity(org.bukkit.entity.Player player)
{
getPlugin().Get(player).IgnoreVelocity = !getPlugin().Get(player).IgnoreVelocity;
_hubIgnoreVelocityToggled = !_hubIgnoreVelocityToggled;
buildPage();
}
@Override @Override
public void playerClosed() public void playerClosed()
{ {
super.playerClosed(); super.playerClosed();
System.out.println("Prefs have changed: " + preferencesChanged());
if (preferencesChanged()) if (preferencesChanged())
{ {
getPlugin().savePreferences(getPlayer()); getPlugin().savePreferences(getPlayer());
@ -256,43 +178,47 @@ public class PreferencesPage extends ShopPageBase<PreferencesManager, Preference
clear(); clear();
UserPreferences userPreferences = getPlugin().Get(getPlayer()); UserPreferences userPreferences = getPlugin().Get(getPlayer());
int index = 9; Rank rank = getClientManager().Get(getPlayer()).GetRank();
buildPreference(index, Material.FIREBALL, "Hub Player Stacker", userPreferences.HubGames, _toggleHubGames); int[] indices = UtilUI.getIndicesFor(7, 0, 2);
index += 2;
buildPreference(index, Material.EYE_OF_ENDER, "Hub Player Visibility", userPreferences.ShowPlayers, _toggleHubPlayers);
index += 2;
buildPreference(index, Material.PAPER, "Player Chat", userPreferences.ShowChat, _toggleChat);
index += 2;
buildPreference(index, Material.EMPTY_MAP, "Private Messaging", userPreferences.PrivateMessaging, _togglePrivateChat);
index += 2;
buildPreference(index, Material.SKULL_ITEM, (byte)3, "Hub Party Requests", userPreferences.PartyRequests, _toggleHubPartyRequests);
buildPreference(40, Material.RED_ROSE, "Show Pending Friend Requests", userPreferences.PendingFriendRequests, _togglePendingFriendRequests); buildPreference(indices[0], Material.FIREBALL, "Hub Player Stacker", userPreferences.HubGames, _toggleHubGames);
buildPreference(indices[1], Material.EYE_OF_ENDER, "Hub Player Visibility", userPreferences.ShowPlayers, _toggleHubPlayers);
buildPreference(indices[2], Material.PAPER, "Player Chat", userPreferences.ShowChat, _toggleChat);
buildPreference(indices[3], Material.EMPTY_MAP, "Private Messaging", userPreferences.PrivateMessaging, _togglePrivateChat);
buildPreference(indices[4], Material.SKULL_ITEM, (byte) 3, "Hub Party Requests", userPreferences.PartyRequests, _toggleHubPartyRequests);
buildPreference(indices[5], Material.RED_ROSE, "Show Pending Friend Requests", userPreferences.PendingFriendRequests, _togglePendingFriendRequests);
buildPreference(indices[6], Material.IRON_SWORD, "Show Clan Tips", userPreferences.ClanTips, _toggleClanTips);
if (getClientManager().Get(getPlayer()).GetRank().has(Rank.ADMIN) || getClientManager().Get(getPlayer()).GetRank() == Rank.JNR_DEV) if (rank.has(Rank.MODERATOR) || rank == Rank.YOUTUBE || rank == Rank.TWITCH)
{ {
buildPreference(36, Material.NETHER_STAR, "Hub Invisibility", userPreferences.Invisibility, _toggleHubInvisibility); addButton(53, new ShopItem(Material.DIAMOND, (byte) 0, C.cAqua + "Exclusive Preferences", new String[]{C.cGold + "This will open a page of preferences", C.cGold + "that are only available to you."}, 1, false, false), new IButton()
buildPreference(38, Material.SLIME_BALL, "Hub Forcefield", userPreferences.HubForcefield, _toggleHubForcefield);
buildPreference(42, Material.PAPER, "Mac Reports", userPreferences.ShowMacReports, _toggleMacReports);
buildPreference(44, Material.SADDLE, "Hub Ignore Velocity", userPreferences.IgnoreVelocity, _toggleHubIgnoreVelocity);
}
else if (getClientManager().Get(getPlayer()).GetRank().has(Rank.MODERATOR))
{ {
buildPreference(38, Material.NETHER_STAR, "Hub Invisibility", userPreferences.Invisibility, _toggleHubInvisibility); @Override
buildPreference(42, Material.PAPER, "Mac Reports", userPreferences.ShowMacReports, _toggleMacReports); public void onClick(Player player, ClickType clickType)
buildPreference(44, Material.SADDLE, "Hub Ignore Velocity", userPreferences.IgnoreVelocity, _toggleHubIgnoreVelocity);
}
else if (getClientManager().Get(getPlayer()).GetRank() == Rank.YOUTUBE || getClientManager().Get(getPlayer()).GetRank() == Rank.TWITCH)
{ {
buildPreference(38, Material.NETHER_STAR, "Hub Invisibility & Flight", userPreferences.Invisibility, _toggleHubInvisibility); player.closeInventory();
buildPreference(42, Material.SLIME_BALL, "Hub Forcefield", userPreferences.HubForcefield, _toggleHubForcefield); _exclusiveShop.attemptShopOpen(player);
buildPreference(44, Material.SADDLE, "Hub Ignore Velocity", userPreferences.IgnoreVelocity, _toggleHubIgnoreVelocity);
} }
});
}
}
private void buildPreference(int index, Material material, String name, boolean preference, IButton button)
{
buildPreference(index, material, (byte) 0, name, preference, button);
}
private void buildPreference(int index, Material material, byte data, String name, boolean preference, IButton button)
{
String[] description = new String[] { "" + (preference ? ChatColor.GREEN + "Enabled" : ChatColor.RED + "Disabled"), ChatColor.RED + " ", ChatColor.RESET + "Click to " + (preference ? "Disable" : "Enable") };
addButton(index, new ShopItem(material, data, (preference ? ChatColor.GREEN : ChatColor.RED) + name, description, 1, false, false), button);
addButton(index + 9, new ShopItem(Material.INK_SACK, (preference ? (byte) 10 : (byte) 8), (preference ? ChatColor.GREEN : ChatColor.RED) + name, description, 1, false, false), button);
} }
public boolean preferencesChanged() public boolean preferencesChanged()
{ {
return _hubGamesToggled || _hubPlayersToggled || _hubChatToggled || _hubPrivateChatToggled || _hubPartyRequestsToggled || _hubInvisibilityToggled || _hubForcefieldToggled || _pendingFriendRequestsToggled || _macReportsToggled || _hubIgnoreVelocityToggled; return _hubGamesToggled || _hubPlayersToggled || _hubChatToggled || _hubPrivateChatToggled || _hubPartyRequestsToggled || _pendingFriendRequestsToggled || _clanTipsToggled;
} }
} }

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