Merge branches 'feature/report' and 'master' of ssh://184.154.0.242:7999/min/mineplex into feature/report

# Conflicts:
#	Plugins/Mineplex.Core/src/mineplex/core/preferences/PreferencesManager.java
#	Plugins/Mineplex.Core/src/mineplex/core/preferences/PreferencesRepository.java
#	Plugins/Mineplex.Core/src/mineplex/core/preferences/ui/PreferencesPage.java
#	Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/Clans.java
This commit is contained in:
Keir 2015-12-05 00:05:05 +00:00
commit ef6fd0eaa3
631 changed files with 45180 additions and 5784 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

BIN
Art/MS SMoke.psd Normal file

Binary file not shown.

View File

@ -18,6 +18,9 @@
<element id="file-copy" path="$PROJECT_DIR$/Mineplex.Game.Clans/plugin.yml" /> <element id="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>
@ -24,14 +23,12 @@
</profile> </profile>
<profile default="false" name="Annotation profile for bungee" enabled="true"> <profile default="false" name="Annotation profile for bungee" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" /> <sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" /> <sourceTestOutputDir name="target\generated-test-sources\test-annotations" />
<outputRelativeToContentRoot value="true" /> <outputRelativeToContentRoot value="true" />
<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,22 +3,24 @@
<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.ChatSnapManager/Mineplex.ChatSnapManager.iml" filepath="$PROJECT_DIR$/Mineplex.ChatSnapManager/Mineplex.ChatSnapManager.iml" group="Core" /> <module fileurl="file://$PROJECT_DIR$/Mineplex.ChatSnapManager/Mineplex.ChatSnapManager.iml" filepath="$PROJECT_DIR$/Mineplex.ChatSnapManager/Mineplex.ChatSnapManager.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/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

@ -12,5 +12,4 @@
<orderEntry type="library" name="commons-pool2" level="project" /> <orderEntry type="library" name="commons-pool2" level="project" />
<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;
}
}

Binary file not shown.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,8 +6,9 @@ public enum CurrencyType
{ {
Tokens(" Tokens", Material.EMERALD), 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

@ -116,4 +116,12 @@ public enum Rank
{ {
return _donor; return _donor;
} }
public String getRawTag()
{
if (Name.equalsIgnoreCase("ALL"))
return "";
return Name;
}
} }

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

@ -0,0 +1,132 @@
package mineplex.core.common.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class NautArrayList<Elem>
{
private ArrayList<Elem> _wrappedArrayList = new ArrayList<Elem>();
public boolean add(Elem elem)
{
return _wrappedArrayList.add(elem);
}
public void add(int index, Elem elem)
{
_wrappedArrayList.add(index, elem);
}
public boolean addAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.addAll(elements);
}
public boolean addAll(int index, Collection<? extends Elem> elements)
{
return _wrappedArrayList.addAll(index, elements);
}
public void clear()
{
_wrappedArrayList.clear();
}
public boolean contains(Elem elem)
{
return _wrappedArrayList.contains(elem);
}
public boolean containsAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.containsAll(elements);
}
public Elem get(int index)
{
return _wrappedArrayList.get(index);
}
public boolean equals(Object o)
{
return _wrappedArrayList.equals(o);
}
public int hashCode()
{
return _wrappedArrayList.hashCode();
}
public int indexOf(Elem elem)
{
return _wrappedArrayList.indexOf(elem);
}
public boolean isEmpty()
{
return _wrappedArrayList.isEmpty();
}
public Iterator<Elem> iterator()
{
return _wrappedArrayList.iterator();
}
public int lastIndexOf(Elem elem)
{
return _wrappedArrayList.lastIndexOf(elem);
}
public ListIterator<Elem> listIterator()
{
return _wrappedArrayList.listIterator();
}
public ListIterator<Elem> listIterator(int index)
{
return _wrappedArrayList.listIterator(index);
}
public Elem remove(int index)
{
return _wrappedArrayList.remove(index);
}
public boolean remove(Elem element)
{
return _wrappedArrayList.remove(element);
}
public boolean removeAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.removeAll(elements);
}
public boolean retainAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.retainAll(elements);
}
public Elem set(int index, Elem element)
{
return _wrappedArrayList.set(index, element);
}
public int size()
{
return _wrappedArrayList.size();
}
public List<Elem> subList(int begin, int end)
{
return _wrappedArrayList.subList(begin, end);
}
public Object[] toArray()
{
return _wrappedArrayList.toArray();
}
}

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,17 +10,26 @@ 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.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;
} }
@ -39,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)
@ -54,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)
@ -407,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>();
@ -439,4 +499,15 @@ public class UtilAlg
return value; return value;
} }
public static EulerAngle vectorToEuler(Vector vector)
{
//JUST MAKE SURE THE ARMOR STAND ISNT ROTATED.
return new EulerAngle(
Math.toRadians(UtilAlg.GetPitch(vector)),
Math.toRadians(UtilAlg.GetYaw(vector)),
0);
}
} }

