Let intellij reformat the code

This commit is contained in:
Alex 2021-04-16 10:29:54 +02:00
parent 3ccfca9ecf
commit 87aaf7f7b3
115 changed files with 8024 additions and 8227 deletions

View File

@ -1,60 +1,66 @@
package com.loohp.limbo; package com.loohp.limbo;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.stream.Collectors;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.Ansi.Attribute;
import org.jline.reader.Candidate;
import org.jline.reader.Completer;
import org.jline.reader.EndOfFileException;
import org.jline.reader.LineReader;
import org.jline.reader.LineReader.SuggestionType;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.ParsedLine;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import com.loohp.limbo.commands.CommandSender; import com.loohp.limbo.commands.CommandSender;
import com.loohp.limbo.consolegui.ConsoleTextOutput; import com.loohp.limbo.consolegui.ConsoleTextOutput;
import com.loohp.limbo.utils.CustomStringUtils; import com.loohp.limbo.utils.CustomStringUtils;
import jline.console.ConsoleReader; import jline.console.ConsoleReader;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.Ansi.Attribute;
import org.jline.reader.*;
import org.jline.reader.LineReader.SuggestionType;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class Console implements CommandSender { public class Console implements CommandSender {
protected static final Map<ChatColor, String> REPLACEMENTS = new HashMap<>(); protected static final Map<ChatColor, String> REPLACEMENTS = new HashMap<>();
private final static String CONSOLE = "CONSOLE";
private final static String PROMPT = "> ";
protected final static String ERROR_RED = "\u001B[31;1m"; protected final static String ERROR_RED = "\u001B[31;1m";
protected final static String RESET_COLOR = "\u001B[0m"; protected final static String RESET_COLOR = "\u001B[0m";
private final static String CONSOLE = "CONSOLE";
private final static String PROMPT = "> ";
private Terminal terminal; static {
private LineReader tabReader; REPLACEMENTS.put(ChatColor.BLACK, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString());
private ConsoleReader reader; REPLACEMENTS.put(ChatColor.DARK_BLUE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString());
REPLACEMENTS.put(ChatColor.DARK_GREEN, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString());
REPLACEMENTS.put(ChatColor.DARK_AQUA, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString());
REPLACEMENTS.put(ChatColor.DARK_RED, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString());
REPLACEMENTS.put(ChatColor.DARK_PURPLE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString());
REPLACEMENTS.put(ChatColor.GOLD, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString());
REPLACEMENTS.put(ChatColor.GRAY, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString());
REPLACEMENTS.put(ChatColor.DARK_GRAY, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString());
REPLACEMENTS.put(ChatColor.BLUE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString());
REPLACEMENTS.put(ChatColor.GREEN, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString());
REPLACEMENTS.put(ChatColor.AQUA, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString());
REPLACEMENTS.put(ChatColor.RED, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.RED).bold().toString());
REPLACEMENTS.put(ChatColor.LIGHT_PURPLE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.MAGENTA).bold().toString());
REPLACEMENTS.put(ChatColor.YELLOW, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString());
REPLACEMENTS.put(ChatColor.WHITE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString());
REPLACEMENTS.put(ChatColor.MAGIC, Ansi.ansi().a(Attribute.BLINK_SLOW).toString());
REPLACEMENTS.put(ChatColor.BOLD, Ansi.ansi().a(Attribute.UNDERLINE_DOUBLE).toString());
REPLACEMENTS.put(ChatColor.STRIKETHROUGH, Ansi.ansi().a(Attribute.STRIKETHROUGH_ON).toString());
REPLACEMENTS.put(ChatColor.UNDERLINE, Ansi.ansi().a(Attribute.UNDERLINE).toString());
REPLACEMENTS.put(ChatColor.ITALIC, Ansi.ansi().a(Attribute.ITALIC).toString());
REPLACEMENTS.put(ChatColor.RESET, Ansi.ansi().a(Attribute.RESET).toString());
}
private InputStream in;
@SuppressWarnings("unused")
private PrintStream out;
@SuppressWarnings("unused")
private PrintStream err;
protected PrintStream logs; protected PrintStream logs;
private final Terminal terminal;
private final LineReader tabReader;
private final ConsoleReader reader;
private final InputStream in;
@SuppressWarnings("unused")
private final PrintStream out;
@SuppressWarnings("unused")
private final PrintStream err;
public Console(InputStream in, PrintStream out, PrintStream err) throws IOException { public Console(InputStream in, PrintStream out, PrintStream err) throws IOException {
String fileName = new SimpleDateFormat("yyyy'-'MM'-'dd'_'HH'-'mm'-'ss'_'zzz'.log'").format(new Date()); String fileName = new SimpleDateFormat("yyyy'-'MM'-'dd'_'HH'-'mm'-'ss'_'zzz'.log'").format(new Date());
@ -103,6 +109,14 @@ public class Console implements CommandSender {
tabReader.setAutosuggestion(SuggestionType.NONE); tabReader.setAutosuggestion(SuggestionType.NONE);
} }
protected static String translateToConsole(String str) {
for (Entry<ChatColor, String> entry : REPLACEMENTS.entrySet()) {
str = str.replace(entry.getKey().toString(), entry.getValue());
}
str = str.replaceAll("(?i)" + ChatColor.COLOR_CHAR + "x(" + ChatColor.COLOR_CHAR + "[0-9a-f]){6}", "");
return str + RESET_COLOR;
}
@Override @Override
public String getName() { public String getName() {
return CONSOLE; return CONSOLE;
@ -175,7 +189,8 @@ public class Console implements CommandSender {
protected void stashLine() { protected void stashLine() {
try { try {
tabReader.callWidget(LineReader.CLEAR); tabReader.callWidget(LineReader.CLEAR);
} catch (Exception ignore) {} } catch (Exception ignore) {
}
} }
protected void unstashLine() { protected void unstashLine() {
@ -183,46 +198,14 @@ public class Console implements CommandSender {
tabReader.callWidget(LineReader.REDRAW_LINE); tabReader.callWidget(LineReader.REDRAW_LINE);
tabReader.callWidget(LineReader.REDISPLAY); tabReader.callWidget(LineReader.REDISPLAY);
tabReader.getTerminal().writer().flush(); tabReader.getTerminal().writer().flush();
} catch (Exception ignore) {} } catch (Exception ignore) {
} }
static {
REPLACEMENTS.put(ChatColor.BLACK, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString());
REPLACEMENTS.put(ChatColor.DARK_BLUE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString());
REPLACEMENTS.put(ChatColor.DARK_GREEN, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString());
REPLACEMENTS.put(ChatColor.DARK_AQUA, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString());
REPLACEMENTS.put(ChatColor.DARK_RED, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString());
REPLACEMENTS.put(ChatColor.DARK_PURPLE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString());
REPLACEMENTS.put(ChatColor.GOLD, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString());
REPLACEMENTS.put(ChatColor.GRAY, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString());
REPLACEMENTS.put(ChatColor.DARK_GRAY, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString());
REPLACEMENTS.put(ChatColor.BLUE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString());
REPLACEMENTS.put(ChatColor.GREEN, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString());
REPLACEMENTS.put(ChatColor.AQUA, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString());
REPLACEMENTS.put(ChatColor.RED, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.RED).bold().toString());
REPLACEMENTS.put(ChatColor.LIGHT_PURPLE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.MAGENTA).bold().toString());
REPLACEMENTS.put(ChatColor.YELLOW, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString());
REPLACEMENTS.put(ChatColor.WHITE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString());
REPLACEMENTS.put(ChatColor.MAGIC, Ansi.ansi().a(Attribute.BLINK_SLOW).toString());
REPLACEMENTS.put(ChatColor.BOLD, Ansi.ansi().a(Attribute.UNDERLINE_DOUBLE).toString());
REPLACEMENTS.put(ChatColor.STRIKETHROUGH, Ansi.ansi().a(Attribute.STRIKETHROUGH_ON).toString());
REPLACEMENTS.put(ChatColor.UNDERLINE, Ansi.ansi().a(Attribute.UNDERLINE).toString());
REPLACEMENTS.put(ChatColor.ITALIC, Ansi.ansi().a(Attribute.ITALIC).toString());
REPLACEMENTS.put(ChatColor.RESET, Ansi.ansi().a(Attribute.RESET).toString());
}
protected static String translateToConsole(String str) {
for (Entry<ChatColor, String> entry : REPLACEMENTS.entrySet()) {
str = str.replace(entry.getKey().toString(), entry.getValue());
}
str = str.replaceAll("(?i)" + ChatColor.COLOR_CHAR + "x(" + ChatColor.COLOR_CHAR + "[0-9a-f]){6}", "");
return str + RESET_COLOR;
} }
public static class ConsoleOutputStream extends PrintStream { public static class ConsoleOutputStream extends PrintStream {
private PrintStream logs; private final PrintStream logs;
private Console console; private final Console console;
public ConsoleOutputStream(Console console, OutputStream out, PrintStream logs) { public ConsoleOutputStream(Console console, OutputStream out, PrintStream logs) {
super(out); super(out);
@ -357,8 +340,8 @@ public class Console implements CommandSender {
public static class ConsoleErrorStream extends PrintStream { public static class ConsoleErrorStream extends PrintStream {
private PrintStream logs; private final PrintStream logs;
private Console console; private final Console console;
public ConsoleErrorStream(Console console, OutputStream out, PrintStream logs) { public ConsoleErrorStream(Console console, OutputStream out, PrintStream logs) {
super(out); super(out);

View File

@ -1,51 +1,10 @@
package com.loohp.limbo; package com.loohp.limbo;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.loohp.limbo.events.EventsManager;
import com.loohp.limbo.server.ServerConnection;
import com.loohp.limbo.server.packets.Packet;
import com.loohp.limbo.server.packets.PacketIn;
import com.loohp.limbo.server.packets.PacketOut;
import com.loohp.limbo.commands.CommandSender; import com.loohp.limbo.commands.CommandSender;
import com.loohp.limbo.consolegui.GUI; import com.loohp.limbo.consolegui.GUI;
import com.loohp.limbo.events.EventsManager;
import com.loohp.limbo.file.ServerProperties; import com.loohp.limbo.file.ServerProperties;
import com.loohp.limbo.location.Location; import com.loohp.limbo.location.Location;
import com.loohp.limbo.metrics.Metrics; import com.loohp.limbo.metrics.Metrics;
@ -55,6 +14,10 @@ import com.loohp.limbo.plugins.LimboPlugin;
import com.loohp.limbo.plugins.PluginManager; import com.loohp.limbo.plugins.PluginManager;
import com.loohp.limbo.scheduler.LimboScheduler; import com.loohp.limbo.scheduler.LimboScheduler;
import com.loohp.limbo.scheduler.Tick; import com.loohp.limbo.scheduler.Tick;
import com.loohp.limbo.server.ServerConnection;
import com.loohp.limbo.server.packets.Packet;
import com.loohp.limbo.server.packets.PacketIn;
import com.loohp.limbo.server.packets.PacketOut;
import com.loohp.limbo.utils.CustomStringUtils; import com.loohp.limbo.utils.CustomStringUtils;
import com.loohp.limbo.utils.ImageUtils; import com.loohp.limbo.utils.ImageUtils;
import com.loohp.limbo.utils.NetworkUtils; import com.loohp.limbo.utils.NetworkUtils;
@ -62,85 +25,60 @@ import com.loohp.limbo.world.DimensionRegistry;
import com.loohp.limbo.world.Environment; import com.loohp.limbo.world.Environment;
import com.loohp.limbo.world.Schematic; import com.loohp.limbo.world.Schematic;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.chat.ComponentSerializer; import net.md_5.bungee.chat.ComponentSerializer;
import net.querz.nbt.io.NBTUtil; import net.querz.nbt.io.NBTUtil;
import net.querz.nbt.tag.CompoundTag; import net.querz.nbt.tag.CompoundTag;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class Limbo { public class Limbo {
private static Limbo instance;
public static boolean noGui = false; public static boolean noGui = false;
private static Limbo instance;
public static void main(String args[]) throws IOException, ParseException, NumberFormatException, ClassNotFoundException, InterruptedException {
for (String flag : args) {
if (flag.equals("--nogui") || flag.equals("nogui")) {
noGui = true;
} else if (flag.equals("--help")) {
System.out.println("Accepted flags:");
System.out.println(" --nogui <- Disable the GUI");
System.exit(0);
} else {
System.out.println("Unknown flag: \"" + flag + "\". Ignoring...");
}
}
if (GraphicsEnvironment.isHeadless()) {
noGui = true;
}
if (!noGui) {
System.out.println("Launching Server GUI.. Add \"--nogui\" in launch arguments to disable");
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
GUI.main();
}
});
t1.start();
}
new Limbo();
}
public static Limbo getInstance() {
return instance;
}
//===========================
public final String serverImplementationVersion = "1.16.5"; public final String serverImplementationVersion = "1.16.5";
public final int serverImplmentationProtocol = 754; public final int serverImplmentationProtocol = 754;
//===========================
public final String limboImplementationVersion; public final String limboImplementationVersion;
private AtomicBoolean isRunning;
private ServerConnection server;
private Console console;
private List<World> worlds = new ArrayList<>();
private Map<String, Player> playersByName = new HashMap<>();
private Map<UUID, Player> playersByUUID = new HashMap<>();
private ServerProperties properties;
private PluginManager pluginManager;
private EventsManager eventsManager;
private PermissionsManager permissionManager;
private File pluginFolder;
private File internalDataFolder;
private DimensionRegistry dimensionRegistry;
private Tick tick;
private LimboScheduler scheduler;
private Metrics metrics;
public AtomicInteger entityIdCount = new AtomicInteger(); public AtomicInteger entityIdCount = new AtomicInteger();
private final AtomicBoolean isRunning;
private final ServerConnection server;
private final Console console;
private final List<World> worlds = new ArrayList<>();
private final Map<String, Player> playersByName = new HashMap<>();
private final Map<UUID, Player> playersByUUID = new HashMap<>();
private final ServerProperties properties;
private final PluginManager pluginManager;
private final EventsManager eventsManager;
private final PermissionsManager permissionManager;
private final File pluginFolder;
private final File internalDataFolder;
private final DimensionRegistry dimensionRegistry;
private final Tick tick;
private final LimboScheduler scheduler;
private final Metrics metrics;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private Unsafe unsafe = new Unsafe(); private final Unsafe unsafe = new Unsafe();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Limbo() throws IOException, ParseException, NumberFormatException, ClassNotFoundException, InterruptedException { public Limbo() throws IOException, ParseException, NumberFormatException, ClassNotFoundException, InterruptedException {
@ -203,7 +141,7 @@ public class Limbo {
Map<Integer, Class<? extends PacketIn>> HandshakeIn = new HashMap<>(); Map<Integer, Class<? extends PacketIn>> HandshakeIn = new HashMap<>();
for (Object key : ((JSONObject) json.get("HandshakeIn")).keySet()) { for (Object key : ((JSONObject) json.get("HandshakeIn")).keySet()) {
int packetId = Integer.decode((String) key); int packetId = Integer.decode((String) key);
HandshakeIn.put(packetId, (Class<? extends PacketIn>) Class.forName(classPrefix + (String) ((JSONObject) json.get("HandshakeIn")).get(key))); HandshakeIn.put(packetId, (Class<? extends PacketIn>) Class.forName(classPrefix + ((JSONObject) json.get("HandshakeIn")).get(key)));
} }
Packet.setHandshakeIn(HandshakeIn); Packet.setHandshakeIn(HandshakeIn);
mappingsCount += HandshakeIn.size(); mappingsCount += HandshakeIn.size();
@ -211,14 +149,14 @@ public class Limbo {
Map<Integer, Class<? extends PacketIn>> StatusIn = new HashMap<>(); Map<Integer, Class<? extends PacketIn>> StatusIn = new HashMap<>();
for (Object key : ((JSONObject) json.get("StatusIn")).keySet()) { for (Object key : ((JSONObject) json.get("StatusIn")).keySet()) {
int packetId = Integer.decode((String) key); int packetId = Integer.decode((String) key);
StatusIn.put(packetId, (Class<? extends PacketIn>) Class.forName(classPrefix + (String) ((JSONObject) json.get("StatusIn")).get(key))); StatusIn.put(packetId, (Class<? extends PacketIn>) Class.forName(classPrefix + ((JSONObject) json.get("StatusIn")).get(key)));
} }
Packet.setStatusIn(StatusIn); Packet.setStatusIn(StatusIn);
mappingsCount += StatusIn.size(); mappingsCount += StatusIn.size();
Map<Class<? extends PacketOut>, Integer> StatusOut = new HashMap<>(); Map<Class<? extends PacketOut>, Integer> StatusOut = new HashMap<>();
for (Object key : ((JSONObject) json.get("StatusOut")).keySet()) { for (Object key : ((JSONObject) json.get("StatusOut")).keySet()) {
Class<? extends PacketOut> packetClass = (Class<? extends PacketOut>) Class.forName(classPrefix + (String) key); Class<? extends PacketOut> packetClass = (Class<? extends PacketOut>) Class.forName(classPrefix + key);
StatusOut.put(packetClass, Integer.decode((String) ((JSONObject) json.get("StatusOut")).get(key))); StatusOut.put(packetClass, Integer.decode((String) ((JSONObject) json.get("StatusOut")).get(key)));
} }
Packet.setStatusOut(StatusOut); Packet.setStatusOut(StatusOut);
@ -227,14 +165,14 @@ public class Limbo {
Map<Integer, Class<? extends PacketIn>> LoginIn = new HashMap<>(); Map<Integer, Class<? extends PacketIn>> LoginIn = new HashMap<>();
for (Object key : ((JSONObject) json.get("LoginIn")).keySet()) { for (Object key : ((JSONObject) json.get("LoginIn")).keySet()) {
int packetId = Integer.decode((String) key); int packetId = Integer.decode((String) key);
LoginIn.put(packetId, (Class<? extends PacketIn>) Class.forName(classPrefix + (String) ((JSONObject) json.get("LoginIn")).get(key))); LoginIn.put(packetId, (Class<? extends PacketIn>) Class.forName(classPrefix + ((JSONObject) json.get("LoginIn")).get(key)));
} }
Packet.setLoginIn(LoginIn); Packet.setLoginIn(LoginIn);
mappingsCount += LoginIn.size(); mappingsCount += LoginIn.size();
Map<Class<? extends PacketOut>, Integer> LoginOut = new HashMap<>(); Map<Class<? extends PacketOut>, Integer> LoginOut = new HashMap<>();
for (Object key : ((JSONObject) json.get("LoginOut")).keySet()) { for (Object key : ((JSONObject) json.get("LoginOut")).keySet()) {
Class<? extends PacketOut> packetClass = (Class<? extends PacketOut>) Class.forName(classPrefix + (String) key); Class<? extends PacketOut> packetClass = (Class<? extends PacketOut>) Class.forName(classPrefix + key);
LoginOut.put(packetClass, Integer.decode((String) ((JSONObject) json.get("LoginOut")).get(key))); LoginOut.put(packetClass, Integer.decode((String) ((JSONObject) json.get("LoginOut")).get(key)));
} }
Packet.setLoginOut(LoginOut); Packet.setLoginOut(LoginOut);
@ -243,14 +181,14 @@ public class Limbo {
Map<Integer, Class<? extends PacketIn>> PlayIn = new HashMap<>(); Map<Integer, Class<? extends PacketIn>> PlayIn = new HashMap<>();
for (Object key : ((JSONObject) json.get("PlayIn")).keySet()) { for (Object key : ((JSONObject) json.get("PlayIn")).keySet()) {
int packetId = Integer.decode((String) key); int packetId = Integer.decode((String) key);
PlayIn.put(packetId, (Class<? extends PacketIn>) Class.forName(classPrefix + (String) ((JSONObject) json.get("PlayIn")).get(key))); PlayIn.put(packetId, (Class<? extends PacketIn>) Class.forName(classPrefix + ((JSONObject) json.get("PlayIn")).get(key)));
} }
Packet.setPlayIn(PlayIn); Packet.setPlayIn(PlayIn);
mappingsCount += PlayIn.size(); mappingsCount += PlayIn.size();
Map<Class<? extends PacketOut>, Integer> PlayOut = new HashMap<>(); Map<Class<? extends PacketOut>, Integer> PlayOut = new HashMap<>();
for (Object key : ((JSONObject) json.get("PlayOut")).keySet()) { for (Object key : ((JSONObject) json.get("PlayOut")).keySet()) {
Class<? extends PacketOut> packetClass = (Class<? extends PacketOut>) Class.forName(classPrefix + (String) key); Class<? extends PacketOut> packetClass = (Class<? extends PacketOut>) Class.forName(classPrefix + key);
PlayOut.put(packetClass, Integer.decode((String) ((JSONObject) json.get("PlayOut")).get(key))); PlayOut.put(packetClass, Integer.decode((String) ((JSONObject) json.get("PlayOut")).get(key)));
} }
Packet.setPlayOut(PlayOut); Packet.setPlayOut(PlayOut);
@ -328,6 +266,39 @@ public class Limbo {
console.run(); console.run();
} }
public static void main(String[] args) throws IOException, ParseException, NumberFormatException, ClassNotFoundException, InterruptedException {
for (String flag : args) {
if (flag.equals("--nogui") || flag.equals("nogui")) {
noGui = true;
} else if (flag.equals("--help")) {
System.out.println("Accepted flags:");
System.out.println(" --nogui <- Disable the GUI");
System.exit(0);
} else {
System.out.println("Unknown flag: \"" + flag + "\". Ignoring...");
}
}
if (GraphicsEnvironment.isHeadless()) {
noGui = true;
}
if (!noGui) {
System.out.println("Launching Server GUI.. Add \"--nogui\" in launch arguments to disable");
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
GUI.main();
}
});
t1.start();
}
new Limbo();
}
public static Limbo getInstance() {
return instance;
}
@Deprecated @Deprecated
public Unsafe getUnsafe() { public Unsafe getUnsafe() {
return unsafe; return unsafe;
@ -496,7 +467,7 @@ public class Limbo {
} }
public String buildLegacyPingResponse(String version, BaseComponent[] motd, int maxPlayers, int playersOnline) { public String buildLegacyPingResponse(String version, BaseComponent[] motd, int maxPlayers, int playersOnline) {
String begin = "§1"; String begin = "<EFBFBD>1";
return String.join("\00", begin, "127", version, String.join("", Arrays.asList(motd).stream().map(each -> each.toLegacyText()).collect(Collectors.toList())), String.valueOf(playersOnline), String.valueOf(maxPlayers)); return String.join("\00", begin, "127", version, String.join("", Arrays.asList(motd).stream().map(each -> each.toLegacyText()).collect(Collectors.toList())), String.valueOf(playersOnline), String.valueOf(maxPlayers));
} }

View File

@ -1,7 +1,5 @@
package com.loohp.limbo; package com.loohp.limbo;
import java.lang.reflect.Constructor;
import com.loohp.limbo.entity.DataWatcher; import com.loohp.limbo.entity.DataWatcher;
import com.loohp.limbo.entity.Entity; import com.loohp.limbo.entity.Entity;
import com.loohp.limbo.location.Location; import com.loohp.limbo.location.Location;
@ -9,6 +7,8 @@ import com.loohp.limbo.player.Player;
import com.loohp.limbo.utils.GameMode; import com.loohp.limbo.utils.GameMode;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import java.lang.reflect.Constructor;
@Deprecated @Deprecated
public class Unsafe { public class Unsafe {
@ -26,7 +26,9 @@ public class Unsafe {
worldConstructor.setAccessible(true); worldConstructor.setAccessible(true);
worldUnsafe = worldConstructor.newInstance(); worldUnsafe = worldConstructor.newInstance();
worldConstructor.setAccessible(false); worldConstructor.setAccessible(false);
} catch (Exception e) {e.printStackTrace();} } catch (Exception e) {
e.printStackTrace();
}
} }
@Deprecated @Deprecated

View File

@ -2,6 +2,6 @@ package com.loohp.limbo.commands;
public interface CommandExecutor { public interface CommandExecutor {
public void execute(CommandSender sender, String[] args); void execute(CommandSender sender, String[] args);
} }

View File

@ -1,25 +1,25 @@
package com.loohp.limbo.commands; package com.loohp.limbo.commands;
import java.util.UUID;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
import java.util.UUID;
public interface CommandSender { public interface CommandSender {
public void sendMessage(BaseComponent[] component, UUID uuid); void sendMessage(BaseComponent[] component, UUID uuid);
public void sendMessage(BaseComponent component, UUID uuid); void sendMessage(BaseComponent component, UUID uuid);
public void sendMessage(String message, UUID uuid); void sendMessage(String message, UUID uuid);
public void sendMessage(BaseComponent[] component); void sendMessage(BaseComponent[] component);
public void sendMessage(BaseComponent component); void sendMessage(BaseComponent component);
public void sendMessage(String message); void sendMessage(String message);
public boolean hasPermission(String permission); boolean hasPermission(String permission);
public String getName(); String getName();
} }

View File

@ -4,6 +4,6 @@ import java.util.List;
public interface TabCompletor { public interface TabCompletor {
public List<String> tabComplete(CommandSender sender, String[] args); List<String> tabComplete(CommandSender sender, String[] args);
} }

View File

@ -1,29 +1,14 @@
package com.loohp.limbo.consolegui; package com.loohp.limbo.consolegui;
import java.awt.Font; import com.loohp.limbo.Limbo;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout; import javax.swing.*;
import java.awt.Insets; import javax.swing.border.EmptyBorder;
import java.awt.event.KeyAdapter; import java.awt.*;
import java.awt.event.KeyEvent; import java.awt.event.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import com.loohp.limbo.Limbo;
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class GUI extends JFrame { public class GUI extends JFrame {
@ -45,24 +30,6 @@ public class GUI extends JFrame {
public static boolean loadFinish = false; public static boolean loadFinish = false;
/**
* Launch the application.
*/
public static void main() {
GUI frame = new GUI();
frame.setVisible(true);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
SystemInfo.printInfo();
}
});
t1.start();
loadFinish = true;
}
/** /**
* Create the frame. * Create the frame.
*/ */
@ -217,4 +184,22 @@ public class GUI extends JFrame {
contentPane.add(execCommand, gbc_execCommand); contentPane.add(execCommand, gbc_execCommand);
} }
/**
* Launch the application.
*/
public static void main() {
GUI frame = new GUI();
frame.setVisible(true);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
SystemInfo.printInfo();
}
});
t1.start();
loadFinish = true;
}
} }

View File

@ -1,11 +1,11 @@
package com.loohp.limbo.consolegui; package com.loohp.limbo.consolegui;
import com.loohp.limbo.Limbo;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.loohp.limbo.Limbo;
public class SystemInfo { public class SystemInfo {
public static void printInfo() { public static void printInfo() {
@ -39,9 +39,13 @@ public class SystemInfo {
sb.append("Process CPU Load: " + Math.round(processLoad * 100) + "%\n"); sb.append("Process CPU Load: " + Math.round(processLoad * 100) + "%\n");
sb.append("System CPU Load: " + Math.round(systemLoad * 100) + "%\n"); sb.append("System CPU Load: " + Math.round(systemLoad * 100) + "%\n");
GUI.sysText.setText(sb.toString()); GUI.sysText.setText(sb.toString());
} catch (Exception ignore) {} } catch (Exception ignore) {
}
try {TimeUnit.MILLISECONDS.sleep(1000);} catch (InterruptedException e) {} try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
}
} }
} }
} }

View File

@ -1,7 +1,5 @@
package com.loohp.limbo.entity; package com.loohp.limbo.entity;
import java.util.UUID;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.entity.DataWatcher.WatchableField; import com.loohp.limbo.entity.DataWatcher.WatchableField;
import com.loohp.limbo.entity.DataWatcher.WatchableObjectType; import com.loohp.limbo.entity.DataWatcher.WatchableObjectType;
@ -9,6 +7,8 @@ import com.loohp.limbo.location.Location;
import com.loohp.limbo.utils.Rotation3f; import com.loohp.limbo.utils.Rotation3f;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import java.util.UUID;
public class ArmorStand extends LivingEntity { public class ArmorStand extends LivingEntity {
@WatchableField(MetadataIndex = 14, WatchableObjectType = WatchableObjectType.BYTE, IsBitmask = true, Bitmask = 0x01) @WatchableField(MetadataIndex = 14, WatchableObjectType = WatchableObjectType.BYTE, IsBitmask = true, Bitmask = 0x01)

View File

@ -12,8 +12,8 @@ import java.util.Map.Entry;
public class DataWatcher { public class DataWatcher {
private Entity entity; private final Entity entity;
private Map<Field, WatchableObject> values; private final Map<Field, WatchableObject> values;
public DataWatcher(Entity entity) { public DataWatcher(Entity entity) {
this.entity = entity; this.entity = entity;
@ -66,13 +66,66 @@ public class DataWatcher {
return Collections.unmodifiableMap(values); return Collections.unmodifiableMap(values);
} }
public enum WatchableObjectType {
BYTE(0),
VARINT(1, 17),
FLOAT(2),
STRING(3),
CHAT(4, 5),
SLOT(6),
BOOLEAN(7),
ROTATION(8),
POSITION(9, 10),
DIRECTION(11),
UUID(-1, 12),
BLOCKID(-1, 13),
NBT(14),
PARTICLE(15),
VILLAGER_DATA(16),
POSE(18);
int typeId;
int optionalTypeId;
WatchableObjectType(int typeId, int optionalTypeId) {
this.typeId = typeId;
this.optionalTypeId = optionalTypeId;
}
WatchableObjectType(int typeId) {
this(typeId, -1);
}
public int getTypeId() {
return typeId;
}
public int getOptionalTypeId() {
return optionalTypeId;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface WatchableField {
int MetadataIndex();
WatchableObjectType WatchableObjectType();
boolean IsOptional() default false;
boolean IsBitmask() default false;
int Bitmask() default 0x00;
}
public static class WatchableObject { public static class WatchableObject {
private int index; private final int index;
private WatchableObjectType type; private final WatchableObjectType type;
private boolean optional; private final boolean optional;
private boolean isBitmask; private final boolean isBitmask;
private int bitmask; private final int bitmask;
private Object value; private Object value;
@ -126,53 +179,4 @@ public class DataWatcher {
} }
} }
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public static @interface WatchableField {
int MetadataIndex();
WatchableObjectType WatchableObjectType();
boolean IsOptional() default false;
boolean IsBitmask() default false;
int Bitmask() default 0x00;
}
public static enum WatchableObjectType {
BYTE(0),
VARINT(1, 17),
FLOAT(2),
STRING(3),
CHAT(4, 5),
SLOT(6),
BOOLEAN(7),
ROTATION(8),
POSITION(9, 10),
DIRECTION(11),
UUID(-1, 12),
BLOCKID(-1, 13),
NBT(14),
PARTICLE(15),
VILLAGER_DATA(16),
POSE(18);
int typeId;
int optionalTypeId;
WatchableObjectType(int typeId, int optionalTypeId) {
this.typeId = typeId;
this.optionalTypeId = optionalTypeId;
}
WatchableObjectType(int typeId) {
this(typeId, -1);
}
public int getTypeId() {
return typeId;
}
public int getOptionalTypeId() {
return optionalTypeId;
}
}
} }

View File

@ -1,18 +1,18 @@
package com.loohp.limbo.entity; package com.loohp.limbo.entity;
import java.util.UUID;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.entity.DataWatcher.WatchableField; import com.loohp.limbo.entity.DataWatcher.WatchableField;
import com.loohp.limbo.entity.DataWatcher.WatchableObjectType; import com.loohp.limbo.entity.DataWatcher.WatchableObjectType;
import com.loohp.limbo.location.Location; import com.loohp.limbo.location.Location;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.chat.TextComponent;
import java.util.UUID;
public abstract class Entity { public abstract class Entity {
protected final EntityType type;
@WatchableField(MetadataIndex = 0, WatchableObjectType = WatchableObjectType.BYTE, IsBitmask = true, Bitmask = 0x01) @WatchableField(MetadataIndex = 0, WatchableObjectType = WatchableObjectType.BYTE, IsBitmask = true, Bitmask = 0x01)
protected boolean onFire = false; protected boolean onFire = false;
@WatchableField(MetadataIndex = 0, WatchableObjectType = WatchableObjectType.BYTE, IsBitmask = true, Bitmask = 0x02) @WatchableField(MetadataIndex = 0, WatchableObjectType = WatchableObjectType.BYTE, IsBitmask = true, Bitmask = 0x02)
@ -41,9 +41,6 @@ public abstract class Entity {
protected boolean noGravity = false; protected boolean noGravity = false;
@WatchableField(MetadataIndex = 6, WatchableObjectType = WatchableObjectType.POSE) @WatchableField(MetadataIndex = 6, WatchableObjectType = WatchableObjectType.POSE)
protected Pose pose = Pose.STANDING; protected Pose pose = Pose.STANDING;
protected final EntityType type;
protected int entityId; protected int entityId;
protected UUID uuid; protected UUID uuid;
protected World world; protected World world;

View File

@ -1,13 +1,13 @@
package com.loohp.limbo.entity; package com.loohp.limbo.entity;
import java.util.HashMap;
import java.util.Map;
import com.loohp.limbo.location.Location; import com.loohp.limbo.location.Location;
import com.loohp.limbo.player.Player; import com.loohp.limbo.player.Player;
import com.loohp.limbo.utils.NamespacedKey; import com.loohp.limbo.utils.NamespacedKey;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import java.util.HashMap;
import java.util.Map;
public enum EntityType { public enum EntityType {
// These strings MUST match the strings in nms.EntityTypes and are case sensitive. // These strings MUST match the strings in nms.EntityTypes and are case sensitive.
@ -270,13 +270,6 @@ public enum EntityType {
*/ */
UNKNOWN(null, null, -1, false); UNKNOWN(null, null, -1, false);
private final String name;
private final Class<? extends Entity> clazz;
private final short typeId;
private final boolean independent;
private final boolean living;
private final NamespacedKey key;
private static final Map<String, EntityType> NAME_MAP = new HashMap<>(); private static final Map<String, EntityType> NAME_MAP = new HashMap<>();
private static final Map<Short, EntityType> ID_MAP = new HashMap<>(); private static final Map<Short, EntityType> ID_MAP = new HashMap<>();
@ -308,11 +301,18 @@ public enum EntityType {
*/ */
} }
private EntityType(String name, Class<? extends Entity> clazz, int typeId) { private final String name;
private final Class<? extends Entity> clazz;
private final short typeId;
private final boolean independent;
private final boolean living;
private final NamespacedKey key;
EntityType(String name, Class<? extends Entity> clazz, int typeId) {
this(name, clazz, typeId, true); this(name, clazz, typeId, true);
} }
private EntityType(String name, Class<? extends Entity> clazz, int typeId, boolean independent) { EntityType(String name, Class<? extends Entity> clazz, int typeId, boolean independent) {
this.name = name; this.name = name;
this.clazz = clazz; this.clazz = clazz;
this.typeId = (short) typeId; this.typeId = (short) typeId;
@ -321,34 +321,6 @@ public enum EntityType {
this.key = (name == null) ? null : NamespacedKey.minecraft(name); this.key = (name == null) ? null : NamespacedKey.minecraft(name);
} }
/**
* Gets the entity type name.
*
* @return the entity type's name
* @deprecated Magic value
*/
@Deprecated
public String getName() {
return name;
}
public NamespacedKey getKey() {
return key;
}
public Class<? extends Entity> getEntityClass() {
return clazz;
}
/**
* Gets the entity network type id.
*
* @return the network type id
*/
public short getTypeId() {
return typeId;
}
/** /**
* Gets an entity type from its name. * Gets an entity type from its name.
* *
@ -379,6 +351,34 @@ public enum EntityType {
return ID_MAP.get((short) id); return ID_MAP.get((short) id);
} }
/**
* Gets the entity type name.
*
* @return the entity type's name
* @deprecated Magic value
*/
@Deprecated
public String getName() {
return name;
}
public NamespacedKey getKey() {
return key;
}
public Class<? extends Entity> getEntityClass() {
return clazz;
}
/**
* Gets the entity network type id.
*
* @return the network type id
*/
public short getTypeId() {
return typeId;
}
/** /**
* Some entities cannot be spawned using {@link * Some entities cannot be spawned using {@link
* World#spawnEntity(Location, EntityType)} or {@link * World#spawnEntity(Location, EntityType)} or {@link

View File

@ -1,7 +1,5 @@
package com.loohp.limbo.entity; package com.loohp.limbo.entity;
import java.util.UUID;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.entity.DataWatcher.WatchableField; import com.loohp.limbo.entity.DataWatcher.WatchableField;
import com.loohp.limbo.entity.DataWatcher.WatchableObjectType; import com.loohp.limbo.entity.DataWatcher.WatchableObjectType;
@ -10,6 +8,8 @@ import com.loohp.limbo.location.Location;
import com.loohp.limbo.world.BlockPosition; import com.loohp.limbo.world.BlockPosition;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import java.util.UUID;
public abstract class LivingEntity extends Entity { public abstract class LivingEntity extends Entity {
@WatchableField(MetadataIndex = 7, WatchableObjectType = WatchableObjectType.BYTE, IsBitmask = true, Bitmask = 0x01) @WatchableField(MetadataIndex = 7, WatchableObjectType = WatchableObjectType.BYTE, IsBitmask = true, Bitmask = 0x01)
@ -69,7 +69,7 @@ public abstract class LivingEntity extends Entity {
} else if (activeHand.equals(EquipmentSlot.OFFHAND)) { } else if (activeHand.equals(EquipmentSlot.OFFHAND)) {
this.activeHand = true; this.activeHand = true;
} else { } else {
throw new IllegalArgumentException("Invalid EquipmentSlot " + activeHand.toString()); throw new IllegalArgumentException("Invalid EquipmentSlot " + activeHand);
} }
} }

View File

@ -12,16 +12,12 @@ public enum Pose {
private static final Pose[] VALUES = values(); private static final Pose[] VALUES = values();
private int id; private final int id;
Pose(int id) { Pose(int id) {
this.id = id; this.id = id;
} }
public int getId() {
return id;
}
public static Pose fromId(int id) { public static Pose fromId(int id) {
for (Pose pose : VALUES) { for (Pose pose : VALUES) {
if (id == pose.id) { if (id == pose.id) {
@ -31,4 +27,8 @@ public enum Pose {
return null; return null;
} }
public int getId() {
return id;
}
} }

View File

@ -2,8 +2,8 @@ package com.loohp.limbo.events;
public interface Cancellable { public interface Cancellable {
public void setCancelled(boolean cancelled); boolean isCancelled();
public boolean isCancelled(); void setCancelled(boolean cancelled);
} }

View File

@ -1,10 +1,6 @@
package com.loohp.limbo.events; package com.loohp.limbo.events;
import java.lang.annotation.Documented; import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented @Documented
@Target(ElementType.METHOD) @Target(ElementType.METHOD)

View File

@ -14,10 +14,6 @@ public enum EventPriority {
this.order = order; this.order = order;
} }
public int getOrder() {
return order;
}
public static EventPriority getByOrder(int order) { public static EventPriority getByOrder(int order) {
for (EventPriority each : EventPriority.values()) { for (EventPriority each : EventPriority.values()) {
if (each.getOrder() == order) { if (each.getOrder() == order) {
@ -34,4 +30,8 @@ public enum EventPriority {
} }
return array; return array;
} }
public int getOrder() {
return order;
}
} }

View File

@ -1,14 +1,14 @@
package com.loohp.limbo.events; package com.loohp.limbo.events;
import com.loohp.limbo.plugins.LimboPlugin;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.loohp.limbo.plugins.LimboPlugin;
public class EventsManager { public class EventsManager {
private List<ListenerPair> listeners; private final List<ListenerPair> listeners;
public EventsManager() { public EventsManager() {
listeners = new ArrayList<>(); listeners = new ArrayList<>();

View File

@ -32,14 +32,14 @@ public class PlayerChatEvent extends PlayerEvent implements Cancellable {
this.message = message; this.message = message;
} }
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return cancelled; return cancelled;
} }
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
} }

View File

@ -5,7 +5,7 @@ import com.loohp.limbo.player.Player;
public class PlayerEvent extends Event { public class PlayerEvent extends Event {
private Player player; private final Player player;
public PlayerEvent(Player player) { public PlayerEvent(Player player) {
this.player = player; this.player = player;

View File

@ -3,12 +3,11 @@ package com.loohp.limbo.events.player;
import com.loohp.limbo.events.Cancellable; import com.loohp.limbo.events.Cancellable;
import com.loohp.limbo.events.Event; import com.loohp.limbo.events.Event;
import com.loohp.limbo.server.ClientConnection; import com.loohp.limbo.server.ClientConnection;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
public class PlayerLoginEvent extends Event implements Cancellable { public class PlayerLoginEvent extends Event implements Cancellable {
private ClientConnection connection; private final ClientConnection connection;
private boolean cancelled; private boolean cancelled;
private BaseComponent[] cancelReason; private BaseComponent[] cancelReason;
@ -30,14 +29,14 @@ public class PlayerLoginEvent extends Event implements Cancellable {
this.cancelReason = cancelReason; this.cancelReason = cancelReason;
} }
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return cancelled; return cancelled;
} }
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
} }

View File

@ -14,13 +14,13 @@ public class PlayerSelectedSlotChangeEvent extends PlayerEvent implements Cancel
} }
@Override @Override
public void setCancelled(boolean cancelled) { public boolean isCancelled() {
this.cancel = cancelled; return cancel;
} }
@Override @Override
public boolean isCancelled() { public void setCancelled(boolean cancelled) {
return cancel; this.cancel = cancelled;
} }
public byte getSlot() { public byte getSlot() {

View File

@ -1,15 +1,14 @@
package com.loohp.limbo.events.status; package com.loohp.limbo.events.status;
import java.awt.image.BufferedImage;
import com.loohp.limbo.events.Event; import com.loohp.limbo.events.Event;
import com.loohp.limbo.server.ClientConnection; import com.loohp.limbo.server.ClientConnection;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
import java.awt.image.BufferedImage;
public class StatusPingEvent extends Event { public class StatusPingEvent extends Event {
private ClientConnection connection; private final ClientConnection connection;
private String version; private String version;
private int protocol; private int protocol;
private BaseComponent[] motd; private BaseComponent[] motd;

View File

@ -1,25 +1,14 @@
package com.loohp.limbo.file; package com.loohp.limbo.file;
import java.io.ByteArrayOutputStream; import com.loohp.limbo.utils.YamlOrder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.representer.Representer;
import com.loohp.limbo.utils.YamlOrder; import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
public class FileConfiguration { public class FileConfiguration {
@ -92,7 +81,7 @@ public class FileConfiguration {
map = map1; map = map1;
} }
if (value != null) { if (value != null) {
map.put(tree[tree.length - 1], (T) value); map.put(tree[tree.length - 1], value);
} else { } else {
map.remove(tree[tree.length - 1]); map.remove(tree[tree.length - 1]);
} }

View File

@ -1,50 +1,41 @@
package com.loohp.limbo.file; package com.loohp.limbo.file;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Properties;
import javax.imageio.ImageIO;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.location.Location; import com.loohp.limbo.location.Location;
import com.loohp.limbo.utils.GameMode; import com.loohp.limbo.utils.GameMode;
import com.loohp.limbo.utils.NamespacedKey; import com.loohp.limbo.utils.NamespacedKey;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Properties;
public class ServerProperties { public class ServerProperties {
public static final String COMMENT = "For explaination of what each of the options does, please visit:\nhttps://github.com/LOOHP/Limbo/blob/master/src/main/resources/server.properties"; public static final String COMMENT = "For explaination of what each of the options does, please visit:\nhttps://github.com/LOOHP/Limbo/blob/master/src/main/resources/server.properties";
private File file;
private int maxPlayers;
private int serverPort;
private String serverIp;
private NamespacedKey levelName;
private String schemFileName;
private NamespacedKey levelDimension;
private GameMode defaultGamemode;
private Location worldSpawn;
private boolean reducedDebugInfo;
private boolean allowFlight;
private String motdJson;
private String versionString;
private int protocol;
private boolean bungeecord;
private int viewDistance;
private double ticksPerSecond;
private boolean handshakeVerbose;
Optional<BufferedImage> favicon; Optional<BufferedImage> favicon;
private final File file;
private final int maxPlayers;
private final int serverPort;
private final String serverIp;
private final NamespacedKey levelName;
private final String schemFileName;
private final NamespacedKey levelDimension;
private final GameMode defaultGamemode;
private Location worldSpawn;
private final boolean reducedDebugInfo;
private final boolean allowFlight;
private final String motdJson;
private final String versionString;
private final int protocol;
private final boolean bungeecord;
private final int viewDistance;
private final double ticksPerSecond;
private final boolean handshakeVerbose;
public ServerProperties(File file) throws IOException { public ServerProperties(File file) throws IOException {
this.file = file; this.file = file;

View File

@ -7,6 +7,6 @@ public enum EquipmentSlot {
HELMENT, HELMENT,
CHESTPLATE, CHESTPLATE,
LEGGINGS, LEGGINGS,
BOOTS; BOOTS
} }

View File

@ -27,6 +27,52 @@ public class Location implements Cloneable {
this(world, x, y, z, 0, 0); this(world, x, y, z, 0, 0);
} }
/**
* Safely converts a double (location coordinate) to an int (block
* coordinate)
*
* @param loc Precise coordinate
* @return Block coordinate
*/
public static int locToBlock(double loc) {
return NumberConversions.floor(loc);
}
/**
* Normalizes the given yaw angle to a value between <code>+/-180</code>
* degrees.
*
* @param yaw the yaw in degrees
* @return the normalized yaw in degrees
* @see Location#getYaw()
*/
public static float normalizeYaw(float yaw) {
yaw %= 360.0f;
if (yaw >= 180.0f) {
yaw -= 360.0f;
} else if (yaw < -180.0f) {
yaw += 360.0f;
}
return yaw;
}
/**
* Normalizes the given pitch angle to a value between <code>+/-90</code>
* degrees.
*
* @param pitch the pitch in degrees
* @return the normalized pitch in degrees
* @see Location#getPitch()
*/
public static float normalizePitch(float pitch) {
if (pitch > 90.0f) {
pitch = 90.0f;
} else if (pitch < -90.0f) {
pitch = -90.0f;
}
return pitch;
}
@Override @Override
public Location clone() { public Location clone() {
try { try {
@ -158,10 +204,10 @@ public class Location implements Cloneable {
/** /**
* Adds the location by another. * Adds the location by another.
* *
* @see Vector
* @param vec The other location * @param vec The other location
* @return the same location * @return the same location
* @throws IllegalArgumentException for differing worlds * @throws IllegalArgumentException for differing worlds
* @see Vector
*/ */
public Location add(Location vec) { public Location add(Location vec) {
if (vec == null || vec.getWorld() != getWorld()) { if (vec == null || vec.getWorld() != getWorld()) {
@ -177,9 +223,9 @@ public class Location implements Cloneable {
/** /**
* Adds the location by a vector. * Adds the location by a vector.
* *
* @see Vector
* @param vec Vector to use * @param vec Vector to use
* @return the same location * @return the same location
* @see Vector
*/ */
public Location add(Vector vec) { public Location add(Vector vec) {
this.x += vec.getX(); this.x += vec.getX();
@ -191,11 +237,11 @@ public class Location implements Cloneable {
/** /**
* Adds the location by another. Not world-aware. * Adds the location by another. Not world-aware.
* *
* @see Vector
* @param x X coordinate * @param x X coordinate
* @param y Y coordinate * @param y Y coordinate
* @param z Z coordinate * @param z Z coordinate
* @return the same location * @return the same location
* @see Vector
*/ */
public Location add(double x, double y, double z) { public Location add(double x, double y, double z) {
this.x += x; this.x += x;
@ -207,10 +253,10 @@ public class Location implements Cloneable {
/** /**
* Subtracts the location by another. * Subtracts the location by another.
* *
* @see Vector
* @param vec The other location * @param vec The other location
* @return the same location * @return the same location
* @throws IllegalArgumentException for differing worlds * @throws IllegalArgumentException for differing worlds
* @see Vector
*/ */
public Location subtract(Location vec) { public Location subtract(Location vec) {
if (vec == null || vec.getWorld() != getWorld()) { if (vec == null || vec.getWorld() != getWorld()) {
@ -226,9 +272,9 @@ public class Location implements Cloneable {
/** /**
* Subtracts the location by a vector. * Subtracts the location by a vector.
* *
* @see Vector
* @param vec The vector to use * @param vec The vector to use
* @return the same location * @return the same location
* @see Vector
*/ */
public Location subtract(Vector vec) { public Location subtract(Vector vec) {
this.x -= vec.getX(); this.x -= vec.getX();
@ -241,11 +287,11 @@ public class Location implements Cloneable {
* Subtracts the location by another. Not world-aware and * Subtracts the location by another. Not world-aware and
* orientation independent. * orientation independent.
* *
* @see Vector
* @param x X coordinate * @param x X coordinate
* @param y Y coordinate * @param y Y coordinate
* @param z Z coordinate * @param z Z coordinate
* @return the same location * @return the same location
* @see Vector
*/ */
public Location subtract(double x, double y, double z) { public Location subtract(double x, double y, double z) {
this.x -= x; this.x -= x;
@ -367,52 +413,6 @@ public class Location implements Cloneable {
NumberConversions.checkFinite(yaw, "yaw not finite"); NumberConversions.checkFinite(yaw, "yaw not finite");
} }
/**
* Safely converts a double (location coordinate) to an int (block
* coordinate)
*
* @param loc Precise coordinate
* @return Block coordinate
*/
public static int locToBlock(double loc) {
return NumberConversions.floor(loc);
}
/**
* Normalizes the given yaw angle to a value between <code>+/-180</code>
* degrees.
*
* @param yaw the yaw in degrees
* @return the normalized yaw in degrees
* @see Location#getYaw()
*/
public static float normalizeYaw(float yaw) {
yaw %= 360.0f;
if (yaw >= 180.0f) {
yaw -= 360.0f;
} else if (yaw < -180.0f) {
yaw += 360.0f;
}
return yaw;
}
/**
* Normalizes the given pitch angle to a value between <code>+/-90</code>
* degrees.
*
* @param pitch the pitch in degrees
* @return the normalized pitch in degrees
* @see Location#getPitch()
*/
public static float normalizePitch(float pitch) {
if (pitch > 90.0f) {
pitch = 90.0f;
} else if (pitch < -90.0f) {
pitch = -90.0f;
}
return pitch;
}
@Override @Override
public String toString() { public String toString() {
return "Location{" + "world=" + world + ",x=" + x + ",y=" + y + ",z=" + z + ",pitch=" + pitch + ",yaw=" + yaw + "}"; return "Location{" + "world=" + world + ",x=" + x + ",y=" + y + ",z=" + z + ",pitch=" + pitch + ",yaw=" + yaw + "}";
@ -445,10 +445,7 @@ public class Location implements Cloneable {
if (Float.floatToIntBits(this.pitch) != Float.floatToIntBits(other.pitch)) { if (Float.floatToIntBits(this.pitch) != Float.floatToIntBits(other.pitch)) {
return false; return false;
} }
if (Float.floatToIntBits(this.yaw) != Float.floatToIntBits(other.yaw)) { return Float.floatToIntBits(this.yaw) == Float.floatToIntBits(other.yaw);
return false;
}
return true;
} }
@Override @Override

View File

@ -1,12 +1,12 @@
package com.loohp.limbo.location; package com.loohp.limbo.location;
import java.util.Random;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.google.common.primitives.Doubles; import com.google.common.primitives.Doubles;
import com.loohp.limbo.utils.NumberConversions; import com.loohp.limbo.utils.NumberConversions;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import java.util.Random;
/** /**
* Represents a mutable vector. Because the components of Vectors are mutable, * Represents a mutable vector. Because the components of Vectors are mutable,
* storing Vectors long term may be dangerous if passing code modifies the * storing Vectors long term may be dangerous if passing code modifies the
@ -15,13 +15,11 @@ import com.loohp.limbo.world.World;
*/ */
public class Vector implements Cloneable { public class Vector implements Cloneable {
private static Random random = new Random();
/** /**
* Threshold for fuzzy equals(). * Threshold for fuzzy equals().
*/ */
private static final double epsilon = 0.000001; private static final double epsilon = 0.000001;
private static final Random random = new Random();
protected double x; protected double x;
protected double y; protected double y;
protected double z; protected double z;
@ -74,6 +72,47 @@ public class Vector implements Cloneable {
this.z = z; this.z = z;
} }
/**
* Get the threshold used for equals().
*
* @return The epsilon.
*/
public static double getEpsilon() {
return epsilon;
}
/**
* Gets the minimum components of two vectors.
*
* @param v1 The first vector.
* @param v2 The second vector.
* @return minimum
*/
public static Vector getMinimum(Vector v1, Vector v2) {
return new Vector(Math.min(v1.x, v2.x), Math.min(v1.y, v2.y), Math.min(v1.z, v2.z));
}
/**
* Gets the maximum components of two vectors.
*
* @param v1 The first vector.
* @param v2 The second vector.
* @return maximum
*/
public static Vector getMaximum(Vector v1, Vector v2) {
return new Vector(Math.max(v1.x, v2.x), Math.max(v1.y, v2.y), Math.max(v1.z, v2.z));
}
/**
* Gets a random vector with components having a random value between 0
* and 1.
*
* @return A random vector.
*/
public static Vector getRandom() {
return new Vector(random.nextDouble(), random.nextDouble(), random.nextDouble());
}
/** /**
* Adds a vector to this one * Adds a vector to this one
* *
@ -533,54 +572,6 @@ public class Vector implements Cloneable {
return x; return x;
} }
/**
* Gets the floored value of the X component, indicating the block that
* this vector is contained with.
*
* @return block X
*/
public int getBlockX() {
return NumberConversions.floor(x);
}
/**
* Gets the Y component.
*
* @return The Y component.
*/
public double getY() {
return y;
}
/**
* Gets the floored value of the Y component, indicating the block that
* this vector is contained with.
*
* @return block y
*/
public int getBlockY() {
return NumberConversions.floor(y);
}
/**
* Gets the Z component.
*
* @return The Z component.
*/
public double getZ() {
return z;
}
/**
* Gets the floored value of the Z component, indicating the block that
* this vector is contained with.
*
* @return block z
*/
public int getBlockZ() {
return NumberConversions.floor(z);
}
/** /**
* Set the X component. * Set the X component.
* *
@ -614,6 +605,25 @@ public class Vector implements Cloneable {
return this; return this;
} }
/**
* Gets the floored value of the X component, indicating the block that
* this vector is contained with.
*
* @return block X
*/
public int getBlockX() {
return NumberConversions.floor(x);
}
/**
* Gets the Y component.
*
* @return The Y component.
*/
public double getY() {
return y;
}
/** /**
* Set the Y component. * Set the Y component.
* *
@ -647,6 +657,25 @@ public class Vector implements Cloneable {
return this; return this;
} }
/**
* Gets the floored value of the Y component, indicating the block that
* this vector is contained with.
*
* @return block y
*/
public int getBlockY() {
return NumberConversions.floor(y);
}
/**
* Gets the Z component.
*
* @return The Z component.
*/
public double getZ() {
return z;
}
/** /**
* Set the Z component. * Set the Z component.
* *
@ -680,6 +709,16 @@ public class Vector implements Cloneable {
return this; return this;
} }
/**
* Gets the floored value of the Z component, indicating the block that
* this vector is contained with.
*
* @return block z
*/
public int getBlockZ() {
return NumberConversions.floor(z);
}
/** /**
* Checks to see if two objects are equal. * Checks to see if two objects are equal.
* <p> * <p>
@ -713,6 +752,15 @@ public class Vector implements Cloneable {
return hash; return hash;
} }
/**
* Get the block vector of this vector.
*
* @return A block vector.
public BlockVector toBlockVector() {
return new BlockVector(x, y, z);
}
*/
/** /**
* Get a new vector. * Get a new vector.
* *
@ -757,15 +805,6 @@ public class Vector implements Cloneable {
return new Location(world, x, y, z, yaw, pitch); return new Location(world, x, y, z, yaw, pitch);
} }
/**
* Get the block vector of this vector.
*
* @return A block vector.
public BlockVector toBlockVector() {
return new BlockVector(x, y, z);
}
*/
/** /**
* Check if each component of this Vector is finite. * Check if each component of this Vector is finite.
* *
@ -777,47 +816,6 @@ public class Vector implements Cloneable {
NumberConversions.checkFinite(z, "z not finite"); NumberConversions.checkFinite(z, "z not finite");
} }
/**
* Get the threshold used for equals().
*
* @return The epsilon.
*/
public static double getEpsilon() {
return epsilon;
}
/**
* Gets the minimum components of two vectors.
*
* @param v1 The first vector.
* @param v2 The second vector.
* @return minimum
*/
public static Vector getMinimum(Vector v1, Vector v2) {
return new Vector(Math.min(v1.x, v2.x), Math.min(v1.y, v2.y), Math.min(v1.z, v2.z));
}
/**
* Gets the maximum components of two vectors.
*
* @param v1 The first vector.
* @param v2 The second vector.
* @return maximum
*/
public static Vector getMaximum(Vector v1, Vector v2) {
return new Vector(Math.max(v1.x, v2.x), Math.max(v1.y, v2.y), Math.max(v1.z, v2.z));
}
/**
* Gets a random vector with components having a random value between 0
* and 1.
*
* @return A random vector.
*/
public static Vector getRandom() {
return new Vector(random.nextDouble(), random.nextDouble(), random.nextDouble());
}
/* /*
@Override @Override
public Map<String, Object> serialize() { public Map<String, Object> serialize() {

View File

@ -1,32 +1,24 @@
package com.loohp.limbo.metrics; package com.loohp.limbo.metrics;
import com.loohp.limbo.Limbo;
import com.loohp.limbo.file.FileConfiguration;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.*;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
import javax.net.ssl.HttpsURLConnection;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.loohp.limbo.Limbo;
import com.loohp.limbo.file.FileConfiguration;
/** /**
* bStats collects some data for plugin authors. * bStats collects some data for plugin authors.
* * <p>
* Check out https://bStats.org/ to learn more about bStats! * Check out https://bStats.org/ to learn more about bStats!
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -123,6 +115,58 @@ public class Metrics {
})); }));
} }
/**
* Sends the data to the bStats server.
*
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes(StandardCharsets.UTF_8));
gzip.close();
return outputStream.toByteArray();
}
/** /**
* Adds a custom chart. * Adds a custom chart.
* *
@ -221,55 +265,318 @@ public class Metrics {
} }
/** /**
* Sends the data to the bStats server. * A enum which is used for custom maps.
*
* @param data The data to send.
* @throws Exception If the request failed.
*/ */
private static void sendData(JSONObject data) throws Exception { public enum Country {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth /**
byte[] compressedData = compress(data.toString()); * bStats will use the country of the server.
*/
AUTO_DETECT("AUTO", "Auto Detected"),
// Add headers ANDORRA("AD", "Andorra"),
connection.setRequestMethod("POST"); UNITED_ARAB_EMIRATES("AE", "United Arab Emirates"),
connection.addRequestProperty("Accept", "application/json"); AFGHANISTAN("AF", "Afghanistan"),
connection.addRequestProperty("Connection", "close"); ANTIGUA_AND_BARBUDA("AG", "Antigua and Barbuda"),
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request ANGUILLA("AI", "Anguilla"),
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); ALBANIA("AL", "Albania"),
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format ARMENIA("AM", "Armenia"),
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); NETHERLANDS_ANTILLES("AN", "Netherlands Antilles"),
ANGOLA("AO", "Angola"),
ANTARCTICA("AQ", "Antarctica"),
ARGENTINA("AR", "Argentina"),
AMERICAN_SAMOA("AS", "American Samoa"),
AUSTRIA("AT", "Austria"),
AUSTRALIA("AU", "Australia"),
ARUBA("AW", "Aruba"),
ALAND_ISLANDS("AX", "<EFBFBD>land Islands"),
AZERBAIJAN("AZ", "Azerbaijan"),
BOSNIA_AND_HERZEGOVINA("BA", "Bosnia and Herzegovina"),
BARBADOS("BB", "Barbados"),
BANGLADESH("BD", "Bangladesh"),
BELGIUM("BE", "Belgium"),
BURKINA_FASO("BF", "Burkina Faso"),
BULGARIA("BG", "Bulgaria"),
BAHRAIN("BH", "Bahrain"),
BURUNDI("BI", "Burundi"),
BENIN("BJ", "Benin"),
SAINT_BARTHELEMY("BL", "Saint Barth<74>lemy"),
BERMUDA("BM", "Bermuda"),
BRUNEI("BN", "Brunei"),
BOLIVIA("BO", "Bolivia"),
BONAIRE_SINT_EUSTATIUS_AND_SABA("BQ", "Bonaire, Sint Eustatius and Saba"),
BRAZIL("BR", "Brazil"),
BAHAMAS("BS", "Bahamas"),
BHUTAN("BT", "Bhutan"),
BOUVET_ISLAND("BV", "Bouvet Island"),
BOTSWANA("BW", "Botswana"),
BELARUS("BY", "Belarus"),
BELIZE("BZ", "Belize"),
CANADA("CA", "Canada"),
COCOS_ISLANDS("CC", "Cocos Islands"),
THE_DEMOCRATIC_REPUBLIC_OF_CONGO("CD", "The Democratic Republic Of Congo"),
CENTRAL_AFRICAN_REPUBLIC("CF", "Central African Republic"),
CONGO("CG", "Congo"),
SWITZERLAND("CH", "Switzerland"),
COTE_D_IVOIRE("CI", "C<EFBFBD>te d'Ivoire"),
COOK_ISLANDS("CK", "Cook Islands"),
CHILE("CL", "Chile"),
CAMEROON("CM", "Cameroon"),
CHINA("CN", "China"),
COLOMBIA("CO", "Colombia"),
COSTA_RICA("CR", "Costa Rica"),
CUBA("CU", "Cuba"),
CAPE_VERDE("CV", "Cape Verde"),
CURACAO("CW", "Cura<EFBFBD>ao"),
CHRISTMAS_ISLAND("CX", "Christmas Island"),
CYPRUS("CY", "Cyprus"),
CZECH_REPUBLIC("CZ", "Czech Republic"),
GERMANY("DE", "Germany"),
DJIBOUTI("DJ", "Djibouti"),
DENMARK("DK", "Denmark"),
DOMINICA("DM", "Dominica"),
DOMINICAN_REPUBLIC("DO", "Dominican Republic"),
ALGERIA("DZ", "Algeria"),
ECUADOR("EC", "Ecuador"),
ESTONIA("EE", "Estonia"),
EGYPT("EG", "Egypt"),
WESTERN_SAHARA("EH", "Western Sahara"),
ERITREA("ER", "Eritrea"),
SPAIN("ES", "Spain"),
ETHIOPIA("ET", "Ethiopia"),
FINLAND("FI", "Finland"),
FIJI("FJ", "Fiji"),
FALKLAND_ISLANDS("FK", "Falkland Islands"),
MICRONESIA("FM", "Micronesia"),
FAROE_ISLANDS("FO", "Faroe Islands"),
FRANCE("FR", "France"),
GABON("GA", "Gabon"),
UNITED_KINGDOM("GB", "United Kingdom"),
GRENADA("GD", "Grenada"),
GEORGIA("GE", "Georgia"),
FRENCH_GUIANA("GF", "French Guiana"),
GUERNSEY("GG", "Guernsey"),
GHANA("GH", "Ghana"),
GIBRALTAR("GI", "Gibraltar"),
GREENLAND("GL", "Greenland"),
GAMBIA("GM", "Gambia"),
GUINEA("GN", "Guinea"),
GUADELOUPE("GP", "Guadeloupe"),
EQUATORIAL_GUINEA("GQ", "Equatorial Guinea"),
GREECE("GR", "Greece"),
SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS("GS", "South Georgia And The South Sandwich Islands"),
GUATEMALA("GT", "Guatemala"),
GUAM("GU", "Guam"),
GUINEA_BISSAU("GW", "Guinea-Bissau"),
GUYANA("GY", "Guyana"),
HONG_KONG("HK", "Hong Kong"),
HEARD_ISLAND_AND_MCDONALD_ISLANDS("HM", "Heard Island And McDonald Islands"),
HONDURAS("HN", "Honduras"),
CROATIA("HR", "Croatia"),
HAITI("HT", "Haiti"),
HUNGARY("HU", "Hungary"),
INDONESIA("ID", "Indonesia"),
IRELAND("IE", "Ireland"),
ISRAEL("IL", "Israel"),
ISLE_OF_MAN("IM", "Isle Of Man"),
INDIA("IN", "India"),
BRITISH_INDIAN_OCEAN_TERRITORY("IO", "British Indian Ocean Territory"),
IRAQ("IQ", "Iraq"),
IRAN("IR", "Iran"),
ICELAND("IS", "Iceland"),
ITALY("IT", "Italy"),
JERSEY("JE", "Jersey"),
JAMAICA("JM", "Jamaica"),
JORDAN("JO", "Jordan"),
JAPAN("JP", "Japan"),
KENYA("KE", "Kenya"),
KYRGYZSTAN("KG", "Kyrgyzstan"),
CAMBODIA("KH", "Cambodia"),
KIRIBATI("KI", "Kiribati"),
COMOROS("KM", "Comoros"),
SAINT_KITTS_AND_NEVIS("KN", "Saint Kitts And Nevis"),
NORTH_KOREA("KP", "North Korea"),
SOUTH_KOREA("KR", "South Korea"),
KUWAIT("KW", "Kuwait"),
CAYMAN_ISLANDS("KY", "Cayman Islands"),
KAZAKHSTAN("KZ", "Kazakhstan"),
LAOS("LA", "Laos"),
LEBANON("LB", "Lebanon"),
SAINT_LUCIA("LC", "Saint Lucia"),
LIECHTENSTEIN("LI", "Liechtenstein"),
SRI_LANKA("LK", "Sri Lanka"),
LIBERIA("LR", "Liberia"),
LESOTHO("LS", "Lesotho"),
LITHUANIA("LT", "Lithuania"),
LUXEMBOURG("LU", "Luxembourg"),
LATVIA("LV", "Latvia"),
LIBYA("LY", "Libya"),
MOROCCO("MA", "Morocco"),
MONACO("MC", "Monaco"),
MOLDOVA("MD", "Moldova"),
MONTENEGRO("ME", "Montenegro"),
SAINT_MARTIN("MF", "Saint Martin"),
MADAGASCAR("MG", "Madagascar"),
MARSHALL_ISLANDS("MH", "Marshall Islands"),
MACEDONIA("MK", "Macedonia"),
MALI("ML", "Mali"),
MYANMAR("MM", "Myanmar"),
MONGOLIA("MN", "Mongolia"),
MACAO("MO", "Macao"),
NORTHERN_MARIANA_ISLANDS("MP", "Northern Mariana Islands"),
MARTINIQUE("MQ", "Martinique"),
MAURITANIA("MR", "Mauritania"),
MONTSERRAT("MS", "Montserrat"),
MALTA("MT", "Malta"),
MAURITIUS("MU", "Mauritius"),
MALDIVES("MV", "Maldives"),
MALAWI("MW", "Malawi"),
MEXICO("MX", "Mexico"),
MALAYSIA("MY", "Malaysia"),
MOZAMBIQUE("MZ", "Mozambique"),
NAMIBIA("NA", "Namibia"),
NEW_CALEDONIA("NC", "New Caledonia"),
NIGER("NE", "Niger"),
NORFOLK_ISLAND("NF", "Norfolk Island"),
NIGERIA("NG", "Nigeria"),
NICARAGUA("NI", "Nicaragua"),
NETHERLANDS("NL", "Netherlands"),
NORWAY("NO", "Norway"),
NEPAL("NP", "Nepal"),
NAURU("NR", "Nauru"),
NIUE("NU", "Niue"),
NEW_ZEALAND("NZ", "New Zealand"),
OMAN("OM", "Oman"),
PANAMA("PA", "Panama"),
PERU("PE", "Peru"),
FRENCH_POLYNESIA("PF", "French Polynesia"),
PAPUA_NEW_GUINEA("PG", "Papua New Guinea"),
PHILIPPINES("PH", "Philippines"),
PAKISTAN("PK", "Pakistan"),
POLAND("PL", "Poland"),
SAINT_PIERRE_AND_MIQUELON("PM", "Saint Pierre And Miquelon"),
PITCAIRN("PN", "Pitcairn"),
PUERTO_RICO("PR", "Puerto Rico"),
PALESTINE("PS", "Palestine"),
PORTUGAL("PT", "Portugal"),
PALAU("PW", "Palau"),
PARAGUAY("PY", "Paraguay"),
QATAR("QA", "Qatar"),
REUNION("RE", "Reunion"),
ROMANIA("RO", "Romania"),
SERBIA("RS", "Serbia"),
RUSSIA("RU", "Russia"),
RWANDA("RW", "Rwanda"),
SAUDI_ARABIA("SA", "Saudi Arabia"),
SOLOMON_ISLANDS("SB", "Solomon Islands"),
SEYCHELLES("SC", "Seychelles"),
SUDAN("SD", "Sudan"),
SWEDEN("SE", "Sweden"),
SINGAPORE("SG", "Singapore"),
SAINT_HELENA("SH", "Saint Helena"),
SLOVENIA("SI", "Slovenia"),
SVALBARD_AND_JAN_MAYEN("SJ", "Svalbard And Jan Mayen"),
SLOVAKIA("SK", "Slovakia"),
SIERRA_LEONE("SL", "Sierra Leone"),
SAN_MARINO("SM", "San Marino"),
SENEGAL("SN", "Senegal"),
SOMALIA("SO", "Somalia"),
SURINAME("SR", "Suriname"),
SOUTH_SUDAN("SS", "South Sudan"),
SAO_TOME_AND_PRINCIPE("ST", "Sao Tome And Principe"),
EL_SALVADOR("SV", "El Salvador"),
SINT_MAARTEN_DUTCH_PART("SX", "Sint Maarten (Dutch part)"),
SYRIA("SY", "Syria"),
SWAZILAND("SZ", "Swaziland"),
TURKS_AND_CAICOS_ISLANDS("TC", "Turks And Caicos Islands"),
CHAD("TD", "Chad"),
FRENCH_SOUTHERN_TERRITORIES("TF", "French Southern Territories"),
TOGO("TG", "Togo"),
THAILAND("TH", "Thailand"),
TAJIKISTAN("TJ", "Tajikistan"),
TOKELAU("TK", "Tokelau"),
TIMOR_LESTE("TL", "Timor-Leste"),
TURKMENISTAN("TM", "Turkmenistan"),
TUNISIA("TN", "Tunisia"),
TONGA("TO", "Tonga"),
TURKEY("TR", "Turkey"),
TRINIDAD_AND_TOBAGO("TT", "Trinidad and Tobago"),
TUVALU("TV", "Tuvalu"),
TAIWAN("TW", "Taiwan"),
TANZANIA("TZ", "Tanzania"),
UKRAINE("UA", "Ukraine"),
UGANDA("UG", "Uganda"),
UNITED_STATES_MINOR_OUTLYING_ISLANDS("UM", "United States Minor Outlying Islands"),
UNITED_STATES("US", "United States"),
URUGUAY("UY", "Uruguay"),
UZBEKISTAN("UZ", "Uzbekistan"),
VATICAN("VA", "Vatican"),
SAINT_VINCENT_AND_THE_GRENADINES("VC", "Saint Vincent And The Grenadines"),
VENEZUELA("VE", "Venezuela"),
BRITISH_VIRGIN_ISLANDS("VG", "British Virgin Islands"),
U_S__VIRGIN_ISLANDS("VI", "U.S. Virgin Islands"),
VIETNAM("VN", "Vietnam"),
VANUATU("VU", "Vanuatu"),
WALLIS_AND_FUTUNA("WF", "Wallis And Futuna"),
SAMOA("WS", "Samoa"),
YEMEN("YE", "Yemen"),
MAYOTTE("YT", "Mayotte"),
SOUTH_AFRICA("ZA", "South Africa"),
ZAMBIA("ZM", "Zambia"),
ZIMBABWE("ZW", "Zimbabwe");
// Send data private final String isoTag;
connection.setDoOutput(true); private final String name;
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
connection.getInputStream().close(); // We don't care about the response - Just send our data :) Country(String isoTag, String name) {
this.isoTag = isoTag;
this.name = name;
} }
/** /**
* Gzips the given String. * Gets a country by it's iso tag.
* *
* @param str The string to gzip. * @param isoTag The iso tag of the county.
* @return The gzipped String. * @return The country with the given iso tag or <code>null</code> if unknown.
* @throws IOException If the compression failed.
*/ */
private static byte[] compress(final String str) throws IOException { public static Country byIsoTag(String isoTag) {
if (str == null) { for (Country country : Country.values()) {
if (country.getCountryIsoTag().equals(isoTag)) {
return country;
}
}
return null; return null;
} }
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream); /**
gzip.write(str.getBytes("UTF-8")); * Gets a country by a locale.
gzip.close(); *
return outputStream.toByteArray(); * @param locale The locale.
* @return The country from the giben locale or <code>null</code> if unknown country or
* if the locale does not contain a country.
*/
public static Country byLocale(Locale locale) {
return byIsoTag(locale.getCountry());
}
/**
* Gets the name of the country.
*
* @return The name of the country.
*/
public String getCountryName() {
return name;
}
/**
* Gets the iso tag of the country.
*
* @return The iso tag of the country.
*/
public String getCountryIsoTag() {
return isoTag;
}
} }
/** /**
@ -689,319 +996,4 @@ public class Metrics {
} }
/**
* A enum which is used for custom maps.
*/
public enum Country {
/**
* bStats will use the country of the server.
*/
AUTO_DETECT("AUTO", "Auto Detected"),
ANDORRA("AD", "Andorra"),
UNITED_ARAB_EMIRATES("AE", "United Arab Emirates"),
AFGHANISTAN("AF", "Afghanistan"),
ANTIGUA_AND_BARBUDA("AG", "Antigua and Barbuda"),
ANGUILLA("AI", "Anguilla"),
ALBANIA("AL", "Albania"),
ARMENIA("AM", "Armenia"),
NETHERLANDS_ANTILLES("AN", "Netherlands Antilles"),
ANGOLA("AO", "Angola"),
ANTARCTICA("AQ", "Antarctica"),
ARGENTINA("AR", "Argentina"),
AMERICAN_SAMOA("AS", "American Samoa"),
AUSTRIA("AT", "Austria"),
AUSTRALIA("AU", "Australia"),
ARUBA("AW", "Aruba"),
ALAND_ISLANDS("AX", "Åland Islands"),
AZERBAIJAN("AZ", "Azerbaijan"),
BOSNIA_AND_HERZEGOVINA("BA", "Bosnia and Herzegovina"),
BARBADOS("BB", "Barbados"),
BANGLADESH("BD", "Bangladesh"),
BELGIUM("BE", "Belgium"),
BURKINA_FASO("BF", "Burkina Faso"),
BULGARIA("BG", "Bulgaria"),
BAHRAIN("BH", "Bahrain"),
BURUNDI("BI", "Burundi"),
BENIN("BJ", "Benin"),
SAINT_BARTHELEMY("BL", "Saint Barthélemy"),
BERMUDA("BM", "Bermuda"),
BRUNEI("BN", "Brunei"),
BOLIVIA("BO", "Bolivia"),
BONAIRE_SINT_EUSTATIUS_AND_SABA("BQ", "Bonaire, Sint Eustatius and Saba"),
BRAZIL("BR", "Brazil"),
BAHAMAS("BS", "Bahamas"),
BHUTAN("BT", "Bhutan"),
BOUVET_ISLAND("BV", "Bouvet Island"),
BOTSWANA("BW", "Botswana"),
BELARUS("BY", "Belarus"),
BELIZE("BZ", "Belize"),
CANADA("CA", "Canada"),
COCOS_ISLANDS("CC", "Cocos Islands"),
THE_DEMOCRATIC_REPUBLIC_OF_CONGO("CD", "The Democratic Republic Of Congo"),
CENTRAL_AFRICAN_REPUBLIC("CF", "Central African Republic"),
CONGO("CG", "Congo"),
SWITZERLAND("CH", "Switzerland"),
COTE_D_IVOIRE("CI", "Côte d'Ivoire"),
COOK_ISLANDS("CK", "Cook Islands"),
CHILE("CL", "Chile"),
CAMEROON("CM", "Cameroon"),
CHINA("CN", "China"),
COLOMBIA("CO", "Colombia"),
COSTA_RICA("CR", "Costa Rica"),
CUBA("CU", "Cuba"),
CAPE_VERDE("CV", "Cape Verde"),
CURACAO("CW", "Curaçao"),
CHRISTMAS_ISLAND("CX", "Christmas Island"),
CYPRUS("CY", "Cyprus"),
CZECH_REPUBLIC("CZ", "Czech Republic"),
GERMANY("DE", "Germany"),
DJIBOUTI("DJ", "Djibouti"),
DENMARK("DK", "Denmark"),
DOMINICA("DM", "Dominica"),
DOMINICAN_REPUBLIC("DO", "Dominican Republic"),
ALGERIA("DZ", "Algeria"),
ECUADOR("EC", "Ecuador"),
ESTONIA("EE", "Estonia"),
EGYPT("EG", "Egypt"),
WESTERN_SAHARA("EH", "Western Sahara"),
ERITREA("ER", "Eritrea"),
SPAIN("ES", "Spain"),
ETHIOPIA("ET", "Ethiopia"),
FINLAND("FI", "Finland"),
FIJI("FJ", "Fiji"),
FALKLAND_ISLANDS("FK", "Falkland Islands"),
MICRONESIA("FM", "Micronesia"),
FAROE_ISLANDS("FO", "Faroe Islands"),
FRANCE("FR", "France"),
GABON("GA", "Gabon"),
UNITED_KINGDOM("GB", "United Kingdom"),
GRENADA("GD", "Grenada"),
GEORGIA("GE", "Georgia"),
FRENCH_GUIANA("GF", "French Guiana"),
GUERNSEY("GG", "Guernsey"),
GHANA("GH", "Ghana"),
GIBRALTAR("GI", "Gibraltar"),
GREENLAND("GL", "Greenland"),
GAMBIA("GM", "Gambia"),
GUINEA("GN", "Guinea"),
GUADELOUPE("GP", "Guadeloupe"),
EQUATORIAL_GUINEA("GQ", "Equatorial Guinea"),
GREECE("GR", "Greece"),
SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS("GS", "South Georgia And The South Sandwich Islands"),
GUATEMALA("GT", "Guatemala"),
GUAM("GU", "Guam"),
GUINEA_BISSAU("GW", "Guinea-Bissau"),
GUYANA("GY", "Guyana"),
HONG_KONG("HK", "Hong Kong"),
HEARD_ISLAND_AND_MCDONALD_ISLANDS("HM", "Heard Island And McDonald Islands"),
HONDURAS("HN", "Honduras"),
CROATIA("HR", "Croatia"),
HAITI("HT", "Haiti"),
HUNGARY("HU", "Hungary"),
INDONESIA("ID", "Indonesia"),
IRELAND("IE", "Ireland"),
ISRAEL("IL", "Israel"),
ISLE_OF_MAN("IM", "Isle Of Man"),
INDIA("IN", "India"),
BRITISH_INDIAN_OCEAN_TERRITORY("IO", "British Indian Ocean Territory"),
IRAQ("IQ", "Iraq"),
IRAN("IR", "Iran"),
ICELAND("IS", "Iceland"),
ITALY("IT", "Italy"),
JERSEY("JE", "Jersey"),
JAMAICA("JM", "Jamaica"),
JORDAN("JO", "Jordan"),
JAPAN("JP", "Japan"),
KENYA("KE", "Kenya"),
KYRGYZSTAN("KG", "Kyrgyzstan"),
CAMBODIA("KH", "Cambodia"),
KIRIBATI("KI", "Kiribati"),
COMOROS("KM", "Comoros"),
SAINT_KITTS_AND_NEVIS("KN", "Saint Kitts And Nevis"),
NORTH_KOREA("KP", "North Korea"),
SOUTH_KOREA("KR", "South Korea"),
KUWAIT("KW", "Kuwait"),
CAYMAN_ISLANDS("KY", "Cayman Islands"),
KAZAKHSTAN("KZ", "Kazakhstan"),
LAOS("LA", "Laos"),
LEBANON("LB", "Lebanon"),
SAINT_LUCIA("LC", "Saint Lucia"),
LIECHTENSTEIN("LI", "Liechtenstein"),
SRI_LANKA("LK", "Sri Lanka"),
LIBERIA("LR", "Liberia"),
LESOTHO("LS", "Lesotho"),
LITHUANIA("LT", "Lithuania"),
LUXEMBOURG("LU", "Luxembourg"),
LATVIA("LV", "Latvia"),
LIBYA("LY", "Libya"),
MOROCCO("MA", "Morocco"),
MONACO("MC", "Monaco"),
MOLDOVA("MD", "Moldova"),
MONTENEGRO("ME", "Montenegro"),
SAINT_MARTIN("MF", "Saint Martin"),
MADAGASCAR("MG", "Madagascar"),
MARSHALL_ISLANDS("MH", "Marshall Islands"),
MACEDONIA("MK", "Macedonia"),
MALI("ML", "Mali"),
MYANMAR("MM", "Myanmar"),
MONGOLIA("MN", "Mongolia"),
MACAO("MO", "Macao"),
NORTHERN_MARIANA_ISLANDS("MP", "Northern Mariana Islands"),
MARTINIQUE("MQ", "Martinique"),
MAURITANIA("MR", "Mauritania"),
MONTSERRAT("MS", "Montserrat"),
MALTA("MT", "Malta"),
MAURITIUS("MU", "Mauritius"),
MALDIVES("MV", "Maldives"),
MALAWI("MW", "Malawi"),
MEXICO("MX", "Mexico"),
MALAYSIA("MY", "Malaysia"),
MOZAMBIQUE("MZ", "Mozambique"),
NAMIBIA("NA", "Namibia"),
NEW_CALEDONIA("NC", "New Caledonia"),
NIGER("NE", "Niger"),
NORFOLK_ISLAND("NF", "Norfolk Island"),
NIGERIA("NG", "Nigeria"),
NICARAGUA("NI", "Nicaragua"),
NETHERLANDS("NL", "Netherlands"),
NORWAY("NO", "Norway"),
NEPAL("NP", "Nepal"),
NAURU("NR", "Nauru"),
NIUE("NU", "Niue"),
NEW_ZEALAND("NZ", "New Zealand"),
OMAN("OM", "Oman"),
PANAMA("PA", "Panama"),
PERU("PE", "Peru"),
FRENCH_POLYNESIA("PF", "French Polynesia"),
PAPUA_NEW_GUINEA("PG", "Papua New Guinea"),
PHILIPPINES("PH", "Philippines"),
PAKISTAN("PK", "Pakistan"),
POLAND("PL", "Poland"),
SAINT_PIERRE_AND_MIQUELON("PM", "Saint Pierre And Miquelon"),
PITCAIRN("PN", "Pitcairn"),
PUERTO_RICO("PR", "Puerto Rico"),
PALESTINE("PS", "Palestine"),
PORTUGAL("PT", "Portugal"),
PALAU("PW", "Palau"),
PARAGUAY("PY", "Paraguay"),
QATAR("QA", "Qatar"),
REUNION("RE", "Reunion"),
ROMANIA("RO", "Romania"),
SERBIA("RS", "Serbia"),
RUSSIA("RU", "Russia"),
RWANDA("RW", "Rwanda"),
SAUDI_ARABIA("SA", "Saudi Arabia"),
SOLOMON_ISLANDS("SB", "Solomon Islands"),
SEYCHELLES("SC", "Seychelles"),
SUDAN("SD", "Sudan"),
SWEDEN("SE", "Sweden"),
SINGAPORE("SG", "Singapore"),
SAINT_HELENA("SH", "Saint Helena"),
SLOVENIA("SI", "Slovenia"),
SVALBARD_AND_JAN_MAYEN("SJ", "Svalbard And Jan Mayen"),
SLOVAKIA("SK", "Slovakia"),
SIERRA_LEONE("SL", "Sierra Leone"),
SAN_MARINO("SM", "San Marino"),
SENEGAL("SN", "Senegal"),
SOMALIA("SO", "Somalia"),
SURINAME("SR", "Suriname"),
SOUTH_SUDAN("SS", "South Sudan"),
SAO_TOME_AND_PRINCIPE("ST", "Sao Tome And Principe"),
EL_SALVADOR("SV", "El Salvador"),
SINT_MAARTEN_DUTCH_PART("SX", "Sint Maarten (Dutch part)"),
SYRIA("SY", "Syria"),
SWAZILAND("SZ", "Swaziland"),
TURKS_AND_CAICOS_ISLANDS("TC", "Turks And Caicos Islands"),
CHAD("TD", "Chad"),
FRENCH_SOUTHERN_TERRITORIES("TF", "French Southern Territories"),
TOGO("TG", "Togo"),
THAILAND("TH", "Thailand"),
TAJIKISTAN("TJ", "Tajikistan"),
TOKELAU("TK", "Tokelau"),
TIMOR_LESTE("TL", "Timor-Leste"),
TURKMENISTAN("TM", "Turkmenistan"),
TUNISIA("TN", "Tunisia"),
TONGA("TO", "Tonga"),
TURKEY("TR", "Turkey"),
TRINIDAD_AND_TOBAGO("TT", "Trinidad and Tobago"),
TUVALU("TV", "Tuvalu"),
TAIWAN("TW", "Taiwan"),
TANZANIA("TZ", "Tanzania"),
UKRAINE("UA", "Ukraine"),
UGANDA("UG", "Uganda"),
UNITED_STATES_MINOR_OUTLYING_ISLANDS("UM", "United States Minor Outlying Islands"),
UNITED_STATES("US", "United States"),
URUGUAY("UY", "Uruguay"),
UZBEKISTAN("UZ", "Uzbekistan"),
VATICAN("VA", "Vatican"),
SAINT_VINCENT_AND_THE_GRENADINES("VC", "Saint Vincent And The Grenadines"),
VENEZUELA("VE", "Venezuela"),
BRITISH_VIRGIN_ISLANDS("VG", "British Virgin Islands"),
U_S__VIRGIN_ISLANDS("VI", "U.S. Virgin Islands"),
VIETNAM("VN", "Vietnam"),
VANUATU("VU", "Vanuatu"),
WALLIS_AND_FUTUNA("WF", "Wallis And Futuna"),
SAMOA("WS", "Samoa"),
YEMEN("YE", "Yemen"),
MAYOTTE("YT", "Mayotte"),
SOUTH_AFRICA("ZA", "South Africa"),
ZAMBIA("ZM", "Zambia"),
ZIMBABWE("ZW", "Zimbabwe");
private String isoTag;
private String name;
Country(String isoTag, String name) {
this.isoTag = isoTag;
this.name = name;
}
/**
* Gets the name of the country.
*
* @return The name of the country.
*/
public String getCountryName() {
return name;
}
/**
* Gets the iso tag of the country.
*
* @return The iso tag of the country.
*/
public String getCountryIsoTag() {
return isoTag;
}
/**
* Gets a country by it's iso tag.
*
* @param isoTag The iso tag of the county.
* @return The country with the given iso tag or <code>null</code> if unknown.
*/
public static Country byIsoTag(String isoTag) {
for (Country country : Country.values()) {
if (country.getCountryIsoTag().equals(isoTag)) {
return country;
}
}
return null;
}
/**
* Gets a country by a locale.
*
* @param locale The locale.
* @return The country from the giben locale or <code>null</code> if unknown country or
* if the locale does not contain a country.
*/
public static Country byLocale(Locale locale) {
return byIsoTag(locale.getCountry());
}
}
} }

View File

@ -1,5 +1,10 @@
package com.loohp.limbo.permissions; package com.loohp.limbo.permissions;
import com.loohp.limbo.Console;
import com.loohp.limbo.commands.CommandSender;
import com.loohp.limbo.file.FileConfiguration;
import com.loohp.limbo.player.Player;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@ -7,15 +12,10 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.loohp.limbo.Console;
import com.loohp.limbo.commands.CommandSender;
import com.loohp.limbo.file.FileConfiguration;
import com.loohp.limbo.player.Player;
public class PermissionsManager { public class PermissionsManager {
private Map<String, List<String>> users; private final Map<String, List<String>> users;
private Map<String, List<String>> permissions; private final Map<String, List<String>> permissions;
public PermissionsManager() { public PermissionsManager() {
users = new HashMap<>(); users = new HashMap<>();
@ -33,7 +33,8 @@ public class PermissionsManager {
nodes.addAll(config.get("groups." + key, List.class)); nodes.addAll(config.get("groups." + key, List.class));
permissions.put(key, nodes); permissions.put(key, nodes);
} }
} catch (Exception e) {} } catch (Exception e) {
}
try { try {
for (Object obj : config.get("players", Map.class).keySet()) { for (Object obj : config.get("players", Map.class).keySet()) {
String key = (String) obj; String key = (String) obj;
@ -41,7 +42,8 @@ public class PermissionsManager {
groups.addAll(config.get("players." + key, List.class)); groups.addAll(config.get("players." + key, List.class));
users.put(key, groups); users.put(key, groups);
} }
} catch (Exception e) {} } catch (Exception e) {
}
} }
public boolean hasPermission(CommandSender sender, String permission) { public boolean hasPermission(CommandSender sender, String permission) {

View File

@ -1,30 +1,25 @@
package com.loohp.limbo.player; package com.loohp.limbo.player;
import java.io.IOException;
import java.util.UUID;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.events.player.PlayerChatEvent;
import com.loohp.limbo.events.player.PlayerTeleportEvent;
import com.loohp.limbo.server.ClientConnection;
import com.loohp.limbo.server.packets.PacketPlayOutChat;
import com.loohp.limbo.server.packets.PacketPlayOutGameState;
import com.loohp.limbo.server.packets.PacketPlayOutHeldItemChange;
import com.loohp.limbo.server.packets.PacketPlayOutPositionAndLook;
import com.loohp.limbo.server.packets.PacketPlayOutRespawn;
import com.loohp.limbo.commands.CommandSender; import com.loohp.limbo.commands.CommandSender;
import com.loohp.limbo.entity.DataWatcher; import com.loohp.limbo.entity.DataWatcher;
import com.loohp.limbo.entity.EntityType;
import com.loohp.limbo.entity.LivingEntity;
import com.loohp.limbo.entity.DataWatcher.WatchableField; import com.loohp.limbo.entity.DataWatcher.WatchableField;
import com.loohp.limbo.entity.DataWatcher.WatchableObjectType; import com.loohp.limbo.entity.DataWatcher.WatchableObjectType;
import com.loohp.limbo.entity.EntityType;
import com.loohp.limbo.entity.LivingEntity;
import com.loohp.limbo.events.player.PlayerChatEvent;
import com.loohp.limbo.events.player.PlayerTeleportEvent;
import com.loohp.limbo.location.Location; import com.loohp.limbo.location.Location;
import com.loohp.limbo.server.ClientConnection;
import com.loohp.limbo.server.packets.*;
import com.loohp.limbo.utils.GameMode; import com.loohp.limbo.utils.GameMode;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer; import net.md_5.bungee.chat.ComponentSerializer;
import java.io.IOException;
import java.util.UUID;
public class Player extends LivingEntity implements CommandSender { public class Player extends LivingEntity implements CommandSender {
public final ClientConnection clientConnection; public final ClientConnection clientConnection;
@ -248,7 +243,7 @@ public class Player extends LivingEntity implements CommandSender {
public void chat(String message) { public void chat(String message) {
String prefix = "<" + username + "> "; String prefix = "<" + username + "> ";
PlayerChatEvent event = (PlayerChatEvent) Limbo.getInstance().getEventsManager().callEvent(new PlayerChatEvent(this, prefix, message, false)); PlayerChatEvent event = Limbo.getInstance().getEventsManager().callEvent(new PlayerChatEvent(this, prefix, message, false));
if (!event.isCancelled()) { if (!event.isCancelled()) {
String chat = event.getPrefix() + event.getMessage(); String chat = event.getPrefix() + event.getMessage();
Limbo.getInstance().getConsole().sendMessage(chat); Limbo.getInstance().getConsole().sendMessage(chat);

View File

@ -1,29 +1,17 @@
package com.loohp.limbo.player; package com.loohp.limbo.player;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.server.packets.PacketPlayOutEntityDestroy;
import com.loohp.limbo.server.packets.PacketPlayOutEntityMetadata;
import com.loohp.limbo.server.packets.PacketPlayOutLightUpdate;
import com.loohp.limbo.server.packets.PacketPlayOutMapChunk;
import com.loohp.limbo.server.packets.PacketPlayOutSpawnEntity;
import com.loohp.limbo.server.packets.PacketPlayOutSpawnEntityLiving;
import com.loohp.limbo.server.packets.PacketPlayOutUnloadChunk;
import com.loohp.limbo.entity.Entity; import com.loohp.limbo.entity.Entity;
import com.loohp.limbo.location.Location; import com.loohp.limbo.location.Location;
import com.loohp.limbo.server.packets.*;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import net.querz.mca.Chunk; import net.querz.mca.Chunk;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class PlayerInteractManager { public class PlayerInteractManager {
private Player player; private Player player;
@ -37,6 +25,10 @@ public class PlayerInteractManager {
this.chunks = new HashMap<>(); this.chunks = new HashMap<>();
} }
public Player getPlayer() {
return player;
}
protected void setPlayer(Player player) { protected void setPlayer(Player player) {
if (this.player == null) { if (this.player == null) {
this.player = player; this.player = player;
@ -45,10 +37,6 @@ public class PlayerInteractManager {
} }
} }
public Player getPlayer() {
return player;
}
public void update() throws IOException { public void update() throws IOException {
int viewDistanceChunks = Limbo.getInstance().getServerProperties().getViewDistance(); int viewDistanceChunks = Limbo.getInstance().getServerProperties().getViewDistance();
int viewDistanceBlocks = viewDistanceChunks << 4; int viewDistanceBlocks = viewDistanceChunks << 4;

View File

@ -6,7 +6,8 @@ import com.loohp.limbo.utils.GameMode;
@Deprecated @Deprecated
public class Unsafe { public class Unsafe {
private Unsafe() {} private Unsafe() {
}
@Deprecated @Deprecated
public void a(Player a, GameMode b) { public void a(Player a, GameMode b) {

View File

@ -1,10 +1,10 @@
package com.loohp.limbo.plugins; package com.loohp.limbo.plugins;
import java.io.File;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.file.FileConfiguration; import com.loohp.limbo.file.FileConfiguration;
import java.io.File;
public class LimboPlugin { public class LimboPlugin {
private String name; private String name;

View File

@ -4,11 +4,11 @@ import com.loohp.limbo.file.FileConfiguration;
public class PluginInfo { public class PluginInfo {
private String name; private final String name;
private String description; private final String description;
private String author; private final String author;
private String version; private final String version;
private String main; private final String main;
public PluginInfo(FileConfiguration file) { public PluginInfo(FileConfiguration file) {
name = file.get("name", String.class); name = file.get("name", String.class);

View File

@ -1,28 +1,24 @@
package com.loohp.limbo.plugins; package com.loohp.limbo.plugins;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.commands.CommandExecutor; import com.loohp.limbo.commands.CommandExecutor;
import com.loohp.limbo.commands.CommandSender; import com.loohp.limbo.commands.CommandSender;
import com.loohp.limbo.commands.TabCompletor; import com.loohp.limbo.commands.TabCompletor;
import com.loohp.limbo.file.FileConfiguration; import com.loohp.limbo.file.FileConfiguration;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class PluginManager { public class PluginManager {
private Map<String, LimboPlugin> plugins; private final Map<String, LimboPlugin> plugins;
private List<Executor> executors; private final List<Executor> executors;
private File pluginFolder; private final File pluginFolder;
public PluginManager(File pluginFolder) { public PluginManager(File pluginFolder) {
this.pluginFolder = pluginFolder; this.pluginFolder = pluginFolder;

View File

@ -5,8 +5,8 @@ import com.loohp.limbo.plugins.LimboPlugin;
public abstract class LimboRunnable implements LimboTask { public abstract class LimboRunnable implements LimboTask {
private volatile boolean registered = false;
protected volatile int taskId = -1; protected volatile int taskId = -1;
private volatile boolean registered = false;
public void cancel() { public void cancel() {
synchronized (this) { synchronized (this) {

View File

@ -1,23 +1,17 @@
package com.loohp.limbo.scheduler; package com.loohp.limbo.scheduler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.plugins.LimboPlugin; import com.loohp.limbo.plugins.LimboPlugin;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class LimboScheduler { public class LimboScheduler {
private AtomicInteger idProvider = new AtomicInteger(0); private final AtomicInteger idProvider = new AtomicInteger(0);
private Map<Long, List<LimboSchedulerTask>> registeredTasks = new HashMap<>(); private final Map<Long, List<LimboSchedulerTask>> registeredTasks = new HashMap<>();
private Map<Integer, LimboSchedulerTask> tasksById = new HashMap<>(); private final Map<Integer, LimboSchedulerTask> tasksById = new HashMap<>();
private Set<Integer> cancelledTasks = new HashSet<>(); private final Set<Integer> cancelledTasks = new HashSet<>();
public LimboScheduler() { public LimboScheduler() {
@ -180,10 +174,19 @@ public class LimboScheduler {
return new CurrentSchedulerTask(syncedTasks, asyncTasks); return new CurrentSchedulerTask(syncedTasks, asyncTasks);
} }
public enum LimboSchedulerTaskType {
SYNC,
ASYNC,
TIMER_SYNC,
TIMER_ASYNC
}
public static class CurrentSchedulerTask { public static class CurrentSchedulerTask {
private List<LimboSchedulerTask> asyncTasks; private final List<LimboSchedulerTask> asyncTasks;
private List<LimboSchedulerTask> syncedTasks; private final List<LimboSchedulerTask> syncedTasks;
public CurrentSchedulerTask(List<LimboSchedulerTask> syncedTasks, List<LimboSchedulerTask> asyncTasks) { public CurrentSchedulerTask(List<LimboSchedulerTask> syncedTasks, List<LimboSchedulerTask> asyncTasks) {
this.asyncTasks = asyncTasks; this.asyncTasks = asyncTasks;
@ -202,11 +205,11 @@ public class LimboScheduler {
public static class LimboSchedulerTask { public static class LimboSchedulerTask {
private int taskId; private final int taskId;
private LimboPlugin plugin; private final LimboPlugin plugin;
private LimboTask task; private final LimboTask task;
private LimboSchedulerTaskType type; private final LimboSchedulerTaskType type;
private long period; private final long period;
private LimboSchedulerTask(LimboPlugin plugin, LimboTask task, int taskId, LimboSchedulerTaskType type, long period) { private LimboSchedulerTask(LimboPlugin plugin, LimboTask task, int taskId, LimboSchedulerTaskType type, long period) {
this.plugin = plugin; this.plugin = plugin;
@ -238,13 +241,4 @@ public class LimboScheduler {
} }
public static enum LimboSchedulerTaskType {
SYNC,
ASYNC,
TIMER_SYNC,
TIMER_ASYNC;
}
} }

View File

@ -1,5 +1,9 @@
package com.loohp.limbo.scheduler; package com.loohp.limbo.scheduler;
import com.loohp.limbo.Limbo;
import com.loohp.limbo.scheduler.LimboScheduler.CurrentSchedulerTask;
import com.loohp.limbo.scheduler.LimboScheduler.LimboSchedulerTask;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -8,17 +12,13 @@ import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import com.loohp.limbo.Limbo;
import com.loohp.limbo.scheduler.LimboScheduler.CurrentSchedulerTask;
import com.loohp.limbo.scheduler.LimboScheduler.LimboSchedulerTask;
public class Tick { public class Tick {
private int tickingInterval; private int tickingInterval;
private AtomicLong tick = new AtomicLong(0); private final AtomicLong tick = new AtomicLong(0);
private List<Thread> threads = new ArrayList<>(); private final List<Thread> threads = new ArrayList<>();
private Queue<LimboSchedulerTask> asyncTasksQueue = new ConcurrentLinkedQueue<>(); private final Queue<LimboSchedulerTask> asyncTasksQueue = new ConcurrentLinkedQueue<>();
public Tick(Limbo instance) { public Tick(Limbo instance) {
new Thread(new Runnable() { new Thread(new Runnable() {

View File

@ -1,103 +1,48 @@
package com.loohp.limbo.server; package com.loohp.limbo.server;
import com.loohp.limbo.Limbo;
import com.loohp.limbo.events.player.*;
import com.loohp.limbo.events.status.StatusPingEvent;
import com.loohp.limbo.file.ServerProperties;
import com.loohp.limbo.location.Location;
import com.loohp.limbo.player.Player;
import com.loohp.limbo.player.PlayerInteractManager;
import com.loohp.limbo.server.packets.*;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerAbilities.PlayerAbilityFlags;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoAction;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoData;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoData.PlayerInfoDataAddPlayer.PlayerSkinProperty;
import com.loohp.limbo.server.packets.PacketPlayOutTabComplete.TabCompleteMatches;
import com.loohp.limbo.utils.*;
import com.loohp.limbo.utils.MojangAPIUtils.SkinResponse;
import com.loohp.limbo.world.BlockPosition;
import com.loohp.limbo.world.World;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.Socket; import java.net.Socket;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.*;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.loohp.limbo.Limbo;
import com.loohp.limbo.events.player.PlayerJoinEvent;
import com.loohp.limbo.events.player.PlayerLoginEvent;
import com.loohp.limbo.events.player.PlayerMoveEvent;
import com.loohp.limbo.events.player.PlayerQuitEvent;
import com.loohp.limbo.events.player.PlayerSelectedSlotChangeEvent;
import com.loohp.limbo.events.status.StatusPingEvent;
import com.loohp.limbo.server.packets.Packet;
import com.loohp.limbo.server.packets.PacketHandshakingIn;
import com.loohp.limbo.server.packets.PacketLoginInLoginStart;
import com.loohp.limbo.server.packets.PacketLoginOutDisconnect;
import com.loohp.limbo.server.packets.PacketLoginOutLoginSuccess;
import com.loohp.limbo.server.packets.PacketOut;
import com.loohp.limbo.server.packets.PacketPlayInChat;
import com.loohp.limbo.server.packets.PacketPlayInHeldItemChange;
import com.loohp.limbo.server.packets.PacketPlayInKeepAlive;
import com.loohp.limbo.server.packets.PacketPlayInPosition;
import com.loohp.limbo.server.packets.PacketPlayInPositionAndLook;
import com.loohp.limbo.server.packets.PacketPlayInRotation;
import com.loohp.limbo.server.packets.PacketPlayInTabComplete;
import com.loohp.limbo.server.packets.PacketPlayOutDeclareCommands;
import com.loohp.limbo.server.packets.PacketPlayOutDisconnect;
import com.loohp.limbo.server.packets.PacketPlayOutEntityMetadata;
import com.loohp.limbo.server.packets.PacketPlayOutHeldItemChange;
import com.loohp.limbo.server.packets.PacketPlayOutLogin;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerAbilities;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo;
import com.loohp.limbo.server.packets.PacketPlayOutPositionAndLook;
import com.loohp.limbo.server.packets.PacketPlayOutSpawnPosition;
import com.loohp.limbo.server.packets.PacketPlayOutTabComplete;
import com.loohp.limbo.server.packets.PacketPlayOutUpdateViewPosition;
import com.loohp.limbo.server.packets.PacketStatusInPing;
import com.loohp.limbo.server.packets.PacketStatusInRequest;
import com.loohp.limbo.server.packets.PacketStatusOutPong;
import com.loohp.limbo.server.packets.PacketStatusOutResponse;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerAbilities.PlayerAbilityFlags;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoAction;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoData;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoData.PlayerInfoDataAddPlayer.PlayerSkinProperty;
import com.loohp.limbo.server.packets.PacketPlayOutTabComplete.TabCompleteMatches;
import com.loohp.limbo.file.ServerProperties;
import com.loohp.limbo.location.Location;
import com.loohp.limbo.player.Player;
import com.loohp.limbo.player.PlayerInteractManager;
import com.loohp.limbo.utils.CustomStringUtils;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.DeclareCommands;
import com.loohp.limbo.utils.GameMode;
import com.loohp.limbo.utils.MojangAPIUtils;
import com.loohp.limbo.utils.NamespacedKey;
import com.loohp.limbo.utils.MojangAPIUtils.SkinResponse;
import com.loohp.limbo.world.BlockPosition;
import com.loohp.limbo.world.World;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;
public class ClientConnection extends Thread { public class ClientConnection extends Thread {
public static enum ClientState {
LEGACY,
HANDSHAKE,
STATUS,
LOGIN,
PLAY,
DISCONNECTED;
}
private final Socket client_socket; private final Socket client_socket;
private boolean running; private boolean running;
private ClientState state; private ClientState state;
private Player player; private Player player;
private AtomicLong lastKeepAlivePayLoad; private final AtomicLong lastKeepAlivePayLoad;
private DataOutputStream output; private DataOutputStream output;
private DataInputStream input; private DataInputStream input;
private InetAddress inetAddress; private InetAddress inetAddress;
private boolean ready; private boolean ready;
public ClientConnection(Socket client_socket) { public ClientConnection(Socket client_socket) {
@ -151,20 +96,24 @@ public class ClientConnection extends Thread {
try { try {
PacketPlayOutDisconnect packet = new PacketPlayOutDisconnect(ComponentSerializer.toString(reason)); PacketPlayOutDisconnect packet = new PacketPlayOutDisconnect(ComponentSerializer.toString(reason));
sendPacket(packet); sendPacket(packet);
} catch (IOException e) {} } catch (IOException e) {
}
try { try {
client_socket.close(); client_socket.close();
} catch (IOException e) {} } catch (IOException e) {
}
} }
private void disconnectDuringLogin(BaseComponent[] reason) { private void disconnectDuringLogin(BaseComponent[] reason) {
try { try {
PacketLoginOutDisconnect packet = new PacketLoginOutDisconnect(ComponentSerializer.toString(reason)); PacketLoginOutDisconnect packet = new PacketLoginOutDisconnect(ComponentSerializer.toString(reason));
sendPacket(packet); sendPacket(packet);
} catch (IOException e) {} } catch (IOException e) {
}
try { try {
client_socket.close(); client_socket.close();
} catch (IOException e) {} } catch (IOException e) {
}
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@ -451,11 +400,14 @@ public class ClientConnection extends Thread {
} }
} catch (Exception e) {e.printStackTrace();} } catch (Exception e) {
e.printStackTrace();
}
try { try {
client_socket.close(); client_socket.close();
} catch (IOException e) {} } catch (IOException e) {
}
state = ClientState.DISCONNECTED; state = ClientState.DISCONNECTED;
if (player != null) { if (player != null) {
@ -465,6 +417,15 @@ public class ClientConnection extends Thread {
running = false; running = false;
} }
public enum ClientState {
LEGACY,
HANDSHAKE,
STATUS,
LOGIN,
PLAY,
DISCONNECTED
}
@FunctionalInterface @FunctionalInterface
public interface CheckedConsumer<T, TException extends Throwable> { public interface CheckedConsumer<T, TException extends Throwable> {
void consume(T t) throws TException; void consume(T t) throws TException;

View File

@ -1,16 +1,16 @@
package com.loohp.limbo.server; package com.loohp.limbo.server;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import com.loohp.limbo.Limbo; import com.loohp.limbo.Limbo;
import com.loohp.limbo.server.ClientConnection.ClientState; import com.loohp.limbo.server.ClientConnection.ClientState;
import com.loohp.limbo.server.packets.PacketPlayOutKeepAlive; import com.loohp.limbo.server.packets.PacketPlayOutKeepAlive;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class KeepAliveSender extends Thread { public class KeepAliveSender extends Thread {
private Random random; private final Random random;
public KeepAliveSender() { public KeepAliveSender() {
random = new Random(); random = new Random();
@ -27,7 +27,8 @@ public class KeepAliveSender extends Thread {
PacketPlayOutKeepAlive packet = new PacketPlayOutKeepAlive(random.nextLong()); PacketPlayOutKeepAlive packet = new PacketPlayOutKeepAlive(random.nextLong());
client.setLastKeepAlivePayLoad(packet.getPayload()); client.setLastKeepAlivePayLoad(packet.getPayload());
client.sendPacket(packet); client.sendPacket(packet);
} catch (IOException ignore) {} } catch (IOException ignore) {
}
} }
} }
TimeUnit.SECONDS.sleep(5); TimeUnit.SECONDS.sleep(5);

View File

@ -1,5 +1,7 @@
package com.loohp.limbo.server; package com.loohp.limbo.server;
import com.loohp.limbo.Limbo;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.ServerSocket; import java.net.ServerSocket;
@ -7,15 +9,13 @@ import java.net.Socket;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.loohp.limbo.Limbo;
public class ServerConnection extends Thread { public class ServerConnection extends Thread {
private ServerSocket serverSocket; private ServerSocket serverSocket;
private List<ClientConnection> clients; private final List<ClientConnection> clients;
private String ip; private final String ip;
private int port; private final int port;
private KeepAliveSender keepAliveSender; private final KeepAliveSender keepAliveSender;
public ServerConnection(String ip, int port) { public ServerConnection(String ip, int port) {
clients = new ArrayList<ClientConnection>(); clients = new ArrayList<ClientConnection>();

View File

@ -1,44 +1,19 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketHandshakingIn extends PacketIn { public class PacketHandshakingIn extends PacketIn {
public static enum HandshakeType { private final int protocolVersion;
STATUS(1),
LOGIN(2);
int networkId;
HandshakeType(int networkId) {
this.networkId = networkId;
}
public int getNetworkId() {
return networkId;
}
public static HandshakeType fromNetworkId(int networkId) {
for (HandshakeType type : HandshakeType.values()) {
if (type.getNetworkId() == networkId) {
return type;
}
}
return null;
}
}
//============================== //==============================
private final String serverAddress;
private int protocolVersion; private final int serverPort;
private String serverAddress; private final HandshakeType handshakeType;
private int serverPort;
private HandshakeType handshakeType;
public PacketHandshakingIn(int protocolVersion, String serverAddress, int serverPort, HandshakeType handshakeType) { public PacketHandshakingIn(int protocolVersion, String serverAddress, int serverPort, HandshakeType handshakeType) {
this.protocolVersion = protocolVersion; this.protocolVersion = protocolVersion;
this.serverAddress = serverAddress; this.serverAddress = serverAddress;
@ -66,4 +41,28 @@ public class PacketHandshakingIn extends PacketIn {
return handshakeType; return handshakeType;
} }
public enum HandshakeType {
STATUS(1),
LOGIN(2);
int networkId;
HandshakeType(int networkId) {
this.networkId = networkId;
}
public static HandshakeType fromNetworkId(int networkId) {
for (HandshakeType type : HandshakeType.values()) {
if (type.getNetworkId() == networkId) {
return type;
}
}
return null;
}
public int getNetworkId() {
return networkId;
}
}
} }

View File

@ -1,14 +1,14 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketLoginInLoginStart extends PacketIn { public class PacketLoginInLoginStart extends PacketIn {
private String username; private final String username;
public PacketLoginInLoginStart(String username) { public PacketLoginInLoginStart(String username) {
this.username = username; this.username = username;

View File

@ -1,17 +1,17 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.NamespacedKey;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.NamespacedKey;
public class PacketLoginInPluginMessaging extends PacketIn { public class PacketLoginInPluginMessaging extends PacketIn {
private int messageId; private final int messageId;
private NamespacedKey channel; private final NamespacedKey channel;
private byte[] data; private final byte[] data;
public PacketLoginInPluginMessaging(int messageId, NamespacedKey channel, byte[] data) { public PacketLoginInPluginMessaging(int messageId, NamespacedKey channel, byte[] data) {
this.messageId = messageId; this.messageId = messageId;

View File

@ -1,15 +1,15 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketLoginOutDisconnect extends PacketOut { public class PacketLoginOutDisconnect extends PacketOut {
private String jsonReason; private final String jsonReason;
public PacketLoginOutDisconnect(String jsonReason) { public PacketLoginOutDisconnect(String jsonReason) {
this.jsonReason = jsonReason; this.jsonReason = jsonReason;

View File

@ -1,17 +1,17 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.UUID; import java.util.UUID;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketLoginOutLoginSuccess extends PacketOut { public class PacketLoginOutLoginSuccess extends PacketOut {
private UUID uuid; private final UUID uuid;
private String username; private final String username;
public PacketLoginOutLoginSuccess(UUID uuid, String username) { public PacketLoginOutLoginSuccess(UUID uuid, String username) {
this.uuid = uuid; this.uuid = uuid;

View File

@ -1,18 +1,18 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.NamespacedKey;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.NamespacedKey;
public class PacketLoginOutPluginMessaging extends PacketOut { public class PacketLoginOutPluginMessaging extends PacketOut {
private int messageId; private final int messageId;
private NamespacedKey channel; private final NamespacedKey channel;
private byte[] data; private final byte[] data;
public PacketLoginOutPluginMessaging(int messageId, NamespacedKey channel, byte[] data) { public PacketLoginOutPluginMessaging(int messageId, NamespacedKey channel, byte[] data) {
this.messageId = messageId; this.messageId = messageId;

View File

@ -1,14 +1,14 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketPlayInChat extends PacketIn { public class PacketPlayInChat extends PacketIn {
private String message; private final String message;
public PacketPlayInChat(String message) { public PacketPlayInChat(String message) {
this.message = message; this.message = message;

View File

@ -5,7 +5,7 @@ import java.io.IOException;
public class PacketPlayInHeldItemChange extends PacketIn { public class PacketPlayInHeldItemChange extends PacketIn {
private short slot; private final short slot;
public PacketPlayInHeldItemChange(short slot) { public PacketPlayInHeldItemChange(short slot) {
this.slot = slot; this.slot = slot;

View File

@ -5,7 +5,7 @@ import java.io.IOException;
public class PacketPlayInKeepAlive extends PacketIn { public class PacketPlayInKeepAlive extends PacketIn {
private long payload; private final long payload;
public PacketPlayInKeepAlive(long payload) { public PacketPlayInKeepAlive(long payload) {
this.payload = payload; this.payload = payload;

View File

@ -1,16 +1,16 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.NamespacedKey;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.NamespacedKey;
public class PacketPlayInPluginMessaging extends PacketIn { public class PacketPlayInPluginMessaging extends PacketIn {
private NamespacedKey channel; private final NamespacedKey channel;
private byte[] data; private final byte[] data;
public PacketPlayInPluginMessaging(NamespacedKey channel, byte[] data) { public PacketPlayInPluginMessaging(NamespacedKey channel, byte[] data) {
this.channel = channel; this.channel = channel;

View File

@ -5,10 +5,10 @@ import java.io.IOException;
public class PacketPlayInPosition extends PacketIn { public class PacketPlayInPosition extends PacketIn {
private double x; private final double x;
private double y; private final double y;
private double z; private final double z;
private boolean onGround; private final boolean onGround;
public PacketPlayInPosition(double x, double y, double z, boolean onGround) { public PacketPlayInPosition(double x, double y, double z, boolean onGround) {
this.x = x; this.x = x;

View File

@ -5,12 +5,12 @@ import java.io.IOException;
public class PacketPlayInPositionAndLook extends PacketIn { public class PacketPlayInPositionAndLook extends PacketIn {
private double x; private final double x;
private double y; private final double y;
private double z; private final double z;
private float yaw; private final float yaw;
private float pitch; private final float pitch;
private boolean onGround; private final boolean onGround;
public PacketPlayInPositionAndLook(double x, double y, double z, float yaw, float pitch, boolean onGround) { public PacketPlayInPositionAndLook(double x, double y, double z, float yaw, float pitch, boolean onGround) {
this.x = x; this.x = x;

View File

@ -5,9 +5,9 @@ import java.io.IOException;
public class PacketPlayInRotation extends PacketIn { public class PacketPlayInRotation extends PacketIn {
private float yaw; private final float yaw;
private float pitch; private final float pitch;
private boolean onGround; private final boolean onGround;
public PacketPlayInRotation(float yaw, float pitch, boolean onGround) { public PacketPlayInRotation(float yaw, float pitch, boolean onGround) {
this.yaw = yaw; this.yaw = yaw;

View File

@ -1,15 +1,15 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketPlayInTabComplete extends PacketIn { public class PacketPlayInTabComplete extends PacketIn {
private int id; private final int id;
private String text; private final String text;
public PacketPlayInTabComplete(int id, String text) { public PacketPlayInTabComplete(int id, String text) {
this.id = id; this.id = id;

View File

@ -1,18 +1,18 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.UUID; import java.util.UUID;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketPlayOutChat extends PacketOut { public class PacketPlayOutChat extends PacketOut {
private String json; private final String json;
private int position; private final int position;
private UUID sender; private final UUID sender;
public PacketPlayOutChat(String json, int position, UUID sender) { public PacketPlayOutChat(String json, int position, UUID sender) {
this.json = json; this.json = json;

View File

@ -6,7 +6,7 @@ import java.io.IOException;
public class PacketPlayOutDeclareCommands extends PacketOut { public class PacketPlayOutDeclareCommands extends PacketOut {
private byte[] data; private final byte[] data;
public PacketPlayOutDeclareCommands(byte[] data) { public PacketPlayOutDeclareCommands(byte[] data) {
this.data = data; this.data = data;

View File

@ -1,15 +1,15 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketPlayOutDisconnect extends PacketOut { public class PacketPlayOutDisconnect extends PacketOut {
private String jsonReason; private final String jsonReason;
public PacketPlayOutDisconnect(String jsonReason) { public PacketPlayOutDisconnect(String jsonReason) {
this.jsonReason = jsonReason; this.jsonReason = jsonReason;

View File

@ -1,14 +1,14 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketPlayOutEntityDestroy extends PacketOut { public class PacketPlayOutEntityDestroy extends PacketOut {
private int[] entityIds; private final int[] entityIds;
public PacketPlayOutEntityDestroy(int... entityIds) { public PacketPlayOutEntityDestroy(int... entityIds) {
this.entityIds = entityIds; this.entityIds = entityIds;

View File

@ -1,35 +1,28 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.entity.DataWatcher.WatchableObject;
import com.loohp.limbo.entity.DataWatcher.WatchableObjectType;
import com.loohp.limbo.entity.Entity;
import com.loohp.limbo.entity.Pose;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.Rotation3f;
import com.loohp.limbo.world.BlockPosition;
import net.md_5.bungee.chat.ComponentSerializer;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Collection; import java.util.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.UUID;
import com.loohp.limbo.entity.Entity;
import com.loohp.limbo.entity.Pose;
import com.loohp.limbo.entity.DataWatcher.WatchableObject;
import com.loohp.limbo.entity.DataWatcher.WatchableObjectType;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.Rotation3f;
import com.loohp.limbo.world.BlockPosition;
import net.md_5.bungee.chat.ComponentSerializer;
public class PacketPlayOutEntityMetadata extends PacketOut { public class PacketPlayOutEntityMetadata extends PacketOut {
public static final int END_OFF_METADATA = 0xff; public static final int END_OFF_METADATA = 0xff;
private Entity entity;
public boolean allFields; public boolean allFields;
public Field[] fields; public Field[] fields;
private final Entity entity;
public PacketPlayOutEntityMetadata(Entity entity, boolean allFields, Field... fields) { public PacketPlayOutEntityMetadata(Entity entity, boolean allFields, Field... fields) {
this.entity = entity; this.entity = entity;

View File

@ -6,8 +6,8 @@ import java.io.IOException;
public class PacketPlayOutGameState extends PacketOut { public class PacketPlayOutGameState extends PacketOut {
private int reason; private final int reason;
private float value; private final float value;
public PacketPlayOutGameState(int reason, float value) { public PacketPlayOutGameState(int reason, float value) {
this.reason = reason; this.reason = reason;

View File

@ -1,21 +1,21 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketPlayOutLightUpdate extends PacketOut { public class PacketPlayOutLightUpdate extends PacketOut {
private int chunkX; private final int chunkX;
private int chunkZ; private final int chunkZ;
private boolean trustEdges; private final boolean trustEdges;
private int skyLightBitMask; private int skyLightBitMask;
private int blockLightBitMask; private int blockLightBitMask;
private List<Byte[]> skylightArrays; private final List<Byte[]> skylightArrays;
private List<Byte[]> blocklightArrays; private final List<Byte[]> blocklightArrays;
public PacketPlayOutLightUpdate(int chunkX, int chunkZ, boolean trustEdges, List<Byte[]> skylightArrays, List<Byte[]> blocklightArrays) { public PacketPlayOutLightUpdate(int chunkX, int chunkZ, boolean trustEdges, List<Byte[]> skylightArrays, List<Byte[]> blocklightArrays) {
this.chunkX = chunkX; this.chunkX = chunkX;

View File

@ -1,35 +1,34 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO; import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.GameMode; import com.loohp.limbo.utils.GameMode;
import com.loohp.limbo.utils.NamespacedKey; import com.loohp.limbo.utils.NamespacedKey;
import com.loohp.limbo.world.Environment; import com.loohp.limbo.world.Environment;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import net.querz.nbt.tag.CompoundTag; import net.querz.nbt.tag.CompoundTag;
import net.querz.nbt.tag.ListTag; import net.querz.nbt.tag.ListTag;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class PacketPlayOutLogin extends PacketOut { public class PacketPlayOutLogin extends PacketOut {
private int entityId; private final int entityId;
private boolean isHardcore; private final boolean isHardcore;
private GameMode gamemode; private final GameMode gamemode;
private String[] worldsNames; private final String[] worldsNames;
private CompoundTag dimensionCodec; private final CompoundTag dimensionCodec;
private Environment dimension; private final Environment dimension;
private String worldName; private final String worldName;
private long hashedSeed; private final long hashedSeed;
private byte maxPlayers; private final byte maxPlayers;
private int viewDistance; private final int viewDistance;
private boolean reducedDebugInfo; private final boolean reducedDebugInfo;
private boolean enableRespawnScreen; private final boolean enableRespawnScreen;
private boolean isDebug; private final boolean isDebug;
private boolean isFlat; private final boolean isFlat;
public PacketPlayOutLogin(int entityId, boolean isHardcore, GameMode gamemode, public PacketPlayOutLogin(int entityId, boolean isHardcore, GameMode gamemode,
String[] worldsNames, CompoundTag dimensionCodec, World world, long hashedSeed, String[] worldsNames, CompoundTag dimensionCodec, World world, long hashedSeed,

View File

@ -1,30 +1,25 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.loohp.limbo.utils.BitsUtils; import com.loohp.limbo.utils.BitsUtils;
import com.loohp.limbo.utils.DataTypeIO; import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.world.Environment; import com.loohp.limbo.world.Environment;
import com.loohp.limbo.world.GeneratedBlockDataMappings; import com.loohp.limbo.world.GeneratedBlockDataMappings;
import net.querz.mca.Chunk; import net.querz.mca.Chunk;
import net.querz.mca.Section; import net.querz.mca.Section;
import net.querz.nbt.tag.CompoundTag; import net.querz.nbt.tag.CompoundTag;
import net.querz.nbt.tag.ListTag; import net.querz.nbt.tag.ListTag;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.*;
public class PacketPlayOutMapChunk extends PacketOut { public class PacketPlayOutMapChunk extends PacketOut {
private int chunkX; private final int chunkX;
private int chunkZ; private final int chunkZ;
private Chunk chunk; private final Chunk chunk;
private Environment environment; private final Environment environment;
public PacketPlayOutMapChunk(int chunkX, int chunkZ, Chunk chunk, Environment environment) { public PacketPlayOutMapChunk(int chunkX, int chunkZ, Chunk chunk, Environment environment) {
this.chunkX = chunkX; this.chunkX = chunkX;
@ -179,7 +174,7 @@ public class PacketPlayOutMapChunk extends PacketOut {
} }
int id = list.isEmpty() ? 0 : list.remove(0); int id = list.isEmpty() ? 0 : list.remove(0);
currentLong = currentLong << 15; currentLong = currentLong << 15;
currentLong |= (long) id; currentLong |= id;
} }
DataTypeIO.writeVarInt(dataOut, longsNeeded); DataTypeIO.writeVarInt(dataOut, longsNeeded);
for (int j = 0; j < longsNeeded; j++) { for (int j = 0; j < longsNeeded; j++) {

View File

@ -6,27 +6,9 @@ import java.io.IOException;
public class PacketPlayOutPlayerAbilities extends PacketOut { public class PacketPlayOutPlayerAbilities extends PacketOut {
public enum PlayerAbilityFlags { private final PlayerAbilityFlags[] flags;
INVULNERABLE(0x01), private final float flySpeed;
FLY(0x02), private final float fieldOfField;
ALLOW_FLYING(0x04),
CREATIVE(0x08);
int bitvalue;
PlayerAbilityFlags(int bitvalue) {
this.bitvalue = bitvalue;
}
public int getValue() {
return bitvalue;
}
}
private PlayerAbilityFlags[] flags;
private float flySpeed;
private float fieldOfField;
public PacketPlayOutPlayerAbilities(float flySpeed, float fieldOfField, PlayerAbilityFlags... flags) { public PacketPlayOutPlayerAbilities(float flySpeed, float fieldOfField, PlayerAbilityFlags... flags) {
this.flags = flags; this.flags = flags;
this.flySpeed = flySpeed; this.flySpeed = flySpeed;
@ -63,4 +45,21 @@ public class PacketPlayOutPlayerAbilities extends PacketOut {
return buffer.toByteArray(); return buffer.toByteArray();
} }
public enum PlayerAbilityFlags {
INVULNERABLE(0x01),
FLY(0x02),
ALLOW_FLYING(0x04),
CREATIVE(0x08);
int bitvalue;
PlayerAbilityFlags(int bitvalue) {
this.bitvalue = bitvalue;
}
public int getValue() {
return bitvalue;
}
}
} }

View File

@ -1,5 +1,9 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoData.PlayerInfoDataAddPlayer;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.GameMode;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
@ -7,30 +11,11 @@ import java.nio.charset.StandardCharsets;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import com.loohp.limbo.server.packets.PacketPlayOutPlayerInfo.PlayerInfoData.PlayerInfoDataAddPlayer;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.GameMode;
public class PacketPlayOutPlayerInfo extends PacketOut { public class PacketPlayOutPlayerInfo extends PacketOut {
public enum PlayerInfoAction { private final PlayerInfoAction action;
ADD_PLAYER(0), UPDATE_GAMEMODE(1), UPDATE_LATENCY(2), UPDATE_DISPLAY_NAME(3), REMOVE_PLAYER(4); private final UUID uuid;
private final PlayerInfoData data;
int id;
PlayerInfoAction(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
private PlayerInfoAction action;
private UUID uuid;
private PlayerInfoData data;
public PacketPlayOutPlayerInfo(PlayerInfoAction action, UUID uuid, PlayerInfoData data) { public PacketPlayOutPlayerInfo(PlayerInfoAction action, UUID uuid, PlayerInfoData data) {
this.action = action; this.action = action;
this.uuid = uuid; this.uuid = uuid;
@ -94,18 +79,32 @@ public class PacketPlayOutPlayerInfo extends PacketOut {
return buffer.toByteArray(); return buffer.toByteArray();
} }
public enum PlayerInfoAction {
ADD_PLAYER(0), UPDATE_GAMEMODE(1), UPDATE_LATENCY(2), UPDATE_DISPLAY_NAME(3), REMOVE_PLAYER(4);
int id;
PlayerInfoAction(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
// ========= // =========
public static class PlayerInfoData { public static class PlayerInfoData {
public static class PlayerInfoDataAddPlayer extends PlayerInfoData { public static class PlayerInfoDataAddPlayer extends PlayerInfoData {
private String name; private final String name;
private Optional<PlayerSkinProperty> skin; private final Optional<PlayerSkinProperty> skin;
private GameMode gamemode; private final GameMode gamemode;
private int ping; private final int ping;
private boolean hasDisplayName; private final boolean hasDisplayName;
private Optional<String> displayNameJson; private final Optional<String> displayNameJson;
public PlayerInfoDataAddPlayer(String name, Optional<PlayerSkinProperty> skin, GameMode gamemode, int ping, public PlayerInfoDataAddPlayer(String name, Optional<PlayerSkinProperty> skin, GameMode gamemode, int ping,
boolean hasDisplayName, Optional<String> displayNameJson) { boolean hasDisplayName, Optional<String> displayNameJson) {
@ -143,8 +142,8 @@ public class PacketPlayOutPlayerInfo extends PacketOut {
public static class PlayerSkinProperty { public static class PlayerSkinProperty {
private String skin; private final String skin;
private String signature; private final String signature;
public PlayerSkinProperty(String skin, String signature) { public PlayerSkinProperty(String skin, String signature) {
this.skin = skin; this.skin = skin;

View File

@ -1,17 +1,17 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.NamespacedKey;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.NamespacedKey;
public class PacketPlayOutPluginMessaging extends PacketOut { public class PacketPlayOutPluginMessaging extends PacketOut {
private NamespacedKey channel; private final NamespacedKey channel;
private byte[] data; private final byte[] data;
public PacketPlayOutPluginMessaging(NamespacedKey channel, byte[] data) { public PacketPlayOutPluginMessaging(NamespacedKey channel, byte[] data) {
this.channel = channel; this.channel = channel;

View File

@ -1,5 +1,7 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
@ -7,36 +9,15 @@ import java.util.Arrays;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketPlayOutPositionAndLook extends PacketOut { public class PacketPlayOutPositionAndLook extends PacketOut {
public enum PlayerTeleportFlags { private final double x;
X((byte) 0x01), private final double y;
Y((byte) 0x02), private final double z;
Z((byte) 0x04), private final float yaw;
Y_ROT((byte) 0x08), private final float pitch;
X_ROT((byte) 0x10); private final Set<PlayerTeleportFlags> flags;
private final int teleportId;
byte bit;
PlayerTeleportFlags(byte bit) {
this.bit = bit;
}
public byte getBit() {
return bit;
}
}
private double x;
private double y;
private double z;
private float yaw;
private float pitch;
private Set<PlayerTeleportFlags> flags;
private int teleportId;
public PacketPlayOutPositionAndLook(double x, double y, double z, float yaw, float pitch, int teleportId, PlayerTeleportFlags... flags) { public PacketPlayOutPositionAndLook(double x, double y, double z, float yaw, float pitch, int teleportId, PlayerTeleportFlags... flags) {
this.x = x; this.x = x;
this.y = y; this.y = y;
@ -98,4 +79,22 @@ public class PacketPlayOutPositionAndLook extends PacketOut {
return buffer.toByteArray(); return buffer.toByteArray();
} }
public enum PlayerTeleportFlags {
X((byte) 0x01),
Y((byte) 0x02),
Z((byte) 0x04),
Y_ROT((byte) 0x08),
X_ROT((byte) 0x10);
byte bit;
PlayerTeleportFlags(byte bit) {
this.bit = bit;
}
public byte getBit() {
return bit;
}
}
} }

View File

@ -1,29 +1,28 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO; import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.utils.GameMode; import com.loohp.limbo.utils.GameMode;
import com.loohp.limbo.utils.NamespacedKey; import com.loohp.limbo.utils.NamespacedKey;
import com.loohp.limbo.world.Environment; import com.loohp.limbo.world.Environment;
import com.loohp.limbo.world.World; import com.loohp.limbo.world.World;
import net.querz.nbt.tag.CompoundTag; import net.querz.nbt.tag.CompoundTag;
import net.querz.nbt.tag.ListTag; import net.querz.nbt.tag.ListTag;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class PacketPlayOutRespawn extends PacketOut { public class PacketPlayOutRespawn extends PacketOut {
private Environment dimension; private final Environment dimension;
private String worldName; private final String worldName;
private CompoundTag dimensionCodec; private final CompoundTag dimensionCodec;
private long hashedSeed; private final long hashedSeed;
private GameMode gamemode; private final GameMode gamemode;
private boolean isDebug; private final boolean isDebug;
private boolean isFlat; private final boolean isFlat;
private boolean copyMetaData; private final boolean copyMetaData;
public PacketPlayOutRespawn(World world, CompoundTag dimensionCodec, long hashedSeed, GameMode gamemode, boolean isDebug, boolean isFlat, boolean copyMetaData) { public PacketPlayOutRespawn(World world, CompoundTag dimensionCodec, long hashedSeed, GameMode gamemode, boolean isDebug, boolean isFlat, boolean copyMetaData) {
this.dimension = world.getEnvironment(); this.dimension = world.getEnvironment();

View File

@ -1,27 +1,27 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.entity.EntityType;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.UUID; import java.util.UUID;
import com.loohp.limbo.entity.EntityType;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketPlayOutSpawnEntity extends PacketOut { public class PacketPlayOutSpawnEntity extends PacketOut {
private int entityId; private final int entityId;
private UUID uuid; private final UUID uuid;
private EntityType type; private final EntityType type;
private double x; private final double x;
private double y; private final double y;
private double z; private final double z;
private float pitch; private final float pitch;
private float yaw; private final float yaw;
private int data; private final int data;
private short velocityX; private final short velocityX;
private short velocityY; private final short velocityY;
private short velocityZ; private final short velocityZ;
public PacketPlayOutSpawnEntity(int entityId, UUID uuid, EntityType type, double x, double y, double z, float pitch, float yaw, short velocityX, short velocityY, short velocityZ) { public PacketPlayOutSpawnEntity(int entityId, UUID uuid, EntityType type, double x, double y, double z, float pitch, float yaw, short velocityX, short velocityY, short velocityZ) {
this.entityId = entityId; this.entityId = entityId;
@ -101,9 +101,9 @@ public class PacketPlayOutSpawnEntity extends PacketOut {
output.writeByte((byte) (int) (pitch * 256.0F / 360.0F)); output.writeByte((byte) (int) (pitch * 256.0F / 360.0F));
output.writeByte((byte) (int) (yaw * 256.0F / 360.0F)); output.writeByte((byte) (int) (yaw * 256.0F / 360.0F));
output.writeInt(data); output.writeInt(data);
output.writeShort((int) (velocityX * 8000)); output.writeShort(velocityX * 8000);
output.writeShort((int) (velocityY * 8000)); output.writeShort(velocityY * 8000);
output.writeShort((int) (velocityZ * 8000)); output.writeShort(velocityZ * 8000);
return buffer.toByteArray(); return buffer.toByteArray();
} }

View File

@ -1,27 +1,27 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.entity.EntityType;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.UUID; import java.util.UUID;
import com.loohp.limbo.entity.EntityType;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketPlayOutSpawnEntityLiving extends PacketOut { public class PacketPlayOutSpawnEntityLiving extends PacketOut {
private int entityId; private final int entityId;
private UUID uuid; private final UUID uuid;
private EntityType type; private final EntityType type;
private double x; private final double x;
private double y; private final double y;
private double z; private final double z;
private float yaw; private final float yaw;
private float pitch; private final float pitch;
private float headPitch; private final float headPitch;
private short velocityX; private final short velocityX;
private short velocityY; private final short velocityY;
private short velocityZ; private final short velocityZ;
public PacketPlayOutSpawnEntityLiving(int entityId, UUID uuid, EntityType type, double x, double y, double z, float yaw, float pitch, float headPitch, short velocityX, short velocityY, short velocityZ) { public PacketPlayOutSpawnEntityLiving(int entityId, UUID uuid, EntityType type, double x, double y, double z, float yaw, float pitch, float headPitch, short velocityX, short velocityY, short velocityZ) {
this.entityId = entityId; this.entityId = entityId;
@ -101,9 +101,9 @@ public class PacketPlayOutSpawnEntityLiving extends PacketOut {
output.writeByte((byte) (int) (yaw * 256.0F / 360.0F)); output.writeByte((byte) (int) (yaw * 256.0F / 360.0F));
output.writeByte((byte) (int) (pitch * 256.0F / 360.0F)); output.writeByte((byte) (int) (pitch * 256.0F / 360.0F));
output.writeByte((byte) (int) (headPitch * 256.0F / 360.0F)); output.writeByte((byte) (int) (headPitch * 256.0F / 360.0F));
output.writeShort((int) (velocityX * 8000)); output.writeShort(velocityX * 8000);
output.writeShort((int) (velocityY * 8000)); output.writeShort(velocityY * 8000);
output.writeShort((int) (velocityZ * 8000)); output.writeShort(velocityZ * 8000);
return buffer.toByteArray(); return buffer.toByteArray();
} }

View File

@ -1,15 +1,15 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.world.BlockPosition;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import com.loohp.limbo.utils.DataTypeIO;
import com.loohp.limbo.world.BlockPosition;
public class PacketPlayOutSpawnPosition extends PacketOut { public class PacketPlayOutSpawnPosition extends PacketOut {
private BlockPosition position; private final BlockPosition position;
public PacketPlayOutSpawnPosition(BlockPosition position) { public PacketPlayOutSpawnPosition(BlockPosition position) {
this.position = position; this.position = position;

View File

@ -1,22 +1,21 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.chat.ComponentSerializer;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Optional; import java.util.Optional;
import com.loohp.limbo.utils.DataTypeIO;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.chat.ComponentSerializer;
public class PacketPlayOutTabComplete extends PacketOut { public class PacketPlayOutTabComplete extends PacketOut {
private int id; private final int id;
private int start; private final int start;
private int length; private final int length;
private TabCompleteMatches[] matches; private final TabCompleteMatches[] matches;
public PacketPlayOutTabComplete(int id, int start, int length, TabCompleteMatches... matches) { public PacketPlayOutTabComplete(int id, int start, int length, TabCompleteMatches... matches) {
this.id = id; this.id = id;
@ -67,8 +66,8 @@ public class PacketPlayOutTabComplete extends PacketOut {
public static class TabCompleteMatches { public static class TabCompleteMatches {
private String match; private final String match;
private Optional<BaseComponent[]> tooltip; private final Optional<BaseComponent[]> tooltip;
public TabCompleteMatches(String match, BaseComponent... tooltip) { public TabCompleteMatches(String match, BaseComponent... tooltip) {
this.match = match; this.match = match;

View File

@ -6,8 +6,8 @@ import java.io.IOException;
public class PacketPlayOutUnloadChunk extends PacketOut { public class PacketPlayOutUnloadChunk extends PacketOut {
private int chunkX; private final int chunkX;
private int chunkZ; private final int chunkZ;
public PacketPlayOutUnloadChunk(int chunkX, int chunkZ) { public PacketPlayOutUnloadChunk(int chunkX, int chunkZ) {
this.chunkX = chunkX; this.chunkX = chunkX;

View File

@ -1,15 +1,15 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketPlayOutUpdateViewPosition extends PacketOut { public class PacketPlayOutUpdateViewPosition extends PacketOut {
private int chunkX; private final int chunkX;
private int chunkZ; private final int chunkZ;
public PacketPlayOutUpdateViewPosition(int chunkX, int chunkZ) { public PacketPlayOutUpdateViewPosition(int chunkX, int chunkZ) {
this.chunkX = chunkX; this.chunkX = chunkX;

View File

@ -5,7 +5,7 @@ import java.io.IOException;
public class PacketStatusInPing extends PacketIn { public class PacketStatusInPing extends PacketIn {
private long payload; private final long payload;
public PacketStatusInPing(long payload) { public PacketStatusInPing(long payload) {
this.payload = payload; this.payload = payload;

View File

@ -6,7 +6,7 @@ import java.io.IOException;
public class PacketStatusOutPong extends PacketOut { public class PacketStatusOutPong extends PacketOut {
private long payload; private final long payload;
public PacketStatusOutPong(long payload) { public PacketStatusOutPong(long payload) {
this.payload = payload; this.payload = payload;

View File

@ -1,15 +1,15 @@
package com.loohp.limbo.server.packets; package com.loohp.limbo.server.packets;
import com.loohp.limbo.utils.DataTypeIO;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.loohp.limbo.utils.DataTypeIO;
public class PacketStatusOutResponse extends PacketOut { public class PacketStatusOutResponse extends PacketOut {
private String json; private final String json;
public PacketStatusOutResponse(String json) { public PacketStatusOutResponse(String json) {
this.json = json; this.json = json;

View File

@ -1,16 +1,16 @@
package com.loohp.limbo.utils; package com.loohp.limbo.utils;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import com.loohp.limbo.server.packets.PacketPlayOutPluginMessaging;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.UUID; import java.util.UUID;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import com.loohp.limbo.server.packets.PacketPlayOutPluginMessaging;
public class BungeeLoginMessageUtils { public class BungeeLoginMessageUtils {
public static void sendUUIDRequest(DataOutputStream output) throws IOException { public static void sendUUIDRequest(DataOutputStream output) throws IOException {

View File

@ -1,50 +1,12 @@
package com.loohp.limbo.utils; package com.loohp.limbo.utils;
import net.querz.nbt.tag.*;
import org.json.simple.JSONArray; import org.json.simple.JSONArray;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import net.querz.nbt.tag.ByteArrayTag;
import net.querz.nbt.tag.ByteTag;
import net.querz.nbt.tag.CompoundTag;
import net.querz.nbt.tag.DoubleTag;
import net.querz.nbt.tag.FloatTag;
import net.querz.nbt.tag.IntArrayTag;
import net.querz.nbt.tag.IntTag;
import net.querz.nbt.tag.ListTag;
import net.querz.nbt.tag.LongArrayTag;
import net.querz.nbt.tag.LongTag;
import net.querz.nbt.tag.ShortTag;
import net.querz.nbt.tag.StringTag;
import net.querz.nbt.tag.Tag;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class CustomNBTUtils { public class CustomNBTUtils {
public enum TagClass {
CompoundTagClass(CompoundTag.class),
ByteTagClass(ByteTag.class),
ShortTagClass(ShortTag.class),
IntTagClass(IntTag.class),
LongTagClass(LongTag.class),
FloatTagClass(FloatTag.class),
DoubleTagClass(DoubleTag.class),
ByteArrayTagClass(ByteArrayTag.class),
IntArrayTagClass(IntArrayTag.class),
LongArrayTagClass(LongArrayTag.class),
StringTagClass(StringTag.class),
ListTagClass(ListTag.class);
Class<? extends Tag> clazz;
TagClass(Class<? extends Tag> clazz) {
this.clazz = clazz;
}
public Class<? extends Tag> getTagClass() {
return clazz;
}
}
public static Class<? extends Tag> getClassFromName(String name) { public static Class<? extends Tag> getClassFromName(String name) {
for (TagClass clazz : TagClass.values()) { for (TagClass clazz : TagClass.values()) {
if (clazz.getTagClass().getSimpleName().equals(name)) { if (clazz.getTagClass().getSimpleName().equals(name)) {
@ -177,4 +139,29 @@ public class CustomNBTUtils {
return listTag; return listTag;
} }
public enum TagClass {
CompoundTagClass(CompoundTag.class),
ByteTagClass(ByteTag.class),
ShortTagClass(ShortTag.class),
IntTagClass(IntTag.class),
LongTagClass(LongTag.class),
FloatTagClass(FloatTag.class),
DoubleTagClass(DoubleTag.class),
ByteArrayTagClass(ByteArrayTag.class),
IntArrayTagClass(IntArrayTag.class),
LongArrayTagClass(LongArrayTag.class),
StringTagClass(StringTag.class),
ListTagClass(ListTag.class);
Class<? extends Tag> clazz;
TagClass(Class<? extends Tag> clazz) {
this.clazz = clazz;
}
public Class<? extends Tag> getTagClass() {
return clazz;
}
}
} }

View File

@ -1,5 +1,10 @@
package com.loohp.limbo.utils; package com.loohp.limbo.utils;
import com.loohp.limbo.world.BlockPosition;
import net.querz.nbt.io.NBTOutputStream;
import net.querz.nbt.tag.CompoundTag;
import net.querz.nbt.tag.Tag;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
@ -7,12 +12,6 @@ import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.UUID; import java.util.UUID;
import com.loohp.limbo.world.BlockPosition;
import net.querz.nbt.io.NBTOutputStream;
import net.querz.nbt.tag.CompoundTag;
import net.querz.nbt.tag.Tag;
public class DataTypeIO { public class DataTypeIO {
public static void writeBlockPosition(DataOutputStream out, BlockPosition position) throws IOException { public static void writeBlockPosition(DataOutputStream out, BlockPosition position) throws IOException {

View File

@ -1,15 +1,15 @@
package com.loohp.limbo.utils; package com.loohp.limbo.utils;
import com.loohp.limbo.Limbo;
import com.loohp.limbo.commands.CommandSender;
import com.loohp.limbo.server.packets.PacketPlayOutDeclareCommands;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import com.loohp.limbo.Limbo;
import com.loohp.limbo.server.packets.PacketPlayOutDeclareCommands;
import com.loohp.limbo.commands.CommandSender;
public class DeclareCommands { public class DeclareCommands {
public static PacketPlayOutDeclareCommands getDeclareCommandsPacket(CommandSender sender) throws IOException { public static PacketPlayOutDeclareCommands getDeclareCommandsPacket(CommandSender sender) throws IOException {

View File

@ -15,14 +15,6 @@ public enum GameMode {
this.name = name; this.name = name;
} }
public int getId() {
return id;
}
public String getName() {
return name;
}
public static GameMode fromId(int id) { public static GameMode fromId(int id) {
for (GameMode mode : GameMode.values()) { for (GameMode mode : GameMode.values()) {
if (mode.getId() == id) { if (mode.getId() == id) {
@ -41,4 +33,12 @@ public enum GameMode {
return null; return null;
} }
public int getId() {
return id;
}
public String getName() {
return name;
}
} }

View File

@ -1,12 +1,11 @@
package com.loohp.limbo.utils; package com.loohp.limbo.utils;
import javax.imageio.ImageIO;
import java.awt.image.RenderedImage; import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Base64; import java.util.Base64;
import javax.imageio.ImageIO;
public class ImageUtils { public class ImageUtils {
public static String imgToBase64String(final RenderedImage img, String formatName) throws IOException { public static String imgToBase64String(final RenderedImage img, String formatName) throws IOException {

View File

@ -1,5 +1,6 @@
package com.loohp.limbo.utils; package com.loohp.limbo.utils;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -7,30 +8,8 @@ import java.net.URL;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.net.ssl.HttpsURLConnection;
public class MojangAPIUtils { public class MojangAPIUtils {
public static class SkinResponse {
String skin;
String signature;
public SkinResponse(String skin, String signature) {
this.skin = skin;
this.signature = signature;
}
public String getSkin() {
return skin;
}
public String getSignature() {
return signature;
}
}
public static UUID getOnlineUUIDOfPlayerFromMojang(String username) { public static UUID getOnlineUUIDOfPlayerFromMojang(String username) {
try { try {
URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + username); URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + username);
@ -90,4 +69,24 @@ public class MojangAPIUtils {
} }
} }
public static class SkinResponse {
String skin;
String signature;
public SkinResponse(String skin, String signature) {
this.skin = skin;
this.signature = signature;
}
public String getSkin() {
return skin;
}
public String getSignature() {
return signature;
}
}
} }

View File

@ -4,8 +4,8 @@ public class NamespacedKey {
public static final String MINECRAFT_KEY = "minecraft"; public static final String MINECRAFT_KEY = "minecraft";
private String namespace; private final String namespace;
private String key; private final String key;
public NamespacedKey(String namespacedKey) { public NamespacedKey(String namespacedKey) {
int index = namespacedKey.indexOf(":"); int index = namespacedKey.indexOf(":");
@ -64,11 +64,8 @@ public class NamespacedKey {
} else if (!key.equals(other.key)) } else if (!key.equals(other.key))
return false; return false;
if (namespace == null) { if (namespace == null) {
if (other.namespace != null) return other.namespace == null;
return false; } else return namespace.equals(other.namespace);
} else if (!namespace.equals(other.namespace))
return false;
return true;
} }
} }

View File

@ -4,7 +4,8 @@ package com.loohp.limbo.utils;
* Utils for casting number types to other number types * Utils for casting number types to other number types
*/ */
public final class NumberConversions { public final class NumberConversions {
private NumberConversions() {} private NumberConversions() {
}
public static int floor(double num) { public static int floor(double num) {
final int floor = (int) num; final int floor = (int) num;

View File

@ -68,10 +68,7 @@ public class Rotation3f {
if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y)) { if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y)) {
return false; return false;
} }
if (Double.doubleToLongBits(z) != Double.doubleToLongBits(other.z)) { return Double.doubleToLongBits(z) == Double.doubleToLongBits(other.z);
return false;
}
return true;
} }
} }

View File

@ -1,5 +1,9 @@
package com.loohp.limbo.utils; package com.loohp.limbo.utils;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.introspector.*;
import org.yaml.snakeyaml.util.PlatformFeatureDetector;
import java.beans.FeatureDescriptor; import java.beans.FeatureDescriptor;
import java.beans.IntrospectionException; import java.beans.IntrospectionException;
import java.beans.Introspector; import java.beans.Introspector;
@ -7,31 +11,17 @@ import java.beans.PropertyDescriptor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.Collection; import java.util.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.introspector.BeanAccess;
import org.yaml.snakeyaml.introspector.FieldProperty;
import org.yaml.snakeyaml.introspector.MethodProperty;
import org.yaml.snakeyaml.introspector.MissingProperty;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.introspector.PropertyUtils;
import org.yaml.snakeyaml.util.PlatformFeatureDetector;
public class YamlOrder extends PropertyUtils { public class YamlOrder extends PropertyUtils {
private static final String TRANSIENT = "transient";
private final Map<Class<?>, Map<String, Property>> propertiesCache = new HashMap<Class<?>, Map<String, Property>>(); private final Map<Class<?>, Map<String, Property>> propertiesCache = new HashMap<Class<?>, Map<String, Property>>();
private final Map<Class<?>, Set<Property>> readableProperties = new HashMap<Class<?>, Set<Property>>(); private final Map<Class<?>, Set<Property>> readableProperties = new HashMap<Class<?>, Set<Property>>();
private BeanAccess beanAccess = BeanAccess.DEFAULT; private BeanAccess beanAccess = BeanAccess.DEFAULT;
private boolean allowReadOnlyProperties = false; private boolean allowReadOnlyProperties = false;
private boolean skipMissingProperties = false; private boolean skipMissingProperties = false;
private final PlatformFeatureDetector platformFeatureDetector;
private PlatformFeatureDetector platformFeatureDetector;
public YamlOrder() { public YamlOrder() {
this(new PlatformFeatureDetector()); this(new PlatformFeatureDetector());
@ -100,8 +90,6 @@ public class YamlOrder extends PropertyUtils {
return properties; return properties;
} }
private static final String TRANSIENT = "transient";
private boolean isTransient(FeatureDescriptor fd) { private boolean isTransient(FeatureDescriptor fd) {
return Boolean.TRUE.equals(fd.getValue(TRANSIENT)); return Boolean.TRUE.equals(fd.getValue(TRANSIENT));
} }
@ -160,6 +148,10 @@ public class YamlOrder extends PropertyUtils {
} }
} }
public boolean isAllowReadOnlyProperties() {
return allowReadOnlyProperties;
}
public void setAllowReadOnlyProperties(boolean allowReadOnlyProperties) { public void setAllowReadOnlyProperties(boolean allowReadOnlyProperties) {
if (this.allowReadOnlyProperties != allowReadOnlyProperties) { if (this.allowReadOnlyProperties != allowReadOnlyProperties) {
this.allowReadOnlyProperties = allowReadOnlyProperties; this.allowReadOnlyProperties = allowReadOnlyProperties;
@ -167,8 +159,8 @@ public class YamlOrder extends PropertyUtils {
} }
} }
public boolean isAllowReadOnlyProperties() { public boolean isSkipMissingProperties() {
return allowReadOnlyProperties; return skipMissingProperties;
} }
public void setSkipMissingProperties(boolean skipMissingProperties) { public void setSkipMissingProperties(boolean skipMissingProperties) {
@ -177,8 +169,4 @@ public class YamlOrder extends PropertyUtils {
readableProperties.clear(); readableProperties.clear();
} }
} }
public boolean isSkipMissingProperties() {
return skipMissingProperties;
}
} }

View File

@ -3,9 +3,9 @@ package com.loohp.limbo.world;
import com.loohp.limbo.location.Location; import com.loohp.limbo.location.Location;
public class BlockPosition { public class BlockPosition {
private int x; private final int x;
private int y; private final int y;
private int z; private final int z;
public BlockPosition(int x, int y, int z) { public BlockPosition(int x, int y, int z) {
this.x = x; this.x = x;
@ -13,6 +13,10 @@ public class BlockPosition {
this.z = z; this.z = z;
} }
public static BlockPosition from(Location location) {
return new BlockPosition((int) Math.floor(location.getX()), (int) Math.floor(location.getY()), (int) Math.floor(location.getZ()));
}
public int getX() { public int getX() {
return this.x; return this.x;
} }
@ -24,8 +28,4 @@ public class BlockPosition {
public int getZ() { public int getZ() {
return this.z; return this.z;
} }
public static BlockPosition from(Location location) {
return new BlockPosition((int) Math.floor(location.getX()), (int) Math.floor(location.getY()), (int) Math.floor(location.getZ()));
}
} }

View File

@ -1,18 +1,17 @@
package com.loohp.limbo.world; package com.loohp.limbo.world;
import com.loohp.limbo.utils.NamespacedKey;
import net.querz.nbt.tag.CompoundTag;
import net.querz.nbt.tag.StringTag;
import net.querz.nbt.tag.Tag;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import com.loohp.limbo.utils.NamespacedKey;
import net.querz.nbt.tag.CompoundTag;
import net.querz.nbt.tag.StringTag;
import net.querz.nbt.tag.Tag;
public class BlockState { public class BlockState {
private CompoundTag tag; private final CompoundTag tag;
public BlockState(CompoundTag tag) { public BlockState(CompoundTag tag) {
this.tag = tag; this.tag = tag;
@ -40,11 +39,6 @@ public class BlockState {
return mapping; return mapping;
} }
public String getProperty(String key) {
Tag<?> value = tag.getCompoundTag("Properties").get(key);
return value == null ? null : ((StringTag) value).getValue();
}
public void setProperties(Map<String, String> mapping) { public void setProperties(Map<String, String> mapping) {
CompoundTag properties = new CompoundTag(); CompoundTag properties = new CompoundTag();
for (Entry<String, String> entry : mapping.entrySet()) { for (Entry<String, String> entry : mapping.entrySet()) {
@ -55,9 +49,14 @@ public class BlockState {
tag.put("Properties", properties); tag.put("Properties", properties);
} }
public String getProperty(String key) {
Tag<?> value = tag.getCompoundTag("Properties").get(key);
return value == null ? null : ((StringTag) value).getValue();
}
public <T> void setProperty(String key, T value) { public <T> void setProperty(String key, T value) {
CompoundTag properties = tag.getCompoundTag("Properties"); CompoundTag properties = tag.getCompoundTag("Properties");
properties.putString(key, ((T) value).toString()); properties.putString(key, value.toString());
} }
@Override @Override
@ -81,13 +80,8 @@ public class BlockState {
} }
BlockState other = (BlockState) obj; BlockState other = (BlockState) obj;
if (tag == null) { if (tag == null) {
if (other.tag != null) { return other.tag == null;
return false; } else return tag.equals(other.tag);
}
} else if (!tag.equals(other.tag)) {
return false;
}
return true;
} }
} }

View File

@ -1,27 +1,21 @@
package com.loohp.limbo.world; package com.loohp.limbo.world;
import java.io.File; import com.loohp.limbo.Limbo;
import java.io.FileInputStream; import com.loohp.limbo.utils.CustomNBTUtils;
import java.io.IOException; import net.querz.nbt.tag.CompoundTag;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import com.loohp.limbo.Limbo; import java.io.*;
import com.loohp.limbo.utils.CustomNBTUtils; import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import net.querz.nbt.tag.CompoundTag;
public class DimensionRegistry { public class DimensionRegistry {
private CompoundTag defaultTag; private CompoundTag defaultTag;
private CompoundTag codec; private CompoundTag codec;
private File reg; private final File reg;
public DimensionRegistry() { public DimensionRegistry() {
this.defaultTag = new CompoundTag(); this.defaultTag = new CompoundTag();

View File

@ -1,10 +1,10 @@
package com.loohp.limbo.world; package com.loohp.limbo.world;
import com.loohp.limbo.utils.NamespacedKey;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import com.loohp.limbo.utils.NamespacedKey;
public class Environment { public class Environment {
public static final Environment NORMAL = new Environment(new NamespacedKey("minecraft:overworld"), true); public static final Environment NORMAL = new Environment(new NamespacedKey("minecraft:overworld"), true);
@ -12,6 +12,13 @@ public class Environment {
public static final Environment END = new Environment(new NamespacedKey("minecraft:the_end"), false); public static final Environment END = new Environment(new NamespacedKey("minecraft:the_end"), false);
public static final Set<Environment> REGISTERED_ENVIRONMENTS = new HashSet<>(); public static final Set<Environment> REGISTERED_ENVIRONMENTS = new HashSet<>();
private final NamespacedKey key;
private final boolean hasSkyLight;
private Environment(NamespacedKey key, boolean hasSkyLight) {
this.key = key;
this.hasSkyLight = hasSkyLight;
}
public static Environment fromNamespacedKey(NamespacedKey key) { public static Environment fromNamespacedKey(NamespacedKey key) {
if (key.equals(NORMAL.getNamespacedKey())) { if (key.equals(NORMAL.getNamespacedKey())) {
@ -24,6 +31,8 @@ public class Environment {
return null; return null;
} }
//=========================
@Deprecated @Deprecated
public static Environment createCustom(NamespacedKey key) { public static Environment createCustom(NamespacedKey key) {
return createCustom(key, true); return createCustom(key, true);
@ -40,16 +49,6 @@ public class Environment {
return REGISTERED_ENVIRONMENTS.stream().filter(each -> each.getNamespacedKey().equals(key)).findFirst().orElse(null); return REGISTERED_ENVIRONMENTS.stream().filter(each -> each.getNamespacedKey().equals(key)).findFirst().orElse(null);
} }
//=========================
private NamespacedKey key;
private boolean hasSkyLight;
private Environment(NamespacedKey key, boolean hasSkyLight) {
this.key = key;
this.hasSkyLight = hasSkyLight;
}
public NamespacedKey getNamespacedKey() { public NamespacedKey getNamespacedKey() {
return key; return key;
} }
@ -83,12 +82,7 @@ public class Environment {
return false; return false;
} }
if (key == null) { if (key == null) {
if (other.key != null) { return other.key == null;
return false; } else return key.equals(other.key);
}
} else if (!key.equals(other.key)) {
return false;
}
return true;
} }
} }

View File

@ -1,5 +1,12 @@
package com.loohp.limbo.world; package com.loohp.limbo.world;
import com.loohp.limbo.Limbo;
import net.querz.nbt.tag.CompoundTag;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
@ -8,15 +15,6 @@ import java.nio.file.Files;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.loohp.limbo.Limbo;
import net.querz.nbt.tag.CompoundTag;
public class GeneratedBlockDataMappings { public class GeneratedBlockDataMappings {
private static JSONObject globalPalette = new JSONObject(); private static JSONObject globalPalette = new JSONObject();
@ -60,7 +58,7 @@ public class GeneratedBlockDataMappings {
for (Object entry : (JSONArray) data.get("states")) { for (Object entry : (JSONArray) data.get("states")) {
JSONObject jsonobj = (JSONObject) entry; JSONObject jsonobj = (JSONObject) entry;
if (((JSONObject) jsonobj.get("properties")).keySet().stream().allMatch(key -> blockstate.get(key).equals((String) (((JSONObject) jsonobj.get("properties")).get(key))))) { if (((JSONObject) jsonobj.get("properties")).keySet().stream().allMatch(key -> blockstate.get(key).equals(((JSONObject) jsonobj.get("properties")).get(key)))) {
return (int) (long) jsonobj.get("id"); return (int) (long) jsonobj.get("id");
} }
} }

View File

@ -5,7 +5,7 @@ import java.util.Map;
public abstract class LightEngine { public abstract class LightEngine {
private static Map<String, Byte> blockLightLevelMapping = new HashMap<>(); private static final Map<String, Byte> blockLightLevelMapping = new HashMap<>();
static { static {
blockLightLevelMapping.put("minecraft:beacon", (byte) 15); blockLightLevelMapping.put("minecraft:beacon", (byte) 15);

View File

@ -5,7 +5,7 @@ import java.util.List;
public class LightEngineBlock extends LightEngine { public class LightEngineBlock extends LightEngine {
private World world; private final World world;
private byte[][][] blockLightArray; private byte[][][] blockLightArray;
public LightEngineBlock(World world) { public LightEngineBlock(World world) {
@ -38,15 +38,34 @@ public class LightEngineBlock extends LightEngine {
if (blockLightArray[x][y + 16][z] < level) { if (blockLightArray[x][y + 16][z] < level) {
blockLightArray[x][y + 16][z] = (byte) level; blockLightArray[x][y + 16][z] = (byte) level;
if (level > 1) { if (level > 1) {
try {propergate(level - 1, x + 1, y, z);} catch (ArrayIndexOutOfBoundsException e) {} try {
try {propergate(level - 1, x - 1, y, z);} catch (ArrayIndexOutOfBoundsException e) {} propergate(level - 1, x + 1, y, z);
try {propergate(level - 1, x, y + 1, z);} catch (ArrayIndexOutOfBoundsException e) {} } catch (ArrayIndexOutOfBoundsException e) {
try {propergate(level - 1, x, y - 1, z);} catch (ArrayIndexOutOfBoundsException e) {} }
try {propergate(level - 1, x, y, z + 1);} catch (ArrayIndexOutOfBoundsException e) {} try {
try {propergate(level - 1, x, y, z - 1);} catch (ArrayIndexOutOfBoundsException e) {} propergate(level - 1, x - 1, y, z);
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
propergate(level - 1, x, y + 1, z);
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
propergate(level - 1, x, y - 1, z);
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
propergate(level - 1, x, y, z + 1);
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
propergate(level - 1, x, y, z - 1);
} catch (ArrayIndexOutOfBoundsException e) {
} }
} }
} catch (ArrayIndexOutOfBoundsException e) {} }
} catch (ArrayIndexOutOfBoundsException e) {
}
} }
public List<Byte[]> getBlockLightBitMask(int chunkX, int chunkZ) { public List<Byte[]> getBlockLightBitMask(int chunkX, int chunkZ) {

View File

@ -5,7 +5,7 @@ import java.util.List;
public class LightEngineSky extends LightEngine { public class LightEngineSky extends LightEngine {
private World world; private final World world;
private byte[][][] skyLightArray; private byte[][][] skyLightArray;
public LightEngineSky(World world) { public LightEngineSky(World world) {
@ -49,14 +49,30 @@ public class LightEngineSky extends LightEngine {
if (skyLightArray[x][y + 16][z] < level) { if (skyLightArray[x][y + 16][z] < level) {
skyLightArray[x][y + 16][z] = (byte) level; skyLightArray[x][y + 16][z] = (byte) level;
if (level > 1) { if (level > 1) {
try {propergate(level - 1, x + 1, y, z);} catch (ArrayIndexOutOfBoundsException e) {} try {
try {propergate(level - 1, x - 1, y, z);} catch (ArrayIndexOutOfBoundsException e) {} propergate(level - 1, x + 1, y, z);
try {propergate(level - 1, x, y + 1, z);} catch (ArrayIndexOutOfBoundsException e) {} } catch (ArrayIndexOutOfBoundsException e) {
try {propergate(level - 1, x, y, z + 1);} catch (ArrayIndexOutOfBoundsException e) {} }
try {propergate(level - 1, x, y, z - 1);} catch (ArrayIndexOutOfBoundsException e) {} try {
propergate(level - 1, x - 1, y, z);
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
propergate(level - 1, x, y + 1, z);
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
propergate(level - 1, x, y, z + 1);
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
propergate(level - 1, x, y, z - 1);
} catch (ArrayIndexOutOfBoundsException e) {
} }
} }
} catch (ArrayIndexOutOfBoundsException e) {} }
} catch (ArrayIndexOutOfBoundsException e) {
}
} }
public List<Byte[]> getSkyLightBitMask(int chunkX, int chunkZ) { public List<Byte[]> getSkyLightBitMask(int chunkX, int chunkZ) {

View File

@ -1,15 +1,14 @@
package com.loohp.limbo.world; package com.loohp.limbo.world;
import com.loohp.limbo.utils.SchematicConvertionUtils;
import net.querz.mca.Chunk;
import net.querz.nbt.tag.CompoundTag;
import net.querz.nbt.tag.ListTag;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import com.loohp.limbo.utils.SchematicConvertionUtils;
import net.querz.mca.Chunk;
import net.querz.nbt.tag.CompoundTag;
import net.querz.nbt.tag.ListTag;
public class Schematic { public class Schematic {

View File

@ -6,7 +6,8 @@ import com.loohp.limbo.entity.Entity;
@Deprecated @Deprecated
public class Unsafe { public class Unsafe {
private Unsafe() {} private Unsafe() {
}
@Deprecated @Deprecated
public void a(World a, Entity b) { public void a(World a, Entity b) {

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