View File

@ -33,6 +33,7 @@ import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftCreature; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftCreature;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftLivingEntity; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftLivingEntity;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Creature; import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
@ -531,10 +532,27 @@ public class UtilEnt
} }
public static boolean isGrounded(Entity ent) public static boolean isGrounded(Entity ent)
{
if(!(ent instanceof Player)) {
return ent.isOnGround();
}
AxisAlignedBB box = ((CraftEntity)ent).getHandle().getBoundingBox().shrink(0.05, 0, 0.05);
Location bottom_corner_1 = new Location(ent.getWorld(), box.a, ent.getLocation().getY()-0.05, box.c);
Location bottom_corner_2 = new Location(ent.getWorld(), box.d, ent.getLocation().getY()-0.05, box.f);
for(Block b : UtilBlock.getInBoundingBox(bottom_corner_1, bottom_corner_2)){
if(UtilBlock.solid(b)) return true;
}
return false;
}
public static boolean isGrounded(Entity ent, Location loc)
{ {
AxisAlignedBB box = ((CraftEntity)ent).getHandle().getBoundingBox(); AxisAlignedBB box = ((CraftEntity)ent).getHandle().getBoundingBox();
Location bottom_corner_1 = new Location(ent.getWorld(), box.a, ent.getLocation().getY()-0.1, box.c); Location bottom_corner_1 = new Location(ent.getWorld(), box.a, loc.getY()-0.1, box.c);
Location bottom_corner_2 = new Location(ent.getWorld(), box.d, ent.getLocation().getY()-0.1, box.f); Location bottom_corner_2 = new Location(ent.getWorld(), box.d, loc.getY()-0.1, box.f);
for(Block b : UtilBlock.getInBoundingBox(bottom_corner_1, bottom_corner_2)){ for(Block b : UtilBlock.getInBoundingBox(bottom_corner_1, bottom_corner_2)){
if(UtilBlock.solid(b)) return true; if(UtilBlock.solid(b)) return true;
@ -639,6 +657,11 @@ public class UtilEnt
return CreatureLook(ent, UtilAlg.GetPitch(vec), UtilAlg.GetYaw(vec)); return CreatureLook(ent, UtilAlg.GetPitch(vec), UtilAlg.GetYaw(vec));
} }
public static boolean CreatureLook(Entity ent, Vector target)
{
return CreatureLook(ent, UtilAlg.GetPitch(target), UtilAlg.GetYaw(target));
}
public static void setFakeHead(Entity ent, boolean fakeHead) public static void setFakeHead(Entity ent, boolean fakeHead)
{ {
net.minecraft.server.v1_8_R3.Entity ec = ((CraftEntity) ent).getHandle(); net.minecraft.server.v1_8_R3.Entity ec = ((CraftEntity) ent).getHandle();
@ -781,6 +804,20 @@ public class UtilEnt
return null; return null;
} }
public static void setAI(LivingEntity entity, boolean ai)
{
if(entity instanceof ArmorStand)
{
((ArmorStand)entity).setGravity(ai);
return;
}
CraftEntity e = (CraftEntity)entity;
if(e.getHandle() instanceof EntityInsentient)
{
((EntityInsentient)e.getHandle()).k(!ai);
}
}
public static boolean inWater(LivingEntity ent) public static boolean inWater(LivingEntity ent)
{ {

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,7 +13,44 @@ 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)
{ {
if (item == null) if (item == null)
@ -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;
@ -12,31 +12,36 @@ import org.bukkit.util.Vector;
public class UtilMath public class UtilMath
{ {
public static double trim(int degree, double d) public static double trim(int degree, double d)
{ {
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);
DecimalFormat twoDForm = new DecimalFormat(format, symb); DecimalFormat twoDForm = new DecimalFormat(format, symb);
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 double offset2d(Entity a, Entity b) public static int rRange(int min, int max)
{
return min + r(1 + max - min);
}
public static double offset2d(Entity a, Entity b)
{ {
return offset2d(a.getLocation().toVector(), b.getLocation().toVector()); return offset2d(a.getLocation().toVector(), b.getLocation().toVector());
} }
public static double offset2d(Location a, Location b) public static double offset2d(Location a, Location b)
{ {
return offset2d(a.toVector(), b.toVector()); return offset2d(a.toVector(), b.toVector());
} }
@ -48,48 +53,67 @@ public class UtilMath
return a.subtract(b).length(); return a.subtract(b).length();
} }
public static double offset(Entity a, Entity b) public static double offset(Entity a, Entity b)
{ {
return offset(a.getLocation().toVector(), b.getLocation().toVector()); return offset(a.getLocation().toVector(), b.getLocation().toVector());
} }
public static double offset(Location a, Location b) public static double offset(Location a, Location b)
{ {
return offset(a.toVector(), b.toVector()); return offset(a.toVector(), b.toVector());
} }
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)
{ {
return offsetSquared(a.getLocation(), b.getLocation()); return offsetSquared(a.getLocation(), b.getLocation());
} }
public static double offsetSquared(Location a, Location b) public static double offsetSquared(Location a, Location b)
{ {
return offsetSquared(a.toVector(), b.toVector()); return offsetSquared(a.toVector(), b.toVector());
} }
public static double offsetSquared(Vector a, Vector b) public static double offsetSquared(Vector a, Vector b)
{ {
return a.distanceSquared(b); return a.distanceSquared(b);
} }
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

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

View File

@ -4,13 +4,12 @@ import java.util.Collection;
import java.util.HashMap; import java.util.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)
continue; {
for (int i = 0; i < ignore.length; i++)
{
if (cur.equals(ignore[i]))
continue;
}
}
double dist = UtilMath.offset(cur.getLocation(), loc); double dist = UtilMath.offset(cur.getLocation(), loc);
@ -498,6 +547,14 @@ public class UtilPlayer
if (log) if (log)
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)
{ {
@ -527,7 +584,7 @@ public class UtilPlayer
continue; continue;
//Get lower offset (eye to eye, eye to feet) //Get lower offset (eye to eye, eye to feet)
double offset = Math.min(UtilMath.offset(player.getEyeLocation(), cur.getEyeLocation()), double offset = Math.min(UtilMath.offset(player.getEyeLocation(), cur.getEyeLocation()),
UtilMath.offset(player.getEyeLocation(), cur.getLocation())); UtilMath.offset(player.getEyeLocation(), cur.getLocation()));
if (offset < distance && UtilAlg.isTargetInPlayerPyramid(player, cur, angleLimit)) if (offset < distance && UtilAlg.isTargetInPlayerPyramid(player, cur, angleLimit))
@ -590,6 +647,23 @@ public class UtilPlayer
return (((CraftEntity) player).getHandle().getDataWatcher().getByte(0) & 1 << 4) != 0; 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,18 @@ 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;
}
public static String trim(int maxLength, String s) {
return s.length() <= maxLength ? s : s.substring(0, maxLength);
}
} }

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)
@ -103,7 +124,7 @@ public class UtilTime
if (type == TimeUnit.DAYS) text = (num = UtilMath.trim(trim, time / 86400000d)) + " Day"; if (type == TimeUnit.DAYS) text = (num = UtilMath.trim(trim, time / 86400000d)) + " Day";
else if (type == TimeUnit.HOURS) text = (num = UtilMath.trim(trim, time / 3600000d)) + " Hour"; else if (type == TimeUnit.HOURS) text = (num = UtilMath.trim(trim, time / 3600000d)) + " Hour";
else if (type == TimeUnit.MINUTES) text = (num = UtilMath.trim(trim, time / 60000d)) + " Minute"; else if (type == TimeUnit.MINUTES) text = (num = UtilMath.trim(trim, time / 60000d)) + " Minute";
else if (type == TimeUnit.SECONDS) text = (int) (num = (int) UtilMath.trim(trim, time / 1000d)) + " Second"; else if (type == TimeUnit.SECONDS) text = (int) (num = (int) UtilMath.trim(trim, time / 1000d)) + " Second";
else text = (int) (num = (int) UtilMath.trim(trim, time)) + " Millisecond"; else text = (int) (num = (int) UtilMath.trim(trim, time)) + " Millisecond";
} }
else else

View File

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

View File

@ -7,6 +7,7 @@ import org.bukkit.Chunk;
import org.bukkit.Location; import org.bukkit.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
@ -45,7 +46,55 @@ public class UtilWorld
return null; return null;
} }
} }
public static String blockToStr(Block block)
{
if (block == null)
return "";
return block.getWorld().getName() + "," +
block.getX() + "," +
block.getY() + "," +
block.getZ();
}
public static String blockToStrClean(Block block)
{
if (block == null)
return "";
return "(" + block.getX() + "," +
block.getY() + "," +
block.getZ() + ")";
}
public static Block strToBlock(String string)
{
if (string.length() == 0)
return null;
String[] parts = string.split(",");
try
{
for (World cur : UtilServer.getServer().getWorlds())
{
if (cur.getName().equalsIgnoreCase(parts[0]))
{
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
return cur.getBlockAt(x, y, z);
}
}
}
catch (Exception e)
{
}
return null;
}
public static String locToStr(Location loc) 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;
@ -47,7 +48,7 @@ public class CoreClientManager extends MiniPlugin
private AccountRepository _repository; private AccountRepository _repository;
private NautHashMap<String, CoreClient> _clientList; private NautHashMap<String, CoreClient> _clientList;
private HashSet<String> _duplicateLoginGlitchPreventionList; private HashSet<String> _duplicateLoginGlitchPreventionList;
private NautHashMap<String, ILoginProcessor> _loginProcessors = new NautHashMap<String, ILoginProcessor>(); private NautHashMap<String, ILoginProcessor> _loginProcessors = new NautHashMap<String, ILoginProcessor>();
private LinkedList<IQuerylessLoginProcessor> _querylessLoginProcessors = new LinkedList<IQuerylessLoginProcessor>(); private LinkedList<IQuerylessLoginProcessor> _querylessLoginProcessors = new LinkedList<IQuerylessLoginProcessor>();
@ -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

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

View File

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

View File

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

View File

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

View File

@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.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)
{
if (!Contains(block)) GetBlocks().put(block, new BlockRestoreData(block, toID, toData, fromID, fromData, expireTime, 0));
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, long expireTime, boolean restoreOnBreak)
{
add(block, toID, toData, block.getTypeId(), block.getData(), expireTime, restoreOnBreak);
}
public void add(Block block, int toID, byte toData, int fromID, byte fromData, long expireTime)
{
add(block, toID, toData, fromID, fromData, expireTime, false);
}
public void add(Block block, int toID, byte toData, int fromID, byte fromData, long expireTime, boolean restoreOnBreak)
{
if (!contains(block)) getBlocks().put(block, new BlockRestoreData(block, toID, toData, fromID, fromData, expireTime, 0, restoreOnBreak));
else getData(block).update(toID, toData, expireTime);
}
public void snow(Block block, byte heightAdd, byte heightMax, long expireTime, long meltDelay, int heightJumps)
{ {
//Fill Above //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

@ -43,6 +43,14 @@ public class MountPage extends ShopPageBase<CosmeticManager, CosmeticShop>
if (slot == 26) if (slot == 26)
slot = 28; slot = 28;
} }
addButton(4, new ShopItem(Material.BED, C.cGray + " \u21FD Go Back", new String[]{}, 1, false), new IButton()
{
public void onClick(Player player, ClickType clickType)
{
getShop().openPageForPlayer(getPlayer(), new Menu(getPlugin(), getShop(), getClientManager(), getDonationManager(), player));
}
});
} }
protected void addMount(Mount<?> mount, int slot) protected void addMount(Mount<?> mount, int slot)
@ -76,12 +84,5 @@ public class MountPage extends ShopPageBase<CosmeticManager, CosmeticShop>
setItem(slot, new ShopItem(mount.GetDisplayMaterial(), mount.GetDisplayData(), (mount.GetCost(CurrencyType.Coins) < 0 ? "" : "Purchase ") + mount.GetName(), itemLore.toArray(new String[itemLore.size()]), 1, true, false)); setItem(slot, new ShopItem(mount.GetDisplayMaterial(), mount.GetDisplayData(), (mount.GetCost(CurrencyType.Coins) < 0 ? "" : "Purchase ") + mount.GetName(), itemLore.toArray(new String[itemLore.size()]), 1, true, false));
} }
addButton(4, new ShopItem(Material.BED, C.cGray + " \u21FD Go Back", new String[]{}, 1, false), new IButton()
{
public void onClick(Player player, ClickType clickType)
{
getShop().openPageForPlayer(getPlayer(), new Menu(getPlugin(), getShop(), getClientManager(), getDonationManager(), player));
}
});
} }
} }

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;
@ -46,7 +47,7 @@ public abstract class RepositoryBase implements Listener
public void run() public void run()
{ {
initialize(); initialize();
update(); update();
} }
}); });
@ -69,7 +70,7 @@ public abstract class RepositoryBase implements Listener
{ {
return DSL.using(DBPool.ACCOUNT, SQLDialect.MYSQL); return DSL.using(DBPool.ACCOUNT, SQLDialect.MYSQL);
} }
/** /**
* Requirements: {@link Connection}s must be closed after usage so they may be returned to the pool! * Requirements: {@link Connection}s must be closed after usage so they may be returned to the pool!
* @see Connection#close() * @see Connection#close()
@ -88,7 +89,7 @@ public abstract class RepositoryBase implements Listener
return null; return null;
} }
} }
/** /**
* Execute a query against the repository. * Execute a query against the repository.
* @param query - the concatenated query to execute in string form. * @param query - the concatenated query to execute in string form.

View File

@ -607,6 +607,22 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
{ {
entry.getKey().setEntity(entity); 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());
} }
} }
@ -864,8 +880,6 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
@EventHandler @EventHandler
public void PlayerQuit(PlayerQuitEvent event) public void PlayerQuit(PlayerQuitEvent event)
{ {
undisguise(event.getPlayer());
for (DisguiseBase disguise : _disguisePlayerMap.keySet()) for (DisguiseBase disguise : _disguisePlayerMap.keySet())
{ {
_disguisePlayerMap.get(disguise).remove(event.getPlayer()); _disguisePlayerMap.get(disguise).remove(event.getPlayer());
@ -875,6 +889,8 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
{ {
_lastRabbitHop.get(disguise).remove(event.getPlayer().getEntityId()); _lastRabbitHop.get(disguise).remove(event.getPlayer().getEntityId());
} }
undisguise(event.getPlayer());
} }
private void prepareChunk(Location loc) private void prepareChunk(Location loc)
@ -1046,8 +1062,12 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
_movePacketMap.remove(entity.getEntityId()); _movePacketMap.remove(entity.getEntityId());
_moveTempMap.remove(entity.getEntityId()); _moveTempMap.remove(entity.getEntityId());
_blockedNames.remove(((Player) entity).getName());
if (entity instanceof Player)
{
_blockedNames.remove(((Player) entity).getName());
}
refreshTrackers(entity, players.toArray(new Player[0])); refreshTrackers(entity, players.toArray(new Player[0]));
if (_bedPackets && disguise instanceof DisguisePlayer && ((DisguisePlayer) disguise).getSleepingDirection() != null) if (_bedPackets && disguise instanceof DisguisePlayer && ((DisguisePlayer) disguise).getSleepingDirection() != null)

View File

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

View File

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

View File

@ -44,6 +44,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
@Override @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(Callback<Boolean> callback, String caller, String name, int accountId, int amount)
{
rewardGold(callback, caller, name, accountId, amount, true);
} }
public void RewardGold(final Callback<Boolean> callback, final String caller, final String name, final int accountId, final int amount, final boolean updateTotal) public void rewardGold(final Callback<Boolean> callback, final String caller, final String name, final int accountId, final int amount, final boolean updateTotal)
{ {
_repository.rewardGold(new Callback<Boolean>() _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,37 +355,55 @@ 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;
for (String curCaller : _goldQueue.get(player).keySet())
{
caller = curCaller;
total += _goldQueue.get(player).get(curCaller);
}
if (caller == null)
continue;
//Actually Add Gold
RewardGold(null, caller, player.getName(), ClientManager.Get(player).getAccountId(), total, false);
System.out.println("Queue Added [" + player + "] with Gold [" + total + "] for [" + caller + "]");
//Clean
_goldQueue.get(player).clear();
} }
//Clean //Clean
_goldQueue.clear(); _goldQueue.clear();
} }
public void updateGoldQueue(final Callback<Boolean> callback, final Player player)
{
String tempCaller = null;
int tempTotal = 0;
for (String curCaller : _goldQueue.get(player).keySet())
{
tempCaller = curCaller;
tempTotal += _goldQueue.get(player).get(curCaller);
}
final String caller = tempCaller;
final int total = tempTotal;
if (caller == null)
return;
if (player.isOnline() && player.isValid())
rewardGold(callback, caller, player.getName(), ClientManager.Get(player).getAccountId(), total, false);
else
{
Bukkit.getServer().getScheduler().runTaskAsynchronously(getPlugin(), new Runnable()
{
public void run()
{
rewardGold(callback, caller, player.getName(), PlayerCache.getInstance().getPlayer(player.getUniqueId()).getAccountId(), total, false);
}
});
}
System.out.println("Queue Added [" + player + "] with Gold [" + total + "] for [" + caller + "]");
//Clean
_goldQueue.get(player).clear();
}
public void applyKits(String playerName) public void applyKits(String 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,16 +193,12 @@ 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 : ");
} }
@Override @Override
protected void initialize() protected void initialize()
{ {

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

@ -30,7 +30,7 @@ public class ItemFirework extends ItemGadget
}, },
-1, -1,
Material.FIREWORK, (byte)0, Material.FIREWORK, (byte)0,
250, new Ammo("Fireworks", "50 Fireworks", Material.FIREWORK, (byte)0, new String[] { C.cWhite + "50 Fireworks for you to launch!" }, 500, 50)); 500, new Ammo("Fireworks", "50 Fireworks", Material.FIREWORK, (byte)0, new String[] { C.cWhite + "50 Fireworks for you to launch!" }, 500, 50));
} }
@Override @Override

View File

@ -140,7 +140,7 @@ public class ItemMelonLauncher extends ItemGadget implements IThrown
{ {
Item melon = melonIterator.next(); Item melon = melonIterator.next();
if (melon.isDead() || !melon.isValid() || melon.getTicksLived() > 400) if (melon.isDead() || !melon.isValid() || melon.getTicksLived() > 100)
{ {
melonIterator.remove(); melonIterator.remove();
melon.remove(); melon.remove();

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

@ -61,7 +61,7 @@ public class ItemTNT extends ItemGadget
if (!_tnt.remove(event.getEntity())) if (!_tnt.remove(event.getEntity()))
return; return;
HashMap<Player, Double> players = UtilPlayer.getInRadius(event.getLocation(), 10); HashMap<Player, Double> players = UtilPlayer.getInRadius(event.getLocation(), 8);
for (Player player : players.keySet()) for (Player player : players.keySet())
{ {
if (Manager.collideEvent(this, player)) if (Manager.collideEvent(this, player))
@ -70,7 +70,7 @@ public class ItemTNT extends ItemGadget
double mult = players.get(player); double mult = players.get(player);
//Knockback //Knockback
UtilAction.velocity(player, UtilAlg.getTrajectory(event.getLocation(), player.getLocation()), 3 * mult, false, 0, 0.5 + 2 * mult, 10, true); UtilAction.velocity(player, UtilAlg.getTrajectory(event.getLocation(), player.getLocation()), 1 * mult, false, 0, 0.5 + 0.5 * mult, 10, true);
} }
// Simulating explosion to prevent water from being evaporated. // Simulating explosion to prevent water from being evaporated.

View File

@ -85,7 +85,7 @@ public class MorphBat extends MorphGadget implements IThrown
if (!UtilEvent.isAction(event, ActionType.L)) if (!UtilEvent.isAction(event, ActionType.L))
return; return;
if (!Recharge.Instance.use(player, GetName(), 100, false, false)) if (!Recharge.Instance.use(player, GetName(), 100, false, false, "Cosmetics"))
return; return;
//Effect //Effect
@ -106,7 +106,7 @@ public class MorphBat extends MorphGadget implements IThrown
if (!IsActive(player)) if (!IsActive(player))
return; return;
if (!Recharge.Instance.use(player, "Poop", 4000, true, false)) if (!Recharge.Instance.use(player, "Poop", 4000, true, false, "Cosmetics"))
return; return;
//Action //Action

View File

@ -76,7 +76,7 @@ public class MorphChicken extends MorphGadget
if (!UtilEvent.isAction(event, ActionType.L)) if (!UtilEvent.isAction(event, ActionType.L))
return; return;
if (!Recharge.Instance.use(player, GetName(), 100, false, false)) if (!Recharge.Instance.use(player, GetName(), 100, false, false, "Cosmetics"))
return; return;
Vector offset = player.getLocation().getDirection(); Vector offset = player.getLocation().getDirection();

View File

@ -57,7 +57,7 @@ public class MorphCow extends MorphGadget
if (!UtilEvent.isAction(event, ActionType.L)) if (!UtilEvent.isAction(event, ActionType.L))
return; return;
if (!Recharge.Instance.use(player, GetName(), 2500, false, false)) if (!Recharge.Instance.use(player, GetName(), 2500, false, false, "Cosmetics"))
return; return;
player.getWorld().playSound(player.getLocation(), Sound.COW_IDLE, 1f, 1f); player.getWorld().playSound(player.getLocation(), Sound.COW_IDLE, 1f, 1f);

View File

@ -119,7 +119,7 @@ public class MorphCreeper extends MorphGadget
double mult = players.get(other); double mult = players.get(other);
//Knockback //Knockback
UtilAction.velocity(other, UtilAlg.getTrajectory(player.getLocation(), other.getLocation()), 1 + 1.5 * mult, false, 0, 0.5 + 1 * mult, 3, true); UtilAction.velocity(other, UtilAlg.getTrajectory(player.getLocation(), other.getLocation()), 1 + 1 * mult, false, 0, 0.6 + 0.6 * mult, 3, true);
} }
} }
} }

View File

@ -78,7 +78,7 @@ public class MorphEnderman extends MorphGadget
player.setAllowFlight(false); player.setAllowFlight(false);
//Set Recharge //Set Recharge
Recharge.Instance.use(player, GetName(), 2000, false, false); Recharge.Instance.use(player, GetName(), 2000, false, false, "Cosmetics");
//Smoke Trail //Smoke Trail
Block lastSmoke = player.getLocation().getBlock(); Block lastSmoke = player.getLocation().getBlock();

View File

@ -73,7 +73,7 @@ public class MorphPig extends MorphGadget
if (!UtilEvent.isAction(event, ActionType.L)) if (!UtilEvent.isAction(event, ActionType.L))
return; return;
if (!Recharge.Instance.use(player, GetName(), 400, false, false)) if (!Recharge.Instance.use(player, GetName(), 400, false, false, "Cosmetics"))
return; return;
player.getWorld().playSound(player.getLocation(), Sound.PIG_IDLE, 1f, (float)(0.75 + Math.random() * 0.5)); player.getWorld().playSound(player.getLocation(), Sound.PIG_IDLE, 1f, (float)(0.75 + Math.random() * 0.5));

View File

@ -83,7 +83,7 @@ public class MorphSlime extends MorphGadget
if (!UtilEnt.isGrounded(player)) if (!UtilEnt.isGrounded(player))
return; return;
if (!Recharge.Instance.use(player, GetName(), 1000, false, false)) if (!Recharge.Instance.use(player, GetName(), 1000, false, false, "Cosmetics"))
return; return;
player.getWorld().playSound(player.getLocation(), Sound.SLIME_ATTACK, 1f, 1f); player.getWorld().playSound(player.getLocation(), Sound.SLIME_ATTACK, 1f, 1f);

View File

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

View File

@ -87,7 +87,7 @@ public class MorphVillager extends MorphGadget implements IThrown
return; return;
} }
if (!Recharge.Instance.use(player, GetName(), 800, false, false)) if (!Recharge.Instance.use(player, GetName(), 800, false, false, "Cosmetics"))
return; return;
player.getWorld().playSound(player.getLocation(), Sound.VILLAGER_IDLE, 1f, 1f); player.getWorld().playSound(player.getLocation(), Sound.VILLAGER_IDLE, 1f, 1f);

View File

@ -96,7 +96,7 @@ public class MorphWither extends MorphGadget
if (!UtilEvent.isAction(event, ActionType.L)) if (!UtilEvent.isAction(event, ActionType.L))
return; return;
if (!Recharge.Instance.use(player, GetName(), 1600, false, false)) if (!Recharge.Instance.use(player, GetName(), 2500, false, false, "Cosmetics"))
return; return;
Vector offset = player.getLocation().getDirection(); Vector offset = player.getLocation().getDirection();

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