diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index f91f646..0000000 --- a/.gitattributes +++ /dev/null @@ -1,12 +0,0 @@ -# -# https://help.github.com/articles/dealing-with-line-endings/ -# -# Linux start script should use lf -/gradlew text eol=lf - -# These are Windows script files and should use crlf -*.bat text eol=crlf - -# Binary files should be left untouched -*.jar binary - diff --git a/.gitignore b/.gitignore index 0f51950..0da720f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,8 @@ -/dev -.metadata -.classpath -.project -.settings -.gradle -bin -build +/common/dev +/common/bin +/client/bin +/client/run +/server/bin +/server/run +/export +/.metadata diff --git a/README.md b/README.md index 6e35be5..58d9bbb 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,3 @@ -# TCR - That Cube Rocks +# TCR -Ein Block-basiertes Open-World-Spiel mit vielen Dimensionen und RPG-Elementen. - -**Projekt ist in der frühen Entwicklungsphase / Alpha** - -Dieses Projekt ist Public Domain, siehe UNLICENSE. -Der Client verwendet LWJGL für GLFW und OpenGL, für dessen Lizenz siehe [Die LWJGL Website](https://www.lwjgl.org/license). +Ein Minecraft®™ 1.8.9 "Fork" diff --git a/client/build.gradle.kts b/client/build.gradle.kts deleted file mode 100644 index 78abd8c..0000000 --- a/client/build.gradle.kts +++ /dev/null @@ -1,47 +0,0 @@ - -plugins { - application - id("com.gradleup.shadow") version "8.3.6" -} - -repositories { - mavenCentral() -} - -dependencies { - implementation(project(":common")) - - implementation(platform("org.lwjgl:lwjgl-bom:3.3.6")) - - implementation("org.lwjgl", "lwjgl") - implementation("org.lwjgl", "lwjgl-glfw") - implementation("org.lwjgl", "lwjgl-opengl") - - runtimeOnly("org.lwjgl", "lwjgl", classifier = "natives-linux") - runtimeOnly("org.lwjgl", "lwjgl", classifier = "natives-freebsd") - runtimeOnly("org.lwjgl", "lwjgl", classifier = "natives-windows") - runtimeOnly("org.lwjgl", "lwjgl-glfw", classifier = "natives-linux") - runtimeOnly("org.lwjgl", "lwjgl-glfw", classifier = "natives-freebsd") - runtimeOnly("org.lwjgl", "lwjgl-glfw", classifier = "natives-windows") - runtimeOnly("org.lwjgl", "lwjgl-opengl", classifier = "natives-linux") - runtimeOnly("org.lwjgl", "lwjgl-opengl", classifier = "natives-freebsd") - runtimeOnly("org.lwjgl", "lwjgl-opengl", classifier = "natives-windows") -} - -java { - toolchain { - languageVersion = JavaLanguageVersion.of(21) - } -} - -application { - mainClass = "client.Client" - tasks.run.get().workingDir = rootProject.file("dev/client") - tasks.run.get().workingDir.mkdirs() - tasks.run.get().systemProperties.put("runtime.devmode", "") -} - -tasks.shadowJar { - destinationDirectory = rootProject.file("dev") - archiveFileName = "tcr_client.jar" -} diff --git a/client/src/main/java/client/Client.java b/client/src/client/Client.java similarity index 84% rename from client/src/main/java/client/Client.java rename to client/src/client/Client.java index 135071b..3ac6dda 100755 --- a/client/src/main/java/client/Client.java +++ b/client/src/client/Client.java @@ -19,10 +19,10 @@ import java.util.ArrayDeque; import java.util.Date; import java.util.Iterator; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; +import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; @@ -41,7 +41,6 @@ import client.audio.Volume; import client.gui.FileCallback; import client.gui.Font; import client.gui.Gui; -import client.gui.GuiConnect.ServerInfo; import client.gui.GuiConsole; import client.gui.GuiInfo; import client.gui.GuiLoading; @@ -55,7 +54,6 @@ import client.gui.element.Area; import client.gui.ingame.GuiGameOver; import client.network.ClientLoginHandler; import client.network.ClientPlayer; -import client.network.DummyConnection; import client.renderer.BlockRenderer; import client.renderer.Drawing; import client.renderer.EntityRenderer; @@ -72,10 +70,6 @@ import client.renderer.texture.ColormapLoader; import client.renderer.texture.EntityTexManager; import client.renderer.texture.TextureManager; import client.renderer.texture.TextureMap; -import client.util.FileUtils; -import client.util.Message; -import client.util.PerfSection; -import client.util.PlayerController; import client.vars.BoolVar; import client.vars.CVar; import client.vars.CVarCategory; @@ -100,28 +94,22 @@ import client.window.Keysym; import client.window.Wheel; import client.window.Window; import client.window.WindowEvent; -import client.world.ChunkClient; import client.world.WorldClient; -import common.Version; -import common.biome.Biome; import common.block.Block; import common.collect.Lists; import common.collect.Maps; import common.color.TextColor; -import common.dimension.Space; import common.entity.Entity; import common.entity.animal.EntityHorse; import common.entity.npc.Energy; -import common.entity.npc.EntityCpu; import common.entity.npc.EntityNPC; -import common.entity.npc.PlayerCharacter; import common.entity.types.EntityLiving; import common.future.Futures; import common.future.ListenableFuture; import common.future.ListenableFutureTask; import common.future.ThreadFactoryBuilder; import common.init.BlockRegistry; -import common.init.Blocks; +import common.init.Config; import common.init.EntityRegistry; import common.init.ItemRegistry; import common.init.Items; @@ -135,33 +123,26 @@ import common.item.ItemControl; import common.item.ItemStack; import common.log.Log; import common.log.LogLevel; -import common.net.bootstrap.Bootstrap; -import common.net.channel.Channel; -import common.net.channel.ChannelException; -import common.net.channel.ChannelHandler; -import common.net.channel.ChannelInitializer; -import common.net.channel.ChannelOption; -import common.net.channel.nio.NioEventLoopGroup; -import common.net.channel.socket.nio.NioSocketChannel; -import common.net.handler.timeout.ReadTimeoutHandler; -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; +import common.log.Message; +import common.material.Material; import common.network.IThreadListener; import common.network.NetConnection; import common.network.PacketDecoder; import common.network.PacketEncoder; import common.network.PacketPrepender; -import common.network.PacketRegistry; import common.network.PacketSplitter; import common.network.NetHandler.ThreadQuickExitException; import common.packet.CPacketAction; import common.packet.CPacketCheat; import common.packet.CPacketMessage; import common.packet.HPacketHandshake; +import common.packet.LPacketLogin; import common.packet.CPacketAction.Action; import common.potion.Potion; import common.potion.PotionEffect; +import common.potion.PotionHelper; import common.properties.IProperty; +import common.rng.Random; import common.sound.EventType; import common.sound.PositionedSound; import common.util.BlockPos; @@ -169,13 +150,22 @@ import common.util.BoundingBox; import common.util.CharValidator; import common.util.ExtMath; import common.util.Facing; +import common.util.FileUtils; import common.util.HitPosition; -import common.util.LazyLoader; +import common.util.LazyLoadBase; import common.util.Util; import common.util.HitPosition.ObjectType; -import common.world.LightType; +import common.world.Chunk; import common.world.State; -import common.world.World; +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelException; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.timeout.ReadTimeoutHandler; /* Een net ganz funktionierndes Programm ... @@ -241,25 +231,12 @@ public class Client implements IThreadListener { } } - public static class RedrawFunction implements IntFunction { - public void apply(IntVar cv, int value) { - Client.CLIENT.rescale(); - } - } - public static class LevelFunction implements EnumFunction { public void apply(EnumVar cv, LogLevel value) { Log.setLevel(value); } } - public static class FontFunction implements BoolFunction { - public void apply(BoolVar cv, boolean value) { - Font.load(value); - Client.CLIENT.rescale(); - } - } - private interface DebugRunner { void execute(Keysym key); } @@ -275,12 +252,9 @@ public class Client implements IThreadListener { this.help = help; } } - - public static final String VERSION = Version.NAME + " Client " + Util.VERSION; + public static final int LOG_BUFFER = 32768; - public static final int MIN_WIDTH = 800; - public static final int MIN_HEIGHT = 450; - private static final LazyLoader CLIENT_NIO_EVENTLOOP = new LazyLoader() + private static final LazyLoadBase CLIENT_NIO_EVENTLOOP = new LazyLoadBase() { protected NioEventLoopGroup load() { @@ -298,9 +272,7 @@ public class Client implements IThreadListener { private final List feed = Lists.newArrayList(); private final List hotbar = Lists.newArrayList(); private final File config = new File(System.getProperty("config.file", "client.cfg")); - public final Map playerList = Maps.newTreeMap(); - public final List characterList = Lists.newArrayList(); - + private boolean primary; private boolean secondary; private boolean tertiary; @@ -330,7 +302,6 @@ public class Client implements IThreadListener { public int thirdPersonView; public int timeFactor = 1; public int chunksUpdated; - public int selectedCharacter = -1; private long lastTicked = 0L; private long debugUpdateTime = System.currentTimeMillis(); @@ -342,33 +313,6 @@ public class Client implements IThreadListener { public float moveForward; public float zoomLevel; public float gravity = 1.0f; - - private long tmr_timer; - private long tmr_start; - private long tmr_current; - private long tmr_last; - - private long tmr_delta; - private long tmr_update; - private long tmr_frames; - private long tmr_iters; - - private long tick_torun; - private long tick_done; - private long tick_total; - private long tick_time; - private long tick_stime; - private long tick_ftime; - - private long tick_ttime; - private long tick_update; - - private double tick_fraction; - private float framerate; - private float tickrate; - private float fdelta; - private int tickTarget; - private int tickFrame; private TextureManager textureManager; private RenderManager renderManager; @@ -394,9 +338,9 @@ public class Client implements IThreadListener { public EntityNPC player; public HitPosition pointed; - @Variable(name = "chunk_view_distance", category = CVarCategory.RENDER, min = 2, max = 16, callback = DistanceFunction.class, display = "Sichtweite", unit = "Chunks") + @Variable(name = "chunk_view_distance", category = CVarCategory.RENDER, min = 2, max = 16 /* 128 */, callback = DistanceFunction.class, display = "Sichtweite", unit = "Chunks") public int renderDistance = 8; - @Variable(name = "chunk_build_time", category = CVarCategory.RENDER, min = 1, max = 100, display = "Zeit für Chunk-Bau", unit = "ms") + @Variable(name = "chunk_build_time", category = CVarCategory.RENDER, min = 1, max = 100, display = "Max. Zeit für Chunk-Bau pro Frame", unit = "ms") public int maxBuildTime = 8; @Variable(name = "gl_fov", category = CVarCategory.RENDER, min = 1.0f, max = 179.0f, display = "Sichtfeld (FOV)", unit = "°", precision = 1) public float fov = 70.0f; @@ -411,27 +355,20 @@ public class Client implements IThreadListener { @Variable(name = "win_sync", category = CVarCategory.WINDOW, min = -1, max = 16384, callback = SyncFunction.class, display = "Maximale Bildrate") public int sync = 0; - @Variable(name = "win_width", category = CVarCategory.WINDOW, min = MIN_WIDTH, max = 65536, display = "Fensterbreite") + public int width; + public int height; + public int mouse_x; + public int mouse_y; + @Variable(name = "win_width", category = CVarCategory.WINDOW, min = 1, max = 65536, display = "Fensterbreite") public int xsize = 1280; - @Variable(name = "win_height", category = CVarCategory.WINDOW, min = MIN_HEIGHT, max = 65536, display = "Fensterhöhe") + @Variable(name = "win_height", category = CVarCategory.WINDOW, min = 1, max = 65536, display = "Fensterhöhe") public int ysize = 800; @Variable(name = "win_pos_x", category = CVarCategory.WINDOW, min = -65536, max = 65536, display = "Fenster X-Position") public int saved_xpos = 0x80000000; @Variable(name = "win_pos_y", category = CVarCategory.WINDOW, min = -65536, max = 65536, display = "Fenster Y-Position") public int saved_ypos = 0x80000000; - - public int fb_raw_x; - public int fb_raw_y; - private int mouse_raw_x; - private int mouse_raw_y; public int fb_x; public int fb_y; - public int mouse_x; - public int mouse_y; - private int scale = 1; - - @Variable(name = "gui_scale", category = CVarCategory.GUI, min = 1, max = 5, display = "Skalierung", unit = "x", callback = RedrawFunction.class) - private int scaleVar = 1; @Variable(name = "phy_sensitivity", category = CVarCategory.INPUT, min = 0.01f, max = 10.0f, display = "Mausempfindlichkeit", precision = 2, unit = "%") public float sensitivity = 1.0f; @@ -442,19 +379,19 @@ public class Client implements IThreadListener { public DisplayMode vidMode; @Variable(name = "gui_dclick_delay", category = CVarCategory.INPUT, min = 150, max = 750, display = "Doppelklick bei", unit = "ms") public int dclickDelay = 250; - @Variable(name = "console_size", category = CVarCategory.CONSOLE, min = 0, max = 128, callback = ConsoleFunction.class, display = "Nachrichten in Konsole") + @Variable(name = "console_size", category = CVarCategory.CONSOLE, min = 0, max = 128, callback = ConsoleFunction.class, display = "Nachrichten in der Konsole") public int consoleSize = 32; @Variable(name = "chat_size", category = CVarCategory.CONSOLE, min = 0, max = 128, callback = ChatFunction.class, display = "Nachrichten im Chat") public int chatSize = 32; @Variable(name = "feed_size", category = CVarCategory.CONSOLE, min = 0, max = 128, callback = FeedFunction.class, display = "Nachrichten im Feed") public int feedSize = 8; - @Variable(name = "hotbar_size", category = CVarCategory.CONSOLE, min = 0, max = 16, callback = HotbarFunction.class, display = "Nachrichten in Hotbar") + @Variable(name = "hotbar_size", category = CVarCategory.CONSOLE, min = 0, max = 16, callback = HotbarFunction.class, display = "Nachrichten in der Hotbar") public int hotbarSize = 2; - @Variable(name = "overlay_fadeout", category = CVarCategory.CONSOLE, min = 1, max = 60, display = "Anzeigedauer", unit = "s") + @Variable(name = "overlay_fadeout", category = CVarCategory.CONSOLE, min = 1, max = 60, display = "Dauer bis zum Ausblenden", unit = "s") public int hudFadeout = 8; @Variable(name = "overlay_enabled", category = CVarCategory.CONSOLE, display = "Nachrichten-Overlay") public boolean hudOverlay = true; - @Variable(name = "chat_permanent", category = CVarCategory.CONSOLE, display = "Chat immer einblenden") + @Variable(name = "chat_permanent", category = CVarCategory.CONSOLE, display = "Nachrichten im Chat immer einblenden") public boolean chatPermanent = false; @Variable(name = "overlay_opacity", category = CVarCategory.CONSOLE, min = 0x00, max = 0xff, display = "Deckkraft Hintergrund") public int hudOpacity = 0x40; @@ -464,7 +401,7 @@ public class Client implements IThreadListener { public boolean saving; public boolean drawFps; public boolean drawDebug; - @Variable(name = "gl_vsync_flush", category = CVarCategory.RENDER, display = "Puffer leeren") + @Variable(name = "gl_vsync_flush", category = CVarCategory.RENDER, display = "Puffer vor Synch. leeren") public boolean glFlush = false; @Variable(name = "con_autoclose", category = CVarCategory.CONSOLE, display = "Schließen") public boolean conAutoclose = true; @@ -473,8 +410,6 @@ public class Client implements IThreadListener { public Style style = Style.DEFAULT; @Variable(name = "gui_scroll_lines", category = CVarCategory.GUI, min = 1, max = 10, display = "Scrollbreite", unit = "Zeilen") public int scrollLines = 3; - @Variable(name = "gui_font_tiny", category = CVarCategory.GUI, display = "Kleine Schrift", callback = FontFunction.class) - public boolean tinyFont = false; @@ -485,12 +420,13 @@ public class Client implements IThreadListener { @Variable(name = "snd_enabled", category = CVarCategory.SOUND, display = "Tonausgabe") public boolean soundEnabled = true; - @Variable(name = "snd_buffer_size", category = CVarCategory.SOUND, min = 0, max = 1048576, display = "Puffer") - public int soundBufferSize = 16384; - @Variable(name = "snd_frame_size", category = CVarCategory.SOUND, min = 2, max = 8192, display = "Intervall") + @Variable(name = "snd_buffer_size", category = CVarCategory.SOUND, min = 0, max = 1048576, display = "Puffergröße") + public int soundBufferSize = 2048; + @Variable(name = "snd_frame_size", category = CVarCategory.SOUND, min = 2, max = 8192, display = "PCM-Intervall") public int soundFrameSize = 32; - + private String serverInfo; + private String tickInfo; private int lastTickTime = -1; private AudioInterface audio; private boolean cfgDirty; @@ -542,74 +478,33 @@ public class Client implements IThreadListener { })).channel(NioSocketChannel.class)).connect(address, serverPort).syncUninterruptibly(); return networkmanager; } - - public void displayConnecting(ServerInfo server) { - this.displayGuiScreen(GuiLoading.makeWaitTask("Verbinde zu " + (server.getAddress() == null ? "localhost" : server.getAddress()) + ":" + server.getPort() + " ...")); - } - public void connect(final ServerInfo server) { - this.displayConnecting(server); - Log.NETWORK.info("Verbinde zu " + (server.getAddress() == null ? "localhost" : server.getAddress()) + ":" + server.getPort()); - new Thread(new Runnable() { - public void run() { - final NetConnection connection; - try - { - connection = createNetworkManagerAndConnect(server.getAddress() == null ? InetAddress.getLoopbackAddress() : InetAddress.getByName(IDN.toASCII(server.getAddress())), server.getPort()); - connection.setNetHandler(new ClientLoginHandler(connection, Client.this, server)); - connection.sendPacket(new HPacketHandshake(Util.PROTOCOL), new GenericFutureListener>() { - public void operationComplete(Future u) throws Exception { - connection.setConnectionState(PacketRegistry.LOGIN); - } - }); - } - catch (UnknownHostException u) - { - Log.NETWORK.error(u, "Konnte nicht zu Server verbinden"); - Client.this.schedule(new Runnable() { - public void run() { - Client.this.disconnected("Unbekannter Hostname: " + (server.getAddress() == null ? "localhost" : server.getAddress())); - } - }); - return; - } - catch (Exception e) - { - Log.NETWORK.error(e, "Konnte nicht zu Server verbinden"); - Client.this.schedule(new Runnable() { - public void run() { - Client.this.disconnected((e instanceof RuntimeException && !(e.getCause() instanceof RuntimeException) ? e.getCause() : e).toString()); - } - }); - return; - } - Client.this.schedule(new Runnable() { - public void run() { - Client.this.connection = connection; - } - }); - } - }, "Server connector").start(); + public void connect(String address, int port, String user, String pass, String access) { + this.displayGuiScreen(GuiLoading.makeWaitTask("Verbinde zu " + (address == null ? "localhost" : address) + ":" + port + " ...")); + Log.JNI.info("Verbinde zu " + (address == null ? "localhost" : address) + ":" + port); + NetConnection connection = null; + try + { + connection = createNetworkManagerAndConnect(address == null ? InetAddress.getLoopbackAddress() : InetAddress.getByName(IDN.toASCII(address)), port); + connection.setNetHandler(new ClientLoginHandler(connection, this, user, access, pass)); + connection.sendPacket(new HPacketHandshake(Config.PROTOCOL)); + connection.sendPacket(new LPacketLogin()); + } + catch (UnknownHostException u) + { + Log.JNI.error(u, "Konnte nicht zu Server verbinden"); + this.disconnected("Unbekannter Hostname: " + (address == null ? "localhost" : address)); + return; + } + catch (Exception e) + { + Log.JNI.error(e, "Konnte nicht zu Server verbinden"); + this.disconnected(e.toString()); + return; + } + this.connection = connection; } - public void joinDebugWorld() { - ClientPlayer player = new ClientPlayer(this, new DummyConnection()); - this.debugWorld = true; - this.charEditor = false; - this.controller = new PlayerController(this, player); - WorldClient world = new WorldClient(this, Space.INSTANCE); - this.loadWorld(world, EntityRegistry.getEntityID(EntityCpu.class)); - this.player.setId(0); - this.displayGuiScreen(null); - this.player.flying = true; - this.player.noclip = true; - this.player.addEffect(new PotionEffect(Potion.FLYING, Integer.MAX_VALUE, 1)); - this.player.setHeight(2.0f); - world.setGravity(this.gravity = 1.0f); - world.setTimeFactor(this.timeFactor = 1); - this.dayCycle = true; - } - public void unloadWorld() { ClientPlayer netHandler = this.getNetHandler(); if(netHandler != null) @@ -622,9 +517,6 @@ public class Client implements IThreadListener { this.player = null; this.serverInfo = null; this.lastTickTime = -1; - this.selectedCharacter = -1; - this.playerList.clear(); - this.characterList.clear(); this.soundManager.stopSounds(); } @@ -692,10 +584,10 @@ public class Client implements IThreadListener { } catch(ExecutionException e1) { if(!(e1.getCause() instanceof ThreadQuickExitException)) - Log.SYSTEM.error(e1, "Fehler beim Ausführen von Render-Task " + task); + Log.JNI.error(e1, "Fehler beim Ausführen von Render-Task " + task); } catch(InterruptedException e2) { - Log.SYSTEM.error(e2, "Fehler beim Ausführen von Render-Task " + task); + Log.JNI.error(e2, "Fehler beim Ausführen von Render-Task " + task); } } } @@ -775,7 +667,7 @@ public class Client implements IThreadListener { this.entityRenderer.getMouseOver(1.0F); if (/* !this.paused && */ this.world != null) { - this.controller.update(); + this.controller.updateController(); } this.textureMap.updateAnimations(); if (this.open != null) @@ -805,7 +697,7 @@ public class Client implements IThreadListener { { if (!Bind.SECONDARY.isDown()) { - this.controller.stopUsing(this.player); + this.controller.onStoppedUsingItem(this.player); } } else @@ -870,10 +762,8 @@ public class Client implements IThreadListener { } else if (this.connection != null) { - if(this.connection.isChannelOpen()) - this.connection.processReceivedPackets(); - else - this.connection.checkDisconnected(); + this.connection.processReceivedPackets(); + this.connection.checkDisconnected(); } } @@ -892,14 +782,14 @@ public class Client implements IThreadListener { this.deltaX = this.deltaY = 0.0f; } if(this.player != null) - this.soundManager.setListener(this.player, (float)this.tick_fraction); + this.soundManager.setListener(this.player, (float)Timing.tick_fraction); if(this.player != null && this.player.isEntityInsideOpaqueBlock()) this.thirdPersonView = 0; GL11.glPushMatrix(); GL11.glClear(16640); GlState.enableTexture2D(); if(this.world != null) - this.entityRenderer.renderWorld((float)this.tick_fraction, System.nanoTime() - this.tickStart); + this.entityRenderer.renderWorld((float)Timing.tick_fraction, System.nanoTime() - this.tickStart); GL11.glPopMatrix(); GlState.disableTexture2D(); @@ -932,7 +822,7 @@ public class Client implements IThreadListener { this.setupOverlay(); if(this.world != null && this.open == null && this.thirdPersonView == 0 && this.viewEntity != null) { if(this.drawDebug) { - this.renderWorldDirections((float)this.tick_fraction); + this.renderWorldDirections((float)Timing.tick_fraction); } else { Drawing.drawRect(this.fb_x / 2 - 1, this.fb_y / 2 - 16, 2, 32, this.pointed != null && this.pointed.type != ObjectType.MISS ? 0xffffffff : 0xffcfcfcf); @@ -987,13 +877,13 @@ public class Client implements IThreadListener { for(PotionEffect effect : this.player.getEffects()) { Potion potion = effect.getPotion(); int color = potion.getColor(); - String name = (potion.isBadEffect() ? TextColor.ORANGE : TextColor.ACID) + effect.getEffectName(); + String name = (potion.isBadEffect() ? TextColor.ORANGE : TextColor.ACID) + potion.getDisplay() + PotionHelper.getPotionPotency(effect.getAmplifier()); String desc = TextColor.NEON + effect.getDurationString(); // Drawing.drawRectColor(x, y, 250, Font.DEFAULT.yglyph + 2, color | 0xff000000); - Drawing.drawRectBorder(x, y, 250, Font.YGLYPH + 6, 0xff000000, 0xff202020, 0xffcfcfcf, 0xff6f6f6f); - Drawing.drawGradient(x + 2, y + 2, effect.isInfinite() ? 246 : ((int)(246.0f * ((float)effect.getRemaining() / (float)effect.getDuration()))), Font.YGLYPH + 2, color | 0xff000000, Util.mixColor(color | 0xff000000, 0xff000000)); - Drawing.drawText(name, x + 4, y + 3, 0xffffffff); - Drawing.drawTextRight(desc, x + 250 - 4, y + 3, 0xffffffff); + Drawing.drawRectBorder(x, y, 250, Font.YGLYPH + 4, 0xff000000, 0xff202020, 0xffcfcfcf, 0xff6f6f6f); + Drawing.drawGradient(x + 2, y + 2, effect.isInfinite() ? 246 : ((int)(246.0f * ((float)effect.getRemaining() / (float)effect.getDuration()))), Font.YGLYPH, color | 0xff000000, Util.mixColor(color | 0xff000000, 0xff000000)); + Drawing.drawText(name, x + 4, y + 2, 0xffffffff); + Drawing.drawTextRight(desc, x + 250 - 4, y + 2, 0xffffffff); y += 24; } } @@ -1003,7 +893,7 @@ public class Client implements IThreadListener { int absorb = entity.getAbsorptionAmount(); int armor = entity.getTotalArmorValue(); int stats = 1 + (absorb > 0 ? 1 : 0) + (armor > 0 ? 1 : 0) + (entity.vehicle instanceof EntityLiving ? 1 : 0) - + (entity instanceof EntityNPC npc && npc.getManaPoints() > 0 ? 1 : 0); + + (entity instanceof EntityNPC && ((EntityNPC)entity).canUseMagic() ? 1 : 0); for(Energy energy : Energy.values()) { if(entity.getEnergy(energy) > 0) stats += 1; @@ -1023,9 +913,9 @@ public class Client implements IThreadListener { int vhMax = living.getMaxHealth(); y = stats(x, y, living.getDisplayName() /* + " (Reittier)" */, vh, vhMax, 0xff6060); } - if(entity instanceof EntityNPC npc && npc.getManaPoints() > 0) { - int mana = npc.getManaPoints(); - int maxm = npc.getMaxMana(); + if(entity instanceof EntityNPC && ((EntityNPC)entity).canUseMagic()) { + int mana = entity.getManaPoints(); + int maxm = entity.getMaxMana(); y = stats(x, y, TextColor.CYAN + "Mana", mana, maxm, 0x0000ff); } for(int z = 0; z < Energy.values().length; z++) { @@ -1117,8 +1007,8 @@ public class Client implements IThreadListener { } if(this.open != null) this.open.render(); - else if(this.world == null || this.charEditor) - Drawing.drawScaled(this, Gui.BACKGROUND); + else if(this.world == null || this.world.hasNoChunks() || this.charEditor) + Drawing.drawScaled(this, Gui.DIRT_BACKGROUND); if(Bind.INFO.isDown() && (this.open == null || !(this.open.selected instanceof client.gui.element.Field || this.open.selected instanceof Area))) this.drawInfo(); if(this.hudOverlay && !(this.open instanceof GuiConsole)) { @@ -1133,7 +1023,7 @@ public class Client implements IThreadListener { this.renderLagometer(); } else { - Drawing.drawText(String.format("%s%.2f", framecode(), this.framerate), 0, 0, 0xffffffff); + Drawing.drawText(String.format("%s%.2f", framecode(), Timing.framerate), 0, 0, 0xffffffff); } } GlState.enableBlend(); @@ -1161,13 +1051,13 @@ public class Client implements IThreadListener { , GL11.glGetString(GL11.GL_VERSION), // WCF.glGetString(WCF.GL_SHADING_LANGUAGE_VERSION), GL11.glGetString(GL11.GL_RENDERER), GL11.glGetString(GL11.GL_VENDOR), - this.framecode(), this.framerate < 1.0f ? 1.0f / this.framerate : this.framerate, this.framerate < 1.0f ? "SPF" : "FPS", + this.framecode(), Timing.framerate < 1.0f ? 1.0f / Timing.framerate : Timing.framerate, Timing.framerate < 1.0f ? "SPF" : "FPS", this.vsync ? TextColor.DGRAY + "VSYNC" : (this.syncLimited ? TextColor.GREEN + "" + this.syncLimit : TextColor.RED + "UNL"), - (float)PerfSection.getTotal(false) / 1000.0f, this.fb_raw_x, this.fb_raw_y, - this.fullscreen ? " @ " + (this.vidMode == null ? "?" : this.vidMode.refresh()) + " Hz" : "", - this.tpscode(), this.tickrate < 1.0f ? 1.0f / this.tickrate : this.tickrate, - this.tickrate < 1.0f ? "SPT" : "TPS", (float)this.tickTarget / 1000.0f, - (float)this.tick_time / 1000.0f, this.tickTimeout, + (float)PerfSection.getTotal(false) / 1000.0f, this.fb_x, this.fb_y, + this.fullscreen ? " @ " + (this.vidMode == null ? "?" : this.vidMode.refresh) + " Hz" : "", + this.tpscode(), Timing.tickrate < 1.0f ? 1.0f / Timing.tickrate : Timing.tickrate, + Timing.tickrate < 1.0f ? "SPT" : "TPS", (float)Timing.tickTarget / 1000.0f, + (float)Timing.tick_time / 1000.0f, this.tickTimeout, str != null ? "\n" : "", str != null ? str : "" ); // if(str) @@ -1320,14 +1210,14 @@ public class Client implements IThreadListener { // SKC.setGuiMenu(); // else // SKC.setGuiAny(); - Window.setTitle(String.format("%s - %s", VERSION, gui.getTitle())); + Window.setTitle(String.format("%s - %s", Config.CLIENT_VERSION, gui.getTitle())); } else { this.menu(false); this.leftClickCounter = 10000; Bind.disableMouse(); - Window.setTitle(String.format("%s - %s%s", VERSION, "Welt / Render", this.nograb ? "" : " (Maus gefangen)")); + Window.setTitle(String.format("%s - %s%s", Config.CLIENT_VERSION, "Welt / Render", this.nograb ? "" : " (Maus gefangen)")); // SKC.setGuiNone(); } } @@ -1346,7 +1236,7 @@ public class Client implements IThreadListener { { BlockPos blockpos = this.pointed.block; - if (this.world.getState(blockpos).getBlock() != Blocks.air && this.controller.damageBlock(blockpos, this.pointed.side)) + if (this.world.getState(blockpos).getBlock().getMaterial() != Material.air && this.controller.onPlayerDamageBlock(blockpos, this.pointed.side)) { this.effectRenderer.addBlockHitEffects(blockpos, this.pointed.side); this.player.swingItem(); @@ -1354,7 +1244,7 @@ public class Client implements IThreadListener { } else { - this.controller.resetProgress(); + this.controller.resetBlockRemoving(); } } } @@ -1366,13 +1256,13 @@ public class Client implements IThreadListener { if (this.pointed == null) { this.player.swingItem(); - Log.TICK.warn("Null zurückgegeben als 'hitResult', das sollte niemals passieren!"); + Log.JNI.warn("Null zurückgegeben als 'hitResult', das sollte niemals passieren!"); this.leftClickCounter = 10; } else { ItemStack itemstack = this.player.inventory.getCurrentItem(); - if ((this.pointed.type != ObjectType.BLOCK || this.world.getState(this.pointed.block).getBlock() == Blocks.air) && itemstack != null && itemstack.getItem().onAction(itemstack, this.player, this.world, ItemControl.PRIMARY, null)) + if ((this.pointed.type != ObjectType.BLOCK || this.world.getState(this.pointed.block).getBlock().getMaterial() == Material.air) && itemstack != null && itemstack.getItem().onAction(itemstack, this.player, this.world, ItemControl.PRIMARY, null)) { this.player.swingItem(); this.player.client.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.PRIMARY.ordinal())); @@ -1389,7 +1279,7 @@ public class Client implements IThreadListener { case BLOCK: this.player.swingItem(); BlockPos blockpos = this.pointed.block; - if (this.world.getState(blockpos).getBlock() != Blocks.air) + if (this.world.getState(blockpos).getBlock().getMaterial() != Material.air) { this.controller.clickBlock(blockpos, this.pointed.side); break; @@ -1407,7 +1297,7 @@ public class Client implements IThreadListener { private void secondary() { - if (!this.controller.isHittingBlock()) + if (!this.controller.getIsHittingBlock()) { this.rightClickTimer = 4; boolean flag = true; @@ -1420,11 +1310,11 @@ public class Client implements IThreadListener { if (this.pointed == null) { - Log.TICK.warn("Null zurückgegeben als 'hitResult', das sollte niemals passieren!"); + Log.JNI.warn("Null zurückgegeben als 'hitResult', das sollte niemals passieren!"); } else { - if ((this.pointed.type != ObjectType.BLOCK || this.world.getState(this.pointed.block).getBlock() == Blocks.air) && itemstack != null && itemstack.getItem().onAction(itemstack, this.player, this.world, ItemControl.SECONDARY, null)) + if ((this.pointed.type != ObjectType.BLOCK || this.world.getState(this.pointed.block).getBlock().getMaterial() == Material.air) && itemstack != null && itemstack.getItem().onAction(itemstack, this.player, this.world, ItemControl.SECONDARY, null)) { this.player.swingItem(); this.player.client.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.SECONDARY.ordinal())); @@ -1439,7 +1329,7 @@ public class Client implements IThreadListener { // flag = false; // } // else - if (this.controller.interact(this.player, this.pointed.entity)) + if (this.controller.interactWithEntitySendPacket(this.player, this.pointed.entity)) { flag = false; } @@ -1449,11 +1339,11 @@ public class Client implements IThreadListener { case BLOCK: BlockPos blockpos = this.pointed.block; - if (this.world.getState(blockpos).getBlock() != Blocks.air) + if (this.world.getState(blockpos).getBlock().getMaterial() != Material.air) { - int i = itemstack != null ? itemstack.size : 0; + int i = itemstack != null ? itemstack.stackSize : 0; - if (this.controller.clickRight(this.player, this.world, itemstack, blockpos, this.pointed.side, this.pointed.vec)) + if (this.controller.onPlayerRightClick(this.player, this.world, itemstack, blockpos, this.pointed.side, this.pointed.vec)) { flag = false; this.player.swingItem(); @@ -1464,11 +1354,11 @@ public class Client implements IThreadListener { return; } - if (itemstack.size == 0) + if (itemstack.stackSize == 0) { this.player.inventory.mainInventory[this.player.inventory.currentItem] = null; } - else if (itemstack.size != i) // || this.controller.isCreative()) + else if (itemstack.stackSize != i) // || this.controller.isCreative()) { this.entityRenderer.itemRenderer.resetEquippedProgress(); } @@ -1497,16 +1387,19 @@ public class Client implements IThreadListener { return; } +// boolean flag = this.thePlayer.creative; int meta = 0; boolean flag1 = false; +// TileEntity tileentity = null; Item item = null; +// NBTTagCompound tag = null; if (this.pointed.type == HitPosition.ObjectType.BLOCK) { BlockPos blockpos = this.pointed.block; Block block = this.world.getState(blockpos).getBlock(); - if (block == Blocks.air) + if (block.getMaterial() == Material.air) { return; } @@ -1718,7 +1611,6 @@ public class Client implements IThreadListener { } catch (Exception exception) { - Log.SYSTEM.error(exception, "Fehler beim sofortigen Ausführen von Render-Task " + callableToSchedule); return Futures.immediateFailedFuture(exception); } } @@ -1759,10 +1651,11 @@ public class Client implements IThreadListener { this.serverInfo = info; } - public void setLastTick(int time) { + public void setLastTick(int time, String info) { if(this.lastTickTime >= 0) { this.lastTicked = System.currentTimeMillis(); this.lastTickTime = time; + this.tickInfo = info; } } @@ -1836,30 +1729,20 @@ public class Client implements IThreadListener { break; } - Biome biome = null; - String bline; - String lline; + String light; if(this.world.isBlockLoaded(blockpos)) { - ChunkClient chunk = this.world.getChunk(blockpos); - biome = chunk.getBiome(blockpos); - bline = "Biom: " + biome.display + " (" + biome.id + ")" + /* (this.debugHideInfo ? "" : */ (", D: " + - TextColor.stripCodes(this.world.dimension.getFormattedName(false)) + - " (" + this.world.dimension.getDimensionId() + ")"); - lline = "Licht: " + chunk.getLightSub(blockpos, 0) + " (" + chunk.getLight(LightType.SKY, blockpos) + " Himmel, " - + chunk.getLight(LightType.BLOCK, blockpos) + " Blöcke, " + String.format( + Chunk chunk = this.world.getChunk(blockpos); + light = "Licht: " + chunk.getLightSub(blockpos, 0) + " (" + + chunk.getLight(blockpos) + " Blöcke, " + String.format( "%.1f", this.world.getSunBrightness(1.0f) * 15.0f) + " Welt), A: " + String.format("%.3f", this.world.getCelestialAngle(1.0f)); } else { - bline = "Biom: , D: " + - TextColor.stripCodes(this.world.dimension.getFormattedName(false)) + - " (" + this.world.dimension.getDimensionId() + ")"; - lline = "Licht: " + String.format( + light = "Licht: " + String.format( "%.1f", this.world.getSunBrightness(1.0f) * 15.0f) + " Welt, A: " + String.format("%.3f", this.world.getCelestialAngle(1.0f)); } - - float temp = Math.max(this.world.getTempOffset() + (biome != null ? biome.getTemperature(blockpos) : 0.0f), 0.0f); + long ticked = System.currentTimeMillis() - this.lastTicked; return @@ -1884,8 +1767,10 @@ public class Client implements IThreadListener { String.format(" (Zoom x%.1f)", this.zoomLevel) : "") + "\n" + String.format("Richtung: %s (%.1f / %.1f)", dirStr, ExtMath.wrapf(entity.rotYaw), ExtMath.wrapf(entity.rotPitch)) + "\n" + - bline + "\n" + - lline + "\n" + + "Dimension: " + (this.world.isExterminated() ? "[zerstört] " : "") + + TextColor.stripCodes(this.world.dimension.getFormattedName(false)) + + " (" + this.world.dimension.getDimensionId() + ")" + "\n" + + light + "\n" + String.format("Zeit: %d T, R %d / %d T, U %d / %d T", this.world.getDayTime(), this.world.getDayTime() % this.world.dimension.getRotationalPeriod(), @@ -1893,10 +1778,7 @@ public class Client implements IThreadListener { this.world.getDayTime() % this.world.dimension.getOrbitalPeriod(), this.world.dimension.getOrbitalPeriod() ) + "\n" + - String.format("Laub: %s%s, T: %.2f K / %.2f °C, %s (R %.1f, %.1f)", - !this.world.dimension.getType().days ? "*" : "", - this.world.getLeavesGen(blockpos).getDisplayName(), - temp, World.ABSOLUTE_ZERO + temp, + String.format("Wetter: %s (R %.1f, %.1f)", this.world.getWeather().getDisplay(), this.world.getRainStrength(), this.world.getDarkness() ) + "\n" + @@ -1905,9 +1787,9 @@ public class Client implements IThreadListener { ) + "\n" + String.format("Letzte Zeitsynch.: + %d.%d s", ticked / 1000L, (ticked / 100L) % 10L - ) + "\n" + - "Startwert: " + this.world.dimension.getSeed() + - (this.serverInfo != null ? "\n" + this.serverInfo : "") + ) + + (this.serverInfo != null ? "\n" + this.serverInfo : "") + + (this.tickInfo != null ? "\n" + this.tickInfo : "") // IWorldServer world = this.server.getWorld(this.theWorld.dimension.getDimensionId()); // if(world != null) // list.add("Seed: " + world.getSeed()); @@ -1929,42 +1811,56 @@ public class Client implements IThreadListener { } StringBuilder str = new StringBuilder( - "Schaue auf: " + BlockRegistry.getNameFromBlock(block.getBlock()) + " [" + BlockRegistry.getIdFromBlock(block.getBlock()) + + "Schaue auf: " + BlockRegistry.REGISTRY.getNameForObject(block.getBlock()) + " [" + BlockRegistry.getIdFromBlock(block.getBlock()) + ":" + block.getBlock().getMetaFromState(block) + "]" + "\n" + String.format("Position: %d %d %d", pos.getX(), pos.getY(), pos.getZ()) ); +// int off = 2; for(Entry entry : block.getProperties().entrySet()) { str.append("\n" + entry.getKey().getName() + ": " + entry.getValue().toString()); } - return str.toString(); + return str.toString(); // new String[] { +// list.add(""); +// list.add(); +// }; } - else if((this.pointed != null && this.pointed.type == HitPosition.ObjectType.ENTITY && this.pointed.entity != null) || showPlayerInfo) { + else if((this.pointed != null && this.pointed.type == HitPosition.ObjectType.ENTITY + && this.pointed.entity != null) || showPlayerInfo) { Entity entity = showPlayerInfo ? this.player : this.pointed.entity; ItemStack held = entity instanceof EntityLiving && ((EntityLiving)entity).getHeldItem() != null ? ((EntityLiving)entity).getHeldItem() : null; return - (showPlayerInfo ? "Charakter: " : "Schaue auf: ") + EntityRegistry.getEntityString(entity) + " (" + entity.getId() + ")" + "\n" + +// list.add(""); + (showPlayerInfo ? "Charakter: " : "Schaue auf: ") + (entity.isPlayer() ? "Player/" : "") + EntityRegistry.getEntityString(entity) + // " [" + (entity.isPlayer() ? "player" : + /* (EntityRegistry.getEntityID(entity) + "/" + EntityRegistry.getObjectID(entity))) + "]" */ " (" + entity.getId() + ")" + + "\n" + String.format("Position: %.3f %.3f %.3f", entity.posX, entity.posY, entity.posZ) + "\n" + + // list.add("Name: '" + entity.getName() + "'"); "Geladen: " + entity.ticksExisted + "t" + (entity instanceof EntityLiving ? (", Alter: " + ((EntityLiving)entity).getGrowingAge()) + "t" : "") + "\n" + String.format("Größe: %.2fx%.2f, A: %.2f", entity.width, entity.height, entity.getEyeHeight()) + "\n" + + // if(!this.debugHideInfo) { String.format("Bewegung: %.3f %.3f %.3f", entity.motionX, entity.motionY, entity.motionZ) + "\n" + String.format("Drehung: %.1f %.1f, K: %.1f", entity.rotYaw, entity.rotPitch, entity.getRotationYawHead()) + "\n" + + // } (entity instanceof EntityLiving ? String.format("Leben: %d/%d, A: %d", ((EntityLiving)entity).getHealth(), ((EntityLiving)entity).getMaxHealth(), ((EntityLiving)entity).getAbsorptionAmount()) : "Leben: n/a") + "\n" + - "Schaden: " + entity.hurtResistance + "t" + (showPlayerInfo ? String.format(", Fallh.: %.3f", entity.fallDistance) : "") + "\n" + + "Schaden: " + entity.hurtResistance + "t" + (showPlayerInfo ? String.format(", Fallh.: %.3f", entity.fallDistance) : "") + "\n" + // + ", Luft: " + entity.getAir()); (entity instanceof EntityLiving ? (((EntityLiving)entity).deathTime != 0 ? "Tod: " + ((EntityLiving)entity).deathTime + "t, " : "") + "Rüstung: " + ((EntityLiving)entity).getTotalArmorValue() + ", Pfeile: " + ((EntityLiving)entity).getArrowCountInEntity() : "Rüstung: n/a, Pfeile: n/a") + "\n" + +// ItemStack held = ((EntityLiving)entity).getHeldItem(); (held != null ? - "Gegens.: " + ItemRegistry.getNameFromItem(held.getItem()) + " x" + held.size + " (" + held.getMetadata() + ")" : "Gegens.: n/a") + "\n" + - "Eigens.: " + (entity.dead ? "D" : "") + (entity.noClip ? "N" : "") + (entity.onGround ? "G" : "") - + (entity.canBeCollidedWith() ? "C" : "") + (entity.canBePushed() ? "P" : "") - + (entity.isBurning() ? "B" : "") + (entity.isPlayer() ? "S" : "") - + (entity.isWet() ? "W" : "") + (entity.canAttackWithItem() ? "A" : "") - + (entity.passenger != null ? "H" : "") + (entity.vehicle != null ? "R" : "") - + (entity.doesEntityNotTriggerPressurePlate() ? "L" : "") + "\n" + + "Gegens.: " + ItemRegistry.REGISTRY.getNameForObject(held.getItem()) + " x" + held.stackSize + " (" + held.getMetadata() + ")" : "Gegens.: n/a") + "\n" + + "Eigens.: " + (entity.dead ? "D" : " ") + (entity.noClip ? "N" : " ") + (entity.onGround ? "G" : " ") + + (entity.canBeCollidedWith() ? "C" : " ") + (entity.canBePushed() ? "P" : " ") + + (entity.isBurning() ? "B" : " ") // + (entity.isInvisible() ? "I" : " ") // + (entity.isSilent() ? "S" : " ") + + (entity.canAttackWithItem() ? "A" : " ") + + (entity.passenger != null ? "H" : " ") + (entity.vehicle != null ? "R" : " ") + (entity instanceof EntityLiving ? + ("+" /* + (((EntityLivingBase)entity).isEntityUndead() ? "U" : " ") */ // + (((EntityLivingBase)entity).isChild() ? "C" : " ") + + (((EntityLiving)entity).doesEntityNotTriggerPressurePlate() ? "P" : " ")) : "") + "\n" + + // list.add("UUID: " + entity.getUniqueID().toString()); (entity.hasCustomName() ? "Name: '" + TextColor.stripCodes(entity.getCustomNameTag()) + "'" : "Name: n/a") ; } @@ -1986,9 +1882,13 @@ public class Client implements IThreadListener { private void fbsize(int x, int y) { GL11.glViewport(0, 0, x, y); - fb_raw_x = x; - fb_raw_y = y; - this.rescale(); + fb_x = x; + fb_y = y; + if(this.open != null) { + this.refreshing = true; + this.displayGuiScreen(this.open); + this.refreshing = false; + } if(!fullscreen) { xsize = x; ysize = y; @@ -2004,11 +1904,9 @@ public class Client implements IThreadListener { private void mouse(int x, int y) { if(!mouseFirst && open == null) - this.moveCamera((float)(x - mouse_raw_x) * sensitivity, (float)(mouse_raw_y - y) * sensitivity); - mouse_raw_x = x; - mouse_raw_y = y; - mouse_x = x / this.scale; - mouse_y = y / this.scale; + this.moveCamera((float)(x - mouse_x) * sensitivity, (float)(mouse_y - y) * sensitivity); + mouse_x = x; + mouse_y = y; mouseFirst = false; if(open != null && Bind.isInputEnabled() && Button.isMouseDown() /* && !(win->mouse & 0xfc) */ && !ctrl()) { // if(mouse_clickx < 0 || mouse_clicky < 0) { @@ -2091,13 +1989,7 @@ public class Client implements IThreadListener { // open.restyle(); } - private void rescale() { - this.scale = this.scaleVar; - while(this.scale > 1 && (this.fb_raw_x / this.scale < MIN_WIDTH || this.fb_raw_y / this.scale < MIN_HEIGHT)) { - this.scale--; - } - this.fb_x = Math.max(this.fb_raw_x / this.scale, MIN_WIDTH); - this.fb_y = Math.max(this.fb_raw_y / this.scale, MIN_HEIGHT); + private void redraw() { if(this.open != null) { this.refreshing = true; this.displayGuiScreen(this.open); @@ -2111,40 +2003,40 @@ public class Client implements IThreadListener { public void poll() { for(WindowEvent event : Window.poll()) { - switch(event.action()) { + switch(event.action) { case BUTTON: - if(event.param1() >= 0 && event.param1() < Button.values().length) - button(Button.values()[event.param1()], event.param2() != 0); + if(event.param1 >= 0 && event.param1 < Button.values().length) + button(Button.values()[event.param1], event.param2 != 0); break; case CHARACTER: - if(event.param1() >= (int)Log.CHR_SPC && event.param1() <= (int)Character.MAX_VALUE) - character((char)event.param1()); + if(event.param1 >= (int)Log.CHR_SPC && event.param1 <= (int)Character.MAX_VALUE) + character((char)event.param1); break; case CLOSED: closed(); break; case CURSOR: - mouse(event.param1(), event.param2()); + mouse(event.param1, event.param2); break; case FOCUS: - focus(event.param1() != 0); + focus(event.param1 != 0); break; case KEY: - if(event.param1() >= 0 && event.param1() < Keysym.values().length) - key(Keysym.values()[event.param1()], KeyEvent.values()[event.param2() % KeyEvent.values().length]); + if(event.param1 >= 0 && event.param1 < Keysym.values().length) + key(Keysym.values()[event.param1], KeyEvent.values()[event.param2 % KeyEvent.values().length]); break; case POSITION: - pos(event.param1(), event.param2()); + pos(event.param1, event.param2); break; case REDRAW: - // redraw(); disable as it is pretty useless + redraw(); break; case RESIZE: - fbsize(event.param1(), event.param2()); + fbsize(event.param1, event.param2); break; case SCROLL: - if(event.param1() != 0 || event.param2() != 0) - scroll(event.param1(), event.param2()); + if(event.param1 != 0 || event.param2 != 0) + scroll(event.param1, event.param2); break; } } @@ -2160,7 +2052,7 @@ public class Client implements IThreadListener { public void full(boolean full) { if((full != fullscreen || full) && (!full || vidMode != null)) { if(full) { - Window.setFullscreen(vidMode.width(), vidMode.height(), vidMode.refresh()); + Window.setFullscreen(vidMode.width, vidMode.height, vidMode.refresh); } else { Window.setWindowed(saved_xpos, saved_ypos, xsize, ysize); @@ -2178,7 +2070,7 @@ public class Client implements IThreadListener { } else { DisplayMode mode = Window.getDisplayMode(); - syncLimit = mode != null ? mode.refresh() : 60; + syncLimit = mode != null ? mode.refresh : 60; } Window.setVSync(vsync); } @@ -2191,16 +2083,10 @@ public class Client implements IThreadListener { GL11.glClear(256); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); - GL11.glOrtho(0.0D, (double)this.fb_raw_x, (double)this.fb_raw_y, 0.0D, 1000.0D, 3000.0D); + GL11.glOrtho(0.0D, (double)this.fb_x, (double)this.fb_y, 0.0D, 1000.0D, 3000.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -2000.0F); - if(this.scale != 1) - GL11.glScalef((float)this.scale, (float)this.scale, 1.0f); - } - - public void scissor(int x, int y, int width, int height) { - GL11.glScissor(x * this.scale, y * this.scale, width * this.scale, height * this.scale); } private void addFrame(long runningTime) @@ -2236,8 +2122,10 @@ public class Client implements IThreadListener { } } - public void run(long time) { - if(!Window.createWindow(VERSION, System.getProperty("opengl.debug") != null)) + public void run() { + Log.SYSTEM.info("Java " + System.getProperty("java.version")); + Log.SYSTEM.info(Config.CLIENT_VERSION); + if(!Window.createWindow(Config.CLIENT_VERSION, System.getProperty("opengl.debug") != null)) System.exit(1); Log.SYSTEM.info("OpenGL %s", GL11.glGetString(GL11.GL_VERSION)); Log.SYSTEM.info("GL_VENDOR: %s", GL11.glGetString(GL11.GL_VENDOR)); @@ -2248,33 +2136,30 @@ public class Client implements IThreadListener { this.registerDebug(); System.gc(); System.gc(); - Font.load(false); + Font.load(); GlState.enableBlend(); GlState.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); this.initConsole(); this.startSound(true); this.vidMode = Window.getDisplayMode(); - if(this.vidMode != null && (this.vidMode.width() < MIN_WIDTH || this.vidMode.height() < MIN_HEIGHT)) - this.vidMode = null; - Window.initWindow(this.saved_xpos, this.saved_ypos, this.xsize, this.ysize, MIN_WIDTH, MIN_HEIGHT); + Window.initWindow(this.saved_xpos, this.saved_ypos, this.xsize, this.ysize); Window.setIcon(genTriwave(64, 64, 0x00000000, 0xffff0000, 0xff00ff00, 0xff0000ff, 0xff7f00ff, 0xff000000), 64, 64); this.sync(this.sync); // this.startSound(true); this.getVar("tic_target").setDefault(); this.displayGuiScreen(GuiMenu.INSTANCE); - Log.SYSTEM.info("Client gestartet in " + String.format("%.1f", (double)(System.currentTimeMillis() - time) / 1000.0) + " Sekunden"); while(!this.interrupted) { PerfSection.swap(); PerfSection.TIMING.enter(); - this.tmr_current = Util.rtime(); - this.tmr_delta = this.tmr_current - this.tmr_last; - this.tmr_last = this.tmr_current; - this.fdelta = ((float)this.tmr_delta) / 1000000.0f; - if((this.tmr_current - this.tmr_update) >= 1000000L) { - this.framerate = ((float)this.tmr_frames) * 1000000.0f / ((float)(long)(this.tmr_current - this.tmr_update)); - this.tmr_frames = 0L; - this.tmr_update = this.tmr_current; + Timing.tmr_current = Util.rtime(); + Timing.tmr_delta = Timing.tmr_current - Timing.tmr_last; + Timing.tmr_last = Timing.tmr_current; + Timing.fdelta = ((float)Timing.tmr_delta) / 1000000.0f; + if((Timing.tmr_current - Timing.tmr_update) >= 1000000L) { + Timing.framerate = ((float)Timing.tmr_frames) * 1000000.0f / ((float)(long)(Timing.tmr_current - Timing.tmr_update)); + Timing.tmr_frames = 0L; + Timing.tmr_update = Timing.tmr_current; } this.start(); PerfSection.INPUT.enter(); @@ -2307,10 +2192,10 @@ public class Client implements IThreadListener { long now = System.nanoTime(); this.addFrame(now - this.startNanoTime); this.startNanoTime = now; - while(this.syncLimited && (Util.rtime() - this.tmr_current) < (1000000L / this.syncLimit)) { + while(this.syncLimited && (Util.rtime() - Timing.tmr_current) < (1000000L / this.syncLimit)) { ; } - this.tmr_frames += 1L; + Timing.tmr_frames += 1L; } Log.SYSTEM.info("Beende ..."); @@ -2336,7 +2221,7 @@ public class Client implements IThreadListener { // } public void disconnected(String msg) { - Log.NETWORK.info("Getrennt: %s", msg); + Log.SYSTEM.info("Getrennt: %s", msg); this.unload(true); this.displayGuiScreen(new GuiInfo("Von Server getrennt", TextColor.RED + "Verbindung zum Server wurde getrennt\n\n" + TextColor.RESET + msg)); } @@ -2398,23 +2283,23 @@ public class Client implements IThreadListener { if(this.saving) return; this.saving = true; - final int stride = ((this.fb_raw_x * 3) & 3) != 0 ? 4 + ((this.fb_raw_x * 3) & ~3) : (this.fb_raw_x * 3); - final ByteBuffer data = ByteBuffer.allocateDirect(stride * this.fb_raw_y).order(ByteOrder.nativeOrder()); - GL11.glReadPixels(0, 0, this.fb_raw_x, this.fb_raw_y, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, data); + final int stride = ((this.fb_x * 3) & 3) != 0 ? 4 + ((this.fb_x * 3) & ~3) : (this.fb_x * 3); + final ByteBuffer data = ByteBuffer.allocateDirect(stride * this.fb_y).order(ByteOrder.nativeOrder()); + GL11.glReadPixels(0, 0, this.fb_x, this.fb_y, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, data); new Thread(new Runnable() { public void run() { - byte[] pixels = new byte[stride * Client.this.fb_raw_y]; + byte[] pixels = new byte[stride * Client.this.fb_y]; data.get(pixels); - byte[] conv = new byte[Client.this.fb_raw_x * Client.this.fb_raw_y * 3]; - for(int l = 0; l < Client.this.fb_raw_y; l++) { - System.arraycopy(pixels, l * stride, conv, (Client.this.fb_raw_y - 1 - l) * Client.this.fb_raw_x * 3, Client.this.fb_raw_x * 3); + byte[] conv = new byte[Client.this.fb_x * Client.this.fb_y * 3]; + for(int l = 0; l < Client.this.fb_y; l++) { + System.arraycopy(pixels, l * stride, conv, (Client.this.fb_y - 1 - l) * Client.this.fb_x * 3, Client.this.fb_x * 3); } - BufferedImage image = new BufferedImage(Client.this.fb_raw_x, Client.this.fb_raw_y, BufferedImage.TYPE_INT_ARGB); - int[] img = new int[Client.this.fb_raw_x * Client.this.fb_raw_y]; + BufferedImage image = new BufferedImage(Client.this.fb_x, Client.this.fb_y, BufferedImage.TYPE_INT_ARGB); + int[] img = new int[Client.this.fb_x * Client.this.fb_y]; for(int z = 0; z < img.length; z++) { img[z] = (int)(conv[(z * 3) + 2] & 0xff) | ((int)(conv[(z * 3) + 1] & 0xff) << 8) | ((int)(conv[(z * 3) + 0] & 0xff) << 16) | 0xff000000; } - image.setRGB(0, 0, Client.this.fb_raw_x, Client.this.fb_raw_y, img, 0, Client.this.fb_raw_x); + image.setRGB(0, 0, Client.this.fb_x, Client.this.fb_y, img, 0, Client.this.fb_x); File dir = new File("screenshots"); dir.mkdirs(); @@ -2450,51 +2335,51 @@ public class Client implements IThreadListener { } public TextColor framecode() { - return (this.framerate >= 59.0f) ? TextColor.GREEN : ((this.framerate >= 29.0f) ? TextColor.YELLOW : ((this.framerate >= 14.0f) ? TextColor.ORANGE : TextColor.RED)); + return (Timing.framerate >= 59.0f) ? TextColor.GREEN : ((Timing.framerate >= 29.0f) ? TextColor.YELLOW : ((Timing.framerate >= 14.0f) ? TextColor.ORANGE : TextColor.RED)); } public TextColor tpscode() { - return (this.tickrate >= (((float)this.tickTarget / 1000.0f) - 1.0f)) ? TextColor.GREEN : ((this.tickrate >= (((float)this.tickTarget / 1000.0f) / 2.0f - 1.0f)) ? TextColor.YELLOW : - ((this.tickrate >= (((float)this.tickTarget / 1000.0f) / 4.0f - 1.0f)) ? TextColor.ORANGE : TextColor.RED)); + return (Timing.tickrate >= (((float)Timing.tickTarget / 1000.0f) - 1.0f)) ? TextColor.GREEN : ((Timing.tickrate >= (((float)Timing.tickTarget / 1000.0f) / 2.0f - 1.0f)) ? TextColor.YELLOW : + ((Timing.tickrate >= (((float)Timing.tickTarget / 1000.0f) / 4.0f - 1.0f)) ? TextColor.ORANGE : TextColor.RED)); } private void doTicks() { - this.tick_stime = Util.rtime(); - if((this.tick_stime - this.tick_update) >= 1000000L) { - this.tickrate = ((float)this.tick_done) * 1000000.0f / ((float)(long)(this.tick_stime - this.tick_update)); - this.tick_done = 0; - this.tick_update = this.tick_stime; + Timing.tick_stime = Util.rtime(); + if((Timing.tick_stime - Timing.tick_update) >= 1000000L) { + Timing.tickrate = ((float)Timing.tick_done) * 1000000.0f / ((float)(long)(Timing.tick_stime - Timing.tick_update)); + Timing.tick_done = 0; + Timing.tick_update = Timing.tick_stime; } - this.tick_torun += (((long)this.tickTarget) * this.tmr_delta) / 1000L; - this.tickFrame = 0; - this.tick_torun = this.tick_torun > 2000000L ? 1000000L : this.tick_torun; - while(this.tick_torun >= 1000000L) { + Timing.tick_torun += (((long)Timing.tickTarget) * Timing.tmr_delta) / 1000L; + Timing.tickFrame = 0; + Timing.tick_torun = Timing.tick_torun > 2000000L ? 1000000L : Timing.tick_torun; + while(Timing.tick_torun >= 1000000L) { this.tick(); - this.tick_done += 1L; - this.tickFrame += 1; - this.tick_total += 1L; - this.tick_torun -= 1000000L; - if((this.tick_ftime = (Util.rtime() - this.tick_stime)) >= (((long)this.tickTimeout) * 1000L)) { - Log.TICK.warn("Ticks benötigten %d ms dieses Frame (maximal %d ms), überspringe %d Ticks", this.tick_ftime / 1000L, this.tickTimeout, this.tick_torun / 1000000L); - this.tick_torun = 0L; + Timing.tick_done += 1L; + Timing.tickFrame += 1; + Timing.tick_total += 1L; + Timing.tick_torun -= 1000000L; + if((Timing.tick_ftime = (Util.rtime() - Timing.tick_stime)) >= (((long)this.tickTimeout) * 1000L)) { + Log.TICK.warn("Ticks benötigten %d ms dieses Frame (maximal %d ms), überspringe %d Ticks", Timing.tick_ftime / 1000L, this.tickTimeout, Timing.tick_torun / 1000000L); + Timing.tick_torun = 0L; break; } } - this.tick_fraction = ((double)this.tick_torun) / 1000000.0; - this.tick_ttime += this.tick_ftime; - this.tick_time = this.tickFrame != 0 ? (this.tick_ftime / (long)this.tickFrame) : 0L; + Timing.tick_fraction = ((double)Timing.tick_torun) / 1000000.0; + Timing.tick_ttime += Timing.tick_ftime; + Timing.tick_time = Timing.tickFrame != 0 ? (Timing.tick_ftime / (long)Timing.tickFrame) : 0L; } public void tick_target(float tps) { - this.tickTarget = (int)(tps * 1000.0f); - this.tick_torun = 0L; - this.tick_done = 0L; - this.tick_update = Util.rtime(); + Timing.tickTarget = (int)(tps * 1000.0f); + Timing.tick_torun = 0L; + Timing.tick_done = 0L; + Timing.tick_update = Util.rtime(); } public void unload(boolean loading) { if(this.world != null && this.getNetHandler() != null) - this.getNetHandler().getConnection().closeChannel("Quitting"); + this.getNetHandler().getNetworkManager().closeChannel("Quitting"); this.unloadWorld(); this.displayGuiScreen(GuiMenu.INSTANCE); } @@ -2680,7 +2565,7 @@ public class Client implements IThreadListener { Client.this.soundManager.stopSounds(); } }); - this.registerDebug(Keysym.Q, "Programm sofort beenden und trennen", new DebugRunner() { + this.registerDebug(Keysym.Q, "Programm sofort beenden und speichern", new DebugRunner() { public void execute(Keysym key) { Client.this.interrupted = true; } @@ -2713,6 +2598,7 @@ public class Client implements IThreadListener { if(Client.this.lastTickTime >= 0) { Client.this.performAction(Action.STOP_PROFILING); Client.this.lastTickTime = -1; + Client.this.tickInfo = null; } else { Client.this.performAction(Action.START_PROFILING); @@ -2720,26 +2606,6 @@ public class Client implements IThreadListener { } } }); - if(Util.DEVMODE) - this.registerDebug(Keysym.AE, "Programm sofort beenden und server beenden", new DebugRunner() { - public void execute(Keysym key) { - if(Client.this.getNetHandler() != null) { - Client.this.getNetHandler().getConnection().sendPacket(new CPacketMessage(CPacketMessage.Type.COMMAND, "shutdown"), new GenericFutureListener>() { - public void operationComplete(Future u) throws Exception { - try { - Thread.sleep(1000L); - } - catch(InterruptedException e) { - } - Client.this.interrupted = true; - } - }); - } - else { - Client.this.interrupted = true; - } - } - }); } private boolean handleDebugKey(Keysym key) { @@ -2757,22 +2623,13 @@ public class Client implements IThreadListener { public static void main(String[] args) { - long time = System.currentTimeMillis(); - Util.checkPlatform(); - Thread.currentThread().setName("Render thread"); - Locale.setDefault(Locale.ROOT); - Util.setupHandlers(); - Log.init(); - Log.SYSTEM.info("Java " + System.getProperty("java.version")); - Log.SYSTEM.info("Starte " + VERSION + " (Protokoll #" + Util.PROTOCOL + ")"); - if(Util.DEVMODE) - Log.SYSTEM.warn("Entwicklungsmodus aktiv - Debugging-Features sind verfügbar"); + Util.checkOs(); + Log.init(CLIENT); Window.init(); ModelBlock.setAsProvider(); - Registry.register(); + Registry.setup("Render thread"); UniverseRegistry.register(); - Log.setSync(CLIENT); - CLIENT.run(time); + CLIENT.run(); Window.end(); } @@ -2832,6 +2689,26 @@ public class Client implements IThreadListener { return data; } + // plr_play("/home/sen/Musik/midi50k/Video_Games/ff/ff2cecil.mid", 0); + public static void meltdown() { + Random rand = new Random(); + Log.SYSTEM.error("CORE_MELTDOWN: Nuclear processor core meltdown imminent\n\n" + + " ************************ CAUTION ************************\n" + + " KCTL: Processor core #%02d has reached a critical\n" + + " temperature, system explosion is imminent! \n" + + " According to the general core density \n" + + " calculation routine defined by the SKC \n" + + " (Hard) Warfare Testing Facility (SKC-WTF) \n" + + " your processor will cause a detonation with \n" + + " a radius of (roughly) %d.%d kilometers. \n" + + " In addition, it will release appoximately \n" + + " %d megajoules of ionizing radiation. \n" + + " You have an estimate time of %d minutes and \n" + + " %d seconds left to clear the detonation area. \n" + + " ************************ CAUTION ************************\n" + , rand.range(1, 64), rand.range(1, 9), rand.range(0, 9), rand.range(10000, 39999), rand.range(3, 9), rand.range(2, 59)); + } + public T getVar(String name) { return (T)cvars.get(name); } @@ -2852,14 +2729,6 @@ public class Client implements IThreadListener { return buffer; } - public float getTickFraction() { - return (float)this.tick_fraction; - } - - public long getPassedTime() { - return this.tmr_delta; - } - private void regVar(CVar cv) { if(cvars.containsKey(cv.getCVarName())) throw new IllegalArgumentException("Variable " + cv.getCVarName() + " existiert bereits!"); @@ -2944,7 +2813,7 @@ public class Client implements IThreadListener { data = FileUtils.read(config); } catch(IOException e) { - Log.IO.error(e, "Konnte Konfigurationsdatei nicht laden"); + Log.CONSOLE.error(e, "Konnte Konfigurationsdatei nicht laden"); return; } if(data == null) @@ -2981,7 +2850,7 @@ public class Client implements IThreadListener { FileUtils.write(config, sb.toString()); } catch(IOException e) { - Log.IO.error(e, "Konnte Konfigurationsdatei nicht speichern"); + Log.CONSOLE.error(e, "Konnte Konfigurationsdatei nicht speichern"); } } @@ -3028,7 +2897,7 @@ public class Client implements IThreadListener { } public void reset() { - this.buffer = TextColor.NEON + "*** " + VERSION + " ***"; + this.buffer = TextColor.NEON + "*** " + Config.CLIENT_VERSION + " ***"; this.console.clear(); this.chat.clear(); this.feed.clear(); @@ -3075,7 +2944,7 @@ public class Client implements IThreadListener { Log.CONSOLE.user(msg); if(size > 0) { for(String line : msg.split("\n")) { - Message lmsg = new Message(line, this.tmr_current); + Message lmsg = new Message(line, Timing.tmr_current); while(log.size() >= size) { log.remove(log.size() - 1); } @@ -3123,13 +2992,13 @@ public class Client implements IThreadListener { y = up ? y - Font.YGLYPH : y; for(Iterator iter = log.iterator(); iter.hasNext();) { Message msg = iter.next(); - if((this.tmr_current - msg.time()) <= fade || (log == this.chat && this.chatPermanent)) { + if((Timing.tmr_current - msg.time) <= fade || (log == this.chat && this.chatPermanent)) { if(align > 0) - Drawing.drawTextbox(msg.message(), x, y, bg); + Drawing.drawTextbox(msg.message, x, y, bg); else if(align < 0) - Drawing.drawTextboxRight(msg.message(), x, y, bg); + Drawing.drawTextboxRight(msg.message, x, y, bg); else - Drawing.drawTextboxCentered(msg.message(), x, y, bg); + Drawing.drawTextboxCentered(msg.message, x, y, bg); y += up ? -(Font.YGLYPH) : Font.YGLYPH; } else { @@ -3202,17 +3071,18 @@ public class Client implements IThreadListener { public void drawInfo() { ClientPlayer netHandler = this.getNetHandler(); if(netHandler != null) { - int size = this.playerList.size(); + Set> list = netHandler.getPlayerList(); + int size = list.size(); int w = size > 80 ? 4 : (size > 40 ? 3 : (size > 10 ? 2 : 1)); w = Math.min(w, Math.max(1, this.fb_x / 300)); int bx = 0; int by = 0; - for(Entry elem : this.playerList.entrySet()) { + for(Entry elem : list) { int x = this.fb_x / 2 - (w * 300) / 2 + bx * 300; - int y = 10 + by * (Font.YGLYPH + 2); - Drawing.drawGradient(x, y, 300, Font.YGLYPH + 2, 0x7f404040, 0x7f000000); - Drawing.drawText(elem.getKey(), x + 4, y + 1, 0xffffffff); - Drawing.drawTextRight(formatPing(elem.getValue()), x + 300 - 4, y + 1, 0xffffffff); + int y = 10 + by * Font.YGLYPH; + Drawing.drawGradient(x, y, 300, Font.YGLYPH, 0x7f404040, 0x7f000000); + Drawing.drawText(elem.getKey(), x + 4, y, 0xffffffff); + Drawing.drawTextRight(formatPing(elem.getValue()), x + 300 - 4, y, 0xffffffff); if(++bx >= w) { bx = 0; ++by; diff --git a/client/src/main/java/client/util/PerfSection.java b/client/src/client/PerfSection.java similarity index 97% rename from client/src/main/java/client/util/PerfSection.java rename to client/src/client/PerfSection.java index 9938445..ba9599f 100644 --- a/client/src/main/java/client/util/PerfSection.java +++ b/client/src/client/PerfSection.java @@ -1,4 +1,4 @@ -package client.util; +package client; import common.util.Util; diff --git a/client/src/client/PlayerController.java b/client/src/client/PlayerController.java new file mode 100755 index 0000000..a06986e --- /dev/null +++ b/client/src/client/PlayerController.java @@ -0,0 +1,603 @@ +package client; + +import client.network.ClientPlayer; +import client.world.WorldClient; +import common.block.Block; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.init.BlockRegistry; +import common.init.EntityRegistry; +import common.item.ItemBlock; +import common.item.ItemControl; +import common.item.ItemStack; +import common.material.Material; +import common.packet.CPacketAction; +import common.packet.CPacketBreak; +import common.packet.CPacketClick; +import common.packet.CPacketPlace; +import common.sound.PositionedSound; +import common.util.BlockPos; +import common.util.Facing; +import common.util.Vec3; +import common.world.State; +import common.world.World; + +public class PlayerController +{ + private final Client gm; + private final ClientPlayer netClientHandler; + private BlockPos currentBlock = new BlockPos(-1, -1, -1); + private ItemStack currentItemHittingBlock; + private float curBlockDamageMP; + private float stepSoundTickCounter; + private int blockHitDelay; + private boolean isHittingBlock; + private boolean noclip; + private int currentPlayerItem; + private boolean interacting; + + public PlayerController(Client gmIn, ClientPlayer netHandler) + { + this.gm = gmIn; + this.netClientHandler = netHandler; + } + +// public static void clickBlockCreative(Game gmIn, PlayerController playerController, BlockPos pos, Facing facing) +// { +// if (!gmIn.theWorld.extinguishFire(gmIn.thePlayer, pos, facing)) +// { +// playerController.onPlayerDestroyBlock(pos, facing); +// } +// } + +// public void setPlayerCapabilities() +// { +// this.gm.thePlayer.flying &= this.gm.thePlayer.hasEffect(Potion.flying) || this.gm.thePlayer.noclip; +// } + +// public boolean isNoclip() +// { +// return this.gm.thePlayer.capabilities.noClip; +// } + +// public void setNoclip(boolean noclip) +// { +// this.noclip = noclip; +// } + +// public void setCheat(boolean cheat) +// { +// this.cheat = cheat; +// this.setPlayerCapabilities(); +// } + + + +// public boolean shouldDrawHUD() +// { +// return !this.creative; +// } + + /** + * Called when a player completes the destruction of a block + */ + public boolean onPlayerDestroyBlock(BlockPos pos, Facing side) + { +// if (this.gamemode.isAdventure()) +// { +// if (this.gamemode == Gamemode.SPECTATOR) +// { +// return false; +// } + +// if (!this.gm.thePlayer.isAllowEdit()) +// { +// Block block = this.gm.theWorld.getBlockState(pos).getBlock(); +// ItemStack itemstack = this.gm.thePlayer.getCurrentEquippedItem(); +// +// if (itemstack == null) +// { +// return false; +// } +// +// if (!itemstack.canDestroy(block)) +// { +// return false; +// } +// } +// } + +// if (this.gm.thePlayer.getHeldItem() != null && !this.gm.thePlayer.getHeldItem().getItem().canBreakBlocks()) +// { +// return false; +// } +// else +// { + World world = this.gm.world; + State iblockstate = world.getState(pos); + Block block1 = iblockstate.getBlock(); + + if (block1.getMaterial() == Material.air) + { + return false; + } + else + { + world.playAuxSFX(2001, pos, BlockRegistry.getStateId(iblockstate)); + boolean flag = world.setBlockToAir(pos); + + if (flag) + { + block1.onBlockDestroyedByPlayer(world, pos, iblockstate); + } + + this.currentBlock = new BlockPos(this.currentBlock.getX(), -1, this.currentBlock.getZ()); + +// if (!this.creative) +// { + ItemStack itemstack1 = this.gm.player.getCurrentEquippedItem(); + + if (itemstack1 != null) + { + itemstack1.onBlockDestroyed(world, block1, pos, this.gm.player); + + if (itemstack1.stackSize == 0) + { + this.gm.player.destroyCurrentEquippedItem(); + } + } +// } + + return flag; + } +// } + } + + /** + * Called when the player is hitting a block with an item. + */ + public boolean clickBlock(BlockPos loc, Facing face) + { +// if (this.gamemode.isAdventure()) +// { +// if (this.gamemode == Gamemode.SPECTATOR) +// { +// return false; +// } + +// if (!this.gm.thePlayer.isAllowEdit()) +// { +// Block block = this.gm.theWorld.getBlockState(loc).getBlock(); +// ItemStack itemstack = this.gm.thePlayer.getCurrentEquippedItem(); +// +// if (itemstack == null) +// { +// return false; +// } +// +// if (!itemstack.canDestroy(block)) +// { +// return false; +// } +// } +// } + + if (!World.isValidXZ(loc)) + { + return false; + } + else + { + ItemStack stack = this.gm.player.getHeldItem(); + if(stack != null && stack.getItem().onAction(stack, this.gm.player, this.gm.world, ItemControl.PRIMARY, loc)) { + this.interacting = true; + this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, loc, face)); + return true; + } +// if (this.creative) +// { +// this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, loc, face)); +// clickBlockCreative(this.gm, this, loc, face); +// this.blockHitDelay = 5; +// } +// else + if (!this.isHittingBlock || !this.isHittingPosition(loc)) + { + if (this.isHittingBlock) + { + this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.ABORT_DESTROY_BLOCK, this.currentBlock, face)); + } + + this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, loc, face)); + Block block1 = this.gm.world.getState(loc).getBlock(); + boolean flag = block1.getMaterial() != Material.air; + + if (flag && this.curBlockDamageMP == 0.0F) + { + block1.onBlockClicked(this.gm.world, loc, this.gm.player); + } + + if (flag && block1.getPlayerRelativeBlockHardness(this.gm.player, this.gm.player.worldObj, loc) >= 1.0F) + { + this.onPlayerDestroyBlock(loc, face); +// if(this.cheat && block1.getPlayerRelativeBlockHardness(this.gm.thePlayer, this.gm.thePlayer.worldObj, loc) < 1.0F) + this.blockHitDelay = 3; + } + else + { + this.isHittingBlock = true; + this.currentBlock = loc; + this.currentItemHittingBlock = this.gm.player.getHeldItem(); + this.curBlockDamageMP = 0.0F; + this.stepSoundTickCounter = 0.0F; + this.gm.world.sendBlockBreakProgress(this.gm.player.getId(), this.currentBlock, (int)(this.curBlockDamageMP * 10.0F) - 1); + } + } + + return true; + } + } + + /** + * Resets current block damage and isHittingBlock + */ + public void resetBlockRemoving() + { + if (this.isHittingBlock) + { + this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.ABORT_DESTROY_BLOCK, this.currentBlock, Facing.DOWN)); + this.isHittingBlock = false; + this.curBlockDamageMP = 0.0F; + this.gm.world.sendBlockBreakProgress(this.gm.player.getId(), this.currentBlock, -1); + } + } + + public void resetInteraction() + { + this.interacting = false; + } + + public boolean onPlayerDamageBlock(BlockPos posBlock, Facing directionFacing) + { + if(this.interacting) + return false; + this.syncCurrentPlayItem(); + + if (this.blockHitDelay > 0) + { + --this.blockHitDelay; + return true; + } +// else if (this.creative && World.isValidXZ(posBlock)) +// { +// this.blockHitDelay = 5; +// this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, posBlock, directionFacing)); +// clickBlockCreative(this.gm, this, posBlock, directionFacing); +// return true; +// } + else if (this.isHittingPosition(posBlock)) + { + Block block = this.gm.world.getState(posBlock).getBlock(); + + if (block.getMaterial() == Material.air) + { + this.isHittingBlock = false; + return false; + } + else + { + this.curBlockDamageMP += block.getPlayerRelativeBlockHardness(this.gm.player, this.gm.player.worldObj, posBlock); + + if (this.stepSoundTickCounter % 4.0F == 0.0F && block.sound.getStepSound() != null) + { + this.gm.getSoundManager().playSound(new PositionedSound(block.sound.getStepSound(), 0.25F, /* block.sound.getFrequency() * 0.5F, */ (float)posBlock.getX() + 0.5F, (float)posBlock.getY() + 0.5F, (float)posBlock.getZ() + 0.5F)); + } + + ++this.stepSoundTickCounter; + + if (this.curBlockDamageMP >= 1.0F) + { + this.isHittingBlock = false; + this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.STOP_DESTROY_BLOCK, posBlock, directionFacing)); + this.onPlayerDestroyBlock(posBlock, directionFacing); + this.curBlockDamageMP = 0.0F; + this.stepSoundTickCounter = 0.0F; + this.blockHitDelay = 5; + } + + this.gm.world.sendBlockBreakProgress(this.gm.player.getId(), this.currentBlock, (int)(this.curBlockDamageMP * 10.0F) - 1); + return true; + } + } + else + { + return this.clickBlock(posBlock, directionFacing); + } + } + +// /** +// * player reach distance = 4F +// */ +// public float getBlockReachDistance() +// { +// return ; +// } + + public void updateController() + { + this.syncCurrentPlayItem(); + + if (this.netClientHandler.getNetworkManager().isChannelOpen()) + { + this.netClientHandler.getNetworkManager().processReceivedPackets(); + } + else + { + this.netClientHandler.getNetworkManager().checkDisconnected(); + } + } + + private boolean isHittingPosition(BlockPos pos) + { + ItemStack itemstack = this.gm.player.getHeldItem(); + boolean flag = this.currentItemHittingBlock == null && itemstack == null; + + if (this.currentItemHittingBlock != null && itemstack != null) + { + flag = itemstack.getItem() == this.currentItemHittingBlock.getItem() && ItemStack.areItemStackTagsEqual(itemstack, this.currentItemHittingBlock) && (itemstack.isItemStackDamageable() || itemstack.getMetadata() == this.currentItemHittingBlock.getMetadata()); + } + + return pos.equals(this.currentBlock) && flag; + } + + /** + * Syncs the current player item with the server + */ + private void syncCurrentPlayItem() + { + int i = this.gm.player.inventory.currentItem; + + if (i != this.currentPlayerItem) + { + this.currentPlayerItem = i; + this.netClientHandler.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_ITEMSLOT, this.currentPlayerItem)); + } + } + + public boolean onPlayerRightClick(EntityNPC player, WorldClient worldIn, ItemStack heldStack, BlockPos hitPos, Facing side, Vec3 hitVec) + { + this.syncCurrentPlayItem(); + float f = (float)(hitVec.xCoord - (double)hitPos.getX()); + float f1 = (float)(hitVec.yCoord - (double)hitPos.getY()); + float f2 = (float)(hitVec.zCoord - (double)hitPos.getZ()); + boolean flag = false; + + if (!World.isValidXZ(hitPos)) + { + return false; + } + else + { + if(heldStack == null || !heldStack.getItem().onAction(heldStack, player, worldIn, ItemControl.SECONDARY, hitPos)) { +// if (this.gamemode != Gamemode.SPECTATOR) +// { + State iblockstate = worldIn.getState(hitPos); + + if ((!player.isSneaking() || player.getHeldItem() == null) // && (player.getHeldItem() == null || !player.getHeldItem().getItem().ignoresBlocks()) + && iblockstate.getBlock().onBlockActivated(worldIn, hitPos, iblockstate, player, side, f, f1, f2)) + { + flag = true; + } + + if (!flag && heldStack != null && heldStack.getItem() instanceof ItemBlock) + { + ItemBlock itemblock = (ItemBlock)heldStack.getItem(); + + if (!itemblock.canPlaceBlockOnSide(worldIn, hitPos, side, player, heldStack)) + { + return false; + } + } +// } + } + else { + heldStack.getItem().onItemUse(heldStack, player, worldIn, hitPos, side, f, f1, f2); + flag = true; + } + + this.netClientHandler.addToSendQueue(new CPacketPlace(hitPos, side.getIndex(), player.inventory.getCurrentItem(), f, f1, f2)); + + if (!flag) // && this.gamemode != Gamemode.SPECTATOR) + { + if (heldStack == null) + { + return false; + } +// else if (this.creative) +// { +// int i = heldStack.getMetadata(); +// int j = heldStack.stackSize; +// boolean flag1 = heldStack.onItemUse(player, worldIn, hitPos, side, f, f1, f2); +// heldStack.setItemDamage(i); +// heldStack.stackSize = j; +// return flag1; +// } + else + { + return heldStack.onItemUse(player, worldIn, hitPos, side, f, f1, f2); + } + } + else + { + return true; + } + } + } + + /** + * Notifies the server of things like consuming food, etc... + */ + public boolean sendUseItem(EntityNPC playerIn, World worldIn, ItemStack itemStackIn) + { +// if (this.gamemode == Gamemode.SPECTATOR) +// { +// return false; +// } +// else +// { + this.syncCurrentPlayItem(); + this.netClientHandler.addToSendQueue(new CPacketPlace(playerIn.inventory.getCurrentItem())); + int i = itemStackIn.stackSize; + ItemStack itemstack = itemStackIn.useItemRightClick(worldIn, playerIn); + + if (itemstack != itemStackIn || itemstack != null && itemstack.stackSize != i) + { + playerIn.inventory.mainInventory[playerIn.inventory.currentItem] = itemstack; + + if (itemstack.stackSize == 0) + { + playerIn.inventory.mainInventory[playerIn.inventory.currentItem] = null; + } + + return true; + } + else + { + return false; + } +// } + } + + public EntityNPC createPlayerEntity(WorldClient worldIn, int type) + { + EntityNPC player = (EntityNPC)EntityRegistry.createEntityByID(type, worldIn); + player.setClientPlayer(this.netClientHandler); + return player; + } + + /** + * Attacks an entity + */ + public void attackEntity(EntityNPC playerIn, Entity targetEntity) + { + this.syncCurrentPlayItem(); + this.netClientHandler.addToSendQueue(new CPacketAction(CPacketAction.Action.ATTACK, targetEntity.getId())); + +// if (this.gamemode != Gamemode.SPECTATOR) +// { + playerIn.attackTargetEntityWithCurrentItem(targetEntity); +// } + } + + /** + * Send packet to server - player is interacting with another entity (left click) + */ + public boolean interactWithEntitySendPacket(EntityNPC playerIn, Entity targetEntity) + { + this.syncCurrentPlayItem(); + this.netClientHandler.addToSendQueue(new CPacketAction(CPacketAction.Action.INTERACT, targetEntity.getId())); + return /* this.gamemode != Gamemode.SPECTATOR && */ playerIn.interactWith(targetEntity); + } + +// /** +// * Return true when the player rightclick on an entity +// * +// * @param player The player's instance +// * @param entityIn The entity clicked +// * @param movingObject The object clicked +// */ +// public boolean isPlayerRightClickingOnEntity(EntityNPC player, Entity entityIn, MovingObjectPosition movingObject) +// { +// this.syncCurrentPlayItem(); +// Vec3 vec3 = new Vec3(movingObject.hitVec.xCoord - entityIn.posX, movingObject.hitVec.yCoord - entityIn.posY, movingObject.hitVec.zCoord - entityIn.posZ); +// this.netClientHandler.addToSendQueue(new C02PacketUseEntity(entityIn, vec3)); +// return this.gamemode != Gamemode.SPECTATOR && entityIn.interactAt(player, vec3); +// } + + /** + * Handles slot clicks sends a packet to the server. + */ + public ItemStack windowClick(int windowId, int slotId, int mouseButtonClicked, int mode, EntityNPC playerIn) + { + short short1 = playerIn.openContainer.getNextTransactionID(playerIn.inventory); + ItemStack itemstack = playerIn.openContainer.slotClick(slotId, mouseButtonClicked, mode, playerIn); + this.netClientHandler.addToSendQueue(new CPacketClick(windowId, slotId, mouseButtonClicked, mode, itemstack, short1)); + return itemstack; + } + + /** + * GuiEnchantment uses this during multiplayer to tell PlayerControllerMP to send a packet indicating the + * enchantment action the player has taken. + * + * @param windowID The ID of the current window + * @param button The button id (enchantment selected) + */ + public void sendEnchantPacket(int windowID, int button) + { + this.netClientHandler.addToSendQueue(new CPacketAction(CPacketAction.Action.ENCHANT_ITEM, windowID | (button << 8))); + } + +// /** +// * Used in PlayerControllerMP to update the server with an ItemStack in a slot. +// */ +// public void sendCheatPacket(ItemStack itemStackIn, boolean full) +// { +// } + +// /** +// * Sends a Packet107 to the server to drop the item on the ground +// */ +// public void sendPacketDropItem(ItemStack itemStackIn) +// { +// if (this.creative && itemStackIn != null) +// { +// this.netClientHandler.addToSendQueue(new CPacketCreative(-1, itemStackIn)); +// } +// } + + public void onStoppedUsingItem(EntityNPC playerIn) + { + this.syncCurrentPlayItem(); + this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, Facing.DOWN)); + playerIn.stopUsingItem(); + } + + + +// /** +// * Checks if the player is not creative, used for checking if it should break a block instantly +// */ +// public boolean isNotCreative() +// { +// return !this.creative; +// } + +// /** +// * returns true if player is in creative mode +// */ +// public boolean isCreative() +// { +// return this.creative; +// } + +// /** +// * Checks if the player is riding a horse, used to chose the GUI to open +// */ +// public boolean isRidingHorse() +// { +// return ; +// } + +// public Gamemode getGamemode() +// { +// return this.gamemode; +// } + + /** + * Return isHittingBlock + */ + public boolean getIsHittingBlock() + { + return this.isHittingBlock; + } +} diff --git a/client/src/main/java/client/util/SkinConverter.java b/client/src/client/SkinConverter.java similarity index 95% rename from client/src/main/java/client/util/SkinConverter.java rename to client/src/client/SkinConverter.java index dffc049..6c7695e 100755 --- a/client/src/main/java/client/util/SkinConverter.java +++ b/client/src/client/SkinConverter.java @@ -1,4 +1,4 @@ -package client.util; +package client; import java.awt.Color; import java.awt.Graphics; @@ -171,20 +171,20 @@ public abstract class SkinConverter { img = ImageIO.read(source); } catch(IOException e) { - Log.IO.error(e, "Konnte kein Bild von " + source + " laden"); + Log.JNI.error(e, "Konnte kein Bild von " + source + " laden"); return false; } if(img == null) { - Log.IO.warn("Konnte kein Bild von " + source + " laden"); + Log.JNI.warn("Konnte kein Bild von " + source + " laden"); return false; } - Log.IO.info("Bild von " + source + " geladen"); + Log.JNI.info("Bild von " + source + " geladen"); if(img.getWidth() == 64 && img.getHeight() == 32) { img = convertSkin(img); - Log.IO.info("Skin " + source + " konvertiert"); + Log.JNI.info("Skin " + source + " konvertiert"); } else if(img.getWidth() != 64 || img.getHeight() != 64) { - Log.IO.warn("Falsche Bildgröße von " + source + ": " + img.getWidth() + "x" + img.getHeight()); + Log.JNI.warn("Falsche Bildgröße von " + source + ": " + img.getWidth() + "x" + img.getHeight()); return false; } String name = source.getName(); @@ -195,7 +195,7 @@ public abstract class SkinConverter { name = "skin"; if(slim) { img = convertSlim(img); - Log.IO.info("Skin " + source + " von 'Slim' konvertiert"); + Log.JNI.info("Skin " + source + " von 'Slim' konvertiert"); if(!name.startsWith("slim_")) name = "slim_" + name; } @@ -217,10 +217,10 @@ public abstract class SkinConverter { ImageIO.write(img, "png", file); } catch(Exception e) { - Log.IO.error(e, "Konnte Bild nicht speichern"); + Log.JNI.error(e, "Konnte Bild nicht speichern"); return false; } - Log.IO.info("Skin " + source + " gespeichert als " + file.getName()); + Log.JNI.info("Skin " + source + " gespeichert als " + file.getName()); return true; } diff --git a/client/src/client/Timing.java b/client/src/client/Timing.java new file mode 100644 index 0000000..96094f3 --- /dev/null +++ b/client/src/client/Timing.java @@ -0,0 +1,30 @@ +package client; + +public class Timing { + public static long tmr_timer; + public static long tmr_start; + public static long tmr_current; + public static long tmr_last; + + public static long tmr_delta; + public static long tmr_update; + public static long tmr_frames; + public static long tmr_iters; + + public static long tick_torun; + public static long tick_done; + public static long tick_total; + public static long tick_time; + public static long tick_stime; + public static long tick_ftime; + + public static long tick_ttime; + public static long tick_update; + + public static double tick_fraction; + public static float framerate; + public static float tickrate; + public static float fdelta; + public static int tickTarget; + public static int tickFrame; +} diff --git a/client/src/main/java/client/audio/AudioInterface.java b/client/src/client/audio/AudioInterface.java similarity index 97% rename from client/src/main/java/client/audio/AudioInterface.java rename to client/src/client/audio/AudioInterface.java index 47dbefd..2e7c105 100644 --- a/client/src/main/java/client/audio/AudioInterface.java +++ b/client/src/client/audio/AudioInterface.java @@ -11,6 +11,7 @@ import javax.sound.sampled.DataLine.Info; import common.collect.Lists; import common.log.Log; +import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; public class AudioInterface implements Runnable { @@ -137,12 +138,12 @@ public class AudioInterface implements Runnable { public void run() { AudioFormat format = new AudioFormat(Encoding.PCM_SIGNED, 48000, 16, 2, 2 * 2, 48000, false); - Info info = new Info(SourceDataLine.class, format, this.devbufsize == 0 ? AudioSystem.NOT_SPECIFIED : this.devbufsize); + Info info = new Info(SourceDataLine.class, format, this.devbufsize); try { this.line = (SourceDataLine)AudioSystem.getLine(info); - this.line.open(format, this.devbufsize == 0 ? AudioSystem.NOT_SPECIFIED : this.devbufsize); + this.line.open(format, this.devbufsize); } - catch(Exception e) { + catch(LineUnavailableException e) { this.line = null; Log.SOUND.error(e, "Konnte Audiogerät nicht öffnen"); } diff --git a/client/src/main/java/client/audio/CodecJOrbis.java b/client/src/client/audio/CodecJOrbis.java similarity index 100% rename from client/src/main/java/client/audio/CodecJOrbis.java rename to client/src/client/audio/CodecJOrbis.java diff --git a/client/src/main/java/client/audio/SoundManager.java b/client/src/client/audio/SoundManager.java similarity index 98% rename from client/src/main/java/client/audio/SoundManager.java rename to client/src/client/audio/SoundManager.java index b37eb87..6942153 100755 --- a/client/src/main/java/client/audio/SoundManager.java +++ b/client/src/client/audio/SoundManager.java @@ -11,7 +11,6 @@ import java.util.Map; import java.util.Map.Entry; import client.Client; -import client.util.FileUtils; import common.collect.BiMap; import common.collect.HashBiMap; import common.collect.Lists; @@ -23,6 +22,7 @@ import common.rng.Random; import common.sound.MovingSound; import common.sound.Sound; import common.util.ExtMath; +import common.util.FileUtils; public class SoundManager { private class Source { @@ -238,8 +238,8 @@ public class SoundManager { this.sources.put(s, new Source(getBuffer(sound.getSoundLocation()), Volume.getByType(sound.getChannelType()), sound.canRepeat(), s, sound.getXPosF(), sound.getYPosF(), sound.getZPosF(), sound.getAttenuationType(), attn, volume)); this.playingSoundsStopTime.put(s, this.playTime + 20); this.playingSounds.put(s, sound); - if (sound instanceof MovingSound moving) - this.tickableSounds.add(moving); + if (sound instanceof MovingSound) + this.tickableSounds.add((MovingSound)sound); } } diff --git a/client/src/main/java/client/audio/Volume.java b/client/src/client/audio/Volume.java similarity index 100% rename from client/src/main/java/client/audio/Volume.java rename to client/src/client/audio/Volume.java diff --git a/client/src/main/java/client/audio/jogg/Buffer.java b/client/src/client/audio/jogg/Buffer.java similarity index 100% rename from client/src/main/java/client/audio/jogg/Buffer.java rename to client/src/client/audio/jogg/Buffer.java diff --git a/client/src/main/java/client/audio/jogg/Packet.java b/client/src/client/audio/jogg/Packet.java similarity index 100% rename from client/src/main/java/client/audio/jogg/Packet.java rename to client/src/client/audio/jogg/Packet.java diff --git a/client/src/main/java/client/audio/jogg/Page.java b/client/src/client/audio/jogg/Page.java similarity index 100% rename from client/src/main/java/client/audio/jogg/Page.java rename to client/src/client/audio/jogg/Page.java diff --git a/client/src/main/java/client/audio/jogg/StreamState.java b/client/src/client/audio/jogg/StreamState.java similarity index 100% rename from client/src/main/java/client/audio/jogg/StreamState.java rename to client/src/client/audio/jogg/StreamState.java diff --git a/client/src/main/java/client/audio/jogg/SyncState.java b/client/src/client/audio/jogg/SyncState.java similarity index 100% rename from client/src/main/java/client/audio/jogg/SyncState.java rename to client/src/client/audio/jogg/SyncState.java diff --git a/client/src/main/java/client/audio/jorbis/Block.java b/client/src/client/audio/jorbis/Block.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Block.java rename to client/src/client/audio/jorbis/Block.java diff --git a/client/src/main/java/client/audio/jorbis/ChainingExample.java b/client/src/client/audio/jorbis/ChainingExample.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/ChainingExample.java rename to client/src/client/audio/jorbis/ChainingExample.java diff --git a/client/src/main/java/client/audio/jorbis/CodeBook.java b/client/src/client/audio/jorbis/CodeBook.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/CodeBook.java rename to client/src/client/audio/jorbis/CodeBook.java diff --git a/client/src/main/java/client/audio/jorbis/Comment.java b/client/src/client/audio/jorbis/Comment.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Comment.java rename to client/src/client/audio/jorbis/Comment.java diff --git a/client/src/main/java/client/audio/jorbis/DecodeExample.java b/client/src/client/audio/jorbis/DecodeExample.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/DecodeExample.java rename to client/src/client/audio/jorbis/DecodeExample.java diff --git a/client/src/main/java/client/audio/jorbis/Drft.java b/client/src/client/audio/jorbis/Drft.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Drft.java rename to client/src/client/audio/jorbis/Drft.java diff --git a/client/src/main/java/client/audio/jorbis/DspState.java b/client/src/client/audio/jorbis/DspState.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/DspState.java rename to client/src/client/audio/jorbis/DspState.java diff --git a/client/src/main/java/client/audio/jorbis/Floor0.java b/client/src/client/audio/jorbis/Floor0.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Floor0.java rename to client/src/client/audio/jorbis/Floor0.java diff --git a/client/src/main/java/client/audio/jorbis/Floor1.java b/client/src/client/audio/jorbis/Floor1.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Floor1.java rename to client/src/client/audio/jorbis/Floor1.java diff --git a/client/src/main/java/client/audio/jorbis/FuncFloor.java b/client/src/client/audio/jorbis/FuncFloor.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/FuncFloor.java rename to client/src/client/audio/jorbis/FuncFloor.java diff --git a/client/src/main/java/client/audio/jorbis/FuncMapping.java b/client/src/client/audio/jorbis/FuncMapping.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/FuncMapping.java rename to client/src/client/audio/jorbis/FuncMapping.java diff --git a/client/src/main/java/client/audio/jorbis/FuncResidue.java b/client/src/client/audio/jorbis/FuncResidue.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/FuncResidue.java rename to client/src/client/audio/jorbis/FuncResidue.java diff --git a/client/src/main/java/client/audio/jorbis/FuncTime.java b/client/src/client/audio/jorbis/FuncTime.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/FuncTime.java rename to client/src/client/audio/jorbis/FuncTime.java diff --git a/client/src/main/java/client/audio/jorbis/Info.java b/client/src/client/audio/jorbis/Info.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Info.java rename to client/src/client/audio/jorbis/Info.java diff --git a/client/src/main/java/client/audio/jorbis/InfoMode.java b/client/src/client/audio/jorbis/InfoMode.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/InfoMode.java rename to client/src/client/audio/jorbis/InfoMode.java diff --git a/client/src/main/java/client/audio/jorbis/JOrbisException.java b/client/src/client/audio/jorbis/JOrbisException.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/JOrbisException.java rename to client/src/client/audio/jorbis/JOrbisException.java diff --git a/client/src/main/java/client/audio/jorbis/Lookup.java b/client/src/client/audio/jorbis/Lookup.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Lookup.java rename to client/src/client/audio/jorbis/Lookup.java diff --git a/client/src/main/java/client/audio/jorbis/Lpc.java b/client/src/client/audio/jorbis/Lpc.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Lpc.java rename to client/src/client/audio/jorbis/Lpc.java diff --git a/client/src/main/java/client/audio/jorbis/Lsp.java b/client/src/client/audio/jorbis/Lsp.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Lsp.java rename to client/src/client/audio/jorbis/Lsp.java diff --git a/client/src/main/java/client/audio/jorbis/Mapping0.java b/client/src/client/audio/jorbis/Mapping0.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Mapping0.java rename to client/src/client/audio/jorbis/Mapping0.java diff --git a/client/src/main/java/client/audio/jorbis/Mdct.java b/client/src/client/audio/jorbis/Mdct.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Mdct.java rename to client/src/client/audio/jorbis/Mdct.java diff --git a/client/src/main/java/client/audio/jorbis/PsyInfo.java b/client/src/client/audio/jorbis/PsyInfo.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/PsyInfo.java rename to client/src/client/audio/jorbis/PsyInfo.java diff --git a/client/src/main/java/client/audio/jorbis/PsyLook.java b/client/src/client/audio/jorbis/PsyLook.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/PsyLook.java rename to client/src/client/audio/jorbis/PsyLook.java diff --git a/client/src/main/java/client/audio/jorbis/Residue0.java b/client/src/client/audio/jorbis/Residue0.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Residue0.java rename to client/src/client/audio/jorbis/Residue0.java diff --git a/client/src/main/java/client/audio/jorbis/Residue1.java b/client/src/client/audio/jorbis/Residue1.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Residue1.java rename to client/src/client/audio/jorbis/Residue1.java diff --git a/client/src/main/java/client/audio/jorbis/Residue2.java b/client/src/client/audio/jorbis/Residue2.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Residue2.java rename to client/src/client/audio/jorbis/Residue2.java diff --git a/client/src/main/java/client/audio/jorbis/StaticCodeBook.java b/client/src/client/audio/jorbis/StaticCodeBook.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/StaticCodeBook.java rename to client/src/client/audio/jorbis/StaticCodeBook.java diff --git a/client/src/main/java/client/audio/jorbis/Time0.java b/client/src/client/audio/jorbis/Time0.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Time0.java rename to client/src/client/audio/jorbis/Time0.java diff --git a/client/src/main/java/client/audio/jorbis/Util.java b/client/src/client/audio/jorbis/Util.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/Util.java rename to client/src/client/audio/jorbis/Util.java diff --git a/client/src/main/java/client/audio/jorbis/VorbisFile.java b/client/src/client/audio/jorbis/VorbisFile.java similarity index 100% rename from client/src/main/java/client/audio/jorbis/VorbisFile.java rename to client/src/client/audio/jorbis/VorbisFile.java diff --git a/client/src/main/java/client/gui/FileCallback.java b/client/src/client/gui/FileCallback.java similarity index 100% rename from client/src/main/java/client/gui/FileCallback.java rename to client/src/client/gui/FileCallback.java diff --git a/client/src/main/java/client/gui/Font.java b/client/src/client/gui/Font.java similarity index 92% rename from client/src/main/java/client/gui/Font.java rename to client/src/client/gui/Font.java index 2ddfabe..51fa18b 100644 --- a/client/src/main/java/client/gui/Font.java +++ b/client/src/client/gui/Font.java @@ -8,14 +8,13 @@ import org.lwjgl.opengl.GL11; import client.renderer.GlState; import client.renderer.texture.TextureUtil; -import client.util.FileUtils; import common.log.Log; +import common.util.FileUtils; public class Font { public static final FontChar[] SIZES = new FontChar[256]; - - public static int XGLYPH = 12; - public static int YGLYPH = 14; + public static final int XGLYPH = 12; + public static final int YGLYPH = 18; private static int texture; @@ -73,12 +72,10 @@ public class Font { } } - public static void load(boolean tiny) { - XGLYPH = tiny ? 6 : 12; - YGLYPH = tiny ? 7 : 14; + public static void load() { BufferedImage img = null; try { - img = TextureUtil.readImage(FileUtils.getResource("textures/font" + (tiny ? "_tiny" : "") + ".png")); + img = TextureUtil.readImage(FileUtils.getResource("textures/font.png")); } catch(FileNotFoundException e) { Log.IO.error("Konnte Font-Textur nicht laden: Datei nicht vorhanden"); diff --git a/client/src/main/java/client/gui/FontChar.java b/client/src/client/gui/FontChar.java similarity index 100% rename from client/src/main/java/client/gui/FontChar.java rename to client/src/client/gui/FontChar.java diff --git a/client/src/main/java/client/gui/Formatter.java b/client/src/client/gui/Formatter.java similarity index 100% rename from client/src/main/java/client/gui/Formatter.java rename to client/src/client/gui/Formatter.java diff --git a/client/src/main/java/client/gui/Gui.java b/client/src/client/gui/Gui.java similarity index 98% rename from client/src/main/java/client/gui/Gui.java rename to client/src/client/gui/Gui.java index b8e4fbf..73628a8 100644 --- a/client/src/main/java/client/gui/Gui.java +++ b/client/src/client/gui/Gui.java @@ -16,7 +16,7 @@ import client.window.Keysym; import common.collect.Lists; public abstract class Gui { - public static final String BACKGROUND = "textures/background.png"; + public static final String DIRT_BACKGROUND = "textures/background.png"; public static final int HOVER_COLOR = 0x288080ff; public static final int PRESS_COLOR = 0x30afafff; @@ -176,8 +176,8 @@ public abstract class Gui { this.min_y = Math.min(this.min_y, elem.getY()); this.max_x = Math.max(this.max_x, elem.getX() + elem.getWidth()); this.max_y = Math.max(this.max_y, elem.getY() + elem.getHeight()); - if(elem instanceof Dropdown drop) - this.add(drop.getHandle()); + if(elem instanceof Dropdown) + this.add(((Dropdown)elem).getHandle()); return elem; } @@ -307,7 +307,7 @@ public abstract class Gui { Drawing.drawGradient(0, 0, this.gm.fb_x, this.gm.fb_y, 0xc0101010, 0xd0101010); } else { - Drawing.drawScaled(this.gm, BACKGROUND); + Drawing.drawScaled(this.gm, DIRT_BACKGROUND); } } diff --git a/client/src/main/java/client/gui/GuiConfirm.java b/client/src/client/gui/GuiConfirm.java similarity index 62% rename from client/src/main/java/client/gui/GuiConfirm.java rename to client/src/client/gui/GuiConfirm.java index 6e0d288..901117c 100755 --- a/client/src/main/java/client/gui/GuiConfirm.java +++ b/client/src/client/gui/GuiConfirm.java @@ -3,20 +3,19 @@ package client.gui; import client.gui.element.ActButton; import client.gui.element.ButtonCallback; import client.gui.element.Label; -import client.gui.element.MultiLabel; import client.gui.element.PressType; +import client.gui.element.TransparentArea; public class GuiConfirm extends Gui implements ButtonCallback { public static interface Callback { void confirm(boolean confirmed); } - private final Callback callback; - private final String messageLine1; - private final String messageLine2; - private final String confirmButtonText; - private final String cancelButtonText; - + protected Callback callback; + protected String messageLine1; + private String messageLine2; + protected String confirmButtonText; + protected String cancelButtonText; private ActButton confirmBtn; private ActButton cancelBtn; @@ -29,10 +28,10 @@ public class GuiConfirm extends Gui implements ButtonCallback { } public void init(int width, int height) { - this.add(new Label(0, 0, 700, 0, this.messageLine1)); - this.add(new MultiLabel(0, 40, 700, 300, this.messageLine2, true)); - this.confirmBtn = this.add(new ActButton(100, 400, 245, 0, this, this.confirmButtonText)); - this.cancelBtn = this.add(new ActButton(355, 400, 245, 0, this, this.cancelButtonText)); + this.add(new Label(0, 0, 500, 24, this.messageLine1, true)); + this.add(new TransparentArea(0, 80, 500, 300, this.messageLine2, this.gm.world != null && !this.gm.charEditor)); + this.confirmBtn = this.add(new ActButton(48, 500, 200, 24, this, this.confirmButtonText)); + this.cancelBtn = this.add(new ActButton(252, 500, 200, 24, this, this.cancelButtonText)); this.shift(); } diff --git a/client/src/client/gui/GuiConnect.java b/client/src/client/gui/GuiConnect.java new file mode 100644 index 0000000..789fcf0 --- /dev/null +++ b/client/src/client/gui/GuiConnect.java @@ -0,0 +1,268 @@ +package client.gui; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; + +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.GuiList; +import client.gui.element.ListEntry; +import client.gui.element.NavButton; +import client.gui.element.PressType; +import client.renderer.Drawing; +import common.color.TextColor; +import common.init.Config; +import common.log.Log; +import common.network.IPlayer; +import common.util.FileUtils; +import common.util.Tuple; +import common.util.Util; + +public class GuiConnect extends GuiList implements ButtonCallback { + public class ServerInfo implements Comparable, ListEntry { + private String name; + private String address; + private int port; + private String user; + private String password; + private String access; + private long lastConnected; + + public ServerInfo(String name, String address, int port, String user, String password, String access, long lastConnected) { + this.name = name; + this.address = address; + this.port = port; + this.user = user; + this.password = password; + this.access = access; + this.lastConnected = lastConnected; + } + + public String getName() { + return this.name; + } + + public String getAddress() { + return this.address; + } + + public int getPort() { + return this.port; + } + + public String getUser() { + return this.user; + } + + public String getPassword() { + return this.password; + } + + public String getAccess() { + return this.access; + } + + public long getLastConnected() { + return this.lastConnected; + } + + public void setData(String name, String address, int port, String user, String password, String access) { + this.name = name; + this.address = address; + this.port = port; + this.user = user; + this.password = password; + this.access = access; + } + + public void setLastConnected() { + this.lastConnected = System.currentTimeMillis(); + } + + public int compareTo(ServerInfo comp) { + return this.lastConnected < comp.lastConnected ? 1 : (this.lastConnected > comp.lastConnected ? -1 : this.name.compareTo(comp.name)); + } + + public void select(boolean isDoubleClick, int mouseX, int mouseY) { + GuiConnect.this.selectButton.enabled = true; + GuiConnect.this.deleteButton.enabled = true; + GuiConnect.this.editButton.enabled = true; + GuiConnect.this.copyButton.enabled = true; + + if(isDoubleClick) { + GuiConnect.this.use(GuiConnect.this.selectButton, PressType.PRIMARY); + } + } + + public void draw(int x, int y, int mouseXIn, int mouseYIn, boolean hover) { + Drawing.drawText(this.name + TextColor.GRAY + " - " + TextColor.RESET + this.user, x + 2, y, 0xffffffff); + Drawing.drawText(this.address + TextColor.GRAY + " Port " + TextColor.RESET + this.port, x + 2, y + 18, 0xff808080); + Drawing.drawText("Zuletzt verbunden: " + (this.lastConnected == -1L ? "nie" : DATE_FORMAT.format(new Date(this.lastConnected))), x + 2, y + 18 + 16, 0xff808080); + } + } + + public static final GuiConnect INSTANCE = new GuiConnect(); + private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + private static final File SERVERS_FILE = new File("servers.cfg"); + + private ActButton deleteButton; + private ActButton selectButton; + private ActButton copyButton; + private ActButton editButton; + private ActButton createButton; + + private GuiConnect() { + } + + public void init(int width, int height) { + super.init(width, height); + this.setDimensions(width, height, 32, height - 32); + this.elements.clear(); + if(SERVERS_FILE.exists()) { + try { + String[] lines = FileUtils.read(SERVERS_FILE).split("\n"); + String name = ""; + String address = ""; + int port = -1; + String user = ""; + String password = ""; + String access = ""; + long time = -1L; + for(int z = 0; z <= lines.length; z++) { + String line = z == lines.length ? null : lines[z]; + if(line == null || (line.startsWith("[") && line.endsWith("]"))) { + if(!name.isEmpty() && !address.isEmpty() && !user.isEmpty() && user.length() < IPlayer.MAX_USER_LENGTH && IPlayer.isValidUser(user) && password.length() < IPlayer.MAX_PASS_LENGTH && access.length() < IPlayer.MAX_PASS_LENGTH && address.length() < 128 && name.length() < 128 && port >= 0 && port < 65536) + this.elements.add(new ServerInfo(name, address, port, user, password, access, time)); + if(line != null) { + address = ""; + port = -1; + user = ""; + password = ""; + access = ""; + time = -1L; + name = line.substring(1, line.length() - 1); + } + } + else { + Tuple value = Util.getKeyValue(line); + if(value.first.equals("address")) + address = value.second; + else if(value.first.equals("port")) + try { + port = Integer.parseInt(value.second); + } + catch(NumberFormatException e) { + } + else if(value.first.equals("user")) + user = value.second; + else if(value.first.equals("password")) + password = value.second; + else if(value.first.equals("access")) + access = value.second; + else if(value.first.equals("connected")) + try { + time = Long.parseLong(value.second); + } + catch(NumberFormatException e) { + } + } + } + Collections.sort(this.elements); + } + catch(Exception e) { + Log.IO.error("Konnte Serverliste nicht laden", e); + this.elements.clear(); + } + } + + this.add(this.selectButton = new ActButton(width / 2 - 383, height - 28, 150, 24, this, "Verbinden")); + this.add(this.createButton = new ActButton(width - 204, 4, 200, 24, this, "Server hinzufügen ...")); + this.add(this.deleteButton = new ActButton(width / 2 - 75, height - 28, 150, 24, this, "Löschen")); + this.add(this.editButton = new ActButton(width / 2 + 79, height - 28, 150, 24, this, "Bearbeiten")); + this.add(this.copyButton = new ActButton(width / 2 - 229, height - 28, 150, 24, this, "Kopieren")); + this.add(new NavButton(width / 2 + 233, height - 28, 150, 24, GuiMenu.INSTANCE, "Abbrechen")); + + this.selectButton.enabled = false; + this.deleteButton.enabled = false; + this.editButton.enabled = false; + this.copyButton.enabled = false; + } + + public void onGuiClosed() { + this.save(); + } + + public void applyServer(ServerInfo server) { + if(this.selectedElement < 0) + this.elements.add(server); + this.save(); + this.gm.displayGuiScreen(this); + } + + private void save() { + try { + StringBuilder sb = new StringBuilder(); + for(ServerInfo server : this.elements) { + if(sb.length() > 0) + sb.append("\n"); + sb.append("[" + server.getName() + "]\n"); + sb.append("address " + server.getAddress() + "\n"); + sb.append("port " + server.getPort() + "\n"); + sb.append("user " + server.getUser() + "\n"); + sb.append("password " + server.getPassword() + "\n"); + sb.append("access " + server.getAccess() + "\n"); + sb.append("connected " + server.getLastConnected()); + } + FileUtils.write(SERVERS_FILE, sb.toString()); + } + catch(Exception e) { + Log.IO.error("Konnte Serverliste nicht speichern", e); + } + } + + public String getTitle() { + return "Server auswählen"; + } + + public int getListWidth() { + return 660; + } + + public int getSlotHeight() { + return 56; + } + + public void use(ActButton button, PressType mode) { + if(button == this.deleteButton) { + if(this.selectedElement >= 0) { + this.elements.remove(this.selectedElement); + this.gm.displayGuiScreen(this); + } + } + else if(button == this.selectButton) { + ServerInfo server = this.getSelected(); + if(server != null) { + server.setLastConnected(); + this.gm.connect(server.address, server.port, server.user, server.password, server.access); + } + } + else if(button == this.createButton) { + this.setSelected(-1); + this.gm.displayGuiScreen(new GuiServer(new ServerInfo("", "", Config.PORT, "", "", "", -1L))); + } + else if(button == this.editButton) { + ServerInfo server = this.getSelected(); + if(server != null) + this.gm.displayGuiScreen(new GuiServer(server)); + } + else if(button == this.copyButton) { + ServerInfo server = this.getSelected(); + if(server != null) { + this.setSelected(-1); + this.gm.displayGuiScreen(new GuiServer(new ServerInfo(server.name, server.address, server.port, server.user, server.password, server.access, -1L))); + } + } + } +} diff --git a/client/src/main/java/client/gui/GuiConsole.java b/client/src/client/gui/GuiConsole.java similarity index 94% rename from client/src/main/java/client/gui/GuiConsole.java rename to client/src/client/gui/GuiConsole.java index 673d90b..d3c6aca 100644 --- a/client/src/main/java/client/gui/GuiConsole.java +++ b/client/src/client/gui/GuiConsole.java @@ -5,12 +5,12 @@ import java.util.List; import client.Client; import client.gui.element.ActButton; import client.gui.element.ButtonCallback; -import client.gui.element.Element; import client.gui.element.Fill; import client.gui.element.PressType; import client.gui.element.FieldAction; import client.gui.element.Field; import client.gui.element.FieldCallback; +import client.network.ClientPlayer; import client.vars.BoolVar; import client.vars.CVar; import client.gui.element.TransparentArea; @@ -48,20 +48,20 @@ public class GuiConsole extends Gui implements FieldCallback { public void init(int width, int height) { if(this.full) { - this.addSelector("con_autoclose", 0, 0, 160, 0); - this.addSelector("con_timestamps", 160, 0, 160, 0); - this.addSelector("con_loglevel", 320, 0, 160, 0); - this.add(new ActButton(480, 0, 160, 0, new ButtonCallback() { + this.addSelector("con_autoclose", 0, 0, 160, 24); + this.addSelector("con_timestamps", 160, 0, 160, 24); + this.addSelector("con_loglevel", 320, 0, 160, 24); + this.add(new ActButton(480, 0, 160, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { GuiConsole.this.reset(); GuiConsole.this.setLog(GuiConsole.this.gm.getBuffer()); } }, "Löschen")); } - this.logBox = this.add(new TransparentArea(0, this.full ? Element.BASE_HEIGHT : 0, width, height - Element.BASE_HEIGHT * (this.full ? 2 : 1), this.gm.getBuffer(), this.gm.world != null && !this.gm.charEditor)); + this.logBox = this.add(new TransparentArea(0, this.full ? 24 : 0, width, height - (this.full ? 48 : 24), this.gm.getBuffer(), this.gm.world != null && !this.gm.charEditor)); if(this.full) - this.add(new Fill(640, 0, width - 640, 0)); - this.inputField = this.add(new Field(0, height - Element.BASE_HEIGHT, width, 0, IPlayer.MAX_CMD_LENGTH, this, "")); + this.add(new Fill(640, 0, width - 640, 24)); + this.inputField = this.add(new Field(0, height - 24, width, 24, IPlayer.MAX_CMD_LENGTH, this, "")); this.inputField.setSelected(); this.sentHistoryCursor = this.sentMessages.size(); } @@ -218,7 +218,7 @@ public class GuiConsole extends Gui implements FieldCallback { s = argv[argv.length - 1]; Iterable res = pre.startsWith("#") ? (argv.length == 1 ? this.gm.getVars() : (argv.length == 2 ? getVarCompletion(argv[0].substring(1)) : Lists.newArrayList())) : - (this.gm.player == null ? Lists.newArrayList() : this.gm.playerList.keySet()); + (this.gm.player == null ? Lists.newArrayList() : ((ClientPlayer)this.gm.player.client).getPlayerNames()); if(argv.length == 1 && pre.startsWith("#")) s = s.substring(1); for(String s1 : res) { diff --git a/client/src/main/java/client/gui/GuiInfo.java b/client/src/client/gui/GuiInfo.java similarity index 61% rename from client/src/main/java/client/gui/GuiInfo.java rename to client/src/client/gui/GuiInfo.java index 98f1b94..5653efb 100644 --- a/client/src/main/java/client/gui/GuiInfo.java +++ b/client/src/client/gui/GuiInfo.java @@ -1,35 +1,32 @@ package client.gui; -import client.Client; -import client.gui.element.MultiLabel; import client.gui.element.NavButton; -import common.Version; +import client.gui.element.TransparentArea; import common.color.TextColor; +import common.init.Config; import common.log.Log; -import common.util.Util; public class GuiInfo extends Gui { private static final String VER = - TextColor.GREEN + "" + Util.repeatString(TextColor.BUG, Version.RELEASE.getId()) + TextColor.DVIOLET + "|-| " + TextColor.VIOLET + Client.VERSION + TextColor.DVIOLET + " |-|" + - TextColor.GREEN + Util.repeatString(TextColor.BUG, Version.RELEASE.getId()); + TextColor.GREEN + "" + TextColor.BUG + "" + TextColor.BUG + "" + TextColor.BUG + " " + TextColor.VIOLET + "" + Config.CLIENT_VERSION + "" + + TextColor.GREEN + " " + TextColor.BUG + "" + TextColor.BUG + "" + TextColor.BUG; private static final String INFO = "Ein Spiel zur Simulation, zum Testen, für Rollenspiele, Mehrspieler und vieles mehr." + "\n" + "Optimiert für Geschwindigkeit, Stabilität und" + TextColor.UNKNOWN + "" + TextColor.UNKNOWN + " [Speicherzugriffsfehler]"; - private static final String HACKED = "Ein weiterer Release von WAAAAAAAAAAAAGHDRIVE!!!1!!!ONEoneOnetyone!1!!!" + "\n" + + private static final String HACKED = "Ein weiterer Release von WAAAAAAAAAAAAAAAAAAAAAAAAAAAAGHDRIVE!!!1!!!ONEoneOnetyone!1!!!" + "\n" + "Update 0.2 - Läuft jetzt auch mit nur 512KB Fast-RAM!"; private static final String[] LIBRARIES = { - "LWJGL 3.3.6", - "LWJGL-GLFW 3.3.6", - "LWJGL-OpenGL 3.3.6" + "LWJGL 3.3.6+1 (GLFW + OpenGL)", + "Netty 4.1.119-Final" }; private static final String[] CODE = { "Albert Pham - WorldEdit (Snippets)", "Joonas Vali - NameGenerator", "LWJGL 2.9.4-nightly-20150209 - Project, Vector*, Matrix*", "Guava 17.0 - collect, future, Predicates", - "Netty 4.0.23-Final - net.*", - "JOrbis 20101023 (JCraft) - jogg, jorbis, CodecJOrbis" + "JOrbis 20101023 (JCraft) - jogg, jorbis, CodecJOrbis", + "MC 1.8.9" }; public static final GuiInfo INSTANCE = new GuiInfo("Über dieses Programm", getFormat(false)); @@ -39,12 +36,12 @@ public class GuiInfo extends Gui { private final String info; private static String getFormat(boolean hax) { - return getInfo(hax) + "\n\n" + getCredits(hax) + "\n\n" + getLibraries(hax) + "\n\n" + getCode(hax) + "\n\n" + getColors(); + return getInfo(hax) + "\n\n" + getCredits(hax) + "\n\n" + getLibraries(hax) + "\n\n" + getCode(hax) + "\n\n" + getOldCredits(hax) + "\n\n" + getColors(); } private static String getHeader(boolean hax, String normal, String hacked) { return (hax ? TextColor.RED : TextColor.YELLOW) + (hax ? hacked : normal) + "\n" + - (hax ? TextColor.CYAN : TextColor.WHITE) + "==========================+=========================="; + (hax ? TextColor.CYAN : TextColor.WHITE) + "==========================================+=========================================="; } private static void addLines(StringBuilder sb, boolean hax, String alternate, String category, String... authors) { @@ -64,7 +61,7 @@ public class GuiInfo extends Gui { private static String getLibraries(boolean hax) { StringBuilder sb = new StringBuilder(getHeader(hax, "Verwendete Programmbibliotheken", "U$3d 3xpl0its")); for(String lib : LIBRARIES) { - sb.append("\n" + TextColor.NEON + lib); + sb.append("\n" + TextColor.LGRAY + "-> " + TextColor.NEON + lib); } return sb.toString(); } @@ -72,7 +69,7 @@ public class GuiInfo extends Gui { private static String getCode(boolean hax) { StringBuilder sb = new StringBuilder(getHeader(hax, "Zusätzlicher Quellcode", "M0ar 3xpl01ts")); for(String lib : CODE) { - sb.append("\n" + TextColor.NEON + lib); + sb.append("\n" + TextColor.LGRAY + "-> " + TextColor.NEON + lib); } return sb.toString(); } @@ -81,16 +78,37 @@ public class GuiInfo extends Gui { StringBuilder sb = new StringBuilder(); int num = 0; for(TextColor color : TextColor.values()) { - if(num == 14) - sb.append('\n'); + if(num > 0) + sb.append(' '); if((color.code >= Log.CHR_COLORS1 && color.code <= Log.CHR_COLORE1) || (color.code >= Log.CHR_COLORS2 && color.code <= Log.CHR_COLORE2)) { - sb.append(color + "#" + (char)(num < 10 ? ('0' + num) : ('A' + (num - 10))) + ' '); + sb.append(color + "#" + (char)(num < 10 ? ('0' + num) : ('A' + (num - 10)))); num++; } } return sb.toString(); } + private static String getOldCredits(boolean hax) { + StringBuilder sb = new StringBuilder(getHeader(hax, "Ursprüngliche Mitwirkende", "Das Team -- Nicht TCQ")); + + addLines(sb, hax, "Absolut größter Lamer des Universums", "Spielidee und ursprüngliche Umsetzung", + "Markus Persson"); + addLines(sb, hax, "Crack und weitere Programmierung", "Spiel-Design, Programmierung und Grafiken", + "Jens Bergensten", "Nathan Adams", "Ryan Holtz", "Michael Stoyke"); + addLines(sb, hax, "Entschlüsselung von Ressourcen", "Programmierung", + "Erik Broes", "Paul Spooner", "Ryan Hitchman", "Elliot Segal"); + addLines(sb, hax, "Cracktro, Grafiken und Intromusik", "Töne und Geräusche", + "Daniel Rosenfeld", "freesound.org"); + addLines(sb, hax, "Packing und Verbreitung", "Management, Administration und Spaß", + "Carl Manneh", "Daniel Kaplan", "Lydia Winters"); + addLines(sb, hax, "Server und Hosting", "Zahlen und Statistiken", + "Patrick Geuder"); + addLines(sb, hax, "Weiterer Dank und Grüße", "Entwickler von Mo' Creatures (Pferde usw.)", + "John Olarte", "Kent Christian Jensen", "Dan Roque"); + + return sb.toString(); + } + private static String getCredits(boolean hax) { StringBuilder sb = new StringBuilder(getHeader(hax, "Mitwirkende dieses Programms", "Das Team -- TCQ")); @@ -107,8 +125,8 @@ public class GuiInfo extends Gui { } public void init(int width, int height) { - this.add(new MultiLabel(10, 10, width - 20, height - 44, this.info, false)); - this.add(new NavButton((width - 280) / 2, height - 20, 280, 0, GuiMenu.INSTANCE, "Zurück")); + this.add(new TransparentArea(10, 10, width - 20, height - 44, this.info, this.gm.world != null && !this.gm.charEditor)); + this.add(new NavButton(0, height - 24, width, 24, GuiMenu.INSTANCE, "Zurück")); } public String getTitle() { diff --git a/client/src/main/java/client/gui/GuiLoading.java b/client/src/client/gui/GuiLoading.java similarity index 91% rename from client/src/main/java/client/gui/GuiLoading.java rename to client/src/client/gui/GuiLoading.java index 26f5b8a..f51592b 100644 --- a/client/src/main/java/client/gui/GuiLoading.java +++ b/client/src/client/gui/GuiLoading.java @@ -46,11 +46,11 @@ public class GuiLoading extends Gui { } public void init(int width, int height) { - this.taskLabel = this.add(new Label(0, 40, 500, 0, "")); - this.progressBar1 = this.add(new Bar(0, 80, 500, 0)); - this.progressBar2 = this.add(new Bar(0, 120, 500, 0)); + this.taskLabel = this.add(new Label(0, 40, 500, 20, "")); + this.progressBar1 = this.add(new Bar(0, 80, 500, 24)); + this.progressBar2 = this.add(new Bar(0, 120, 500, 24)); this.shift(); - this.headerLabel = this.add(new Label(0, 40, width, 0, this.message)); + this.headerLabel = this.add(new Label(0, 40, width, 20, this.message)); this.progressBar1.visible = false; this.progressBar2.visible = false; } diff --git a/client/src/main/java/client/gui/GuiMenu.java b/client/src/client/gui/GuiMenu.java similarity index 83% rename from client/src/main/java/client/gui/GuiMenu.java rename to client/src/client/gui/GuiMenu.java index 51fda9b..fd2093b 100644 --- a/client/src/main/java/client/gui/GuiMenu.java +++ b/client/src/client/gui/GuiMenu.java @@ -1,6 +1,6 @@ package client.gui; -import client.Client; +import client.Timing; import client.gui.character.GuiChar; import client.gui.character.GuiCharacters; import client.gui.element.ActButton; @@ -12,6 +12,7 @@ import client.gui.options.GuiOptions; import client.renderer.Drawing; import client.window.Keysym; import common.color.TextColor; +import common.init.Config; import common.rng.Random; import common.util.ExtMath; @@ -25,7 +26,7 @@ public class GuiMenu extends Gui { if(this.gm.world != null) super.drawMainBackground(); else - this.gm.renderGlobal.renderStarField(this.gm.fb_x, this.gm.fb_y, 0x000000, 0xffffff, (float)this.ticks + this.gm.getTickFraction(), this.rand); + this.gm.renderGlobal.renderStarField(this.gm.fb_x, this.gm.fb_y, 0x000000, 0xffffff, (float)this.ticks + (float)Timing.tick_fraction, this.rand); } private final Random rand = new Random(); @@ -51,12 +52,8 @@ public class GuiMenu extends Gui { this.ticks = 0; this.hacked = 0; this.resetAnimation(); - this.add(new ActButton(0, 0, 180, 0, new ButtonCallback() { + this.add(new ActButton(0, -28, 400, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { - if(action == PressType.SECONDARY) { - GuiMenu.this.gm.joinDebugWorld(); - return; - } if(GuiMenu.this.hacked == 9) { GuiMenu.this.hacked++; GuiMenu.this.splashLabel.setText(TextColor.VIOLET + "Hax!"); @@ -66,20 +63,20 @@ public class GuiMenu extends Gui { } } }, "Server beitreten")); - this.add(new ActButton(0, 20, 180, 0, new ButtonCallback() { + this.add(new NavButton(0, 0, 400, 24, GuiServer.INSTANCE, "Schnellverbindung")); + this.add(new ActButton(0, 28, 400, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { if(GuiMenu.this.hacked == 8) GuiMenu.this.hacked++; else - GuiMenu.this.gm.displayGuiScreen(GuiServer.INSTANCE); + GuiMenu.this.gm.displayGuiScreen(GuiOptions.getPage()); } - }, "Schnellverbindung")); - this.add(new NavButton(0, 40, 180, 0, GuiOptions.getPage(), "Einstellungen")); - this.infoButton = this.add(new ActButton(0, 60, 180, 0, new ButtonCallback() { + }, "Einstellungen")); + this.infoButton = this.add(new ActButton(0, 56, 400, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { GuiMenu.this.gm.displayGuiScreen(GuiMenu.this.hacked == 10 ? GuiInfo.HAX : GuiInfo.INSTANCE); } - }, "Info / Mitwirkende") { + }, "Info / Über / Mitwirkende") { public void drawHover() { if(GuiMenu.this.hacked == 10) { Drawing.drawRect(this.pos_x, this.pos_y, this.size_x, this.size_y, 0x287f00ff); @@ -87,9 +84,9 @@ public class GuiMenu extends Gui { int width = Drawing.getWidth("Hax!"); for(int z = 0; z < 64; z++) { Drawing.drawText("Hax!", GuiMenu.this.rand.zrange(Math.max(1, this.gm.fb_x - width)) + - (int)(ExtMath.sin(((float)(GuiMenu.this.ticks + GuiMenu.this.rand.zrange(256)) + this.gm.getTickFraction()) / 100.0f * (float)Math.PI * 2.0f) * 16.0f), + (int)(ExtMath.sin(((float)(GuiMenu.this.ticks + GuiMenu.this.rand.zrange(256)) + (float)Timing.tick_fraction) / 100.0f * (float)Math.PI * 2.0f) * 16.0f), GuiMenu.this.rand.zrange(Math.max(1, this.gm.fb_y - Font.YGLYPH)) + - (int)(ExtMath.sin(((float)(GuiMenu.this.ticks + GuiMenu.this.rand.zrange(256)) + this.gm.getTickFraction()) / 100.0f * (float)Math.PI * 2.0f) * 16.0f), + (int)(ExtMath.sin(((float)(GuiMenu.this.ticks + GuiMenu.this.rand.zrange(256)) + (float)Timing.tick_fraction) / 100.0f * (float)Math.PI * 2.0f) * 16.0f), 0xff0000ff | (GuiMenu.this.rand.zrange(256) << 16)); } } @@ -98,27 +95,27 @@ public class GuiMenu extends Gui { } } }); - this.add(new ActButton(0, 90, 180, 0, new ButtonCallback() { + this.add(new ActButton(0, 102, 400, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { GuiMenu.this.gm.interrupted = true; } }, "Client schließen")); this.shift(); - this.add(new Label(4, 4, 200, 0, TextColor.VIOLET + Client.VERSION, true)); - this.splashLabel = this.add(new Label(0, 100, width, 0, "")); + this.add(new Label(4, /* this.gm.fb_y - 2 */ 0, 200, 20, TextColor.VIOLET + Config.CLIENT_VERSION, true)); + this.splashLabel = this.add(new Label(0, 160, width, 24, "")); this.pickSplash(); } else { - this.add(new NavButton(0, 0, 180, 0, this.gm.charEditor ? GuiChar.INSTANCE : null, this.gm.charEditor ? "Zurück zum Editor" : "Zurück zum Spiel")); - this.add(new NavButton(0, 20, 180, 0, GuiOptions.getPage(), "Einstellungen")); + this.add(new NavButton(0, 0, 400, 24, this.gm.charEditor ? GuiChar.INSTANCE : null, this.gm.charEditor ? "Zurück zum Charakter-Editor" : "Zurück zum Spiel")); + this.add(new NavButton(0, 28, this.gm.charEditor ? 400 : 198, 24, GuiOptions.getPage(), "Einstellungen")); if(!this.gm.charEditor) - this.add(new NavButton(0, 40, 180, 0, GuiCharacters.INSTANCE, "Charakter")); - this.add(new ActButton(0, this.gm.charEditor ? 50 : 70, 180, 0, new ButtonCallback() { + this.add(new NavButton(202, 28, 198, 24, GuiCharacters.INSTANCE, "Charakter")); + this.add(new ActButton(0, 102, 400, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { GuiMenu.this.gm.unload(true); // GuiMenu.this.gm.displayGuiScreen(INSTANCE); } - }, "Server verlassen")); + }, "Server verlassen und Verbindung trennen")); this.shift(); } } @@ -292,7 +289,7 @@ public class GuiMenu extends Gui { public void drawOverlays() { super.drawOverlays(); if(this.gm.world == null) { - int y = 99; + int y = 164; int h = 16; int n = Drawing.getWidth(this.splashLabel.getText()); Drawing.drawRect(0, y, this.gm.fb_x / 2 - n / 2 - 10, h, 0x7f7f00ff); diff --git a/client/src/client/gui/GuiServer.java b/client/src/client/gui/GuiServer.java new file mode 100644 index 0000000..3cb509e --- /dev/null +++ b/client/src/client/gui/GuiServer.java @@ -0,0 +1,149 @@ +package client.gui; + +import client.gui.GuiConnect.ServerInfo; +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.Label; +import client.gui.element.NavButton; +import client.gui.element.PressType; +import client.gui.element.FieldAction; +import client.gui.element.Field; +import client.gui.element.FieldCallback; +import client.vars.CVarCategory; +import client.vars.Variable; +import common.color.TextColor; +import common.init.Config; +import common.network.IPlayer; + +public class GuiServer extends Gui implements FieldCallback { + public static final GuiServer INSTANCE = new GuiServer(null); + + private final ServerInfo server; + + private Field nameBox; + private Field addrBox; + private Field portBox; + private Field userBox; + private Field passBox; + private Field accBox; + private Label nameLabel; + private Label addrLabel; + private Label portLabel; + private Label userLabel; + private Label passLabel; + private Label accLabel; + + public GuiServer(ServerInfo server) { + this.server = server; + } + + @Variable(name = "srv_last_address", category = CVarCategory.SYSTEM, min = 1, max = 128, display = "Letzte Server-Adresse") + private String lastAddr = ""; + @Variable(name = "srv_last_port", category = CVarCategory.SYSTEM, min = 0, max = 65535, display = "Letzter Server-Port") + private int lastPort = Config.PORT; + @Variable(name = "srv_last_user", category = CVarCategory.SYSTEM, max = IPlayer.MAX_USER_LENGTH, display = "Letzter Server-Nutzer", validator = IPlayer.UserValidator.class) + private String lastUser = ""; + @Variable(name = "srv_last_password", category = CVarCategory.SYSTEM, max = IPlayer.MAX_PASS_LENGTH, display = "Letztes Server-Passwort") + private String lastPass = ""; + @Variable(name = "srv_last_access", category = CVarCategory.SYSTEM, max = IPlayer.MAX_PASS_LENGTH, display = "Letzter Server-Zugang") + private String lastAcc = ""; + + public void init(int width, int height) { + if(this.server != null) + this.nameBox = this.add(new Field(0, -50, 400, 24, 128, this, this.server.getName())); + this.addrBox = this.add(new Field(0, 20, 400, 24, 128, this, this.server == null ? this.lastAddr : this.server.getAddress())); + this.portBox = this.add(new Field(404, 20, 76, 24, 5, this, "" + (this.server == null ? this.lastPort : this.server.getPort()))); + this.userBox = this.add(new Field(0, 70, 220, 24, IPlayer.MAX_USER_LENGTH, this, IPlayer.VALID_USER, this.server == null ? this.lastUser : this.server.getUser())); + this.passBox = this.add(new Field(0, 120, 480, 24, IPlayer.MAX_PASS_LENGTH, this, this.server == null ? this.lastPass : this.server.getPassword())); + this.accBox = this.add(new Field(0, 170, 480, 24, IPlayer.MAX_PASS_LENGTH, this, this.server == null ? this.lastAcc : this.server.getAccess())); + this.add(new ActButton(0, 220, 480, 24, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + GuiServer.this.connect(); + } + }, this.server == null ? "Verbinden" : (this.server.getName().isEmpty() ? "Hinzufügen" : "Übernehmen"))); + this.add(new NavButton(0, 250, 480, 24, this.server != null ? GuiConnect.INSTANCE : GuiMenu.INSTANCE, "Zurück")); + if(this.server != null) + this.nameLabel = this.add(new Label(0, -70, 410, 20, "Name", true)); + this.addrLabel = this.add(new Label(0, 0, 410, 20, "Adresse", true)); + this.portLabel = this.add(new Label(414, 0, 66, 20, "Port", true)); + this.userLabel = this.add(new Label(0, 50, 220, 20, "Nutzer", true)); + this.passLabel = this.add(new Label(0, 100, 480, 20, "Passwort", true)); + this.accLabel = this.add(new Label(0, 150, 480, 20, "Zugang", true)); + this.shift(); + } + + public String getTitle() { + return this.server == null ? "Mit Server verbinden" : (this.server.getName().isEmpty() ? "Server hinzufügen" : "Server bearbeiten"); + } + + private void connect() { + if(this.gm.world != null) + return; + String name = null; + if(this.server != null) { + name = this.nameBox.getText(); + if(name.isEmpty()) { + this.nameLabel.setText(TextColor.RED + "Name"); + return; + } + } + String addr = this.addrBox.getText(); + if(addr.isEmpty()) { + this.addrLabel.setText(TextColor.RED + "Adresse"); + return; + } + int port = -1; + if(this.portBox.getText().isEmpty()) { + this.portLabel.setText(TextColor.RED + "Port"); + return; + } + else { + try { + port = Integer.parseInt(this.portBox.getText()); + } + catch(NumberFormatException e) { + } + if(port < 0 || port > 65535) { + this.portLabel.setText(TextColor.RED + "Port"); + return; + } + } + String user = this.userBox.getText(); + if(user.isEmpty()) { + this.userLabel.setText(TextColor.RED + "Nutzer"); + return; + } + String pass = this.passBox.getText(); + String acc = this.accBox.getText(); + if(this.server == null) { + this.lastAddr = addr; + this.lastPort = port; + this.lastUser = user; + this.lastPass = pass; + this.lastAcc = acc; + this.gm.setDirty(); + this.gm.connect(addr, port, user, pass, acc); + } + else { + this.server.setData(name, addr, port, user, pass, acc); + GuiConnect.INSTANCE.applyServer(this.server); + } + } + + public void use(Field elem, FieldAction value) { + if(value == FieldAction.SEND) { + elem.setDeselected(); + this.connect(); + } + else if(value == FieldAction.FOCUS) { + if(elem == this.addrBox) + this.addrLabel.setText("Adresse"); + else if(elem == this.portBox) + this.portLabel.setText("Port"); + else if(elem == this.userBox) + this.userLabel.setText("Nutzer"); + else if(this.server != null && elem == this.nameBox) + this.nameLabel.setText("Name"); + } + } +} diff --git a/client/src/main/java/client/gui/Splashes.java b/client/src/client/gui/Splashes.java similarity index 75% rename from client/src/main/java/client/gui/Splashes.java rename to client/src/client/gui/Splashes.java index de6257e..78711ab 100644 --- a/client/src/main/java/client/gui/Splashes.java +++ b/client/src/client/gui/Splashes.java @@ -2,34 +2,35 @@ package client.gui; public abstract class Splashes { public static final String[] SPLASHES = { - "Aus der Toiletten-Werbung!", + "Aus der TV-Werbung!", + "Toll!", "0% pur!", "Kann Nüsse enthalten!", - "Kann *.,-#+~ enthalten!", + "Besser als Crysis!", "Mehr Polygone!", "Sexy!", "Limitierte Edition!", "Blinkende Buchstaben!", - "Erstellt von Satan!", - "Er ist hier!", - "Das Schlimmste seiner Klasse!", - "Es ist vollendet (nicht)!", + "Erstellt von Notch!", + "Es ist hier!", + "Das Beste seiner Klasse!", + "Es ist vollendet!", "Mehr oder weniger frei von Drachen!", "Aufregung!", "Weniger als -5 verkauft!", "Einzigartig!", "Einen Haufen Scheiße auf YouTube!", - "Dev!", - "Alpha!", - "Beta!", + "Indev!", "Spinnen überall!", "Schau es dir an!", "Heilige Kuh, mann!", "Es ist ein Spiel!", - "Hergestellt im Schattenland!", + "Hergestellt in Schweden!", "Benutzt LWJGL!", "Retikulierende Splinen!", + "Meine Kraft!", "Hurraaa!", + "Einzelspieler!", "Tastatur ist kompatibel!", "Undokumentiert!", "Barren!", @@ -40,14 +41,17 @@ public abstract class Splashes { "Überlebe!", "Verlies!", "Exklusiv!", + "Die Knie der Biene!", + "Weg mit O.P.P.!", "Mit Quellcode (mehr oder weniger)!", "Mit Klasse(n)!", "Wow!", - "Niemals auf Steam - und das ist auch gut so!", + "Immer noch nicht auf Steam - und das ist auch gut so!", "Oh, mann!", "Grauenvolle Community!", "Pixel!", - "Garfiiieeeeeeeld!", + "Teetsuuuuoooo!", + "Kaaneeeedaaaa!", "Jetzt ohne Schwierigkeit!", "Verbessert!", "9% frei von Bugs!", @@ -55,26 +59,31 @@ public abstract class Splashes { "13 Kräuter und Gewürze!", "Fettfrei!", "Absolut keine Memes!", - "Kostenlose Vampirzähne!", + "Kostenlose Zähne!", "Fragen Sie Ihnen Arzt oder Apotheker!", "Alle Bergleute sind willkommen!", "Cloud-Computing!", - "Frei von \"\"KI\"\"!", - "Legal in Norwegen!", - "Illegal in China!", + "Legal in Finnland!", "Schwer zu beschreiben!", "Technisch gesehen gut!", + "Bringe den Speck nach Hause!", "Indie!", + "GOTY!", + "Ceci n'est pas une title screen!", "Euklidisch!", - "Jetzt in 4D?!", + "Jetzt in 3D!", "Bietet Inspiration!", + "Herregud!", + "Komplexe Zellvorgänge!", "Ja, Sir!", - "Ja, Miss!", - "Von Trollen gespielt!", + "Von Cowboys gespielt!", "OpenGL 1.5 oder höher!", - "Millionen von Farben!", + "Tausende von Farben!", "Probiere es!", + "Age of Wonders ist besser!", + "Probiere die Pilzsuppe!", "Sensationell!", + "Heiße Tamale, heiße heiße Tamale!", "Spiele ihn runter, Klavierkatze!", "Garantiert!", "Makroskopisch!", @@ -85,22 +94,27 @@ public abstract class Splashes { "Von Melonen geliebt!", "Ultimative Edition!", "Merkwürdig!", + "Du hast einen nagelneuen Schlüssel bekommen!", "Wasserfest!", "Nicht brennbar!", "Oha, du!", "Alles inklusive!", "Sag es deinen Freunden!", "NP ist nicht in P!", + "Musik von C418 (DLC)!", + "Viel zu oft live gestreamt!", "Heimgesucht!", "Polynomial!", "Terrestrisch!", "Alles ist voller Zerstörung!", "Voll mit Sternen, Planeten und Monden!", "Wissenschaftlich!", + "Nicht so cool wie Spock!", "Trage nix bei und höre weg!", "Grabe niemals nach unten, wenn du keine Erze brauchst!", "Mache nie Pause!", "Nicht linear!", + "Han hat zuerst geschossen!", "Schön dich zu sehen!", "Eimer mit Lava!", "Reite auf dem Schwein!", @@ -110,18 +124,25 @@ public abstract class Splashes { "Holz schlagen!", "Von Klippen fallen!", "0% Zucker!", - "180% Alkohol!", + "150% hyperbol!", + "Synecdoche!", "Lasst uns tanzne!", + "Geheeimes Freitags-Update!", "Referenz-Implementation!", "Frei mit zwei.. äähhh fünf Typen mit Essen!", "Küsse den Himmel!", "20 GOTO 10!", + "Verlet-Intregration!", + "Peter Griffin!", "Verteile die Erde gut!", - "8263273626252622872652 Zeilen Quellcode (287228 am 30.7.)!", + "Cogito ergo sum!", + "4815162342 Zeilen Quellcode (287228 am 30.7.)!", "Ein Skelett fiel heraus!", - "Das Werk von Luzifer!", + "Das Werk von Notch!", "Die Summe seiner Teile!", - "mureh srednA!", + "BTAF war mal gut!", + "Ich vermisse ADOM!", + "umop-apisdn!", "GTX750Ti!", "Bringe mir Mentos und Cola!", "Finger-leckend!", @@ -141,16 +162,25 @@ public abstract class Splashes { "Doppelt gepuffert!", "Fan-Fiction!", "Flaxkikare!", + "Jason! Jason! Jason!", "Heißer als die Sonne!", "Internet-Funktionalität!", "Autonom!", "Engagiere!", "Fantasie!", - "Mau! Mau! Mau!", + "DRR! DRR! DRR!", "Stoß es Wurzel runter!", "Regionale Ressourcen!", + "Jaa, facepunch!", + "Jaa, somethingawful!", + "Jaa, /v/!", + "Jaa, tigsource!", + "Jaa, weinkraftforum!", + "Jaa, worldofweinkraft!", + "Buu, reddit!", + "Jaa, 2pp!", "Goggle anllyticsed:DD :DDD:D!", - "Unterstützt jetzt äöüß!", + "Unterstützt jetzt äöü!", "Gebt uns Gordon!", "Gib deinem Kellner Trinkgeld!", "Macht viel Spaß!", @@ -161,12 +191,15 @@ public abstract class Splashes { "Allmächtig!", "Huch!", "...!", - "Bienen, Mienen, Minen, W-!", + "Bienen, Bienen, Bienen, Bienen!", + "Jag känner en bot!", "Dieser Text ist schwer bei der Standard-Auflösung zu lesen, aber auf 1080p ist es in Ordnung!", "Haha, LOL!", "Hampsterdance!", "Schalter und Erze!", "Menger-Schwamm!", + "idspispopd!", + "Eple (originale Version)!", "So frisch, so sauber!", "Schnell reagierende Portale!", "Probiere den Warp aus!", @@ -174,9 +207,10 @@ public abstract class Splashes { "Oh, ok, NPCs!", "Endlich mit Leitern!", "Gruselig!", + "Spiele Minenkraft, schaue Topgear, bekomme Schwein!", "Darüber gewittert!", "Spring hoch, spring hoch, und komme runter!", - "Strahlung ist klasse!", + "Joel ist klasse!", "Ein Rätsel, in einen Mythos verwoben!", "Riesige Landeszüge voll mit TNT!", "Willkommen zu deinem Ende! Muahahahahahaha!", @@ -188,21 +222,23 @@ public abstract class Splashes { "\"Fast nie\" ist ein interessantes Konzept!", "Eine Menge Wahrheitigkeit!", "Der TNT-Block ist ein Spion!", - "Turing-unvollständig!", + "Turing-vollständig!", "Es ist bahnbrechend!", "Lasst unsere Schlachten beginnen!", "Der Himmel ist die Grenze - oder auch nicht!", - "Dein PC hat tolle Haare, mach das Ding mal sauber!", - "Shen hat auch tolle Haare!", + "Jeb hat tolle Haare!", + "Ryan hat auch tolle Haare!", "Gelegentliches Spielen!", "Unbesiegt!", "Ein Bisschen wie Lemmings!", "Folge dem Zug, CJ!", "Macht von Synergie Verwendung!", - "Diese Nachricht sollte niemals als Splash-Text erscheinen, oder etwa doch? Trololololol!", + "Diese Nachricht wird niemals als Splash-Text erscheinen, ist das nicht komisch?", + "DungeonQuest ist unfair!", "0815!", "666!", "Geh zu den fernen Ländern und weiter!", + "Tyrion würde es lieben!", "Probiere auch Stellaris!", "Probiere auch Garry's Mod!", "Probiere auch GZDoom!", @@ -216,43 +252,52 @@ public abstract class Splashes { "Brot ist Schmerz!", "Lese mehr Bücher!", "Khaaaaaaaaan!", - "Weniger süchtig machend als [zensiert da NSFW]!", + "Weniger süchtig machend als TV Tropes!", "Mehr süchtig machend als Limonade!", "Größer als eine Brotkiste!", "Millionen von Pfirsichen!", + "Fnord!", "Dies ist meine echte Gestalt! Muahahahaha!", - "Verschwende keine Zeit mit \"\"KI\"\"!", - "Erstellt von einer Katze!", + "Habe Dre vollkommen vergessen!", + "Verschwende keine Zeit mit den Klonen!", + "Kürbiskopf!", + "Hobo humping slobo babe!", + "Erstellt von Jeb!", "Hat kein Ende!", "Endlich vollständig!", "Voll mit Features!", "Stiefel mit dem Fell!", "Stop, hammertime!", - "Test!", + "Testificates!", "Nicht konventionell!", - "Nicht kommerziell!", + "Homeomorphisch zu einer 3-Kugel!", "Vermeidet nicht doppelte Verneinung!", "Platziere ALL die Blöcke!", "Macht Walzen!", "Erfüllt Erwartungen!", - "Spielen am PC seit 1992!", + "Spielen am PC seit 1873!", + "Ghoughpteighbteau tchoghs!", "Deja vu!", "Deja vu!", "Hab deine Nase!", + "Haley liebt Elan!", "Hat keine Angst vor der großen, schwarzen Fledermaus!", "Benutzt nicht das U-Wort!", "Nicht wirklich leicht!", "Bis nächsten Freitag oder so!", - "Von den Straßen von Nibelheim!", + "Von den Straßen von Södermalm!", + "150 BPM für 400000 Minuten!", "Technologisch!", - "Hallo Japan!", + "Funk Soul Bruder!", + "Pumpa kungen!", + "Hallo Japan!", "Hallo Korea!", "Hallo Wales!", "Hallo Polen!", - "Hallo China!", + "Hallo China!", "Hallo Russland!", "Hallo Griechenland!", - "Mein Leben für Aiur (warte mal..)!", + "Mein Leben für Aiur!", "Lenny lenny = new Lenny(\"(°^°)\");", "Ich sehe dein Wortschatz hat sich verbessert!", "Wer hat es dort hin getan?", @@ -260,14 +305,14 @@ public abstract class Splashes { "if not ok then return end", "Mehrfarbig!", "FUNKY LOL", - "Copyright bedeutet LOSER in allen Sprachen!", + "SOPA bedeutet LOSER in Schwedisch!", "Große Spitze Zähne!", "Mein Shizun bewacht das Tor!", "Mmmph, mmph!", - "Füttere keine Landminen an Piranhas!", + "Füttere keine Avocados an Papageien!", "Schwerter für alle!", "Bitteee antworte meinem Tweet! (Nutzer wurde gebannt)", - ".party().crash().commitWarcrimes().forTheEmperor()!", + ".party()!", "Nehme ihr Kissen!", "Lege diesen Keks weg!", "Extrem gruselig!", @@ -275,21 +320,26 @@ public abstract class Splashes { "Jetzt mit extra Sprengstoff!", "Nicht kompatibel zu Java 6!", "Oha.", + "HURNERJSGER?", "Was'n los, Doc?", "Enthält jetzt 0 zufällige tägliche Katzen!", + "Das ist Numberwang!", "((pls rt)) -- Der Vogel ist tot!", "Willst du meinem Server beitreten?", "Mach einen großen Zaun drum herum! Oder du wirst v-", "Lege eine Landmine drüber!", - "Eines Tages, irgendwann in der Zukunft, wird mein Werk r3- ÄÄHHH kopiert werden!", + "Eines Tages, irgendwann in der Zukunft, wird mein Werk zitiert werden!", "Jetzt mit zusätzlichem Zeug!", "Zusätzliche Dinge!", "Hurra, Atombomben für alle!", - "So süß, wie ein schöner ****!", + "So süß, wie ein schöner Bon-Bon!", + "Poppende Tags!", "Sehr einflussreich in seinem Kreis!", "Jetzt mit Mehrspieler!", "Stehe aus deinem Grab auf!", "Warnung! Ein großes Kampfschiff \"SHEN\" nähert sich schnell!", + "Der blaue Krieger hat das Essen beschossen!", + "Renn, Feigling! Ich hunger!", "Geschmack ohne Würze!", "Seltsam, aber nicht fremd!", "Härter als Diamanten, Reich wie Creme!", @@ -305,13 +355,14 @@ public abstract class Splashes { "Bau mir einen Tisch, einen funkigen Tisch!", "Nehm den Aufzug in die Hölle!", "Hör auf vernünftig zu sein, das hier ist das Internet!", - "/give * tnt 67108864 7", + "/give @a tnt 67108864 7", "Das ist gut für 3D Realms.", "Jeder Computer ist ein Laptop, wenn du tapfer genug bist!", "Mach es alles, jede Sache!", "Wo ist kein Licht, da kann Spinne!", "GNU Terry Pratchett", - "Jetzt Java 21!", + "Jetzt Java 8!", + "MeinKraft!", "Immer noch zu viele Bugs!", "Wird nicht laggen!", "Er hat es ruiniert!", @@ -319,6 +370,7 @@ public abstract class Splashes { "OpenGL 2.0+ (definitiv nicht unterstützt)!", "Keine Segfaults (nicht) möglich!", "Keine Abstürze (un)möglich!", + "Alpha!", "Enthält Bugs!", "Enthält Mäuse!", "Enthält Gewalt!", @@ -327,7 +379,6 @@ public abstract class Splashes { "Du hattest eine. aufgabe.", "Spinnen können TNT1 A 0 sein!", "RTFM!", - "Hex, nur mit mehr Ameisen!", "Vorherrschaft des Imperiums!", "Vorherrschaft der Eldar!", "Vorherrschaft der Drukhari!", @@ -358,11 +409,6 @@ public abstract class Splashes { "Eimer mit Wasser!", "Hergestellt in Deutschland!", "Hergestellt in China!", - "Jetzt ohne Einzelspieler!", - "Jetzt mit tieferen Schluchten!", - "Was bist du denn für ein hübsches Ding?", - "[TEXT ZENSIERT]", - "Mehr Energie!", - "Maximale Energie!" + "Jetzt mit Einzelspieler!" }; } diff --git a/client/src/main/java/client/gui/Style.java b/client/src/client/gui/Style.java similarity index 96% rename from client/src/main/java/client/gui/Style.java rename to client/src/client/gui/Style.java index f9a2753..db7435f 100644 --- a/client/src/main/java/client/gui/Style.java +++ b/client/src/client/gui/Style.java @@ -17,9 +17,9 @@ public enum Style implements Identifyable, Displayable { this.name = name; } - @Variable(type = IntType.COLOR, name = "color_border_top", category = CVarCategory.GUI, display = "Umrahmung A") + @Variable(type = IntType.COLOR, name = "color_border_top", category = CVarCategory.GUI, display = "Umrahmung oben / l.") public int brdr_top; - @Variable(type = IntType.COLOR, name = "color_border_btm", category = CVarCategory.GUI, display = "Umrahmung B") + @Variable(type = IntType.COLOR, name = "color_border_btm", category = CVarCategory.GUI, display = "Umrahmung unten / r.") public int brdr_btm; @Variable(type = IntType.COLOR, name = "color_button_top", category = CVarCategory.GUI, display = "Knopf oben") diff --git a/client/src/main/java/client/gui/character/GuiChar.java b/client/src/client/gui/character/GuiChar.java similarity index 84% rename from client/src/main/java/client/gui/character/GuiChar.java rename to client/src/client/gui/character/GuiChar.java index 33cc771..01117c0 100755 --- a/client/src/main/java/client/gui/character/GuiChar.java +++ b/client/src/client/gui/character/GuiChar.java @@ -16,15 +16,14 @@ import org.lwjgl.opengl.GL13; import client.Client; import client.Client.FileMode; +import client.SkinConverter; import client.gui.FileCallback; -import client.gui.Font; import client.gui.GuiLoading; import client.gui.element.ActButton; import client.gui.element.Element; import client.gui.element.GuiList; import client.gui.element.Label; import client.gui.element.ListEntry; -import client.gui.element.MultiLabel; import client.gui.element.NavButton; import client.gui.element.PressType; import client.gui.element.Slider; @@ -34,13 +33,12 @@ import client.gui.element.Area; import client.gui.element.ButtonCallback; import client.gui.element.Field; import client.gui.element.FieldCallback; +import client.gui.element.TransparentArea; import client.renderer.Drawing; import client.renderer.GlState; import client.renderer.ItemRenderer; import client.renderer.entity.RenderManager; import client.renderer.texture.EntityTexManager; -import client.util.FileUtils; -import client.util.SkinConverter; import client.vars.CVarCategory; import client.vars.EnumVar; import client.vars.Variable; @@ -55,7 +53,7 @@ import common.entity.npc.EntityHuman; import common.entity.npc.EntityNPC; import common.entity.npc.SpeciesInfo; import common.entity.types.EntityLiving; -import common.init.EntityInfo; +import common.init.EntityEggInfo; import common.init.EntityRegistry; import common.init.SpeciesRegistry; import common.init.UniverseRegistry; @@ -67,6 +65,7 @@ import common.packet.CPacketMessage; import common.packet.CPacketSkin; import common.rng.Random; import common.util.Displayable; +import common.util.FileUtils; import common.util.Identifyable; import common.util.Util; @@ -102,7 +101,7 @@ public class GuiChar extends GuiList } } - public void draw(int x, int y, int width, int height, int mouseX, int mouseY, boolean hovered) + public void draw(int x, int y, int mouseX, int mouseY, boolean hovered) { String str = (this.skinFile != null ? this.skinFile.getName() : ( @@ -114,7 +113,7 @@ public class GuiChar extends GuiList Drawing.drawText(str, x + 64 + 3, y, 0xff000000 | (this.charinfo == null ? 0xffffff : this.charinfo.color1 | this.charinfo.color2)); if(this.charinfo != null) - Drawing.drawTextRight(this.charinfo.skin, x + width - 2, y + height - Font.YGLYPH, 0xffc0c0c0); + Drawing.drawText(this.charinfo.skin, x + 64 + 3, y + 18, 0xffc0c0c0); GlState.color(1.0F, 1.0F, 1.0F, 1.0F); @@ -253,8 +252,7 @@ public class GuiChar extends GuiList private ActButton templateButton; private DragAdjust adjust; private ActButton dimButton; - private MultiLabel descLines; - private ActButton cancelButton; + private TransparentArea descLines; private float yaw = -15.0f; private float pitch = -15.0f; private boolean waiting = true; @@ -271,7 +269,7 @@ public class GuiChar extends GuiList { super.init(width, height); this.waiting = true; - this.setDimensions(390, height, 32, height - 32); + this.setDimensions(400, height, 32, height - 32); if(this.gm.getRenderManager().gm == null) { this.unload(); this.adjust = null; @@ -279,7 +277,7 @@ public class GuiChar extends GuiList } this.currentSkin = this.gm.player != null && !EntityTexManager.hasCustomSkin(this.gm.player.getId()) ? this.gm.player.getChar() : null; this.load(this.gm.player == null ? ModelType.HUMANOID : this.gm.player.getModel(), this.gm.player != null ? this.gm.player.getSpecies() : SpeciesRegistry.CLASSES.get(EntityHuman.class)); - this.add(new ActButton(2, 12, 193, 0, new ButtonCallback() { + this.add(new ActButton(4, 4, 194, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { GuiChar.this.gm.showFileDialog(FileMode.FILE_LOAD_MULTI, "Skin konvertieren", TEXTURE_FOLDER, new FileCallback() { public void selected(File file) { @@ -289,7 +287,7 @@ public class GuiChar extends GuiList }); } }, "Importieren: Standard")); - this.add(new ActButton(197, 12, 193, 0, new ButtonCallback() { + this.add(new ActButton(202, 4, 194, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { GuiChar.this.gm.showFileDialog(FileMode.FILE_LOAD_MULTI, "Skin konvertieren (schlank)", TEXTURE_FOLDER, new FileCallback() { public void selected(File file) { @@ -299,13 +297,13 @@ public class GuiChar extends GuiList }); } }, "Importieren: Schlank")); - this.addSelector("char_filter_species", 392, 12, 250, 0); - this.add(new ActButton(2, height - 30, 193, 0, new ButtonCallback() { + this.addSelector("char_filter_species", 400, 4, 300, 24); + this.add(new ActButton(4, height - 28, 194, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { GuiChar.this.gm.displayGuiScreen(GuiChar.this); } }, "Neu laden")); - this.templateButton = this.add(new ActButton(197, height - 30, 193, 0, new ButtonCallback() { + this.templateButton = this.add(new ActButton(202, height - 28, 194, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { SkinEntry skin = GuiChar.this.getSelected(); if(skin != null && skin.getLocation() != null) { @@ -322,9 +320,9 @@ public class GuiChar extends GuiList } catch(Exception e) { if(e instanceof FileNotFoundException) - Log.IO.warn("Textur ist nicht zum Kopieren vorhanden: " + EntityNPC.getSkinTexture(loc)); + Log.JNI.warn("Textur ist nicht zum Kopieren vorhanden: " + EntityNPC.getSkinTexture(loc)); else - Log.IO.error(e, "Konnte Textur nicht kopieren"); + Log.JNI.error(e, "Konnte Textur nicht kopieren"); } finally { if(in != null) { @@ -339,23 +337,20 @@ public class GuiChar extends GuiList } } }, "Vorlage kopieren")); - if(width >= 784 + 460 && height >= 128 + 640) - this.adjust = this.add(new DragAdjust(width / 2 - 230, height - 64 - 640, 460, 640)); - else - this.adjust = this.add(new DragAdjust(390 - 115 - 4, height - 32 - 160 - 4, 115, 160)); + this.adjust = this.add(new DragAdjust(width / 2 - 230, height - 64 - 640, 460, 640)); - this.add(new Label(width - 390, 48, 388, "Spezies: " + (this.gm.player == null ? "" : this.gm.player.getSpecies().name), true)); - this.add(new NavButton(width - 390, 48, 388, 0, GuiSpecies.INSTANCE, "Spezies ändern")); - this.add(new Label(width - 390, 82, 388, "Klasse: " + (this.gm.player == null || this.gm.player.getSpecies().classEnum == null || this.gm.player.getNpcClass() == null || this.gm.player.getNpcClass().toString().isEmpty() ? "" : this.gm.player.getNpcClass().toString()), true)) + this.add(new Label(width - 396, 36, 392, 20, "Spezies: " + (this.gm.player == null ? "" : this.gm.player.getSpecies().name), true)); + this.add(new NavButton(width - 396, 56, 392, 24, GuiSpecies.INSTANCE, "Spezies ändern")); + this.add(new Label(width - 396, 36 + 92, 392, 20, "Klasse: " + (this.gm.player == null || this.gm.player.getSpecies().classEnum == null || this.gm.player.getNpcClass() == null || this.gm.player.getNpcClass().toString().isEmpty() ? "" : this.gm.player.getNpcClass().toString()), true)) .enabled = this.gm.player != null && this.gm.player.getSpecies().classEnum != null; - this.add(new NavButton(width - 390, 82, 388, 0, GuiClass.INSTANCE, "Klasse ändern")) + this.add(new NavButton(width - 396, 56 + 92, 392, 24, GuiClass.INSTANCE, "Klasse ändern")) .enabled = this.gm.player != null && this.gm.player.getSpecies().classEnum != null; final ActButton[] alignBtns = new ActButton[Alignment.values().length]; for (int z = 0; z < Alignment.values().length; z++) { final Alignment align = Alignment.values()[z]; - alignBtns[z] = this.add(new ActButton(width - 390 + (z % 3) * 130, height - 32 - 20 * 3 + 20 * (z / 3), 128, 0, new ButtonCallback() { + alignBtns[z] = this.add(new ActButton(width - 396 + (z % 3) * 132, height - 32 - 28 * 3 + 28 * (z / 3), 128, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { if(GuiChar.this.gm.player != null) { GuiChar.this.waiting = false; @@ -368,7 +363,7 @@ public class GuiChar extends GuiList }, align.color + align.display)); alignBtns[z].enabled = this.gm.player == null || this.gm.player.getAlignment() != align; } - this.add(new Slider(width - 390, 136, 388, 0, 1, this.gm.player == null ? 120 : this.gm.player.getMinSize(), this.gm.player == null ? 320 : this.gm.player.getMaxSize(), this.gm.player == null ? 180 : this.gm.player.getDefaultSize(), this.gm.player == null ? 180 : this.gm.player.getCurrentSize(), new SliderCallback() { + this.add(new Slider(width / 2 - 200, height - 28, 400, 24, 1, this.gm.player == null ? 120 : this.gm.player.getMinSize(), this.gm.player == null ? 320 : this.gm.player.getMaxSize(), this.gm.player == null ? 180 : this.gm.player.getDefaultSize(), this.gm.player == null ? 180 : this.gm.player.getCurrentSize(), new SliderCallback() { public void use(Slider elem, int value) { if(GuiChar.this.gm.player != null) { GuiChar.this.waiting = false; @@ -376,10 +371,10 @@ public class GuiChar extends GuiList } } }, "Spieler-Größe", "cm")).enabled = this.gm.player == null || this.gm.player.getMinSize() != this.gm.player.getMaxSize(); - this.add(new Label(width - 390, 116, 388, "Name", true)); - this.add(new Label(width - 390, 170, 388, "Beschreibung", true)); - final Area descField = this.add(new Area(width - 390, 170, 388, height - 328, IPlayer.MAX_INFO_LENGTH, "")); - this.add(new ActButton(width - 195, height - 30, 193, 0, new ButtonCallback() { + this.add(new Label(width / 2 - 200, 36, 400, 20, "Name", true)); + this.add(new Label(width - 396, height - 384, 392, 20, "Beschreibung", true)); + final Area descField = this.add(new Area(width - 396, height - 364, 392, 130, IPlayer.MAX_INFO_LENGTH, "")); + this.add(new ActButton(width - 198, height - 28, 194, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { if(GuiChar.this.gm.player != null) { GuiChar.this.gm.displayGuiScreen(GuiLoading.makeWaitTask("Lade Welt ...")); @@ -389,14 +384,7 @@ public class GuiChar extends GuiList } } }, "Charakter erstellen")); - this.cancelButton = this.add(new ActButton(width - 390, height - 30, 193, 0, new ButtonCallback() { - public void use(ActButton elem, PressType action) { - if(GuiChar.this.gm.player != null) - GuiChar.this.gm.displayGuiScreen(GuiCharacters.INSTANCE); - } - }, "Abbrechen")); - this.setCharsAvailable(); - this.add(new Field(width - 390, 116, 388, 0, IPlayer.MAX_NICK_LENGTH, new FieldCallback() { + this.add(new Field(width / 2 - 200, 36 + 20, 400, 24, IPlayer.MAX_NICK_LENGTH, new FieldCallback() { public void use(Field elem, FieldAction value) { if(value == FieldAction.SEND || value == FieldAction.UNFOCUS) { String name = elem.getText(); @@ -411,9 +399,9 @@ public class GuiChar extends GuiList }, IPlayer.VALID_NICK, this.gm.player == null ? "" : this.gm.player.getCustomNameTag())); this.templateButton.enabled = false; this.dimension = new Random().zrange(UniverseRegistry.getBaseDimensions().size()); - EntityInfo egg = EntityRegistry.SPAWN_EGGS.get(this.gm.player == null ? EntityRegistry.getEntityString(EntityHuman.class) : EntityRegistry.getEntityString(this.gm.player)); - if(egg != null && egg.origin() != null) { - Dimension dim = UniverseRegistry.getDimension(egg.origin()); + EntityEggInfo egg = EntityRegistry.SPAWN_EGGS.get(this.gm.player == null ? EntityRegistry.getEntityString(EntityHuman.class) : EntityRegistry.getEntityString(this.gm.player)); + if(egg != null && egg.origin != null) { + Dimension dim = UniverseRegistry.getDimension(egg.origin); if(dim != null) { for(int z = 0; z < UniverseRegistry.getBaseDimensions().size(); z++) { if(UniverseRegistry.getBaseDimensions().get(z).getDimensionId() == dim.getDimensionId()) { @@ -423,7 +411,7 @@ public class GuiChar extends GuiList } } } - this.dimButton = this.add(new ActButton(width - 390, height - 156, 388, 0, new ButtonCallback() { + this.dimButton = this.add(new ActButton(width - 396, height - 220, 392, 24, new ButtonCallback() { public void use(ActButton elem, PressType mode) { if(mode == PressType.TERTIARY) { GuiChar.this.dimension = new Random().zrange(UniverseRegistry.getBaseDimensions().size()); @@ -439,7 +427,7 @@ public class GuiChar extends GuiList GuiChar.this.setDimButton(); } }, "")); - this.descLines = this.add(new MultiLabel(width - 390, height - 156 + Element.BASE_HEIGHT, 388, 42, "", true)); + this.descLines = this.add(new TransparentArea(width - 396, height - 220 + 24, 392, 66, "", false)); this.setDimButton(); } @@ -461,10 +449,8 @@ public class GuiChar extends GuiList if(this.adjust != null) { float factor = this.gm.player.width > 2.15f ? 2.15f / this.gm.player.width : 1.0f; factor = this.gm.player.height > 3.0f && 3.0f / this.gm.player.height < factor ? 3.0f / this.gm.player.height : factor; - if(this.gm.fb_x >= 784 + 460 && this.gm.fb_y >= 128 + 640) - drawEntity(400 + (this.gm.fb_x - 400 - 400) / 2, this.gm.fb_y - 160, 160.0f * factor, this.yaw, this.pitch, this.gm.player); - else - drawEntity(390 - 4 - 115 / 2, this.gm.fb_y - 60, 40.0f * factor, this.yaw, this.pitch, this.gm.player); + drawEntity(400 + (this.gm.fb_x - 400 - 400) / 2, this.gm.fb_y - 160, 160.0f * factor + , this.yaw, this.pitch, this.gm.player); } } @@ -484,11 +470,6 @@ public class GuiChar extends GuiList return "Charakter anpassen"; } - public void setCharsAvailable() { - if(this.cancelButton != null) - this.cancelButton.enabled = !this.gm.characterList.isEmpty(); - } - public static BufferedImage loadSkin(File file) { BufferedImage img = null; @@ -556,6 +537,11 @@ public class GuiChar extends GuiList this.elements.clear(); } + + public int getListWidth() + { + return 400 - 20; + } public int getSlotHeight() { diff --git a/client/src/main/java/client/gui/character/GuiCharacters.java b/client/src/client/gui/character/GuiCharacters.java similarity index 59% rename from client/src/main/java/client/gui/character/GuiCharacters.java rename to client/src/client/gui/character/GuiCharacters.java index 9d53d9e..46e99d8 100644 --- a/client/src/main/java/client/gui/character/GuiCharacters.java +++ b/client/src/client/gui/character/GuiCharacters.java @@ -1,21 +1,18 @@ package client.gui.character; -import client.gui.Font; import client.gui.GuiConfirm; import client.gui.GuiMenu; import client.gui.element.ActButton; -import client.gui.element.Area; import client.gui.element.ButtonCallback; import client.gui.element.GuiList; import client.gui.element.ListEntry; import client.gui.element.NavButton; import client.gui.element.PressType; +import client.gui.element.TransparentArea; import client.renderer.Drawing; import common.color.TextColor; import common.entity.npc.PlayerCharacter; import common.packet.CPacketAction; -import common.packet.CPacketAction.Action; -import common.util.ExtMath; public class GuiCharacters extends GuiList implements ButtonCallback { @@ -30,18 +27,18 @@ public class GuiCharacters extends GuiList impleme this.initial = initial; } - public void draw(int x, int y, int width, int height, int mouseX, int mouseY, boolean hovered) + public void draw(int x, int y, int mouseX, int mouseY, boolean hovered) { if(this.initial) Drawing.drawRect(x, y, 1, 36, 0xffaf0000); String str = this.character == null ? TextColor.BLUE + "[" + TextColor.CYAN + "+" + TextColor.BLUE + "]" : - String.format(TextColor.GREEN + "Level " + TextColor.DGREEN + "%d " + TextColor.YELLOW + "%s " + TextColor.VIOLET + "%s", - character.level(), character.type(), character.name()); + String.format(TextColor.GREEN + "Level " + TextColor.DGREEN + "%d " + TextColor.YELLOW + "%s " + TextColor.VIOLET + "%s" + TextColor.GRAY + " [%s%s" + TextColor.GRAY + "]", + character.level, character.type, character.name, character.align.color, character.align.display); String pos = this.character == null ? TextColor.BROWN + "Neuen Charakter erstellen" : String.format(TextColor.NEON + "%s " + TextColor.GRAY + "bei " + TextColor.ACID + "%d" + TextColor.GRAY + ", " + TextColor.ACID + "%d" + TextColor.GRAY + ", " + TextColor.ACID + "%d", - character.dim(), character.pos().getX(), character.pos().getY(), character.pos().getZ()); + character.dim, character.pos.getX(), character.pos.getY(), character.pos.getZ()); Drawing.drawText(str, x + 3, y, 0xffffffff); - Drawing.drawText(pos, x + 3, y + height - Font.YGLYPH, 0xffffffff); + Drawing.drawText(pos, x + 3, y + 16, 0xffffffff); } public void select(boolean dclick, int mx, int my) @@ -54,7 +51,7 @@ public class GuiCharacters extends GuiList impleme public static final GuiCharacters INSTANCE = new GuiCharacters(); - private Area descField; + private TransparentArea descField; private ActButton actionButtom; private ActButton deleteButtom; @@ -63,34 +60,40 @@ public class GuiCharacters extends GuiList impleme private void updateButtons() { CharacterEntry entry = this.getSelected(); - this.descField.setText(entry == null ? "" : (entry.character == null ? "*neuer Charakter*" : String.format(TextColor.GRAY + "[%s%s" + TextColor.GRAY + "]\n" + TextColor.RESET + "%s", entry.character.align().color, entry.character.align().display, entry.character.info() == null ? "*keine Beschreibung vorhanden*" : this.getSelected().character.info()))); + this.descField.setText(entry == null ? "" : (entry.character == null ? "*neuer Charakter*" : (entry.character.info == null ? "*keine Beschreibung vorhanden*" : this.getSelected().character.info))); this.actionButtom.setText(entry != null && entry.character == null ? "Charakter erstellen" : "Charakter spielen"); this.actionButtom.enabled = entry != null && !entry.initial; - this.deleteButtom.enabled = !this.gm.charEditor && entry != null && entry.character != null && !entry.initial; + this.deleteButtom.enabled = entry != null && entry.character != null && !entry.initial; } public void init(int width, int height) { super.init(width, height); - this.setDimensions(width - 300, height, 32, height - 32); + this.setDimensions(600, height, 32, height - 32); this.elements.clear(); - int selected = this.gm.selectedCharacter; - for(PlayerCharacter character : this.gm.characterList) { - this.elements.add(new CharacterEntry(selected == this.elements.size() ? new PlayerCharacter(character.name(), character.info(), character.align(), this.gm.player.worldObj.dimension.getFormattedName(false), this.gm.player.getPosition(), character.type(), this.gm.player.experienceLevel) : character, selected == this.elements.size())); - } - if(!this.gm.charEditor) - this.elements.add(new CharacterEntry(null, false)); - this.setSelected(ExtMath.clampi(selected, -1, this.elements.size() - 1)); - this.descField = this.add(new Area(width - 300, 32, 300, height - 64, "")); - this.deleteButtom = this.add(new ActButton(width / 2 - 302, height - 30, 200, 0, this, "Charakter löschen")); - this.actionButtom = this.add(new ActButton(width / 2 - 100, height - 30, 200, 0, this, "")); - this.add(new NavButton(width / 2 + 102, height - 30, 200, 0, this.gm.charEditor ? GuiChar.INSTANCE : GuiMenu.INSTANCE, this.gm.charEditor ? "Zurück" : "Abbrechen")); + if(this.gm.getNetHandler() != null) { + int initialSelection = this.gm.getNetHandler().getSelectedCharacter(); + for(PlayerCharacter character : this.gm.getNetHandler().getCharacterList()) { + this.elements.add(new CharacterEntry(initialSelection == this.elements.size() ? new PlayerCharacter(character.name, character.info, character.align, this.gm.player.worldObj.dimension.getFormattedName(false), this.gm.player.getPosition(), character.type, this.gm.player.experienceLevel) : character, initialSelection == this.elements.size())); + } + this.elements.add(new CharacterEntry(null, false)); + this.setSelected(initialSelection); + } + this.descField = this.add(new TransparentArea(width - 390, 62, 380, height - 124, "", false)); + this.deleteButtom = this.add(new ActButton(width / 2 - 304, height - 28, 200, 24, this, "Charakter löschen")); + this.actionButtom = this.add(new ActButton(width / 2 - 100, height - 28, 200, 24, this, "")); + this.add(new NavButton(width / 2 + 104, height - 28, 200, 24, GuiMenu.INSTANCE, "Abbrechen")); this.updateButtons(); } public String getTitle() { - return "Charakter auswählen"; + return "Charakter anpassen"; } + + public int getListWidth() + { + return 560; + } public int getSlotHeight() { @@ -104,7 +107,7 @@ public class GuiCharacters extends GuiList impleme if(entry.character == null) this.gm.getNetHandler().addToSendQueue(new CPacketAction(CPacketAction.Action.OPEN_EDITOR)); else - this.gm.getNetHandler().addToSendQueue(new CPacketAction(GuiCharacters.this.gm.charEditor ? Action.CANCEL_EDITOR : CPacketAction.Action.SELECT_CHARACTER, this.selectedElement)); + this.gm.getNetHandler().addToSendQueue(new CPacketAction(CPacketAction.Action.SELECT_CHARACTER, this.selectedElement)); } else if(elem == this.deleteButtom && entry.character != null) { this.gm.displayGuiScreen(new GuiConfirm(new GuiConfirm.Callback() { @@ -113,7 +116,7 @@ public class GuiCharacters extends GuiList impleme GuiCharacters.this.gm.getNetHandler().addToSendQueue(new CPacketAction(CPacketAction.Action.DELETE_CHARACTER, GuiCharacters.this.selectedElement)); GuiCharacters.this.gm.displayGuiScreen(GuiCharacters.this); } - }, "Möchtest du diesen Charakter wirklich löschen?", "Der Fortschritt, die Gegenstände und die Historie\nvon \"" + entry.character.name() + "\" werden für immer verloren sein!", "Löschen", "Abbrechen")); + }, "Möchtest du diesen Charakter wirklich löschen?", "Der Fortschritt, die Gegenstände und die Historie von \"" + entry.character.name + "\" werden für imer verloren sein!", "Löschen", "Abbrechen")); } } } diff --git a/client/src/main/java/client/gui/character/GuiClass.java b/client/src/client/gui/character/GuiClass.java similarity index 83% rename from client/src/main/java/client/gui/character/GuiClass.java rename to client/src/client/gui/character/GuiClass.java index 775a266..9b83871 100644 --- a/client/src/main/java/client/gui/character/GuiClass.java +++ b/client/src/client/gui/character/GuiClass.java @@ -20,7 +20,7 @@ public class GuiClass extends GuiList implements ButtonCall this.clazz = clazz; } - public void draw(int x, int y, int width, int height, int mouseX, int mouseY, boolean hovered) + public void draw(int x, int y, int mouseX, int mouseY, boolean hovered) { if(GuiClass.this.gm.player != null && this.clazz == GuiClass.this.gm.player.getNpcClass()) Drawing.drawRect(x, y, 1, 44, 0xffaf0000); @@ -44,19 +44,24 @@ public class GuiClass extends GuiList implements ButtonCall public void init(int width, int height) { super.init(width, height); - this.setDimensions(width, height, 32, height - 32); + this.setDimensions(400, height, 32, height - 32); this.elements.clear(); if(this.gm.player != null && this.gm.player.getSpecies().classEnum != null) for(Enum clazz : this.gm.player.getSpecies().classEnum.getEnumConstants()) { this.elements.add(new ClassEntry(clazz)); } - this.add(new NavButton(width / 2 - 195, height - 30, 194, 0, GuiChar.INSTANCE, "Zurück")); - this.selectButton = this.add(new ActButton(width / 2 + 1, height - 30, 194, 0, this, "Klasse ändern")); + this.add(new NavButton(width - 198 * 2, height - 28, 194, 24, GuiChar.INSTANCE, "Zurück")); + this.selectButton = this.add(new ActButton(width - 198, height - 28, 194, 24, this, "Klasse ändern")); } public String getTitle() { return "Klasse wählen"; } + + public int getListWidth() + { + return 400 - 20; + } public int getSlotHeight() { diff --git a/client/src/main/java/client/gui/character/GuiSpecies.java b/client/src/client/gui/character/GuiSpecies.java similarity index 84% rename from client/src/main/java/client/gui/character/GuiSpecies.java rename to client/src/client/gui/character/GuiSpecies.java index 6f190db..10e8c01 100644 --- a/client/src/main/java/client/gui/character/GuiSpecies.java +++ b/client/src/client/gui/character/GuiSpecies.java @@ -23,7 +23,7 @@ public class GuiSpecies extends GuiList implements Butt this.species = species; } - public void draw(int x, int y, int width, int height, int mouseX, int mouseY, boolean hovered) + public void draw(int x, int y, int mouseX, int mouseY, boolean hovered) { if(GuiSpecies.this.gm.player != null && this.species == GuiSpecies.this.gm.player.getSpecies()) Drawing.drawRect(x, y, 1, 44, 0xffaf0000); @@ -49,18 +49,23 @@ public class GuiSpecies extends GuiList implements Butt public void init(int width, int height) { super.init(width, height); - this.setDimensions(width, height, 32, height - 32); + this.setDimensions(400, height, 32, height - 32); this.elements.clear(); for(SpeciesInfo species : SpeciesRegistry.SPECIMEN) { this.elements.add(new SpeciesEntry(species)); } - this.add(new NavButton(width / 2 - 195, height - 30, 194, 0, GuiChar.INSTANCE, "Zurück")); - this.selectButton = this.add(new ActButton(width / 2 + 1, height - 30, 194, 0, this, "Spezies ändern")); + this.add(new NavButton(width - 198 * 2, height - 28, 194, 24, GuiChar.INSTANCE, "Zurück")); + this.selectButton = this.add(new ActButton(width - 198, height - 28, 194, 24, this, "Spezies ändern")); } public String getTitle() { return "Spezies wählen"; } + + public int getListWidth() + { + return 400 - 20; + } public int getSlotHeight() { diff --git a/client/src/main/java/client/gui/container/GuiBrewing.java b/client/src/client/gui/container/GuiBrewing.java similarity index 100% rename from client/src/main/java/client/gui/container/GuiBrewing.java rename to client/src/client/gui/container/GuiBrewing.java diff --git a/client/src/main/java/client/gui/container/GuiChest.java b/client/src/client/gui/container/GuiChest.java similarity index 100% rename from client/src/main/java/client/gui/container/GuiChest.java rename to client/src/client/gui/container/GuiChest.java diff --git a/client/src/main/java/client/gui/container/GuiContainer.java b/client/src/client/gui/container/GuiContainer.java similarity index 95% rename from client/src/main/java/client/gui/container/GuiContainer.java rename to client/src/client/gui/container/GuiContainer.java index 967dfa5..7ae0eb8 100755 --- a/client/src/main/java/client/gui/container/GuiContainer.java +++ b/client/src/client/gui/container/GuiContainer.java @@ -6,7 +6,6 @@ import java.util.Set; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import client.gui.Font; import client.gui.Gui; import client.gui.element.InventoryButton; import client.renderer.Drawing; @@ -43,7 +42,7 @@ public abstract class GuiContainer extends Gui private static final List ITEM_LIST = Lists.newArrayList(); - private static CheatTab selectedTab = CheatTab.BLOCKS; + private static CheatTab selectedTab = CheatTab.tabBlocks; // /** The location of the inventory background texture */ // protected static final String inventoryBackground = "textures/gui/inventory.png"; @@ -375,20 +374,20 @@ public abstract class GuiContainer extends Gui if (this.draggedStack != null && this.isRightMouseClick) { itemstack = itemstack.copy(); - itemstack.size = ExtMath.ceilf((float)itemstack.size / 2.0F); + itemstack.stackSize = ExtMath.ceilf((float)itemstack.stackSize / 2.0F); } else if (this.dragSplitting && this.dragSplittingSlots.size() > 1) { itemstack = itemstack.copy(); - itemstack.size = this.dragSplittingRemnant; + itemstack.stackSize = this.dragSplittingRemnant; - if (itemstack.size == 0) + if (itemstack.stackSize == 0) { s = "" + TextColor.YELLOW + "0"; } } else if(itemstack == this.cheatStack) { - s = TextColor.DGREEN + "+" + TextColor.GREEN + ItemStack.formatAmount(itemstack.size); + s = TextColor.DGREEN + "+" + TextColor.GREEN + ItemStack.formatAmount(itemstack.stackSize); } this.drawItemStack(itemstack, mouseX - j2, mouseY - k2, s); @@ -519,7 +518,7 @@ public abstract class GuiContainer extends Gui if (slotIn == this.clickedSlot && this.draggedStack != null && this.isRightMouseClick && itemstack != null) { itemstack = itemstack.copy(); - itemstack.size /= 2; + itemstack.stackSize /= 2; } else if (this.dragSplitting && this.dragSplittingSlots.contains(slotIn) && itemstack1 != null) { @@ -532,18 +531,18 @@ public abstract class GuiContainer extends Gui { itemstack = itemstack1.copy(); flag = true; - Container.computeStackSize(this.dragSplittingSlots, this.dragSplittingLimit, itemstack, slotIn.getStack() == null ? 0 : slotIn.getStack().size); + Container.computeStackSize(this.dragSplittingSlots, this.dragSplittingLimit, itemstack, slotIn.getStack() == null ? 0 : slotIn.getStack().stackSize); - if (itemstack.size > itemstack.getMaxStackSize()) + if (itemstack.stackSize > itemstack.getMaxStackSize()) { s = TextColor.YELLOW + ItemStack.formatAmount(itemstack.getMaxStackSize()); - itemstack.size = itemstack.getMaxStackSize(); + itemstack.stackSize = itemstack.getMaxStackSize(); } - if (itemstack.size > slotIn.getItemStackLimit(itemstack)) + if (itemstack.stackSize > slotIn.getItemStackLimit(itemstack)) { s = TextColor.YELLOW + ItemStack.formatAmount(slotIn.getItemStackLimit(itemstack)); - itemstack.size = slotIn.getItemStackLimit(itemstack); + itemstack.stackSize = slotIn.getItemStackLimit(itemstack); } } else @@ -594,25 +593,25 @@ public abstract class GuiContainer extends Gui if (itemstack != null && this.dragSplitting) { - this.dragSplittingRemnant = itemstack.size; + this.dragSplittingRemnant = itemstack.stackSize; for (Slot slot : this.dragSplittingSlots) { ItemStack itemstack1 = itemstack.copy(); - int i = slot.getStack() == null ? 0 : slot.getStack().size; + int i = slot.getStack() == null ? 0 : slot.getStack().stackSize; Container.computeStackSize(this.dragSplittingSlots, this.dragSplittingLimit, itemstack1, i); - if (itemstack1.size > itemstack1.getMaxStackSize()) + if (itemstack1.stackSize > itemstack1.getMaxStackSize()) { - itemstack1.size = itemstack1.getMaxStackSize(); + itemstack1.stackSize = itemstack1.getMaxStackSize(); } - if (itemstack1.size > slot.getItemStackLimit(itemstack1)) + if (itemstack1.stackSize > slot.getItemStackLimit(itemstack1)) { - itemstack1.size = slot.getItemStackLimit(itemstack1); + itemstack1.stackSize = slot.getItemStackLimit(itemstack1); } - this.dragSplittingRemnant -= itemstack1.size - i; + this.dragSplittingRemnant -= itemstack1.stackSize - i; } } } @@ -645,7 +644,7 @@ public abstract class GuiContainer extends Gui if(this.cheatStack != null) { Slot slot = this.getSlotAtPosition(mouseX, mouseY); if((mouseButton == 0 || mouseButton == 1) && slot != null && this.gm.player != null && slot.inventory == this.gm.player.inventory) - this.gm.player.client.addToSendQueue(new CPacketCheat(this.cheatStack, slot.getIndex(), mouseButton == 0 && this.cheatStack.size > 1)); + this.gm.player.client.addToSendQueue(new CPacketCheat(this.cheatStack, slot.getIndex(), mouseButton == 0 && this.cheatStack.stackSize > 1)); if(mouseButton != 1 && !this.gm.ctrl()) this.cheatStack = null; return; @@ -812,7 +811,7 @@ public abstract class GuiContainer extends Gui // } // } // else - if (this.dragSplitting && slot != null && itemstack != null && itemstack.size > this.dragSplittingSlots.size() && Container.canAddItemToSlot(slot, itemstack, true) && slot.isItemValid(itemstack) && this.inventorySlots.canDragIntoSlot(slot)) + if (this.dragSplitting && slot != null && itemstack != null && itemstack.stackSize > this.dragSplittingSlots.size() && Container.canAddItemToSlot(slot, itemstack, true) && slot.isItemValid(itemstack) && this.inventorySlots.canDragIntoSlot(slot)) { this.dragSplittingSlots.add(slot); this.updateDragSplitting(); @@ -1078,7 +1077,7 @@ public abstract class GuiContainer extends Gui if (this.gm != null && this.gm.player != null && (!this.gm.player.isEntityAlive() || this.gm.player.dead)) { - this.gm.displayGuiScreen(null); + this.gm.player.closeScreen(); } } @@ -1091,13 +1090,13 @@ public abstract class GuiContainer extends Gui { if (stack != null) { - if (stack.size != 1 || text != null) + if (stack.stackSize != 1 || text != null) { - String s = text == null ? ItemStack.formatAmount(stack.size) : text; + String s = text == null ? ItemStack.formatAmount(stack.stackSize) : text; - if (text == null && stack.size < 1) + if (text == null && stack.stackSize < 1) { - s = TextColor.RED + ItemStack.formatAmount(stack.size); + s = TextColor.RED + ItemStack.formatAmount(stack.stackSize); } // this.drawString(s, , ); // Vec2i size = Drawing.txt_size(0, 0, 0, 0, 65536, 65536, s); @@ -1105,7 +1104,7 @@ public abstract class GuiContainer extends Gui // int y = ; // x = x * 2 + this.container_x; // y = y * 2 + this.container_y; - Drawing.drawTextRight(s, xPosition + 32, yPosition + 33 - Font.YGLYPH, 0xffffffff); + Drawing.drawTextRight(s, xPosition + 32, yPosition + 17, 0xffffffff); } if (stack.isItemDamaged()) @@ -1152,7 +1151,7 @@ public abstract class GuiContainer extends Gui protected void drawTab(CheatTab tab) { this.itemRender.zLevel = 100.0F; - ItemStack itemstack = tab.getIcon(); + ItemStack itemstack = tab.getIconItemStack(); GlState.enableDepth(); this.itemRender.renderItemAndEffectIntoGUI(itemstack, this.xSize + 2 + 18 * tab.getHorizontal() + 1, 9 * 18 + 4 + 20 * tab.getVertical() + 1); this.itemRender.zLevel = 0.0F; @@ -1177,7 +1176,7 @@ public abstract class GuiContainer extends Gui selectedTab = tab; this.dragSplittingSlots.clear(); ITEM_LIST.clear(); - tab.filter(ITEM_LIST); + tab.displayAllReleventItems(ITEM_LIST); this.currentScroll = 0.0F; } @@ -1202,7 +1201,7 @@ public abstract class GuiContainer extends Gui } else { this.cheatStack = ITEM_LIST.get(i1).copy(); - this.cheatStack.size = full ? this.cheatStack.getMaxStackSize() : 1; + this.cheatStack.stackSize = full ? this.cheatStack.getMaxStackSize() : 1; } return true; } diff --git a/client/src/client/gui/container/GuiCrafting.java b/client/src/client/gui/container/GuiCrafting.java new file mode 100755 index 0000000..d38e913 --- /dev/null +++ b/client/src/client/gui/container/GuiCrafting.java @@ -0,0 +1,42 @@ +package client.gui.container; + +import common.inventory.ContainerWorkbench; +import common.inventory.InventoryPlayer; +import common.util.BlockPos; +import common.world.World; + +public class GuiCrafting extends GuiContainer +{ +// private static final String craftingTableGuiTextures = "textures/gui/crafting_table.png"; + + public GuiCrafting(InventoryPlayer playerInv, World worldIn) + { + this(playerInv, worldIn, BlockPos.ORIGIN); + } + + public GuiCrafting(InventoryPlayer playerInv, World worldIn, BlockPos blockPosition) + { + super(new ContainerWorkbench(playerInv, worldIn, blockPosition)); + } + + /** + * Draw the foreground layer for the GuiContainer (everything in front of the items). Args : mouseX, mouseY + */ + public void drawGuiContainerForegroundLayer() + { + this.drawString("Handwerk", 28, 6); + this.drawString("Inventar", 8, this.ySize - 96 + 2); + } + +// /** +// * Args : renderPartialTicks, mouseX, mouseY +// */ +// protected void drawGuiContainerBackgroundLayer(int mouseX, int mouseY) +// { +// GlState.color(1.0F, 1.0F, 1.0F, 1.0F); +// this.gm.getTextureManager().bindTexture(craftingTableGuiTextures); +// int i = (this.width - this.xSize) / 2; +// int j = (this.height - this.ySize) / 2; +//// this.rect(i, j, 0, 0, this.xSize, this.ySize); +// } +} diff --git a/client/src/main/java/client/gui/container/GuiDispenser.java b/client/src/client/gui/container/GuiDispenser.java similarity index 100% rename from client/src/main/java/client/gui/container/GuiDispenser.java rename to client/src/client/gui/container/GuiDispenser.java diff --git a/client/src/main/java/client/gui/container/GuiEnchant.java b/client/src/client/gui/container/GuiEnchant.java similarity index 88% rename from client/src/main/java/client/gui/container/GuiEnchant.java rename to client/src/client/gui/container/GuiEnchant.java index b9a7181..0b25ef3 100755 --- a/client/src/main/java/client/gui/container/GuiEnchant.java +++ b/client/src/client/gui/container/GuiEnchant.java @@ -5,7 +5,7 @@ import common.enchantment.Enchantment; import common.inventory.ContainerEnchantment; import common.inventory.InventoryPlayer; import common.rng.Random; -import common.util.Pair; +import common.tileentity.IWorldNameable; import common.world.World; public class GuiEnchant extends GuiContainer @@ -19,7 +19,7 @@ public class GuiEnchant extends GuiContainer private final Random nameRand = new Random(); private final Random random = new Random(); private final ContainerEnchantment container; - private final String title; + private final IWorldNameable table; // public int field_147073_u; // public float field_147071_v; @@ -30,12 +30,12 @@ public class GuiEnchant extends GuiContainer // public float field_147076_A; // ItemStack field_147077_B; - public GuiEnchant(InventoryPlayer inventory, World worldIn, String title) + public GuiEnchant(InventoryPlayer inventory, World worldIn, IWorldNameable table) { super(new ContainerEnchantment(inventory, worldIn)); this.playerInventory = inventory; this.container = (ContainerEnchantment)this.inventorySlots; - this.title = title; + this.table = table; } /** @@ -43,7 +43,7 @@ public class GuiEnchant extends GuiContainer */ public void drawGuiContainerForegroundLayer() { - this.drawString(this.title, 12, 5); + this.drawString(this.table.getCommandName(), 12, 5); this.drawString(this.playerInventory.getCommandName(), 8, this.ySize - 96 + 2); } @@ -89,14 +89,14 @@ public class GuiEnchant extends GuiContainer */ public void drawGuiContainerBackgroundLayer() { - this.nameRand.setSeed((long)this.container.seed); + this.nameRand.setSeed((long)this.container.xpSeed); for (int l = 0; l < 3; ++l) { int i1 = 60; int j1 = i1 + 20; String s = this.getRandomName(); - int l1 = this.container.mana[l]; + int l1 = this.container.enchantLevels[l]; if (l1 == 0) { @@ -107,7 +107,7 @@ public class GuiEnchant extends GuiContainer String s1 = "" + l1; int i2 = 6839882; - if (/* (k < l + 1 || */ this.gm.player.getManaPoints() < l1) // && !this.gm.thePlayer.creative) + if (/* (k < l + 1 || */ this.gm.player.experienceLevel < l1) // && !this.gm.thePlayer.creative) { this.rect(i1, 14 + 19 * l, 108, 19, 0x400000); this.rect(i1 + 1, 15 + 19 * l, 16, 16, 0x200000); @@ -150,16 +150,19 @@ public class GuiEnchant extends GuiContainer for (int j = 0; j < 3; ++j) { - int k = this.container.mana[j]; - Pair l = this.container.ench[j]; + int k = this.container.enchantLevels[j]; + int l = this.container.enchantmentIds[j]; int i1 = j + 1; - if (this.isPointInRegion(60, 14 + 19 * j, 108, 17, mouseX, mouseY) && k > 0 && l != null) + if (this.isPointInRegion(60, 14 + 19 * j, 108, 17, mouseX, mouseY) && k > 0 && l >= 0) { StringBuilder sb = new StringBuilder(); - String s = l.first().getFormattedName(l.second()); - sb.append(TextColor.WHITE + s + " . . . ?"); + if (l >= 0 && Enchantment.getEnchantmentById(l & 255) != null) + { + String s = Enchantment.getEnchantmentById(l & 255).getFormattedName((l & 65280) >> 8); + sb.append(TextColor.WHITE + s + " . . . ?"); + } // if (!flag) // { @@ -168,9 +171,9 @@ public class GuiEnchant extends GuiContainer // sb.append("\n"); // } - if (this.gm.player.getManaPoints() < k) + if (this.gm.player.experienceLevel < k) { - sb.append((sb.length() != 0 ? "\n" : "") + TextColor.RED + String.format("%d Mana erforderlich", this.container.mana[j])); + sb.append((sb.length() != 0 ? "\n" : "") + TextColor.RED + String.format("Erfahrungsstufe %d erforderlich", this.container.enchantLevels[j])); } else { @@ -196,11 +199,11 @@ public class GuiEnchant extends GuiContainer if (i1 == 1) { - s1 = "1 Manapunkt"; + s1 = "1 Erfahrungsstufe"; } else { - s1 = String.format("%d Manapunkte", i1); + s1 = String.format("%d Erfahrungsstufen", i1); } sb.append((sb.length() != 0 ? "\n" : "") + TextColor.LGRAY.toString() + "" + s1); diff --git a/client/src/main/java/client/gui/container/GuiFurnace.java b/client/src/client/gui/container/GuiFurnace.java similarity index 100% rename from client/src/main/java/client/gui/container/GuiFurnace.java rename to client/src/client/gui/container/GuiFurnace.java diff --git a/client/src/main/java/client/gui/container/GuiHopper.java b/client/src/client/gui/container/GuiHopper.java similarity index 100% rename from client/src/main/java/client/gui/container/GuiHopper.java rename to client/src/client/gui/container/GuiHopper.java diff --git a/client/src/main/java/client/gui/container/GuiEntity.java b/client/src/client/gui/container/GuiHorse.java similarity index 56% rename from client/src/main/java/client/gui/container/GuiEntity.java rename to client/src/client/gui/container/GuiHorse.java index a4aa4bb..ad5cf54 100755 --- a/client/src/main/java/client/gui/container/GuiEntity.java +++ b/client/src/client/gui/container/GuiHorse.java @@ -1,26 +1,45 @@ package client.gui.container; import client.Client; -import common.entity.Entity; -import common.inventory.ContainerEntityInventory; +import common.entity.animal.EntityHorse; +import common.inventory.ContainerHorseInventory; import common.inventory.IInventory; -public class GuiEntity extends GuiContainer +public class GuiHorse extends GuiContainer { - private IInventory playerInventory; - private IInventory entityInventory; +// private static final String horseGuiTextures = "textures/gui/horse.png"; - public GuiEntity(IInventory playerInv, IInventory entityInv, Entity entity) + /** The player inventory bound to this GUI. */ + private IInventory playerInventory; + + /** The horse inventory bound to this GUI. */ + private IInventory horseInventory; + +// /** The EntityHorse whose inventory is currently being accessed. */ +// private EntityHorse horseEntity; + +// /** The mouse x-position recorded during the last rendered frame. */ +// private float mousePosx; +// +// /** The mouse y-position recorded during the last renderered frame. */ +// private float mousePosY; + + public GuiHorse(IInventory playerInv, IInventory horseInv, EntityHorse horse) { - super(new ContainerEntityInventory(playerInv, entityInv, entity, Client.CLIENT.player)); + super(new ContainerHorseInventory(playerInv, horseInv, horse, Client.CLIENT.player)); this.playerInventory = playerInv; - this.entityInventory = entityInv; + this.horseInventory = horseInv; +// this.horseEntity = horse; +// this.allowUserInput = false; } + /** + * Draw the foreground layer for the GuiContainer (everything in front of the items). Args : mouseX, mouseY + */ public void drawGuiContainerForegroundLayer() { - this.drawString(this.entityInventory.getCommandName(), 8, 6); + this.drawString(this.horseInventory.getCommandName(), 8, 6); this.drawString(this.playerInventory.getCommandName(), 8, this.ySize - 96 + 2); } diff --git a/client/src/main/java/client/gui/container/GuiInventory.java b/client/src/client/gui/container/GuiInventory.java similarity index 100% rename from client/src/main/java/client/gui/container/GuiInventory.java rename to client/src/client/gui/container/GuiInventory.java diff --git a/client/src/client/gui/container/GuiMachine.java b/client/src/client/gui/container/GuiMachine.java new file mode 100755 index 0000000..2467e18 --- /dev/null +++ b/client/src/client/gui/container/GuiMachine.java @@ -0,0 +1,44 @@ +package client.gui.container; + +import client.Client; +import common.inventory.ContainerMachine; +import common.inventory.IInventory; +import common.inventory.InventoryPlayer; +import common.tileentity.TileEntityMachine; + + +public class GuiMachine extends GuiContainer +{ +// private final String texture; + private final IInventory playerInv; + private final IInventory machineInv; + private final TileEntityMachine machine; + + public GuiMachine(InventoryPlayer player, IInventory inv, TileEntityMachine machine) + { + super(new ContainerMachine(player, machine, inv, Client.CLIENT.player)); + this.playerInv = player; + this.machineInv = machine; +// this.allowUserInput = false; + this.ySize = 153; +// this.texture = "textures/gui/" + texture + ".png"; + this.machine = machine; + } + + public void drawGuiContainerForegroundLayer() + { + this.drawString(this.machine.getStatus().color + this.machineInv.getCommandName() + " - " + this.machine.getStatus().name, 8, 6); + this.drawString(this.playerInv.getCommandName(), 8, this.ySize - 96 + 2); + this.drawString(String.format("Temperatur: %d °", this.machine.getTemperature()), 8, 18); + this.drawString(this.machine.formatDisplay(), 8, 28); + } + +// protected void drawGuiContainerBackgroundLayer(int mouseX, int mouseY) +// { +// GlState.color(1.0F, 1.0F, 1.0F, 1.0F); +// this.gm.getTextureManager().bindTexture(this.texture); +// int i = (this.width - this.xSize) / 2; +// int j = (this.height - this.ySize) / 2; +//// this.rect(i, j, 0, 0, this.xSize, this.ySize); +// } +} diff --git a/client/src/main/java/client/gui/container/GuiMerchant.java b/client/src/client/gui/container/GuiMerchant.java similarity index 96% rename from client/src/main/java/client/gui/container/GuiMerchant.java rename to client/src/client/gui/container/GuiMerchant.java index f76faa9..0b1543e 100755 --- a/client/src/main/java/client/gui/container/GuiMerchant.java +++ b/client/src/client/gui/container/GuiMerchant.java @@ -81,9 +81,9 @@ public class GuiMerchant extends GuiContainer if (merchantrecipelist != null && !merchantrecipelist.isEmpty()) { int k = this.selectedMerchantRecipe; MerchantRecipe merchantrecipe = (MerchantRecipe)merchantrecipelist.get(k); - ItemStack itemstack = merchantrecipe.first(); - ItemStack itemstack1 = merchantrecipe.second(); - ItemStack itemstack2 = merchantrecipe.result(); + ItemStack itemstack = merchantrecipe.getItemToBuy(); + ItemStack itemstack1 = merchantrecipe.getSecondItemToBuy(); + ItemStack itemstack2 = merchantrecipe.getItemToSell(); this.renderItemOverlayIntoGUI(itemstack, 36, 24, null); if(itemstack1 != null) this.renderItemOverlayIntoGUI(itemstack1, 62, 24, null); @@ -180,9 +180,9 @@ public class GuiMerchant extends GuiContainer // int j = (this.height - this.ySize) / 2; int k = this.selectedMerchantRecipe; MerchantRecipe merchantrecipe = (MerchantRecipe)merchantrecipelist.get(k); - ItemStack itemstack = merchantrecipe.first(); - ItemStack itemstack1 = merchantrecipe.second(); - ItemStack itemstack2 = merchantrecipe.result(); + ItemStack itemstack = merchantrecipe.getItemToBuy(); + ItemStack itemstack1 = merchantrecipe.getSecondItemToBuy(); + ItemStack itemstack2 = merchantrecipe.getItemToSell(); GL11.glPushMatrix(); ItemRenderer.enableGUIStandardItemLighting(); GlState.disableLighting(); diff --git a/client/src/main/java/client/gui/container/GuiRepair.java b/client/src/client/gui/container/GuiRepair.java similarity index 98% rename from client/src/main/java/client/gui/container/GuiRepair.java rename to client/src/client/gui/container/GuiRepair.java index b8257bc..2d7dfb7 100755 --- a/client/src/main/java/client/gui/container/GuiRepair.java +++ b/client/src/client/gui/container/GuiRepair.java @@ -68,7 +68,7 @@ public class GuiRepair extends GuiContainer implements ICrafting { int i = 8453920; boolean flag = true; - String s = String.format("Manakosten: %d", this.anvil.maximumCost); + String s = String.format("Erfahrungskosten: %d", this.anvil.maximumCost); if (this.anvil.maximumCost >= 40) // && !this.gm.thePlayer.creative) { diff --git a/client/src/main/java/client/gui/element/ActButton.java b/client/src/client/gui/element/ActButton.java similarity index 100% rename from client/src/main/java/client/gui/element/ActButton.java rename to client/src/client/gui/element/ActButton.java diff --git a/client/src/main/java/client/gui/element/Area.java b/client/src/client/gui/element/Area.java similarity index 100% rename from client/src/main/java/client/gui/element/Area.java rename to client/src/client/gui/element/Area.java diff --git a/client/src/main/java/client/gui/element/Bar.java b/client/src/client/gui/element/Bar.java similarity index 100% rename from client/src/main/java/client/gui/element/Bar.java rename to client/src/client/gui/element/Bar.java diff --git a/client/src/main/java/client/gui/element/ButtonCallback.java b/client/src/client/gui/element/ButtonCallback.java similarity index 100% rename from client/src/main/java/client/gui/element/ButtonCallback.java rename to client/src/client/gui/element/ButtonCallback.java diff --git a/client/src/main/java/client/gui/element/Dropdown.java b/client/src/client/gui/element/Dropdown.java similarity index 89% rename from client/src/main/java/client/gui/element/Dropdown.java rename to client/src/client/gui/element/Dropdown.java index 773cda0..a49b053 100644 --- a/client/src/main/java/client/gui/element/Dropdown.java +++ b/client/src/client/gui/element/Dropdown.java @@ -17,7 +17,7 @@ public class Dropdown extends Element { for(T value : Dropdown.this.values) { if(sb.length() > 0) sb.append('\n'); - sb.append(value instanceof Displayable disp ? disp.getDisplay() : value.toString()); + sb.append(value instanceof Displayable ? ((Displayable)value).getDisplay() : value.toString()); } this.setText(sb.toString()); this.visible = /* this.r_dirty = */ false; @@ -82,15 +82,10 @@ public class Dropdown extends Element { } public Dropdown(int x, int y, int w, int h, boolean up, T[] values, T def, T init, DropdownCallback callback, final String text) { - this(x, y, w, h, up, values, def, init, callback, text == null ? new Formatter>() { + this(x, y, w, h, up, values, def, init, callback, new Formatter>() { public String use(Dropdown elem) { T value = elem.getValue(); - return value instanceof Displayable disp ? disp.getDisplay() : value.toString(); - } - } : new Formatter>() { - public String use(Dropdown elem) { - T value = elem.getValue(); - return String.format("%s: %s", text, value instanceof Displayable disp ? disp.getDisplay() : value.toString()); + return String.format("%s: %s", text, value instanceof Displayable ? ((Displayable)value).getDisplay() : value.toString()); } }); } diff --git a/client/src/main/java/client/gui/element/DropdownCallback.java b/client/src/client/gui/element/DropdownCallback.java similarity index 100% rename from client/src/main/java/client/gui/element/DropdownCallback.java rename to client/src/client/gui/element/DropdownCallback.java diff --git a/client/src/main/java/client/gui/element/Element.java b/client/src/client/gui/element/Element.java similarity index 94% rename from client/src/main/java/client/gui/element/Element.java rename to client/src/client/gui/element/Element.java index f670156..f5f8b88 100644 --- a/client/src/main/java/client/gui/element/Element.java +++ b/client/src/client/gui/element/Element.java @@ -15,8 +15,6 @@ import common.sound.PositionedSound; import common.util.Util; public abstract class Element { - public static final int BASE_HEIGHT = 18; - protected final Client gm = Client.CLIENT; protected Gui gui; @@ -38,11 +36,12 @@ public abstract class Element { public boolean visible = true; public boolean enabled = true; + public Element(int x, int y, int w, int h, Formatter formatter) { this.pos_x = x; this.pos_y = y; this.size_x = w; - this.size_y = h <= 0 ? BASE_HEIGHT : h; + this.size_y = h; this.format = formatter; // gui_update_style(this, 1); // if(type != ElemType.SLIDER) { @@ -113,8 +112,8 @@ public abstract class Element { public void updateText() { Vec2i size = Drawing.getSize(this.text); - this.text_x = ((this.size_x - (this.margin_x1 + this.margin_x2)) - size.xpos) / 2; - this.text_y = ((this.size_y - (this.margin_y1 + this.margin_y2)) - size.ypos + 1) / 2; + this.text_x = (this.size_x - size.xpos) / 2; + this.text_y = (this.size_y - size.ypos) / 2; } public void setText(String str) { @@ -221,7 +220,7 @@ public abstract class Element { int x2 = this.size_x - (this.margin_x1 + this.margin_x2); int y2 = this.size_y - (this.margin_y1 + this.margin_y2); // if(elem.type == ElemType.FIELD) { - this.gm.scissor(x1 < 0 ? 0 : x1, (this.gm.fb_y - (y1 + y2)) < 0 ? 0 : (this.gm.fb_y - (y1 + y2)), x2 < 0 ? 0 : x2, y2 < 0 ? 0 : y2); + GL11.glScissor(x1 < 0 ? 0 : x1, (this.gm.fb_y - (y1 + y2)) < 0 ? 0 : (this.gm.fb_y - (y1 + y2)), x2 < 0 ? 0 : x2, y2 < 0 ? 0 : y2); GL11.glEnable(GL11.GL_SCISSOR_TEST); // } // if(this.type == ElemType.CUSTOM) diff --git a/client/src/main/java/client/gui/element/Field.java b/client/src/client/gui/element/Field.java similarity index 96% rename from client/src/main/java/client/gui/element/Field.java rename to client/src/client/gui/element/Field.java index 78340d0..bd82813 100644 --- a/client/src/main/java/client/gui/element/Field.java +++ b/client/src/client/gui/element/Field.java @@ -34,7 +34,7 @@ public class Field extends Textbox { public void updateText() { this.textWidth = Drawing.txt_size(this.pos_x + this.margin_x1, this.pos_y + this.margin_y1, this.pos_x + this.margin_x1, this.pos_y + this.margin_y1, - Integer.MAX_VALUE, Integer.MAX_VALUE, this.getDrawnText()).xpos; + Integer.MAX_VALUE, Integer.MAX_VALUE, this.text).xpos; } public void mouserel() { @@ -95,7 +95,7 @@ public class Field extends Textbox { protected void updateCursor(int offset, boolean shift, int x1, int y1, int x2, int y2) { Vec2i coord = Drawing.txt_coord(offset, x1 + this.text_x, y1 + this.text_y, - x1 + this.text_x, y1 + this.text_y, 0x7fffffff, 0x7fffffff, this.getDrawnText()); + x1 + this.text_x, y1 + this.text_y, 0x7fffffff, 0x7fffffff, this.text); this.cursorPos = coord.xpos; if(shift) { if(this.cursorPos < x1) @@ -108,7 +108,7 @@ public class Field extends Textbox { protected int onCursorOffset(int x, int y, int x1, int y1, int x2, int y2) { Offset off = Drawing.txt_offset(x, y, x1 + this.text_x, y1 + this.text_y, - x1 + this.text_x, y1 + this.text_y, 0x7fffffff, 0x7fffffff, this.getDrawnText()); + x1 + this.text_x, y1 + this.text_y, 0x7fffffff, 0x7fffffff, this.text); if(off != null) { this.cursorPos = off.xpos; } @@ -130,21 +130,17 @@ public class Field extends Textbox { protected void drawForeground(int x1, int y1, int x2, int y2) { Drawing.txt_draw(x1 + this.text_x, y1 + this.text_y, x1 + this.text_x, y1 + this.text_y, - Integer.MAX_VALUE, Integer.MAX_VALUE, this.enabled ? this.gm.style.text_field : Util.mulColor(this.gm.style.text_field, 0.5f), this.getDrawnText()); + Integer.MAX_VALUE, Integer.MAX_VALUE, this.enabled ? this.gm.style.text_field : Util.mulColor(this.gm.style.text_field, 0.5f), this.text); if(this.sel_start >= 0 && this.sel_end != this.sel_start) Drawing.txt_overlay(this.sel_start, this.sel_end, x1 + this.text_x, y1 + this.text_y, x1 + this.text_x, y1 + this.text_y, - Integer.MAX_VALUE, Integer.MAX_VALUE, this.enabled ? 0x808080ff : 0x80404040, this.getDrawnText()); + Integer.MAX_VALUE, Integer.MAX_VALUE, this.enabled ? 0x808080ff : 0x80404040, this.text); } protected char getNewline() { return ' '; } - protected String getDrawnText() { - return this.text; - } - diff --git a/client/src/main/java/client/gui/element/FieldAction.java b/client/src/client/gui/element/FieldAction.java similarity index 100% rename from client/src/main/java/client/gui/element/FieldAction.java rename to client/src/client/gui/element/FieldAction.java diff --git a/client/src/main/java/client/gui/element/FieldCallback.java b/client/src/client/gui/element/FieldCallback.java similarity index 100% rename from client/src/main/java/client/gui/element/FieldCallback.java rename to client/src/client/gui/element/FieldCallback.java diff --git a/client/src/main/java/client/gui/element/Fill.java b/client/src/client/gui/element/Fill.java similarity index 87% rename from client/src/main/java/client/gui/element/Fill.java rename to client/src/client/gui/element/Fill.java index 7067dcf..5fecb12 100644 --- a/client/src/main/java/client/gui/element/Fill.java +++ b/client/src/client/gui/element/Fill.java @@ -50,8 +50,8 @@ public class Fill extends Element { public void updateText() { Vec2i size = Drawing.getSize(this.text); if(!this.left) - this.text_x = ((this.size_x - (this.margin_x1 + this.margin_x2)) - size.xpos) / 2; + this.text_x = (this.size_x - size.xpos) / 2; if(!this.top) - this.text_y = ((this.size_y - (this.margin_y1 + this.margin_y2)) - size.ypos + 1) / 2; + this.text_y = (this.size_y - size.ypos) / 2; } } diff --git a/client/src/client/gui/element/GuiList.java b/client/src/client/gui/element/GuiList.java new file mode 100755 index 0000000..1f4ac01 --- /dev/null +++ b/client/src/client/gui/element/GuiList.java @@ -0,0 +1,413 @@ +package client.gui.element; + +import java.util.List; + +import org.lwjgl.opengl.GL11; + +import client.gui.Gui; +import client.renderer.DefaultVertexFormats; +import client.renderer.Drawing; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.window.Button; +import common.collect.Lists; +import common.util.ExtMath; + +public abstract class GuiList extends Gui +{ + protected final List elements = Lists.newArrayList(); + + protected int width; + protected int height; + + protected int top; + protected int bottom; + protected int right; + protected int left; + protected int mouseX; + protected int mouseY; + protected int initialClickY = -2; + protected float scrollMultiplier; + protected float amountScrolled; + protected int selectedElement = -1; + protected long lastClicked; + + public abstract int getListWidth(); // 220 + + public abstract int getSlotHeight(); + + protected int getScrollBarX() + { + return 0; + } + + public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn) + { + this.width = widthIn; + this.height = heightIn; + this.top = topIn; + this.bottom = bottomIn; + this.left = 0; + this.right = widthIn; + } + + public void init(int width, int height) { + + this.selectedElement = -1; + } + + public void setSlotXBoundsFromLeft(int leftIn) + { + this.left = leftIn; + this.right = leftIn + this.width; + } + + public final T getListEntry(int index) { + return this.elements.get(index); + } + + public final T getSelected() { + return this.selectedElement < 0 ? null : this.elements.get(this.selectedElement); + } + + public final int getSize() { + return this.elements.size(); + } + + public final void setSelected(int index) { + this.selectedElement = index; + } + + protected int getContentHeight() + { + return this.getSize() * this.getSlotHeight(); + } + + public int getSlotIndexFromScreenCoords(int x, int y) + { + int i = this.left + this.width / 2 - this.getListWidth() / 2; + int j = this.left + this.width / 2 + this.getListWidth() / 2; + int k = y - this.top + (int)this.amountScrolled - 4; + int l = k / this.getSlotHeight(); + return this.isInList(x, y) && x >= i && x <= j && l >= 0 && k >= 0 && l < this.getSize() ? l : -1; + } + + protected boolean isInList(int x, int y) + { + return x >= this.getScrollBarX() + 6; // x < this.getScrollBarX(); + } + + protected final boolean isSelected(int slotIndex) + { + return slotIndex == this.selectedElement; + } + + protected void bindAmountScrolled() + { + this.amountScrolled = ExtMath.clampf(this.amountScrolled, 0.0F, (float)this.getMaxScroll()); + } + + public int getMaxScroll() + { + return Math.max(0, this.getContentHeight() - (this.bottom - this.top - 4)); + } + + public int getAmountScrolled() + { + return (int)this.amountScrolled; + } + + public boolean isMouseYWithinSlotBounds(int p_148141_1_) + { + return p_148141_1_ >= this.top && p_148141_1_ <= this.bottom && this.mouseX >= this.left && this.mouseX <= this.right; + } + + public void scrollBy(int amount) + { + this.amountScrolled += (float)amount; + this.bindAmountScrolled(); + this.initialClickY = -2; + } + +// public void actionPerformed(Button button) +// { +// if (button.enabled) +// { +// if (button.id == this.scrollUpButtonID) +// { +// this.amountScrolled -= (float)(this.slotHeight * 2 / 3); +// this.initialClickY = -2; +// this.bindAmountScrolled(); +// } +// else if (button.id == this.scrollDownButtonID) +// { +// this.amountScrolled += (float)(this.slotHeight * 2 / 3); +// this.initialClickY = -2; +// this.bindAmountScrolled(); +// } +// } +// } + + public void draw() + { + int mouseXIn = this.gm.mouse_x; + int mouseYIn = this.gm.mouse_y; + this.mouseX = mouseXIn; + this.mouseY = mouseYIn; + this.drawBackground(); + int i = this.getScrollBarX(); + int j = i + 6; + this.bindAmountScrolled(); + GlState.disableLighting(); + GlState.disableFog(); + GlState.enableTexture2D(); + RenderBuffer worldrenderer = Tessellator.getBuffer(); + this.gm.getTextureManager().bindTexture(Gui.DIRT_BACKGROUND); + GlState.color(1.0F, 1.0F, 1.0F, 1.0F); + + float f = 32.0F; + worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos((double)0, (double)this.bottom, 0.0D).tex((double)((float)0 / f), (double)((float)(this.bottom + (int)this.amountScrolled) / f)).color(32, 32, 32, 255).endVertex(); + worldrenderer.pos((double)this.gm.fb_x, (double)this.bottom, 0.0D).tex((double)((float)this.gm.fb_x / f), (double)((float)(this.bottom + (int)this.amountScrolled) / f)).color(32, 32, 32, 255).endVertex(); + worldrenderer.pos((double)this.gm.fb_x, (double)this.top, 0.0D).tex((double)((float)this.gm.fb_x / f), (double)((float)(this.top + (int)this.amountScrolled) / f)).color(32, 32, 32, 255).endVertex(); + worldrenderer.pos((double)0, (double)this.top, 0.0D).tex((double)((float)0 / f), (double)((float)(this.top + (int)this.amountScrolled) / f)).color(32, 32, 32, 255).endVertex(); + Tessellator.draw(); + + int x = this.left + this.width / 2 - this.getListWidth() / 2 + 2; + int y = this.top + 4 - (int)this.amountScrolled; + + this.drawSelectionBox(x, y, mouseXIn, mouseYIn); + GlState.disableDepth(); + + this.overlayBackground(0, this.top, 255, 255); + this.overlayBackground(this.bottom, this.height, 255, 255); + + GlState.enableBlend(); + GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ZERO, GL11.GL_ONE); + GlState.disableAlpha(); + GlState.shadeModel(GL11.GL_SMOOTH); + GlState.disableTexture2D(); + + int i1 = 4; + worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos((double)0, (double)(this.top + i1), 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 0).endVertex(); + worldrenderer.pos((double)this.gm.fb_x, (double)(this.top + i1), 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 0).endVertex(); + worldrenderer.pos((double)this.gm.fb_x, (double)this.top, 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos((double)0, (double)this.top, 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); + Tessellator.draw(); + worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos((double)0, (double)this.bottom, 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos((double)this.gm.fb_x, (double)this.bottom, 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos((double)this.gm.fb_x, (double)(this.bottom - i1), 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 0).endVertex(); + worldrenderer.pos((double)0, (double)(this.bottom - i1), 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 0).endVertex(); + Tessellator.draw(); + + int j1 = this.getMaxScroll(); + + if (j1 > 0) + { + int k1 = (this.bottom - this.top) * (this.bottom - this.top) / this.getContentHeight(); + k1 = ExtMath.clampi(k1, 32, this.bottom - this.top - 8); + int l1 = (int)this.amountScrolled * (this.bottom - this.top - k1) / j1 + this.top; + + if (l1 < this.top) + { + l1 = this.top; + } + + worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos((double)i, (double)this.bottom, 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos((double)j, (double)this.bottom, 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos((double)j, (double)this.top, 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos((double)i, (double)this.top, 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); + Tessellator.draw(); + worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos((double)i, (double)(l1 + k1), 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255).endVertex(); + worldrenderer.pos((double)j, (double)(l1 + k1), 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255).endVertex(); + worldrenderer.pos((double)j, (double)l1, 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255).endVertex(); + worldrenderer.pos((double)i, (double)l1, 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255).endVertex(); + Tessellator.draw(); + worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos((double)i, (double)(l1 + k1 - 1), 0.0D).tex(0.0D, 1.0D).color(192, 192, 192, 255).endVertex(); + worldrenderer.pos((double)(j - 1), (double)(l1 + k1 - 1), 0.0D).tex(1.0D, 1.0D).color(192, 192, 192, 255).endVertex(); + worldrenderer.pos((double)(j - 1), (double)l1, 0.0D).tex(1.0D, 0.0D).color(192, 192, 192, 255).endVertex(); + worldrenderer.pos((double)i, (double)l1, 0.0D).tex(0.0D, 0.0D).color(192, 192, 192, 255).endVertex(); + Tessellator.draw(); + } + + GlState.enableTexture2D(); + GlState.shadeModel(GL11.GL_FLAT); + GlState.enableAlpha(); + GlState.disableBlend(); + + super.draw(); + } + + public void handleMouseInput() + { + if (this.isMouseYWithinSlotBounds(this.mouseY)) + { +// if (Button.MOUSE_LEFT.isDown() && this.getEnabled()) +// { + if (this.initialClickY == -1) + { + boolean flag1 = true; + + if (this.mouseY >= this.top && this.mouseY <= this.bottom) + { + int j2 = (this.width - this.getListWidth()) / 2; + int k2 = (this.width + this.getListWidth()) / 2; + int l2 = this.mouseY - this.top + (int)this.amountScrolled - 4; + int i1 = l2 / this.getSlotHeight(); + + if (i1 < this.getSize() && this.mouseX >= j2 && this.mouseX <= k2 && i1 >= 0 && l2 >= 0) + { + } + else if (this.mouseX >= j2 && this.mouseX <= k2 && l2 < 0) + { + flag1 = false; + } + + int i3 = this.getScrollBarX(); + int j1 = i3 + 6; + + if (this.mouseX >= i3 && this.mouseX <= j1) + { + this.scrollMultiplier = -1.0F; + int k1 = this.getMaxScroll(); + + if (k1 < 1) + { + k1 = 1; + } + + int l1 = (int)((float)((this.bottom - this.top) * (this.bottom - this.top)) / (float)this.getContentHeight()); + l1 = ExtMath.clampi(l1, 32, this.bottom - this.top - 8); + this.scrollMultiplier /= (float)(this.bottom - this.top - l1) / (float)k1; + } + else + { + this.scrollMultiplier = 1.0F; + } + + if (flag1) + { + this.initialClickY = this.mouseY; + } + else + { + this.initialClickY = -2; + } + } + else + { + this.initialClickY = -2; + } + } + else if (this.initialClickY >= 0) + { + this.amountScrolled -= (float)(this.mouseY - this.initialClickY) * this.scrollMultiplier; + this.initialClickY = this.mouseY; + } +// } +// else +// { +// this.initialClickY = -1; +// } + } + } + + protected void drawSelectionBox(int x, int y, int mouseXIn, int mouseYIn) + { + int size = this.getSize(); + RenderBuffer rb = Tessellator.getBuffer(); + + for (int z = 0; z < size; z++) + { + int y1 = y + z * this.getSlotHeight(); + int h = this.getSlotHeight() - 4; + + if (this.isSelected(z)) + { + int x1 = this.left + (this.width / 2 - this.getListWidth() / 2); + int x2 = this.left + this.width / 2 + this.getListWidth() / 2; + GlState.color(1.0F, 1.0F, 1.0F, 1.0F); + GlState.disableTexture2D(); + rb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + rb.pos((double)x1, (double)(y1 + h + 2), 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255).endVertex(); + rb.pos((double)x2, (double)(y1 + h + 2), 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255).endVertex(); + rb.pos((double)x2, (double)(y1 - 2), 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255).endVertex(); + rb.pos((double)x1, (double)(y1 - 2), 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255).endVertex(); + rb.pos((double)(x1 + 1), (double)(y1 + h + 1), 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + rb.pos((double)(x2 - 1), (double)(y1 + h + 1), 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + rb.pos((double)(x2 - 1), (double)(y1 - 1), 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex(); + rb.pos((double)(x1 + 1), (double)(y1 - 1), 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); + Tessellator.draw(); + GlState.enableTexture2D(); + } + + boolean hover = this.getSlotIndexFromScreenCoords(mouseXIn, mouseYIn) == z; + this.getListEntry(z).draw(x, y1, mouseXIn - x, mouseYIn - y1, hover); + if(hover) + Drawing.drawRect(x - 2, y1 - 2, this.getListWidth(), this.getSlotHeight(), Gui.HOVER_COLOR); + } + } + + protected void overlayBackground(int startY, int endY, int startAlpha, int endAlpha) + { + RenderBuffer rb = Tessellator.getBuffer(); + this.gm.getTextureManager().bindTexture(Gui.DIRT_BACKGROUND); + GlState.color(1.0F, 1.0F, 1.0F, 1.0F); + float f = 32.0F; + rb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + rb.pos((double)0, (double)endY, 0.0D).tex(0.0D, (double)((float)endY / 32.0F)).color(64, 64, 64, endAlpha).endVertex(); + rb.pos((double)this.gm.fb_x, (double)endY, 0.0D).tex((double)((float)this.gm.fb_x / 32.0F), (double)((float)endY / 32.0F)).color(64, 64, 64, endAlpha).endVertex(); + rb.pos((double)this.gm.fb_x, (double)startY, 0.0D).tex((double)((float)this.gm.fb_x / 32.0F), (double)((float)startY / 32.0F)).color(64, 64, 64, startAlpha).endVertex(); + rb.pos((double)0, (double)startY, 0.0D).tex(0.0D, (double)((float)startY / 32.0F)).color(64, 64, 64, startAlpha).endVertex(); + Tessellator.draw(); + } + + public void mouse(Button btn, int x, int y, boolean ctrl, boolean shift) + { + super.mouse(btn, x, y, ctrl, shift); + if (this.isMouseYWithinSlotBounds(y)) + { + int i = this.getSlotIndexFromScreenCoords(x, y); + + if (i >= 0) + { + int j = this.left + this.width / 2 - this.getListWidth() / 2 + 2; + int k = this.top + 4 - this.getAmountScrolled() + i * this.getSlotHeight(); + int l = x - j; + int i1 = y - k; + + boolean flag = i == this.selectedElement && System.currentTimeMillis() - this.lastClicked < (long)this.gm.dclickDelay; + this.selectedElement = i; + this.lastClicked = System.currentTimeMillis(); + + this.getListEntry(i).select(flag, l, i1); + } + } + if(btn == Button.MOUSE_LEFT && this.clicked(x, y) == null) + this.handleMouseInput(); + } + + public void mouserel(Button btn, int x, int y) { + super.mouserel(btn, x, y); + if(btn == Button.MOUSE_LEFT) + this.initialClickY = -1; + } + + public void scroll(int scr_x, int scr_y, int x, int y, boolean ctrl, boolean shift) { + super.scroll(scr_x, scr_y, x, y, ctrl, shift); + if(scr_y != 0 && this.clicked(x, y) == null) + this.amountScrolled -= (float)(ExtMath.clampi(scr_y, -1, 1) * this.getSlotHeight() / 2); + } + + public void drag(int x, int y) { + super.drag(x, y); + if(this.selected == null && Button.MOUSE_LEFT.isDown()) + this.handleMouseInput(); + } +} diff --git a/client/src/main/java/client/gui/element/InventoryButton.java b/client/src/client/gui/element/InventoryButton.java similarity index 100% rename from client/src/main/java/client/gui/element/InventoryButton.java rename to client/src/client/gui/element/InventoryButton.java diff --git a/client/src/main/java/client/gui/element/Label.java b/client/src/client/gui/element/Label.java similarity index 54% rename from client/src/main/java/client/gui/element/Label.java rename to client/src/client/gui/element/Label.java index b371741..7420a1d 100644 --- a/client/src/main/java/client/gui/element/Label.java +++ b/client/src/client/gui/element/Label.java @@ -4,30 +4,16 @@ import client.renderer.Drawing; import common.util.Util; public class Label extends Fill { - public static final int LABEL_HEIGHT = 14; - public Label(int x, int y, int w, int h, String text, boolean top, boolean left) { - super(x, y, w, h <= 0 ? LABEL_HEIGHT : h, text, top, left); + super(x, y, w, h, text, top, left); } public Label(int x, int y, int w, int h, String text, boolean left) { - super(x, y, w, h <= 0 ? LABEL_HEIGHT : h, text, left); + super(x, y, w, h, text, left); } public Label(int x, int y, int w, int h, String text) { - super(x, y, w, h <= 0 ? LABEL_HEIGHT : h, text); - } - - public Label(int x, int y, int w, String text, boolean top, boolean left) { - super(x, y - LABEL_HEIGHT, w, LABEL_HEIGHT, text, top, left); - } - - public Label(int x, int y, int w, String text, boolean left) { - super(x, y - LABEL_HEIGHT, w, LABEL_HEIGHT, text, left); - } - - public Label(int x, int y, int w, String text) { - super(x, y - LABEL_HEIGHT, w, LABEL_HEIGHT, text); + super(x, y, w, h, text); } protected void drawBackground() { diff --git a/client/src/main/java/client/gui/element/ListEntry.java b/client/src/client/gui/element/ListEntry.java similarity index 53% rename from client/src/main/java/client/gui/element/ListEntry.java rename to client/src/client/gui/element/ListEntry.java index 1360285..76236d1 100644 --- a/client/src/main/java/client/gui/element/ListEntry.java +++ b/client/src/client/gui/element/ListEntry.java @@ -2,6 +2,6 @@ package client.gui.element; public interface ListEntry { - void draw(int x, int y, int width, int height, int mouseX, int mouseY, boolean hovered); + void draw(int x, int y, int mouseX, int mouseY, boolean hovered); void select(boolean dclick, int mx, int my); } \ No newline at end of file diff --git a/client/src/main/java/client/gui/element/NavButton.java b/client/src/client/gui/element/NavButton.java similarity index 100% rename from client/src/main/java/client/gui/element/NavButton.java rename to client/src/client/gui/element/NavButton.java diff --git a/client/src/client/gui/element/PasswordField.java b/client/src/client/gui/element/PasswordField.java new file mode 100644 index 0000000..efd3d9a --- /dev/null +++ b/client/src/client/gui/element/PasswordField.java @@ -0,0 +1,20 @@ +package client.gui.element; + +import client.renderer.Drawing; +import common.util.Util; + +public class PasswordField extends Field { + public PasswordField(int x, int y, int w, int h, int cap, FieldCallback callback, String text) { + super(x, y, w, h, cap, callback, text); + } + + protected void drawForeground(int x1, int y1, int x2, int y2) { + Drawing.txt_draw(x1 + this.text_x, y1 + this.text_y, + x1 + this.text_x, y1 + this.text_y, + Integer.MAX_VALUE, Integer.MAX_VALUE, this.enabled ? this.gm.style.text_field : Util.mulColor(this.gm.style.text_field, 0.5f), this.text.isEmpty() ? "" : "****"); + } + + protected int getCursorX(int x1, int x2) { + return x1; + } +} diff --git a/client/src/main/java/client/gui/element/PressType.java b/client/src/client/gui/element/PressType.java similarity index 100% rename from client/src/main/java/client/gui/element/PressType.java rename to client/src/client/gui/element/PressType.java diff --git a/client/src/main/java/client/gui/element/SelectableButton.java b/client/src/client/gui/element/SelectableButton.java similarity index 100% rename from client/src/main/java/client/gui/element/SelectableButton.java rename to client/src/client/gui/element/SelectableButton.java diff --git a/client/src/main/java/client/gui/element/Slider.java b/client/src/client/gui/element/Slider.java similarity index 98% rename from client/src/main/java/client/gui/element/Slider.java rename to client/src/client/gui/element/Slider.java index 5df5d99..347cef9 100644 --- a/client/src/main/java/client/gui/element/Slider.java +++ b/client/src/client/gui/element/Slider.java @@ -7,7 +7,7 @@ import common.util.ExtMath; import common.util.Util; public class Slider extends Element { - private static final int SLIDER_WIDTH = 8; + private static final int SLIDER_WIDTH = 10; private final SliderCallback func; private final int def; @@ -21,7 +21,7 @@ public class Slider extends Element { public Slider(int x, int y, int w, int h, int prec, int min, int max, int def, int init, SliderCallback callback, Formatter formatter) { super(x, y, w, h, formatter); - this.handle = ((this.size_y * SLIDER_WIDTH) / BASE_HEIGHT) & ~1; + this.handle = ((this.size_y * SLIDER_WIDTH) / 24) & ~1; this.func = callback; this.precision = prec; this.min = min; diff --git a/client/src/main/java/client/gui/element/SliderCallback.java b/client/src/client/gui/element/SliderCallback.java similarity index 100% rename from client/src/main/java/client/gui/element/SliderCallback.java rename to client/src/client/gui/element/SliderCallback.java diff --git a/client/src/main/java/client/gui/element/SliderFloatCallback.java b/client/src/client/gui/element/SliderFloatCallback.java similarity index 100% rename from client/src/main/java/client/gui/element/SliderFloatCallback.java rename to client/src/client/gui/element/SliderFloatCallback.java diff --git a/client/src/main/java/client/gui/element/Switch.java b/client/src/client/gui/element/Switch.java similarity index 96% rename from client/src/main/java/client/gui/element/Switch.java rename to client/src/client/gui/element/Switch.java index 02449a8..878ebcc 100644 --- a/client/src/main/java/client/gui/element/Switch.java +++ b/client/src/client/gui/element/Switch.java @@ -25,7 +25,7 @@ public class Switch extends Element { this(x, y, w, h, values, def, init, callback, new Formatter>() { public String use(Switch elem) { T value = elem.getValue(); - return String.format("%s: %s", text, value instanceof Displayable disp ? disp.getDisplay() : value.toString()); + return String.format("%s: %s", text, value instanceof Displayable ? ((Displayable)value).getDisplay() : value.toString()); } }); } diff --git a/client/src/main/java/client/gui/element/SwitchCallback.java b/client/src/client/gui/element/SwitchCallback.java similarity index 100% rename from client/src/main/java/client/gui/element/SwitchCallback.java rename to client/src/client/gui/element/SwitchCallback.java diff --git a/client/src/main/java/client/gui/element/TextCallback.java b/client/src/client/gui/element/TextCallback.java similarity index 100% rename from client/src/main/java/client/gui/element/TextCallback.java rename to client/src/client/gui/element/TextCallback.java diff --git a/client/src/main/java/client/gui/element/Textbox.java b/client/src/client/gui/element/Textbox.java similarity index 94% rename from client/src/main/java/client/gui/element/Textbox.java rename to client/src/client/gui/element/Textbox.java index dd69674..fa82c1a 100644 --- a/client/src/main/java/client/gui/element/Textbox.java +++ b/client/src/client/gui/element/Textbox.java @@ -2,6 +2,7 @@ package client.gui.element; import org.lwjgl.opengl.GL11; +import client.Timing; import client.gui.Font; import client.renderer.Drawing; import client.window.Button; @@ -51,10 +52,6 @@ abstract class Textbox extends Element { return 4; } - protected boolean canCopy() { - return true; - } - public void setText(String str) { if(this.validator != null) str = this.validator.filter(str); @@ -66,14 +63,14 @@ abstract class Textbox extends Element { public void mouse(Button btn, int x, int y, boolean ctrl, boolean shift) { if(btn == Button.MOUSE_LEFT) { - if(!shift && ((System.currentTimeMillis() - this.tmr_leftmb) <= (long)this.gm.dclickDelay)) { + if(!shift && ((Timing.tmr_current - this.tmr_leftmb) <= (((long)this.gm.dclickDelay) * 1000L))) { this.sel_start = this.sel_drag = 0; this.sel_end = this.text.length(); } else { gui_text_select(x, y, shift); } - this.tmr_leftmb = System.currentTimeMillis(); + this.tmr_leftmb = Timing.tmr_current; } else if((btn == Button.MOUSE_MIDDLE) && this.func != null) { this.func.use(this, FieldAction.FUNCTION); @@ -95,7 +92,7 @@ abstract class Textbox extends Element { this.sel_end = this.text.length(); } else if(ctrl && (key == Keysym.C) || (this.editable && (key == Keysym.X))) { - if(this.canCopy() && this.sel_start >= 0 && this.sel_start != this.sel_end) { // fix empty + if(this.sel_start >= 0 && this.sel_start != this.sel_end) { // fix empty String str = Util.strip(this.text, this.sel_start, this.sel_end - this.sel_start, '\n', (char)0, '?'); Window.setClipboard(str); if(key == Keysym.X) @@ -180,7 +177,7 @@ abstract class Textbox extends Element { this.tmr_scroll -= ((long)n) * 1000000L; else this.tmr_scroll = 0L; - this.tmr_scroll += this.gm.getPassedTime(); + this.tmr_scroll += Timing.tmr_delta; return n; } return 0; @@ -242,7 +239,7 @@ abstract class Textbox extends Element { int y1 = this.pos_y + this.margin_y1; int x2 = this.size_x - (this.margin_x1 + this.margin_x2); int y2 = this.size_y - (this.margin_y1 + this.margin_y2); - this.gm.scissor(x1 < 0 ? 0 : x1, (this.gm.fb_y - (y1 + y2)) < 0 ? 0 : (this.gm.fb_y - (y1 + y2)), x2 < 0 ? 0 : x2, y2 < 0 ? 0 : y2); + GL11.glScissor(x1 < 0 ? 0 : x1, (this.gm.fb_y - (y1 + y2)) < 0 ? 0 : (this.gm.fb_y - (y1 + y2)), x2 < 0 ? 0 : x2, y2 < 0 ? 0 : y2); GL11.glEnable(GL11.GL_SCISSOR_TEST); Drawing.drawRect(this.getCursorX(x1, x2), this.getCursorY(y1, y2), 1, Font.YGLYPH, 0xff000000 | (~Util.mixColor(this.gm.style.field_top, this.gm.style.field_btm))); GL11.glDisable(GL11.GL_SCISSOR_TEST); diff --git a/client/src/main/java/client/gui/element/Toggle.java b/client/src/client/gui/element/Toggle.java similarity index 88% rename from client/src/main/java/client/gui/element/Toggle.java rename to client/src/client/gui/element/Toggle.java index ea0467d..b020dd5 100644 --- a/client/src/main/java/client/gui/element/Toggle.java +++ b/client/src/client/gui/element/Toggle.java @@ -34,8 +34,7 @@ public class Toggle extends Element { // this.type = this.value != 0 ? ElemType.TOGGLE_ON : ElemType.TOGGLE_OFF; // gui_update_style(this, 1); // this.r_dirty = true; - if(this.func != null) - this.func.use(this, this.value); + this.func.use(this, this.value); this.formatText(); this.playSound(); } @@ -51,15 +50,4 @@ public class Toggle extends Element { else super.drawBackground(); } - - public void setValue(boolean value) { - if(this.value != value) { - this.value = value; - this.formatText(); - } - } - - public boolean getValue() { - return this.value; - } } diff --git a/client/src/main/java/client/gui/element/ToggleCallback.java b/client/src/client/gui/element/ToggleCallback.java similarity index 100% rename from client/src/main/java/client/gui/element/ToggleCallback.java rename to client/src/client/gui/element/ToggleCallback.java diff --git a/client/src/main/java/client/gui/element/TransparentArea.java b/client/src/client/gui/element/TransparentArea.java similarity index 100% rename from client/src/main/java/client/gui/element/TransparentArea.java rename to client/src/client/gui/element/TransparentArea.java diff --git a/client/src/main/java/client/gui/ingame/GuiForm.java b/client/src/client/gui/ingame/GuiForm.java similarity index 79% rename from client/src/main/java/client/gui/ingame/GuiForm.java rename to client/src/client/gui/ingame/GuiForm.java index 510de33..3533242 100644 --- a/client/src/main/java/client/gui/ingame/GuiForm.java +++ b/client/src/client/gui/ingame/GuiForm.java @@ -32,22 +32,23 @@ public class GuiForm extends Gui implements ButtonCallback { private boolean sent; public void init(int width, int height) { - this.add(new Label(0, -100, 300, 0, this.title)); + this.add(new Label(0, -100, 300, 20, this.title)); for(int z = 0; z < this.inputs.length; z++) { final int index = z; - final String name = this.inputData[z].first(); - Object obj = this.inputData[z].second(); - int param = this.inputData[z].third(); - if(obj instanceof Boolean bool) { - this.inputs[z] = this.add(new Toggle(0, 50 * z, 300, 0, bool, bool, new ToggleCallback() { + final String name = this.inputData[z].first; + Object obj = this.inputData[z].second; + int param = this.inputData[z].third; + if(obj instanceof Boolean) { + this.inputs[z] = this.add(new Toggle(0, 50 * z, 300, 24, (Boolean)obj, (Boolean)obj, new ToggleCallback() { public void use(Toggle elem, boolean value) { GuiForm.this.outputData[index] = value; } }, name)); } - else if(obj instanceof String[] strs) { + else if(obj instanceof String[]) { + final String[] strs = (String[])obj; param = ExtMath.clampi(param, 0, strs.length - 1); - this.inputs[z] = this.add(new Switch(0, 50 * z, 300, 0, strs, strs[param], strs[param], new SwitchCallback() { + this.inputs[z] = this.add(new Switch(0, 50 * z, 300, 24, strs, strs[param], strs[param], new SwitchCallback() { public void use(Switch elem, String value) { for(int n = 0; n < strs.length; n++) { if(value == strs[n]) { @@ -59,19 +60,19 @@ public class GuiForm extends Gui implements ButtonCallback { }, name)); } else { - this.labels[z] = this.add(new Label(0, 50 * z, 300, name, true)); + this.labels[z] = this.add(new Label(0, 50 * z - 20, 300, 20, name, true)); FieldCallback callback = new FieldCallback() { public void use(Field elem, FieldAction value) { if(value == FieldAction.FOCUS) GuiForm.this.labels[index].setText(name); } }; - this.inputs[z] = this.add((param & 0x80000000) != 0 ? new PasswordField(0, 50 * z, 300, 0, Math.min(param & 0xffff, 1024), callback, (String)obj) : - new Field(0, 50 * z, 300, 0, Math.min(param & 0xffff, 1024), callback, (String)obj)); + this.inputs[z] = this.add((param & 0x80000000) != 0 ? new PasswordField(0, 50 * z, 300, 24, Math.min(param & 0xffff, 256), callback, (String)obj) : + new Field(0, 50 * z, 300, 24, Math.min(param & 0xffff, 256), callback, (String)obj)); } } - this.add(new NavButton(0, 50 * (this.inputs.length + 1), 148, 0, null, "Abbrechen")); - this.add(new ActButton(152, 50 * (this.inputs.length + 1), 148, 0, this, "Senden")); + this.add(new NavButton(0, 50 * (this.inputs.length + 1), 148, 24, null, "Abbrechen")); + this.add(new ActButton(152, 50 * (this.inputs.length + 1), 148, 24, this, "Senden")); this.shift(); } @@ -96,15 +97,15 @@ public class GuiForm extends Gui implements ButtonCallback { this.inputData = data; this.outputData = new Object[data.length]; for(int z = 0; z < data.length; z++) { - Object obj = data[z].second(); - this.outputData[z] = obj instanceof String[] ? data[z].third() : obj; + Object obj = data[z].second; + this.outputData[z] = obj instanceof String[] ? data[z].third : obj; } } public void use(ActButton elem, PressType action) { for(int z = 0; z < this.inputs.length; z++) { if(this.inputs[z] instanceof Field) { - int min = (this.inputData[z].third() & 0x7fffffff) >> 16; + int min = (this.inputData[z].third & 0x7fffffff) >> 16; String text = this.inputs[z].getText(); if(text.length() < min) { if(!GuiForm.this.labels[z].getText().startsWith("" + TextColor.RED)) diff --git a/client/src/main/java/client/gui/ingame/GuiGameOver.java b/client/src/client/gui/ingame/GuiGameOver.java similarity index 57% rename from client/src/main/java/client/gui/ingame/GuiGameOver.java rename to client/src/client/gui/ingame/GuiGameOver.java index 5fec815..ce3f7ab 100755 --- a/client/src/main/java/client/gui/ingame/GuiGameOver.java +++ b/client/src/client/gui/ingame/GuiGameOver.java @@ -4,9 +4,7 @@ import client.gui.Gui; import client.gui.element.ActButton; import client.gui.element.ButtonCallback; import common.color.TextColor; -import common.util.ExtMath; import client.gui.element.Label; -import client.gui.element.MultiLabel; import client.gui.element.PressType; public class GuiGameOver extends Gui { @@ -20,9 +18,9 @@ public class GuiGameOver extends Gui { public void init(int width, int height) { this.timer = 0; - this.add(new Label(0, 0, 400, 0, TextColor.DRED + "Du bist gestorben!")); - this.add(new MultiLabel(0, 32, 400, 42, String.format(TextColor.GREEN + "Letzte Position" + TextColor.GRAY + ":\n" + TextColor.YELLOW + "%d, %d, %d\n" + TextColor.YELLOW + "%s", ExtMath.floord(this.gm.player.posX), ExtMath.floord(this.gm.player.posY), ExtMath.floord(this.gm.player.posZ), this.gm.player.worldObj.dimension.getFormattedName(false)))); - this.button = this.add(new ActButton(100, 100, 200, 0, new ButtonCallback() { + this.add(new Label(0, 0, 200, 20, "Du bist gestorben!")); + this.add(new Label(0, 32, 200, 20, "Punktestand: " + TextColor.YELLOW + this.gm.player.experienceLevel)); + this.button = this.add(new ActButton(0, 100, 200, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { GuiGameOver.this.gm.player.respawnPlayer(); GuiGameOver.this.gm.displayGuiScreen(null); @@ -33,7 +31,7 @@ public class GuiGameOver extends Gui { } public String getTitle() { - return "Game over - Wiederbeleben?"; + return "Game over"; } public void updateScreen() { diff --git a/client/src/main/java/client/gui/ingame/GuiSign.java b/client/src/client/gui/ingame/GuiSign.java similarity index 72% rename from client/src/main/java/client/gui/ingame/GuiSign.java rename to client/src/client/gui/ingame/GuiSign.java index 1e3d59d..c5530fd 100644 --- a/client/src/main/java/client/gui/ingame/GuiSign.java +++ b/client/src/client/gui/ingame/GuiSign.java @@ -16,13 +16,13 @@ public class GuiSign extends Gui implements FieldCallback { private final String[] tempLines; public void init(int width, int height) { - this.add(new Label(0, -140, 300, 0, "Bearbeite Schild")); - this.add(new Label(0, -80, 300, 0, String.format("%d, %d, %d", this.position.getX(), this.position.getY(), this.position.getZ()))); - this.add(new Label(0, -50, 300, 0, this.gm.world == null ? "" : this.gm.world.dimension.getFormattedName(false))); + this.add(new Label(0, -140, 300, 20, "Bearbeite Schild")); + this.add(new Label(0, -80, 300, 20, String.format("%d, %d, %d", this.position.getX(), this.position.getY(), this.position.getZ()))); + this.add(new Label(0, -50, 300, 20, this.gm.world == null ? "" : this.gm.world.dimension.getFormattedName(false))); for(int z = 0; z < this.lines.length; z++) { - this.lines[z] = this.add(new Field(0, 40 * z, 300, 0, 50, this, this.tempLines[z] == null ? "" : this.tempLines[z])); + this.lines[z] = this.add(new Field(0, 40 * z, 300, 24, 50, this, this.tempLines[z] == null ? "" : this.tempLines[z])); } - this.add(new NavButton(0, 40 * (this.lines.length + 1), 300, 0, null, "Fertig")); + this.add(new NavButton(0, 40 * (this.lines.length + 1), 300, 24, null, "Fertig")); this.shift(); } diff --git a/client/src/main/java/client/gui/options/GuiBinds.java b/client/src/client/gui/options/GuiBinds.java similarity index 81% rename from client/src/main/java/client/gui/options/GuiBinds.java rename to client/src/client/gui/options/GuiBinds.java index 2face9d..ffc6262 100644 --- a/client/src/main/java/client/gui/options/GuiBinds.java +++ b/client/src/client/gui/options/GuiBinds.java @@ -16,8 +16,8 @@ public class GuiBinds extends GuiOptions { int y = 0; int x = 0; for(Bind bind : Bind.values()) { - this.add(new Label(x * 152, 100 + y * 34, 150, bind.getDisplay())); - this.add(new ActButton(x * 152, 100 + y * 34, 150, 0, new ButtonCallback() { + this.add(new Label(10 + x * 190, 80 + y * 50, 180, 20, bind.getDisplay())); + this.add(new ActButton(10 + x * 190, 100 + y * 50, 180, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { if(action == PressType.SECONDARY) { if(!bind.isDefault()) { @@ -45,13 +45,13 @@ public class GuiBinds extends GuiOptions { return (bind.isDupe() ? TextColor.RED : TextColor.YELLOW) + (bind.getInput() == null ? "---" : bind.getInput().getDisplay()); } })); - if(++x == 4) { + if(++x == 5) { x = 0; y++; } } y += x != 0 ? 1 : 0; - this.add(new ActButton(0, 100 + y * 34, 150 * 4 + 2 * 3, 0, new ButtonCallback() { + this.add(new ActButton(200, 100 + y * 50, 560, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { boolean flag = false; for(Bind bind : Bind.values()) { @@ -64,8 +64,8 @@ public class GuiBinds extends GuiOptions { } } }, "Zurücksetzen")); - this.addSelector("phy_sensitivity", 0, 140 + y * 34, 302, 0); - this.addSelector("gui_dclick_delay", 304, 140 + y * 34, 302, 0); + this.addSelector("phy_sensitivity", 30, 160 + y * 50, 440, 24); + this.addSelector("gui_dclick_delay", 490, 160 + y * 50, 440, 24); super.init(width, height); } diff --git a/client/src/client/gui/options/GuiDisplay.java b/client/src/client/gui/options/GuiDisplay.java new file mode 100644 index 0000000..22262d0 --- /dev/null +++ b/client/src/client/gui/options/GuiDisplay.java @@ -0,0 +1,106 @@ +package client.gui.options; + +import client.gui.Formatter; +import client.gui.element.Dropdown; +import client.gui.element.DropdownCallback; +import client.gui.element.Element; +import client.gui.element.Fill; +import client.gui.element.Slider; +import client.gui.element.SliderCallback; +import client.gui.element.Toggle; +import client.gui.element.ToggleCallback; +import client.window.Button; +import client.window.DisplayMode; +import client.window.Window; +import common.color.TextColor; + +public class GuiDisplay extends GuiOptions { + private static final String[] DISTANCES = new String[] {"Gruselig", "Winzig", "Gering", "Normal", "Weit"}; + + private Element distanceSlider; + + protected GuiDisplay() { + } + + public void init(int width, int height) { + DisplayMode[] dmodes = Window.getDisplayModes(); + if(dmodes != null && dmodes.length > 0) { + int offset = 0; + int pos = 0; + int num = dmodes.length; + if(dmodes.length > DisplayMode.VID_MODES) { + offset = dmodes.length - DisplayMode.VID_MODES; + num = DisplayMode.VID_MODES; + } + DisplayMode[] modes = new DisplayMode[num]; + DisplayMode selected = dmodes[num + offset - 1]; + for(int z = 0; z < num; z++) { + modes[z] = dmodes[z + offset]; + if(modes[z].equals(this.gm.vidMode)) + selected = modes[z]; + } + this.add(new Dropdown(30, 80, 440, 24, false, modes, modes[modes.length - 1], selected, new DropdownCallback() { + public void use(Dropdown elem, DisplayMode value) { + GuiDisplay.this.gm.vidMode = value; + GuiDisplay.this.gm.full(true); + } + }, "Auflösung")); + } + else { + this.add(new Fill(30, 80, 440, 24, TextColor.RED + "Auflösung: ")); + } + + this.add(new Toggle(490, 80, 440, 24, false, GuiDisplay.this.gm.fullscreen, new ToggleCallback() { + public void use(Toggle elem, boolean value) { + GuiDisplay.this.gm.full(value); + } + }, "Vollbild")); + this.add(new Slider(30, 120, 440, 24, 0, 0, 360 - 8, 0, (this.gm.sync < 0) ? (360 - 8) : (this.gm.sync != 0 ? ((this.gm.sync < 10) ? 1 : (this.gm.sync - 9)) : 0), new SliderCallback() { + public void use(Slider elem, int value) { + GuiDisplay.this.gm.getVar("win_sync").parse("" + ((value > 0 && value < 360 - 8) ? (value + 9) : (value != 0 ? -1 : 0))); + GuiDisplay.this.gm.setDirty(); + } + }, new Formatter() { + public String use(Slider elem) { + int value = elem.getValue(); + return "Max. Bildrate: " + (value > 0 && value < (360 - 8) ? (value + 9) + " FPS" : (value != 0 ? "Unbegrenzt" : "VSync")); + } + })); + this.addSelector("gl_vsync_flush", 490, 120, 440, 24); + + this.addSelector("overlay_enabled", 30, 200, 440, 24); + this.addSelector("overlay_opacity", 490, 200, 440, 24); + + this.addSelector("overlay_fadeout", 30, 240, 440, 24); + this.addSelector("chat_permanent", 490, 240, 440, 24); + + this.addSelector("console_size", 30, 280, 440, 24); + this.addSelector("chat_size", 490, 280, 440, 24); + + this.addSelector("feed_size", 30, 320, 440, 24); + this.addSelector("hotbar_size", 490, 320, 440, 24); + + this.addSelector("gl_fov", 30, 400, 440, 24); + this.distanceSlider = this.addSelector("chunk_view_distance", 30, 440, 440, 24); + this.addSelector("chunk_build_time", 490, 440, 440, 24); + super.init(width, height); + } + + public String getTitle() { + return "Grafik und Anzeige"; + } + + private String getDistanceName() { + int distance = this.gm.renderDistance; + distance = distance > 16 ? 16 : distance; + String str = distance < 0 ? DISTANCES[0] : DISTANCES[(distance + 1) / 4]; + if(distance > 2 && (((distance + 1) / 2) & 1) == 1) + str = str + "+"; + return String.format("Sichtweite: %d Chunks [%d Blöcke, %s]", this.gm.renderDistance, this.gm.renderDistance * 16, str); + } + + public void updateScreen() { + if(!Button.isMouseDown()) + this.distanceSlider.setText(this.getDistanceName()); + } +} diff --git a/client/src/main/java/client/gui/options/GuiOptions.java b/client/src/client/gui/options/GuiOptions.java similarity index 57% rename from client/src/main/java/client/gui/options/GuiOptions.java rename to client/src/client/gui/options/GuiOptions.java index 57bfdac..51258d8 100644 --- a/client/src/main/java/client/gui/options/GuiOptions.java +++ b/client/src/client/gui/options/GuiOptions.java @@ -16,10 +16,16 @@ public abstract class GuiOptions extends Gui { public void init(int width, int height) { lastPage = this; this.shift(); - for(int z = 0; z < PAGES.length; z++) { - GuiOptions gui = PAGES[z]; - this.add(new NavButton(z % 2 == 1 ? width - 212 : 2, 2 + 20 * (z / 2), 210, 0, gui, gui.getTitle())); + int x = 0; + int y = 0; + for(GuiOptions gui : PAGES) { + this.add( // gui == this ? new SelectedButton(240 * x, 24 * y, 240, 24, gui, gui.getTitle()) : + new NavButton(240 * x, 24 * y, 240, 24, gui, gui.getTitle())); + if(++x == 4) { + x = 0; + ++y; + } } - this.add(new NavButton((width - 280) / 2, height - 20, 280, 0, GuiMenu.INSTANCE, "Zurück")); + this.add(new NavButton(width - 240, 0, 240, 24, GuiMenu.INSTANCE, "Zurück")); } } diff --git a/client/src/main/java/client/gui/options/GuiSound.java b/client/src/client/gui/options/GuiSound.java similarity index 55% rename from client/src/main/java/client/gui/options/GuiSound.java rename to client/src/client/gui/options/GuiSound.java index 9e49c02..29a3814 100644 --- a/client/src/main/java/client/gui/options/GuiSound.java +++ b/client/src/client/gui/options/GuiSound.java @@ -10,26 +10,25 @@ public class GuiSound extends GuiOptions { } public void init(int width, int height) { - int x = 0; - int y = 0; - for(Volume volume : Volume.values()) { - this.addSelector(volume.getCVarName(), x, y, 150, 0); - x = (x == 0) ? 152 : 0; - if(x == 0) - y += 20; - } + this.addSelector("snd_enabled", 30, 380, 440, 24); - this.addSelector("snd_enabled", 0, 50, 150, 0); - - this.addSelector("snd_buffer_size", 0, 70, 150, 0); - this.addSelector("snd_frame_size", 152, 70, 150, 0); + this.addSelector("snd_buffer_size", 30, 420, 440, 24); + this.addSelector("snd_frame_size", 490, 420, 440, 24); - this.add(new ActButton(0, 100, 302, 0, new ButtonCallback() { + this.add(new ActButton(30, 480, 900, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { GuiSound.this.gm.restartSound(false); } - }, "Übernehmen und Audio neu starten")); + }, "Übernehmen und Audio-Thread neu starten")); + int x = 30; + int y = 220; + for(Volume volume : Volume.values()) { + this.addSelector(volume.getCVarName(), x, y, 440, 24); + x = (x == 30) ? 490 : 30; + if(x == 30) + y += 40; + } super.init(width, height); } diff --git a/client/src/main/java/client/gui/options/GuiStyle.java b/client/src/client/gui/options/GuiStyle.java similarity index 71% rename from client/src/main/java/client/gui/options/GuiStyle.java rename to client/src/client/gui/options/GuiStyle.java index c322e25..7905591 100644 --- a/client/src/main/java/client/gui/options/GuiStyle.java +++ b/client/src/client/gui/options/GuiStyle.java @@ -40,9 +40,10 @@ public class GuiStyle extends GuiOptions implements DropdownCallback, Bu protected Element addSelector(String cvar, int x, int y, int w, int h) { CVar cv = this.gm.getVar(cvar); - if(cv instanceof ColorVar color) { + if(cv instanceof ColorVar) { + ColorVar color = (ColorVar)cv; if(!color.getDisplay().isEmpty()) - this.add(color.label(x, y, w)); + this.add(color.label(x, y - 20, w, 20)); if(this.gm.style != Style.CUSTOM) return this.add(new Field(x, y, w, h, color.getFieldValue(this.gm.style))); else @@ -54,7 +55,7 @@ public class GuiStyle extends GuiOptions implements DropdownCallback, Bu public void init(int width, int height) { int z; for(z = 0; z < STYLE_CVARS.length; z++) { - this.addSelector(STYLE_CVARS[z], (z % 3) * 122, z / 3 * 34, 120, 0); + this.addSelector(STYLE_CVARS[z], 10 + ((z % 3) + 1) * 190, 100 + z / 3 * 50, 180, 24); } z = 0; for(Style theme : Style.values()) { @@ -67,16 +68,23 @@ public class GuiStyle extends GuiOptions implements DropdownCallback, Bu } } }; - this.add( // theme == this.gm.style ? new SelectedButton(10 + (z % 3) * 320, 360 + (z / 3) * 40, 300, 0, callback, theme.name) : - new SelectableButton((z % 3) * 122, 4 * 34 + (z / 3) * 20, 120, 0, callback, theme.name, theme == this.gm.style)); + this.add( // theme == this.gm.style ? new SelectedButton(10 + (z % 3) * 320, 360 + (z / 3) * 40, 300, 24, callback, theme.name) : + new SelectableButton(10 + (z % 3) * 320, 360 + (z / 3) * 40, 300, 24, callback, theme.name, theme == this.gm.style)); z++; } - this.addSelector("gui_scale", 0, 5 * 34 + (Style.values().length / 3) * 20, 181, 0); - this.addSelector("gui_font_tiny", 183, 5 * 34 + (Style.values().length / 3) * 20, 181, 0); + String[] values = new String[] {"VALUE 1", "VALUE 2"}; + this.add(new Dropdown(10, height - 74, 300, 24, false, values, values[1], values[0], this, "DROPDOWN")); + this.add(new ActButton(330, height - 74, 300, 24, this, "BUTTON")); + this.add(new Toggle(650, height - 74, 140, 24, false, true, this, "TOGGLE")); + this.add(new Toggle(810, height - 74, 140, 24, true, false, this, "TOGGLE")); + values = new String[] {"VALUE 1", "VALUE 2", "VALUE 3", "VALUE 4"}; + this.add(new Switch(10, height - 34, 300, 24, values, values[2], values[0], this, "ENUM")); + this.add(new Slider(330, height - 34, 300, 24, 0, -20, 827, 60, 120, this, "SLIDER")); + this.add(new Field(650, height - 34, 300, 24, 128, this, "FIELD")); if(this.gm.style != Style.CUSTOM) { - this.add(new ActButton(0, 3 * 34, 364, 0, new ButtonCallback() { + this.add(new ActButton(200, 100 + 3 * 50, 560, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { if(GuiStyle.this.gm.style != Style.CUSTOM) { GuiStyle.this.gm.style.copyToCustom(); @@ -88,7 +96,7 @@ public class GuiStyle extends GuiOptions implements DropdownCallback, Bu }, "In angepasstes Design kopieren")); } else { - this.add(new ActButton(0, 3 * 34, 364, 0, new ButtonCallback() { + this.add(new ActButton(200, 100 + 3 * 50, 560, 24, new ButtonCallback() { public void use(ActButton elem, PressType action) { GuiStyle.this.gm.style = Style.CUSTOM; for(String cvar : STYLE_CVARS) { diff --git a/client/src/main/java/client/init/RenderRegistry.java b/client/src/client/init/RenderRegistry.java similarity index 95% rename from client/src/main/java/client/init/RenderRegistry.java rename to client/src/client/init/RenderRegistry.java index 254989d..d57d794 100644 --- a/client/src/main/java/client/init/RenderRegistry.java +++ b/client/src/client/init/RenderRegistry.java @@ -21,7 +21,6 @@ import client.renderer.entity.RenderFallingBlock; import client.renderer.entity.RenderFireball; import client.renderer.entity.RenderFish; import client.renderer.entity.RenderFlyingBox; -import client.renderer.entity.RenderFox; import client.renderer.entity.RenderHorse; import client.renderer.entity.RenderHumanoid; import client.renderer.entity.RenderItem; @@ -47,7 +46,6 @@ import client.renderer.entity.RenderWolf; import client.renderer.entity.RenderXpOrb; import client.renderer.model.ModelChicken; import client.renderer.model.ModelCow; -import client.renderer.model.ModelFox; import client.renderer.model.ModelHorse; import client.renderer.model.ModelMouse; import client.renderer.model.ModelOcelot; @@ -59,8 +57,6 @@ import client.renderer.model.ModelWolf; import client.renderer.texture.TextureTicked; import client.renderer.ticked.TextureFlamesFX1; import client.renderer.ticked.TextureFlamesFX2; -import client.renderer.ticked.TextureFlamesFXMono1; -import client.renderer.ticked.TextureFlamesFXMono2; import client.renderer.ticked.TextureLavaFX; import client.renderer.ticked.TextureLavaFlowFX; import client.renderer.ticked.TextureWaterFX; @@ -70,7 +66,6 @@ import common.entity.animal.EntityBat; import common.entity.animal.EntityChicken; import common.entity.animal.EntityCow; import common.entity.animal.EntityDragon; -import common.entity.animal.EntityFox; import common.entity.animal.EntityHorse; import common.entity.animal.EntityMooshroom; import common.entity.animal.EntityMouse; @@ -119,7 +114,6 @@ public abstract class RenderRegistry { map.put(EntityCow.class, new RenderCow(mgr, new ModelCow())); map.put(EntityMooshroom.class, new RenderMooshroom(mgr, new ModelCow())); map.put(EntityWolf.class, new RenderWolf(mgr, new ModelWolf())); - map.put(EntityFox.class, new RenderFox(mgr, new ModelFox())); map.put(EntityChicken.class, new RenderChicken(mgr, new ModelChicken())); map.put(EntityOcelot.class, new RenderOcelot(mgr, new ModelOcelot())); map.put(EntityRabbit.class, new RenderRabbit(mgr, new ModelRabbit())); @@ -171,8 +165,6 @@ public abstract class RenderRegistry { public static void registerAnimations(Map> anim) { anim.put("fire1", TextureFlamesFX1.class); anim.put("fire2", TextureFlamesFX2.class); - anim.put("flame1", TextureFlamesFXMono1.class); - anim.put("flame2", TextureFlamesFXMono2.class); anim.put("lavaflow", TextureLavaFlowFX.class); anim.put("lava", TextureLavaFX.class); anim.put("waterflow", TextureWaterFlowFX.class); diff --git a/client/src/client/network/ClientLoginHandler.java b/client/src/client/network/ClientLoginHandler.java new file mode 100755 index 0000000..cfda5c6 --- /dev/null +++ b/client/src/client/network/ClientLoginHandler.java @@ -0,0 +1,69 @@ +package client.network; + +import java.security.PublicKey; + +import javax.crypto.SecretKey; + +import client.Client; +import common.network.IClientLoginHandler; +import common.network.NetConnection; +import common.network.NetHandler; +import common.network.PacketRegistry; +import common.packet.LPacketPasswordResponse; +import common.packet.LPacketStartEncrypt; +import common.packet.RPacketDisconnect; +import common.packet.RPacketEnableCompression; +import common.packet.RPacketLoginSuccess; +import common.packet.RPacketRequestEncrypt; +import common.util.EncryptUtil; +import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.GenericFutureListener; + +public class ClientLoginHandler extends NetHandler implements IClientLoginHandler { + private final Client gm; + private final NetConnection networkManager; + private final String user; + private final String access; + private final String password; + + public ClientLoginHandler(NetConnection conn, Client gmIn, String userIn, String accessIn, String passwordIn) { + this.networkManager = conn; + this.gm = gmIn; + this.user = userIn; + this.access = accessIn; + this.password = passwordIn; + } + + public void onDisconnect(String reason) + { + this.gm.disconnected(reason); + } + + public void handleDisconnect(RPacketDisconnect packetIn) + { + this.networkManager.closeChannel(packetIn.getReason()); + } + + public void handleEncrypt(RPacketRequestEncrypt packet) { + final SecretKey secret = EncryptUtil.createNewSharedKey(); + PublicKey pubkey = packet.getKey(); + this.networkManager.sendPacket(new LPacketStartEncrypt(secret, pubkey, packet.getToken()), new GenericFutureListener < Future > () { + public void operationComplete(Future u) throws Exception { + ClientLoginHandler.this.networkManager.startEncryption(secret); + ClientLoginHandler.this.networkManager.sendPacket(new LPacketPasswordResponse(ClientLoginHandler.this.user, ClientLoginHandler.this.access, ClientLoginHandler.this.password)); + } + }); + } + + public void handleLoginSuccess(RPacketLoginSuccess packetIn) + { + this.gm.debugWorld = packetIn.isDebug(); + this.networkManager.setConnectionState(PacketRegistry.PLAY); + this.networkManager.setNetHandler(new ClientPlayer(this.gm, this.networkManager)); + } + + public void handleEnableCompression(RPacketEnableCompression packetIn) + { + this.networkManager.setCompressionTreshold(packetIn.getValue()); + } +} diff --git a/client/src/main/java/client/network/ClientPlayer.java b/client/src/client/network/ClientPlayer.java similarity index 61% rename from client/src/main/java/client/network/ClientPlayer.java rename to client/src/client/network/ClientPlayer.java index 5981cfc..fd0f656 100755 --- a/client/src/main/java/client/network/ClientPlayer.java +++ b/client/src/client/network/ClientPlayer.java @@ -1,8 +1,13 @@ package client.network; +import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; + import client.Client; +import client.PlayerController; import client.gui.Gui; import client.gui.GuiConsole; import client.gui.GuiLoading; @@ -15,22 +20,25 @@ import client.gui.container.GuiDispenser; import client.gui.container.GuiEnchant; import client.gui.container.GuiFurnace; import client.gui.container.GuiHopper; -import client.gui.container.GuiEntity; -import client.gui.container.GuiTile; +import client.gui.container.GuiHorse; +import client.gui.container.GuiMachine; import client.gui.container.GuiMerchant; import client.gui.container.GuiRepair; import client.gui.ingame.GuiSign; import client.gui.ingame.GuiForm; import client.renderer.particle.EntityPickupFX; import client.renderer.texture.EntityTexManager; -import client.util.PlayerController; -import client.world.ChunkClient; import client.world.WorldClient; -import common.block.Block; -import common.block.tech.BlockWorkbench; +import common.attributes.Attribute; +import common.attributes.AttributeInstance; +import common.attributes.AttributeMap; +import common.attributes.AttributeModifier; +import common.collect.Lists; +import common.collect.Maps; import common.dimension.Dimension; import common.entity.DataWatcher; import common.entity.Entity; +import common.entity.animal.EntityHorse; import common.entity.effect.EntityLightning; import common.entity.item.EntityBoat; import common.entity.item.EntityXp; @@ -38,12 +46,13 @@ import common.entity.npc.EntityNPC; import common.entity.npc.PlayerCharacter; import common.entity.projectile.EntityProjectile; import common.entity.types.EntityLiving; -import common.init.BlockRegistry; import common.init.EntityRegistry; import common.init.ItemRegistry; import common.init.SoundEvent; import common.inventory.AnimalChest; import common.inventory.Container; +import common.inventory.ContainerLocalMenu; +import common.inventory.IInventory; import common.inventory.InventoryBasic; import common.inventory.InventoryPlayer; import common.item.ItemStack; @@ -53,38 +62,38 @@ import common.network.IClientPlayer; import common.network.NetConnection; import common.network.NetHandler; import common.network.Packet; -import common.packet.CPacketPlayerPosLook; import common.packet.CPacketAction; import common.packet.CPacketKeepAlive; -import common.packet.SPacketEntity; -import common.packet.SPacketEntityTeleport; -import common.packet.SPacketEntityHeadLook; -import common.packet.SPacketEntityStatus; -import common.packet.SPacketEntityAttach; -import common.packet.SPacketEntityMetadata; -import common.packet.SPacketEntityEffect; -import common.packet.SPacketRemoveEntityEffect; -import common.packet.SPacketExplosion; -import common.packet.SPacketEffect; -import common.packet.SPacketSoundEffect; -import common.packet.SPacketParticles; -import common.packet.SPacketChangeGameState; -import common.packet.SPacketSpawnGlobalEntity; -import common.packet.SPacketOpenWindow; -import common.packet.SPacketCloseWindow; -import common.packet.SPacketSetSlot; -import common.packet.SPacketWindowItems; -import common.packet.SPacketWindowProperty; -import common.packet.SPacketConfirmTransaction; -import common.packet.SPacketUpdateSign; -import common.packet.SPacketUpdateTileEntity; -import common.packet.SPacketSignEditorOpen; -import common.packet.SPacketPlayerListItem; -import common.packet.SPacketPlayerAbilities; -import common.packet.SPacketTabComplete; -import common.packet.SPacketUpdateEntityTags; +import common.packet.CPacketPlayer; +import common.packet.S14PacketEntity; +import common.packet.S18PacketEntityTeleport; +import common.packet.S19PacketEntityHeadLook; +import common.packet.S1APacketEntityStatus; +import common.packet.S1BPacketEntityAttach; +import common.packet.S1CPacketEntityMetadata; +import common.packet.S1DPacketEntityEffect; +import common.packet.S1EPacketRemoveEntityEffect; +import common.packet.S20PacketEntityProperties; +import common.packet.S27PacketExplosion; +import common.packet.S28PacketEffect; +import common.packet.S29PacketSoundEffect; +import common.packet.S2APacketParticles; +import common.packet.S2BPacketChangeGameState; +import common.packet.S2CPacketSpawnGlobalEntity; +import common.packet.S2DPacketOpenWindow; +import common.packet.S2EPacketCloseWindow; +import common.packet.S2FPacketSetSlot; +import common.packet.S30PacketWindowItems; +import common.packet.S31PacketWindowProperty; +import common.packet.S32PacketConfirmTransaction; +import common.packet.S33PacketUpdateSign; +import common.packet.S35PacketUpdateTileEntity; +import common.packet.S36PacketSignEditorOpen; +import common.packet.S38PacketPlayerListItem; +import common.packet.S39PacketPlayerAbilities; +import common.packet.S3APacketTabComplete; +import common.packet.S43PacketUpdateEntityNBT; import common.packet.SPacketAnimation; -import common.packet.SPacketBiome; import common.packet.SPacketBlockAction; import common.packet.SPacketBlockBreakAnim; import common.packet.SPacketBlockChange; @@ -120,94 +129,111 @@ import common.packet.SPacketWorld; import common.potion.PotionEffect; import common.rng.Random; import common.sound.Sound; +import common.tileentity.IInteractionObject; +import common.tileentity.LocalBlockIntercommunication; import common.tileentity.TileEntity; -import common.tileentity.TileEntityDevice; +import common.tileentity.TileEntityMachine; import common.tileentity.TileEntitySign; +import common.util.BlockPos; import common.village.MerchantRecipeList; +import common.world.Chunk; import common.world.Explosion; import common.world.Weather; import common.world.World; -public class ClientPlayer implements IClientPlayer +public class ClientPlayer extends NetHandler implements IClientPlayer { - protected final Client gm; - private final NetConnection connection; - private WorldClient world; - private boolean loaded; - private final Random rand = new Random(); + /** + * The NetworkManager instance used to communicate with the server (used only by handlePlayerPosLook to update + * positioning and handleJoinGame to inform the server of the client distribution/mods) + */ + private final NetConnection netManager; - public ClientPlayer(Client gm, NetConnection connection) + /** + * Reference to the Game instance, which many handler methods operate on + */ + private Client gameController; + + /** + * Reference to the current ClientWorld instance, which many handler methods operate on + */ + private WorldClient clientWorldController; + + /** + * True if the client has finished downloading terrain and may spawn. Set upon receipt of S08PacketPlayerPosLook, + * reset upon respawning + */ + private boolean doneLoadingTerrain; +// private boolean travelSound; + private final Map playerList = Maps.newTreeMap(); + private final List characterList = Lists.newArrayList(); +// private final List> players = Lists.newArrayList(); + private int selectedCharacter = -1; + + /** + * Just an ordinary random number generator, used to randomize audio pitch of item/orb pickup and randomize both + * particlespawn offset and velocity + */ + private final Random avRandomizer = new Random(); + + public ClientPlayer(Client gmIn, NetConnection p_i46300_3_) { - this.gm = gm; - this.connection = connection; - } - - - public final boolean isJumping() { - return this.gm.jump; - } - - public final boolean isSprinting() { - return this.gm.sprint; - } - - public final boolean isSneaking() { - return this.gm.sneak; - } - - public final float getMoveForward() { - return this.gm.moveForward; - } - - public final float getMoveStrafe() { - return this.gm.moveStrafe; - } - - public final void setMoveForward(float value) { - this.gm.moveForward = value; - } - - public final void setMoveStrafe(float value) { - this.gm.moveStrafe = value; - } - - public final boolean isRenderViewEntity(Entity entity) { - return this.gm.getRenderViewEntity() == entity; - } - - public final void updatePlayerMoveState() { - this.gm.updatePlayerMoveState(); - } - - public final NetConnection getConnection() { - return this.connection; + this.gameController = gmIn; + this.netManager = p_i46300_3_; } public void playSound(Sound sound) { - this.gm.getSoundManager().playSound(sound); + this.gameController.getSoundManager().playSound(sound); } public void emitParticleAtEntity(Entity entityIn, ParticleType particleTypes) { - this.gm.effectRenderer.emitParticleAtEntity(entityIn, particleTypes); + this.gameController.effectRenderer.emitParticleAtEntity(entityIn, particleTypes); + } + + public boolean isJumping() { + return this.gameController.jump; + } + + public boolean isSprinting() { + return this.gameController.sprint; + } + + public boolean isSneaking() { + return this.gameController.sneak; + } + + public float getMoveForward() { + return this.gameController.moveForward; + } + + public float getMoveStrafe() { + return this.gameController.moveStrafe; + } + + public void setMoveForward(float value) { + this.gameController.moveForward = value; + } + + public void setMoveStrafe(float value) { + this.gameController.moveStrafe = value; } - - public void onDisconnect(String reason) - { - this.gm.disconnected(reason); - } - public void addToSendQueue(Packet p_147297_1_) - { - this.connection.sendPacket(p_147297_1_); + public boolean isRenderViewEntity(Entity entity) { + return this.gameController.getRenderViewEntity() == entity; } + + public void updatePlayerMoveState() { + this.gameController.updatePlayerMoveState(); + } + /** * Clears the WorldClient instance associated with this NetHandlerPlayClient */ public void cleanup() { - this.world = null; + this.clientWorldController = null; // for(String user : this.playerInfoMap.keySet()) { // DefaultPlayerSkin.setTexture(user, null); // } @@ -217,15 +243,15 @@ public class ClientPlayer implements IClientPlayer public void handleJoinGame(SPacketJoinGame packetIn) { - NetHandler.checkThread(packetIn, this, this.gm); - this.gm.charEditor = packetIn.isInEditor(); - this.gm.controller = new PlayerController(this.gm, this); - this.world = new WorldClient(this.gm, packetIn.getDimension()); + NetHandler.checkThread(packetIn, this, this.gameController); + this.gameController.charEditor = packetIn.isInEditor(); + this.gameController.controller = new PlayerController(this.gameController, this); + this.clientWorldController = new WorldClient(this.gameController, this.gameController.debugWorld, packetIn.getDimension()); // this.gameController.gameSettings.difficulty = packetIn.getDifficulty(); - this.gm.loadWorld(this.world, packetIn.getEntityType()); + this.gameController.loadWorld(this.clientWorldController, packetIn.getEntityType()); // this.gameController.thePlayer.dimension = this.clientWorldController.dimension.getDimensionId(); - this.gm.player.setId(packetIn.getEntityId()); - this.gm.displayGuiScreen(this.gm.charEditor ? GuiChar.INSTANCE : null); + this.gameController.player.setId(packetIn.getEntityId()); + this.gameController.displayGuiScreen(this.gameController.charEditor ? GuiChar.INSTANCE : null); // this.currentServerMaxPlayers = packetIn.getMaxPlayers(); // this.gameController.controller.setCheat(packetIn.getCheat()); // this.gameController.updateViewDistance(); @@ -243,7 +269,7 @@ public class ClientPlayer implements IClientPlayer */ public void handleSpawnObject(SPacketSpawnObject packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); double d0 = (double)packetIn.getX() / 32.0D; double d1 = (double)packetIn.getY() / 32.0D; double d2 = (double)packetIn.getZ() / 32.0D; @@ -266,7 +292,7 @@ public class ClientPlayer implements IClientPlayer // packetIn.setData(0); // } // else { - entity = EntityRegistry.createEntityByID(packetIn.getType(), this.world, d0, d1, d2, packetIn.getData()); + entity = EntityRegistry.createEntityByID(packetIn.getType(), this.clientWorldController, d0, d1, d2, packetIn.getData()); // } if(entity != null && entity.dead) { entity = null; @@ -384,10 +410,10 @@ public class ClientPlayer implements IClientPlayer } entity.setId(packetIn.getEntityID()); - this.world.addEntityToWorld(packetIn.getEntityID(), entity); + this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entity); - if(entity instanceof EntityProjectile projectile) { - projectile.setAcceleration((double)packetIn.getSpeedX() / 8000.0D, (double)packetIn.getSpeedY() / 8000.0D, (double)packetIn.getSpeedZ() / 8000.0D); + if(entity instanceof EntityProjectile) { + ((EntityProjectile)entity).setAcceleration((double)packetIn.getSpeedX() / 8000.0D, (double)packetIn.getSpeedY() / 8000.0D, (double)packetIn.getSpeedZ() / 8000.0D); } else if (entity.hasSpawnVelocity()) // packetIn.getData() > 0) { @@ -425,9 +451,9 @@ public class ClientPlayer implements IClientPlayer /** * Handles globally visible entities. Used in vanilla for lightning bolts */ - public void handleSpawnGlobalEntity(SPacketSpawnGlobalEntity packetIn) + public void handleSpawnGlobalEntity(S2CPacketSpawnGlobalEntity packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); double d0 = (double)packetIn.getEncodedX() / 32.0D; double d1 = (double)packetIn.getEncodedY() / 32.0D; double d2 = (double)packetIn.getEncodedZ() / 32.0D; @@ -435,7 +461,7 @@ public class ClientPlayer implements IClientPlayer if (packetIn.getType() == 1) { - entity = new EntityLightning(this.world, d0, d1, d2, packetIn.getData(), 0, false, null); + entity = new EntityLightning(this.clientWorldController, d0, d1, d2, packetIn.getData(), 0, false, null); } if (entity != null) @@ -446,7 +472,7 @@ public class ClientPlayer implements IClientPlayer entity.rotYaw = 0.0F; entity.rotPitch = 0.0F; entity.setId(packetIn.getEntityId()); - this.world.effects.add(entity); + this.clientWorldController.effects.add(entity); } } @@ -465,8 +491,8 @@ public class ClientPlayer implements IClientPlayer */ public void handleEntityVelocity(SPacketEntityVelocity packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = this.world.getEntityByID(packetIn.getEntityID()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); if (entity != null) { @@ -478,17 +504,17 @@ public class ClientPlayer implements IClientPlayer * Invoked when the server registers new proximate objects in your watchlist or when objects in your watchlist have * changed -> Registers any changes locally */ - public void handleEntityMetadata(SPacketEntityMetadata packetIn) + public void handleEntityMetadata(S1CPacketEntityMetadata packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = this.world.getEntityByID(packetIn.getEntityId()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); if (entity != null && packetIn.func_149376_c() != null) { entity.getDataWatcher().updateWatchedObjectsFromList(packetIn.func_149376_c()); - if(entity == this.gm.player && this.gm.open instanceof GuiChar gui) - gui.checkReopen(); + if(entity == this.gameController.player && this.gameController.open instanceof GuiChar) + ((GuiChar)this.gameController.open).checkReopen(); } } @@ -497,13 +523,13 @@ public class ClientPlayer implements IClientPlayer */ public void handleSpawnPlayer(SPacketSpawnPlayer packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); double x = (double)packetIn.getX() / 32.0D; double y = (double)packetIn.getY() / 32.0D; double z = (double)packetIn.getZ() / 32.0D; float yaw = packetIn.getYaw(); float pitch = packetIn.getPitch(); - EntityNPC player = (EntityNPC)EntityRegistry.createEntityByID(packetIn.getEntityType(), this.gm.world); // new EntityNPC(this.gameController.theWorld); // , /* this.getPlayerInfo( */ packetIn.getUser()); // ).getUser()); + EntityNPC player = (EntityNPC)EntityRegistry.createEntityByID(packetIn.getEntityType(), this.gameController.world); // new EntityNPC(this.gameController.theWorld); // , /* this.getPlayerInfo( */ packetIn.getUser()); // ).getUser()); player.setOtherPlayer(); player.prevX = player.lastTickPosX = (double)(player.serverPosX = packetIn.getX()); player.prevY = player.lastTickPosY = (double)(player.serverPosY = packetIn.getY()); @@ -521,7 +547,7 @@ public class ClientPlayer implements IClientPlayer } player.setPositionAndRotation(x, y, z, yaw, pitch); - this.world.addEntityToWorld(packetIn.getEntityID(), player); + this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), player); List list = packetIn.getData(); if (list != null) @@ -535,10 +561,10 @@ public class ClientPlayer implements IClientPlayer /** * Updates an entity's position and rotation as specified by the packet */ - public void handleEntityTeleport(SPacketEntityTeleport packetIn) + public void handleEntityTeleport(S18PacketEntityTeleport packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = this.world.getEntityByID(packetIn.getEntityId()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); if (entity != null) { @@ -553,11 +579,11 @@ public class ClientPlayer implements IClientPlayer if (Math.abs(entity.posX - d0) < 0.03125D && Math.abs(entity.posY - d1) < 0.015625D && Math.abs(entity.posZ - d2) < 0.03125D) { - entity.setClientPosition(entity.posX, entity.posY, entity.posZ, f, f1, true); + entity.setPositionAndRotation2(entity.posX, entity.posY, entity.posZ, f, f1, 3, true); } else { - entity.setClientPosition(d0, d1, d2, f, f1, true); + entity.setPositionAndRotation2(d0, d1, d2, f, f1, 3, true); } entity.onGround = packetIn.getOnGround(); @@ -569,11 +595,11 @@ public class ClientPlayer implements IClientPlayer */ public void handleHeldItemChange(SPacketHeldItemChange packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); if (packetIn.getHeldItemHotbarIndex() >= 0 && packetIn.getHeldItemHotbarIndex() < InventoryPlayer.getHotbarSize()) { - this.gm.player.inventory.currentItem = packetIn.getHeldItemHotbarIndex(); + this.gameController.player.inventory.currentItem = packetIn.getHeldItemHotbarIndex(); } } @@ -582,10 +608,10 @@ public class ClientPlayer implements IClientPlayer * subclassing of the packet allows for the specification of a subset of this data (e.g. only rel. position, abs. * rotation or both). */ - public void handleEntityMovement(SPacketEntity packetIn) + public void handleEntityMovement(S14PacketEntity packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = packetIn.getEntity(this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = packetIn.getEntity(this.clientWorldController); if (entity != null) { @@ -597,7 +623,7 @@ public class ClientPlayer implements IClientPlayer double d2 = (double)entity.serverPosZ / 32.0D; float f = packetIn.hasRotations() ? (float)(packetIn.getYaw() * 360) / 256.0F : entity.rotYaw; float f1 = packetIn.hasRotations() ? (float)(packetIn.getPitch() * 360) / 256.0F : entity.rotPitch; - entity.setClientPosition(d0, d1, d2, f, f1, false); + entity.setPositionAndRotation2(d0, d1, d2, f, f1, 3, false); entity.onGround = packetIn.getOnGround(); } } @@ -606,10 +632,10 @@ public class ClientPlayer implements IClientPlayer * Updates the direction in which the specified entity is looking, normally this head rotation is independent of the * rotation of the entity itself */ - public void handleEntityHeadLook(SPacketEntityHeadLook packetIn) + public void handleEntityHeadLook(S19PacketEntityHeadLook packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = packetIn.getEntity(this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = packetIn.getEntity(this.clientWorldController); if (entity != null) { @@ -625,11 +651,11 @@ public class ClientPlayer implements IClientPlayer */ public void handleDestroyEntities(SPacketDestroyEntities packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); for (int i = 0; i < packetIn.getEntityIDs().length; ++i) { - this.world.removeEntityFromWorld(packetIn.getEntityIDs()[i]); + this.clientWorldController.removeEntityFromWorld(packetIn.getEntityIDs()[i]); EntityTexManager.setTexture(packetIn.getEntityIDs()[i], null, null); } } @@ -641,8 +667,8 @@ public class ClientPlayer implements IClientPlayer */ public void handlePlayerPosLook(SPacketPlayerPosLook packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - EntityNPC entityplayer = this.gm.player; + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + EntityNPC entityplayer = this.gameController.player; double d0 = packetIn.getX(); double d1 = packetIn.getY(); double d2 = packetIn.getZ(); @@ -687,15 +713,14 @@ public class ClientPlayer implements IClientPlayer } entityplayer.setPositionAndRotation(d0, d1, d2, f, f1); - this.connection.sendPacket(new CPacketPlayerPosLook(entityplayer.posX, entityplayer.getEntityBoundingBox().minY, entityplayer.posZ, entityplayer.rotYaw, entityplayer.rotPitch, false)); + this.netManager.sendPacket(new CPacketPlayer.C06PacketPlayerPosLook(entityplayer.posX, entityplayer.getEntityBoundingBox().minY, entityplayer.posZ, entityplayer.rotYaw, entityplayer.rotPitch, false)); - if (!this.loaded) + if (!this.doneLoadingTerrain) { - this.gm.player.prevX = this.gm.player.posX; - this.gm.player.prevY = this.gm.player.posY; - this.gm.player.prevZ = this.gm.player.posZ; - this.loaded = true; - this.world.markReload(); + this.gameController.player.prevX = this.gameController.player.posX; + this.gameController.player.prevY = this.gameController.player.posY; + this.gameController.player.prevZ = this.gameController.player.posZ; + this.doneLoadingTerrain = true; // this.gameController.displayGuiScreen(null); // if(this.travelSound) { // this.gameController.getSoundManager().playSound(new PositionedSound(SoundEvent.TELEPORT)); @@ -712,11 +737,11 @@ public class ClientPlayer implements IClientPlayer */ public void handleMultiBlockChange(SPacketMultiBlockChange packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - for (SPacketMultiBlockChange.BlockUpdateData update : packetIn.getChangedBlocks()) + for (SPacketMultiBlockChange.BlockUpdateData s22packetmultiblockchange$blockupdatedata : packetIn.getChangedBlocks()) { - this.world.invalidateRegionAndSetBlock(SPacketMultiBlockChange.getPos(packetIn.getChunkPos(), update.getRawPos()), update.getBlockState()); + this.clientWorldController.invalidateRegionAndSetBlock(s22packetmultiblockchange$blockupdatedata.getPos(), s22packetmultiblockchange$blockupdatedata.getBlockState()); } } @@ -725,45 +750,37 @@ public class ClientPlayer implements IClientPlayer */ public void handleChunkData(SPacketChunkData packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - if (packetIn.hasBiomes()) + if (packetIn.isResend()) { - if (packetIn.getExtractedExtend().length == 0) + if (packetIn.getExtractedSize() == 0) { - this.world.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), false); + this.clientWorldController.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), false); return; } - this.world.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), true); + this.clientWorldController.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), true); } // this.clientWorldController.invalidateBlockReceiveRegion(packetIn.getChunkX() << 4, 0, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, 512, (packetIn.getChunkZ() << 4) + 15); - ChunkClient chunk = this.world.getChunk(packetIn.getChunkX(), packetIn.getChunkZ()); - chunk.setData(packetIn.getExtractedDataBytes(), packetIn.getExtractedExtend(), packetIn.hasBiomes()); - this.world.markBlockRangeForRenderUpdate(packetIn.getChunkX() << 4, -World.MAX_SIZE_Y, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, World.MAX_SIZE_Y, (packetIn.getChunkZ() << 4) + 15); + Chunk chunk = this.clientWorldController.getChunk(packetIn.getChunkX(), packetIn.getChunkZ()); + chunk.setData(packetIn.getExtractedDataBytes(), packetIn.getExtractedSize(), packetIn.isResend()); + this.clientWorldController.markBlockRangeForRenderUpdate(packetIn.getChunkX() << 4, 0, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, 512, (packetIn.getChunkZ() << 4) + 15); - if (!packetIn.hasBiomes() || this.world.dimension.hasNoLight()) // TODO: check + if (!packetIn.isResend() || this.clientWorldController.dimension.hasNoLight()) // TODO: check { chunk.resetRelight(); } } - public void handleBiomes(SPacketBiome packetIn) - { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - ChunkClient chunk = this.world.getChunk(packetIn.getChunkX(), packetIn.getChunkZ()); - chunk.setBiome(packetIn.getPos(), packetIn.getBiome()); - this.world.markBlockRangeForRenderUpdate(packetIn.getChunkX() << 4, -World.MAX_SIZE_Y, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, World.MAX_SIZE_Y, (packetIn.getChunkZ() << 4) + 15); - } - /** * Updates the block and metadata and generates a blockupdate (and notify the clients) */ public void handleBlockChange(SPacketBlockChange packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - this.world.invalidateRegionAndSetBlock(packetIn.getBlockPosition(), packetIn.getBlockState()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + this.clientWorldController.invalidateRegionAndSetBlock(packetIn.getBlockPosition(), packetIn.getBlockState()); } /** @@ -771,33 +788,43 @@ public class ClientPlayer implements IClientPlayer */ public void handleDisconnect(SPacketDisconnect packetIn) { - this.connection.closeChannel(packetIn.getMessage()); + this.netManager.closeChannel(packetIn.getMessage()); + } + + public void onDisconnect(String reason) + { + this.gameController.disconnected(reason); + } + + public void addToSendQueue(Packet p_147297_1_) + { + this.netManager.sendPacket(p_147297_1_); } public void handleCollectItem(SPacketCollectItem packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = this.world.getEntityByID(packetIn.getCollectedItemEntityID()); - EntityLiving entitylivingbase = (EntityLiving)this.world.getEntityByID(packetIn.getEntityID()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getCollectedItemEntityID()); + EntityLiving entitylivingbase = (EntityLiving)this.clientWorldController.getEntityByID(packetIn.getEntityID()); if (entitylivingbase == null) { - entitylivingbase = this.gm.player; + entitylivingbase = this.gameController.player; } if (entity != null) { if (entity instanceof EntityXp) { - this.world.playSoundAtEntity(entity, SoundEvent.ORB, 0.2F); + this.clientWorldController.playSoundAtEntity(entity, SoundEvent.ORB, 0.2F); } else { - this.world.playSoundAtEntity(entity, SoundEvent.POP, 0.2F); + this.clientWorldController.playSoundAtEntity(entity, SoundEvent.POP, 0.2F); } - this.gm.effectRenderer.addEffect(new EntityPickupFX(this.world, entity, entitylivingbase, 0.5F)); - this.world.removeEntityFromWorld(packetIn.getCollectedItemEntityID()); + this.gameController.effectRenderer.addEffect(new EntityPickupFX(this.clientWorldController, entity, entitylivingbase, 0.5F)); + this.clientWorldController.removeEntityFromWorld(packetIn.getCollectedItemEntityID()); } } @@ -806,44 +833,44 @@ public class ClientPlayer implements IClientPlayer */ public void handleMessage(SPacketMessage packetIn) { - NetHandler.checkThread(packetIn, this, this.gm); + NetHandler.checkThread(packetIn, this, this.gameController); // if(this.gameController.chatVisibility == EnumChatVisibility.FULL || // (this.gameController.chatVisibility == EnumChatVisibility.SYSTEM && packetIn.isSystem())) // { switch(packetIn.getType()) { case CONSOLE: - this.gm.logConsole(packetIn.getMessage()); + this.gameController.logConsole(packetIn.getMessage()); break; case CHAT: - this.gm.logChat(packetIn.getMessage()); + this.gameController.logChat(packetIn.getMessage()); break; case FEED: - this.gm.logFeed(packetIn.getMessage()); + this.gameController.logFeed(packetIn.getMessage()); break; case HOTBAR: - this.gm.logHotbar(packetIn.getMessage()); + this.gameController.logHotbar(packetIn.getMessage()); break; } // } } public void handleLoading(SPacketLoading packet) { - NetHandler.checkThread(packet, this, this.gm); + NetHandler.checkThread(packet, this, this.gameController); if(packet.getMessage() == null) { if(packet.getTask() != null) - this.gm.message = packet.getTask(); + this.gameController.message = packet.getTask(); if(packet.getTotal() >= 0) - this.gm.total = packet.getTotal(); + this.gameController.total = packet.getTotal(); if(packet.getProgress() >= -1) - this.gm.progress = packet.getProgress(); + this.gameController.progress = packet.getProgress(); } else { - this.gm.message = ""; - this.gm.total = 0; - this.gm.progress = -1; - this.gm.displayGuiScreen(GuiLoading.makeServerTask(packet.getMessage())); + this.gameController.message = ""; + this.gameController.total = 0; + this.gameController.progress = -1; + this.gameController.displayGuiScreen(GuiLoading.makeServerTask(packet.getMessage())); } } @@ -868,8 +895,8 @@ public class ClientPlayer implements IClientPlayer */ public void handleAnimation(SPacketAnimation packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = this.world.getEntityByID(packetIn.getEntityID()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); if (entity != null) { @@ -889,11 +916,11 @@ public class ClientPlayer implements IClientPlayer // } else if (packetIn.getAnimationType() == 4) { - this.gm.effectRenderer.emitParticleAtEntity(entity, ParticleType.CRIT); + this.gameController.effectRenderer.emitParticleAtEntity(entity, ParticleType.CRIT); } else if (packetIn.getAnimationType() == 5) { - this.gm.effectRenderer.emitParticleAtEntity(entity, ParticleType.CRIT_MAGIC); + this.gameController.effectRenderer.emitParticleAtEntity(entity, ParticleType.CRIT_MAGIC); } } } @@ -914,13 +941,13 @@ public class ClientPlayer implements IClientPlayer */ public void handleSpawnMob(SPacketSpawnMob packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); double d0 = (double)packetIn.getX() / 32.0D; double d1 = (double)packetIn.getY() / 32.0D; double d2 = (double)packetIn.getZ() / 32.0D; float f = (float)(packetIn.getYaw() * 360) / 256.0F; float f1 = (float)(packetIn.getPitch() * 360) / 256.0F; - EntityLiving entitylivingbase = (EntityLiving)EntityRegistry.createEntityByID(packetIn.getEntityType(), this.gm.world); + EntityLiving entitylivingbase = (EntityLiving)EntityRegistry.createEntityByID(packetIn.getEntityType(), this.gameController.world); entitylivingbase.serverPosX = packetIn.getX(); entitylivingbase.serverPosY = packetIn.getY(); entitylivingbase.serverPosZ = packetIn.getZ(); @@ -942,7 +969,7 @@ public class ClientPlayer implements IClientPlayer entitylivingbase.motionX = (double)((float)packetIn.getVelocityX() / 8000.0F); entitylivingbase.motionY = (double)((float)packetIn.getVelocityY() / 8000.0F); entitylivingbase.motionZ = (double)((float)packetIn.getVelocityZ() / 8000.0F); - this.world.addEntityToWorld(packetIn.getEntityID(), entitylivingbase); + this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entitylivingbase); List list = packetIn.getMetadata(); if (list != null) @@ -953,16 +980,16 @@ public class ClientPlayer implements IClientPlayer public void handleTimeUpdate(SPacketTimeUpdate packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); // this.gameController.theWorld.getWorldInfo().setTime(packetIn.getTotalWorldTime()); - this.gm.world.setDayTime(packetIn.getWorldTime()); - this.gm.setTicked(packetIn.getServerinfo()); + this.gameController.world.setDayTime(packetIn.getWorldTime()); + this.gameController.setTicked(packetIn.getServerinfo()); } public void handleServerTick(SPacketServerTick packet) { - NetHandler.checkThread(packet, this, this.gm); - this.gm.setLastTick(packet.getTime()); + NetHandler.checkThread(packet, this, this.gameController); + this.gameController.setLastTick(packet.getTime(), packet.getServerinfo()); } // public void handleCompass(SPacketCompass packetIn) @@ -971,30 +998,30 @@ public class ClientPlayer implements IClientPlayer // this.gameController.thePlayer.setSpawnPoint(packetIn.getSpawnPos(), true); // } - public void handleEntityAttach(SPacketEntityAttach packetIn) + public void handleEntityAttach(S1BPacketEntityAttach packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = this.world.getEntityByID(packetIn.getEntityId()); - Entity entity1 = this.world.getEntityByID(packetIn.getVehicleEntityId()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + Entity entity1 = this.clientWorldController.getEntityByID(packetIn.getVehicleEntityId()); if (packetIn.getLeash() == 0) { // boolean flag = false; - if (packetIn.getEntityId() == this.gm.player.getId()) + if (packetIn.getEntityId() == this.gameController.player.getId()) { - entity = this.gm.player; + entity = this.gameController.player; - if (entity1 instanceof EntityBoat boat) + if (entity1 instanceof EntityBoat) { - boat.setIsBoatEmpty(false); + ((EntityBoat)entity1).setIsBoatEmpty(false); } // flag = entity.vehicle == null && entity1 != null; } - else if (entity1 instanceof EntityBoat boat) + else if (entity1 instanceof EntityBoat) { - boat.setIsBoatEmpty(true); + ((EntityBoat)entity1).setIsBoatEmpty(true); } if (entity == null) @@ -1009,15 +1036,15 @@ public class ClientPlayer implements IClientPlayer // this.gameController.ingameGui.displayHotbar(TextColor.LIGHT_GRAY + String.format("Drücke %s zum Verlassen", this.gameController.keyBindSneak.getKeyDisplay())); // } } - else if (packetIn.getLeash() == 1 && entity instanceof EntityLiving living) + else if (packetIn.getLeash() == 1 && entity instanceof EntityLiving) { if (entity1 != null) { - living.setLeashedTo(entity1, false); + ((EntityLiving)entity).setLeashedTo(entity1, false); } else { - living.clearLeashed(false, false); + ((EntityLiving)entity).clearLeashed(false, false); } } } @@ -1028,10 +1055,10 @@ public class ClientPlayer implements IClientPlayer * (spawn particles), Zombie (villager transformation), Animal (breeding mode particles), Horse (breeding/smoke * particles), Sheep (...), Tameable (...), Villager (particles for breeding mode, angry and happy), Wolf (...) */ - public void handleEntityStatus(SPacketEntityStatus packetIn) + public void handleEntityStatus(S1APacketEntityStatus packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = packetIn.getEntity(this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = packetIn.getEntity(this.clientWorldController); if (entity != null) { @@ -1048,141 +1075,115 @@ public class ClientPlayer implements IClientPlayer public void handleUpdateHealth(SPacketUpdateHealth packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - this.gm.player.setPlayerSPHealth(packetIn.getHealth()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + this.gameController.player.setPlayerSPHealth(packetIn.getHealth()); // this.gameController.thePlayer.getFoodStats().setFoodLevel(packetIn.getFoodLevel()); // this.gameController.thePlayer.getFoodStats().setFoodSaturationLevel(packetIn.getSaturationLevel()); } public void handleSetExperience(SPacketSetExperience packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - this.gm.player.setXPStats(packetIn.getProgress(), packetIn.getTotalExperience(), packetIn.getLevel()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + this.gameController.player.setXPStats(packetIn.getProgress(), packetIn.getTotalExperience(), packetIn.getLevel()); } public void handleRespawn(SPacketRespawn packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - this.gm.charEditor = packetIn.isInEditor(); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + this.gameController.charEditor = packetIn.isInEditor(); Dimension dim = packetIn.getDimension(); - if (dim.getDimensionId() != this.world.dimension.getDimensionId()) // this.gameController.thePlayer.dimension) + if (dim.getDimensionId() != this.clientWorldController.dimension.getDimensionId()) // this.gameController.thePlayer.dimension) { - this.loaded = false; + this.doneLoadingTerrain = false; // if(dim.getDimensionId() < 0 && this.gameController.thePlayer.dimension >= 0) { // this.travelSound = "portal.travel"; // } // Scoreboard scoreboard = this.clientWorldController.getScoreboard(); - this.world = new WorldClient(this.gm, dim); + this.clientWorldController = new WorldClient(this.gameController, this.gameController.debugWorld, dim); // this.clientWorldController.setWorldScoreboard(scoreboard); - this.gm.loadWorld(this.world, packetIn.getEntityType()); + this.gameController.loadWorld(this.clientWorldController, packetIn.getEntityType()); // this.gameController.thePlayer.dimension = dim.getDimensionId(); } // else if(this.gameController.charEditor) { // this.gameController.displayGuiScreen(GuiSkin.INSTANCE); // } - this.gm.setDimensionAndSpawnPlayer(dim.getDimensionId(), packetIn.getEntityType()); - this.gm.displayGuiScreen(this.gm.charEditor ? GuiChar.INSTANCE : null); + this.gameController.setDimensionAndSpawnPlayer(dim.getDimensionId(), packetIn.getEntityType()); + this.gameController.displayGuiScreen(this.gameController.charEditor ? GuiChar.INSTANCE : null); // this.gameController.controller.setCheat(packetIn.getCheat()); } /** * Initiates a new explosion (sound, particles, drop spawn) for the affected blocks indicated by the packet. */ - public void handleExplosion(SPacketExplosion packetIn) + public void handleExplosion(S27PacketExplosion packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Explosion explosion = new Explosion(this.gm.world, (Entity)null, packetIn.getX(), packetIn.getY(), packetIn.getZ(), packetIn.getStrength(), packetIn.getAffectedBlockPositions()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Explosion explosion = new Explosion(this.gameController.world, (Entity)null, packetIn.getX(), packetIn.getY(), packetIn.getZ(), packetIn.getStrength(), packetIn.getAffectedBlockPositions()); explosion.doExplosionB(true, packetIn.hasAltSound()); - this.gm.player.motionX += (double)packetIn.func_149149_c(); - this.gm.player.motionY += (double)packetIn.func_149144_d(); - this.gm.player.motionZ += (double)packetIn.func_149147_e(); + this.gameController.player.motionX += (double)packetIn.func_149149_c(); + this.gameController.player.motionY += (double)packetIn.func_149144_d(); + this.gameController.player.motionZ += (double)packetIn.func_149147_e(); } /** * Displays a GUI by ID. In order starting from id 0: Chest, Workbench, Furnace, Dispenser, Enchanting table, * Brewing stand, Villager merchant, Beacon, Anvil, Hopper, Dropper, Horse */ - public void handleOpenWindow(SPacketOpenWindow packet) + public void handleOpenWindow(S2DPacketOpenWindow packetIn) { - NetHandler.checkThread(packet, this, this.gm, this.world); - EntityNPC player = this.gm.player; - String id = packet.getGuiId(); - String title = packet.getWindowTitle(); - int slots = packet.getSlotCount(); - LocalContainer local = new LocalContainer(title, slots); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + EntityNPC entityplayersp = this.gameController.player; - if ("container".equals(id)) + if ("container".equals(packetIn.getGuiId())) { - this.gm.displayGuiScreen(new GuiChest(player.inventory, new InventoryBasic(title, slots))); + entityplayersp.displayGUIChest(new InventoryBasic(packetIn.getWindowTitle(), packetIn.getSlotCount())); + entityplayersp.openContainer.windowId = packetIn.getWindowId(); } - else if ("enchanting_table".equals(id)) + else if ("trade".equals(packetIn.getGuiId())) { - this.gm.displayGuiScreen(new GuiEnchant(player.inventory, player.worldObj, title)); + entityplayersp.displayTradeGui(packetIn.getWindowTitle()); + entityplayersp.openContainer.windowId = packetIn.getWindowId(); } - else if ("anvil".equals(id)) + else if ("EntityHorse".equals(packetIn.getGuiId())) { - this.gm.displayGuiScreen(new GuiRepair(player.inventory, player.worldObj)); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + + if (entity instanceof EntityHorse) + { + entityplayersp.displayGUIHorse((EntityHorse)entity, new AnimalChest(packetIn.getWindowTitle(), true, packetIn.getSlotCount())); + entityplayersp.openContainer.windowId = packetIn.getWindowId(); + } } - else if ("chest".equals(id)) + else if (!packetIn.hasSlots()) { - this.gm.displayGuiScreen(new GuiChest(player.inventory, local)); - } - else if ("hopper".equals(id)) - { - this.gm.displayGuiScreen(new GuiHopper(player.inventory, local)); - } - else if ("furnace".equals(id)) - { - this.gm.displayGuiScreen(new GuiFurnace(player.inventory, local)); - } - else if ("brewing_stand".equals(id)) - { - this.gm.displayGuiScreen(new GuiBrewing(player.inventory, local)); - } - else if ("dispenser".equals(id) || "dropper".equals(id)) - { - this.gm.displayGuiScreen(new GuiDispenser(player.inventory, local)); - } - else if ("trade".equals(id)) - { - this.gm.displayGuiScreen(new GuiMerchant(player.inventory, title, player.worldObj)); - } - else if ("entity".equals(id)) - { - Entity entity = this.world.getEntityByID(packet.getEntityId()); - if(entity == null) - return; - this.gm.displayGuiScreen(new GuiEntity(player.inventory, new AnimalChest(title, true, slots), entity)); - } - else if ("tile".equals(id)) - { - TileEntity tile = this.world.getTileEntity(packet.getTilePos()); - if(!(tile instanceof TileEntityDevice dev)) - return; - this.gm.displayGuiScreen(new GuiTile(this.gm.player.inventory, local, dev)); + entityplayersp.displayGui(new LocalBlockIntercommunication(packetIn.getGuiId(), packetIn.getWindowTitle())); + entityplayersp.openContainer.windowId = packetIn.getWindowId(); } else { - Block block = BlockRegistry.getRegisteredBlock(id); - if(block instanceof BlockWorkbench bench) { - this.gm.displayGuiScreen(new GuiCrafting(player.inventory, player.worldObj, bench)); - } - else { - this.gm.displayGuiScreen(new GuiChest(player.inventory, local)); - } + ContainerLocalMenu containerlocalmenu = new ContainerLocalMenu(packetIn.getGuiId(), packetIn.getWindowTitle(), packetIn.getSlotCount()); + if (packetIn.getGuiId().startsWith("machine_")) + { + TileEntity machine = this.clientWorldController.getTileEntity(packetIn.getTilePos()); + if(machine instanceof TileEntityMachine) + this.gameController.displayGuiScreen(new GuiMachine(this.gameController.player.inventory, containerlocalmenu, (TileEntityMachine)machine)); + } + else { + entityplayersp.displayGUIChest(containerlocalmenu); + } + entityplayersp.openContainer.windowId = packetIn.getWindowId(); } - player.openContainer.windowId = packet.getWindowId(); } - - /** + + /** * Handles pickin up an ItemStack or dropping one in your inventory or an open container */ - public void handleSetSlot(SPacketSetSlot packetIn) + public void handleSetSlot(S2FPacketSetSlot packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - EntityNPC entityplayer = this.gm.player; + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + EntityNPC entityplayer = this.gameController.player; if (packetIn.getWindowId() == -1) { @@ -1220,11 +1221,11 @@ public class ClientPlayer implements IClientPlayer * Verifies that the server and client are synchronized with respect to the inventory/container opened by the player * and confirms if it is the case. */ - public void handleConfirmTransaction(SPacketConfirmTransaction packetIn) + public void handleConfirmTransaction(S32PacketConfirmTransaction packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); Container container = null; - EntityNPC entityplayer = this.gm.player; + EntityNPC entityplayer = this.gameController.player; if (packetIn.getWindowId() == 0) { @@ -1244,10 +1245,10 @@ public class ClientPlayer implements IClientPlayer /** * Handles the placement of a specified ItemStack in a specified container/inventory slot */ - public void handleWindowItems(SPacketWindowItems packetIn) + public void handleWindowItems(S30PacketWindowItems packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - EntityNPC entityplayer = this.gm.player; + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + EntityNPC entityplayer = this.gameController.player; if (packetIn.func_148911_c() == 0) { @@ -1262,40 +1263,42 @@ public class ClientPlayer implements IClientPlayer /** * Creates a sign in the specified location if it didn't exist and opens the GUI to edit its text */ - public void handleSignEditorOpen(SPacketSignEditorOpen packetIn) + public void handleSignEditorOpen(S36PacketSignEditorOpen packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - TileEntity tileentity = this.world.getTileEntity(packetIn.getSignPosition()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + TileEntity tileentity = this.clientWorldController.getTileEntity(packetIn.getSignPosition()); if (!(tileentity instanceof TileEntitySign)) { tileentity = new TileEntitySign(); - tileentity.setWorldObj(this.world); + tileentity.setWorldObj(this.clientWorldController); tileentity.setPos(packetIn.getSignPosition()); } - this.gm.displayGuiScreen(new GuiSign(packetIn.getSignPosition(), ((TileEntitySign)tileentity).signText)); + this.gameController.player.openEditSign((TileEntitySign)tileentity); } public void handleForm(SPacketDisplayForm packet) { - NetHandler.checkThread(packet, this, this.gm, this.world); - this.gm.displayGuiScreen(new GuiForm(packet.getId(), packet.getTitle(), packet.getData())); + NetHandler.checkThread(packet, this, this.gameController, this.clientWorldController); + this.gameController.displayGuiScreen(new GuiForm(packet.getId(), packet.getTitle(), packet.getData())); } /** * Updates a specified sign with the specified text lines */ - public void handleUpdateSign(SPacketUpdateSign packetIn) + public void handleUpdateSign(S33PacketUpdateSign packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); // boolean flag = false; - if (this.gm.world.isBlockLoaded(packetIn.getPos())) + if (this.gameController.world.isBlockLoaded(packetIn.getPos())) { - TileEntity tileentity = this.gm.world.getTileEntity(packetIn.getPos()); + TileEntity tileentity = this.gameController.world.getTileEntity(packetIn.getPos()); - if (tileentity instanceof TileEntitySign tileentitysign) + if (tileentity instanceof TileEntitySign) { + TileEntitySign tileentitysign = (TileEntitySign)tileentity; + // if (tileentitysign.getIsEditable()) // { System.arraycopy(packetIn.getLines(), 0, tileentitysign.signText, 0, 4); @@ -1315,21 +1318,21 @@ public class ClientPlayer implements IClientPlayer } /** - * Updates the metadata of instances of the following entitytypes: Mob spawners, command blocks, + * Updates the NBTTagCompound metadata of instances of the following entitytypes: Mob spawners, command blocks, * beacons, skulls, flowerpot */ - public void handleUpdateTileEntity(SPacketUpdateTileEntity packetIn) + public void handleUpdateTileEntity(S35PacketUpdateTileEntity packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - if (this.gm.world.isBlockLoaded(packetIn.getPos())) + if (this.gameController.world.isBlockLoaded(packetIn.getPos())) { - TileEntity tileentity = this.gm.world.getTileEntity(packetIn.getPos()); + TileEntity tileentity = this.gameController.world.getTileEntity(packetIn.getPos()); // int i = packetIn.getTileEntityType(); if (tileentity != null && packetIn.isTileEntityType(tileentity)) // i == 1 && tileentity instanceof TileEntityMobSpawner || /* i == 2 && tileentity instanceof TileEntityCommandBlock || */ i == 3 && tileentity instanceof TileEntityBeacon || i == 4 && tileentity instanceof TileEntitySkull || /* i == 5 && tileentity instanceof TileEntityFlowerPot || */ i == 6 && tileentity instanceof TileEntityBanner || i == 7 && tileentity instanceof TileEntityMachine) { - tileentity.readTags(packetIn.getTags()); + tileentity.readFromNBT(packetIn.getNbtCompound()); } } } @@ -1337,10 +1340,10 @@ public class ClientPlayer implements IClientPlayer /** * Sets the progressbar of the opened window to the specified value */ - public void handleWindowProperty(SPacketWindowProperty packetIn) + public void handleWindowProperty(S31PacketWindowProperty packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - EntityNPC entityplayer = this.gm.player; + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + EntityNPC entityplayer = this.gameController.player; if (entityplayer.openContainer != null && entityplayer.openContainer.windowId == packetIn.getWindowId()) { @@ -1350,8 +1353,8 @@ public class ClientPlayer implements IClientPlayer public void handleEntityEquipment(SPacketEntityEquipment packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = this.world.getEntityByID(packetIn.getEntityID()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); if (entity != null) { @@ -1362,11 +1365,11 @@ public class ClientPlayer implements IClientPlayer /** * Resets the ItemStack held in hand and closes the window that is opened */ - public void handleCloseWindow(SPacketCloseWindow packetIn) + public void handleCloseWindow(S2EPacketCloseWindow packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); // this.gameController.thePlayer.closeScreenAndDropStack(); - this.gm.displayGuiScreen(null); + this.gameController.displayGuiScreen(null); } /** @@ -1376,8 +1379,8 @@ public class ClientPlayer implements IClientPlayer */ public void handleBlockAction(SPacketBlockAction packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - this.gm.world.addBlockEvent(packetIn.getBlockPosition(), packetIn.getBlockType(), packetIn.getData1(), packetIn.getData2()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + this.gameController.world.addBlockEvent(packetIn.getBlockPosition(), packetIn.getBlockType(), packetIn.getData1(), packetIn.getData2()); } /** @@ -1385,59 +1388,56 @@ public class ClientPlayer implements IClientPlayer */ public void handleBlockBreakAnim(SPacketBlockBreakAnim packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - this.gm.world.sendBlockBreakProgress(packetIn.getBreakerId(), packetIn.getPosition(), packetIn.getProgress()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + this.gameController.world.sendBlockBreakProgress(packetIn.getBreakerId(), packetIn.getPosition(), packetIn.getProgress()); } public void handleMapChunkBulk(SPacketMapChunkBulk packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); for (int i = 0; i < packetIn.getChunkCount(); ++i) { int j = packetIn.getChunkX(i); int k = packetIn.getChunkZ(i); - this.world.doPreChunk(j, k, true); + this.clientWorldController.doPreChunk(j, k, true); // this.clientWorldController.invalidateBlockReceiveRegion(j << 4, 0, k << 4, (j << 4) + 15, 512, (k << 4) + 15); - ChunkClient chunk = this.world.getChunk(j, k); - chunk.setData(packetIn.getChunkBytes(i), packetIn.getChunkExtend(i), true); - this.world.markBlockRangeForRenderUpdate(j << 4, -World.MAX_SIZE_Y, k << 4, (j << 4) + 15, World.MAX_SIZE_Y, (k << 4) + 15); + Chunk chunk = this.clientWorldController.getChunk(j, k); + chunk.setData(packetIn.getChunkBytes(i), packetIn.getChunkSize(i), true); + this.clientWorldController.markBlockRangeForRenderUpdate(j << 4, 0, k << 4, (j << 4) + 15, 512, (k << 4) + 15); - if (this.world.dimension.hasNoLight()) // TODO: check + if (this.clientWorldController.dimension.hasNoLight()) // TODO: check { chunk.resetRelight(); } } } - public void handleChangeGameState(SPacketChangeGameState packetIn) + public void handleChangeGameState(S2BPacketChangeGameState packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); switch(packetIn.getAction()) { // case SET_CHEAT: // this.gameController.controller.setCheat(packetIn.getInt() == 1); // break; case SET_WEATHER: - this.world.setWeather(Weather.getByID(packetIn.getInt())); + this.clientWorldController.setWeather(Weather.getByID(packetIn.getInt())); break; case RAIN_STRENGTH: - this.world.setRainStrength(packetIn.getFloat(true)); + this.clientWorldController.setRainStrength(packetIn.getFloat(true)); break; case DARKNESS: - this.world.setDarkness(packetIn.getFloat(true)); + this.clientWorldController.setDarkness(packetIn.getFloat(true)); break; case FOG_STRENGTH: - this.world.setFogStrength(packetIn.getFloat(true)); - break; - case TEMPERATURE: - this.world.setTemperature(packetIn.getFloat(false)); + this.clientWorldController.setFogStrength(packetIn.getFloat(true)); break; } } - public void handleEffect(SPacketEffect packetIn) + public void handleEffect(S28PacketEffect packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); // if (packetIn.isSoundServerwide()) // { @@ -1445,7 +1445,7 @@ public class ClientPlayer implements IClientPlayer // } // else // { - this.gm.world.playAuxSFX(packetIn.getSoundType(), packetIn.getSoundPos(), packetIn.getSoundData()); + this.gameController.world.playAuxSFX(packetIn.getSoundType(), packetIn.getSoundPos(), packetIn.getSoundData()); // } } @@ -1500,16 +1500,16 @@ public class ClientPlayer implements IClientPlayer // } // } - public void handleEntityEffect(SPacketEntityEffect packetIn) + public void handleEntityEffect(S1DPacketEntityEffect packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = this.world.getEntityByID(packetIn.getEntityId()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - if (entity instanceof EntityLiving living) + if (entity instanceof EntityLiving) { PotionEffect potioneffect = new PotionEffect(packetIn.getEffectId(), packetIn.getDuration(), packetIn.getAmplifier(), false, packetIn.hasParticles()) .setRemaining(packetIn.getRemaining()); - living.addEffect(potioneffect); + ((EntityLiving)entity).addEffect(potioneffect); } } @@ -1528,12 +1528,12 @@ public class ClientPlayer implements IClientPlayer public void handleCamera(SPacketCamera packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = packetIn.getEntity(this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = packetIn.getEntity(this.clientWorldController); if (entity != null) { - this.gm.setRenderViewEntity(entity); + this.gameController.setRenderViewEntity(entity); } } @@ -1577,27 +1577,27 @@ public class ClientPlayer implements IClientPlayer //// } // } - public void handleRemoveEntityEffect(SPacketRemoveEntityEffect packetIn) + public void handleRemoveEntityEffect(S1EPacketRemoveEntityEffect packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = this.world.getEntityByID(packetIn.getEntityId()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - if (entity instanceof EntityLiving living) + if (entity instanceof EntityLiving) { - living.removeEffectClient(packetIn.getEffectId()); + ((EntityLiving)entity).removeEffectClient(packetIn.getEffectId()); } } - public void handlePlayerListItem(SPacketPlayerListItem packetIn) + public void handlePlayerListItem(S38PacketPlayerListItem packetIn) { - NetHandler.checkThread(packetIn, this, this.gm); + NetHandler.checkThread(packetIn, this, this.gameController); for(Entry data : packetIn.getEntries()) { if(data.getValue() < 0) - this.gm.playerList.remove(data.getKey()); + this.playerList.remove(data.getKey()); else - this.gm.playerList.put(data.getKey(), data.getValue()); + this.playerList.put(data.getKey(), data.getValue()); } // String[] list = new String[this.playerList.size()]; // int[] data = new int[this.playerList.size()]; @@ -1611,26 +1611,23 @@ public class ClientPlayer implements IClientPlayer public void handleCharacterList(SPacketCharacterList packet) { - NetHandler.checkThread(packet, this, this.gm); + NetHandler.checkThread(packet, this, this.gameController); for(Entry data : packet.getEntries()) { if(data.getValue() == null) - this.gm.characterList.remove(data.getKey().intValue()); - else if(data.getKey() < this.gm.characterList.size()) - this.gm.characterList.set(data.getKey(), data.getValue()); + this.characterList.remove(data.getKey().intValue()); + else if(data.getKey() < this.characterList.size()) + this.characterList.set(data.getKey(), data.getValue()); else - this.gm.characterList.add(data.getKey(), data.getValue()); + this.characterList.add(data.getKey(), data.getValue()); } - this.gm.selectedCharacter = packet.getSelected(); - if(this.gm.charEditor && this.gm.selectedCharacter >= 0) { - this.gm.charEditor = false; - this.gm.displayGuiScreen(null); + this.selectedCharacter = packet.getSelected(); + if(this.gameController.charEditor && this.selectedCharacter >= 0) { + this.gameController.charEditor = false; + this.gameController.displayGuiScreen(null); } - else if(this.gm.open instanceof GuiCharacters) { - this.gm.displayGuiScreen(this.gm.open); - } - else if(this.gm.open instanceof GuiChar guichar) { - guichar.setCharsAvailable(); + else if(this.gameController.open instanceof GuiCharacters) { + this.gameController.displayGuiScreen(this.gameController.open); } } @@ -1639,10 +1636,10 @@ public class ClientPlayer implements IClientPlayer this.addToSendQueue(new CPacketKeepAlive(packetIn.getValue())); } - public void handlePlayerAbilities(SPacketPlayerAbilities packetIn) + public void handlePlayerAbilities(S39PacketPlayerAbilities packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - EntityNPC entityplayer = this.gm.player; + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + EntityNPC entityplayer = this.gameController.player; entityplayer.flying = packetIn.isFlying(); entityplayer.noclip = packetIn.isNoclip(); // entityplayer.speed = packetIn.getSpeed(); @@ -1652,28 +1649,29 @@ public class ClientPlayer implements IClientPlayer /** * Displays the available command-completion options the server knows of */ - public void handleTabComplete(SPacketTabComplete packetIn) + public void handleTabComplete(S3APacketTabComplete packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); String[] astring = packetIn.func_149630_c(); // this.gameController.complete(astring); - if (this.gm.open instanceof GuiConsole guichat) + if (this.gameController.open instanceof GuiConsole) { + GuiConsole guichat = (GuiConsole)this.gameController.open; guichat.onAutocompleteResponse(astring); } } - public void handleSoundEffect(SPacketSoundEffect packetIn) + public void handleSoundEffect(S29PacketSoundEffect packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); if(packetIn.getSound() == null) { - this.gm.getSoundManager().stopSounds(); + this.gameController.getSoundManager().stopSounds(); return; } // else if(packetIn.getSoundName().startsWith("music#")) { // return; // } - this.gm.world.playSound(packetIn.getX(), packetIn.getY(), packetIn.getZ(), packetIn.getSound(), packetIn.getVolume()); + this.gameController.world.playSound(packetIn.getX(), packetIn.getY(), packetIn.getZ(), packetIn.getSound(), packetIn.getVolume()); } // public void handleDisplay(S48PacketDisplay packetIn) @@ -1700,14 +1698,14 @@ public class ClientPlayer implements IClientPlayer //// } // } - public void handleEntityTags(SPacketUpdateEntityTags packetIn) + public void handleEntityNBT(S43PacketUpdateEntityNBT packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = packetIn.getEntity(this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = packetIn.getEntity(this.clientWorldController); if (entity != null) { - entity.clientUpdateEntityTags(packetIn.getTagCompound()); + entity.clientUpdateEntityNBT(packetIn.getTagCompound()); } } @@ -1824,9 +1822,9 @@ public class ClientPlayer implements IClientPlayer * Spawns a specified number of particles at the specified location with a randomized displacement according to * specified bounds */ - public void handleParticles(SPacketParticles packetIn) + public void handleParticles(S2APacketParticles packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); if (packetIn.getParticleCount() == 0) { @@ -1837,42 +1835,83 @@ public class ClientPlayer implements IClientPlayer try { ParticleType particle = packetIn.getParticleType(); - this.world.spawnEntityFX(particle, particle.getShouldIgnoreRange() | packetIn.isLongDistance(), packetIn.getXCoordinate(), packetIn.getYCoordinate(), packetIn.getZCoordinate(), d0, d2, d4, packetIn.getParticleArgs()); + this.clientWorldController.spawnEntityFX(particle, particle.getShouldIgnoreRange() | packetIn.isLongDistance(), packetIn.getXCoordinate(), packetIn.getYCoordinate(), packetIn.getZCoordinate(), d0, d2, d4, packetIn.getParticleArgs()); } catch (Throwable var17) { - Log.RENDER.warn("Konnte Partikel-Effekt " + packetIn.getParticleType() + " nicht erzeugen"); + Log.JNI.warn("Konnte Partikel-Effekt " + packetIn.getParticleType() + " nicht erzeugen"); } } else { for (int i = 0; i < packetIn.getParticleCount(); ++i) { - double d1 = this.rand.gaussian() * (double)packetIn.getXOffset(); - double d3 = this.rand.gaussian() * (double)packetIn.getYOffset(); - double d5 = this.rand.gaussian() * (double)packetIn.getZOffset(); - double d6 = this.rand.gaussian() * (double)packetIn.getParticleSpeed(); - double d7 = this.rand.gaussian() * (double)packetIn.getParticleSpeed(); - double d8 = this.rand.gaussian() * (double)packetIn.getParticleSpeed(); + double d1 = this.avRandomizer.gaussian() * (double)packetIn.getXOffset(); + double d3 = this.avRandomizer.gaussian() * (double)packetIn.getYOffset(); + double d5 = this.avRandomizer.gaussian() * (double)packetIn.getZOffset(); + double d6 = this.avRandomizer.gaussian() * (double)packetIn.getParticleSpeed(); + double d7 = this.avRandomizer.gaussian() * (double)packetIn.getParticleSpeed(); + double d8 = this.avRandomizer.gaussian() * (double)packetIn.getParticleSpeed(); try { ParticleType particle = packetIn.getParticleType(); - this.world.spawnEntityFX(particle, particle.getShouldIgnoreRange() | packetIn.isLongDistance(), packetIn.getXCoordinate() + d1, packetIn.getYCoordinate() + d3, packetIn.getZCoordinate() + d5, d6, d7, d8, packetIn.getParticleArgs()); + this.clientWorldController.spawnEntityFX(particle, particle.getShouldIgnoreRange() | packetIn.isLongDistance(), packetIn.getXCoordinate() + d1, packetIn.getYCoordinate() + d3, packetIn.getZCoordinate() + d5, d6, d7, d8, packetIn.getParticleArgs()); } catch (Throwable var16) { - Log.RENDER.warn("Konnte Partikel-Effekt " + packetIn.getParticleType() + " nicht erzeugen"); + Log.JNI.warn("Konnte Partikel-Effekt " + packetIn.getParticleType() + " nicht erzeugen"); return; } } } } + /** + * Updates en entity's attributes and their respective modifiers, which are used for speed bonusses (player + * sprinting, animals fleeing, baby speed), weapon/tool attackDamage, hostiles followRange randomization, zombie + * maxHealth and knockback resistance as well as reinforcement spawning chance. + */ + public void handleEntityProperties(S20PacketEntityProperties packetIn) + { + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + + if (entity != null) + { + if (!(entity instanceof EntityLiving)) + { + throw new IllegalStateException("Server tried to update attributes of a non-living entity (actually: " + entity + ")"); + } + else + { + AttributeMap baseattributemap = ((EntityLiving)entity).getAttributeMap(); + + for (S20PacketEntityProperties.Snapshot s20packetentityproperties$snapshot : packetIn.func_149441_d()) + { + AttributeInstance iattributeinstance = baseattributemap.getAttributeInstanceByName(s20packetentityproperties$snapshot.func_151409_a()); + + if (iattributeinstance == null) + { + iattributeinstance = baseattributemap.registerAttribute(Attribute.getAttribute(s20packetentityproperties$snapshot.func_151409_a())); + } + + iattributeinstance.setBaseValue(s20packetentityproperties$snapshot.func_151410_b()); + iattributeinstance.removeAllModifiers(); + + for (AttributeModifier attributemodifier : s20packetentityproperties$snapshot.func_151408_c()) + { + iattributeinstance.applyModifier(attributemodifier); + } + } + } + } + } + public void handleSkin(SPacketSkin packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = packetIn.getEntity(this.world); + Entity entity = packetIn.getEntity(this.clientWorldController); if(entity != null && entity.isPlayer()) // { EntityTexManager.setTexture(entity.getId(), packetIn.getTexture(), ((EntityNPC)entity).getModel()); // if(entity == this.gameController.thePlayer) @@ -1897,37 +1936,131 @@ public class ClientPlayer implements IClientPlayer // } public void handleTrades(SPacketTrades packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); try { int i = packetIn.getWindowId(); - Gui gui = this.gm.open; + Gui gui = this.gameController.open; - if (gui != null && gui instanceof GuiMerchant merchant && i == this.gm.player.openContainer.windowId) + if (gui != null && gui instanceof GuiMerchant && i == this.gameController.player.openContainer.windowId) { // NpcMerchant imerchant = ((GuiMerchant)guiscreen).getMerchant(); MerchantRecipeList merchantrecipelist = packetIn.getTrades(); - merchant.setRecipes(merchantrecipelist); + ((GuiMerchant)gui).setRecipes(merchantrecipelist); } } catch (Exception exception) { - Log.TICK.error((Throwable)exception, (String)"Konnte Handel nicht laden"); + Log.JNI.error((Throwable)exception, (String)"Konnte Handel nicht laden"); } } public void handleWorld(SPacketWorld packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - this.world.setGravity(this.gm.gravity = packetIn.getGravity()); - this.world.setTimeFactor(this.gm.timeFactor = packetIn.getTimeFactor()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + this.clientWorldController.setGravity(this.gameController.gravity = packetIn.getGravity()); + this.clientWorldController.setTimeFactor(this.gameController.timeFactor = packetIn.getTimeFactor()); // this.clientWorldController.setDifficulty(this.gameController.difficulty = packetIn.getDifficulty()); - this.gm.dayCycle = packetIn.hasDayCycle(); + this.gameController.dayCycle = packetIn.hasDayCycle(); } public void handleDimName(SPacketDimensionName packetIn) { - NetHandler.checkThread(packetIn, this, this.gm, this.world); - this.world.dimension.setFullName(packetIn.getFullName()); - this.world.dimension.setCustomName(packetIn.getCustomName()); + NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + this.clientWorldController.dimension.setFullName(packetIn.getFullName()); + this.clientWorldController.dimension.setCustomName(packetIn.getCustomName()); } + + /** + * Returns this the NetworkManager instance registered with this NetworkHandlerPlayClient + */ + public NetConnection getNetworkManager() + { + return this.netManager; + } + + public Set> getPlayerList() + { + return this.playerList.entrySet(); + } + + public Collection getCharacterList() + { + return this.characterList; + } + + public int getSelectedCharacter() + { + return this.selectedCharacter; + } + + public Iterable getPlayerNames() + { + return this.playerList.keySet(); + } + + public void displayGUIChest(IInventory chestInventory, InventoryPlayer inventory) { + String s = chestInventory instanceof IInteractionObject ? ((IInteractionObject)chestInventory).getGuiID() : "container"; + + if ("chest".equals(s)) + { + this.gameController.displayGuiScreen(new GuiChest(inventory, chestInventory)); + } + else if ("hopper".equals(s)) + { + this.gameController.displayGuiScreen(new GuiHopper(inventory, chestInventory)); + } + else if ("furnace".equals(s)) + { + this.gameController.displayGuiScreen(new GuiFurnace(inventory, chestInventory)); + } + else if ("brewing_stand".equals(s)) + { + this.gameController.displayGuiScreen(new GuiBrewing(inventory, chestInventory)); + } +// else if ("beacon".equals(s)) +// { +// this.gm.displayGuiScreen(new GuiBeacon(this.inventory, chestInventory)); +// } + else if (!"dispenser".equals(s) && !"dropper".equals(s)) + { + this.gameController.displayGuiScreen(new GuiChest(inventory, chestInventory)); + } + else + { + this.gameController.displayGuiScreen(new GuiDispenser(inventory, chestInventory)); + } + } + + public void displayGui(IInteractionObject guiOwner, InventoryPlayer inventory, World worldObj) { + String s = guiOwner.getGuiID(); + + if ("crafting_table".equals(s)) + { + this.gameController.displayGuiScreen(new GuiCrafting(inventory, worldObj)); + } + else if ("enchanting_table".equals(s)) + { + this.gameController.displayGuiScreen(new GuiEnchant(inventory, worldObj, guiOwner)); + } + else if ("anvil".equals(s)) + { + this.gameController.displayGuiScreen(new GuiRepair(inventory, worldObj)); + } + } + + public void displayGuiHorse(EntityHorse horse, InventoryPlayer inventory, IInventory horseInventory) { + this.gameController.displayGuiScreen(new GuiHorse(inventory, horseInventory, horse)); + } + + public void displayGuiMerchant(String title, InventoryPlayer inventory, World worldObj) { + this.gameController.displayGuiScreen(new GuiMerchant(inventory, title, worldObj)); + } + + public void displayGuiSign(BlockPos pos, String[] text) { + this.gameController.displayGuiScreen(new GuiSign(pos, text)); + } + + public void closeGui() { + this.gameController.displayGuiScreen(null); + } } diff --git a/client/src/main/java/client/renderer/ActiveRenderInfo.java b/client/src/client/renderer/ActiveRenderInfo.java similarity index 99% rename from client/src/main/java/client/renderer/ActiveRenderInfo.java rename to client/src/client/renderer/ActiveRenderInfo.java index a8e79b2..653eff6 100755 --- a/client/src/main/java/client/renderer/ActiveRenderInfo.java +++ b/client/src/client/renderer/ActiveRenderInfo.java @@ -8,7 +8,7 @@ import java.nio.IntBuffer; import org.lwjgl.opengl.GL11; import common.block.Block; -import common.block.liquid.BlockLiquid; +import common.block.BlockLiquid; import common.entity.Entity; import common.entity.npc.EntityNPC; import common.util.BlockPos; diff --git a/client/src/main/java/client/renderer/BlockRenderer.java b/client/src/client/renderer/BlockRenderer.java similarity index 98% rename from client/src/main/java/client/renderer/BlockRenderer.java rename to client/src/client/renderer/BlockRenderer.java index f0f7871..0288aaf 100755 --- a/client/src/main/java/client/renderer/BlockRenderer.java +++ b/client/src/client/renderer/BlockRenderer.java @@ -15,12 +15,12 @@ import client.renderer.texture.TextureAtlasSprite; import client.renderer.texture.TextureMap; import client.renderer.tileentity.TileEntityItemStackRenderer; import common.block.Block; -import common.block.Material; -import common.block.liquid.BlockLiquid; +import common.block.BlockLiquid; import common.collect.Maps; import common.init.BlockRegistry; import common.init.FluidRegistry; import common.item.ItemStack; +import common.material.Material; import common.util.BlockPos; import common.util.ExtMath; import common.util.Facing; @@ -189,7 +189,7 @@ public class BlockRenderer for (Facing enumfacing : Facing.values()) { - List list = modelIn.getFace(enumfacing); + List list = modelIn.getFaceQuads(enumfacing); if (!list.isEmpty()) { @@ -204,7 +204,7 @@ public class BlockRenderer } } - List list1 = modelIn.getQuads(); + List list1 = modelIn.getGeneralQuads(); if (list1.size() > 0) { @@ -348,10 +348,10 @@ public class BlockRenderer { for (Facing enumfacing : Facing.values()) { - this.renderModelBrightnessColorQuads(p_178262_2_, red, green, blue, bakedModel.getFace(enumfacing)); + this.renderModelBrightnessColorQuads(p_178262_2_, red, green, blue, bakedModel.getFaceQuads(enumfacing)); } - this.renderModelBrightnessColorQuads(p_178262_2_, red, green, blue, bakedModel.getQuads()); + this.renderModelBrightnessColorQuads(p_178262_2_, red, green, blue, bakedModel.getGeneralQuads()); } private void renderModelBrightness(IBakedModel model, State p_178266_2_, float brightness, boolean p_178266_4_) @@ -408,7 +408,7 @@ public class BlockRenderer TextureMap texturemap = Client.CLIENT.getTextureMapBlocks(); for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { BlockLiquid block = FluidRegistry.getStaticBlock(z); - String name = BlockRegistry.getNameFromBlock(block).toString(); + String name = BlockRegistry.REGISTRY.getNameForObject(block).toString(); TextureAtlasSprite[] sprites = new TextureAtlasSprite[] {texturemap.getAtlasSprite("blocks/" + name + "_still"), texturemap.getAtlasSprite("blocks/" + name + "_flow")}; this.fluids.put(FluidRegistry.getFluidBlock(z), sprites); this.fluids.put(block, sprites); diff --git a/client/src/main/java/client/renderer/DefaultVertexFormats.java b/client/src/client/renderer/DefaultVertexFormats.java similarity index 100% rename from client/src/main/java/client/renderer/DefaultVertexFormats.java rename to client/src/client/renderer/DefaultVertexFormats.java diff --git a/client/src/main/java/client/renderer/Drawing.java b/client/src/client/renderer/Drawing.java similarity index 91% rename from client/src/main/java/client/renderer/Drawing.java rename to client/src/client/renderer/Drawing.java index 1337d9b..16c9962 100644 --- a/client/src/main/java/client/renderer/Drawing.java +++ b/client/src/client/renderer/Drawing.java @@ -497,28 +497,6 @@ public abstract class Drawing { drawGradient(x + 2, y + 2, w - 4, h - 4, top, bottom); } - public static void drawRect(int x, int y, int w, int h, int color, int topleft, int btmright) { - int corner = Util.mixColor(topleft, btmright); - drawRect(x, y, w - 1, 1, topleft); - drawRect(x, y + 1, 1, h - 1, topleft); - drawRect(x + w - 1, y + 1, 1, 1, corner); - drawRect(x, y + h - 1, 1, 1, corner); - drawRect(x + w - 1, y + 1, 1, h - 1, btmright); - drawRect(x + 1, y + h - 1, w - 2, 1, btmright); - drawRect(x + 1, y + 1, w - 2, h - 2, color); - } - - public static void drawGradient(int x, int y, int w, int h, int top, int bottom, int topleft, int btmright) { - int corner = Util.mixColor(topleft, btmright); - drawRect(x, y, w - 1, 1, topleft); - drawRect(x, y + 1, 1, h - 1, topleft); - drawRect(x + w - 1, y + 1, 1, 1, corner); - drawRect(x, y + h - 1, 1, 1, corner); - drawRect(x + w - 1, y + 1, 1, h - 1, btmright); - drawRect(x + 1, y + h - 1, w - 2, 1, btmright); - drawGradient(x + 1, y + 1, w - 2, h - 2, top, bottom); - } - public static int getWidth(String str) { return getSize(str).xpos; } @@ -529,8 +507,8 @@ public abstract class Drawing { public static void drawTextbox(String str, int x, int y, int back) { Vec2i size = getSize(str); - drawRect(x, y, size.xpos + 4, size.ypos + 2, back); - drawText(str, x + 2, y + 1, 0xffffffff); + drawRect(x, y, size.xpos + 4, size.ypos, back); + drawText(str, x + 2, y, 0xffffffff); } public static void drawTextboxRight(String str, int x, int y, int back) { @@ -566,24 +544,28 @@ public abstract class Drawing { } public static void drawScaled(Client gm, String texture) { - drawScaled(gm, texture, 0, 0, gm.fb_x, gm.fb_y, 0xffffffff); + drawScaled(gm, texture, 0, 0, gm.fb_x, gm.fb_y); } - public static void drawScaled(Client gm, String texture, int x, int y, int width, int height, int color) { + public static void drawScaled(Client gm, String texture, double x, double y, double width, double height) { GlState.enableTexture2D(); GlState.disableLighting(); GlState.disableFog(); RenderBuffer buf = Tessellator.getBuffer(); gm.getTextureManager().bindTexture(texture); - GlState.color(color); + GlState.color(1.0F, 1.0F, 1.0F, 1.0F); double scale = 32.0; - buf.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX); - buf.pos((double)x, (double)y + (double)height, 0.0D).tex(0.0D, (double)height / scale).endVertex(); - buf.pos((double)x + (double)width, (double)y + (double)height, 0.0D).tex((double)width / scale, (double)height / scale).endVertex(); - buf.pos((double)x + (double)width, (double)y, 0.0D).tex((double)width / scale, 0.0).endVertex(); - buf.pos((double)x, (double)y, 0.0D).tex(0.0D, 0.0).endVertex(); + buf.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + buf.pos(x, y + height, 0.0D).tex(0.0D, height / scale) + .color(64, 64, 64, 255).endVertex(); + buf.pos(x + width, y + height, 0.0D) + .tex(width / scale, height / scale) + .color(64, 64, 64, 255).endVertex(); + buf.pos(x + width, y, 0.0D).tex(width / scale, 0.0) + .color(64, 64, 64, 255).endVertex(); + buf.pos(x, y, 0.0D).tex(0.0D, 0.0) + .color(64, 64, 64, 255).endVertex(); Tessellator.draw(); GlState.disableTexture2D(); - GlState.color(1.0F, 1.0F, 1.0F, 1.0F); } } diff --git a/client/src/main/java/client/renderer/EntityRenderer.java b/client/src/client/renderer/EntityRenderer.java similarity index 97% rename from client/src/main/java/client/renderer/EntityRenderer.java rename to client/src/client/renderer/EntityRenderer.java index 71968c7..36a3002 100755 --- a/client/src/main/java/client/renderer/EntityRenderer.java +++ b/client/src/client/renderer/EntityRenderer.java @@ -14,16 +14,14 @@ import client.renderer.particle.EffectRenderer; import client.renderer.texture.DynamicTexture; import client.renderer.texture.TextureMap; import client.world.WorldClient; -import common.biome.Biome; import common.block.Block; -import common.block.Material; import common.entity.Entity; import common.entity.npc.EntityNPC; import common.entity.types.EntityAnimal; import common.entity.types.EntityLiving; -import common.init.Blocks; import common.init.Items; import common.init.SoundEvent; +import common.material.Material; import common.model.BlockLayer; import common.model.ParticleType; import common.potion.Potion; @@ -590,7 +588,7 @@ public class EntityRenderer { // SKC.glScaled(this.cameraZoom, this.cameraZoom, 1.0D); // } - Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * SQRT_2); + Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * SQRT_2); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); @@ -668,7 +666,7 @@ public class EntityRenderer { // SKC.glTranslatef((float)(-(xOffset * 2 - 1)) * f, 0.0F, 0.0F); // } - Project.gluPerspective(this.getFOVModifier(partialTicks, false), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * 2.0F); + Project.gluPerspective(this.getFOVModifier(partialTicks, false), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * 2.0F); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); @@ -970,12 +968,12 @@ public class EntityRenderer { this.setupFog(-1, partialTicks); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); - Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * 2.0F); + Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * 2.0F); GL11.glMatrixMode(GL11.GL_MODELVIEW); renderglobal.renderSky(partialTicks); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); - Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * SQRT_2); + Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * SQRT_2); GL11.glMatrixMode(GL11.GL_MODELVIEW); } @@ -1092,7 +1090,7 @@ public class EntityRenderer { { GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); - Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * 4.0F); + Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * 4.0F); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); this.setupFog(0, partialTicks); @@ -1103,7 +1101,7 @@ public class EntityRenderer { GL11.glPopMatrix(); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); - Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * SQRT_2); + Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * SQRT_2); GL11.glMatrixMode(GL11.GL_MODELVIEW); } } @@ -1144,18 +1142,17 @@ public class EntityRenderer { for (int l = 0; l < k; ++l) { - BlockPos blockpos1 = world.getPrecipitationHeight(blockpos.add(this.random.zrange(i) - this.random.zrange(i), 0, this.random.zrange(i) - this.random.zrange(i))); - Biome biomegenbase = world.getBiomeGenForCoords(blockpos1); + BlockPos blockpos1 = world.getPrecipitationHeight(blockpos.add(this.random.zrange(i) - this.random.zrange(i), 0, this.random.zrange(i) - this.random.zrange(i)), blockpos.getY() + 48, 64); BlockPos blockpos2 = blockpos1.down(); Block block = world.getState(blockpos2).getBlock(); - float temp = World.ABSOLUTE_ZERO + world.getTempOffset() + biomegenbase.getTemperature(blockpos1); + float temp = 10.0f; // world.getTemperatureC(blockpos1); TODO: fix particles if (blockpos1.getY() <= blockpos.getY() + i && blockpos1.getY() >= blockpos.getY() - i && /* biomegenbase.canRain() && */ temp > 0.0F) { double d3 = this.random.doublev(); double d4 = this.random.doublev(); - if (temp >= 194.0f || block.getMaterial() == Material.LAVA) + if (temp >= 194.0f || block.getMaterial() == Material.lava) { if(temp >= 194.0f) { ++n; @@ -1169,7 +1166,7 @@ public class EntityRenderer { if(temp < 194.0f || this.random.chance(5)) this.gm.world.spawnParticle(temp >= 194.0f && this.random.chance(10) ? ParticleType.LAVA : ParticleType.SMOKE_NORMAL, (double)blockpos1.getX() + d3, (double)((float)blockpos1.getY() + 0.1F) - block.getBlockBoundsMinY(), (double)blockpos1.getZ() + d4, 0.0D, 0.0D, 0.0D); } - else if (block != Blocks.air) + else if (block.getMaterial() != Material.air) { block.setBlockBoundsBasedOnState(world, blockpos2); ++j; @@ -1190,7 +1187,7 @@ public class EntityRenderer { { this.rainSoundCounter = 0; - if (d1 > (double)(blockpos.getY() + 1) && world.getPrecipitationHeight(blockpos).getY() > ExtMath.floorf((float)blockpos.getY())) + if (d1 > (double)(blockpos.getY() + 1) && world.getPrecipitationHeight(blockpos, blockpos.getY() + 46, 48).getY() > ExtMath.floorf((float)blockpos.getY())) { this.gm.world.playSound(d0, d1, d2, n >= j ? this.pickMoltenSound() : SoundEvent.RAIN, n >= j ? 0.2f : 0.1F); } @@ -1254,11 +1251,10 @@ public class EntityRenderer { double d3 = (double)this.rainXCoords[i2] * 0.5D; double d4 = (double)this.rainYCoords[i2] * 0.5D; blockpos$mutableblockpos.set(l1, 0, k1); - Biome biomegenbase = world.getBiomeGenForCoords(blockpos$mutableblockpos); // if (biomegenbase.canRain() || biomegenbase.isSnowyBiome()) // { - int j2 = world.getPrecipitationHeight(blockpos$mutableblockpos).getY(); + int j2 = world.getPrecipitationHeight(blockpos$mutableblockpos, ExtMath.floord(d1) + 48, 64).getY(); int k2 = j - i1; int l2 = j + i1; @@ -1283,7 +1279,7 @@ public class EntityRenderer { { this.random.setSeed((long)(l1 * l1 * 3121 + l1 * 45238971 ^ k1 * k1 * 418711 + k1 * 13761)); blockpos$mutableblockpos.set(l1, k2, k1); - float f2 = World.ABSOLUTE_ZERO + world.getTempOffset() + biomegenbase.getTemperature(blockpos$mutableblockpos); + float f2 = 10.0f; // world.getTemperatureC(blockpos$mutableblockpos); TODO: fix particles if(f2 >= 194.0f) { @@ -1315,14 +1311,14 @@ public class EntityRenderer { } else if (/* world.getBiomeGenerator().getTemperatureAtHeight( */ f2 /* , j2) */ > 0.0F) { - if (mode != (f2 <= 5.0f ? 3 : 0)) + if (mode != 0) { if (mode >= 0) { Tessellator.draw(); } - mode = f2 <= 5.0f ? 3 : 0; + mode = 0; this.gm.getTextureManager().bindTexture(f2 <= 5.0f ? locationHailPng : locationRainPng); worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.PARTICLE_POSITION_TEX_COLOR_LMAP); } diff --git a/client/src/main/java/client/renderer/Frustum.java b/client/src/client/renderer/Frustum.java similarity index 100% rename from client/src/main/java/client/renderer/Frustum.java rename to client/src/client/renderer/Frustum.java diff --git a/client/src/main/java/client/renderer/GlState.java b/client/src/client/renderer/GlState.java similarity index 100% rename from client/src/main/java/client/renderer/GlState.java rename to client/src/client/renderer/GlState.java diff --git a/client/src/main/java/client/renderer/ItemModelMesher.java b/client/src/client/renderer/ItemModelMesher.java similarity index 90% rename from client/src/main/java/client/renderer/ItemModelMesher.java rename to client/src/client/renderer/ItemModelMesher.java index 619016b..b242df1 100755 --- a/client/src/main/java/client/renderer/ItemModelMesher.java +++ b/client/src/client/renderer/ItemModelMesher.java @@ -37,7 +37,7 @@ public class ItemModelMesher public TextureAtlasSprite getParticleIcon(Item item, int meta) { - return this.getItemModel(new ItemStack(item, 1, meta)).getBaseTexture(); + return this.getItemModel(new ItemStack(item, 1, meta)).getParticleTexture(); } public IBakedModel getItemModel(ItemStack stack) @@ -83,13 +83,13 @@ public class ItemModelMesher // public void registerItem(Item itm, int subType, String identifier) // { // this.register(itm, subType, new ResourceLocation(identifier, "inventory")); -//// String id = ItemRegistry.getNameFromItem(itm).toString(); +//// String id = ItemRegistry.REGISTRY.getNameForObject(itm).toString(); //// if(id.equals(identifier)) { ////// throw new IllegalArgumentException("Duplikat: " + identifier); -//// Log.DATA.info("MATCHING: " + ItemRegistry.getNameFromItem(itm) + ":" + subType); +//// Log.DATA.info("MATCHING: " + ItemRegistry.REGISTRY.getNameForObject(itm) + ":" + subType); //// } //// else { -//// Log.DATA.info("MISMATCH: " + ItemRegistry.getNameFromItem(itm) + ":" + subType + ": " + identifier); +//// Log.DATA.info("MISMATCH: " + ItemRegistry.REGISTRY.getNameForObject(itm) + ":" + subType + ": " + identifier); //// } // } @@ -124,7 +124,7 @@ public class ItemModelMesher for(ItemStack stack : stacks) { this.simpleShapesCache.put(this.getIndex(item, stack.getMetadata()), this.modelManager.getModel("item/" + - ItemRegistry.getNameFromItem(item).toString() + "#" + stack.getMetadata() + '#' + "inventory")); + ItemRegistry.REGISTRY.getNameForObject(item).toString() + "#" + stack.getMetadata() + '#' + "inventory")); } stacks.clear(); } diff --git a/client/src/main/java/client/renderer/ItemRenderer.java b/client/src/client/renderer/ItemRenderer.java similarity index 100% rename from client/src/main/java/client/renderer/ItemRenderer.java rename to client/src/client/renderer/ItemRenderer.java diff --git a/client/src/main/java/client/renderer/Project.java b/client/src/client/renderer/Project.java similarity index 100% rename from client/src/main/java/client/renderer/Project.java rename to client/src/client/renderer/Project.java diff --git a/client/src/main/java/client/renderer/RegionRenderCache.java b/client/src/client/renderer/RegionRenderCache.java similarity index 54% rename from client/src/main/java/client/renderer/RegionRenderCache.java rename to client/src/client/renderer/RegionRenderCache.java index d2cba9e..4ea9417 100755 --- a/client/src/main/java/client/renderer/RegionRenderCache.java +++ b/client/src/client/renderer/RegionRenderCache.java @@ -2,62 +2,46 @@ package client.renderer; import java.util.Arrays; -import client.world.ChunkClient; -import client.world.WorldClient; -import common.biome.Biome; import common.init.Blocks; import common.tileentity.TileEntity; import common.util.BlockPos; import common.util.Facing; import common.util.Vec3i; +import common.world.Chunk; +import common.world.ChunkCache; import common.world.IWorldAccess; -import common.world.LightType; import common.world.State; import common.world.World; -public class RegionRenderCache implements IWorldAccess +public class RegionRenderCache extends ChunkCache implements IWorldAccess { private static final State DEFAULT_STATE = Blocks.air.getState(); - - private final int xPos; - private final int zPos; - private final ChunkClient[][] chunks; - private final World world; + + private final World worldObj; private final BlockPos position; private final boolean empty; private int[] combinedLights; private State[] blockStates; - public RegionRenderCache(WorldClient world, BlockPos from, BlockPos to, int sub) + public RegionRenderCache(World worldIn, BlockPos posFromIn, BlockPos posToIn, int subIn) { - this.world = world; - this.xPos = from.getX() - sub >> 4; - this.zPos = from.getZ() - sub >> 4; - int x2 = to.getX() + sub >> 4; - int z2 = to.getZ() + sub >> 4; - this.chunks = new ChunkClient[x2 - this.xPos + 1][z2 - this.zPos + 1]; - for (int x = this.xPos; x <= x2; ++x) - { - for (int z = this.zPos; z <= z2; ++z) - { - this.chunks[x - this.xPos][z - this.zPos] = world.getChunk(x, z); - } - } + super(worldIn, posFromIn, posToIn, subIn); + this.worldObj = worldIn; boolean empty = true; - for (int x = from.getX() >> 4; x <= to.getX() >> 4; ++x) + for (int i1 = posFromIn.getX() >> 4; i1 <= posToIn.getX() >> 4; ++i1) { - for (int z = from.getZ() >> 4; z <= to.getZ() >> 4; ++z) + for (int j1 = posFromIn.getZ() >> 4; j1 <= posToIn.getZ() >> 4; ++j1) { - ChunkClient chunk = this.chunks[x - this.xPos][z - this.zPos]; + Chunk chunk = this.chunkArray[i1 - this.chunkX][j1 - this.chunkZ]; - if (chunk != null && !chunk.isEmpty(from.getY(), to.getY())) + if (chunk != null && !chunk.isEmpty(posFromIn.getY(), posToIn.getY())) { empty = false; } } } this.empty = empty; - this.position = from.subtract(new Vec3i(sub, sub, sub)); + this.position = posFromIn.subtract(new Vec3i(subIn, subIn, subIn)); int i = 16000; this.combinedLights = new int[16000]; Arrays.fill((int[])this.combinedLights, (int) - 1); @@ -66,9 +50,9 @@ public class RegionRenderCache implements IWorldAccess public TileEntity getTileEntity(BlockPos pos) { - int i = (pos.getX() >> 4) - this.xPos; - int j = (pos.getZ() >> 4) - this.zPos; - return this.chunks[i][j].getTileEntity(pos, TileEntity.EnumCreateEntityType.QUEUED); + int i = (pos.getX() >> 4) - this.chunkX; + int j = (pos.getZ() >> 4) - this.chunkZ; + return this.chunkArray[i][j].getTileEntity(pos, TileEntity.EnumCreateEntityType.QUEUED); } public int getCombinedLight(BlockPos pos, int lightValue) @@ -101,11 +85,11 @@ public class RegionRenderCache implements IWorldAccess private State getBlockStateRaw(BlockPos pos) { - if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) + if (pos.getY() >= 0 && pos.getY() < 512) { - int i = (pos.getX() >> 4) - this.xPos; - int j = (pos.getZ() >> 4) - this.zPos; - return this.chunks[i][j].getState(pos); + int i = (pos.getX() >> 4) - this.chunkX; + int j = (pos.getZ() >> 4) - this.chunkZ; + return this.chunkArray[i][j].getState(pos); } else { @@ -128,29 +112,19 @@ public class RegionRenderCache implements IWorldAccess public int getLight(BlockPos pos, int lightValue) { - int i = this.getLightForExt(LightType.SKY, pos); - int j = this.getLightForExt(LightType.BLOCK, pos); + int j = this.getLightForExt(pos); if (j < lightValue) { j = lightValue; } - return i << 20 | j << 4; + return 15 << 20 | j << 4; } - - public Biome getBiomeGenForCoords(BlockPos pos) + + private int getLightForExt(BlockPos pos) { - return this.world.getBiomeGenForCoords(pos); - } - - private int getLightForExt(LightType p_175629_1_, BlockPos pos) - { - if (p_175629_1_ == LightType.SKY && this.world.dimension.hasNoLight()) - { - return 0; - } - else if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) + if (pos.getY() >= 0 && pos.getY() < 512) { if (this.getState(pos).getBlock().getSumBrightness()) { @@ -158,7 +132,7 @@ public class RegionRenderCache implements IWorldAccess for (Facing enumfacing : Facing.values()) { - int k = this.getLightFor(p_175629_1_, pos.offset(enumfacing)); + int k = this.getLightFor(pos.offset(enumfacing)); if (k > l) { @@ -175,14 +149,14 @@ public class RegionRenderCache implements IWorldAccess } else { - int i = (pos.getX() >> 4) - this.xPos; - int j = (pos.getZ() >> 4) - this.zPos; - return this.chunks[i][j].getLight(p_175629_1_, pos); + int i = (pos.getX() >> 4) - this.chunkX; + int j = (pos.getZ() >> 4) - this.chunkZ; + return this.chunkArray[i][j].getLight(pos); } } else { - return p_175629_1_.defValue; + return 0; } } @@ -192,20 +166,20 @@ public class RegionRenderCache implements IWorldAccess // */ // public boolean isAirBlock(BlockPos pos) // { -// return this.getBlockState(pos).getBlock() == Blocks.air; +// return this.getBlockState(pos).getBlock().getMaterial() == Material.air; // } - public int getLightFor(LightType p_175628_1_, BlockPos pos) + public int getLightFor(BlockPos pos) { - if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) + if (pos.getY() >= 0 && pos.getY() < 512) { - int i = (pos.getX() >> 4) - this.xPos; - int j = (pos.getZ() >> 4) - this.zPos; - return this.chunks[i][j].getLight(p_175628_1_, pos); + int i = (pos.getX() >> 4) - this.chunkX; + int j = (pos.getZ() >> 4) - this.chunkZ; + return this.chunkArray[i][j].getLight(pos); } else { - return p_175628_1_.defValue; + return 0; } } diff --git a/client/src/main/java/client/renderer/RegionRenderCacheBuilder.java b/client/src/client/renderer/RegionRenderCacheBuilder.java similarity index 100% rename from client/src/main/java/client/renderer/RegionRenderCacheBuilder.java rename to client/src/client/renderer/RegionRenderCacheBuilder.java diff --git a/client/src/main/java/client/renderer/RenderBuffer.java b/client/src/client/renderer/RenderBuffer.java similarity index 97% rename from client/src/main/java/client/renderer/RenderBuffer.java rename to client/src/client/renderer/RenderBuffer.java index ceaa45a..b5cb077 100755 --- a/client/src/main/java/client/renderer/RenderBuffer.java +++ b/client/src/client/renderer/RenderBuffer.java @@ -46,7 +46,7 @@ public class RenderBuffer int i = this.byteBuffer.capacity(); int j = i % 2097152; int k = j + (((this.rawIntBuffer.position() + p_181670_1_) * 4 - j) / 2097152 + 1) * 2097152; - Log.RENDER.warn("Musste Puffer vergrößern: Alte Größe " + i + " Bytes, neue Größe " + k + " Bytes."); + Log.JNI.warn("Musste Puffer vergrößern: Alte Größe " + i + " Bytes, neue Größe " + k + " Bytes."); int l = this.rawIntBuffer.position(); ByteBuffer bytebuffer = ByteBuffer.allocateDirect(k).order(ByteOrder.nativeOrder()); this.byteBuffer.position(0); @@ -196,7 +196,7 @@ public class RenderBuffer { int i = this.vertexCount * this.vertexFormat.getNextOffset() + this.vertexFormat.getOffset(this.vertexFormatIndex); - switch (this.vertexFormatElement.type()) + switch (this.vertexFormatElement.getType()) { case FLOAT: this.byteBuffer.putFloat(i, (float)u); @@ -229,7 +229,7 @@ public class RenderBuffer { int i = this.vertexCount * this.vertexFormat.getNextOffset() + this.vertexFormat.getOffset(this.vertexFormatIndex); - switch (this.vertexFormatElement.type()) + switch (this.vertexFormatElement.getType()) { case FLOAT: this.byteBuffer.putFloat(i, (float)p_181671_1_); @@ -381,7 +381,7 @@ public class RenderBuffer { int i = this.vertexCount * this.vertexFormat.getNextOffset() + this.vertexFormat.getOffset(this.vertexFormatIndex); - switch (this.vertexFormatElement.type()) + switch (this.vertexFormatElement.getType()) { case FLOAT: this.byteBuffer.putFloat(i, (float)red / 255.0F); @@ -447,7 +447,7 @@ public class RenderBuffer { int i = this.vertexCount * this.vertexFormat.getNextOffset() + this.vertexFormat.getOffset(this.vertexFormatIndex); - switch (this.vertexFormatElement.type()) + switch (this.vertexFormatElement.getType()) { case FLOAT: this.byteBuffer.putFloat(i, (float)(x + this.xOffset)); @@ -500,7 +500,7 @@ public class RenderBuffer this.vertexFormatIndex %= this.vertexFormat.getElementCount(); this.vertexFormatElement = this.vertexFormat.getElement(this.vertexFormatIndex); - if (this.vertexFormatElement.usage() == VertexFormatElement.EnumUsage.PADDING) + if (this.vertexFormatElement.getUsage() == VertexFormatElement.EnumUsage.PADDING) { this.nextVertexFormatIndex(); } @@ -510,7 +510,7 @@ public class RenderBuffer { int i = this.vertexCount * this.vertexFormat.getNextOffset() + this.vertexFormat.getOffset(this.vertexFormatIndex); - switch (this.vertexFormatElement.type()) + switch (this.vertexFormatElement.getType()) { case FLOAT: this.byteBuffer.putFloat(i, p_181663_1_); diff --git a/client/src/main/java/client/renderer/RenderGlobal.java b/client/src/client/renderer/RenderGlobal.java similarity index 96% rename from client/src/main/java/client/renderer/RenderGlobal.java rename to client/src/client/renderer/RenderGlobal.java index e5e257c..f1ad4b3 100755 --- a/client/src/main/java/client/renderer/RenderGlobal.java +++ b/client/src/client/renderer/RenderGlobal.java @@ -25,11 +25,11 @@ import client.renderer.texture.TextureAtlasSprite; import client.renderer.texture.TextureManager; import client.renderer.texture.TextureMap; import client.renderer.tileentity.TileEntityRendererDispatcher; -import client.world.ChunkClient; import client.world.WorldClient; import common.block.Block; -import common.block.tech.BlockChest; -import common.block.tile.BlockSign; +import common.block.BlockChest; +import common.block.BlockSign; +import common.block.BlockSkull; import common.collect.Lists; import common.collect.Maps; import common.collect.Sets; @@ -37,7 +37,7 @@ import common.entity.Entity; import common.entity.npc.EntityNPC; import common.entity.projectile.EntityBox; import common.entity.types.EntityLiving; -import common.init.Blocks; +import common.material.Material; import common.model.BlockLayer; import common.rng.Random; import common.sound.Sound; @@ -45,14 +45,14 @@ import common.tileentity.TileEntity; import common.tileentity.TileEntityChest; import common.util.BlockPos; import common.util.BoundingBox; -import common.util.InheritanceMultiMap; +import common.util.ClassInheritanceMultiMap; import common.util.ExtMath; import common.util.Facing; import common.util.HitPosition; import common.util.Vec3; import common.util.Vector3f; +import common.world.Chunk; import common.world.State; -import common.world.World; public class RenderGlobal { @@ -463,7 +463,7 @@ public class RenderGlobal if (entity != null) { - this.viewFrustum.updateChunkPositions(entity.posX, entity.posY, entity.posZ); + this.viewFrustum.updateChunkPositions(entity.posX, entity.posZ); } } @@ -603,8 +603,8 @@ public class RenderGlobal for (RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation : this.renderInfos) { - ChunkClient chunk = this.theWorld.getChunk(renderglobal$containerlocalrenderinformation.renderChunk.getPosition()); - InheritanceMultiMap classinheritancemultimap = chunk.getEntities()[ExtMath.clampi(renderglobal$containerlocalrenderinformation.renderChunk.getPosition().getY() / 16, 0, 31)]; + Chunk chunk = this.theWorld.getChunk(renderglobal$containerlocalrenderinformation.renderChunk.getPosition()); + ClassInheritanceMultiMap classinheritancemultimap = chunk.getEntities()[renderglobal$containerlocalrenderinformation.renderChunk.getPosition().getY() / 16]; if (!classinheritancemultimap.isEmpty()) { @@ -632,7 +632,7 @@ public class RenderGlobal // boolean flag3 = this.gm.getRenderViewEntity() instanceof EntityLivingBase ? ((EntityLivingBase)this.gm.getRenderViewEntity()).isPlayerSleeping() : false; - if (entity2.posY < (double)(-World.MAX_SIZE_Y) || entity2.posY >= (double)World.MAX_SIZE_Y || this.theWorld.isBlockLoaded(new BlockPos(entity2))) + if (entity2.posY < 0.0D || entity2.posY >= 512.0D || this.theWorld.isBlockLoaded(new BlockPos(entity2))) { if((entity2 != this.gm.getRenderViewEntity() || this.gm.thirdPersonView != 0 /* || flag3 */)) { ++this.countEntitiesRendered; @@ -701,7 +701,7 @@ public class RenderGlobal Block block = this.theWorld.getState(blockpos).getBlock(); - if (tileentity1 != null && (block instanceof BlockChest || block instanceof BlockSign)) + if (tileentity1 != null && (block instanceof BlockChest || /* block instanceof BlockWarpChest || */ block instanceof BlockSign || block instanceof BlockSkull)) { TileEntityRendererDispatcher.instance.renderTileEntity(tileentity1, partialTicks, destroyblockprogress.getPartialBlockDamage()); } @@ -751,7 +751,6 @@ public class RenderGlobal double d0 = viewEntity.posX - this.frustumUpdatePosX; double d1 = viewEntity.posY - this.frustumUpdatePosY; double d2 = viewEntity.posZ - this.frustumUpdatePosZ; - int prev = this.frustumUpdatePosChunkY; if (this.frustumUpdatePosChunkX != viewEntity.chunkCoordX || this.frustumUpdatePosChunkY != viewEntity.chunkCoordY || this.frustumUpdatePosChunkZ != viewEntity.chunkCoordZ || d0 * d0 + d1 * d1 + d2 * d2 > 16.0D) { @@ -761,7 +760,7 @@ public class RenderGlobal this.frustumUpdatePosChunkX = viewEntity.chunkCoordX; this.frustumUpdatePosChunkY = viewEntity.chunkCoordY; this.frustumUpdatePosChunkZ = viewEntity.chunkCoordZ; - this.viewFrustum.updateChunkPositions(viewEntity.posX, viewEntity.posY, viewEntity.posZ); + this.viewFrustum.updateChunkPositions(viewEntity.posX, viewEntity.posZ); } double d3 = viewEntity.lastTickPosX + (viewEntity.posX - viewEntity.lastTickPosX) * partialTicks; double d4 = viewEntity.lastTickPosY + (viewEntity.posY - viewEntity.lastTickPosY) * partialTicks; @@ -821,21 +820,18 @@ public class RenderGlobal else { // int i = blockpos1.getY() > 0 ? 248 : 8; -// int i = blockpos1.getY() > 0 ? 504 : 8; + int i = blockpos1.getY() > 0 ? 504 : 8; for (int j = -this.renderDistanceChunks; j <= this.renderDistanceChunks; ++j) { for (int k = -this.renderDistanceChunks; k <= this.renderDistanceChunks; ++k) { - for (int i = -this.renderDistanceChunks; i <= this.renderDistanceChunks; ++i) + RenderChunk renderchunk1 = this.viewFrustum.getRenderChunk(new BlockPos((j << 4) + 8, i, (k << 4) + 8)); + + if (renderchunk1 != null && Frustum.isInFrustum(renderchunk1.boundingBox)) { - RenderChunk renderchunk1 = this.viewFrustum.getRenderChunk(new BlockPos((j << 4) + 8, (i << 4) + 8, (k << 4) + 8)); - - if (renderchunk1 != null && Frustum.isInFrustum(renderchunk1.boundingBox)) - { - renderchunk1.setFrameIndex(frameCount); - queue.add(new RenderGlobal.ContainerLocalRenderInformation(renderchunk1, (Facing)null, 0)); - } + renderchunk1.setFrameIndex(frameCount); + queue.add(new RenderGlobal.ContainerLocalRenderInformation(renderchunk1, (Facing)null, 0)); } } } @@ -904,24 +900,6 @@ public class RenderGlobal } this.chunksToUpdate.addAll(set); - - if(prev != Integer.MIN_VALUE && viewEntity.chunkCoordY != prev) { - for (int j = -this.renderDistanceChunks; j <= this.renderDistanceChunks; ++j) - { - for (int k = -this.renderDistanceChunks; k <= this.renderDistanceChunks; ++k) - { - for (int i = -this.renderDistanceChunks; i <= this.renderDistanceChunks; ++i) - { - RenderChunk renderchunk1 = this.viewFrustum.getRenderChunk(new BlockPos((j << 4) + 8, (i << 4) + 8, (k << 4) + 8)); - - if (renderchunk1 != null) - { - renderchunk1.setNeedsUpdate(true); - } - } - } - } - } } private boolean isPositionInRenderChunk(BlockPos pos, RenderChunk renderChunkIn) @@ -934,7 +912,7 @@ public class RenderGlobal { VisGraph visgraph = new VisGraph(); BlockPos blockpos = new BlockPos(pos.getX() >> 4 << 4, pos.getY() >> 4 << 4, pos.getZ() >> 4 << 4); - ChunkClient chunk = this.theWorld.getChunk(blockpos); + Chunk chunk = this.theWorld.getChunk(blockpos); for (BlockPos.MutableBlockPos blockpos$mutableblockpos : BlockPos.getAllInBoxMutable(blockpos, blockpos.add(15, 15, 15))) { @@ -953,7 +931,7 @@ public class RenderGlobal private RenderChunk getRenderChunkOffset(BlockPos playerPos, RenderChunk renderChunkBase, Facing facing) { BlockPos blockpos = renderChunkBase.getBlockPosOffset16(facing); - return ExtMath.absi(playerPos.getX() - blockpos.getX()) > this.renderDistanceChunks * 16 ? null : (ExtMath.absi(playerPos.getY() - blockpos.getY()) <= this.renderDistanceChunks * 16 ? (ExtMath.absi(playerPos.getZ() - blockpos.getZ()) > this.renderDistanceChunks * 16 ? null : this.viewFrustum.getRenderChunk(blockpos)) : null); + return ExtMath.absi(playerPos.getX() - blockpos.getX()) > this.renderDistanceChunks * 16 ? null : (blockpos.getY() >= 0 && blockpos.getY() < 512 ? (ExtMath.absi(playerPos.getZ() - blockpos.getZ()) > this.renderDistanceChunks * 16 ? null : this.viewFrustum.getRenderChunk(blockpos)) : null); } protected Vector3f getViewVector(Entity entityIn, double partialTicks) @@ -1041,8 +1019,8 @@ public class RenderGlobal // { for (VertexFormatElement vertexformatelement : DefaultVertexFormats.BLOCK.getElements()) { - VertexFormatElement.EnumUsage vertexformatelement$enumusage = vertexformatelement.usage(); - int i = vertexformatelement.index(); + VertexFormatElement.EnumUsage vertexformatelement$enumusage = vertexformatelement.getUsage(); + int i = vertexformatelement.getIndex(); switch (vertexformatelement$enumusage) { @@ -1569,7 +1547,7 @@ public class RenderGlobal double d5 = (double)blockpos.getZ() - d2; Block block = this.theWorld.getState(blockpos).getBlock(); - if (!(block instanceof BlockChest) && !(block instanceof BlockSign)) + if (!(block instanceof BlockChest) && /* !(block instanceof BlockWarpChest) && */ !(block instanceof BlockSign) && !(block instanceof BlockSkull)) { if (d3 * d3 + d4 * d4 + d5 * d5 > 1024.0D) { @@ -1579,7 +1557,7 @@ public class RenderGlobal { State iblockstate = this.theWorld.getState(blockpos); - if (iblockstate.getBlock() != Blocks.air) + if (iblockstate.getBlock().getMaterial() != Material.air) { int i = destroyblockprogress.getPartialBlockDamage(); TextureAtlasSprite textureatlassprite = this.destroyBlockIcons[i]; @@ -1615,7 +1593,7 @@ public class RenderGlobal BlockPos blockpos = movingObjectPositionIn.block; Block block = this.theWorld.getState(blockpos).getBlock(); - if (block != Blocks.air) // && this.theWorld.getWorldBorder().contains(blockpos)) + if (block.getMaterial() != Material.air) // && this.theWorld.getWorldBorder().contains(blockpos)) { block.setBlockBoundsBasedOnState(this.theWorld, blockpos); double d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double)partialTicks; diff --git a/client/src/main/java/client/renderer/Tessellator.java b/client/src/client/renderer/Tessellator.java similarity index 83% rename from client/src/main/java/client/renderer/Tessellator.java rename to client/src/client/renderer/Tessellator.java index c7d69b9..014e658 100755 --- a/client/src/main/java/client/renderer/Tessellator.java +++ b/client/src/client/renderer/Tessellator.java @@ -28,27 +28,27 @@ public abstract class Tessellator for (int j = 0; j < list.size(); ++j) { VertexFormatElement vertexformatelement = (VertexFormatElement)list.get(j); - VertexFormatElement.EnumUsage vertexformatelement$enumusage = vertexformatelement.usage(); - int k = vertexformatelement.type().getGlConstant(); - int l = vertexformatelement.index(); + VertexFormatElement.EnumUsage vertexformatelement$enumusage = vertexformatelement.getUsage(); + int k = vertexformatelement.getType().getGlConstant(); + int l = vertexformatelement.getIndex(); bytebuffer.position(vertexformat.getOffset(j)); switch (vertexformatelement$enumusage) { case POSITION: - GL11.glVertexPointer(vertexformatelement.count(), k, i, bytebuffer); + GL11.glVertexPointer(vertexformatelement.getElementCount(), k, i, bytebuffer); GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY); break; case UV: GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + l); - GL11.glTexCoordPointer(vertexformatelement.count(), k, i, bytebuffer); + GL11.glTexCoordPointer(vertexformatelement.getElementCount(), k, i, bytebuffer); GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY); GL13.glClientActiveTexture(GL13.GL_TEXTURE0); break; case COLOR: - GL11.glColorPointer(vertexformatelement.count(), k, i, bytebuffer); + GL11.glColorPointer(vertexformatelement.getElementCount(), k, i, bytebuffer); GL11.glEnableClientState(GL11.GL_COLOR_ARRAY); break; @@ -64,8 +64,8 @@ public abstract class Tessellator for (int j1 = list.size(); i1 < j1; ++i1) { VertexFormatElement vertexformatelement1 = (VertexFormatElement)list.get(i1); - VertexFormatElement.EnumUsage vertexformatelement$enumusage1 = vertexformatelement1.usage(); - int k1 = vertexformatelement1.index(); + VertexFormatElement.EnumUsage vertexformatelement$enumusage1 = vertexformatelement1.getUsage(); + int k1 = vertexformatelement1.getIndex(); switch (vertexformatelement$enumusage1) { diff --git a/client/src/main/java/client/renderer/VertexBuffer.java b/client/src/client/renderer/VertexBuffer.java similarity index 100% rename from client/src/main/java/client/renderer/VertexBuffer.java rename to client/src/client/renderer/VertexBuffer.java diff --git a/client/src/main/java/client/renderer/VertexFormat.java b/client/src/client/renderer/VertexFormat.java similarity index 90% rename from client/src/main/java/client/renderer/VertexFormat.java rename to client/src/client/renderer/VertexFormat.java index 0ab4281..d8c6e93 100755 --- a/client/src/main/java/client/renderer/VertexFormat.java +++ b/client/src/client/renderer/VertexFormat.java @@ -51,9 +51,9 @@ public class VertexFormat public VertexFormat addElement(VertexFormatElement element) { - if (element.isPosition() && this.hasPosition()) + if (element.isPositionElement() && this.hasPosition()) { - Log.RENDER.warn("VertexFormat-Fehler: Versuche eine Position vom Typ VertexFormatElement hinzuzufügen, während eine bereits existiert, ignoriere."); + Log.JNI.warn("VertexFormat-Fehler: Versuche eine Position vom Typ VertexFormatElement hinzuzufügen, während eine bereits existiert, ignoriere."); return this; } else @@ -61,7 +61,7 @@ public class VertexFormat this.elements.add(element); this.offsets.add(Integer.valueOf(this.nextOffset)); - switch (element.usage()) + switch (element.getUsage()) { case NORMAL: this.normalElementOffset = this.nextOffset; @@ -72,10 +72,10 @@ public class VertexFormat break; case UV: - this.uvOffsetsById.add(element.index(), Integer.valueOf(this.nextOffset)); + this.uvOffsetsById.add(element.getIndex(), Integer.valueOf(this.nextOffset)); } - this.nextOffset += element.size(); + this.nextOffset += element.getSize(); return this; } } @@ -135,7 +135,7 @@ public class VertexFormat { VertexFormatElement vertexformatelement = (VertexFormatElement)this.elements.get(i); - if (vertexformatelement.isPosition()) + if (vertexformatelement.isPositionElement()) { return true; } diff --git a/client/src/client/renderer/VertexFormatElement.java b/client/src/client/renderer/VertexFormatElement.java new file mode 100755 index 0000000..4ff2116 --- /dev/null +++ b/client/src/client/renderer/VertexFormatElement.java @@ -0,0 +1,156 @@ +package client.renderer; + +import org.lwjgl.opengl.GL11; + +import common.log.Log; + +public class VertexFormatElement +{ + private final VertexFormatElement.EnumType type; + private final VertexFormatElement.EnumUsage usage; + private int index; + private int elementCount; + + public VertexFormatElement(int indexIn, VertexFormatElement.EnumType typeIn, VertexFormatElement.EnumUsage usageIn, int count) + { + if (!this.isValid(indexIn, usageIn)) + { + Log.JNI.warn("Mehrere Vertex-Elemente des gleichen Typs außer UVs sind nicht unterstützt. Erzwinge Typ UV."); + this.usage = VertexFormatElement.EnumUsage.UV; + } + else + { + this.usage = usageIn; + } + + this.type = typeIn; + this.index = indexIn; + this.elementCount = count; + } + + private final boolean isValid(int index, VertexFormatElement.EnumUsage usage) + { + return index == 0 || usage == VertexFormatElement.EnumUsage.UV; + } + + public final VertexFormatElement.EnumType getType() + { + return this.type; + } + + public final VertexFormatElement.EnumUsage getUsage() + { + return this.usage; + } + + public final int getElementCount() + { + return this.elementCount; + } + + public final int getIndex() + { + return this.index; + } + + public String toString() + { + return this.elementCount + "," + this.usage.getDisplayName() + "," + this.type.getDisplayName(); + } + + public final int getSize() + { + return this.type.getSize() * this.elementCount; + } + + public final boolean isPositionElement() + { + return this.usage == VertexFormatElement.EnumUsage.POSITION; + } + + public boolean equals(Object p_equals_1_) + { + if (this == p_equals_1_) + { + return true; + } + else if (p_equals_1_ != null && this.getClass() == p_equals_1_.getClass()) + { + VertexFormatElement vertexformatelement = (VertexFormatElement)p_equals_1_; + return this.elementCount != vertexformatelement.elementCount ? false : (this.index != vertexformatelement.index ? false : (this.type != vertexformatelement.type ? false : this.usage == vertexformatelement.usage)); + } + else + { + return false; + } + } + + public int hashCode() + { + int i = this.type.hashCode(); + i = 31 * i + this.usage.hashCode(); + i = 31 * i + this.index; + i = 31 * i + this.elementCount; + return i; + } + + public static enum EnumType + { + FLOAT(4, "Float", GL11.GL_FLOAT), + UBYTE(1, "Unsigned Byte", GL11.GL_UNSIGNED_BYTE), + BYTE(1, "Byte", GL11.GL_BYTE), + USHORT(2, "Unsigned Short", GL11.GL_UNSIGNED_SHORT), + SHORT(2, "Short", GL11.GL_SHORT), + UINT(4, "Unsigned Int", GL11.GL_UNSIGNED_INT), + INT(4, "Int", GL11.GL_INT); + + private final int size; + private final String displayName; + private final int glConstant; + + private EnumType(int sizeIn, String displayNameIn, int glConstantIn) + { + this.size = sizeIn; + this.displayName = displayNameIn; + this.glConstant = glConstantIn; + } + + public int getSize() + { + return this.size; + } + + public String getDisplayName() + { + return this.displayName; + } + + public int getGlConstant() + { + return this.glConstant; + } + } + + public static enum EnumUsage + { + POSITION("Position"), + NORMAL("Normal"), + COLOR("Vertex Color"), + UV("UV"), +// MATRIX("Bone Matrix"), +// BLEND_WEIGHT("Blend Weight"), + PADDING("Padding"); + + private final String displayName; + + private EnumUsage(String displayNameIn) + { + this.displayName = displayNameIn; + } + + public String getDisplayName() + { + return this.displayName; + } + } +} diff --git a/client/src/main/java/client/renderer/ViewFrustum.java b/client/src/client/renderer/ViewFrustum.java similarity index 85% rename from client/src/main/java/client/renderer/ViewFrustum.java rename to client/src/client/renderer/ViewFrustum.java index ede3e1c..df65bd6 100755 --- a/client/src/main/java/client/renderer/ViewFrustum.java +++ b/client/src/client/renderer/ViewFrustum.java @@ -1,14 +1,14 @@ package client.renderer; import client.renderer.chunk.RenderChunk; -import client.world.WorldClient; import common.util.BlockPos; import common.util.ExtMath; +import common.world.World; public class ViewFrustum { protected final RenderGlobal renderGlobal; - protected final WorldClient world; + protected final World world; protected int countChunksY; protected int countChunksX; protected int countChunksZ; @@ -18,7 +18,7 @@ public class ViewFrustum return i < 0 ? -((-i - 1) / 16) - 1 : i / 16; } - public ViewFrustum(WorldClient worldIn, int renderDistanceChunks, RenderGlobal p_i46246_3_) + public ViewFrustum(World worldIn, int renderDistanceChunks, RenderGlobal p_i46246_3_) { this.renderGlobal = p_i46246_3_; this.world = worldIn; @@ -58,14 +58,13 @@ public class ViewFrustum { int i = renderDistanceChunks * 2 + 1; this.countChunksX = i; - this.countChunksY = i; + this.countChunksY = 32; this.countChunksZ = i; } - public void updateChunkPositions(double viewEntityX, double viewEntityY, double viewEntityZ) + public void updateChunkPositions(double viewEntityX, double viewEntityZ) { int i = ExtMath.floord(viewEntityX) - 8; - int n = ExtMath.floord(viewEntityY) - 8; int j = ExtMath.floord(viewEntityZ) - 8; int k = this.countChunksX * 16; @@ -79,7 +78,7 @@ public class ViewFrustum for (int l1 = 0; l1 < this.countChunksY; ++l1) { - int i2 = this.func_178157_a(n, k, l1); + int i2 = l1 * 16; RenderChunk renderchunk = this.renderChunks[(j1 * this.countChunksY + l1) * this.countChunksX + l]; BlockPos blockpos = new BlockPos(i1, i2, k1); @@ -155,28 +154,28 @@ public class ViewFrustum int y = bucketInt(pos.getY()); int z = bucketInt(pos.getZ()); - x = x % this.countChunksX; - - if (x < 0) + if (y >= 0 && y < this.countChunksY) { - x += this.countChunksX; + x = x % this.countChunksX; + + if (x < 0) + { + x += this.countChunksX; + } + + z = z % this.countChunksZ; + + if (z < 0) + { + z += this.countChunksZ; + } + + int p = (z * this.countChunksY + y) * this.countChunksX + x; + return this.renderChunks[p]; } - - y = y % this.countChunksY; - - if (y < 0) + else { - y += this.countChunksY; + return null; } - - z = z % this.countChunksZ; - - if (z < 0) - { - z += this.countChunksZ; - } - - int p = (z * this.countChunksY + y) * this.countChunksX + x; - return this.renderChunks[p]; } } diff --git a/client/src/client/renderer/blockmodel/BakedModel.java b/client/src/client/renderer/blockmodel/BakedModel.java new file mode 100755 index 0000000..d383523 --- /dev/null +++ b/client/src/client/renderer/blockmodel/BakedModel.java @@ -0,0 +1,153 @@ +package client.renderer.blockmodel; + +import java.util.ArrayList; +import java.util.List; + +import client.renderer.texture.TextureAtlasSprite; +import common.collect.Lists; +import common.model.Transforms; +import common.util.Facing; + +public class BakedModel implements IBakedModel +{ + protected final List generalQuads; + protected final List> faceQuads; + protected final boolean ambientOcclusion; + protected final boolean gui3d; + protected final TextureAtlasSprite texture; + protected final Transforms cameraTransforms; + + public BakedModel(List generalQuadsIn, List> faceQuadsIn, boolean ambientOcclusionIn, boolean gui3dIn, TextureAtlasSprite textureIn, Transforms cameraTransformsIn) + { + this.generalQuads = generalQuadsIn; + this.faceQuads = faceQuadsIn; + this.ambientOcclusion = ambientOcclusionIn; + this.gui3d = gui3dIn; + this.texture = textureIn; + this.cameraTransforms = cameraTransformsIn; + } + + public List getFaceQuads(Facing facing) + { + return this.faceQuads.get(facing.ordinal()); + } + + public List getGeneralQuads() + { + return this.generalQuads; + } + + public boolean isAmbientOcclusion() + { + return this.ambientOcclusion; + } + + public boolean isGui3d() + { + return this.gui3d; + } + + public boolean isBuiltInRenderer() + { + return false; + } + + public TextureAtlasSprite getParticleTexture() + { + return this.texture; + } + + public Transforms getItemCameraTransforms() + { + return this.cameraTransforms; + } + + public static class Builder + { + private final List builderGeneralQuads; + private final List> builderFaceQuads; + private final boolean builderAmbientOcclusion; + private TextureAtlasSprite builderTexture; + private boolean builderGui3d; + private Transforms builderCameraTransforms; + + public Builder(ModelBlock model) + { + this(model.isAmbientOcclusion(), model.isGui3d(), model.getTransform()); + } + + public Builder(IBakedModel bakedModel, TextureAtlasSprite texture) + { + this(bakedModel.isAmbientOcclusion(), bakedModel.isGui3d(), bakedModel.getItemCameraTransforms()); + this.builderTexture = bakedModel.getParticleTexture(); + + for (Facing enumfacing : Facing.values()) + { + this.addFaceBreakingFours(bakedModel, texture, enumfacing); + } + + this.addGeneralBreakingFours(bakedModel, texture); + } + + private void addFaceBreakingFours(IBakedModel bakedModel, TextureAtlasSprite texture, Facing facing) + { + for (BakedQuad bakedquad : bakedModel.getFaceQuads(facing)) + { + this.addFaceQuad(facing, new BreakingFour(bakedquad, texture)); + } + } + + private void addGeneralBreakingFours(IBakedModel p_177647_1_, TextureAtlasSprite texture) + { + for (BakedQuad bakedquad : p_177647_1_.getGeneralQuads()) + { + this.addGeneralQuad(new BreakingFour(bakedquad, texture)); + } + } + + private Builder(boolean ambientOcclusion, boolean gui3d, Transforms cameraTransforms) + { + this.builderGeneralQuads = Lists.newArrayList(); + this.builderFaceQuads = new ArrayList>(6); + + for (Facing enumfacing : Facing.values()) + { + this.builderFaceQuads.add(Lists.newArrayList()); + } + + this.builderAmbientOcclusion = ambientOcclusion; + this.builderGui3d = gui3d; + this.builderCameraTransforms = cameraTransforms; + } + + public BakedModel.Builder addFaceQuad(Facing facing, BakedQuad quad) + { + ((List)this.builderFaceQuads.get(facing.ordinal())).add(quad); + return this; + } + + public BakedModel.Builder addGeneralQuad(BakedQuad quad) + { + this.builderGeneralQuads.add(quad); + return this; + } + + public BakedModel.Builder setTexture(TextureAtlasSprite texture) + { + this.builderTexture = texture; + return this; + } + + public BakedModel makeBakedModel() + { + if (this.builderTexture == null) + { + throw new RuntimeException("Missing particle!"); + } + else + { + return new BakedModel(this.builderGeneralQuads, this.builderFaceQuads, this.builderAmbientOcclusion, this.builderGui3d, this.builderTexture, this.builderCameraTransforms); + } + } + } +} diff --git a/client/src/main/java/client/renderer/blockmodel/BakedQuad.java b/client/src/client/renderer/blockmodel/BakedQuad.java similarity index 100% rename from client/src/main/java/client/renderer/blockmodel/BakedQuad.java rename to client/src/client/renderer/blockmodel/BakedQuad.java diff --git a/client/src/main/java/client/renderer/blockmodel/BlockFaceUV.java b/client/src/client/renderer/blockmodel/BlockFaceUV.java similarity index 100% rename from client/src/main/java/client/renderer/blockmodel/BlockFaceUV.java rename to client/src/client/renderer/blockmodel/BlockFaceUV.java diff --git a/client/src/main/java/client/renderer/blockmodel/BlockPart.java b/client/src/client/renderer/blockmodel/BlockPart.java similarity index 100% rename from client/src/main/java/client/renderer/blockmodel/BlockPart.java rename to client/src/client/renderer/blockmodel/BlockPart.java diff --git a/client/src/main/java/client/renderer/blockmodel/BlockPartFace.java b/client/src/client/renderer/blockmodel/BlockPartFace.java similarity index 100% rename from client/src/main/java/client/renderer/blockmodel/BlockPartFace.java rename to client/src/client/renderer/blockmodel/BlockPartFace.java diff --git a/client/src/main/java/client/renderer/blockmodel/BlockPartRotation.java b/client/src/client/renderer/blockmodel/BlockPartRotation.java similarity index 100% rename from client/src/main/java/client/renderer/blockmodel/BlockPartRotation.java rename to client/src/client/renderer/blockmodel/BlockPartRotation.java diff --git a/client/src/main/java/client/renderer/blockmodel/BreakingFour.java b/client/src/client/renderer/blockmodel/BreakingFour.java similarity index 100% rename from client/src/main/java/client/renderer/blockmodel/BreakingFour.java rename to client/src/client/renderer/blockmodel/BreakingFour.java diff --git a/client/src/client/renderer/blockmodel/BuiltInModel.java b/client/src/client/renderer/blockmodel/BuiltInModel.java new file mode 100755 index 0000000..802fcc9 --- /dev/null +++ b/client/src/client/renderer/blockmodel/BuiltInModel.java @@ -0,0 +1,52 @@ +package client.renderer.blockmodel; + +import java.util.List; + +import client.renderer.texture.TextureAtlasSprite; +import common.model.Transforms; +import common.util.Facing; + +public class BuiltInModel implements IBakedModel +{ + private Transforms cameraTransforms; + + public BuiltInModel(Transforms p_i46086_1_) + { + this.cameraTransforms = p_i46086_1_; + } + + public List getFaceQuads(Facing facing) + { + return null; + } + + public List getGeneralQuads() + { + return null; + } + + public boolean isAmbientOcclusion() + { + return false; + } + + public boolean isGui3d() + { + return true; + } + + public boolean isBuiltInRenderer() + { + return true; + } + + public TextureAtlasSprite getParticleTexture() + { + return null; + } + + public Transforms getItemCameraTransforms() + { + return this.cameraTransforms; + } +} diff --git a/client/src/main/java/client/renderer/blockmodel/FaceBakery.java b/client/src/client/renderer/blockmodel/FaceBakery.java similarity index 100% rename from client/src/main/java/client/renderer/blockmodel/FaceBakery.java rename to client/src/client/renderer/blockmodel/FaceBakery.java diff --git a/client/src/client/renderer/blockmodel/IBakedModel.java b/client/src/client/renderer/blockmodel/IBakedModel.java new file mode 100755 index 0000000..490f71b --- /dev/null +++ b/client/src/client/renderer/blockmodel/IBakedModel.java @@ -0,0 +1,24 @@ +package client.renderer.blockmodel; + +import java.util.List; + +import client.renderer.texture.TextureAtlasSprite; +import common.model.Transforms; +import common.util.Facing; + +public interface IBakedModel +{ + List getFaceQuads(Facing facing); + + List getGeneralQuads(); + + boolean isAmbientOcclusion(); + + boolean isGui3d(); + + boolean isBuiltInRenderer(); + + TextureAtlasSprite getParticleTexture(); + + Transforms getItemCameraTransforms(); +} diff --git a/client/src/main/java/client/renderer/blockmodel/ModelBakery.java b/client/src/client/renderer/blockmodel/ModelBakery.java similarity index 96% rename from client/src/main/java/client/renderer/blockmodel/ModelBakery.java rename to client/src/client/renderer/blockmodel/ModelBakery.java index 3bd370d..5b58a45 100755 --- a/client/src/main/java/client/renderer/blockmodel/ModelBakery.java +++ b/client/src/client/renderer/blockmodel/ModelBakery.java @@ -42,7 +42,7 @@ public abstract class ModelBakery static { for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { - String name = BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)).toString(); + String name = BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)).toString(); LOCATIONS_BUILTIN_TEXTURES.add("blocks/" + name + "_flow"); LOCATIONS_BUILTIN_TEXTURES.add("blocks/" + name + "_still"); } @@ -63,7 +63,7 @@ public abstract class ModelBakery models.put(MISSING, (ModelBlock)new ModelBlock(null).add().all()); variants.add(MISSING); for(Entry entry : map.entrySet()) { - ModelBlock model = (ModelBlock)entry.getKey().getBlock().getModel(ModelBlock.PROVIDER, BlockRegistry.getNameFromBlock(entry.getKey().getBlock()) + ModelBlock model = (ModelBlock)entry.getKey().getBlock().getModel(ModelBlock.PROVIDER, BlockRegistry.REGISTRY.getNameForObject(entry.getKey().getBlock()) .toString(), entry.getKey()); // ResourceLocation blk = new ResourceLocation(entry.getValue().getName()); models.put(entry.getValue(), model); @@ -144,8 +144,8 @@ public abstract class ModelBakery // { item.getRenderItems(item, stacks); for(ItemStack stack : stacks) { - String resourcelocation = "item/" + ItemRegistry.getNameFromItem(item).toString() + "#" + stack.getMetadata() + '#' + "inventory"; - models.put(resourcelocation, (ModelBlock)item.getModel(ModelBlock.PROVIDER, ItemRegistry.getNameFromItem(item).toString(), stack.getMetadata())); + String resourcelocation = "item/" + ItemRegistry.REGISTRY.getNameForObject(item).toString() + "#" + stack.getMetadata() + '#' + "inventory"; + models.put(resourcelocation, (ModelBlock)item.getModel(ModelBlock.PROVIDER, ItemRegistry.REGISTRY.getNameForObject(item).toString(), stack.getMetadata())); itemLocations.add(resourcelocation); } stacks.clear(); diff --git a/client/src/main/java/client/renderer/blockmodel/ModelBlock.java b/client/src/client/renderer/blockmodel/ModelBlock.java similarity index 95% rename from client/src/main/java/client/renderer/blockmodel/ModelBlock.java rename to client/src/client/renderer/blockmodel/ModelBlock.java index 351704d..69504fa 100755 --- a/client/src/main/java/client/renderer/blockmodel/ModelBlock.java +++ b/client/src/client/renderer/blockmodel/ModelBlock.java @@ -37,6 +37,7 @@ public class ModelBlock extends Model { private final String[] layers; private final ModelBlock parent; + private boolean occlusion; private ModelRotation rotation; private boolean uvLock; private Transforms transform; @@ -48,6 +49,11 @@ public class ModelBlock extends Model { ModelProvider.setProvider(PROVIDER); } + public ModelBlock noOcclude() { + this.occlusion = false; + return this; + } + public ModelBlock uvLock() { this.uvLock = true; return this; @@ -145,6 +151,7 @@ public class ModelBlock extends Model { layers[z] = layers[z].indexOf('/') == -1 ? "items/" + layers[z] : layers[z]; } this.elements = parent == null ? elements : parent.getElements(); + this.occlusion = parent == null ? occlude : parent.isAmbientOcclusion(); this.gui3d = gui3d; this.primary = primary == null ? TextureMap.LOCATION_MISSING_TEXTURE : primary; this.parent = parent; @@ -158,6 +165,10 @@ public class ModelBlock extends Model { return this.elements; } + public boolean isAmbientOcclusion() { + return this.occlusion; + } + public boolean isGui3d() { return this.gui3d; } diff --git a/client/src/main/java/client/renderer/blockmodel/ModelGenerator.java b/client/src/client/renderer/blockmodel/ModelGenerator.java similarity index 96% rename from client/src/main/java/client/renderer/blockmodel/ModelGenerator.java rename to client/src/client/renderer/blockmodel/ModelGenerator.java index b487010..9e4ccc6 100755 --- a/client/src/main/java/client/renderer/blockmodel/ModelGenerator.java +++ b/client/src/client/renderer/blockmodel/ModelGenerator.java @@ -26,13 +26,13 @@ public abstract class ModelGenerator { } catch(Throwable e) { if(e instanceof FileNotFoundException) - Log.IO.warn("Textur ist nicht zum Zusammenstellen vorhanden: " + textureLocation); + Log.JNI.warn("Textur ist nicht zum Zusammenstellen vorhanden: " + textureLocation); else - Log.IO.error(e, "Konnte Textur '" + textureLocation + "' nicht zum Zusammenstellen laden"); + Log.JNI.error(e, "Konnte Textur '" + textureLocation + "' nicht zum Zusammenstellen laden"); return Lists.newArrayList(); } if(img.length < tw * th) { - Log.IO.warn("Konnte Textur '" + textureLocation.toString() + "' nicht zum Zusammenstellen laden weil sie zu klein ist " + + Log.JNI.warn("Konnte Textur '" + textureLocation.toString() + "' nicht zum Zusammenstellen laden weil sie zu klein ist " + "(benötige " + (tw*th) + " [" + tw + "x" + th + "], habe " + img.length + ")"); return Lists.newArrayList(); } diff --git a/client/src/main/java/client/renderer/blockmodel/ModelManager.java b/client/src/client/renderer/blockmodel/ModelManager.java similarity index 91% rename from client/src/main/java/client/renderer/blockmodel/ModelManager.java rename to client/src/client/renderer/blockmodel/ModelManager.java index 55a9399..5984f9a 100755 --- a/client/src/main/java/client/renderer/blockmodel/ModelManager.java +++ b/client/src/client/renderer/blockmodel/ModelManager.java @@ -8,7 +8,7 @@ import java.util.Set; import client.renderer.texture.TextureAtlasSprite; import client.renderer.texture.TextureMap; import common.block.Block; -import common.block.liquid.BlockLiquid; +import common.block.BlockLiquid; import common.collect.Maps; import common.init.BlockRegistry; import common.init.Blocks; @@ -33,7 +33,7 @@ public class ModelManager for(Block block : BlockRegistry.REGISTRY) { if(block.getRenderType() != 3) { this.builtin.add(block); - // Log.info("Builtin: " + BlockRegistry.getNameFromBlock(block)); + // Log.info("Builtin: " + BlockRegistry.REGISTRY.getNameForObject(block)); } else { IProperty[] ignored = block.getIgnoredProperties(); @@ -100,6 +100,11 @@ public class ModelManager return this.texMap.getAtlasSprite("blocks/water_still"); } + if (block == Blocks.skull) + { + return this.texMap.getAtlasSprite("blocks/soul_sand"); + } + // if (block == Blocks.barrier) // { // return this.modelManager.getTextureMap().getAtlasSprite("items/barrier"); @@ -109,7 +114,7 @@ public class ModelManager { String texture = this.liquidMap.get(block); if(texture == null) - this.liquidMap.put(block, texture = "blocks/" + BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(FluidRegistry.getFluidMeta((BlockLiquid)block))) + "_still"); + this.liquidMap.put(block, texture = "blocks/" + BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(FluidRegistry.getFluidMeta((BlockLiquid)block))) + "_still"); return this.texMap.getAtlasSprite(texture); } } @@ -119,7 +124,7 @@ public class ModelManager ibakedmodel = this.defaultModel; } - return ibakedmodel.getBaseTexture(); + return ibakedmodel.getParticleTexture(); } public IBakedModel getModelForState(State state) diff --git a/client/src/main/java/client/renderer/blockmodel/MultiStateMap.java b/client/src/client/renderer/blockmodel/MultiStateMap.java similarity index 96% rename from client/src/main/java/client/renderer/blockmodel/MultiStateMap.java rename to client/src/client/renderer/blockmodel/MultiStateMap.java index 496e619..1461f83 100755 --- a/client/src/main/java/client/renderer/blockmodel/MultiStateMap.java +++ b/client/src/client/renderer/blockmodel/MultiStateMap.java @@ -30,7 +30,7 @@ public class MultiStateMap extends StateMap if (this.name == null) { - s = BlockRegistry.getNameFromBlock(state.getBlock()); + s = BlockRegistry.REGISTRY.getNameForObject(state.getBlock()); } else { diff --git a/client/src/main/java/client/renderer/blockmodel/SingleStateMap.java b/client/src/client/renderer/blockmodel/SingleStateMap.java similarity index 60% rename from client/src/main/java/client/renderer/blockmodel/SingleStateMap.java rename to client/src/client/renderer/blockmodel/SingleStateMap.java index 73100e9..6ad21d9 100755 --- a/client/src/main/java/client/renderer/blockmodel/SingleStateMap.java +++ b/client/src/client/renderer/blockmodel/SingleStateMap.java @@ -8,6 +8,6 @@ public class SingleStateMap extends StateMap { protected String getResourceLocation(State state) { - return BlockRegistry.getNameFromBlock(state.getBlock()).toString() + '#' + this.getPropertyString(state.getProperties()); + return BlockRegistry.REGISTRY.getNameForObject(state.getBlock()).toString() + '#' + this.getPropertyString(state.getProperties()); } } diff --git a/client/src/main/java/client/renderer/blockmodel/StateMap.java b/client/src/client/renderer/blockmodel/StateMap.java similarity index 100% rename from client/src/main/java/client/renderer/blockmodel/StateMap.java rename to client/src/client/renderer/blockmodel/StateMap.java diff --git a/client/src/main/java/client/renderer/chunk/ChunkCompileTaskGenerator.java b/client/src/client/renderer/chunk/ChunkCompileTaskGenerator.java similarity index 100% rename from client/src/main/java/client/renderer/chunk/ChunkCompileTaskGenerator.java rename to client/src/client/renderer/chunk/ChunkCompileTaskGenerator.java diff --git a/client/src/main/java/client/renderer/chunk/ChunkRenderDispatcher.java b/client/src/client/renderer/chunk/ChunkRenderDispatcher.java similarity index 100% rename from client/src/main/java/client/renderer/chunk/ChunkRenderDispatcher.java rename to client/src/client/renderer/chunk/ChunkRenderDispatcher.java diff --git a/client/src/main/java/client/renderer/chunk/ChunkRenderWorker.java b/client/src/client/renderer/chunk/ChunkRenderWorker.java similarity index 92% rename from client/src/main/java/client/renderer/chunk/ChunkRenderWorker.java rename to client/src/client/renderer/chunk/ChunkRenderWorker.java index 0fe9a2b..d685f68 100755 --- a/client/src/main/java/client/renderer/chunk/ChunkRenderWorker.java +++ b/client/src/client/renderer/chunk/ChunkRenderWorker.java @@ -62,7 +62,7 @@ public class ChunkRenderWorker implements Runnable { if (!generator.isFinished()) { - Log.RENDER.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn PENDING erwartet war; ignoriere Aufgabe"); + Log.JNI.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn PENDING erwartet war; ignoriere Aufgabe"); } return; @@ -106,7 +106,7 @@ public class ChunkRenderWorker implements Runnable { if (!generator.isFinished()) { - Log.RENDER.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn COMPILING erwartet war; breche Aufgabe ab"); + Log.JNI.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn COMPILING erwartet war; breche Aufgabe ab"); } this.freeRenderBuilder(generator); @@ -164,7 +164,7 @@ public class ChunkRenderWorker implements Runnable if (!generator.isFinished()) { - Log.RENDER.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn UPLOADING erwartet war; breche Aufgabe ab"); + Log.JNI.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn UPLOADING erwartet war; breche Aufgabe ab"); } } finally @@ -182,7 +182,7 @@ public class ChunkRenderWorker implements Runnable if (!(p_onFailure_1_ instanceof CancellationException) && !(p_onFailure_1_ instanceof InterruptedException)) { - Log.RENDER.error(p_onFailure_1_, "Fehler beim Rendern des Chunks"); + Log.JNI.error(p_onFailure_1_, "Fehler beim Rendern des Chunks"); } } }); diff --git a/client/src/main/java/client/renderer/chunk/CompiledChunk.java b/client/src/client/renderer/chunk/CompiledChunk.java similarity index 100% rename from client/src/main/java/client/renderer/chunk/CompiledChunk.java rename to client/src/client/renderer/chunk/CompiledChunk.java diff --git a/client/src/main/java/client/renderer/chunk/RenderChunk.java b/client/src/client/renderer/chunk/RenderChunk.java similarity index 98% rename from client/src/main/java/client/renderer/chunk/RenderChunk.java rename to client/src/client/renderer/chunk/RenderChunk.java index 06de2e2..8667584 100755 --- a/client/src/main/java/client/renderer/chunk/RenderChunk.java +++ b/client/src/client/renderer/chunk/RenderChunk.java @@ -19,7 +19,6 @@ import client.renderer.RenderGlobal; import client.renderer.VertexBuffer; import client.renderer.tileentity.TileEntityRendererDispatcher; import client.renderer.tileentity.TileEntitySpecialRenderer; -import client.world.WorldClient; import common.block.Block; import common.collect.Maps; import common.collect.Sets; @@ -29,10 +28,11 @@ import common.util.BlockPos; import common.util.BoundingBox; import common.util.Facing; import common.world.State; +import common.world.World; public class RenderChunk { - private WorldClient world; + private World world; private final RenderGlobal renderGlobal; public static int renderChunksUpdated; private BlockPos position; @@ -49,7 +49,7 @@ public class RenderChunk private boolean needsUpdate = true; private EnumMap mapEnumFacing = Maps.newEnumMap(Facing.class); - public RenderChunk(WorldClient worldIn, RenderGlobal renderGlobalIn, BlockPos blockPosIn, int indexIn) + public RenderChunk(World worldIn, RenderGlobal renderGlobalIn, BlockPos blockPosIn, int indexIn) { this.world = worldIn; this.renderGlobal = renderGlobalIn; diff --git a/client/src/main/java/client/renderer/chunk/SetVisibility.java b/client/src/client/renderer/chunk/SetVisibility.java similarity index 100% rename from client/src/main/java/client/renderer/chunk/SetVisibility.java rename to client/src/client/renderer/chunk/SetVisibility.java diff --git a/client/src/main/java/client/renderer/chunk/VisGraph.java b/client/src/client/renderer/chunk/VisGraph.java similarity index 100% rename from client/src/main/java/client/renderer/chunk/VisGraph.java rename to client/src/client/renderer/chunk/VisGraph.java diff --git a/client/src/main/java/client/renderer/entity/Render.java b/client/src/client/renderer/entity/Render.java similarity index 100% rename from client/src/main/java/client/renderer/entity/Render.java rename to client/src/client/renderer/entity/Render.java diff --git a/client/src/main/java/client/renderer/entity/RenderArachnoid.java b/client/src/client/renderer/entity/RenderArachnoid.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderArachnoid.java rename to client/src/client/renderer/entity/RenderArachnoid.java diff --git a/client/src/main/java/client/renderer/entity/RenderArrow.java b/client/src/client/renderer/entity/RenderArrow.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderArrow.java rename to client/src/client/renderer/entity/RenderArrow.java diff --git a/client/src/main/java/client/renderer/entity/RenderBat.java b/client/src/client/renderer/entity/RenderBat.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderBat.java rename to client/src/client/renderer/entity/RenderBat.java diff --git a/client/src/main/java/client/renderer/entity/RenderBlockEntity.java b/client/src/client/renderer/entity/RenderBlockEntity.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderBlockEntity.java rename to client/src/client/renderer/entity/RenderBlockEntity.java diff --git a/client/src/main/java/client/renderer/entity/RenderBoat.java b/client/src/client/renderer/entity/RenderBoat.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderBoat.java rename to client/src/client/renderer/entity/RenderBoat.java diff --git a/client/src/main/java/client/renderer/entity/RenderBullet.java b/client/src/client/renderer/entity/RenderBullet.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderBullet.java rename to client/src/client/renderer/entity/RenderBullet.java diff --git a/client/src/main/java/client/renderer/entity/RenderChicken.java b/client/src/client/renderer/entity/RenderChicken.java similarity index 80% rename from client/src/main/java/client/renderer/entity/RenderChicken.java rename to client/src/client/renderer/entity/RenderChicken.java index d9f885c..9afeff9 100755 --- a/client/src/main/java/client/renderer/entity/RenderChicken.java +++ b/client/src/client/renderer/entity/RenderChicken.java @@ -27,8 +27,8 @@ public class RenderChicken extends RenderLiving */ protected float handleRotationFloat(EntityChicken livingBase, float partialTicks) { - float f = livingBase.lastWingRotation + (livingBase.wingRotation - livingBase.lastWingRotation) * partialTicks; - float f1 = livingBase.lastDestPos + (livingBase.destPos - livingBase.lastDestPos) * partialTicks; + float f = livingBase.field_70888_h + (livingBase.wingRotation - livingBase.field_70888_h) * partialTicks; + float f1 = livingBase.field_70884_g + (livingBase.destPos - livingBase.field_70884_g) * partialTicks; return (ExtMath.sin(f) + 1.0F) * f1; } } diff --git a/client/src/main/java/client/renderer/entity/RenderCow.java b/client/src/client/renderer/entity/RenderCow.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderCow.java rename to client/src/client/renderer/entity/RenderCow.java diff --git a/client/src/main/java/client/renderer/entity/RenderCrystal.java b/client/src/client/renderer/entity/RenderCrystal.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderCrystal.java rename to client/src/client/renderer/entity/RenderCrystal.java diff --git a/client/src/main/java/client/renderer/entity/RenderDie.java b/client/src/client/renderer/entity/RenderDie.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderDie.java rename to client/src/client/renderer/entity/RenderDie.java diff --git a/client/src/main/java/client/renderer/entity/RenderDragon.java b/client/src/client/renderer/entity/RenderDragon.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderDragon.java rename to client/src/client/renderer/entity/RenderDragon.java diff --git a/client/src/main/java/client/renderer/entity/RenderDynamite.java b/client/src/client/renderer/entity/RenderDynamite.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderDynamite.java rename to client/src/client/renderer/entity/RenderDynamite.java diff --git a/client/src/main/java/client/renderer/entity/RenderEntity.java b/client/src/client/renderer/entity/RenderEntity.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderEntity.java rename to client/src/client/renderer/entity/RenderEntity.java diff --git a/client/src/main/java/client/renderer/entity/RenderEntityItem.java b/client/src/client/renderer/entity/RenderEntityItem.java similarity index 86% rename from client/src/main/java/client/renderer/entity/RenderEntityItem.java rename to client/src/client/renderer/entity/RenderEntityItem.java index 4ba2eff..21e8fd5 100755 --- a/client/src/main/java/client/renderer/entity/RenderEntityItem.java +++ b/client/src/client/renderer/entity/RenderEntityItem.java @@ -40,7 +40,7 @@ public class RenderEntityItem extends Render int i = this.func_177078_a(itemstack); float f = 0.25F; float f1 = ExtMath.sin(((float)itemIn.getAge() + p_177077_8_) / 10.0F + itemIn.hoverStart) * 0.1F + 0.1F; - float f2 = p_177077_9_.getTransforms().get(Transforms.Camera.GROUND).scale(); + float f2 = p_177077_9_.getItemCameraTransforms().get(Transforms.Camera.GROUND).scale.y; GL11.glTranslatef((float)p_177077_2_, (float)p_177077_4_ + f1 + 0.25F * f2, (float)p_177077_6_); if (flag || this.renderManager.gm != null) @@ -66,19 +66,19 @@ public class RenderEntityItem extends Render { int i = 1; - if (stack.size > 48) + if (stack.stackSize > 48) { i = 5; } - else if (stack.size > 32) + else if (stack.stackSize > 32) { i = 4; } - else if (stack.size > 16) + else if (stack.stackSize > 16) { i = 3; } - else if (stack.size > 1) + else if (stack.stackSize > 1) { i = 2; } @@ -126,18 +126,20 @@ public class RenderEntityItem extends Render } GL11.glScalef(0.5F, 0.5F, 0.5F); - RenderItem.apply(ibakedmodel.getTransforms(), Transforms.Camera.GROUND); + RenderItem.apply(ibakedmodel.getItemCameraTransforms(), Transforms.Camera.GROUND); this.itemRenderer.renderItem(itemstack, ibakedmodel); GL11.glPopMatrix(); } else { GL11.glPushMatrix(); - RenderItem.apply(ibakedmodel.getTransforms(), Transforms.Camera.GROUND); + RenderItem.apply(ibakedmodel.getItemCameraTransforms(), Transforms.Camera.GROUND); this.itemRenderer.renderItem(itemstack, ibakedmodel); GL11.glPopMatrix(); - float f3 = ibakedmodel.getTransforms().ground.scale(); - GL11.glTranslatef(0.0F, 0.0F, 0.046875F * f3); + float f3 = ibakedmodel.getItemCameraTransforms().ground.scale.x; + float f4 = ibakedmodel.getItemCameraTransforms().ground.scale.y; + float f5 = ibakedmodel.getItemCameraTransforms().ground.scale.z; + GL11.glTranslatef(0.0F * f3, 0.0F * f4, 0.046875F * f5); } } diff --git a/client/src/main/java/client/renderer/entity/RenderFallingBlock.java b/client/src/client/renderer/entity/RenderFallingBlock.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderFallingBlock.java rename to client/src/client/renderer/entity/RenderFallingBlock.java diff --git a/client/src/main/java/client/renderer/entity/RenderFireball.java b/client/src/client/renderer/entity/RenderFireball.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderFireball.java rename to client/src/client/renderer/entity/RenderFireball.java diff --git a/client/src/main/java/client/renderer/entity/RenderFish.java b/client/src/client/renderer/entity/RenderFish.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderFish.java rename to client/src/client/renderer/entity/RenderFish.java diff --git a/client/src/main/java/client/renderer/entity/RenderFlyingBox.java b/client/src/client/renderer/entity/RenderFlyingBox.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderFlyingBox.java rename to client/src/client/renderer/entity/RenderFlyingBox.java diff --git a/client/src/main/java/client/renderer/entity/RenderHorse.java b/client/src/client/renderer/entity/RenderHorse.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderHorse.java rename to client/src/client/renderer/entity/RenderHorse.java diff --git a/client/src/main/java/client/renderer/entity/RenderHumanoid.java b/client/src/client/renderer/entity/RenderHumanoid.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderHumanoid.java rename to client/src/client/renderer/entity/RenderHumanoid.java diff --git a/client/src/main/java/client/renderer/entity/RenderItem.java b/client/src/client/renderer/entity/RenderItem.java similarity index 91% rename from client/src/main/java/client/renderer/entity/RenderItem.java rename to client/src/client/renderer/entity/RenderItem.java index a2a790f..d1ab920 100755 --- a/client/src/main/java/client/renderer/entity/RenderItem.java +++ b/client/src/client/renderer/entity/RenderItem.java @@ -77,10 +77,10 @@ public class RenderItem for (Facing enumfacing : Facing.values()) { - this.renderQuads(worldrenderer, model.getFace(enumfacing), color, stack); + this.renderQuads(worldrenderer, model.getFaceQuads(enumfacing), color, stack); } - this.renderQuads(worldrenderer, model.getQuads(), color, stack); + this.renderQuads(worldrenderer, model.getGeneralQuads(), color, stack); Tessellator.draw(); } @@ -91,7 +91,7 @@ public class RenderItem GL11.glPushMatrix(); GL11.glScalef(0.5F, 0.5F, 0.5F); - if (model.isBuiltin()) + if (model.isBuiltInRenderer()) { GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); @@ -270,9 +270,14 @@ public class RenderItem GlState.enableBlend(); GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); GL11.glPushMatrix(); - Transforms itemcameratransforms = model.getTransforms(); + Transforms itemcameratransforms = model.getItemCameraTransforms(); RenderItem.apply(itemcameratransforms, cameraTransformType); + if (this.isThereOneNegativeScale(itemcameratransforms.get(cameraTransformType))) + { + GlState.cullFace(GL11.GL_FRONT); + } + this.renderItem(stack, model); GlState.cullFace(GL11.GL_BACK); GL11.glPopMatrix(); @@ -282,6 +287,16 @@ public class RenderItem // this.textureManager.getTexture(TextureMap.locationBlocksTexture).restoreLastMipmap(); } + /** + * Return true if only one scale is negative + * + * @param itemTranformVec The ItemTransformVec3f instance + */ + private boolean isThereOneNegativeScale(Transform itemTranformVec) + { + return itemTranformVec.scale.x < 0.0F ^ itemTranformVec.scale.y < 0.0F ^ itemTranformVec.scale.z < 0.0F; + } + private void renderItemIntoGUI(ItemStack stack, int x, int y) { IBakedModel ibakedmodel = this.itemModelMesher.getItemModel(stack); @@ -295,7 +310,7 @@ public class RenderItem GlState.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GlState.color(1.0F, 1.0F, 1.0F, 1.0F); this.setupGuiTransform(x, y, ibakedmodel.isGui3d()); - RenderItem.apply(ibakedmodel.getTransforms(), Transforms.Camera.GUI); + RenderItem.apply(ibakedmodel.getItemCameraTransforms(), Transforms.Camera.GUI); this.renderItem(stack, ibakedmodel); GlState.disableAlpha(); GlState.disableRescaleNormal(); @@ -347,11 +362,11 @@ public class RenderItem public static void apply(Transforms trans, Transforms.Camera type) { Transform vec = trans.get(type); if(vec != Transform.IDENTITY) { - GL11.glTranslatef(vec.translationX(), vec.translationY(), vec.translationZ()); - GL11.glRotatef(vec.rotationY(), 0.0F, 1.0F, 0.0F); - GL11.glRotatef(vec.rotationX(), 1.0F, 0.0F, 0.0F); - GL11.glRotatef(vec.rotationZ(), 0.0F, 0.0F, 1.0F); - GL11.glScalef(vec.scale(), vec.scale(), vec.scale()); + GL11.glTranslatef(vec.translation.x, vec.translation.y, vec.translation.z); + GL11.glRotatef(vec.rotation.y, 0.0F, 1.0F, 0.0F); + GL11.glRotatef(vec.rotation.x, 1.0F, 0.0F, 0.0F); + GL11.glRotatef(vec.rotation.z, 0.0F, 0.0F, 1.0F); + GL11.glScalef(vec.scale.x, vec.scale.y, vec.scale.z); } } } diff --git a/client/src/main/java/client/renderer/entity/RenderItemEntity.java b/client/src/client/renderer/entity/RenderItemEntity.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderItemEntity.java rename to client/src/client/renderer/entity/RenderItemEntity.java diff --git a/client/src/main/java/client/renderer/entity/RenderLeashKnot.java b/client/src/client/renderer/entity/RenderLeashKnot.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderLeashKnot.java rename to client/src/client/renderer/entity/RenderLeashKnot.java diff --git a/client/src/main/java/client/renderer/entity/RenderLightning.java b/client/src/client/renderer/entity/RenderLightning.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderLightning.java rename to client/src/client/renderer/entity/RenderLightning.java diff --git a/client/src/main/java/client/renderer/entity/RenderLiving.java b/client/src/client/renderer/entity/RenderLiving.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderLiving.java rename to client/src/client/renderer/entity/RenderLiving.java diff --git a/client/src/main/java/client/renderer/entity/RenderManager.java b/client/src/client/renderer/entity/RenderManager.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderManager.java rename to client/src/client/renderer/entity/RenderManager.java diff --git a/client/src/main/java/client/renderer/entity/RenderMinecart.java b/client/src/client/renderer/entity/RenderMinecart.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderMinecart.java rename to client/src/client/renderer/entity/RenderMinecart.java diff --git a/client/src/main/java/client/renderer/entity/RenderMooshroom.java b/client/src/client/renderer/entity/RenderMooshroom.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderMooshroom.java rename to client/src/client/renderer/entity/RenderMooshroom.java diff --git a/client/src/main/java/client/renderer/entity/RenderMouse.java b/client/src/client/renderer/entity/RenderMouse.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderMouse.java rename to client/src/client/renderer/entity/RenderMouse.java diff --git a/client/src/main/java/client/renderer/entity/RenderNpc.java b/client/src/client/renderer/entity/RenderNpc.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderNpc.java rename to client/src/client/renderer/entity/RenderNpc.java diff --git a/client/src/main/java/client/renderer/entity/RenderOcelot.java b/client/src/client/renderer/entity/RenderOcelot.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderOcelot.java rename to client/src/client/renderer/entity/RenderOcelot.java diff --git a/client/src/main/java/client/renderer/entity/RenderPig.java b/client/src/client/renderer/entity/RenderPig.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderPig.java rename to client/src/client/renderer/entity/RenderPig.java diff --git a/client/src/main/java/client/renderer/entity/RenderPotion.java b/client/src/client/renderer/entity/RenderPotion.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderPotion.java rename to client/src/client/renderer/entity/RenderPotion.java diff --git a/client/src/main/java/client/renderer/entity/RenderRabbit.java b/client/src/client/renderer/entity/RenderRabbit.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderRabbit.java rename to client/src/client/renderer/entity/RenderRabbit.java diff --git a/client/src/main/java/client/renderer/entity/RenderSheep.java b/client/src/client/renderer/entity/RenderSheep.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderSheep.java rename to client/src/client/renderer/entity/RenderSheep.java diff --git a/client/src/main/java/client/renderer/entity/RenderSlime.java b/client/src/client/renderer/entity/RenderSlime.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderSlime.java rename to client/src/client/renderer/entity/RenderSlime.java diff --git a/client/src/main/java/client/renderer/entity/RenderSpaceMarine.java b/client/src/client/renderer/entity/RenderSpaceMarine.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderSpaceMarine.java rename to client/src/client/renderer/entity/RenderSpaceMarine.java diff --git a/client/src/main/java/client/renderer/entity/RenderSquid.java b/client/src/client/renderer/entity/RenderSquid.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderSquid.java rename to client/src/client/renderer/entity/RenderSquid.java diff --git a/client/src/main/java/client/renderer/entity/RenderTntMinecart.java b/client/src/client/renderer/entity/RenderTntMinecart.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderTntMinecart.java rename to client/src/client/renderer/entity/RenderTntMinecart.java diff --git a/client/src/main/java/client/renderer/entity/RenderTntPrimed.java b/client/src/client/renderer/entity/RenderTntPrimed.java similarity index 98% rename from client/src/main/java/client/renderer/entity/RenderTntPrimed.java rename to client/src/client/renderer/entity/RenderTntPrimed.java index 616fd3b..85aa3f8 100755 --- a/client/src/main/java/client/renderer/entity/RenderTntPrimed.java +++ b/client/src/client/renderer/entity/RenderTntPrimed.java @@ -6,7 +6,7 @@ import client.Client; import client.renderer.BlockRenderer; import client.renderer.GlState; import client.renderer.texture.TextureMap; -import common.block.tech.BlockTNT; +import common.block.BlockTNT; import common.entity.item.EntityTnt; import common.init.Blocks; import common.util.ExtMath; diff --git a/client/src/main/java/client/renderer/entity/RenderWolf.java b/client/src/client/renderer/entity/RenderWolf.java similarity index 72% rename from client/src/main/java/client/renderer/entity/RenderWolf.java rename to client/src/client/renderer/entity/RenderWolf.java index 3fb1bf1..66ae7d7 100755 --- a/client/src/main/java/client/renderer/entity/RenderWolf.java +++ b/client/src/client/renderer/entity/RenderWolf.java @@ -1,6 +1,5 @@ package client.renderer.entity; -import client.renderer.GlState; import client.renderer.layers.LayerWolfCollar; import client.renderer.model.ModelBase; import common.entity.animal.EntityWolf; @@ -25,21 +24,7 @@ public class RenderWolf extends RenderLiving { return livingBase.getTailRotation(); } - - /** - * Renders the desired {@code T} type Entity. - */ - public void doRender(EntityWolf entity, double x, double y, double z, float partialTicks) - { - if (entity.isWolfWet()) - { - float f = entity.getBrightness(partialTicks) * entity.getShadingWhileWet(partialTicks); - GlState.color(f, f, f, 1.0F); - } - - super.doRender(entity, x, y, z, partialTicks); - } - + /** * Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture. */ diff --git a/client/src/main/java/client/renderer/entity/RenderXpOrb.java b/client/src/client/renderer/entity/RenderXpOrb.java similarity index 100% rename from client/src/main/java/client/renderer/entity/RenderXpOrb.java rename to client/src/client/renderer/entity/RenderXpOrb.java diff --git a/client/src/main/java/client/renderer/entity/RendererLivingEntity.java b/client/src/client/renderer/entity/RendererLivingEntity.java similarity index 99% rename from client/src/main/java/client/renderer/entity/RendererLivingEntity.java rename to client/src/client/renderer/entity/RendererLivingEntity.java index 26c5539..e8df489 100755 --- a/client/src/main/java/client/renderer/entity/RendererLivingEntity.java +++ b/client/src/client/renderer/entity/RendererLivingEntity.java @@ -182,7 +182,7 @@ public abstract class RendererLivingEntity extends Rende } catch (Exception exception) { - Log.RENDER.error((Throwable)exception, (String)"Konnte Objekt nicht rendern"); + Log.JNI.error((Throwable)exception, (String)"Konnte Objekt nicht rendern"); } GlState.setActiveTexture(GL13.GL_TEXTURE1); diff --git a/client/src/main/java/client/renderer/layers/LayerArachnoidArmor.java b/client/src/client/renderer/layers/LayerArachnoidArmor.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerArachnoidArmor.java rename to client/src/client/renderer/layers/LayerArachnoidArmor.java diff --git a/client/src/main/java/client/renderer/layers/LayerArmor.java b/client/src/client/renderer/layers/LayerArmor.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerArmor.java rename to client/src/client/renderer/layers/LayerArmor.java diff --git a/client/src/main/java/client/renderer/layers/LayerArrow.java b/client/src/client/renderer/layers/LayerArrow.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerArrow.java rename to client/src/client/renderer/layers/LayerArrow.java diff --git a/client/src/main/java/client/renderer/layers/LayerCape.java b/client/src/client/renderer/layers/LayerCape.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerCape.java rename to client/src/client/renderer/layers/LayerCape.java diff --git a/client/src/main/java/client/renderer/layers/LayerCharge.java b/client/src/client/renderer/layers/LayerCharge.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerCharge.java rename to client/src/client/renderer/layers/LayerCharge.java diff --git a/client/src/main/java/client/renderer/layers/LayerEnderDragonEyes.java b/client/src/client/renderer/layers/LayerEnderDragonEyes.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerEnderDragonEyes.java rename to client/src/client/renderer/layers/LayerEnderDragonEyes.java diff --git a/client/src/main/java/client/renderer/layers/LayerEntityBreak.java b/client/src/client/renderer/layers/LayerEntityBreak.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerEntityBreak.java rename to client/src/client/renderer/layers/LayerEntityBreak.java diff --git a/client/src/main/java/client/renderer/layers/LayerExtra.java b/client/src/client/renderer/layers/LayerExtra.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerExtra.java rename to client/src/client/renderer/layers/LayerExtra.java diff --git a/client/src/main/java/client/renderer/layers/LayerHeldItem.java b/client/src/client/renderer/layers/LayerHeldItem.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerHeldItem.java rename to client/src/client/renderer/layers/LayerHeldItem.java diff --git a/client/src/main/java/client/renderer/layers/LayerMooshroomMushroom.java b/client/src/client/renderer/layers/LayerMooshroomMushroom.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerMooshroomMushroom.java rename to client/src/client/renderer/layers/LayerMooshroomMushroom.java diff --git a/client/src/main/java/client/renderer/layers/LayerPowerRods.java b/client/src/client/renderer/layers/LayerPowerRods.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerPowerRods.java rename to client/src/client/renderer/layers/LayerPowerRods.java diff --git a/client/src/main/java/client/renderer/layers/LayerRenderer.java b/client/src/client/renderer/layers/LayerRenderer.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerRenderer.java rename to client/src/client/renderer/layers/LayerRenderer.java diff --git a/client/src/main/java/client/renderer/layers/LayerSaddle.java b/client/src/client/renderer/layers/LayerSaddle.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerSaddle.java rename to client/src/client/renderer/layers/LayerSaddle.java diff --git a/client/src/main/java/client/renderer/layers/LayerSheepWool.java b/client/src/client/renderer/layers/LayerSheepWool.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerSheepWool.java rename to client/src/client/renderer/layers/LayerSheepWool.java diff --git a/client/src/main/java/client/renderer/layers/LayerSlimeGel.java b/client/src/client/renderer/layers/LayerSlimeGel.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerSlimeGel.java rename to client/src/client/renderer/layers/LayerSlimeGel.java diff --git a/client/src/main/java/client/renderer/layers/LayerWolfCollar.java b/client/src/client/renderer/layers/LayerWolfCollar.java similarity index 100% rename from client/src/main/java/client/renderer/layers/LayerWolfCollar.java rename to client/src/client/renderer/layers/LayerWolfCollar.java diff --git a/client/src/main/java/client/renderer/model/ModelArachnoid.java b/client/src/client/renderer/model/ModelArachnoid.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelArachnoid.java rename to client/src/client/renderer/model/ModelArachnoid.java diff --git a/client/src/main/java/client/renderer/model/ModelArmor.java b/client/src/client/renderer/model/ModelArmor.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelArmor.java rename to client/src/client/renderer/model/ModelArmor.java diff --git a/client/src/main/java/client/renderer/model/ModelBanner.java b/client/src/client/renderer/model/ModelBanner.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelBanner.java rename to client/src/client/renderer/model/ModelBanner.java diff --git a/client/src/main/java/client/renderer/model/ModelBase.java b/client/src/client/renderer/model/ModelBase.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelBase.java rename to client/src/client/renderer/model/ModelBase.java diff --git a/client/src/main/java/client/renderer/model/ModelBat.java b/client/src/client/renderer/model/ModelBat.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelBat.java rename to client/src/client/renderer/model/ModelBat.java diff --git a/client/src/main/java/client/renderer/model/ModelBiped.java b/client/src/client/renderer/model/ModelBiped.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelBiped.java rename to client/src/client/renderer/model/ModelBiped.java diff --git a/client/src/main/java/client/renderer/model/ModelBoat.java b/client/src/client/renderer/model/ModelBoat.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelBoat.java rename to client/src/client/renderer/model/ModelBoat.java diff --git a/client/src/main/java/client/renderer/model/ModelBox.java b/client/src/client/renderer/model/ModelBox.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelBox.java rename to client/src/client/renderer/model/ModelBox.java diff --git a/client/src/main/java/client/renderer/model/ModelCharge.java b/client/src/client/renderer/model/ModelCharge.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelCharge.java rename to client/src/client/renderer/model/ModelCharge.java diff --git a/client/src/main/java/client/renderer/model/ModelChest.java b/client/src/client/renderer/model/ModelChest.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelChest.java rename to client/src/client/renderer/model/ModelChest.java diff --git a/client/src/main/java/client/renderer/model/ModelChicken.java b/client/src/client/renderer/model/ModelChicken.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelChicken.java rename to client/src/client/renderer/model/ModelChicken.java diff --git a/client/src/main/java/client/renderer/model/ModelCow.java b/client/src/client/renderer/model/ModelCow.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelCow.java rename to client/src/client/renderer/model/ModelCow.java diff --git a/client/src/main/java/client/renderer/model/ModelCrystal.java b/client/src/client/renderer/model/ModelCrystal.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelCrystal.java rename to client/src/client/renderer/model/ModelCrystal.java diff --git a/client/src/main/java/client/renderer/model/ModelDie.java b/client/src/client/renderer/model/ModelDie.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelDie.java rename to client/src/client/renderer/model/ModelDie.java diff --git a/client/src/main/java/client/renderer/model/ModelDragon.java b/client/src/client/renderer/model/ModelDragon.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelDragon.java rename to client/src/client/renderer/model/ModelDragon.java diff --git a/client/src/main/java/client/renderer/model/ModelHead.java b/client/src/client/renderer/model/ModelHead.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelHead.java rename to client/src/client/renderer/model/ModelHead.java diff --git a/client/src/main/java/client/renderer/model/ModelHorse.java b/client/src/client/renderer/model/ModelHorse.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelHorse.java rename to client/src/client/renderer/model/ModelHorse.java diff --git a/client/src/main/java/client/renderer/model/ModelHumanoid.java b/client/src/client/renderer/model/ModelHumanoid.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelHumanoid.java rename to client/src/client/renderer/model/ModelHumanoid.java diff --git a/client/src/client/renderer/model/ModelHumanoidHead.java b/client/src/client/renderer/model/ModelHumanoidHead.java new file mode 100755 index 0000000..6e787e5 --- /dev/null +++ b/client/src/client/renderer/model/ModelHumanoidHead.java @@ -0,0 +1,36 @@ +package client.renderer.model; + +import common.entity.Entity; + +public class ModelHumanoidHead extends ModelHead +{ + private final ModelRenderer head = new ModelRenderer(this, 32, 0); + + public ModelHumanoidHead() + { + super(0, 0, 64, 64); + this.head.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.25F); + this.head.setRotationPoint(0.0F, 0.0F, 0.0F); + } + + /** + * Sets the models various rotation angles then renders the model. + */ + public void render(Entity entityIn, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float scale) + { + super.render(entityIn, p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, scale); + this.head.render(scale); + } + + /** + * Sets the model's various rotation angles. For bipeds, par1 and par2 are used for animating the movement of arms + * and legs, where par1 represents the time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. + */ + public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn) + { + super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn); + this.head.rotateAngleY = this.mainHead.rotateAngleY; + this.head.rotateAngleX = this.mainHead.rotateAngleX; + } +} diff --git a/client/src/main/java/client/renderer/model/ModelLargeChest.java b/client/src/client/renderer/model/ModelLargeChest.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelLargeChest.java rename to client/src/client/renderer/model/ModelLargeChest.java diff --git a/client/src/main/java/client/renderer/model/ModelLeashKnot.java b/client/src/client/renderer/model/ModelLeashKnot.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelLeashKnot.java rename to client/src/client/renderer/model/ModelLeashKnot.java diff --git a/client/src/main/java/client/renderer/model/ModelMinecart.java b/client/src/client/renderer/model/ModelMinecart.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelMinecart.java rename to client/src/client/renderer/model/ModelMinecart.java diff --git a/client/src/main/java/client/renderer/model/ModelMouse.java b/client/src/client/renderer/model/ModelMouse.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelMouse.java rename to client/src/client/renderer/model/ModelMouse.java diff --git a/client/src/main/java/client/renderer/model/ModelOcelot.java b/client/src/client/renderer/model/ModelOcelot.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelOcelot.java rename to client/src/client/renderer/model/ModelOcelot.java diff --git a/client/src/main/java/client/renderer/model/ModelPig.java b/client/src/client/renderer/model/ModelPig.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelPig.java rename to client/src/client/renderer/model/ModelPig.java diff --git a/client/src/main/java/client/renderer/model/ModelQuadruped.java b/client/src/client/renderer/model/ModelQuadruped.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelQuadruped.java rename to client/src/client/renderer/model/ModelQuadruped.java diff --git a/client/src/main/java/client/renderer/model/ModelRabbit.java b/client/src/client/renderer/model/ModelRabbit.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelRabbit.java rename to client/src/client/renderer/model/ModelRabbit.java diff --git a/client/src/main/java/client/renderer/model/ModelRenderer.java b/client/src/client/renderer/model/ModelRenderer.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelRenderer.java rename to client/src/client/renderer/model/ModelRenderer.java diff --git a/client/src/main/java/client/renderer/model/ModelSheep1.java b/client/src/client/renderer/model/ModelSheep1.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelSheep1.java rename to client/src/client/renderer/model/ModelSheep1.java diff --git a/client/src/main/java/client/renderer/model/ModelSheep2.java b/client/src/client/renderer/model/ModelSheep2.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelSheep2.java rename to client/src/client/renderer/model/ModelSheep2.java diff --git a/client/src/main/java/client/renderer/model/ModelSign.java b/client/src/client/renderer/model/ModelSign.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelSign.java rename to client/src/client/renderer/model/ModelSign.java diff --git a/client/src/main/java/client/renderer/model/ModelSlime.java b/client/src/client/renderer/model/ModelSlime.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelSlime.java rename to client/src/client/renderer/model/ModelSlime.java diff --git a/client/src/main/java/client/renderer/model/ModelSpaceMarine.java b/client/src/client/renderer/model/ModelSpaceMarine.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelSpaceMarine.java rename to client/src/client/renderer/model/ModelSpaceMarine.java diff --git a/client/src/main/java/client/renderer/model/ModelSquid.java b/client/src/client/renderer/model/ModelSquid.java similarity index 100% rename from client/src/main/java/client/renderer/model/ModelSquid.java rename to client/src/client/renderer/model/ModelSquid.java diff --git a/client/src/main/java/client/renderer/model/ModelWolf.java b/client/src/client/renderer/model/ModelWolf.java similarity index 92% rename from client/src/main/java/client/renderer/model/ModelWolf.java rename to client/src/client/renderer/model/ModelWolf.java index 35d8eb2..acc9ff4 100755 --- a/client/src/main/java/client/renderer/model/ModelWolf.java +++ b/client/src/client/renderer/model/ModelWolf.java @@ -110,11 +110,11 @@ public class ModelWolf extends ModelBase * Used for easily adding entity-dependent animations. The second and third float params here are the same second * and third as in the setRotationAngles method. */ - public void setLivingAnimations(EntityLiving living, float p_78086_2_, float p_78086_3_, float partialTickTime) + public void setLivingAnimations(EntityLiving entitylivingbaseIn, float p_78086_2_, float p_78086_3_, float partialTickTime) { - EntityWolf wolf = (EntityWolf)living; + EntityWolf entitywolf = (EntityWolf)entitylivingbaseIn; - if (wolf.isAngry()) + if (entitywolf.isAngry()) { this.wolfTail.rotateAngleY = 0.0F; } @@ -123,7 +123,7 @@ public class ModelWolf extends ModelBase this.wolfTail.rotateAngleY = ExtMath.cos(p_78086_2_ * 0.6662F) * 1.4F * p_78086_3_; } - if (wolf.isSitting()) + if (entitywolf.isSitting()) { this.wolfMane.setRotationPoint(-1.0F, 16.0F, -3.0F); this.wolfMane.rotateAngleX = ((float)Math.PI * 2F / 5F); @@ -157,10 +157,7 @@ public class ModelWolf extends ModelBase this.wolfLeg4.rotateAngleX = ExtMath.cos(p_78086_2_ * 0.6662F) * 1.4F * p_78086_3_; } - this.wolfHeadMain.rotateAngleZ = wolf.getInterestedAngle(partialTickTime) + wolf.getShakeAngle(partialTickTime, 0.0F); - this.wolfMane.rotateAngleZ = wolf.getShakeAngle(partialTickTime, -0.08F); - this.wolfBody.rotateAngleZ = wolf.getShakeAngle(partialTickTime, -0.16F); - this.wolfTail.rotateAngleZ = wolf.getShakeAngle(partialTickTime, -0.2F); + this.wolfHeadMain.rotateAngleZ = entitywolf.getInterestedAngle(partialTickTime); } /** diff --git a/client/src/main/java/client/renderer/model/PositionTextureVertex.java b/client/src/client/renderer/model/PositionTextureVertex.java similarity index 100% rename from client/src/main/java/client/renderer/model/PositionTextureVertex.java rename to client/src/client/renderer/model/PositionTextureVertex.java diff --git a/client/src/main/java/client/renderer/model/TextureOffset.java b/client/src/client/renderer/model/TextureOffset.java similarity index 100% rename from client/src/main/java/client/renderer/model/TextureOffset.java rename to client/src/client/renderer/model/TextureOffset.java diff --git a/client/src/main/java/client/renderer/model/TexturedQuad.java b/client/src/client/renderer/model/TexturedQuad.java similarity index 100% rename from client/src/main/java/client/renderer/model/TexturedQuad.java rename to client/src/client/renderer/model/TexturedQuad.java diff --git a/client/src/main/java/client/renderer/particle/EffectRenderer.java b/client/src/client/renderer/particle/EffectRenderer.java similarity index 99% rename from client/src/main/java/client/renderer/particle/EffectRenderer.java rename to client/src/client/renderer/particle/EffectRenderer.java index 49d88cb..5d6ea5f 100755 --- a/client/src/main/java/client/renderer/particle/EffectRenderer.java +++ b/client/src/client/renderer/particle/EffectRenderer.java @@ -16,7 +16,7 @@ import common.block.Block; import common.collect.Lists; import common.collect.Maps; import common.entity.Entity; -import common.init.Blocks; +import common.material.Material; import common.model.ParticleType; import common.rng.Random; import common.util.BlockPos; @@ -319,7 +319,7 @@ public class EffectRenderer public void addBlockDestroyEffects(BlockPos pos, State state) { - if (state.getBlock() != Blocks.air) + if (state.getBlock().getMaterial() != Material.air) { state = state.getBlock().getActualState(state, this.worldObj, pos); int i = 4; diff --git a/client/src/main/java/client/renderer/particle/EntityAuraFX.java b/client/src/client/renderer/particle/EntityAuraFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityAuraFX.java rename to client/src/client/renderer/particle/EntityAuraFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityBlockDustFX.java b/client/src/client/renderer/particle/EntityBlockDustFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityBlockDustFX.java rename to client/src/client/renderer/particle/EntityBlockDustFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityBreakingFX.java b/client/src/client/renderer/particle/EntityBreakingFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityBreakingFX.java rename to client/src/client/renderer/particle/EntityBreakingFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityBubbleFX.java b/client/src/client/renderer/particle/EntityBubbleFX.java similarity index 96% rename from client/src/main/java/client/renderer/particle/EntityBubbleFX.java rename to client/src/client/renderer/particle/EntityBubbleFX.java index 909b2b5..44c03f7 100755 --- a/client/src/main/java/client/renderer/particle/EntityBubbleFX.java +++ b/client/src/client/renderer/particle/EntityBubbleFX.java @@ -1,6 +1,6 @@ package client.renderer.particle; -import common.block.Material; +import common.material.Material; import common.util.BlockPos; import common.world.World; @@ -35,7 +35,7 @@ public class EntityBubbleFX extends EntityFX this.motionY *= 0.8500000238418579D; this.motionZ *= 0.8500000238418579D; - if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() != Material.WATER) + if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() != Material.water) { this.setDead(); } diff --git a/client/src/main/java/client/renderer/particle/EntityCloudFX.java b/client/src/client/renderer/particle/EntityCloudFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityCloudFX.java rename to client/src/client/renderer/particle/EntityCloudFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityCrit2FX.java b/client/src/client/renderer/particle/EntityCrit2FX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityCrit2FX.java rename to client/src/client/renderer/particle/EntityCrit2FX.java diff --git a/client/src/main/java/client/renderer/particle/EntityCritFX.java b/client/src/client/renderer/particle/EntityCritFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityCritFX.java rename to client/src/client/renderer/particle/EntityCritFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityDiggingFX.java b/client/src/client/renderer/particle/EntityDiggingFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityDiggingFX.java rename to client/src/client/renderer/particle/EntityDiggingFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityDownfallFX.java b/client/src/client/renderer/particle/EntityDownfallFX.java similarity index 97% rename from client/src/main/java/client/renderer/particle/EntityDownfallFX.java rename to client/src/client/renderer/particle/EntityDownfallFX.java index d8d69eb..b2bd951 100755 --- a/client/src/main/java/client/renderer/particle/EntityDownfallFX.java +++ b/client/src/client/renderer/particle/EntityDownfallFX.java @@ -1,8 +1,8 @@ package client.renderer.particle; import common.block.Block; -import common.block.Material; -import common.block.liquid.BlockLiquid; +import common.block.BlockLiquid; +import common.material.Material; import common.util.BlockPos; import common.util.ExtMath; import common.world.State; diff --git a/client/src/main/java/client/renderer/particle/EntityDropParticleFX.java b/client/src/client/renderer/particle/EntityDropParticleFX.java similarity index 91% rename from client/src/main/java/client/renderer/particle/EntityDropParticleFX.java rename to client/src/client/renderer/particle/EntityDropParticleFX.java index bce2874..90542cd 100755 --- a/client/src/main/java/client/renderer/particle/EntityDropParticleFX.java +++ b/client/src/client/renderer/particle/EntityDropParticleFX.java @@ -1,7 +1,7 @@ package client.renderer.particle; -import common.block.Material; -import common.block.liquid.BlockLiquid; +import common.block.BlockLiquid; +import common.material.Material; import common.model.ParticleType; import common.util.BlockPos; import common.util.ExtMath; @@ -21,7 +21,7 @@ public class EntityDropParticleFX extends EntityFX super(worldIn, xCoordIn, yCoordIn, zCoordIn, 0.0D, 0.0D, 0.0D); this.motionX = this.motionY = this.motionZ = 0.0D; - if (p_i1203_8_ == Material.WATER) + if (p_i1203_8_ == Material.water) { this.particleRed = 0.0F; this.particleGreen = 0.0F; @@ -45,7 +45,7 @@ public class EntityDropParticleFX extends EntityFX public int getBrightnessForRender(float partialTicks) { - return this.materialType == Material.WATER ? super.getBrightnessForRender(partialTicks) : 257; + return this.materialType == Material.water ? super.getBrightnessForRender(partialTicks) : 257; } /** @@ -53,7 +53,7 @@ public class EntityDropParticleFX extends EntityFX */ public float getBrightness(float partialTicks) { - return this.materialType == Material.WATER ? super.getBrightness(partialTicks) : 1.0F; + return this.materialType == Material.water ? super.getBrightness(partialTicks) : 1.0F; } /** @@ -65,7 +65,7 @@ public class EntityDropParticleFX extends EntityFX this.prevY = this.posY; this.prevZ = this.posZ; - if (this.materialType == Material.WATER) + if (this.materialType == Material.water) { this.particleRed = 0.2F; this.particleGreen = 0.3F; @@ -104,7 +104,7 @@ public class EntityDropParticleFX extends EntityFX if (this.onGround) { - if (this.materialType == Material.WATER) + if (this.materialType == Material.water) { this.setDead(); this.worldObj.spawnParticle(ParticleType.WATER_SPLASH, this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D); @@ -144,7 +144,7 @@ public class EntityDropParticleFX extends EntityFX { public EntityFX getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { - return new EntityDropParticleFX(worldIn, xCoordIn, yCoordIn, zCoordIn, Material.LAVA); + return new EntityDropParticleFX(worldIn, xCoordIn, yCoordIn, zCoordIn, Material.lava); } } @@ -152,7 +152,7 @@ public class EntityDropParticleFX extends EntityFX { public EntityFX getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { - return new EntityDropParticleFX(worldIn, xCoordIn, yCoordIn, zCoordIn, Material.WATER); + return new EntityDropParticleFX(worldIn, xCoordIn, yCoordIn, zCoordIn, Material.water); } } } diff --git a/client/src/main/java/client/renderer/particle/EntityEnchantmentTableParticleFX.java b/client/src/client/renderer/particle/EntityEnchantmentTableParticleFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityEnchantmentTableParticleFX.java rename to client/src/client/renderer/particle/EntityEnchantmentTableParticleFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityExplodeFX.java b/client/src/client/renderer/particle/EntityExplodeFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityExplodeFX.java rename to client/src/client/renderer/particle/EntityExplodeFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityFX.java b/client/src/client/renderer/particle/EntityFX.java similarity index 98% rename from client/src/main/java/client/renderer/particle/EntityFX.java rename to client/src/client/renderer/particle/EntityFX.java index 6f177ff..67c53bd 100755 --- a/client/src/main/java/client/renderer/particle/EntityFX.java +++ b/client/src/client/renderer/particle/EntityFX.java @@ -5,7 +5,7 @@ import client.renderer.RenderBuffer; import client.renderer.texture.TextureAtlasSprite; import common.entity.Entity; import common.entity.EntityType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.ExtMath; import common.world.World; @@ -208,16 +208,16 @@ public class EntityFX extends Entity } /** - * (abstract) Protected helper method to write subclass entity data. + * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tag) + public void writeEntityToNBT(NBTTagCompound tagCompound) { } /** - * (abstract) Protected helper method to read subclass entity data. + * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tag) + public void readEntityFromNBT(NBTTagCompound tagCompund) { } diff --git a/client/src/main/java/client/renderer/particle/EntityFirework.java b/client/src/client/renderer/particle/EntityFirework.java similarity index 93% rename from client/src/main/java/client/renderer/particle/EntityFirework.java rename to client/src/client/renderer/particle/EntityFirework.java index 476388f..b3f3072 100755 --- a/client/src/main/java/client/renderer/particle/EntityFirework.java +++ b/client/src/client/renderer/particle/EntityFirework.java @@ -6,8 +6,8 @@ import client.world.WorldClient; import common.entity.Entity; import common.init.SoundEvent; import common.item.ItemDye; -import common.tags.TagObject; -import java.util.List; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.util.BoundingBox; import common.util.ExtMath; import common.world.World; @@ -192,10 +192,10 @@ public class EntityFirework { private int fireworkAge; private final EffectRenderer theEffectRenderer; - private List fireworkExplosions; + private NBTTagList fireworkExplosions; boolean twinkle; - public StarterFX(World p_i46464_1_, double p_i46464_2_, double p_i46464_4_, double p_i46464_6_, double p_i46464_8_, double p_i46464_10_, double p_i46464_12_, EffectRenderer p_i46464_14_, TagObject p_i46464_15_) + public StarterFX(World p_i46464_1_, double p_i46464_2_, double p_i46464_4_, double p_i46464_6_, double p_i46464_8_, double p_i46464_10_, double p_i46464_12_, EffectRenderer p_i46464_14_, NBTTagCompound p_i46464_15_) { super(p_i46464_1_, p_i46464_2_, p_i46464_4_, p_i46464_6_, 0.0D, 0.0D, 0.0D); this.motionX = p_i46464_8_; @@ -206,21 +206,21 @@ public class EntityFirework if (p_i46464_15_ != null) { - this.fireworkExplosions = p_i46464_15_.getList("Explosions"); + this.fireworkExplosions = p_i46464_15_.getTagList("Explosions", 10); - if (this.fireworkExplosions.size() == 0) + if (this.fireworkExplosions.tagCount() == 0) { this.fireworkExplosions = null; } else { - this.particleMaxAge = this.fireworkExplosions.size() * 2 - 1; + this.particleMaxAge = this.fireworkExplosions.tagCount() * 2 - 1; - for (int i = 0; i < this.fireworkExplosions.size(); ++i) + for (int i = 0; i < this.fireworkExplosions.tagCount(); ++i) { - TagObject tag = this.fireworkExplosions.get(i); + NBTTagCompound nbttagcompound = this.fireworkExplosions.getCompoundTagAt(i); - if (tag.getBool("Flicker")) + if (nbttagcompound.getBoolean("Flicker")) { this.twinkle = true; this.particleMaxAge += 15; @@ -242,17 +242,17 @@ public class EntityFirework boolean flag = this.isFarAway(); boolean flag1 = false; - if (this.fireworkExplosions.size() >= 3) + if (this.fireworkExplosions.tagCount() >= 3) { flag1 = true; } else { - for (int i = 0; i < this.fireworkExplosions.size(); ++i) + for (int i = 0; i < this.fireworkExplosions.tagCount(); ++i) { - TagObject tag = this.fireworkExplosions.get(i); + NBTTagCompound nbttagcompound = this.fireworkExplosions.getCompoundTagAt(i); - if (tag.getByte("Type") == 1) + if (nbttagcompound.getByte("Type") == 1) { flag1 = true; break; @@ -265,15 +265,15 @@ public class EntityFirework ((WorldClient)this.worldObj).playSound(this.posX, this.posY, this.posZ, s1, 20.0F); } - if (this.fireworkAge % 2 == 0 && this.fireworkExplosions != null && this.fireworkAge / 2 < this.fireworkExplosions.size()) + if (this.fireworkAge % 2 == 0 && this.fireworkExplosions != null && this.fireworkAge / 2 < this.fireworkExplosions.tagCount()) { int k = this.fireworkAge / 2; - TagObject tag = this.fireworkExplosions.get(k); - int l = tag.getByte("Type"); - boolean flag4 = tag.getBool("Trail"); - boolean flag2 = tag.getBool("Flicker"); - int[] aint = tag.getIntArray("Colors"); - int[] aint1 = tag.getIntArray("FadeColors"); + NBTTagCompound nbttagcompound1 = this.fireworkExplosions.getCompoundTagAt(k); + int l = nbttagcompound1.getByte("Type"); + boolean flag4 = nbttagcompound1.getBoolean("Trail"); + boolean flag2 = nbttagcompound1.getBoolean("Flicker"); + int[] aint = nbttagcompound1.getIntArray("Colors"); + int[] aint1 = nbttagcompound1.getIntArray("FadeColors"); if (aint.length == 0) { diff --git a/client/src/main/java/client/renderer/particle/EntityFishWakeFX.java b/client/src/client/renderer/particle/EntityFishWakeFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityFishWakeFX.java rename to client/src/client/renderer/particle/EntityFishWakeFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityFlameFX.java b/client/src/client/renderer/particle/EntityFlameFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityFlameFX.java rename to client/src/client/renderer/particle/EntityFlameFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityFootStepFX.java b/client/src/client/renderer/particle/EntityFootStepFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityFootStepFX.java rename to client/src/client/renderer/particle/EntityFootStepFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityHeartFX.java b/client/src/client/renderer/particle/EntityHeartFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityHeartFX.java rename to client/src/client/renderer/particle/EntityHeartFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityHugeExplodeFX.java b/client/src/client/renderer/particle/EntityHugeExplodeFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityHugeExplodeFX.java rename to client/src/client/renderer/particle/EntityHugeExplodeFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityLargeExplodeFX.java b/client/src/client/renderer/particle/EntityLargeExplodeFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityLargeExplodeFX.java rename to client/src/client/renderer/particle/EntityLargeExplodeFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityLavaFX.java b/client/src/client/renderer/particle/EntityLavaFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityLavaFX.java rename to client/src/client/renderer/particle/EntityLavaFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityNoteFX.java b/client/src/client/renderer/particle/EntityNoteFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityNoteFX.java rename to client/src/client/renderer/particle/EntityNoteFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityParticleEmitter.java b/client/src/client/renderer/particle/EntityParticleEmitter.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityParticleEmitter.java rename to client/src/client/renderer/particle/EntityParticleEmitter.java diff --git a/client/src/main/java/client/renderer/particle/EntityPickupFX.java b/client/src/client/renderer/particle/EntityPickupFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityPickupFX.java rename to client/src/client/renderer/particle/EntityPickupFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityPortalFX.java b/client/src/client/renderer/particle/EntityPortalFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityPortalFX.java rename to client/src/client/renderer/particle/EntityPortalFX.java diff --git a/client/src/main/java/client/renderer/particle/EntityReddustFX.java b/client/src/client/renderer/particle/EntityReddustFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntityReddustFX.java rename to client/src/client/renderer/particle/EntityReddustFX.java diff --git a/client/src/main/java/client/renderer/particle/EntitySmokeFX.java b/client/src/client/renderer/particle/EntitySmokeFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntitySmokeFX.java rename to client/src/client/renderer/particle/EntitySmokeFX.java diff --git a/client/src/main/java/client/renderer/particle/EntitySnowShovelFX.java b/client/src/client/renderer/particle/EntitySnowShovelFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntitySnowShovelFX.java rename to client/src/client/renderer/particle/EntitySnowShovelFX.java diff --git a/client/src/main/java/client/renderer/particle/EntitySpellParticleFX.java b/client/src/client/renderer/particle/EntitySpellParticleFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntitySpellParticleFX.java rename to client/src/client/renderer/particle/EntitySpellParticleFX.java diff --git a/client/src/main/java/client/renderer/particle/EntitySplashFX.java b/client/src/client/renderer/particle/EntitySplashFX.java similarity index 100% rename from client/src/main/java/client/renderer/particle/EntitySplashFX.java rename to client/src/client/renderer/particle/EntitySplashFX.java diff --git a/client/src/main/java/client/renderer/particle/EntitySuspendFX.java b/client/src/client/renderer/particle/EntitySuspendFX.java similarity index 96% rename from client/src/main/java/client/renderer/particle/EntitySuspendFX.java rename to client/src/client/renderer/particle/EntitySuspendFX.java index 2e9893f..4047b03 100755 --- a/client/src/main/java/client/renderer/particle/EntitySuspendFX.java +++ b/client/src/client/renderer/particle/EntitySuspendFX.java @@ -1,6 +1,6 @@ package client.renderer.particle; -import common.block.Material; +import common.material.Material; import common.util.BlockPos; import common.world.World; @@ -31,7 +31,7 @@ public class EntitySuspendFX extends EntityFX this.prevZ = this.posZ; this.moveEntity(this.motionX, this.motionY, this.motionZ); - if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() != Material.WATER) + if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() != Material.water) { this.setDead(); } diff --git a/client/src/main/java/client/renderer/particle/IParticleFactory.java b/client/src/client/renderer/particle/IParticleFactory.java similarity index 100% rename from client/src/main/java/client/renderer/particle/IParticleFactory.java rename to client/src/client/renderer/particle/IParticleFactory.java diff --git a/client/src/main/java/client/renderer/texture/ColormapLoader.java b/client/src/client/renderer/texture/ColormapLoader.java similarity index 95% rename from client/src/main/java/client/renderer/texture/ColormapLoader.java rename to client/src/client/renderer/texture/ColormapLoader.java index 96ff88c..7566500 100644 --- a/client/src/main/java/client/renderer/texture/ColormapLoader.java +++ b/client/src/client/renderer/texture/ColormapLoader.java @@ -2,8 +2,8 @@ package client.renderer.texture; import java.awt.image.BufferedImage; -import client.util.FileUtils; import common.color.Colorizer; +import common.util.FileUtils; public abstract class ColormapLoader { private static final String GRASS_TEX = "textures/world/grass.png"; diff --git a/client/src/main/java/client/renderer/texture/DynamicTexture.java b/client/src/client/renderer/texture/DynamicTexture.java similarity index 100% rename from client/src/main/java/client/renderer/texture/DynamicTexture.java rename to client/src/client/renderer/texture/DynamicTexture.java diff --git a/client/src/main/java/client/renderer/texture/EntityTexManager.java b/client/src/client/renderer/texture/EntityTexManager.java similarity index 95% rename from client/src/main/java/client/renderer/texture/EntityTexManager.java rename to client/src/client/renderer/texture/EntityTexManager.java index 8160703..b273901 100755 --- a/client/src/main/java/client/renderer/texture/EntityTexManager.java +++ b/client/src/client/renderer/texture/EntityTexManager.java @@ -13,7 +13,6 @@ import java.util.Set; import client.Client; import client.renderer.entity.RenderNpc; import client.renderer.layers.LayerExtra; -import client.util.FileUtils; import common.collect.Lists; import common.collect.Maps; import common.collect.Sets; @@ -21,6 +20,7 @@ import common.entity.npc.EntityNPC; import common.init.SpeciesRegistry; import common.init.SpeciesRegistry.ModelType; import common.log.Log; +import common.util.FileUtils; public abstract class EntityTexManager { @@ -46,17 +46,17 @@ public abstract class EntityTexManager } catch(IOException e) { if(e instanceof FileNotFoundException) - Log.IO.warn("Textur ist nicht vorhanden: " + loc); + Log.JNI.warn("Textur ist nicht vorhanden: " + loc); else - Log.IO.error(e, "Konnte Textur nicht laden: " + loc); + Log.JNI.error(e, "Konnte Textur nicht laden: " + loc); try { image = TextureUtil.readImage(FileUtils.getResource(getDefault(entry.getValue()))); } catch(IOException e2) { if(e2 instanceof FileNotFoundException) - Log.IO.warn("Textur ist nicht vorhanden: " + loc); + Log.JNI.warn("Textur ist nicht vorhanden: " + loc); else - Log.IO.error(e2, "Konnte Textur nicht laden: " + loc); + Log.JNI.error(e2, "Konnte Textur nicht laden: " + loc); image = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setColor(Color.BLACK); @@ -98,9 +98,9 @@ public abstract class EntityTexManager } catch(IOException e) { if(e instanceof FileNotFoundException) - Log.IO.warn("Textur ist nicht vorhanden: " + loc); + Log.JNI.warn("Textur ist nicht vorhanden: " + loc); else - Log.IO.error(e, "Konnte Textur nicht laden: " + loc); + Log.JNI.error(e, "Konnte Textur nicht laden: " + loc); image = new BufferedImage(64, 32, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setColor(Color.BLACK); diff --git a/client/src/main/java/client/renderer/texture/IIconCreator.java b/client/src/client/renderer/texture/IIconCreator.java similarity index 100% rename from client/src/main/java/client/renderer/texture/IIconCreator.java rename to client/src/client/renderer/texture/IIconCreator.java diff --git a/client/src/main/java/client/renderer/texture/LayeredColorMaskTexture.java b/client/src/client/renderer/texture/LayeredColorMaskTexture.java similarity index 96% rename from client/src/main/java/client/renderer/texture/LayeredColorMaskTexture.java rename to client/src/client/renderer/texture/LayeredColorMaskTexture.java index dfb3312..654e960 100755 --- a/client/src/main/java/client/renderer/texture/LayeredColorMaskTexture.java +++ b/client/src/client/renderer/texture/LayeredColorMaskTexture.java @@ -7,9 +7,9 @@ import java.io.IOException; import java.io.InputStream; import java.util.List; -import client.util.FileUtils; import common.color.DyeColor; import common.log.Log; +import common.util.FileUtils; public class LayeredColorMaskTexture extends Texture { @@ -92,7 +92,7 @@ public class LayeredColorMaskTexture extends Texture } catch (IOException ioexception) { - Log.IO.error((Throwable)ioexception, (String)"Konnte Bild mit mehreren Schichten nicht laden"); + Log.JNI.error((Throwable)ioexception, (String)"Konnte Bild mit mehreren Schichten nicht laden"); return; } diff --git a/client/src/main/java/client/renderer/texture/LayeredTexture.java b/client/src/client/renderer/texture/LayeredTexture.java similarity index 91% rename from client/src/main/java/client/renderer/texture/LayeredTexture.java rename to client/src/client/renderer/texture/LayeredTexture.java index 26c5a96..5339db5 100755 --- a/client/src/main/java/client/renderer/texture/LayeredTexture.java +++ b/client/src/client/renderer/texture/LayeredTexture.java @@ -6,9 +6,9 @@ import java.io.IOException; import java.io.InputStream; import java.util.List; -import client.util.FileUtils; import common.collect.Lists; import common.log.Log; +import common.util.FileUtils; public class LayeredTexture extends Texture { @@ -44,7 +44,7 @@ public class LayeredTexture extends Texture } catch (IOException ioexception) { - Log.IO.error((Throwable)ioexception, (String)"Konnte Bild mit mehreren Schichten nicht laden"); + Log.JNI.error((Throwable)ioexception, (String)"Konnte Bild mit mehreren Schichten nicht laden"); return; } diff --git a/client/src/main/java/client/renderer/texture/SimpleTexture.java b/client/src/client/renderer/texture/SimpleTexture.java similarity index 96% rename from client/src/main/java/client/renderer/texture/SimpleTexture.java rename to client/src/client/renderer/texture/SimpleTexture.java index c4aa0ed..43c4629 100755 --- a/client/src/main/java/client/renderer/texture/SimpleTexture.java +++ b/client/src/client/renderer/texture/SimpleTexture.java @@ -4,7 +4,7 @@ import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; -import client.util.FileUtils; +import common.util.FileUtils; public class SimpleTexture extends Texture { private final String location; diff --git a/client/src/main/java/client/renderer/texture/Stitcher.java b/client/src/client/renderer/texture/Stitcher.java similarity index 100% rename from client/src/main/java/client/renderer/texture/Stitcher.java rename to client/src/client/renderer/texture/Stitcher.java diff --git a/client/src/main/java/client/renderer/texture/Texture.java b/client/src/client/renderer/texture/Texture.java similarity index 100% rename from client/src/main/java/client/renderer/texture/Texture.java rename to client/src/client/renderer/texture/Texture.java diff --git a/client/src/main/java/client/renderer/texture/TextureAtlasSprite.java b/client/src/client/renderer/texture/TextureAtlasSprite.java similarity index 100% rename from client/src/main/java/client/renderer/texture/TextureAtlasSprite.java rename to client/src/client/renderer/texture/TextureAtlasSprite.java diff --git a/client/src/main/java/client/renderer/texture/TextureManager.java b/client/src/client/renderer/texture/TextureManager.java similarity index 91% rename from client/src/main/java/client/renderer/texture/TextureManager.java rename to client/src/client/renderer/texture/TextureManager.java index 66f45fb..4bd6328 100755 --- a/client/src/main/java/client/renderer/texture/TextureManager.java +++ b/client/src/client/renderer/texture/TextureManager.java @@ -28,9 +28,9 @@ public class TextureManager { } catch(IOException e) { if(e instanceof FileNotFoundException) - Log.IO.warn("Textur ist nicht vorhanden: " + res); + Log.JNI.warn("Textur ist nicht vorhanden: " + res); else - Log.IO.error(e, "Konnte Textur nicht laden: " + res); + Log.JNI.error(e, "Konnte Textur nicht laden: " + res); tex = TextureUtil.MISSING; this.textures.put(res, tex); flag = false; diff --git a/client/src/main/java/client/renderer/texture/TextureMap.java b/client/src/client/renderer/texture/TextureMap.java similarity index 92% rename from client/src/main/java/client/renderer/texture/TextureMap.java rename to client/src/client/renderer/texture/TextureMap.java index 9c52b1e..5e5c2ee 100755 --- a/client/src/main/java/client/renderer/texture/TextureMap.java +++ b/client/src/client/renderer/texture/TextureMap.java @@ -9,13 +9,13 @@ import java.util.Map.Entry; import client.init.RenderRegistry; import client.renderer.GlState; -import client.util.FileUtils; import common.block.Block; import common.collect.Lists; import common.collect.Maps; import common.init.BlockRegistry; import common.init.FluidRegistry; import common.log.Log; +import common.util.FileUtils; public class TextureMap extends Texture { @@ -45,9 +45,9 @@ public class TextureMap extends Texture block.getAnimatedTextures(map); } for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { - map.put("blocks/" + BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)) + "_still", + map.put("blocks/" + BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)) + "_still", FluidRegistry.getStaticAnim(z)); - map.put("blocks/" + BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)) + "_flow", + map.put("blocks/" + BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)) + "_flow", FluidRegistry.getFluidAnim(z)); } for(Entry entry : map.entrySet()) { @@ -115,17 +115,17 @@ public class TextureMap extends Texture } catch (RuntimeException runtimeexception) { - Log.IO.error((Throwable)runtimeexception, (String)("Konnte Metadaten von " + name + " nicht laden")); + Log.JNI.error((Throwable)runtimeexception, (String)("Konnte Metadaten von " + name + " nicht laden")); continue; } catch (FileNotFoundException f) { - Log.IO.warn("Textur ist nicht vorhanden: " + name); + Log.JNI.warn("Textur ist nicht vorhanden: " + name); continue; } catch (IOException ioexception1) { - Log.IO.error((Throwable)ioexception1, (String)("Benutze Ersatztextur, konnte " + name + " nicht laden")); + Log.JNI.error((Throwable)ioexception1, (String)("Benutze Ersatztextur, konnte " + name + " nicht laden")); continue; } @@ -167,7 +167,7 @@ public class TextureMap extends Texture throw stitcherexception; } - Log.RENDER.info("Textur-Atlas in Größe " + stitcher.getCurrentWidth() + "x" + stitcher.getCurrentHeight() + " erstellt"); + Log.JNI.info("Textur-Atlas in Größe " + stitcher.getCurrentWidth() + "x" + stitcher.getCurrentHeight() + " erstellt"); TextureUtil.allocateTexture(this.getGlTextureId(), stitcher.getCurrentWidth(), stitcher.getCurrentHeight()); Map map = Maps.newHashMap(this.mapRegisteredSprites); diff --git a/client/src/main/java/client/renderer/texture/TextureTicked.java b/client/src/client/renderer/texture/TextureTicked.java similarity index 100% rename from client/src/main/java/client/renderer/texture/TextureTicked.java rename to client/src/client/renderer/texture/TextureTicked.java diff --git a/client/src/main/java/client/renderer/texture/TextureUtil.java b/client/src/client/renderer/texture/TextureUtil.java similarity index 99% rename from client/src/main/java/client/renderer/texture/TextureUtil.java rename to client/src/client/renderer/texture/TextureUtil.java index 5fb705e..71bced9 100755 --- a/client/src/main/java/client/renderer/texture/TextureUtil.java +++ b/client/src/client/renderer/texture/TextureUtil.java @@ -15,7 +15,7 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import client.renderer.GlState; -import client.util.FileUtils; +import common.util.FileUtils; public class TextureUtil { diff --git a/client/src/main/java/client/renderer/ticked/TextureFlamesFX1.java b/client/src/client/renderer/ticked/TextureFlamesFX1.java similarity index 82% rename from client/src/main/java/client/renderer/ticked/TextureFlamesFX1.java rename to client/src/client/renderer/ticked/TextureFlamesFX1.java index 470957b..6b07093 100755 --- a/client/src/main/java/client/renderer/ticked/TextureFlamesFX1.java +++ b/client/src/client/renderer/ticked/TextureFlamesFX1.java @@ -4,18 +4,12 @@ import client.renderer.texture.TextureTicked; public class TextureFlamesFX1 extends TextureTicked -{ - private final boolean mono; +{ - public TextureFlamesFX1(boolean mono) + public TextureFlamesFX1() { field_1133_g = new float[320]; - field_1132_h = new float[320]; - this.mono = mono; - } - - public TextureFlamesFX1() { - this(false); + field_1132_h = new float[320]; } public void renderStep(int textureData[]) @@ -82,14 +76,8 @@ public class TextureFlamesFX1 extends TextureTicked // j1 = l2; // l1 = i3; // j2 = j3; -// } - if(this.mono) { - j2 = (j1 + l1 + j2) / 3; - textureData[k] = (c << 24) | (j2 << 16) | (j2 << 8) | j2; - } - else { - textureData[k] = (c << 24) | (j1 << 16) | (l1 << 8) | j2; - } +// } + textureData[k] = (c << 24) | (j1 << 16) | (l1 << 8) | j2; } } diff --git a/client/src/main/java/client/renderer/ticked/TextureFlamesFX2.java b/client/src/client/renderer/ticked/TextureFlamesFX2.java similarity index 72% rename from client/src/main/java/client/renderer/ticked/TextureFlamesFX2.java rename to client/src/client/renderer/ticked/TextureFlamesFX2.java index 89ede38..615af67 100755 --- a/client/src/main/java/client/renderer/ticked/TextureFlamesFX2.java +++ b/client/src/client/renderer/ticked/TextureFlamesFX2.java @@ -1,17 +1,11 @@ package client.renderer.ticked; public class TextureFlamesFX2 extends TextureFlamesFX1 { - public TextureFlamesFX2(boolean mono) + public TextureFlamesFX2() { - super(mono); int[] tex = new int[256]; for(int z = 0; z < 160; z++) { this.renderStep(tex); } } - - public TextureFlamesFX2() - { - this(false); - } } diff --git a/client/src/main/java/client/renderer/ticked/TextureLavaFX.java b/client/src/client/renderer/ticked/TextureLavaFX.java similarity index 100% rename from client/src/main/java/client/renderer/ticked/TextureLavaFX.java rename to client/src/client/renderer/ticked/TextureLavaFX.java diff --git a/client/src/main/java/client/renderer/ticked/TextureLavaFlowFX.java b/client/src/client/renderer/ticked/TextureLavaFlowFX.java similarity index 100% rename from client/src/main/java/client/renderer/ticked/TextureLavaFlowFX.java rename to client/src/client/renderer/ticked/TextureLavaFlowFX.java diff --git a/client/src/main/java/client/renderer/ticked/TextureWaterFX.java b/client/src/client/renderer/ticked/TextureWaterFX.java similarity index 87% rename from client/src/main/java/client/renderer/ticked/TextureWaterFX.java rename to client/src/client/renderer/ticked/TextureWaterFX.java index 7deb1c2..be5a276 100755 --- a/client/src/main/java/client/renderer/ticked/TextureWaterFX.java +++ b/client/src/client/renderer/ticked/TextureWaterFX.java @@ -68,10 +68,10 @@ public class TextureWaterFX extends TextureTicked f1 = 0.0F; } float f2 = f1 * f1; - int r = (int)(32F + f2 * 32F); - int g = (int)(50F + f2 * 64F); - int b = 255; - int a = (int)(146F + f2 * 50F); + int l1 = (int)(32F + f2 * 32F); + int j2 = (int)(50F + f2 * 64F); + int k2 = 255; + int l2 = (int)(146F + f2 * 50F); // if(flag) // { // int i3 = (l1 * 30 + j2 * 59 + k2 * 11) / 100; @@ -81,7 +81,7 @@ public class TextureWaterFX extends TextureTicked // j2 = j3; // k2 = k3; // } - textureData[i1] = (a << 24) | (r << 16) | (g << 8) | b; + textureData[i1] = (l2 << 24) | (l1 << 16) | (j2 << 8) | k2; } } diff --git a/client/src/main/java/client/renderer/ticked/TextureWaterFlowFX.java b/client/src/client/renderer/ticked/TextureWaterFlowFX.java similarity index 88% rename from client/src/main/java/client/renderer/ticked/TextureWaterFlowFX.java rename to client/src/client/renderer/ticked/TextureWaterFlowFX.java index b28f2c1..ebf64ef 100755 --- a/client/src/main/java/client/renderer/ticked/TextureWaterFlowFX.java +++ b/client/src/client/renderer/ticked/TextureWaterFlowFX.java @@ -67,11 +67,11 @@ public class TextureWaterFlowFX extends TextureTicked { f1 = 0.0F; } - float v = f1 * f1; - int r = (int)(32F + v * 32F); - int g = (int)(50F + v * 64F); - int b = 255; - int a = (int)(146F + v * 50F); + float f2 = f1 * f1; + int l1 = (int)(32F + f2 * 32F); + int j2 = (int)(50F + f2 * 64F); + int k2 = 255; + int l2 = (int)(146F + f2 * 50F); // if(flag) // { // int i3 = (l1 * 30 + j2 * 59 + k2 * 11) / 100; @@ -83,7 +83,7 @@ public class TextureWaterFlowFX extends TextureTicked // } textureData[(i1 & 0x0f) | ((i1 & 0xf0) * 2)] = textureData[((i1 & 0x0f) + 16) | ((i1 & 0xf0) * 2)] = textureData[(i1 & 0x0f) | (((i1 & 0xf0) + 256) * 2)] = textureData[((i1 & 0x0f) + 16) | (((i1 & 0xf0) + 256) * 2)] = - (a << 24) | (r << 16) | (g << 8) | b; + (l2 << 24) | (l1 << 16) | (j2 << 8) | k2; } } diff --git a/client/src/main/java/client/renderer/tileentity/TileEntityBannerRenderer.java b/client/src/client/renderer/tileentity/TileEntityBannerRenderer.java similarity index 100% rename from client/src/main/java/client/renderer/tileentity/TileEntityBannerRenderer.java rename to client/src/client/renderer/tileentity/TileEntityBannerRenderer.java diff --git a/client/src/main/java/client/renderer/tileentity/TileEntityChestRenderer.java b/client/src/client/renderer/tileentity/TileEntityChestRenderer.java similarity index 99% rename from client/src/main/java/client/renderer/tileentity/TileEntityChestRenderer.java rename to client/src/client/renderer/tileentity/TileEntityChestRenderer.java index 3e543fd..4fbb70f 100755 --- a/client/src/main/java/client/renderer/tileentity/TileEntityChestRenderer.java +++ b/client/src/client/renderer/tileentity/TileEntityChestRenderer.java @@ -6,7 +6,7 @@ import client.renderer.GlState; import client.renderer.model.ModelChest; import client.renderer.model.ModelLargeChest; import common.block.Block; -import common.block.tech.BlockChest; +import common.block.BlockChest; import common.tileentity.TileEntityChest; diff --git a/client/src/client/renderer/tileentity/TileEntityItemStackRenderer.java b/client/src/client/renderer/tileentity/TileEntityItemStackRenderer.java new file mode 100755 index 0000000..df617b0 --- /dev/null +++ b/client/src/client/renderer/tileentity/TileEntityItemStackRenderer.java @@ -0,0 +1,76 @@ +package client.renderer.tileentity; + +import org.lwjgl.opengl.GL11; + +import client.renderer.GlState; +import common.block.Block; +import common.init.Blocks; +import common.init.Items; +import common.item.ItemStack; +import common.tileentity.TileEntityBanner; +import common.tileentity.TileEntityChest; +import common.tileentity.TileEntitySkull; +import common.util.Facing; + +public class TileEntityItemStackRenderer +{ + public static TileEntityItemStackRenderer instance = new TileEntityItemStackRenderer(); + private TileEntityChest field_147717_b = new TileEntityChest(0); + private TileEntityChest field_147718_c = new TileEntityChest(1); +// private TileEntityWarpChest warpChest = new TileEntityWarpChest(); + private TileEntityBanner banner = new TileEntityBanner(); + private TileEntitySkull skull = new TileEntitySkull(); + + public void renderByItem(ItemStack itemStackIn) + { + if (itemStackIn.getItem() == Items.banner) + { + this.banner.setItemValues(itemStackIn); + TileEntityRendererDispatcher.instance.renderTileEntityAt(this.banner, 0.0D, 0.0D, 0.0D, 0.0F); + } + else if (itemStackIn.getItem() == Items.skull) + { +// String user = null; +// +// if (itemStackIn.hasTagCompound()) +// { +// NBTTagCompound nbttagcompound = itemStackIn.getTagCompound(); +// +// if (nbttagcompound.hasKey("SkullOwner", 8) && nbttagcompound.getString("SkullOwner").length() > 0) +// { +// user = nbttagcompound.getString("SkullOwner"); +// } +// } + + if (TileEntitySkullRenderer.instance != null) + { + GL11.glPushMatrix(); + GL11.glTranslatef(-0.5F, 0.0F, -0.5F); + GL11.glScalef(2.0F, 2.0F, 2.0F); + boolean flag = GlState.isCullEnabled(); + GlState.disableCull(); + TileEntitySkullRenderer.instance.renderSkull(0.0F, 0.0F, 0.0F, Facing.UP, 0.0F, -1); + if(flag) + GlState.enableCull(); + GL11.glPopMatrix(); + } + } + else + { + Block block = itemStackIn.getItem().getBlock(); + +// if (block == Blocks.warp_chest) +// { +// TileEntityRendererDispatcher.instance.renderTileEntityAt(this.warpChest, 0.0D, 0.0D, 0.0D, 0.0F); +// } + if (block == Blocks.trapped_chest) + { + TileEntityRendererDispatcher.instance.renderTileEntityAt(this.field_147718_c, 0.0D, 0.0D, 0.0D, 0.0F); + } + else + { + TileEntityRendererDispatcher.instance.renderTileEntityAt(this.field_147717_b, 0.0D, 0.0D, 0.0D, 0.0F); + } + } + } +} diff --git a/client/src/client/renderer/tileentity/TileEntityMobSpawnerRenderer.java b/client/src/client/renderer/tileentity/TileEntityMobSpawnerRenderer.java new file mode 100755 index 0000000..ae555c7 --- /dev/null +++ b/client/src/client/renderer/tileentity/TileEntityMobSpawnerRenderer.java @@ -0,0 +1,38 @@ +package client.renderer.tileentity; + +import org.lwjgl.opengl.GL11; + +import client.Client; +import common.entity.Entity; +import common.tileentity.TileEntityMobSpawner; + +public class TileEntityMobSpawnerRenderer extends TileEntitySpecialRenderer +{ + public void renderTileEntityAt(TileEntityMobSpawner te, double x, double y, double z, float partialTicks, int destroyStage) + { + GL11.glPushMatrix(); + GL11.glTranslatef((float)x + 0.5F, (float)y, (float)z + 0.5F); + renderMob(te, x, y, z, partialTicks); + GL11.glPopMatrix(); + } + + /** + * Render the mob inside the mob spawner. + */ + public static void renderMob(TileEntityMobSpawner mobSpawnerLogic, double posX, double posY, double posZ, float partialTicks) + { + Entity entity = mobSpawnerLogic.createRenderEntity(mobSpawnerLogic.getWorld()); + + if (entity != null) + { + float f = 0.4375F; + GL11.glTranslatef(0.0F, 0.4F, 0.0F); + GL11.glRotatef((float)(mobSpawnerLogic.getPrevMobRotation() + (mobSpawnerLogic.getMobRotation() - mobSpawnerLogic.getPrevMobRotation()) * (double)partialTicks) * 10.0F, 0.0F, 1.0F, 0.0F); + GL11.glRotatef(-30.0F, 1.0F, 0.0F, 0.0F); + GL11.glTranslatef(0.0F, -0.4F, 0.0F); + GL11.glScalef(f, f, f); + entity.setLocationAndAngles(posX, posY, posZ, 0.0F, 0.0F); + Client.CLIENT.getRenderManager().renderEntity(entity, 0.0D, 0.0D, 0.0D, partialTicks); + } + } +} diff --git a/client/src/main/java/client/renderer/tileentity/TileEntityPistonRenderer.java b/client/src/client/renderer/tileentity/TileEntityPistonRenderer.java similarity index 95% rename from client/src/main/java/client/renderer/tileentity/TileEntityPistonRenderer.java rename to client/src/client/renderer/tileentity/TileEntityPistonRenderer.java index f40c247..ce055f1 100755 --- a/client/src/main/java/client/renderer/tileentity/TileEntityPistonRenderer.java +++ b/client/src/client/renderer/tileentity/TileEntityPistonRenderer.java @@ -11,9 +11,10 @@ import client.renderer.RenderBuffer; import client.renderer.Tessellator; import client.renderer.texture.TextureMap; import common.block.Block; -import common.block.tech.BlockPistonBase; -import common.block.tech.BlockPistonHead; +import common.block.BlockPistonBase; +import common.block.BlockPistonHead; import common.init.Blocks; +import common.material.Material; import common.tileentity.TileEntityPiston; import common.util.BlockPos; import common.world.State; @@ -29,7 +30,7 @@ public class TileEntityPistonRenderer extends TileEntitySpecialRenderer tileentityspecialrenderer : this.mapSpecialRenderers.values()) diff --git a/client/src/main/java/client/renderer/tileentity/TileEntitySignRenderer.java b/client/src/client/renderer/tileentity/TileEntitySignRenderer.java similarity index 97% rename from client/src/main/java/client/renderer/tileentity/TileEntitySignRenderer.java rename to client/src/client/renderer/tileentity/TileEntitySignRenderer.java index 8f3ed06..22d543c 100755 --- a/client/src/main/java/client/renderer/tileentity/TileEntitySignRenderer.java +++ b/client/src/client/renderer/tileentity/TileEntitySignRenderer.java @@ -2,6 +2,7 @@ package client.renderer.tileentity; import org.lwjgl.opengl.GL11; +import client.gui.Font; import client.renderer.Drawing; import client.renderer.GlState; import client.renderer.model.ModelSign; @@ -102,7 +103,7 @@ public class TileEntitySignRenderer extends TileEntitySpecialRenderer +{ + private static final String TEXTURE_SKULL = "textures/entity/skull.png"; + public static TileEntitySkullRenderer instance; + + private final ModelHumanoidHead humanoidHead = new ModelHumanoidHead(); + + public void renderTileEntityAt(TileEntitySkull te, double x, double y, double z, float partialTicks, int destroyStage) + { + Facing enumfacing = Facing.getFront(te.getBlockMetadata() & 7); + this.renderSkull((float)x, (float)y, (float)z, enumfacing, (float)(te.getSkullRotation() * 360) / 16.0F, destroyStage); + } + + public void setRendererDispatcher(TileEntityRendererDispatcher rendererDispatcherIn) + { + super.setRendererDispatcher(rendererDispatcherIn); + instance = this; + } + + public void renderSkull(float x, float y, float z, Facing dir, float rot, int destroyStage) + { +// ModelBase modelbase = this.skeletonHead; + + if (destroyStage >= 0) + { + this.bindTexture(DESTROY_STAGES[destroyStage]); + GL11.glMatrixMode(GL11.GL_TEXTURE); + GL11.glPushMatrix(); + GL11.glScalef(4.0F, 2.0F, 1.0F); + GL11.glTranslatef(0.0625F, 0.0625F, 0.0625F); + GL11.glMatrixMode(GL11.GL_MODELVIEW); + } + else + { +// switch (p_180543_6_) +// { +// case 0: +// default: +// this.bindTexture(SKELETON_TEXTURES); +// break; +// +// case 1: +// this.bindTexture(WITHER_SKELETON_TEXTURES); +// break; +// +// case 2: +// this.bindTexture(ZOMBIE_TEXTURES); +// modelbase = this.humanoidHead; +// break; +// +// case 3: +// modelbase = this.humanoidHead; +// String tex = TEXTURE_SKULL; // EntitySkinManager.TEXTURE_DEF; + +// if (user != null && EntityTexManager.getModel(user) == ModelType.HUMANOID) +// { +// tex = EntityTexManager.getSkin(user, ModelType.HUMANOID); +// } + + this.bindTexture(TEXTURE_SKULL); +// break; +// +// case 4: +// this.bindTexture(CREEPER_TEXTURES); +// } + } + + GL11.glPushMatrix(); + GlState.disableCull(); + + if (dir != Facing.UP) + { + switch (dir) + { + case NORTH: + GL11.glTranslatef(x + 0.5F, y + 0.25F, z + 0.74F); + break; + + case SOUTH: + GL11.glTranslatef(x + 0.5F, y + 0.25F, z + 0.26F); + rot = 180.0F; + break; + + case WEST: + GL11.glTranslatef(x + 0.74F, y + 0.25F, z + 0.5F); + rot = 270.0F; + break; + + case EAST: + default: + GL11.glTranslatef(x + 0.26F, y + 0.25F, z + 0.5F); + rot = 90.0F; + } + } + else + { + GL11.glTranslatef(x + 0.5F, y, z + 0.5F); + } + + float f = 0.0625F; + GlState.enableRescaleNormal(); + GL11.glScalef(-1.0F, -1.0F, 1.0F); + GlState.enableAlpha(); + this.humanoidHead.render(null, 0.0F, 0.0F, 0.0F, rot, 0.0F, f); + GL11.glPopMatrix(); + + if (destroyStage >= 0) + { + GL11.glMatrixMode(GL11.GL_TEXTURE); + GL11.glPopMatrix(); + GL11.glMatrixMode(GL11.GL_MODELVIEW); + } + } +} diff --git a/client/src/main/java/client/renderer/tileentity/TileEntitySpecialRenderer.java b/client/src/client/renderer/tileentity/TileEntitySpecialRenderer.java similarity index 100% rename from client/src/main/java/client/renderer/tileentity/TileEntitySpecialRenderer.java rename to client/src/client/renderer/tileentity/TileEntitySpecialRenderer.java diff --git a/client/src/main/java/client/vars/BaseVar.java b/client/src/client/vars/BaseVar.java similarity index 100% rename from client/src/main/java/client/vars/BaseVar.java rename to client/src/client/vars/BaseVar.java diff --git a/client/src/main/java/client/vars/BoolVar.java b/client/src/client/vars/BoolVar.java similarity index 100% rename from client/src/main/java/client/vars/BoolVar.java rename to client/src/client/vars/BoolVar.java diff --git a/client/src/main/java/client/vars/CVar.java b/client/src/client/vars/CVar.java similarity index 100% rename from client/src/main/java/client/vars/CVar.java rename to client/src/client/vars/CVar.java diff --git a/client/src/main/java/client/vars/CVarCategory.java b/client/src/client/vars/CVarCategory.java similarity index 100% rename from client/src/main/java/client/vars/CVarCategory.java rename to client/src/client/vars/CVarCategory.java diff --git a/client/src/main/java/client/vars/ColorVar.java b/client/src/client/vars/ColorVar.java similarity index 95% rename from client/src/main/java/client/vars/ColorVar.java rename to client/src/client/vars/ColorVar.java index be15feb..9f72dc6 100644 --- a/client/src/main/java/client/vars/ColorVar.java +++ b/client/src/client/vars/ColorVar.java @@ -39,8 +39,8 @@ public class ColorVar extends IntVar { throw new UnsupportedOperationException("Kann keinen Schieberegler für Farben erstellen"); } - public Label label(int x, int y, int w) { - return new Label(x, y, w, this.display); + public Label label(int x, int y, int w, int h) { + return new Label(x, y, w, h, this.display); } public client.gui.element.Field editor(int x, int y, int w, int h) { diff --git a/client/src/main/java/client/vars/EnumVar.java b/client/src/client/vars/EnumVar.java similarity index 100% rename from client/src/main/java/client/vars/EnumVar.java rename to client/src/client/vars/EnumVar.java diff --git a/client/src/main/java/client/vars/FloatVar.java b/client/src/client/vars/FloatVar.java similarity index 100% rename from client/src/main/java/client/vars/FloatVar.java rename to client/src/client/vars/FloatVar.java diff --git a/client/src/main/java/client/vars/IntVar.java b/client/src/client/vars/IntVar.java similarity index 100% rename from client/src/main/java/client/vars/IntVar.java rename to client/src/client/vars/IntVar.java diff --git a/client/src/main/java/client/vars/StringVar.java b/client/src/client/vars/StringVar.java similarity index 100% rename from client/src/main/java/client/vars/StringVar.java rename to client/src/client/vars/StringVar.java diff --git a/client/src/main/java/client/vars/Variable.java b/client/src/client/vars/Variable.java similarity index 100% rename from client/src/main/java/client/vars/Variable.java rename to client/src/client/vars/Variable.java diff --git a/client/src/main/java/client/window/Bind.java b/client/src/client/window/Bind.java similarity index 98% rename from client/src/main/java/client/window/Bind.java rename to client/src/client/window/Bind.java index ce4dfd2..1ab509f 100644 --- a/client/src/main/java/client/window/Bind.java +++ b/client/src/client/window/Bind.java @@ -13,7 +13,7 @@ public enum Bind implements Identifyable, CVar { LEFT("left", "Nach links", Keysym.A), BACKWARD("backward", "Rückwärts", Keysym.S), RIGHT("right", "Nach rechts", Keysym.D), - UP("up", "Aufwärts, Sprung", Keysym.SPACE), + UP("up", "Aufwärts, Springen", Keysym.SPACE), DOWN("down", "Abwärts, Langsam", Keysym.LEFT_CONTROL), FAST("fast", "Schneller", Keysym.LEFT_SHIFT), INVENTORY("inventory", "Inventar", Keysym.E), @@ -34,7 +34,7 @@ public enum Bind implements Identifyable, CVar { CONSOLE("console", "Konsole", Keysym.F1), COMMAND("command", "Befehl / Chat", Keysym.C), INFO("info", "Infos einblenden", Keysym.TAB), - PERSPECTIVE("perspective", "Perspektive", Keysym.F5), + PERSPECTIVE("perspective", "Perspektive ändern", Keysym.F5), ZOOM("zoom", "Kamera zoomen", Keysym.Y), MENU("menu", "Menü", Keysym.ESCAPE), SCREENSHOT("screenshot", "Bildschirmfoto", Keysym.F10), diff --git a/client/src/main/java/client/window/Button.java b/client/src/client/window/Button.java similarity index 87% rename from client/src/main/java/client/window/Button.java rename to client/src/client/window/Button.java index a38c696..5286196 100644 --- a/client/src/main/java/client/window/Button.java +++ b/client/src/client/window/Button.java @@ -5,9 +5,9 @@ import client.Client; public enum Button implements Input { MOUSE_LEFT("lmb", "Linke Maustaste"), MOUSE_RIGHT("rmb", "Rechte Maustaste"), - MOUSE_MIDDLE("mmb", "Mausrad-Taste"), - MOUSE_BTN_X("xmb", "Maus Seite 1"), - MOUSE_BTN_Y("ymb", "Maus Seite 2"), + MOUSE_MIDDLE("mmb", "Mittlere Maustaste"), + MOUSE_BTN_X("xmb", "Maustaste Seite 1"), + MOUSE_BTN_Y("ymb", "Maustaste Seite 2"), MOUSE_BTN_A("m6", "Maustaste 6"), MOUSE_BTN_B("m7", "Maustaste 7"), MOUSE_BTN_C("m8", "Maustaste 8"); diff --git a/client/src/main/java/client/window/DisplayMode.java b/client/src/client/window/DisplayMode.java similarity index 56% rename from client/src/main/java/client/window/DisplayMode.java rename to client/src/client/window/DisplayMode.java index d9dfb47..9ab016f 100644 --- a/client/src/main/java/client/window/DisplayMode.java +++ b/client/src/client/window/DisplayMode.java @@ -1,6 +1,18 @@ package client.window; -public record DisplayMode(int width, int height, int refresh) { +public class DisplayMode { + public static final int VID_MODES = 28; + + public final int width; + public final int height; + public final int refresh; + + public DisplayMode(int width, int height, int refresh) { + this.width = width; + this.height = height; + this.refresh = refresh; + } + public String toString() { return String.format("%dx%d @ %d Hz", this.width, this.height, this.refresh); } diff --git a/client/src/main/java/client/window/Input.java b/client/src/client/window/Input.java similarity index 100% rename from client/src/main/java/client/window/Input.java rename to client/src/client/window/Input.java diff --git a/client/src/main/java/client/window/KeyEvent.java b/client/src/client/window/KeyEvent.java similarity index 100% rename from client/src/main/java/client/window/KeyEvent.java rename to client/src/client/window/KeyEvent.java diff --git a/client/src/main/java/client/window/Keysym.java b/client/src/client/window/Keysym.java similarity index 100% rename from client/src/main/java/client/window/Keysym.java rename to client/src/client/window/Keysym.java diff --git a/client/src/main/java/client/window/Wheel.java b/client/src/client/window/Wheel.java similarity index 87% rename from client/src/main/java/client/window/Wheel.java rename to client/src/client/window/Wheel.java index 1fc5c26..3c4b6bd 100644 --- a/client/src/main/java/client/window/Wheel.java +++ b/client/src/client/window/Wheel.java @@ -3,8 +3,8 @@ package client.window; import client.Client; public enum Wheel implements Input { - SCROLL_UP("scrup", "Mausrad oben"), - SCROLL_DOWN("scrdn", "Mausrad unten"), + SCROLL_UP("scrup", "Mausrad aufwärts"), + SCROLL_DOWN("scrdn", "Mausrad abwärts"), SCROLL_LEFT("scrl", "Mausrad links"), SCROLL_RIGHT("scrr", "Mausrad rechts"); diff --git a/client/src/main/java/client/window/Window.java b/client/src/client/window/Window.java similarity index 95% rename from client/src/main/java/client/window/Window.java rename to client/src/client/window/Window.java index a0c5b90..515c79c 100644 --- a/client/src/main/java/client/window/Window.java +++ b/client/src/client/window/Window.java @@ -43,7 +43,6 @@ import static org.lwjgl.glfw.GLFW.glfwSetWindowPos; import static org.lwjgl.glfw.GLFW.glfwSetWindowPosCallback; import static org.lwjgl.glfw.GLFW.glfwSetWindowRefreshCallback; import static org.lwjgl.glfw.GLFW.glfwSetWindowSize; -import static org.lwjgl.glfw.GLFW.glfwSetWindowSizeLimits; import static org.lwjgl.glfw.GLFW.glfwSetWindowTitle; import static org.lwjgl.glfw.GLFW.glfwShowWindow; import static org.lwjgl.glfw.GLFW.glfwSwapBuffers; @@ -213,7 +212,7 @@ public abstract class Window { window = NULL; } } - public static void initWindow(int sx, int sy, int wx, int wy, int mx, int my) { + public static void initWindow(int sx, int sy, int wx, int wy) { if(window == NULL) return; long monitor = glfwGetPrimaryMonitor(); @@ -222,8 +221,8 @@ public abstract class Window { int[] y = new int[1]; if(monitor != NULL) glfwGetMonitorPos(monitor, x, y); - int xsize = (mode != null && mode.width() >= mx && wx > mode.width()) ? mode.width() : wx; - int ysize = (mode != null && mode.height() >= my && wy > mode.height()) ? mode.height() : wy; + int xsize = (mode != null && wx > mode.width()) ? mode.width() : wx; + int ysize = (mode != null && wy > mode.height()) ? mode.height() : wy; int xpos = x[0] + (mode != null ? mode.width() / 2 - xsize / 2 : 0); int ypos = y[0] + (mode != null ? mode.height() / 2 - ysize / 2 : 0); xsize = xsize < 1 ? 1 : xsize; @@ -237,7 +236,6 @@ public abstract class Window { ysize = wy; } glfwSetWindowSize(window, xsize, ysize); - glfwSetWindowSizeLimits(window, mx, my, GLFW_DONT_CARE, GLFW_DONT_CARE); glfwSetWindowPos(window, xpos, ypos); // wcf_windowed(win, xpos, ypos, xsize, ysize); // wcf_fullscreen does not move while hidden ... @@ -245,7 +243,6 @@ public abstract class Window { glfwShowWindow(window); // wcf_show(win, 1); // wcf_limits(win, 1, 1, -1, -1); - glfwSetWindowMonitor(window, NULL, xpos, ypos, xsize, ysize, GLFW_DONT_CARE); // set position twice to work around bugs in some tiling window managers } public static WindowEvent[] poll() { diff --git a/client/src/main/java/client/window/WindowAction.java b/client/src/client/window/WindowAction.java similarity index 100% rename from client/src/main/java/client/window/WindowAction.java rename to client/src/client/window/WindowAction.java diff --git a/client/src/client/window/WindowEvent.java b/client/src/client/window/WindowEvent.java new file mode 100644 index 0000000..294b005 --- /dev/null +++ b/client/src/client/window/WindowEvent.java @@ -0,0 +1,13 @@ +package client.window; + +public class WindowEvent { + public final WindowAction action; + public final int param1; + public final int param2; + + public WindowEvent(WindowAction action, int p1, int p2) { + this.action = action; + this.param1 = p1; + this.param2 = p2; + } +} diff --git a/client/src/client/world/EmptyChunk.java b/client/src/client/world/EmptyChunk.java new file mode 100755 index 0000000..6bec1b5 --- /dev/null +++ b/client/src/client/world/EmptyChunk.java @@ -0,0 +1,87 @@ +package client.world; + +import java.util.List; +import java.util.function.Predicate; + +import common.block.Block; +import common.entity.Entity; +import common.init.Blocks; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.world.Chunk; + +public class EmptyChunk extends Chunk { + public EmptyChunk(WorldClient world) { + super(world, 0, 0); + } + + public Block getBlock(BlockPos pos) { + return Blocks.air; + } + + public int getOpacity(BlockPos pos) { + return 255; + } + + public int getMeta(BlockPos pos) { + return 0; + } + + public int getLight(BlockPos pos) { + return 0; + } + + public void setLight(BlockPos pos, int value) { + } + + public int getLightSub(BlockPos pos, int amount) { + return 0; + } + + public void addEntity(Entity entity) { + } + + public void removeEntity(Entity entity) { + } + + public TileEntity getTileEntity(BlockPos pos, TileEntity.EnumCreateEntityType type) { + return null; + } + + public void addTileEntity(TileEntity tile) { + } + + public void addTileEntity(BlockPos pos, TileEntity tile) { + } + + public void removeTileEntity(BlockPos pos) { + } + + public void onChunkLoad() { + } + + public void onChunkUnload() { + } + + public void setModified() { + } + + public void getEntities(Entity exclude, BoundingBox bb, List list, Predicate pred) { + } + + public void getEntities(Class clazz, BoundingBox bb, List list, Predicate pred) { + } + + public boolean isDirty() { + return false; + } + + public boolean isEmpty() { + return true; + } + + public boolean isEmpty(int bottom, int top) { + return true; + } +} diff --git a/client/src/main/java/client/world/WorldClient.java b/client/src/client/world/WorldClient.java similarity index 86% rename from client/src/main/java/client/world/WorldClient.java rename to client/src/client/world/WorldClient.java index dbfdf90..096ad5c 100755 --- a/client/src/main/java/client/world/WorldClient.java +++ b/client/src/client/world/WorldClient.java @@ -1,64 +1,62 @@ package client.world; import java.util.List; +import java.util.Map; import java.util.Set; import client.Client; import client.renderer.particle.EntityFX; import client.renderer.particle.EntityFirework; -import common.biome.Biome; import common.block.Block; import common.collect.Lists; +import common.collect.Maps; import common.collect.Sets; import common.dimension.Dimension; import common.entity.Entity; import common.entity.item.EntityCart; import common.entity.npc.EntityNPC; import common.init.BlockRegistry; -import common.init.Blocks; import common.init.ItemRegistry; import common.init.Items; import common.init.SoundEvent; import common.item.ItemDye; import common.log.Log; +import common.material.Material; import common.model.ParticleType; +import common.nbt.NBTTagCompound; import common.rng.Random; import common.sound.MovingSoundMinecart; import common.sound.PositionedSound; -import common.tags.TagObject; import common.tileentity.TileEntity; import common.util.BlockPos; import common.util.ChunkPos; import common.util.ExtMath; -import common.util.LongHashMap; import common.util.Vec3; import common.util.BlockPos.MutableBlockPos; +import common.world.Chunk; import common.world.AWorldClient; import common.world.State; -import common.world.World; public class WorldClient extends AWorldClient { private static final int DISPLAY_RANGE = 16; private final Client gm; - private final ChunkClient emptyChunk; private final Set entityList = Sets.newHashSet(); private final Set spawnQueue = Sets.newHashSet(); private final Set previousActive = Sets.newHashSet(); - private final LongHashMap chunkMapping = new LongHashMap(); - private final List chunkListing = Lists.newArrayList(); - private final Set emptyChunkListing = Sets.newHashSet(); - private final Set nextEmptyChunkListing = Sets.newHashSet(); + private final Map chunkMapping = Maps.newHashMap(); + private final List chunkListing = Lists.newArrayList(); + private final Chunk blankChunk = new EmptyChunk(this); // public final Profiler profiler; protected int lastLightning; protected Vec3 lightColor = new Vec3(0xffffff); + protected boolean exterminated; - public WorldClient(Client gm, Dimension dim) + public WorldClient(Client gm, boolean debug, Dimension dim) { - super(dim); + super(dim, debug); this.gm = gm; - this.emptyChunk = new ChunkEmpty(this, this.gm.debugWorld); this.calculateInitialSkylight(); this.calculateInitialWeather(); this.setGravity(this.gm.gravity); @@ -66,42 +64,8 @@ public class WorldClient extends AWorldClient // this.setDifficulty(this.gm.difficulty); } - private void markReload(int cx, int cz, int range) { - this.nextEmptyChunkListing.clear(); - for(int x = cx - range; x <= cx + range; x++) { - for(int z = cz - range; z <= cz + range; z++) { - long id = LongHashMap.packInt(x, z); - if(this.chunkMapping.getValueByKey(id) != null) { - if(this.emptyChunkListing.contains(id)) { - this.emptyChunkListing.remove(id); - this.nextEmptyChunkListing.add(id); - } - continue; - } - this.chunkMapping.add(id, this.emptyChunk); - this.emptyChunkListing.remove(id); - this.nextEmptyChunkListing.add(id); - this.markBlockRangeForRenderUpdate(x << 4, -World.MAX_SIZE_Y, z << 4, (x << 4) + 15, World.MAX_SIZE_Y, (z << 4) + 15); - } - } - for(Long id : this.emptyChunkListing) { - this.chunkMapping.remove(id); - int x = LongHashMap.getX(id); - int z = LongHashMap.getZ(id); - this.markBlockRangeForRenderUpdate(x << 4, -World.MAX_SIZE_Y, z << 4, (x << 4) + 15, World.MAX_SIZE_Y, (z << 4) + 15); - } - this.emptyChunkListing.clear(); - this.emptyChunkListing.addAll(this.nextEmptyChunkListing); - } - - public void markReload() { - if(this.gm.player != null && !this.gm.charEditor) - this.markReload((int)this.gm.player.posX >> 4, (int)this.gm.player.posZ >> 4, this.gm.renderDistance + 4); - } - public void tick() { - this.markReload(); // this.info.tick(); if (this.gm.dayCycle) @@ -120,13 +84,13 @@ public class WorldClient extends AWorldClient } } long time = System.currentTimeMillis(); - for (ChunkClient chunk : this.chunkListing) + for (Chunk chunk : this.chunkListing) { - chunk.update(System.currentTimeMillis() - time > 5L); + chunk.update(); } if (System.currentTimeMillis() - time > 100L) { - Log.TICK.warn("Render-Chunk-Tick dauerte " + (System.currentTimeMillis() - time) + " ms"); + Log.JNI.info("Warnung: Render-Chunk-Tick dauerte " + (System.currentTimeMillis() - time) + " ms"); } this.updateBlocks(); } @@ -149,7 +113,7 @@ public class WorldClient extends AWorldClient { int j = chunkcoordintpair.x * 16; int k = chunkcoordintpair.z * 16; - ChunkClient chunk = this.getChunk(chunkcoordintpair.x, chunkcoordintpair.z); + Chunk chunk = this.getChunk(chunkcoordintpair.x, chunkcoordintpair.z); chunk.enqueueRelight(); this.previousActive.add(chunkcoordintpair); ++i; @@ -164,28 +128,30 @@ public class WorldClient extends AWorldClient public void doPreChunk(int x, int z, boolean load) { - long id = LongHashMap.packInt(x, z); + ChunkPos pos = new ChunkPos(x, z); if (load) { - if(this.chunkMapping.getValueByKey(id) != null) + if(this.chunkMapping.get(pos) != null) this.doPreChunk(x, z, false); - ChunkClient chunk = new ChunkClient(this, x, z); - this.chunkMapping.add(id, chunk); + Chunk chunk = new Chunk(this, x, z); + this.chunkMapping.put(pos, chunk); this.chunkListing.add(chunk); - chunk.setLoaded(); + chunk.setLoaded(true); } else { - ChunkClient chunk = this.getChunk(x, z); - chunk.onChunkUnload(); - this.chunkMapping.remove(id); + Chunk chunk = this.getChunk(x, z); + if (!chunk.isEmpty()) + { + chunk.onChunkUnload(); + } + this.chunkMapping.remove(pos); this.chunkListing.remove(chunk); - this.emptyChunkListing.remove(id); } if (!load) { - this.markBlockRangeForRenderUpdate(x * 16, -World.MAX_SIZE_Y, z * 16, x * 16 + 15, World.MAX_SIZE_Y, z * 16 + 15); + this.markBlockRangeForRenderUpdate(x * 16, 0, z * 16, x * 16 + 15, 512, z * 16 + 15); } } @@ -382,35 +348,20 @@ public class WorldClient extends AWorldClient // } } - public void makeFireworks(double x, double y, double z, double motionX, double motionY, double motionZ, TagObject compund) + public void makeFireworks(double x, double y, double z, double motionX, double motionY, double motionZ, NBTTagCompound compund) { this.gm.effectRenderer.addEffect(new EntityFirework.StarterFX(this.gm.world, x, y, z, motionX, motionY, motionZ, this.gm.effectRenderer, compund)); } - public ChunkClient getChunk(int x, int z) + public Chunk getChunk(int x, int z) { - ChunkClient chunk = this.chunkMapping.getValueByKey(LongHashMap.packInt(x, z)); - return chunk == null ? this.emptyChunk : chunk; + Chunk chunk = this.chunkMapping.get(new ChunkPos(x, z)); + return chunk == null ? this.blankChunk : chunk; } - - public ChunkClient getChunk(BlockPos pos) { - return this.getChunk(pos.getX() >> 4, pos.getZ() >> 4); - } - - public Biome getBiomeGenForCoords(BlockPos pos) { - if(this.isBlockLoaded(pos)) - return this.getChunk(pos).getBiome(pos); - else - return Biome.DEF_BIOME; - } - - protected boolean isLoaded(int x, int z, boolean allowEmpty) { - return allowEmpty || !this.getChunk(x, z).isDummy(); - } public String getInfo() { - return "Chunk-Cache: M " + this.chunkMapping.getNumHashElements() + ", L " + this.chunkListing.size(); + return "Chunk-Cache: M " + this.chunkMapping.size() + ", L " + this.chunkListing.size(); } public void playSound(SoundEvent sound, double x, double y, double z, float volume) @@ -638,7 +589,7 @@ public class WorldClient extends AWorldClient case 2001: Block block = BlockRegistry.getBlockById(data & 4095); - if (block != Blocks.air) + if (block.getMaterial() != Material.air) { this.gm.getSoundManager().playSound(new PositionedSound(block.sound.getBreakSound(), 1.0F, /* block.sound.getFrequency() * 0.8F, */ (float)blockPosIn.getX() + 0.5F, (float)blockPosIn.getY() + 0.5F, (float)blockPosIn.getZ() + 0.5F)); } @@ -695,6 +646,18 @@ public class WorldClient extends AWorldClient this.playSoundAtPos(blockPosIn, SoundEvent.GLASS, 1.0F); break; + case 2004: + for (int k = 0; k < 20; ++k) + { + double d3 = (double)blockPosIn.getX() + 0.5D + ((double)this.rand.floatv() - 0.5D) * 2.0D; + double d5 = (double)blockPosIn.getY() + 0.5D + ((double)this.rand.floatv() - 0.5D) * 2.0D; + double d7 = (double)blockPosIn.getZ() + 0.5D + ((double)this.rand.floatv() - 0.5D) * 2.0D; + this.spawnParticle(ParticleType.SMOKE_NORMAL, d3, d5, d7, 0.0D, 0.0D, 0.0D); + this.spawnParticle(ParticleType.FLAME, d3, d5, d7, 0.0D, 0.0D, 0.0D); + } + + return; + case 2005: ItemDye.spawnBonemealParticles(this, blockPosIn, data); } @@ -796,19 +759,16 @@ public class WorldClient extends AWorldClient } public Vec3 getSkyColor(Entity entity, float partial) { - BlockPos pos = new BlockPos(ExtMath.floord(entity.posX), ExtMath.floord(entity.posY), - ExtMath.floord(entity.posZ)); - Biome biome = this.getBiomeGenForCoords(pos); Vec3 vec; - if(biome.skyColor != 0xffffffff) - vec = new Vec3(biome.skyColor); + if(this.exterminated) + vec = new Vec3(0x101010); else vec = new Vec3(this.dimension.getSkyColor()); if(this.dimension.getType().days) { float mult = ExtMath.clampf(ExtMath.cos(this.getCelestialAngle(partial) * (float)Math.PI * 2.0F) * 2.0F + 0.5F, 0.0F, 1.0F); if(this.dimension.getSkyColor() == 0xffffffff) { - float temp = ExtMath.clampf(((biome.getTemperature(pos) + 14.0f) / 40.0f + 0.15f) / 3.0F, + float temp = ExtMath.clampf(((0.0f /* temp */ + 14.0f) / 40.0f + 0.15f) / 3.0F, -1.0F, 1.0F); Vec3 sky = new Vec3(hsvToRGB(0.62222224F - temp * 0.05F, 0.5F + temp * 0.1F, 1.0F)); vec = new Vec3(vec.xCoord * sky.xCoord * mult, vec.yCoord * sky.yCoord * mult, vec.zCoord * sky.zCoord * mult); @@ -854,10 +814,8 @@ public class WorldClient extends AWorldClient public Vec3 getCloudColour(Entity entity, float partialTicks) { Vec3 color = new Vec3(this.dimension.getCloudColor()); - Biome biome = this.getBiomeGenForCoords(new BlockPos(ExtMath.floord(entity.posX), ExtMath.floord(entity.posY), - ExtMath.floord(entity.posZ))); - if(biome.cloudColor != 0xffffffff) - color = new Vec3(biome.cloudColor); + if(this.exterminated) + color = new Vec3(0x000000); float r = (float)color.xCoord; float g = (float)color.yCoord; float b = (float)color.zCoord; @@ -893,10 +851,8 @@ public class WorldClient extends AWorldClient public Vec3 getFogColor(Entity entity, float partialTicks) { Vec3 color = new Vec3(this.dimension.getFogColor()); - Biome biome = this.getBiomeGenForCoords(new BlockPos(ExtMath.floord(entity.posX), ExtMath.floord(entity.posY), - ExtMath.floord(entity.posZ))); - if(biome.fogColor != 0xffffffff) - color = new Vec3(biome.fogColor); + if(this.exterminated) + color = new Vec3(0x303030); if(!this.dimension.getType().days) return color; float sun = ExtMath.clampf(ExtMath.cos(this.getCelestialAngle(partialTicks) * (float)Math.PI * 2.0F) * 2.0F + 0.5F, @@ -965,4 +921,16 @@ public class WorldClient extends AWorldClient public String getDebugLoadedEntities() { return "" + this.entities.size(); } + + public boolean hasNoChunks() { + return this.chunkListing.isEmpty(); + } + + public void setExterminated(boolean exterminated) { + this.exterminated = exterminated; + } + + public boolean isExterminated() { + return this.exterminated; + } } diff --git a/client/src/main/java/client/gui/GuiConnect.java b/client/src/main/java/client/gui/GuiConnect.java deleted file mode 100644 index a744c40..0000000 --- a/client/src/main/java/client/gui/GuiConnect.java +++ /dev/null @@ -1,379 +0,0 @@ -package client.gui; - -import java.io.File; -import java.security.KeyPair; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Date; - -import client.gui.element.ActButton; -import client.gui.element.ButtonCallback; -import client.gui.element.GuiList; -import client.gui.element.ListEntry; -import client.gui.element.NavButton; -import client.gui.element.PressType; -import client.renderer.Drawing; -import client.util.FileUtils; -import common.color.TextColor; -import common.log.Log; -import common.network.IPlayer; -import common.util.EncryptUtil; -import common.util.Pair; -import common.util.Util; - -public class GuiConnect extends GuiList implements ButtonCallback { - public class ServerInfo implements Comparable, ListEntry { - private final boolean direct; - - private String name; - private String address; - private int port; - private String user; - private String password; - private String access; - private KeyPair keypair; - private String keyDigest; - private PublicKey serverKey; - private String serverDigest; - private boolean enforceEncryption; - private long lastConnected; - - public ServerInfo(String address, int port, String user, String password, String access) { - this.direct = true; - this.name = DIRECT_NAME; - this.address = address; - this.port = port; - this.user = user; - this.password = password; - this.access = access; - this.lastConnected = -1L; - } - - public ServerInfo(String name, String address, int port, String user, String password, String access, KeyPair keypair, long lastConnected, PublicKey serverKey, boolean enforceEnc) { - this.direct = false; - this.name = name; - this.address = address; - this.port = port; - this.user = user; - this.password = password; - this.access = access; - this.keypair = keypair; - this.lastConnected = lastConnected; - this.serverKey = serverKey; - this.enforceEncryption = enforceEnc; - if(this.keypair != null) - this.keyDigest = EncryptUtil.getXorSha512Hash(this.keypair.getPublic().getEncoded()); - if(this.serverKey != null) - this.serverDigest = EncryptUtil.getXorSha512Hash(this.serverKey.getEncoded()); - } - - public boolean isDirect() { - return this.direct; - } - - public String getName() { - return this.name; - } - - public String getAddress() { - return this.address; - } - - public int getPort() { - return this.port; - } - - public String getUser() { - return this.user; - } - - public String getPassword() { - return this.password; - } - - public String getAccess() { - return this.access; - } - - public KeyPair getKeypair() { - return this.keypair; - } - - public PublicKey getServerKey() { - return this.serverKey; - } - - public boolean requiresEncryption() { - return this.enforceEncryption; - } - - public long getLastConnected() { - return this.lastConnected; - } - - public void setData(String name, String address, int port, String user, String password, String access, KeyPair keypair, PublicKey serverKey, boolean encryptReq) { - this.name = name; - this.address = address; - this.port = port; - this.user = user; - this.password = password; - this.access = access; - this.keypair = keypair; - this.serverKey = serverKey; - this.enforceEncryption = encryptReq; - this.keyDigest = this.keypair != null ? EncryptUtil.getXorSha512Hash(this.keypair.getPublic().getEncoded()) : null; - this.serverDigest = this.serverKey != null ? EncryptUtil.getXorSha512Hash(this.serverKey.getEncoded()) : null; - } - - public void setLastConnected() { - this.lastConnected = System.currentTimeMillis(); - } - - public void setServerKey(PublicKey key) { - this.serverKey = key; - this.serverDigest = this.serverKey != null ? EncryptUtil.getXorSha512Hash(this.serverKey.getEncoded()) : null; - } - - public int compareTo(ServerInfo comp) { - return this.lastConnected < comp.lastConnected ? 1 : (this.lastConnected > comp.lastConnected ? -1 : this.name.compareTo(comp.name)); - } - - public void select(boolean isDoubleClick, int mouseX, int mouseY) { - GuiConnect.this.selectButton.enabled = true; - GuiConnect.this.deleteButton.enabled = true; - GuiConnect.this.editButton.enabled = true; - GuiConnect.this.copyButton.enabled = true; - - if(isDoubleClick) { - GuiConnect.this.use(GuiConnect.this.selectButton, PressType.PRIMARY); - } - } - - public void draw(int x, int y, int width, int height, int mouseXIn, int mouseYIn, boolean hover) { - Drawing.drawText(this.name + TextColor.GRAY + " - " + TextColor.RESET + this.user, x + 2, y, 0xffffffff); - if(this.keypair != null || !this.password.isEmpty()) - Drawing.drawTextRight( - (this.keypair != null ? "Pubkey " + this.keyDigest : "") + (this.keypair != null && !this.password.isEmpty() ? " + " : "") + (!this.password.isEmpty() ? "Passwort" : ""), - x + width - 2, y, 0xffffffff); - Drawing.drawText(this.address + TextColor.GRAY + " Port " + TextColor.RESET + this.port + (this.enforceEncryption ? TextColor.GRAY + ", nur verschlüsselt" : ""), - x + 2, y + height - Font.YGLYPH * 2, 0xffb0b0b0); - if(!this.access.isEmpty()) - Drawing.drawTextRight((this.keypair != null || !this.password.isEmpty() ? "+ " : "") + "Server-Passwort", x + width - 2, y + height - Font.YGLYPH * 2, 0xffb0b0b0); - Drawing.drawText("Zuletzt verbunden: " + (this.lastConnected == -1L ? "nie" : DATE_FORMAT.format(new Date(this.lastConnected))), x + 2, y + height - Font.YGLYPH, 0xffb0b0b0); - if(this.serverDigest != null) - Drawing.drawTextRight("Server-ID: " + this.serverDigest, x + width - 2, y + height - Font.YGLYPH, 0xffb0b0b0); - } - } - - public static final GuiConnect INSTANCE = new GuiConnect(); - private static final String DIRECT_NAME = ""; - private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); - private static final File SERVERS_FILE = new File("servers.cfg"); - - private ActButton deleteButton; - private ActButton selectButton; - private ActButton copyButton; - private ActButton editButton; - private ActButton createButton; - - private GuiConnect() { - } - - public void init(int width, int height) { - super.init(width, height); - this.setDimensions(width, height, 32, height - 32); - this.elements.clear(); - if(SERVERS_FILE.exists()) { - try { - String[] lines = FileUtils.read(SERVERS_FILE).split("\n"); - String name = ""; - String address = ""; - int port = -1; - String user = ""; - String password = ""; - String access = ""; - byte[] key = null; - byte[] pubkey = null; - byte[] serverKey = null; - boolean enforceEnc = false; - long time = -1L; - for(int z = 0; z <= lines.length; z++) { - String line = z == lines.length ? null : lines[z]; - if(line == null || (line.startsWith("[") && line.endsWith("]"))) { - if(!name.isEmpty() && !address.isEmpty() && !user.isEmpty() && user.length() < IPlayer.MAX_USER_LENGTH && IPlayer.isValidUser(user) && - password.length() < IPlayer.MAX_PASS_LENGTH && access.length() < IPlayer.MAX_PASS_LENGTH && address.length() < 128 && name.length() < 128 && - port >= 1024 && port <= 32767 && (password.length() >= 8 || password.isEmpty()) && (access.length() >= 8 || access.isEmpty()) && !this.isNameTaken(name)) { - PrivateKey priv = key == null ? null : EncryptUtil.decodePrivateKey(key); - PublicKey pub = pubkey == null ? null : EncryptUtil.decodePublicKey(pubkey); - PublicKey serv = serverKey == null ? null : EncryptUtil.decodePublicKey(serverKey); - this.elements.add(new ServerInfo(name, address, port, user, password, access, priv == null || pub == null ? null : new KeyPair(pub, priv), time, serv, enforceEnc)); - } - if(line != null) { - address = ""; - port = -1; - user = ""; - password = ""; - access = ""; - key = null; - pubkey = null; - serverKey = null; - enforceEnc = false; - time = -1L; - name = line.substring(1, line.length() - 1); - } - } - else { - Pair value = Util.getKeyValue(line); - if(value.first().equals("address")) - address = value.second(); - else if(value.first().equals("port")) - try { - port = Integer.parseInt(value.second()); - } - catch(NumberFormatException e) { - } - else if(value.first().equals("user")) - user = value.second(); - else if(value.first().equals("password")) - password = value.second(); - else if(value.first().equals("access")) - access = value.second(); - else if(value.first().equals("connected")) - try { - time = Long.parseLong(value.second()); - } - catch(NumberFormatException e) { - } - else if(value.first().equals("encryption_enforced")) - enforceEnc = true; - else if(value.first().equals("serverkey")) - serverKey = Util.fromHexString(value.second()); - else if(value.first().equals("key")) - key = Util.fromHexString(value.second()); - else if(value.first().equals("pubkey")) - pubkey = Util.fromHexString(value.second()); - } - } - Collections.sort(this.elements); - } - catch(Exception e) { - Log.IO.error("Konnte Serverliste nicht laden", e); - this.elements.clear(); - } - } - - this.add(this.selectButton = new ActButton(width / 2 - 379, height - 30, 150, 0, this, "Verbinden")); - this.add(this.createButton = new ActButton(width - 202, 12, 200, 0, this, "Server hinzufügen ...")); - this.add(this.deleteButton = new ActButton(width / 2 - 75, height - 30, 150, 0, this, "Löschen")); - this.add(this.editButton = new ActButton(width / 2 + 77, height - 30, 150, 0, this, "Bearbeiten")); - this.add(this.copyButton = new ActButton(width / 2 - 227, height - 30, 150, 0, this, "Kopieren")); - this.add(new NavButton(width / 2 + 229, height - 30, 150, 0, GuiMenu.INSTANCE, "Abbrechen")); - - this.selectButton.enabled = false; - this.deleteButton.enabled = false; - this.editButton.enabled = false; - this.copyButton.enabled = false; - } - - public void onGuiClosed() { - this.save(); - } - - public void applyServer(ServerInfo server) { - if(this.selectedElement < 0) - this.elements.add(server); - this.save(); - this.gm.displayGuiScreen(this); - } - - public boolean isNameTaken(String name) { - for(int z = 0; z < this.elements.size(); z++) { - if(this.selectedElement != z && this.elements.get(z).getName().equals(name)) - return true; - } - return DIRECT_NAME.equals(name); - } - - public void editServer(ServerInfo server) { - if(!server.isDirect()) - this.save(); - } - - public void connect(String address, int port, String user, String pass, String access) { - this.gm.connect(new ServerInfo(address, port, user, pass, access)); - } - - private void save() { - try { - StringBuilder sb = new StringBuilder(); - for(ServerInfo server : this.elements) { - if(sb.length() > 0) - sb.append("\n"); - sb.append("[" + server.getName() + "]"); - sb.append("\naddress " + server.getAddress()); - sb.append("\nport " + server.getPort()); - sb.append("\nuser " + server.getUser()); - if(!server.getPassword().isEmpty()) - sb.append("\npassword " + server.getPassword()); - if(!server.getAccess().isEmpty()) - sb.append("\naccess " + server.getAccess()); - if(server.getKeypair() != null) { - sb.append("\nkey " + Util.getHexString(server.getKeypair().getPrivate().getEncoded())); - sb.append("\npubkey " + Util.getHexString(server.getKeypair().getPublic().getEncoded())); - } - if(server.requiresEncryption()) - sb.append("\nencryption_enforced"); - if(server.getLastConnected() != -1L) - sb.append("\nconnected " + server.getLastConnected()); - if(server.getServerKey() != null) - sb.append("\nserverkey " + Util.getHexString(server.getServerKey().getEncoded())); - } - FileUtils.write(SERVERS_FILE, sb.toString()); - } - catch(Exception e) { - Log.IO.error("Konnte Serverliste nicht speichern", e); - } - } - - public String getTitle() { - return "Server auswählen"; - } - - public int getSlotHeight() { - return 56; - } - - public void use(ActButton button, PressType mode) { - if(button == this.deleteButton) { - if(this.selectedElement >= 0) { - this.elements.remove(this.selectedElement); - this.gm.displayGuiScreen(this); - } - } - else if(button == this.selectButton) { - ServerInfo server = this.getSelected(); - if(server != null) { - server.setLastConnected(); - this.gm.connect(server); - } - } - else if(button == this.createButton) { - this.setSelected(-1); - this.gm.displayGuiScreen(new GuiServer(new ServerInfo("", "", -1, "", "", "", null, -1L, null, false))); - } - else if(button == this.editButton) { - ServerInfo server = this.getSelected(); - if(server != null) - this.gm.displayGuiScreen(new GuiServer(server)); - } - else if(button == this.copyButton) { - ServerInfo server = this.getSelected(); - if(server != null) { - this.setSelected(-1); - this.gm.displayGuiScreen(new GuiServer(new ServerInfo(server.name, server.address, server.port, server.user, server.password, server.access, server.keypair, -1L, null, server.enforceEncryption))); - } - } - } -} diff --git a/client/src/main/java/client/gui/GuiServer.java b/client/src/main/java/client/gui/GuiServer.java deleted file mode 100644 index a15b796..0000000 --- a/client/src/main/java/client/gui/GuiServer.java +++ /dev/null @@ -1,279 +0,0 @@ -package client.gui; - -import java.security.KeyPair; -import java.security.PublicKey; -import client.gui.GuiConnect.ServerInfo; -import client.gui.element.ActButton; -import client.gui.element.ButtonCallback; -import client.gui.element.Element; -import client.gui.element.Label; -import client.gui.element.NavButton; -import client.gui.element.PasswordField; -import client.gui.element.PressType; -import client.gui.element.Toggle; -import client.gui.element.FieldAction; -import client.gui.element.Field; -import client.gui.element.FieldCallback; -import client.vars.CVarCategory; -import client.vars.Variable; -import client.window.Window; -import common.color.TextColor; -import common.network.IPlayer; -import common.util.EncryptUtil; - -public class GuiServer extends Gui implements FieldCallback { - public static final GuiServer INSTANCE = new GuiServer(null); - - private final ServerInfo server; - - private Field nameBox; - private Field addrBox; - private Field portBox; - private Field userBox; - private PasswordField passBox; - private PasswordField accBox; - private Label nameLabel; - private Label addrLabel; - private Label portLabel; - private Label rangeLabel; - private Label userLabel; - private Label passLabel; - private Label accLabel; - private Label keyLabel; - private Label idLabel; - private Toggle encToggle; - private ActButton keyButton; - private ActButton resetButton; - private ActButton copyKeyButton; - private ActButton copyIdButton; - private KeyPair keypair; - private String keyDigest; - private PublicKey serverKey; - private String serverDigest; - - public GuiServer(ServerInfo server) { - this.server = server; - } - - @Variable(name = "srv_last_address", category = CVarCategory.SYSTEM, min = 1, max = 128, display = "Letzte Server-Adresse") - private String lastAddr = ""; - @Variable(name = "srv_last_port", category = CVarCategory.SYSTEM, min = 1024, max = 32767, display = "Letzter Server-Port") - private int lastPort = -1; - @Variable(name = "srv_last_user", category = CVarCategory.SYSTEM, max = IPlayer.MAX_USER_LENGTH, display = "Letzter Server-Nutzer", validator = IPlayer.UserValidator.class) - private String lastUser = ""; - @Variable(name = "srv_last_password", category = CVarCategory.SYSTEM, max = IPlayer.MAX_PASS_LENGTH, display = "Letztes Server-Passwort") - private String lastPass = ""; - @Variable(name = "srv_last_access", category = CVarCategory.SYSTEM, max = IPlayer.MAX_PASS_LENGTH, display = "Letzter Server-Zugang") - private String lastAcc = ""; - - public void init(int width, int height) { - if(this.server != null) { - this.nameBox = this.add(new Field(0, 0, 400, 0, 128, this, this.server.getName())); - this.nameLabel = this.add(new Label(0, 0, 410, "Name in der Liste", true)); - this.keypair = this.server.getKeypair(); - this.keyDigest = this.keypair == null ? null : EncryptUtil.getXorSha512Hash(this.keypair.getPublic().getEncoded()); - } - this.addrBox = this.add(new Field(0, 34, 400, 0, 128, this, this.server == null ? this.lastAddr : this.server.getAddress())); - this.addrLabel = this.add(new Label(0, 34, 410, "Adresse / Hostname", true)); - int port = this.server == null ? this.lastPort : this.server.getPort(); - this.portBox = this.add(new Field(404, 34, 76, 0, 5, this, port < 0 ? "" : "" + port)); - this.portLabel = this.add(new Label(404, 34, 76, "Port", true)); - this.rangeLabel = this.add(new Label(370, 34 + Element.BASE_HEIGHT, 110, 0, "[1024..32767]", true)); - this.userBox = this.add(new Field(0, 68, 220, 0, IPlayer.MAX_USER_LENGTH, this, IPlayer.VALID_USER, this.server == null ? this.lastUser : this.server.getUser())); - this.userLabel = this.add(new Label(0, 68, 220, "Benutzername", true)); - this.passBox = this.add(new PasswordField(0, this.server == null ? 102 : 136, 480, 0, IPlayer.MAX_PASS_LENGTH, this, this.server == null ? this.lastPass : this.server.getPassword())); - this.passLabel = this.add(new Label(0, this.server == null ? 102 : 136, 480, (this.keypair == null ? "Anmelde" : "Ersatz") + "-Passwort (mind. 8 Zeichen)", true)); - this.accBox = this.add(new PasswordField(0, this.server == null ? 136 : 170, 480, 0, IPlayer.MAX_PASS_LENGTH, this, this.server == null ? this.lastAcc : this.server.getAccess())); - this.accLabel = this.add(new Label(0, this.server == null ? 136 : 170, 480, "Server-Passwort (mind. 8 Zeichen)", true)); - this.add(new ActButton(241, this.server == null ? 166 : 254, 239, 0, new ButtonCallback() { - public void use(ActButton elem, PressType action) { - GuiServer.this.connect(); - } - }, this.server == null ? "Verbinden" : (this.server.getName().isEmpty() ? "Hinzufügen" : "Übernehmen"))); - this.add(new NavButton(0, this.server == null ? 166 : 254, 239, 0, this.server != null ? GuiConnect.INSTANCE : GuiMenu.INSTANCE, "Zurück")); - if(this.server != null) { - this.keyButton = this.add(new ActButton(0, 102, 391, 0, new ButtonCallback() { - public void use(ActButton elem, PressType action) { - if(GuiServer.this.keypair == null) { - GuiServer.this.keypair = EncryptUtil.createKeypair(); - GuiServer.this.keyDigest = EncryptUtil.getXorSha512Hash(GuiServer.this.keypair.getPublic().getEncoded()); - GuiServer.this.keyLabel.setText("Anmelde-Pubkey: " + EncryptUtil.KEY_ALGO_DISPLAY + " " + GuiServer.this.keyDigest); - GuiServer.this.keyButton.setText("Schlüsselpaar entfernen"); - GuiServer.this.passLabel.setText("Ersatz-Passwort (mind. 8 Zeichen)"); - GuiServer.this.copyKeyButton.enabled = true; - } - else { - final String name = GuiServer.this.nameBox.getText(); - final String addr = GuiServer.this.addrBox.getText(); - final String port = GuiServer.this.portBox.getText(); - final String pass = GuiServer.this.passBox.getText(); - final String acc = GuiServer.this.accBox.getText(); - final boolean reqEnc = GuiServer.this.encToggle.getValue(); - final KeyPair keys = GuiServer.this.keypair; - final PublicKey key = GuiServer.this.serverKey; - final String digest = GuiServer.this.keyDigest; - final String sdigest = GuiServer.this.serverDigest; - GuiServer.this.gm.displayGuiScreen(new GuiConfirm(new GuiConfirm.Callback() { - public void confirm(boolean confirmed) { - GuiServer.this.gm.displayGuiScreen(GuiServer.this); - GuiServer.this.nameBox.setText(name); - GuiServer.this.addrBox.setText(addr); - GuiServer.this.portBox.setText(port); - GuiServer.this.passBox.setText(pass); - GuiServer.this.accBox.setText(acc); - GuiServer.this.encToggle.setValue(reqEnc); - GuiServer.this.serverKey = key; - GuiServer.this.serverDigest = sdigest; - GuiServer.this.idLabel.setText("Server-Pubkey: " + (key != null ? EncryptUtil.KEY_ALGO_DISPLAY + " " + GuiServer.this.serverDigest : "nicht vorhanden")); - GuiServer.this.resetButton.enabled = key != null; - GuiServer.this.copyIdButton.enabled = key != null; - GuiServer.this.copyKeyButton.enabled = !confirmed; - if(confirmed) { - GuiServer.this.keypair = null; - GuiServer.this.keyDigest = null; - GuiServer.this.keyLabel.setText("Anmelde-Pubkey: nicht vorhanden"); - GuiServer.this.keyButton.setText("Neues Schlüsselpaar generieren"); - GuiServer.this.passLabel.setText("Anmelde-Passwort (mind. 8 Zeichen)"); - } - else { - GuiServer.this.keypair = keys; - GuiServer.this.keyDigest = digest; - GuiServer.this.keyLabel.setText("Anmelde-Pubkey: " + EncryptUtil.KEY_ALGO_DISPLAY + " " + GuiServer.this.keyDigest); - GuiServer.this.keyButton.setText("Schlüsselpaar entfernen"); - GuiServer.this.passLabel.setText("Ersatz-Passwort (mind. 8 Zeichen)"); - } - } - }, "Schlüsselpaar wirklich entfernen?", "Wenn das Schlüsselpaar gelöscht wird, ist es nicht mehr möglich, sich damit\nauf dem Server zu identifizieren und sich anzumelden.\nDamit könnte der Zugriff auf den Server unmöglich werden.", "Schlüsselpaar löschen", "Abbrechen")); - } - } - }, this.keypair == null ? "Neues Schlüsselpaar generieren" : "Schlüsselpaar entfernen")); - this.copyKeyButton = this.add(new ActButton(395, 102, 85, 0, new ButtonCallback() { - public void use(ActButton elem, PressType action) { - if(GuiServer.this.keypair != null) - Window.setClipboard(EncryptUtil.getArmoredPubkey(GuiServer.this.keypair.getPublic(), GuiServer.this.userBox.getText())); - } - }, "Kopieren")); - this.copyKeyButton.enabled = this.keypair != null; - this.keyLabel = this.add(new Label(0, 102, 480, "Anmelde-Pubkey: " + (this.keypair != null ? EncryptUtil.KEY_ALGO_DISPLAY + " " + this.keyDigest : "nicht vorhanden"), true)); - this.encToggle = this.add(new Toggle(0, 190, 480, 0, false, this.server.requiresEncryption(), null, "Nur Verschlüsselte Verbindung akzeptieren")); - this.serverKey = this.server.getServerKey(); - this.serverDigest = this.serverKey == null ? null : EncryptUtil.getXorSha512Hash(this.serverKey.getEncoded()); - this.resetButton = this.add(new ActButton(0, 224, 391, 0, new ButtonCallback() { - public void use(ActButton elem, PressType action) { - if(GuiServer.this.serverKey != null) { - GuiServer.this.serverKey = null; - GuiServer.this.serverDigest = null; - GuiServer.this.idLabel.setText("Server-Pubkey: nicht vorhanden"); - GuiServer.this.resetButton.enabled = false; - GuiServer.this.copyIdButton.enabled = false; - } - } - }, "Server-Identifizierung / Pubkey zurücksetzen")); - this.resetButton.enabled = this.serverKey != null; - this.copyIdButton = this.add(new ActButton(395, 224, 85, 0, new ButtonCallback() { - public void use(ActButton elem, PressType action) { - if(GuiServer.this.serverKey != null) - Window.setClipboard(EncryptUtil.getArmoredPubkey(GuiServer.this.serverKey, GuiServer.this.nameBox.getText())); - } - }, "Kopieren")); - this.copyIdButton.enabled = this.serverKey != null; - this.idLabel = this.add(new Label(0, 224, 480, "Server-Pubkey: " + (this.serverKey != null ? EncryptUtil.KEY_ALGO_DISPLAY + " " + this.serverDigest : "nicht vorhanden"), true)); - } - this.shift(); - } - - public String getTitle() { - return this.server == null ? "Mit Server verbinden" : (this.server.getName().isEmpty() ? "Server hinzufügen" : "Server bearbeiten"); - } - - private void connect() { - if(this.gm.world != null) - return; - String name = null; - if(this.server != null) { - name = this.nameBox.getText(); - if(name.isEmpty()) { - this.nameLabel.setText(TextColor.RED + "Name in der Liste"); - return; - } - if(GuiConnect.INSTANCE.isNameTaken(name)) { - this.nameLabel.setText("Name in der Liste - " + TextColor.RED + "Bereits vorhanden"); - return; - } - } - String addr = this.addrBox.getText(); - if(addr.isEmpty()) { - this.addrLabel.setText(TextColor.RED + "Adresse / Hostname"); - return; - } - int port = -1; - if(this.portBox.getText().isEmpty()) { - this.portLabel.setText(TextColor.RED + "Port"); - return; - } - else { - try { - port = Integer.parseInt(this.portBox.getText()); - } - catch(NumberFormatException e) { - this.rangeLabel.setText("[" + TextColor.RED + "1024..32767" + TextColor.RESET + "]"); - return; - } - if(port < 1024 || port > 32767) { - this.rangeLabel.setText("[" + (port < 1024 ? TextColor.RED + "1024" + TextColor.RESET + "..32767" : "1024.." + TextColor.RED + "32767" + TextColor.RESET) + "]"); - return; - } - } - String user = this.userBox.getText(); - if(user.isEmpty()) { - this.userLabel.setText(TextColor.RED + "Benutzername"); - return; - } - String pass = this.passBox.getText(); - if(!pass.isEmpty() && pass.length() < 8) { - this.passLabel.setText((this.keypair == null ? "Anmelde" : "Ersatz") + "-Passwort (" + TextColor.RED + "mind. 8 Zeichen" + TextColor.RESET + ")"); - return; - } - String acc = this.accBox.getText(); - if(!acc.isEmpty() && acc.length() < 8) { - this.accLabel.setText("Zugang (" + TextColor.RED + "mind. 8 Zeichen" + TextColor.RESET + ")"); - return; - } - if(this.server == null) { - this.lastAddr = addr; - this.lastPort = port; - this.lastUser = user; - this.lastPass = pass; - this.lastAcc = acc; - this.gm.setDirty(); - GuiConnect.INSTANCE.connect(addr, port, user, pass, acc); - } - else { - this.server.setData(name, addr, port, user, pass, acc, this.keypair, this.serverKey, this.encToggle.getValue()); - GuiConnect.INSTANCE.applyServer(this.server); - } - } - - public void use(Field elem, FieldAction value) { - if(value == FieldAction.SEND) { - elem.setDeselected(); - this.connect(); - } - else if(value == FieldAction.FOCUS) { - if(elem == this.addrBox) - this.addrLabel.setText("Adresse / Hostname"); - else if(elem == this.portBox) { - this.portLabel.setText("Port"); - this.rangeLabel.setText("[1024..32767]"); - } - else if(elem == this.userBox) - this.userLabel.setText("Benutzername"); - else if(elem == this.passBox) - this.passLabel.setText((this.keypair == null ? "Anmelde" : "Ersatz") + "-Passwort (mind. 8 Zeichen)"); - else if(elem == this.accBox) - this.accLabel.setText("Server-Passwort (mind. 8 Zeichen)"); - else if(this.server != null && elem == this.nameBox) - this.nameLabel.setText("Name in der Liste"); - } - } -} diff --git a/client/src/main/java/client/gui/container/GuiCrafting.java b/client/src/main/java/client/gui/container/GuiCrafting.java deleted file mode 100755 index 36b3eb5..0000000 --- a/client/src/main/java/client/gui/container/GuiCrafting.java +++ /dev/null @@ -1,22 +0,0 @@ -package client.gui.container; - -import common.block.tech.BlockWorkbench; -import common.inventory.ContainerWorkbench; -import common.inventory.InventoryPlayer; -import common.util.BlockPos; -import common.world.World; - -public class GuiCrafting extends GuiContainer { - private final BlockWorkbench type; - - public GuiCrafting(InventoryPlayer playerInv, World worldIn, BlockWorkbench type) { - super(new ContainerWorkbench(playerInv, worldIn, BlockPos.ORIGIN, type)); - this.type = type; - this.ySize = 112 + 18 * this.type.getSize(); - } - - public void drawGuiContainerForegroundLayer() { - this.drawString("Handwerk (" + this.type.getDisplay() + ")", 26, 6); - this.drawString("Inventar", 8, this.ySize - 96 + 2); - } -} diff --git a/client/src/main/java/client/gui/container/GuiTile.java b/client/src/main/java/client/gui/container/GuiTile.java deleted file mode 100755 index 018826d..0000000 --- a/client/src/main/java/client/gui/container/GuiTile.java +++ /dev/null @@ -1,32 +0,0 @@ -package client.gui.container; - -import client.Client; -import common.inventory.ContainerTile; -import common.inventory.IInventory; -import common.inventory.InventoryPlayer; -import common.tileentity.TileEntityDevice; - - -public class GuiTile extends GuiContainer -{ - private final IInventory playerInv; - private final IInventory tileInv; - private final TileEntityDevice tile; - - public GuiTile(InventoryPlayer player, IInventory inv, TileEntityDevice tile) - { - super(new ContainerTile(player, tile, inv, Client.CLIENT.player)); - this.playerInv = player; - this.tileInv = tile; - this.ySize = 153; - this.tile = tile; - } - - public void drawGuiContainerForegroundLayer() - { - this.drawString(this.tile.getStatus().color + this.tileInv.getCommandName() + " - " + this.tile.getStatus().name, 8, 6); - this.drawString(this.playerInv.getCommandName(), 8, this.ySize - 96 + 2); - this.drawString(String.format("Temperatur: %d °", this.tile.getTemperature()), 8, 18); - this.drawString(this.tile.formatDisplay((ContainerTile)this.inventorySlots), 8, 28); - } -} diff --git a/client/src/main/java/client/gui/element/GuiList.java b/client/src/main/java/client/gui/element/GuiList.java deleted file mode 100755 index 0727984..0000000 --- a/client/src/main/java/client/gui/element/GuiList.java +++ /dev/null @@ -1,292 +0,0 @@ -package client.gui.element; - -import java.util.List; - -import client.gui.Gui; -import client.renderer.Drawing; -import client.window.Button; -import common.collect.Lists; -import common.util.ExtMath; - -public abstract class GuiList extends Gui -{ - public static final int SCROLLBAR_WIDTH = 6; - - protected final List elements = Lists.newArrayList(); - - protected int width; - protected int height; - - protected int top; - protected int bottom; - protected int right; - protected int left; - protected int mouseX; - protected int mouseY; - protected int initialClickY = -2; - protected float scrollMultiplier; - protected float amountScrolled; - protected int selectedElement = -1; - protected long lastClicked; - - public abstract int getSlotHeight(); - - protected boolean isScrollbarRight() - { - return false; - } - - public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn) - { - this.width = widthIn; - this.height = heightIn; - this.top = topIn; - this.bottom = bottomIn; - this.left = 0; - this.right = widthIn; - } - - public void init(int width, int height) { - - this.selectedElement = -1; - } - - public void setSlotXBoundsFromLeft(int leftIn) - { - this.left = leftIn; - this.right = leftIn + this.width; - } - - public final T getListEntry(int index) { - return this.elements.get(index); - } - - public final T getSelected() { - return this.selectedElement < 0 ? null : this.elements.get(this.selectedElement); - } - - public final int getSize() { - return this.elements.size(); - } - - public final void setSelected(int index) { - this.selectedElement = index; - } - - protected int getContentHeight() - { - return this.getSize() * this.getSlotHeight(); - } - - public int getSlotIndexFromScreenCoords(int x, int y) - { - int x1 = this.left + (this.isScrollbarRight() ? 0 : SCROLLBAR_WIDTH); - int x2 = this.left + (this.isScrollbarRight() ? this.width - SCROLLBAR_WIDTH : this.width); - int y1 = y - this.top + (int)this.amountScrolled - 4; - int idx = y1 / this.getSlotHeight(); - return this.isInList(x, y) && x >= x1 && x <= x2 && idx >= 0 && y1 >= 0 && idx < this.getSize() ? idx : -1; - } - - protected boolean isInList(int x, int y) - { - return this.isScrollbarRight() ? x < this.width - SCROLLBAR_WIDTH : x >= SCROLLBAR_WIDTH; - } - - protected final boolean isSelected(int slotIndex) - { - return slotIndex == this.selectedElement; - } - - protected void bindAmountScrolled() - { - this.amountScrolled = ExtMath.clampf(this.amountScrolled, 0.0F, (float)this.getMaxScroll()); - } - - public int getMaxScroll() - { - return Math.max(0, this.getContentHeight() - (this.bottom - this.top - 4)); - } - - public int getAmountScrolled() - { - return (int)this.amountScrolled; - } - - public boolean isMouseYWithinSlotBounds(int y) - { - return y >= this.top && y <= this.bottom && this.mouseX >= this.left && this.mouseX <= this.right; - } - - public void scrollBy(int amount) - { - this.amountScrolled += (float)amount; - this.bindAmountScrolled(); - this.initialClickY = -2; - } - - public void draw() - { - int mouseXIn = this.gm.mouse_x; - int mouseYIn = this.gm.mouse_y; - this.mouseX = mouseXIn; - this.mouseY = mouseYIn; - this.drawBackground(); - this.bindAmountScrolled(); - - Drawing.drawScaled(this.gm, Gui.BACKGROUND, 0, this.top, this.gm.fb_x, this.bottom - this.top, 0xff7f7f7f); - - int x = this.left + (this.isScrollbarRight() ? 0 : SCROLLBAR_WIDTH); - int y = this.top + 4 - (int)this.amountScrolled; - - int size = this.getSize(); - boolean canHover = this.clicked(mouseXIn, mouseYIn) == null; - - for (int z = 0; z < size; z++) - { - int y1 = y + z * this.getSlotHeight(); - int h = this.getSlotHeight() - 4; - - Drawing.drawRectBorder(x, y1 - 2, this.width - SCROLLBAR_WIDTH, this.getSlotHeight(), this.isSelected(z) ? this.gm.style.fill_btm : this.gm.style.fill_top, this.isSelected(z) ? 0xffffffff : 0xff000000, this.gm.style.brdr_top, this.gm.style.brdr_btm); - - boolean hover = canHover && this.getSlotIndexFromScreenCoords(mouseXIn, mouseYIn) == z; - this.getListEntry(z).draw(x + 2, y1, this.width - SCROLLBAR_WIDTH - 4, this.getSlotHeight() - 4, mouseXIn - x - 2, mouseYIn - y1, hover); - if(hover) - Drawing.drawRect(x, y1 - 2, this.width - SCROLLBAR_WIDTH, this.getSlotHeight(), Gui.HOVER_COLOR); - } - - Drawing.drawScaled(this.gm, Gui.BACKGROUND, 0, 0, this.gm.fb_x, this.top, 0xffffffff); - Drawing.drawScaled(this.gm, Gui.BACKGROUND, 0, this.bottom, this.gm.fb_x, this.height - this.bottom, 0xffffffff); - Drawing.drawRect(-1, -1, this.gm.fb_x + 2, this.top + 1, 0, this.gm.style.brdr_top, this.gm.style.brdr_btm); - Drawing.drawRect(-1, this.bottom, this.gm.fb_x + 2, this.height - this.bottom + 1, 0, this.gm.style.brdr_top, this.gm.style.brdr_btm); - - int edge = 2; - Drawing.drawGradient(0, this.top, this.gm.fb_x, edge, 0xff000000, 0x00000000); - Drawing.drawGradient(0, this.bottom - edge, this.gm.fb_x, edge, 0x00000000, 0xff000000); - - int max = this.getMaxScroll(); - - if (max > 0) - { - int barHeight = (this.bottom - this.top) * (this.bottom - this.top) / this.getContentHeight(); - barHeight = ExtMath.clampi(barHeight, 32, this.bottom - this.top - 8); - int scrollX = this.isScrollbarRight() ? this.width - SCROLLBAR_WIDTH : 0; - int scrollY = (int)this.amountScrolled * (this.bottom - this.top - barHeight) / max + this.top; - if(scrollY < this.top) - scrollY = this.top; - Drawing.drawRect(scrollX, this.top, SCROLLBAR_WIDTH, this.bottom - this.top, 0xff000000); - Drawing.drawGradient(scrollX, scrollY, SCROLLBAR_WIDTH, barHeight, this.gm.style.fill_top, this.gm.style.fill_btm, this.gm.style.brdr_top, this.gm.style.brdr_btm); - } - - super.draw(); - } - - public void handleMouseInput() - { - if (this.isMouseYWithinSlotBounds(this.mouseY)) - { - if (this.initialClickY == -1) - { - boolean flag1 = true; - - if (this.mouseY >= this.top && this.mouseY <= this.bottom) - { - int j2 = (this.isScrollbarRight() ? 0 : SCROLLBAR_WIDTH); - int k2 = (this.isScrollbarRight() ? this.width - SCROLLBAR_WIDTH : this.width); - int l2 = this.mouseY - this.top + (int)this.amountScrolled - 4; - int i1 = l2 / this.getSlotHeight(); - - if (i1 < this.getSize() && this.mouseX >= j2 && this.mouseX <= k2 && i1 >= 0 && l2 >= 0) - { - } - else if (this.mouseX >= j2 && this.mouseX <= k2 && l2 < 0) - { - flag1 = false; - } - - int i3 = this.isScrollbarRight() ? this.width - SCROLLBAR_WIDTH : 0; - int j1 = i3 + SCROLLBAR_WIDTH; - - if (this.mouseX >= i3 && this.mouseX <= j1) - { - this.scrollMultiplier = -1.0F; - int k1 = this.getMaxScroll(); - - if (k1 < 1) - { - k1 = 1; - } - - int l1 = (int)((float)((this.bottom - this.top) * (this.bottom - this.top)) / (float)this.getContentHeight()); - l1 = ExtMath.clampi(l1, 32, this.bottom - this.top - 8); - this.scrollMultiplier /= (float)(this.bottom - this.top - l1) / (float)k1; - } - else - { - this.scrollMultiplier = 1.0F; - } - - if (flag1) - { - this.initialClickY = this.mouseY; - } - else - { - this.initialClickY = -2; - } - } - else - { - this.initialClickY = -2; - } - } - else if (this.initialClickY >= 0) - { - this.amountScrolled -= (float)(this.mouseY - this.initialClickY) * this.scrollMultiplier; - this.initialClickY = this.mouseY; - } - } - } - - public void mouse(Button btn, int x, int y, boolean ctrl, boolean shift) - { - super.mouse(btn, x, y, ctrl, shift); - if (this.isMouseYWithinSlotBounds(y) && this.clicked(x, y) == null) - { - int i = this.getSlotIndexFromScreenCoords(x, y); - - if (i >= 0) - { - int x1 = this.left + (this.isScrollbarRight() ? 0 : SCROLLBAR_WIDTH) + 2; - int y1 = this.top + 4 - this.getAmountScrolled() + i * this.getSlotHeight(); - int mx = x - x1; - int my = y - y1; - - boolean flag = i == this.selectedElement && System.currentTimeMillis() - this.lastClicked < (long)this.gm.dclickDelay; - this.selectedElement = i; - this.lastClicked = System.currentTimeMillis(); - - this.getListEntry(i).select(flag, mx, my); - } - } - if(btn == Button.MOUSE_LEFT && this.clicked(x, y) == null) - this.handleMouseInput(); - } - - public void mouserel(Button btn, int x, int y) { - super.mouserel(btn, x, y); - if(btn == Button.MOUSE_LEFT) - this.initialClickY = -1; - } - - public void scroll(int scr_x, int scr_y, int x, int y, boolean ctrl, boolean shift) { - super.scroll(scr_x, scr_y, x, y, ctrl, shift); - if(scr_y != 0 && this.clicked(x, y) == null) - this.amountScrolled -= (float)(ExtMath.clampi(scr_y, -1, 1) * this.getSlotHeight() / 2); - } - - public void drag(int x, int y) { - super.drag(x, y); - if(this.selected == null && Button.MOUSE_LEFT.isDown() && (this.initialClickY != -1 || this.clicked(x, y) == null)) - this.handleMouseInput(); - } -} diff --git a/client/src/main/java/client/gui/element/MultiLabel.java b/client/src/main/java/client/gui/element/MultiLabel.java deleted file mode 100644 index 3eb64a8..0000000 --- a/client/src/main/java/client/gui/element/MultiLabel.java +++ /dev/null @@ -1,40 +0,0 @@ -package client.gui.element; - -import client.gui.Font; -import client.renderer.Drawing; -import common.util.Util; - -public class MultiLabel extends Fill { - private String[] lines; - - public MultiLabel(int x, int y, int w, int h, String text, boolean top) { - super(x, y, w, h, text, top, true); - } - - public MultiLabel(int x, int y, int w, int h, String text) { - super(x, y, w, h, text, false, true); - } - - public void setText(String str) { - super.setText(str); - this.lines = str.split("\n", -1); - } - - protected void drawBackground() { - } - - protected void drawForeground(int x1, int y1, int x2, int y2) { - int color = this.enabled ? this.gm.style.text_label : Util.mulColor(this.gm.style.text_label, 0.5f); - for(int z = 0; z < this.lines.length; z++) { - Drawing.drawTextCentered(this.lines[z], x1 + x2 / 2, y1 + this.text_y + z * Font.YGLYPH, color); - } - } - - protected int getMarginX() { - return 0; - } - - protected int getMarginY() { - return 0; - } -} diff --git a/client/src/main/java/client/gui/element/PasswordField.java b/client/src/main/java/client/gui/element/PasswordField.java deleted file mode 100644 index a125e03..0000000 --- a/client/src/main/java/client/gui/element/PasswordField.java +++ /dev/null @@ -1,17 +0,0 @@ -package client.gui.element; - -import common.util.Util; - -public class PasswordField extends Field { - public PasswordField(int x, int y, int w, int h, int cap, FieldCallback callback, String text) { - super(x, y, w, h, cap, callback, text); - } - - protected String getDrawnText() { - return Util.repeatString("*", this.text.length()); - } - - protected boolean canCopy() { - return false; - } -} diff --git a/client/src/main/java/client/gui/options/GuiDisplay.java b/client/src/main/java/client/gui/options/GuiDisplay.java deleted file mode 100644 index abbebf8..0000000 --- a/client/src/main/java/client/gui/options/GuiDisplay.java +++ /dev/null @@ -1,115 +0,0 @@ -package client.gui.options; - -import java.util.List; - -import client.Client; -import client.gui.Font; -import client.gui.Formatter; -import client.gui.element.Dropdown; -import client.gui.element.DropdownCallback; -import client.gui.element.Element; -import client.gui.element.Fill; -import client.gui.element.Slider; -import client.gui.element.SliderCallback; -import client.gui.element.Toggle; -import client.gui.element.ToggleCallback; -import client.window.Button; -import client.window.DisplayMode; -import client.window.Window; -import common.collect.Lists; -import common.color.TextColor; -import common.util.ExtMath; - -public class GuiDisplay extends GuiOptions { - private static final String[] DISTANCES = new String[] {"Gruselig", "Winzig", "Gering", "Normal", "Weit"}; - - private Element distanceSlider; - - protected GuiDisplay() { - } - - public void init(int width, int height) { - this.add(new Toggle(0, 0, 240, 0, false, GuiDisplay.this.gm.fullscreen, new ToggleCallback() { - public void use(Toggle elem, boolean value) { - GuiDisplay.this.gm.full(value); - } - }, "Vollbild")); - int maxModes = ExtMath.clampi((height - 120) / Font.YGLYPH, 4, 28); - DisplayMode[] dmodes = Window.getDisplayModes(); - if(dmodes != null) { - List modes = Lists.newArrayList(); - for(int z = dmodes.length - 1; z >= 0 && modes.size() < maxModes; z--) { - DisplayMode mode = dmodes[z]; - if(mode.width() >= Client.MIN_WIDTH && mode.height() >= Client.MIN_HEIGHT) - modes.add(0, mode); - } - if(modes.isEmpty()) { - dmodes = null; - } - else { - DisplayMode selected = modes.get(modes.size() - 1); - for(DisplayMode mode : modes) { - if(mode.equals(this.gm.vidMode)) - selected = mode; - } - this.add(new Dropdown(242, 0, 240, 0, false, modes.toArray(new DisplayMode[modes.size()]), modes.get(modes.size() - 1), selected, new DropdownCallback() { - public void use(Dropdown elem, DisplayMode value) { - GuiDisplay.this.gm.vidMode = value; - GuiDisplay.this.gm.full(true); - } - }, (String)null)); - } - } - if(dmodes == null) - this.add(new Fill(242, 0, 240, 0, TextColor.RED + "")); - - this.add(new Slider(0, 20, 240, 0, 0, 0, 360 - 8, 0, (this.gm.sync < 0) ? (360 - 8) : (this.gm.sync != 0 ? ((this.gm.sync < 10) ? 1 : (this.gm.sync - 9)) : 0), new SliderCallback() { - public void use(Slider elem, int value) { - GuiDisplay.this.gm.getVar("win_sync").parse("" + ((value > 0 && value < 360 - 8) ? (value + 9) : (value != 0 ? -1 : 0))); - GuiDisplay.this.gm.setDirty(); - } - }, new Formatter() { - public String use(Slider elem) { - int value = elem.getValue(); - return "Max. Bildrate: " + (value > 0 && value < (360 - 8) ? (value + 9) + " FPS" : (value != 0 ? "Unbegrenzt" : "VSync")); - } - })); - this.addSelector("gl_vsync_flush", 242, 20, 240, 0); - - this.addSelector("overlay_enabled", 0, 50, 240, 0); - this.addSelector("overlay_opacity", 242, 50, 240, 0); - - this.addSelector("overlay_fadeout", 0, 70, 240, 0); - this.addSelector("chat_permanent", 242, 70, 240, 0); - - this.addSelector("console_size", 0, 90, 240, 0); - this.addSelector("chat_size", 242, 90, 240, 0); - - this.addSelector("feed_size", 0, 110, 240, 0); - this.addSelector("hotbar_size", 242, 110, 240, 0); - - this.addSelector("gl_fov", 0, 140, 240, 0); - - this.distanceSlider = this.addSelector("chunk_view_distance", 0, 160, 240, 0); - this.addSelector("chunk_build_time", 242, 160, 240, 0); - super.init(width, height); - } - - public String getTitle() { - return "Grafik und Anzeige"; - } - - private String getDistanceName() { - int distance = this.gm.renderDistance; - distance = distance > 16 ? 16 : distance; - String str = distance < 0 ? DISTANCES[0] : DISTANCES[(distance + 1) / 4]; - if(distance > 2 && (((distance + 1) / 2) & 1) == 1) - str = str + "+"; - return String.format("Sichtweite: %d [%d, %s]", this.gm.renderDistance, this.gm.renderDistance * 16, str); - } - - public void updateScreen() { - if(!Button.isMouseDown()) - this.distanceSlider.setText(this.getDistanceName()); - } -} diff --git a/client/src/main/java/client/network/ClientLoginHandler.java b/client/src/main/java/client/network/ClientLoginHandler.java deleted file mode 100755 index 2721d05..0000000 --- a/client/src/main/java/client/network/ClientLoginHandler.java +++ /dev/null @@ -1,209 +0,0 @@ -package client.network; - -import java.security.KeyPair; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.util.Base64; - -import client.Client; -import client.gui.GuiConfirm; -import client.gui.GuiConnect; -import client.gui.GuiConnect.ServerInfo; -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; -import common.network.IClientLoginHandler; -import common.network.NetConnection; -import common.network.PacketRegistry; -import common.packet.LPacketChallenge; -import common.packet.LPacketPassword; -import common.packet.LPacketPubkey; -import common.packet.LPacketResponse; -import common.packet.LPacketStartEncrypt; -import common.packet.RPacketChallenge; -import common.packet.RPacketDisconnect; -import common.packet.RPacketEnableCompression; -import common.packet.RPacketLoginSuccess; -import common.packet.RPacketRequestEncrypt; -import common.packet.RPacketResponse; -import common.packet.RPacketServerConfig; -import common.util.EncryptUtil; -import common.util.Util; - -public class ClientLoginHandler implements IClientLoginHandler { - private static enum LoginState { - HANDSHAKE, CONFIRMING, CHALLENGE, ENCRYPTED, PROVING, AUTHENTICATING, DONE; - } - - private static final SecureRandom TOKEN_RNG = new SecureRandom(); - - private final Client gm; - private final NetConnection connection; - private final ServerInfo server; - private final KeyPair tempKeys; - - private LoginState state = LoginState.HANDSHAKE; - private byte[] token; - - public ClientLoginHandler(NetConnection conn, Client gm, ServerInfo server) { - this.connection = conn; - this.gm = gm; - this.server = server; - this.tempKeys = EncryptUtil.createDHKeypair(); - } - - public void onDisconnect(String reason) - { - this.gm.disconnected(reason); - } - - public void handleDisconnect(RPacketDisconnect packet) - { - this.connection.closeChannel(packet.getReason()); - } - - public void handleEncrypt(RPacketRequestEncrypt packet) { - if(this.state != LoginState.HANDSHAKE) { - this.connection.closeChannel("Unerwartetes Verschlüsselungs-Paket"); - return; - } - this.connection.setConnectionState(PacketRegistry.LOGIN); - final PublicKey pubkey = packet.getKey(); - final PublicKey tempKey = packet.getTempKey(); - if(this.server.getServerKey() == null) { - this.state = LoginState.CONFIRMING; - this.gm.schedule(new Runnable() { - public void run() { - ClientLoginHandler.this.gm.displayGuiScreen(new GuiConfirm(new GuiConfirm.Callback() { - public void confirm(boolean confirmed) { - if(confirmed) { - ClientLoginHandler.this.server.setServerKey(pubkey); - GuiConnect.INSTANCE.editServer(ClientLoginHandler.this.server); - ClientLoginHandler.this.gm.displayConnecting(ClientLoginHandler.this.server); - ClientLoginHandler.this.startEncryption(tempKey); - } - else { - ClientLoginHandler.this.connection.closeChannel("Verbindung wurde abgebrochen"); - } - } - }, "Die Identität des Servers ist unbekannt", "Es wurde noch nie mit diesem Server verbunden.\nSoll die Verbindung wirklich fortgesetzt werden?\n\nDie Pubkey-ID des Servers lautet:\n" + EncryptUtil.KEY_ALGO_DISPLAY + " " + EncryptUtil.getXorSha512Hash(pubkey.getEncoded()) + "\n\nDer öffentliche Schlüssel des Servers lautet:\n" + Util.breakString(Base64.getEncoder().encodeToString(pubkey.getEncoded()), 64), "Verbindung herstellen", "Abbrechen und trennen")); - } - }); - return; - } - else if(!this.server.getServerKey().equals(pubkey)) { - this.connection.closeChannel("Die Identität des Servers hat sich geändert\n\nDer Server hat einen anderen öffentlichen Schlüssel als vorher bekannt war,\ndies kann bedeuten dass der Inhaber jetzt einen anderen Schlüssel verwendet\noder sich ein anderer Server als dieser ausgibt (\"Man-in-the-middle-attack\").\n\nDie Pubkey-ID des Servers lautet: " + EncryptUtil.KEY_ALGO_DISPLAY + " " + EncryptUtil.getXorSha512Hash(pubkey.getEncoded()) + "\n\nDer öffentliche Schlüssel des Servers lautet:\n" + Util.breakString(Base64.getEncoder().encodeToString(pubkey.getEncoded()), 64) + "\n\nDie vertrauenswürdige Pubkey-ID lautet: " + EncryptUtil.KEY_ALGO_DISPLAY + " " + EncryptUtil.getXorSha512Hash(this.server.getServerKey().getEncoded()) + - "\n\nFalls der Server trotzdem vertrauenswürdig wirkt, kann die Server-Identifizierung\nin den Einstellungen von '" + this.server.getName() + "' zurückgesetzt werden."); - return; - } - this.startEncryption(tempKey); - } - - private void startEncryption(PublicKey serverKey) { - this.state = LoginState.CHALLENGE; - this.connection.sendPacket(new LPacketStartEncrypt(this.tempKeys.getPublic()), new GenericFutureListener < Future > () { - public void operationComplete(Future u) throws Exception { - ClientLoginHandler.this.connection.startEncryption(EncryptUtil.makeKeyAgreement(ClientLoginHandler.this.tempKeys.getPrivate(), serverKey)); - ClientLoginHandler.this.token = new byte[32]; - TOKEN_RNG.nextBytes(ClientLoginHandler.this.token); - ClientLoginHandler.this.connection.sendPacket(new LPacketChallenge(ClientLoginHandler.this.token)); - } - }); - } - - public void handleResponse(RPacketResponse packet) { - if(this.state != LoginState.CHALLENGE) { - this.connection.closeChannel("Unerwartetes Beweis-Paket"); - return; - } - if(!packet.verifyToken(this.server.getServerKey(), this.token)) { - this.connection.closeChannel("Fehlerhaftes Beweis-Token"); - return; - } - this.state = LoginState.ENCRYPTED; - } - - public void handleConfig(final RPacketServerConfig packet) { - if(this.state == LoginState.HANDSHAKE) { - this.connection.setConnectionState(PacketRegistry.LOGIN); - if(this.server.requiresEncryption()) { - this.connection.closeChannel("Der Server unterstützt keine verschlüsselte Verbindung, dies ist\nin den Servereinstellungen von '" - + this.server.getName() + "' als erforderlich\neingestellt, stelle keine ungesicherte Verbindung her."); - return; - } - if(this.server.getServerKey() != null) { - this.state = LoginState.CONFIRMING; - this.gm.schedule(new Runnable() { - public void run() { - ClientLoginHandler.this.gm.displayGuiScreen(new GuiConfirm(new GuiConfirm.Callback() { - public void confirm(boolean confirmed) { - if(confirmed) { - ClientLoginHandler.this.server.setServerKey(null); - GuiConnect.INSTANCE.editServer(ClientLoginHandler.this.server); - ClientLoginHandler.this.gm.displayConnecting(ClientLoginHandler.this.server); - ClientLoginHandler.this.state = LoginState.HANDSHAKE; - ClientLoginHandler.this.handleConfig(packet); - } - else { - ClientLoginHandler.this.connection.closeChannel("Verbindung wurde abgebrochen"); - } - } - }, "Der Server hat die Verschlüsselung deaktiviert", "Es wurde bereits verschlüsselt mit diesem Server kommuniziert.\n\nSoll die Verbindung wirklich fortgesetzt werden?\n\nDie Pubkey-Authentifizierung wird nicht verfügbar sein\nund die Server-ID wird ignoriert und zurückgesetzt.", "Unverschlüsselt verbinden", "Abbrechen und trennen")); - } - }); - return; - } - } - else if(this.state != LoginState.ENCRYPTED) { - this.connection.closeChannel("Unerwartetes Konfigurations-Paket"); - return; - } - if(packet.hasAccessPassword() && this.server.getAccess().isEmpty()) { - this.connection.closeChannel("Der Server verlangt ein Zugangs-Passwort zur Authentifizierung"); - return; - } - boolean auth = packet.isAuthenticating(); - boolean passwordAuth = packet.canUsePassword(); - boolean pubkeyAuth = packet.canUsePubkey() && this.state == LoginState.ENCRYPTED; - if(auth && (!passwordAuth || this.server.getPassword().isEmpty()) && (!pubkeyAuth || this.server.getKeypair() == null)) { - this.connection.closeChannel("Der Server unterstützt keine der vorhandenen\nAuthentifizierungsmethoden\n\nUnterstützt vom Server: " + - (!passwordAuth && !pubkeyAuth ? "Keine" : ((passwordAuth ? "Passwort" : "") + (passwordAuth && pubkeyAuth ? " und " : "") + (pubkeyAuth ? "Pubkey" : ""))) + - "\n\nVorhanden in Konfiguration für '" + this.server.getName() + "': " + (this.server.getPassword().isEmpty() && this.server.getKeypair() == null ? "Keine" : - ((!this.server.getPassword().isEmpty() ? "Passwort" : "") + - (!this.server.getPassword().isEmpty() && this.server.getKeypair() != null ? " und " : "") + (this.server.getKeypair() != null ? "Pubkey" : "")))); - return; - } - if(auth && pubkeyAuth && this.server.getKeypair() != null) { - this.state = LoginState.PROVING; - this.connection.sendPacket(new LPacketPubkey(this.server.getUser(), this.server.getAccess(), this.server.getKeypair().getPublic())); - } - else { - this.state = LoginState.AUTHENTICATING; - this.connection.sendPacket(new LPacketPassword(this.server.getUser(), this.server.getAccess(), auth ? this.server.getPassword() : "")); - } - } - - public void handleChallenge(RPacketChallenge packet) { - if(this.state != LoginState.PROVING) { - this.connection.closeChannel("Unerwartetes Anforderungs-Paket"); - return; - } - this.state = LoginState.AUTHENTICATING; - this.connection.sendPacket(new LPacketResponse(this.server.getKeypair().getPrivate(), packet.getToken())); - } - - public void handleLoginSuccess(RPacketLoginSuccess packet) - { - if(this.state != LoginState.AUTHENTICATING) { - this.connection.closeChannel("Unerwartetes Bestätigungs-Paket"); - return; - } - this.state = LoginState.DONE; - this.connection.setConnectionState(PacketRegistry.PLAY); - this.connection.setNetHandler(new ClientPlayer(this.gm, this.connection)); - } - - public void handleEnableCompression(RPacketEnableCompression packet) - { - this.connection.setCompressionTreshold(packet.getValue()); - } -} diff --git a/client/src/main/java/client/network/DummyConnection.java b/client/src/main/java/client/network/DummyConnection.java deleted file mode 100644 index b9f6323..0000000 --- a/client/src/main/java/client/network/DummyConnection.java +++ /dev/null @@ -1,67 +0,0 @@ -package client.network; - -import javax.crypto.SecretKey; - -import common.net.channel.ChannelHandlerContext; -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; -import common.network.NetConnection; -import common.network.NetHandler; -import common.network.Packet; -import common.network.PacketRegistry; - -public class DummyConnection extends NetConnection { - public void channelActive(ChannelHandlerContext context) throws Exception { - } - - public void setConnectionState(PacketRegistry newState) { - } - - public void channelInactive(ChannelHandlerContext context) throws Exception { - } - - public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) throws Exception { - } - - protected void channelRead0(ChannelHandlerContext context, Packet packet) throws Exception { - } - - public void setNetHandler(NetHandler handler) { - } - - public void sendPacket(Packet packet) { - } - - public void sendPacket(Packet packet, GenericFutureListener> listener) { - } - - public void processReceivedPackets() { - } - - public String getCutAddress() { - return "local"; - } - - public void closeChannel(String message) { - } - - public boolean isChannelOpen() { - return true; - } - - public boolean hasNoChannel() { - return false; - } - - public void disableAutoRead() { - } - - public void setCompressionTreshold(int treshold) { - } - - public void checkDisconnected() { - } - - public void startEncryption(SecretKey key) { - } -} diff --git a/client/src/main/java/client/network/LocalContainer.java b/client/src/main/java/client/network/LocalContainer.java deleted file mode 100755 index 80653a1..0000000 --- a/client/src/main/java/client/network/LocalContainer.java +++ /dev/null @@ -1,50 +0,0 @@ -package client.network; - -import java.util.Map; - -import common.collect.Maps; -import common.entity.npc.EntityNPC; -import common.inventory.Container; -import common.inventory.InventoryBasic; -import common.inventory.InventoryPlayer; -import common.tileentity.ILockableContainer; -import common.tileentity.Passcode; - -public class LocalContainer extends InventoryBasic implements ILockableContainer { - private Map fields = Maps.newHashMap(); - - public LocalContainer(String title, int slotCount) { - super(title, slotCount); - } - - public int getField(int id) { - return this.fields.containsKey(Integer.valueOf(id)) ? ((Integer)this.fields.get(Integer.valueOf(id))).intValue() : 0; - } - - public void setField(int id, int value) { - this.fields.put(Integer.valueOf(id), Integer.valueOf(value)); - } - - public int getFieldCount() { - return this.fields.size(); - } - - public boolean isLocked() { - return false; - } - - public void setLockCode(Passcode code) { - } - - public Passcode getLockCode() { - return Passcode.EMPTY_CODE; - } - - public String getGuiID() { - return null; - } - - public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) { - throw new UnsupportedOperationException(); - } -} diff --git a/client/src/main/java/client/renderer/VertexFormatElement.java b/client/src/main/java/client/renderer/VertexFormatElement.java deleted file mode 100755 index 9062f91..0000000 --- a/client/src/main/java/client/renderer/VertexFormatElement.java +++ /dev/null @@ -1,84 +0,0 @@ -package client.renderer; - -import org.lwjgl.opengl.GL11; - -public record VertexFormatElement(int index, VertexFormatElement.EnumType type, VertexFormatElement.EnumUsage usage, int count) { - public String toString() { - return this.count + "," + this.usage.getName() + "," + this.type.getName(); - } - - public int size() { - return this.type.getSize() * this.count; - } - - public boolean isPosition() { - return this.usage == VertexFormatElement.EnumUsage.POSITION; - } - - public boolean equals(Object other) { - if(this == other) - return true; - if(!(other instanceof VertexFormatElement)) - return false; - VertexFormatElement elem = (VertexFormatElement)other; - return this.count == elem.count && this.index == elem.index && this.type == elem.type && this.usage == elem.usage; - } - - public int hashCode() { - int i = this.type.hashCode(); - i = 31 * i + this.usage.hashCode(); - i = 31 * i + this.index; - i = 31 * i + this.count; - return i; - } - - public static enum EnumType { - FLOAT(4, "Float", GL11.GL_FLOAT), - UBYTE(1, "Unsigned Byte", GL11.GL_UNSIGNED_BYTE), - BYTE(1, "Byte", GL11.GL_BYTE), - USHORT(2, "Unsigned Short", GL11.GL_UNSIGNED_SHORT), - SHORT(2, "Short", GL11.GL_SHORT), - UINT(4, "Unsigned Int", GL11.GL_UNSIGNED_INT), - INT(4, "Int", GL11.GL_INT); - - private final int size; - private final String name; - private final int glConstant; - - private EnumType(int size, String name, int glConstant) { - this.size = size; - this.name = name; - this.glConstant = glConstant; - } - - public int getSize() { - return this.size; - } - - public String getName() { - return this.name; - } - - public int getGlConstant() { - return this.glConstant; - } - } - - public static enum EnumUsage { - POSITION("Position"), - NORMAL("Normal"), - COLOR("Vertex Color"), - UV("UV"), - PADDING("Padding"); - - private final String name; - - private EnumUsage(String name) { - this.name = name; - } - - public String getName() { - return this.name; - } - } -} diff --git a/client/src/main/java/client/renderer/blockmodel/BakedModel.java b/client/src/main/java/client/renderer/blockmodel/BakedModel.java deleted file mode 100755 index c0ccd78..0000000 --- a/client/src/main/java/client/renderer/blockmodel/BakedModel.java +++ /dev/null @@ -1,87 +0,0 @@ -package client.renderer.blockmodel; - -import java.util.ArrayList; -import java.util.List; - -import client.renderer.texture.TextureAtlasSprite; -import common.collect.Lists; -import common.model.Transforms; -import common.util.Facing; - -public record BakedModel(List getQuads, List> getFace, boolean isGui3d, TextureAtlasSprite getBaseTexture, Transforms getTransforms) implements IBakedModel { - public List getFace(Facing face) { - return this.getFace.get(face.ordinal()); - } - - public boolean isBuiltin() { - return false; - } - - public static class Builder { - private final List quads; - private final List> faces; - private TextureAtlasSprite texture; - private boolean gui3d; - private Transforms transforms; - - public Builder(ModelBlock model) { - this(model.isGui3d(), model.getTransform()); - } - - public Builder(IBakedModel model, TextureAtlasSprite texture) { - this(model.isGui3d(), model.getTransforms()); - this.texture = model.getBaseTexture(); - - for(Facing face : Facing.values()) { - this.addFaceBreakingFours(model, texture, face); - } - - this.addGeneralBreakingFours(model, texture); - } - - private void addFaceBreakingFours(IBakedModel model, TextureAtlasSprite texture, Facing facing) { - for(BakedQuad quad : model.getFace(facing)) { - this.addFaceQuad(facing, new BreakingFour(quad, texture)); - } - } - - private void addGeneralBreakingFours(IBakedModel model, TextureAtlasSprite texture) { - for(BakedQuad quad : model.getQuads()) { - this.addGeneralQuad(new BreakingFour(quad, texture)); - } - } - - private Builder(boolean gui3d, Transforms transforms) { - this.quads = Lists.newArrayList(); - this.faces = new ArrayList>(6); - - for(Facing face : Facing.values()) { - this.faces.add(Lists.newArrayList()); - } - - this.gui3d = gui3d; - this.transforms = transforms; - } - - public BakedModel.Builder addFaceQuad(Facing face, BakedQuad quad) { - this.faces.get(face.ordinal()).add(quad); - return this; - } - - public BakedModel.Builder addGeneralQuad(BakedQuad quad) { - this.quads.add(quad); - return this; - } - - public BakedModel.Builder setTexture(TextureAtlasSprite texture) { - this.texture = texture; - return this; - } - - public BakedModel makeBakedModel() { - if(this.texture == null) - throw new RuntimeException("Fehlende Basistextur"); - return new BakedModel(this.quads, this.faces, this.gui3d, this.texture, this.transforms); - } - } -} diff --git a/client/src/main/java/client/renderer/blockmodel/BuiltInModel.java b/client/src/main/java/client/renderer/blockmodel/BuiltInModel.java deleted file mode 100755 index fd40a16..0000000 --- a/client/src/main/java/client/renderer/blockmodel/BuiltInModel.java +++ /dev/null @@ -1,29 +0,0 @@ -package client.renderer.blockmodel; - -import java.util.List; - -import client.renderer.texture.TextureAtlasSprite; -import common.model.Transforms; -import common.util.Facing; - -public record BuiltInModel(Transforms getTransforms) implements IBakedModel { - public List getFace(Facing face) { - return null; - } - - public List getQuads() { - return null; - } - - public boolean isGui3d() { - return true; - } - - public boolean isBuiltin() { - return true; - } - - public TextureAtlasSprite getBaseTexture() { - return null; - } -} diff --git a/client/src/main/java/client/renderer/blockmodel/IBakedModel.java b/client/src/main/java/client/renderer/blockmodel/IBakedModel.java deleted file mode 100755 index d1de616..0000000 --- a/client/src/main/java/client/renderer/blockmodel/IBakedModel.java +++ /dev/null @@ -1,22 +0,0 @@ -package client.renderer.blockmodel; - -import java.util.List; - -import client.renderer.texture.TextureAtlasSprite; -import common.model.Transforms; -import common.util.Facing; - -public interface IBakedModel -{ - List getFace(Facing facing); - - List getQuads(); - - boolean isGui3d(); - - boolean isBuiltin(); - - TextureAtlasSprite getBaseTexture(); - - Transforms getTransforms(); -} diff --git a/client/src/main/java/client/renderer/entity/RenderFox.java b/client/src/main/java/client/renderer/entity/RenderFox.java deleted file mode 100644 index d3bc73b..0000000 --- a/client/src/main/java/client/renderer/entity/RenderFox.java +++ /dev/null @@ -1,16 +0,0 @@ -package client.renderer.entity; - -import client.renderer.model.ModelBase; -import common.entity.animal.EntityFox; - -public class RenderFox extends RenderLiving { - private static final String FOX_TEXTURE = "textures/entity/fox.png"; - - public RenderFox(RenderManager renderManagerIn, ModelBase modelBaseIn) { - super(renderManagerIn, modelBaseIn); - } - - protected String getEntityTexture(EntityFox entity) { - return FOX_TEXTURE; - } -} diff --git a/client/src/main/java/client/renderer/model/ModelFox.java b/client/src/main/java/client/renderer/model/ModelFox.java deleted file mode 100644 index cedf720..0000000 --- a/client/src/main/java/client/renderer/model/ModelFox.java +++ /dev/null @@ -1,97 +0,0 @@ -package client.renderer.model; - -import org.lwjgl.opengl.GL11; - -import common.entity.Entity; -import common.util.ExtMath; - -public class ModelFox extends ModelBase -{ - private final ModelRenderer head; - private final ModelRenderer body; - private final ModelRenderer wolfLeg1; - private final ModelRenderer wolfLeg2; - private final ModelRenderer wolfLeg3; - private final ModelRenderer wolfLeg4; - private final ModelRenderer tail; - - public ModelFox() - { - float f = 0.0F; - this.head = new ModelRenderer(this, 0, 0); - this.head.addBox(-3.0F, -3.0F, -2.0F, 6, 6, 4, f); - this.head.setRotationPoint(-1.0F, 15.5F, -7.0F); - this.body = new ModelRenderer(this, 24, 0); - this.body.addBox(-3.5F, -2.0F, -2.0F, 5, 13, 5, f); - this.body.setRotationPoint(0.0F, 16.0F, -4.0F); - this.wolfLeg1 = new ModelRenderer(this, 0, 18); - this.wolfLeg1.addBox(-1.0F, 0.0F, -1.0F, 2, 6, 2, f); - this.wolfLeg1.setRotationPoint(-2.49F, 18.0F, 5.0F); - this.wolfLeg2 = new ModelRenderer(this, 0, 18); - this.wolfLeg2.addBox(-1.0F, 0.0F, -1.0F, 2, 6, 2, f); - this.wolfLeg2.setRotationPoint(0.49F, 18.0F, 5.0F); - this.wolfLeg3 = new ModelRenderer(this, 0, 18); - this.wolfLeg3.addBox(-1.0F, 0.0F, -1.0F, 2, 6, 2, f); - this.wolfLeg3.setRotationPoint(-2.49F, 18.0F, -4.0F); - this.wolfLeg4 = new ModelRenderer(this, 0, 18); - this.wolfLeg4.addBox(-1.0F, 0.0F, -1.0F, 2, 6, 2, f); - this.wolfLeg4.setRotationPoint(0.49F, 18.0F, -4.0F); - this.tail = new ModelRenderer(this, 9, 18); - this.tail.addBox(-1.5F, 0.0F, -1.0F, 3, 10, 3, f); - this.tail.setRotationPoint(-1.0F, 15.0F, 6.0F); - this.head.setTextureOffset(16, 14).addBox(-3.15F, -4.35F, 0.0F, 2, 2, 1, f); - this.head.setTextureOffset(16, 14).addBox(1.15F, -4.35F, 0.0F, 2, 2, 1, f); - this.head.setTextureOffset(0, 10).addBox(-1.5F, 0.0F, -5.0F, 3, 2, 4, f); - this.head.setTextureOffset(16, 11).addBox(-3.15F, -5.35F, 0.0F, 1, 1, 1, f); - this.head.setTextureOffset(16, 11).addBox(2.15F, -5.35F, 0.0F, 1, 1, 1, f); - } - - public void render(Entity entityIn, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float scale) - { - super.render(entityIn, p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, scale); - this.setRotationAngles(p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, scale, entityIn); - - if (this.isChild) - { - float f = 2.0F; - GL11.glPushMatrix(); - GL11.glTranslatef(0.0F, 3.5F * scale, 2.0F * scale); - this.head.renderWithRotation(scale); - GL11.glPopMatrix(); - GL11.glPushMatrix(); - GL11.glScalef(1.0F / f, 1.0F / f, 1.0F / f); - GL11.glTranslatef(0.0F, 24.0F * scale, 0.0F); - this.body.render(scale); - this.wolfLeg1.render(scale); - this.wolfLeg2.render(scale); - this.wolfLeg3.render(scale); - this.wolfLeg4.render(scale); - this.tail.renderWithRotation(scale); - GL11.glPopMatrix(); - } - else - { - this.head.renderWithRotation(scale); - this.body.render(scale); - this.wolfLeg1.render(scale); - this.wolfLeg2.render(scale); - this.wolfLeg3.render(scale); - this.wolfLeg4.render(scale); - this.tail.renderWithRotation(scale); - } - } - - public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn) - { - super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn); - this.tail.rotateAngleY = ExtMath.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount; - this.body.rotateAngleX = ((float)Math.PI / 2F); - this.wolfLeg1.rotateAngleX = ExtMath.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount; - this.wolfLeg2.rotateAngleX = ExtMath.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount; - this.wolfLeg3.rotateAngleX = ExtMath.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount; - this.wolfLeg4.rotateAngleX = ExtMath.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount; - this.head.rotateAngleX = headPitch / (180F / (float)Math.PI); - this.head.rotateAngleY = netHeadYaw / (180F / (float)Math.PI); - this.tail.rotateAngleX = (float)Math.PI / 2.5F; - } -} diff --git a/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono1.java b/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono1.java deleted file mode 100644 index df13b2a..0000000 --- a/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono1.java +++ /dev/null @@ -1,7 +0,0 @@ -package client.renderer.ticked; - -public class TextureFlamesFXMono1 extends TextureFlamesFX1 { - public TextureFlamesFXMono1() { - super(true); - } -} diff --git a/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono2.java b/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono2.java deleted file mode 100644 index 2c4a094..0000000 --- a/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono2.java +++ /dev/null @@ -1,7 +0,0 @@ -package client.renderer.ticked; - -public class TextureFlamesFXMono2 extends TextureFlamesFX2 { - public TextureFlamesFXMono2() { - super(true); - } -} diff --git a/client/src/main/java/client/renderer/tileentity/TileEntityItemStackRenderer.java b/client/src/main/java/client/renderer/tileentity/TileEntityItemStackRenderer.java deleted file mode 100755 index d470a79..0000000 --- a/client/src/main/java/client/renderer/tileentity/TileEntityItemStackRenderer.java +++ /dev/null @@ -1,27 +0,0 @@ -package client.renderer.tileentity; - -import common.init.Items; -import common.item.ItemStack; -import common.tileentity.TileEntityBanner; -import common.tileentity.TileEntityChest; - -public class TileEntityItemStackRenderer { - public static TileEntityItemStackRenderer instance = new TileEntityItemStackRenderer(); - - private final TileEntityChest chest = new TileEntityChest(0); - private final TileEntityChest trapChest = new TileEntityChest(1); - private final TileEntityBanner banner = new TileEntityBanner(); - - public void renderByItem(ItemStack stack) { - if(stack.getItem() == Items.banner) { - this.banner.setItemValues(stack); - TileEntityRendererDispatcher.instance.renderTileEntityAt(this.banner, 0.0D, 0.0D, 0.0D, 0.0F); - } - else if(stack.getItem() == Items.trapped_chest) { - TileEntityRendererDispatcher.instance.renderTileEntityAt(this.trapChest, 0.0D, 0.0D, 0.0D, 0.0F); - } - else if(stack.getItem() == Items.chest) { - TileEntityRendererDispatcher.instance.renderTileEntityAt(this.chest, 0.0D, 0.0D, 0.0D, 0.0F); - } - } -} diff --git a/client/src/main/java/client/util/FileUtils.java b/client/src/main/java/client/util/FileUtils.java deleted file mode 100644 index 86f2731..0000000 --- a/client/src/main/java/client/util/FileUtils.java +++ /dev/null @@ -1,65 +0,0 @@ -package client.util; - -import java.io.ByteArrayOutputStream; -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.nio.charset.Charset; - -public class FileUtils { - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - public static String read(File file) throws IOException { - FileInputStream in = null; - String s; - try { - in = new FileInputStream(file); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - byte[] buffer = new byte[4096]; - long count = 0L; - int n; - for(boolean u = false; -1 != (n = in.read(buffer)); count += (long)n) { - output.write(buffer, 0, n); - } - s = new String(output.toByteArray(), UTF_8); - } - finally { - try { - if(in != null) - in.close(); - } - catch(IOException e) { - } - } - return s; - } - - public static void write(File file, String data) throws IOException { - FileOutputStream out = null; - try { - out = new FileOutputStream(file); - if(out != null) { - out.write(data.getBytes(UTF_8)); - out.close(); - } - } - finally { - try { - if(out != null) - out.close(); - } - catch(IOException e) { - } - } - } - - public static InputStream getResource(String path) throws FileNotFoundException { - InputStream in = FileUtils.class.getResourceAsStream("/" + path); - if(in == null) - throw new FileNotFoundException(path); - return in; - } -} diff --git a/client/src/main/java/client/util/Message.java b/client/src/main/java/client/util/Message.java deleted file mode 100644 index 284196c..0000000 --- a/client/src/main/java/client/util/Message.java +++ /dev/null @@ -1,4 +0,0 @@ -package client.util; - -public record Message(String message, long time) { -} diff --git a/client/src/main/java/client/util/PlayerController.java b/client/src/main/java/client/util/PlayerController.java deleted file mode 100755 index e18d64f..0000000 --- a/client/src/main/java/client/util/PlayerController.java +++ /dev/null @@ -1,314 +0,0 @@ -package client.util; - -import client.Client; -import client.network.ClientPlayer; -import client.world.WorldClient; -import common.block.Block; -import common.entity.Entity; -import common.entity.npc.EntityNPC; -import common.init.BlockRegistry; -import common.init.Blocks; -import common.init.EntityRegistry; -import common.item.ItemBlock; -import common.item.ItemControl; -import common.item.ItemStack; -import common.packet.CPacketAction; -import common.packet.CPacketBreak; -import common.packet.CPacketClick; -import common.packet.CPacketPlace; -import common.sound.PositionedSound; -import common.util.BlockPos; -import common.util.Facing; -import common.util.Vec3; -import common.world.State; -import common.world.World; - -public class PlayerController { - private final Client gm; - private final ClientPlayer handler; - - private BlockPos position = new BlockPos(-1, -World.MAX_SIZE_Y - 1, -1); - private ItemStack stack; - private float damage; - private float stepCounter; - private int delay; - private boolean hitting; - private int lastSelected; - private boolean interacting; - - public PlayerController(Client gm, ClientPlayer handler) { - this.gm = gm; - this.handler = handler; - } - - public boolean destroyBlock(BlockPos pos, Facing side) { - World world = this.gm.world; - State state = world.getState(pos); - Block block = state.getBlock(); - - if(block == Blocks.air) { - return false; - } - else { - world.playAuxSFX(2001, pos, BlockRegistry.getStateId(state)); - boolean flag = world.setBlockToAir(pos); - - if(flag) { - block.onBlockDestroyedByPlayer(world, pos, state); - } - - this.position = new BlockPos(this.position.getX(), -1, this.position.getZ()); - - ItemStack stack = this.gm.player.getCurrentEquippedItem(); - - if(stack != null) { - stack.onBlockDestroyed(world, block, pos, this.gm.player); - - if(stack.size == 0) { - this.gm.player.destroyCurrentEquippedItem(); - } - } - - return flag; - } - } - - public boolean clickBlock(BlockPos pos, Facing face) { - if(!World.isValidXZ(pos)) { - return false; - } - else { - ItemStack stack = this.gm.player.getHeldItem(); - if(stack != null && stack.getItem().onAction(stack, this.gm.player, this.gm.world, ItemControl.PRIMARY, pos)) { - this.interacting = true; - this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, pos, face)); - return true; - } - if(!this.hitting || !this.isHitting(pos)) { - if(this.hitting) { - this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.ABORT_DESTROY_BLOCK, this.position, face)); - } - - this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, pos, face)); - Block block = this.gm.world.getState(pos).getBlock(); - boolean flag = block != Blocks.air; - - if(flag && this.damage == 0.0F) { - block.onBlockClicked(this.gm.world, pos, this.gm.player); - } - - if(flag && block.getPlayerRelativeBlockHardness(this.gm.player, this.gm.player.worldObj, pos) >= 1.0F) { - this.destroyBlock(pos, face); - this.delay = 3; - } - else { - this.hitting = true; - this.position = pos; - this.stack = this.gm.player.getHeldItem(); - this.damage = 0.0F; - this.stepCounter = 0.0F; - this.gm.world.sendBlockBreakProgress(this.gm.player.getId(), this.position, (int)(this.damage * 10.0F) - 1); - } - } - - return true; - } - } - - public void resetProgress() { - if(this.hitting) { - this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.ABORT_DESTROY_BLOCK, this.position, Facing.DOWN)); - this.hitting = false; - this.damage = 0.0F; - this.gm.world.sendBlockBreakProgress(this.gm.player.getId(), this.position, -1); - } - } - - public void resetInteraction() { - this.interacting = false; - } - - public boolean damageBlock(BlockPos pos, Facing face) { - if(this.interacting) - return false; - this.syncItem(); - - if(this.delay > 0) { - --this.delay; - return true; - } - else if(this.isHitting(pos)) { - Block block = this.gm.world.getState(pos).getBlock(); - - if(block == Blocks.air) { - this.hitting = false; - return false; - } - else { - this.damage += block.getPlayerRelativeBlockHardness(this.gm.player, this.gm.player.worldObj, pos); - - if(this.stepCounter % 4.0F == 0.0F && block.sound.getStepSound() != null) { - this.gm.getSoundManager().playSound(new PositionedSound(block.sound.getStepSound(), 0.25F, - (float)pos.getX() + 0.5F, (float)pos.getY() + 0.5F, (float)pos.getZ() + 0.5F)); - } - - ++this.stepCounter; - - if(this.damage >= 1.0F) { - this.hitting = false; - this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.STOP_DESTROY_BLOCK, pos, face)); - this.destroyBlock(pos, face); - this.damage = 0.0F; - this.stepCounter = 0.0F; - this.delay = 5; - } - - this.gm.world.sendBlockBreakProgress(this.gm.player.getId(), this.position, (int)(this.damage * 10.0F) - 1); - return true; - } - } - else { - return this.clickBlock(pos, face); - } - } - - public void update() { - this.syncItem(); - - if(this.handler.getConnection().isChannelOpen()) { - this.handler.getConnection().processReceivedPackets(); - } - else { - this.handler.getConnection().checkDisconnected(); - } - } - - private boolean isHitting(BlockPos pos) { - ItemStack stack = this.gm.player.getHeldItem(); - boolean flag = this.stack == null && stack == null; - - if(this.stack != null && stack != null) { - flag = stack.getItem() == this.stack.getItem() - && ItemStack.areItemStackTagsEqual(stack, this.stack) - && (stack.isItemStackDamageable() || stack.getMetadata() == this.stack.getMetadata()); - } - - return pos.equals(this.position) && flag; - } - - private void syncItem() { - int slot = this.gm.player.inventory.currentItem; - - if(slot != this.lastSelected) { - this.lastSelected = slot; - this.handler.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_ITEMSLOT, this.lastSelected)); - } - } - - public boolean clickRight(EntityNPC player, WorldClient world, ItemStack stack, BlockPos pos, Facing side, Vec3 hit) { - this.syncItem(); - float f = (float)(hit.xCoord - (double)pos.getX()); - float f1 = (float)(hit.yCoord - (double)pos.getY()); - float f2 = (float)(hit.zCoord - (double)pos.getZ()); - boolean flag = false; - - if(!World.isValidXZ(pos)) { - return false; - } - else { - if(stack == null || !stack.getItem().onAction(stack, player, world, ItemControl.SECONDARY, pos)) { - State iblockstate = world.getState(pos); - - if((!player.isSneaking() || player.getHeldItem() == null) - && iblockstate.getBlock().onBlockActivated(world, pos, iblockstate, player, side, f, f1, f2)) { - flag = true; - } - - if(!flag && stack != null && stack.getItem() instanceof ItemBlock) { - ItemBlock itemblock = (ItemBlock)stack.getItem(); - - if(!itemblock.canPlaceBlockOnSide(world, pos, side, player, stack)) { - return false; - } - } - } - else { - stack.getItem().onItemUse(stack, player, world, pos, side, f, f1, f2); - flag = true; - } - - this.handler.addToSendQueue(new CPacketPlace(pos, side.getIndex(), player.inventory.getCurrentItem(), f, f1, f2)); - - if(!flag) { - if(stack == null) { - return false; - } - else { - return stack.onItemUse(player, world, pos, side, f, f1, f2); - } - } - else { - return true; - } - } - } - - public boolean sendUseItem(EntityNPC player, World world, ItemStack stack) { - this.syncItem(); - this.handler.addToSendQueue(new CPacketPlace(player.inventory.getCurrentItem())); - int size = stack.size; - ItemStack changed = stack.useItemRightClick(world, player); - - if(changed != stack || changed != null && changed.size != size) { - player.inventory.mainInventory[player.inventory.currentItem] = changed; - - if(changed.size == 0) { - player.inventory.mainInventory[player.inventory.currentItem] = null; - } - - return true; - } - else { - return false; - } - } - - public EntityNPC createPlayerEntity(WorldClient world, int type) { - EntityNPC player = (EntityNPC)EntityRegistry.createEntityByID(type, world); - player.setClientPlayer(this.handler); - return player; - } - - public void attackEntity(EntityNPC player, Entity target) { - this.syncItem(); - this.handler.addToSendQueue(new CPacketAction(CPacketAction.Action.ATTACK, target.getId())); - player.attackTargetEntityWithCurrentItem(target); - } - - public boolean interact(EntityNPC player, Entity target) { - this.syncItem(); - this.handler.addToSendQueue(new CPacketAction(CPacketAction.Action.INTERACT, target.getId())); - return player.interactWith(target); - } - - public ItemStack windowClick(int window, int slot, int button, int mode, EntityNPC player) { - short id = player.openContainer.getNextTransactionID(player.inventory); - ItemStack stack = player.openContainer.slotClick(slot, button, mode, player); - this.handler.addToSendQueue(new CPacketClick(window, slot, button, mode, stack, id)); - return stack; - } - - public void sendEnchantPacket(int window, int button) { - this.handler.addToSendQueue(new CPacketAction(CPacketAction.Action.ENCHANT_ITEM, window | (button << 8))); - } - - public void stopUsing(EntityNPC player) { - this.syncItem(); - this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, Facing.DOWN)); - player.stopUsingItem(); - } - - public boolean isHittingBlock() { - return this.hitting; - } -} diff --git a/client/src/main/java/client/window/WindowEvent.java b/client/src/main/java/client/window/WindowEvent.java deleted file mode 100644 index b92f7a6..0000000 --- a/client/src/main/java/client/window/WindowEvent.java +++ /dev/null @@ -1,4 +0,0 @@ -package client.window; - -public record WindowEvent(WindowAction action, int param1, int param2) { -} diff --git a/client/src/main/java/client/world/ChunkClient.java b/client/src/main/java/client/world/ChunkClient.java deleted file mode 100644 index 8f59b89..0000000 --- a/client/src/main/java/client/world/ChunkClient.java +++ /dev/null @@ -1,144 +0,0 @@ -package client.world; - -import common.biome.Biome; -import common.block.Block; -import common.init.Blocks; -import common.tileentity.TileEntity; -import common.util.BlockPos; -import common.util.NibbleArray; -import common.world.BlockArray; -import common.world.Chunk; -import common.world.World; - -public class ChunkClient extends Chunk { - public ChunkClient(World world, int x, int z) { - super(world, x, z); - } - - private void clearArrays() { - this.blocks.clearMap(); - this.blockList.clear(); - this.bottom = Integer.MAX_VALUE; - this.top = Integer.MIN_VALUE; - } - - private void genHeights() { - int top = this.top; - int bottom = this.bottom; - this.minHeight = Integer.MAX_VALUE; - - for(int x = 0; x < 16; ++x) { - for(int z = 0; z < 16; ++z) { - this.precHeight[x + (z << 4)] = -99999999; - - for(int y = top + 16; y > bottom; --y) { - Block block = this.getBlock0(x, y - 1, z); - - if(block.getLightOpacity() != 0) { - this.height[z << 4 | x] = y; - - if(y < this.minHeight) { - this.minHeight = y; - } - - break; - } - } - } - } - - this.modified = true; - } - - public boolean isEmpty(int bottom, int top) { - for(int y = bottom; y <= top; y += 16) { - BlockArray stor = this.getArray(y >> 4); - - if(stor != null ? !stor.isEmpty() : (y < 0 && this.fillerBlock != Blocks.air)) { - return false; - } - } - - return true; - } - - public void setData(byte[] data, int[] extend, boolean biomes) { - int pos = 0; - boolean sky = !this.world.dimension.hasNoLight(); - - if(biomes) { - this.clearArrays(); - } - for(int cy : extend) { - BlockArray arr = this.getArray(cy); - if(arr == null) { - arr = new BlockArray(cy << 4, sky, null); - this.setArray(arr); - } - - char[] blocks = arr.getData(); - - for(int k = 0; k < blocks.length; ++k) { - blocks[k] = (char)((data[pos + 1] & 255) << 8 | data[pos] & 255); - pos += 2; - } - } - - for(int cy : extend) { - BlockArray arr = this.getArray(cy); - if(arr != null) { - NibbleArray light = arr.getBlocklight(); - System.arraycopy(data, pos, light.getData(), 0, light.getData().length); - pos += light.getData().length; - } - } - - if(sky) { - for(int cy : extend) { - BlockArray arr = this.getArray(cy); - if(arr != null) { - NibbleArray slight = arr.getSkylight(); - System.arraycopy(data, pos, slight.getData(), 0, slight.getData().length); - pos += slight.getData().length; - } - } - } - - if(biomes) { - System.arraycopy(data, pos, this.biomes, 0, this.biomes.length); - } - - for(int cy : extend) { - BlockArray arr = this.getArray(cy); - if(arr != null) { - arr.update(); - } - } - - this.lightInit = true; - this.populated = true; - this.genHeights(); - - for(TileEntity tile : this.tiles.values()) { - tile.updateContainingBlockInfo(); - } - } - - public void setLoaded() { - this.loaded = true; - } - - public Biome getBiome(BlockPos pos) { - int x = pos.getX() & 15; - int z = pos.getZ() & 15; - return Biome.getBiomeDef(this.biomes[z << 4 | x] & 255); - } - - public void setBiome(BlockPos pos, Biome biome) { - this.biomes[((pos.getZ() & 15) << 4 | pos.getX() & 15)] = (byte)biome.id; - } - - public boolean isDummy() { - return false; - } -} diff --git a/client/src/main/java/client/world/ChunkEmpty.java b/client/src/main/java/client/world/ChunkEmpty.java deleted file mode 100755 index dce55fe..0000000 --- a/client/src/main/java/client/world/ChunkEmpty.java +++ /dev/null @@ -1,172 +0,0 @@ -package client.world; - -import java.util.List; -import java.util.function.Predicate; - -import common.biome.Biome; -import common.block.Block; -import common.collect.Lists; -import common.entity.Entity; -import common.init.BlockRegistry; -import common.init.Blocks; -import common.tileentity.TileEntity; -import common.util.BlockPos; -import common.util.BoundingBox; -import common.util.ExtMath; -import common.world.LightType; -import common.world.State; - -public class ChunkEmpty extends ChunkClient { - private static final List STATES = Lists.newArrayList(); - private static final int XSTRETCH; - private static final int ZSTRETCH; - - private final boolean debug; - private final int liquidY; - private final State liquid; - private final Block liquidBlock; - private final State dummy; - private final Block dummyBlock; - - static { - for(Block block : BlockRegistry.REGISTRY) { - STATES.addAll(block.getValidStates()); - } - XSTRETCH = ExtMath.ceilf(ExtMath.sqrtf((float)STATES.size())); - ZSTRETCH = ExtMath.ceilf((float)STATES.size() / (float)XSTRETCH); - } - - private static State getDebug(int x, int z) { - State state = null; - if(x > 0 && z > 0 && x % 2 != 0 && z % 2 != 0) { - x = x / 2; - z = z / 2; - if(x <= XSTRETCH && z <= ZSTRETCH) { - int idx = ExtMath.absi(x * XSTRETCH + z); - if(idx < STATES.size()) { - state = STATES.get(idx); - } - } - } - return state; - } - - public ChunkEmpty(WorldClient world, boolean debug) { - super(world, 0, 0); - this.debug = debug; - this.liquidY = world.dimension.getSeaLevel() - 1; - this.liquid = world.dimension.getLiquid(); - this.liquidBlock = this.liquid.getBlock(); - this.dummyBlock = this.fillerBlock == Blocks.air ? Blocks.air : Blocks.bedrock; - this.dummy = this.dummyBlock.getState(); - } - - public int getHeight(int x, int z) { - return this.liquidY; - } - - public Block getBlock(BlockPos pos) { - return pos.getY() < this.liquidY ? this.dummyBlock : (pos.getY() == this.liquidY ? this.liquidBlock : Blocks.air); - } - - public int getLight(LightType type, BlockPos pos) { - return type.defValue; - } - - public void setLight(LightType type, BlockPos pos, int value) { - } - - public int getLightSub(BlockPos pos, int amount) { - return 0; - } - - public void addEntity(Entity entity) { - } - - public void removeEntity(Entity entity) { - } - - public boolean canSeeSky(BlockPos pos) { - return pos.getY() > this.liquidY; - } - - public TileEntity getTileEntity(BlockPos pos, TileEntity.EnumCreateEntityType type) { - return null; - } - - public void addTileEntity(BlockPos pos, TileEntity tile) { - } - - public void removeTileEntity(BlockPos pos) { - } - - public void getEntities(Entity exclude, BoundingBox bb, List list, Predicate pred) { - } - - public void getEntities(Class clazz, BoundingBox bb, List list, Predicate pred) { - } - - public boolean isDummy() { - return true; - } - - public boolean isEmpty(int bottom, int top) { - return top < 0 || bottom > this.liquidY; - } - - public State getState(BlockPos pos) { - if(this.debug) { - State state = pos.getY() == 1 ? getDebug(pos.getX(), pos.getZ()) : null; - return state == null ? Blocks.air.getState() : state; - } - return pos.getY() < this.liquidY ? this.dummy : (pos.getY() == this.liquidY ? this.liquid : Blocks.air.getState()); - } - - public State setState(BlockPos pos, State state) { - return null; - } - - public BlockPos getPrecipitation(BlockPos pos) { - return new BlockPos(pos.getX(), this.liquidY + 1, pos.getZ()); - } - - public void update(boolean noGaps) { - } - - public void onChunkUnload() { - } - - public boolean isPopulated() { - return true; - } - - public void setData(byte[] data, int[] extend, boolean biomes) { - } - - public Biome getBiome(BlockPos pos) { - return Biome.DEF_BIOME; - } - - public void setBiome(BlockPos pos, Biome biome) { - } - - public void resetRelight() { - } - - public void enqueueRelight() { - } - - public void checkLight() { - } - - public boolean isLoaded() { - return false; - } - - public void setLoaded() { - } - - public int getLowest() { - return 0; - } -} diff --git a/client/src/main/resources/sounds/anvil_break.ogg b/client/src/main/resources/sounds/anvil_break.ogg deleted file mode 100644 index e18b0c0..0000000 Binary files a/client/src/main/resources/sounds/anvil_break.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/anvil_land.ogg b/client/src/main/resources/sounds/anvil_land.ogg deleted file mode 100644 index 45f9cb3..0000000 Binary files a/client/src/main/resources/sounds/anvil_land.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/anvil_use.ogg b/client/src/main/resources/sounds/anvil_use.ogg deleted file mode 100644 index f161d32..0000000 Binary files a/client/src/main/resources/sounds/anvil_use.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bat_death.ogg b/client/src/main/resources/sounds/bat_death.ogg deleted file mode 100644 index 1767f74..0000000 Binary files a/client/src/main/resources/sounds/bat_death.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bat_hurt1.ogg b/client/src/main/resources/sounds/bat_hurt1.ogg deleted file mode 100644 index b9a0f83..0000000 Binary files a/client/src/main/resources/sounds/bat_hurt1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bat_hurt2.ogg b/client/src/main/resources/sounds/bat_hurt2.ogg deleted file mode 100644 index 5b822d7..0000000 Binary files a/client/src/main/resources/sounds/bat_hurt2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bat_hurt3.ogg b/client/src/main/resources/sounds/bat_hurt3.ogg deleted file mode 100644 index bcdf9b0..0000000 Binary files a/client/src/main/resources/sounds/bat_hurt3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bat_hurt4.ogg b/client/src/main/resources/sounds/bat_hurt4.ogg deleted file mode 100644 index 8c2d7f4..0000000 Binary files a/client/src/main/resources/sounds/bat_hurt4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bat_idle1.ogg b/client/src/main/resources/sounds/bat_idle1.ogg deleted file mode 100644 index c0cbe5a..0000000 Binary files a/client/src/main/resources/sounds/bat_idle1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bat_idle2.ogg b/client/src/main/resources/sounds/bat_idle2.ogg deleted file mode 100644 index ce4f072..0000000 Binary files a/client/src/main/resources/sounds/bat_idle2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bat_idle3.ogg b/client/src/main/resources/sounds/bat_idle3.ogg deleted file mode 100644 index 69ca797..0000000 Binary files a/client/src/main/resources/sounds/bat_idle3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bat_idle4.ogg b/client/src/main/resources/sounds/bat_idle4.ogg deleted file mode 100644 index 9b3aafa..0000000 Binary files a/client/src/main/resources/sounds/bat_idle4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bat_takeoff.ogg b/client/src/main/resources/sounds/bat_takeoff.ogg deleted file mode 100644 index e1dd956..0000000 Binary files a/client/src/main/resources/sounds/bat_takeoff.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/blast.ogg b/client/src/main/resources/sounds/blast.ogg deleted file mode 100644 index 574a89a..0000000 Binary files a/client/src/main/resources/sounds/blast.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/blast_far.ogg b/client/src/main/resources/sounds/blast_far.ogg deleted file mode 100644 index 9bd7709..0000000 Binary files a/client/src/main/resources/sounds/blast_far.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bow.ogg b/client/src/main/resources/sounds/bow.ogg deleted file mode 100644 index b7779c7..0000000 Binary files a/client/src/main/resources/sounds/bow.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bowhit1.ogg b/client/src/main/resources/sounds/bowhit1.ogg deleted file mode 100644 index 4e4cea4..0000000 Binary files a/client/src/main/resources/sounds/bowhit1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bowhit2.ogg b/client/src/main/resources/sounds/bowhit2.ogg deleted file mode 100644 index d08be49..0000000 Binary files a/client/src/main/resources/sounds/bowhit2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bowhit3.ogg b/client/src/main/resources/sounds/bowhit3.ogg deleted file mode 100644 index a97c72d..0000000 Binary files a/client/src/main/resources/sounds/bowhit3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/bowhit4.ogg b/client/src/main/resources/sounds/bowhit4.ogg deleted file mode 100644 index d19c74e..0000000 Binary files a/client/src/main/resources/sounds/bowhit4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/break.ogg b/client/src/main/resources/sounds/break.ogg deleted file mode 100644 index 0357d24..0000000 Binary files a/client/src/main/resources/sounds/break.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cat_hitt1.ogg b/client/src/main/resources/sounds/cat_hitt1.ogg deleted file mode 100644 index 2f361e4..0000000 Binary files a/client/src/main/resources/sounds/cat_hitt1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cat_hitt2.ogg b/client/src/main/resources/sounds/cat_hitt2.ogg deleted file mode 100644 index a969987..0000000 Binary files a/client/src/main/resources/sounds/cat_hitt2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cat_hitt3.ogg b/client/src/main/resources/sounds/cat_hitt3.ogg deleted file mode 100644 index d829d9a..0000000 Binary files a/client/src/main/resources/sounds/cat_hitt3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cat_meow1.ogg b/client/src/main/resources/sounds/cat_meow1.ogg deleted file mode 100644 index 4fdd430..0000000 Binary files a/client/src/main/resources/sounds/cat_meow1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cat_meow2.ogg b/client/src/main/resources/sounds/cat_meow2.ogg deleted file mode 100644 index 686e006..0000000 Binary files a/client/src/main/resources/sounds/cat_meow2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cat_meow3.ogg b/client/src/main/resources/sounds/cat_meow3.ogg deleted file mode 100644 index 2dfcd14..0000000 Binary files a/client/src/main/resources/sounds/cat_meow3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cat_meow4.ogg b/client/src/main/resources/sounds/cat_meow4.ogg deleted file mode 100644 index a242c9a..0000000 Binary files a/client/src/main/resources/sounds/cat_meow4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cat_purreow1.ogg b/client/src/main/resources/sounds/cat_purreow1.ogg deleted file mode 100644 index dfb5897..0000000 Binary files a/client/src/main/resources/sounds/cat_purreow1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cat_purreow2.ogg b/client/src/main/resources/sounds/cat_purreow2.ogg deleted file mode 100644 index daaba56..0000000 Binary files a/client/src/main/resources/sounds/cat_purreow2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/chestclosed.ogg b/client/src/main/resources/sounds/chestclosed.ogg deleted file mode 100644 index a388edd..0000000 Binary files a/client/src/main/resources/sounds/chestclosed.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/chestopen.ogg b/client/src/main/resources/sounds/chestopen.ogg deleted file mode 100644 index c735074..0000000 Binary files a/client/src/main/resources/sounds/chestopen.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/chicken_hurt1.ogg b/client/src/main/resources/sounds/chicken_hurt1.ogg deleted file mode 100644 index a347986..0000000 Binary files a/client/src/main/resources/sounds/chicken_hurt1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/chicken_hurt2.ogg b/client/src/main/resources/sounds/chicken_hurt2.ogg deleted file mode 100644 index 2d018a0..0000000 Binary files a/client/src/main/resources/sounds/chicken_hurt2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/chicken_say1.ogg b/client/src/main/resources/sounds/chicken_say1.ogg deleted file mode 100644 index 649fcf9..0000000 Binary files a/client/src/main/resources/sounds/chicken_say1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/chicken_say2.ogg b/client/src/main/resources/sounds/chicken_say2.ogg deleted file mode 100644 index fef786b..0000000 Binary files a/client/src/main/resources/sounds/chicken_say2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/chicken_say3.ogg b/client/src/main/resources/sounds/chicken_say3.ogg deleted file mode 100644 index d058652..0000000 Binary files a/client/src/main/resources/sounds/chicken_say3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/click.ogg b/client/src/main/resources/sounds/click.ogg deleted file mode 100644 index 51f80df..0000000 Binary files a/client/src/main/resources/sounds/click.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cloth1.ogg b/client/src/main/resources/sounds/cloth1.ogg deleted file mode 100644 index 543794d..0000000 Binary files a/client/src/main/resources/sounds/cloth1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cloth2.ogg b/client/src/main/resources/sounds/cloth2.ogg deleted file mode 100644 index dbe0ad6..0000000 Binary files a/client/src/main/resources/sounds/cloth2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cloth3.ogg b/client/src/main/resources/sounds/cloth3.ogg deleted file mode 100644 index 72b763b..0000000 Binary files a/client/src/main/resources/sounds/cloth3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cloth4.ogg b/client/src/main/resources/sounds/cloth4.ogg deleted file mode 100644 index 233d5de..0000000 Binary files a/client/src/main/resources/sounds/cloth4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cow_hurt1.ogg b/client/src/main/resources/sounds/cow_hurt1.ogg deleted file mode 100644 index 41c0e7c..0000000 Binary files a/client/src/main/resources/sounds/cow_hurt1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cow_hurt2.ogg b/client/src/main/resources/sounds/cow_hurt2.ogg deleted file mode 100644 index 50fea21..0000000 Binary files a/client/src/main/resources/sounds/cow_hurt2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cow_hurt3.ogg b/client/src/main/resources/sounds/cow_hurt3.ogg deleted file mode 100644 index 8f46d2c..0000000 Binary files a/client/src/main/resources/sounds/cow_hurt3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cow_say1.ogg b/client/src/main/resources/sounds/cow_say1.ogg deleted file mode 100644 index 017067d..0000000 Binary files a/client/src/main/resources/sounds/cow_say1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cow_say2.ogg b/client/src/main/resources/sounds/cow_say2.ogg deleted file mode 100644 index 4d7dda3..0000000 Binary files a/client/src/main/resources/sounds/cow_say2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cow_say3.ogg b/client/src/main/resources/sounds/cow_say3.ogg deleted file mode 100644 index a1dd244..0000000 Binary files a/client/src/main/resources/sounds/cow_say3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cow_say4.ogg b/client/src/main/resources/sounds/cow_say4.ogg deleted file mode 100644 index 6cd878d..0000000 Binary files a/client/src/main/resources/sounds/cow_say4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/cut.ogg b/client/src/main/resources/sounds/cut.ogg deleted file mode 100644 index 5643843..0000000 Binary files a/client/src/main/resources/sounds/cut.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/door_close.ogg b/client/src/main/resources/sounds/door_close.ogg deleted file mode 100644 index 5888d1a..0000000 Binary files a/client/src/main/resources/sounds/door_close.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/door_open.ogg b/client/src/main/resources/sounds/door_open.ogg deleted file mode 100644 index fa37300..0000000 Binary files a/client/src/main/resources/sounds/door_open.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/dragon_growl1.ogg b/client/src/main/resources/sounds/dragon_growl1.ogg deleted file mode 100644 index 8de8c81..0000000 Binary files a/client/src/main/resources/sounds/dragon_growl1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/dragon_growl2.ogg b/client/src/main/resources/sounds/dragon_growl2.ogg deleted file mode 100644 index 4a8efcf..0000000 Binary files a/client/src/main/resources/sounds/dragon_growl2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/dragon_growl3.ogg b/client/src/main/resources/sounds/dragon_growl3.ogg deleted file mode 100644 index d3ad63d..0000000 Binary files a/client/src/main/resources/sounds/dragon_growl3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/dragon_growl4.ogg b/client/src/main/resources/sounds/dragon_growl4.ogg deleted file mode 100644 index f50567c..0000000 Binary files a/client/src/main/resources/sounds/dragon_growl4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/dragon_wings1.ogg b/client/src/main/resources/sounds/dragon_wings1.ogg deleted file mode 100644 index bfbeb6c..0000000 Binary files a/client/src/main/resources/sounds/dragon_wings1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/dragon_wings2.ogg b/client/src/main/resources/sounds/dragon_wings2.ogg deleted file mode 100644 index 3ab732a..0000000 Binary files a/client/src/main/resources/sounds/dragon_wings2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/dragon_wings3.ogg b/client/src/main/resources/sounds/dragon_wings3.ogg deleted file mode 100644 index 3026a9c..0000000 Binary files a/client/src/main/resources/sounds/dragon_wings3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/dragon_wings4.ogg b/client/src/main/resources/sounds/dragon_wings4.ogg deleted file mode 100644 index 302b15a..0000000 Binary files a/client/src/main/resources/sounds/dragon_wings4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/dragon_wings5.ogg b/client/src/main/resources/sounds/dragon_wings5.ogg deleted file mode 100644 index d4c61f0..0000000 Binary files a/client/src/main/resources/sounds/dragon_wings5.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/dragon_wings6.ogg b/client/src/main/resources/sounds/dragon_wings6.ogg deleted file mode 100644 index 1af680b..0000000 Binary files a/client/src/main/resources/sounds/dragon_wings6.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/drink.ogg b/client/src/main/resources/sounds/drink.ogg deleted file mode 100644 index b5c7352..0000000 Binary files a/client/src/main/resources/sounds/drink.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/eat1.ogg b/client/src/main/resources/sounds/eat1.ogg deleted file mode 100644 index 3084624..0000000 Binary files a/client/src/main/resources/sounds/eat1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/eat2.ogg b/client/src/main/resources/sounds/eat2.ogg deleted file mode 100644 index 7215480..0000000 Binary files a/client/src/main/resources/sounds/eat2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/eat3.ogg b/client/src/main/resources/sounds/eat3.ogg deleted file mode 100644 index 35a3179..0000000 Binary files a/client/src/main/resources/sounds/eat3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/explode1.ogg b/client/src/main/resources/sounds/explode1.ogg deleted file mode 100644 index b661d29..0000000 Binary files a/client/src/main/resources/sounds/explode1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/explode2.ogg b/client/src/main/resources/sounds/explode2.ogg deleted file mode 100644 index 1a776b5..0000000 Binary files a/client/src/main/resources/sounds/explode2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/explode3.ogg b/client/src/main/resources/sounds/explode3.ogg deleted file mode 100644 index d653c75..0000000 Binary files a/client/src/main/resources/sounds/explode3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/explode4.ogg b/client/src/main/resources/sounds/explode4.ogg deleted file mode 100644 index f5e1649..0000000 Binary files a/client/src/main/resources/sounds/explode4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/fallbig1.ogg b/client/src/main/resources/sounds/fallbig1.ogg deleted file mode 100644 index cb63c8c..0000000 Binary files a/client/src/main/resources/sounds/fallbig1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/fallbig2.ogg b/client/src/main/resources/sounds/fallbig2.ogg deleted file mode 100644 index 25d687b..0000000 Binary files a/client/src/main/resources/sounds/fallbig2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/fallsmall.ogg b/client/src/main/resources/sounds/fallsmall.ogg deleted file mode 100644 index ed9a4e9..0000000 Binary files a/client/src/main/resources/sounds/fallsmall.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/fire.ogg b/client/src/main/resources/sounds/fire.ogg deleted file mode 100644 index 747fe59..0000000 Binary files a/client/src/main/resources/sounds/fire.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/fireball.ogg b/client/src/main/resources/sounds/fireball.ogg deleted file mode 100644 index 9754da5..0000000 Binary files a/client/src/main/resources/sounds/fireball.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/fizz.ogg b/client/src/main/resources/sounds/fizz.ogg deleted file mode 100644 index 60f9b2f..0000000 Binary files a/client/src/main/resources/sounds/fizz.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/fox_death.ogg b/client/src/main/resources/sounds/fox_death.ogg deleted file mode 100644 index 6619338..0000000 Binary files a/client/src/main/resources/sounds/fox_death.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/fox_hurt1.ogg b/client/src/main/resources/sounds/fox_hurt1.ogg deleted file mode 100644 index 52b1335..0000000 Binary files a/client/src/main/resources/sounds/fox_hurt1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/fox_hurt2.ogg b/client/src/main/resources/sounds/fox_hurt2.ogg deleted file mode 100644 index e54d9a6..0000000 Binary files a/client/src/main/resources/sounds/fox_hurt2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/fuse.ogg b/client/src/main/resources/sounds/fuse.ogg deleted file mode 100644 index 6f4e821..0000000 Binary files a/client/src/main/resources/sounds/fuse.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/glass1.ogg b/client/src/main/resources/sounds/glass1.ogg deleted file mode 100644 index 3224a90..0000000 Binary files a/client/src/main/resources/sounds/glass1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/glass2.ogg b/client/src/main/resources/sounds/glass2.ogg deleted file mode 100644 index ba69484..0000000 Binary files a/client/src/main/resources/sounds/glass2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/glass3.ogg b/client/src/main/resources/sounds/glass3.ogg deleted file mode 100644 index a4eac8c..0000000 Binary files a/client/src/main/resources/sounds/glass3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/grass1.ogg b/client/src/main/resources/sounds/grass1.ogg deleted file mode 100644 index f455ecb..0000000 Binary files a/client/src/main/resources/sounds/grass1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/grass2.ogg b/client/src/main/resources/sounds/grass2.ogg deleted file mode 100644 index 6aa1e15..0000000 Binary files a/client/src/main/resources/sounds/grass2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/grass3.ogg b/client/src/main/resources/sounds/grass3.ogg deleted file mode 100644 index 5aad07f..0000000 Binary files a/client/src/main/resources/sounds/grass3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/grass4.ogg b/client/src/main/resources/sounds/grass4.ogg deleted file mode 100644 index 80f360b..0000000 Binary files a/client/src/main/resources/sounds/grass4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/gravel1.ogg b/client/src/main/resources/sounds/gravel1.ogg deleted file mode 100644 index 6481adc..0000000 Binary files a/client/src/main/resources/sounds/gravel1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/gravel2.ogg b/client/src/main/resources/sounds/gravel2.ogg deleted file mode 100644 index 3e38880..0000000 Binary files a/client/src/main/resources/sounds/gravel2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/gravel3.ogg b/client/src/main/resources/sounds/gravel3.ogg deleted file mode 100644 index bcf5d82..0000000 Binary files a/client/src/main/resources/sounds/gravel3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/gravel4.ogg b/client/src/main/resources/sounds/gravel4.ogg deleted file mode 100644 index 75a72c7..0000000 Binary files a/client/src/main/resources/sounds/gravel4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/hit1.ogg b/client/src/main/resources/sounds/hit1.ogg deleted file mode 100644 index 46d3fe6..0000000 Binary files a/client/src/main/resources/sounds/hit1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/hit2.ogg b/client/src/main/resources/sounds/hit2.ogg deleted file mode 100644 index e01af94..0000000 Binary files a/client/src/main/resources/sounds/hit2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/hit3.ogg b/client/src/main/resources/sounds/hit3.ogg deleted file mode 100644 index 6b1e1c1..0000000 Binary files a/client/src/main/resources/sounds/hit3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_angry.ogg b/client/src/main/resources/sounds/horse_angry.ogg deleted file mode 100644 index bc7618f..0000000 Binary files a/client/src/main/resources/sounds/horse_angry.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_breathe1.ogg b/client/src/main/resources/sounds/horse_breathe1.ogg deleted file mode 100644 index 8454df5..0000000 Binary files a/client/src/main/resources/sounds/horse_breathe1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_breathe2.ogg b/client/src/main/resources/sounds/horse_breathe2.ogg deleted file mode 100644 index 8968abe..0000000 Binary files a/client/src/main/resources/sounds/horse_breathe2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_breathe3.ogg b/client/src/main/resources/sounds/horse_breathe3.ogg deleted file mode 100644 index bd2f435..0000000 Binary files a/client/src/main/resources/sounds/horse_breathe3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_death.ogg b/client/src/main/resources/sounds/horse_death.ogg deleted file mode 100644 index 76a3326..0000000 Binary files a/client/src/main/resources/sounds/horse_death.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_gallop1.ogg b/client/src/main/resources/sounds/horse_gallop1.ogg deleted file mode 100644 index 3565549..0000000 Binary files a/client/src/main/resources/sounds/horse_gallop1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_gallop2.ogg b/client/src/main/resources/sounds/horse_gallop2.ogg deleted file mode 100644 index f257408..0000000 Binary files a/client/src/main/resources/sounds/horse_gallop2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_gallop3.ogg b/client/src/main/resources/sounds/horse_gallop3.ogg deleted file mode 100644 index 4c19bdb..0000000 Binary files a/client/src/main/resources/sounds/horse_gallop3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_gallop4.ogg b/client/src/main/resources/sounds/horse_gallop4.ogg deleted file mode 100644 index 9b300ce..0000000 Binary files a/client/src/main/resources/sounds/horse_gallop4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_hit1.ogg b/client/src/main/resources/sounds/horse_hit1.ogg deleted file mode 100644 index 4f54dfa..0000000 Binary files a/client/src/main/resources/sounds/horse_hit1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_hit2.ogg b/client/src/main/resources/sounds/horse_hit2.ogg deleted file mode 100644 index 9d628df..0000000 Binary files a/client/src/main/resources/sounds/horse_hit2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_hit3.ogg b/client/src/main/resources/sounds/horse_hit3.ogg deleted file mode 100644 index c13a241..0000000 Binary files a/client/src/main/resources/sounds/horse_hit3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_hit4.ogg b/client/src/main/resources/sounds/horse_hit4.ogg deleted file mode 100644 index 209d0e5..0000000 Binary files a/client/src/main/resources/sounds/horse_hit4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_idle1.ogg b/client/src/main/resources/sounds/horse_idle1.ogg deleted file mode 100644 index 1a94e43..0000000 Binary files a/client/src/main/resources/sounds/horse_idle1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_idle2.ogg b/client/src/main/resources/sounds/horse_idle2.ogg deleted file mode 100644 index d7af74f..0000000 Binary files a/client/src/main/resources/sounds/horse_idle2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_idle3.ogg b/client/src/main/resources/sounds/horse_idle3.ogg deleted file mode 100644 index fbf4228..0000000 Binary files a/client/src/main/resources/sounds/horse_idle3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_jump.ogg b/client/src/main/resources/sounds/horse_jump.ogg deleted file mode 100644 index e1713e9..0000000 Binary files a/client/src/main/resources/sounds/horse_jump.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_land.ogg b/client/src/main/resources/sounds/horse_land.ogg deleted file mode 100644 index 186180f..0000000 Binary files a/client/src/main/resources/sounds/horse_land.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_soft1.ogg b/client/src/main/resources/sounds/horse_soft1.ogg deleted file mode 100644 index bb567b1..0000000 Binary files a/client/src/main/resources/sounds/horse_soft1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_soft2.ogg b/client/src/main/resources/sounds/horse_soft2.ogg deleted file mode 100644 index 7013efd..0000000 Binary files a/client/src/main/resources/sounds/horse_soft2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_soft3.ogg b/client/src/main/resources/sounds/horse_soft3.ogg deleted file mode 100644 index cfe4011..0000000 Binary files a/client/src/main/resources/sounds/horse_soft3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_soft4.ogg b/client/src/main/resources/sounds/horse_soft4.ogg deleted file mode 100644 index 888f4a8..0000000 Binary files a/client/src/main/resources/sounds/horse_soft4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_soft5.ogg b/client/src/main/resources/sounds/horse_soft5.ogg deleted file mode 100644 index d548b5a..0000000 Binary files a/client/src/main/resources/sounds/horse_soft5.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_soft6.ogg b/client/src/main/resources/sounds/horse_soft6.ogg deleted file mode 100644 index 8a5c4aa..0000000 Binary files a/client/src/main/resources/sounds/horse_soft6.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_wood1.ogg b/client/src/main/resources/sounds/horse_wood1.ogg deleted file mode 100644 index 7888040..0000000 Binary files a/client/src/main/resources/sounds/horse_wood1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_wood2.ogg b/client/src/main/resources/sounds/horse_wood2.ogg deleted file mode 100644 index 5ffa309..0000000 Binary files a/client/src/main/resources/sounds/horse_wood2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_wood3.ogg b/client/src/main/resources/sounds/horse_wood3.ogg deleted file mode 100644 index 504bd8e..0000000 Binary files a/client/src/main/resources/sounds/horse_wood3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_wood4.ogg b/client/src/main/resources/sounds/horse_wood4.ogg deleted file mode 100644 index 2668928..0000000 Binary files a/client/src/main/resources/sounds/horse_wood4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_wood5.ogg b/client/src/main/resources/sounds/horse_wood5.ogg deleted file mode 100644 index 596e1bd..0000000 Binary files a/client/src/main/resources/sounds/horse_wood5.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/horse_wood6.ogg b/client/src/main/resources/sounds/horse_wood6.ogg deleted file mode 100644 index 3df5c94..0000000 Binary files a/client/src/main/resources/sounds/horse_wood6.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/ignite.ogg b/client/src/main/resources/sounds/ignite.ogg deleted file mode 100644 index dbb4072..0000000 Binary files a/client/src/main/resources/sounds/ignite.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/large_blast.ogg b/client/src/main/resources/sounds/large_blast.ogg deleted file mode 100644 index ed0a286..0000000 Binary files a/client/src/main/resources/sounds/large_blast.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/large_blast_far.ogg b/client/src/main/resources/sounds/large_blast_far.ogg deleted file mode 100644 index 4be6eaf..0000000 Binary files a/client/src/main/resources/sounds/large_blast_far.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/launch.ogg b/client/src/main/resources/sounds/launch.ogg deleted file mode 100644 index 8660f29..0000000 Binary files a/client/src/main/resources/sounds/launch.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/lava.ogg b/client/src/main/resources/sounds/lava.ogg deleted file mode 100644 index 4a5f0c7..0000000 Binary files a/client/src/main/resources/sounds/lava.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/lavapop.ogg b/client/src/main/resources/sounds/lavapop.ogg deleted file mode 100644 index aad32e6..0000000 Binary files a/client/src/main/resources/sounds/lavapop.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/levelup.ogg b/client/src/main/resources/sounds/levelup.ogg deleted file mode 100644 index a52cfb4..0000000 Binary files a/client/src/main/resources/sounds/levelup.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/magma.ogg b/client/src/main/resources/sounds/magma.ogg deleted file mode 100644 index c49efaa..0000000 Binary files a/client/src/main/resources/sounds/magma.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/magmapop.ogg b/client/src/main/resources/sounds/magmapop.ogg deleted file mode 100644 index 8231976..0000000 Binary files a/client/src/main/resources/sounds/magmapop.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/metal1.ogg b/client/src/main/resources/sounds/metal1.ogg deleted file mode 100644 index e9bd562..0000000 Binary files a/client/src/main/resources/sounds/metal1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/metal2.ogg b/client/src/main/resources/sounds/metal2.ogg deleted file mode 100644 index 1c9938f..0000000 Binary files a/client/src/main/resources/sounds/metal2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/metal3.ogg b/client/src/main/resources/sounds/metal3.ogg deleted file mode 100644 index af84cdc..0000000 Binary files a/client/src/main/resources/sounds/metal3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/metalhit1.ogg b/client/src/main/resources/sounds/metalhit1.ogg deleted file mode 100644 index 433ac53..0000000 Binary files a/client/src/main/resources/sounds/metalhit1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/metalhit2.ogg b/client/src/main/resources/sounds/metalhit2.ogg deleted file mode 100644 index 057126f..0000000 Binary files a/client/src/main/resources/sounds/metalhit2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/minecart_base.ogg b/client/src/main/resources/sounds/minecart_base.ogg deleted file mode 100644 index cf68355..0000000 Binary files a/client/src/main/resources/sounds/minecart_base.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/minecart_inside.ogg b/client/src/main/resources/sounds/minecart_inside.ogg deleted file mode 100644 index 083627a..0000000 Binary files a/client/src/main/resources/sounds/minecart_inside.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/molten.ogg b/client/src/main/resources/sounds/molten.ogg deleted file mode 100644 index 1577743..0000000 Binary files a/client/src/main/resources/sounds/molten.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/note.ogg b/client/src/main/resources/sounds/note.ogg deleted file mode 100644 index 1c02b11..0000000 Binary files a/client/src/main/resources/sounds/note.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/old_explode.ogg b/client/src/main/resources/sounds/old_explode.ogg deleted file mode 100644 index 0eadea5..0000000 Binary files a/client/src/main/resources/sounds/old_explode.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/orb.ogg b/client/src/main/resources/sounds/orb.ogg deleted file mode 100644 index a00df55..0000000 Binary files a/client/src/main/resources/sounds/orb.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/pig_death.ogg b/client/src/main/resources/sounds/pig_death.ogg deleted file mode 100644 index f47b99c..0000000 Binary files a/client/src/main/resources/sounds/pig_death.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/pig_say1.ogg b/client/src/main/resources/sounds/pig_say1.ogg deleted file mode 100644 index 586e10d..0000000 Binary files a/client/src/main/resources/sounds/pig_say1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/pig_say2.ogg b/client/src/main/resources/sounds/pig_say2.ogg deleted file mode 100644 index 32c636a..0000000 Binary files a/client/src/main/resources/sounds/pig_say2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/pig_say3.ogg b/client/src/main/resources/sounds/pig_say3.ogg deleted file mode 100644 index 0f1701c..0000000 Binary files a/client/src/main/resources/sounds/pig_say3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/piston_in.ogg b/client/src/main/resources/sounds/piston_in.ogg deleted file mode 100644 index 3e4ac84..0000000 Binary files a/client/src/main/resources/sounds/piston_in.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/piston_out.ogg b/client/src/main/resources/sounds/piston_out.ogg deleted file mode 100644 index f67b0d7..0000000 Binary files a/client/src/main/resources/sounds/piston_out.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/plop.ogg b/client/src/main/resources/sounds/plop.ogg deleted file mode 100644 index 6186212..0000000 Binary files a/client/src/main/resources/sounds/plop.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/pop.ogg b/client/src/main/resources/sounds/pop.ogg deleted file mode 100644 index 757cc14..0000000 Binary files a/client/src/main/resources/sounds/pop.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_bunnymurder.ogg b/client/src/main/resources/sounds/rabbit_bunnymurder.ogg deleted file mode 100644 index f39302b..0000000 Binary files a/client/src/main/resources/sounds/rabbit_bunnymurder.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_hop1.ogg b/client/src/main/resources/sounds/rabbit_hop1.ogg deleted file mode 100644 index c109eec..0000000 Binary files a/client/src/main/resources/sounds/rabbit_hop1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_hop2.ogg b/client/src/main/resources/sounds/rabbit_hop2.ogg deleted file mode 100644 index 2245c2a..0000000 Binary files a/client/src/main/resources/sounds/rabbit_hop2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_hop3.ogg b/client/src/main/resources/sounds/rabbit_hop3.ogg deleted file mode 100644 index 9df7543..0000000 Binary files a/client/src/main/resources/sounds/rabbit_hop3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_hop4.ogg b/client/src/main/resources/sounds/rabbit_hop4.ogg deleted file mode 100644 index 9725659..0000000 Binary files a/client/src/main/resources/sounds/rabbit_hop4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_hurt1.ogg b/client/src/main/resources/sounds/rabbit_hurt1.ogg deleted file mode 100644 index 0dd07e7..0000000 Binary files a/client/src/main/resources/sounds/rabbit_hurt1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_hurt2.ogg b/client/src/main/resources/sounds/rabbit_hurt2.ogg deleted file mode 100644 index 5f9dc2d..0000000 Binary files a/client/src/main/resources/sounds/rabbit_hurt2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_hurt3.ogg b/client/src/main/resources/sounds/rabbit_hurt3.ogg deleted file mode 100644 index 9b21d91..0000000 Binary files a/client/src/main/resources/sounds/rabbit_hurt3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_hurt4.ogg b/client/src/main/resources/sounds/rabbit_hurt4.ogg deleted file mode 100644 index 7534e91..0000000 Binary files a/client/src/main/resources/sounds/rabbit_hurt4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_idle1.ogg b/client/src/main/resources/sounds/rabbit_idle1.ogg deleted file mode 100644 index 412fe62..0000000 Binary files a/client/src/main/resources/sounds/rabbit_idle1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_idle2.ogg b/client/src/main/resources/sounds/rabbit_idle2.ogg deleted file mode 100644 index ec63d39..0000000 Binary files a/client/src/main/resources/sounds/rabbit_idle2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_idle3.ogg b/client/src/main/resources/sounds/rabbit_idle3.ogg deleted file mode 100644 index 6babe45..0000000 Binary files a/client/src/main/resources/sounds/rabbit_idle3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rabbit_idle4.ogg b/client/src/main/resources/sounds/rabbit_idle4.ogg deleted file mode 100644 index ec13e6b..0000000 Binary files a/client/src/main/resources/sounds/rabbit_idle4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rain1.ogg b/client/src/main/resources/sounds/rain1.ogg deleted file mode 100644 index 91dedae..0000000 Binary files a/client/src/main/resources/sounds/rain1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rain2.ogg b/client/src/main/resources/sounds/rain2.ogg deleted file mode 100644 index c5b504a..0000000 Binary files a/client/src/main/resources/sounds/rain2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rain3.ogg b/client/src/main/resources/sounds/rain3.ogg deleted file mode 100644 index 85f369a..0000000 Binary files a/client/src/main/resources/sounds/rain3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/rain4.ogg b/client/src/main/resources/sounds/rain4.ogg deleted file mode 100644 index 709cce6..0000000 Binary files a/client/src/main/resources/sounds/rain4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/sand1.ogg b/client/src/main/resources/sounds/sand1.ogg deleted file mode 100644 index dd15abd..0000000 Binary files a/client/src/main/resources/sounds/sand1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/sand2.ogg b/client/src/main/resources/sounds/sand2.ogg deleted file mode 100644 index 040e257..0000000 Binary files a/client/src/main/resources/sounds/sand2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/sand3.ogg b/client/src/main/resources/sounds/sand3.ogg deleted file mode 100644 index ca748a0..0000000 Binary files a/client/src/main/resources/sounds/sand3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/sand4.ogg b/client/src/main/resources/sounds/sand4.ogg deleted file mode 100644 index 7eb862c..0000000 Binary files a/client/src/main/resources/sounds/sand4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/sheep_say1.ogg b/client/src/main/resources/sounds/sheep_say1.ogg deleted file mode 100644 index 209d4d5..0000000 Binary files a/client/src/main/resources/sounds/sheep_say1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/sheep_say2.ogg b/client/src/main/resources/sounds/sheep_say2.ogg deleted file mode 100644 index ccc6f9d..0000000 Binary files a/client/src/main/resources/sounds/sheep_say2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/sheep_say3.ogg b/client/src/main/resources/sounds/sheep_say3.ogg deleted file mode 100644 index 80daaee..0000000 Binary files a/client/src/main/resources/sounds/sheep_say3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/slime_attack1.ogg b/client/src/main/resources/sounds/slime_attack1.ogg deleted file mode 100644 index d02d32b..0000000 Binary files a/client/src/main/resources/sounds/slime_attack1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/slime_attack2.ogg b/client/src/main/resources/sounds/slime_attack2.ogg deleted file mode 100644 index b70ff50..0000000 Binary files a/client/src/main/resources/sounds/slime_attack2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/slime_big1.ogg b/client/src/main/resources/sounds/slime_big1.ogg deleted file mode 100644 index db96367..0000000 Binary files a/client/src/main/resources/sounds/slime_big1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/slime_big2.ogg b/client/src/main/resources/sounds/slime_big2.ogg deleted file mode 100644 index 0e10611..0000000 Binary files a/client/src/main/resources/sounds/slime_big2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/slime_big3.ogg b/client/src/main/resources/sounds/slime_big3.ogg deleted file mode 100644 index ded5b71..0000000 Binary files a/client/src/main/resources/sounds/slime_big3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/slime_big4.ogg b/client/src/main/resources/sounds/slime_big4.ogg deleted file mode 100644 index 5d9b676..0000000 Binary files a/client/src/main/resources/sounds/slime_big4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/slime_small1.ogg b/client/src/main/resources/sounds/slime_small1.ogg deleted file mode 100644 index 53ba864..0000000 Binary files a/client/src/main/resources/sounds/slime_small1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/slime_small2.ogg b/client/src/main/resources/sounds/slime_small2.ogg deleted file mode 100644 index 94439fd..0000000 Binary files a/client/src/main/resources/sounds/slime_small2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/slime_small3.ogg b/client/src/main/resources/sounds/slime_small3.ogg deleted file mode 100644 index 0879955..0000000 Binary files a/client/src/main/resources/sounds/slime_small3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/slime_small4.ogg b/client/src/main/resources/sounds/slime_small4.ogg deleted file mode 100644 index e3e84a9..0000000 Binary files a/client/src/main/resources/sounds/slime_small4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/slime_small5.ogg b/client/src/main/resources/sounds/slime_small5.ogg deleted file mode 100644 index a8b38ed..0000000 Binary files a/client/src/main/resources/sounds/slime_small5.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/snow1.ogg b/client/src/main/resources/sounds/snow1.ogg deleted file mode 100644 index 3c141d1..0000000 Binary files a/client/src/main/resources/sounds/snow1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/snow2.ogg b/client/src/main/resources/sounds/snow2.ogg deleted file mode 100644 index c955f91..0000000 Binary files a/client/src/main/resources/sounds/snow2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/snow3.ogg b/client/src/main/resources/sounds/snow3.ogg deleted file mode 100644 index 2232ec0..0000000 Binary files a/client/src/main/resources/sounds/snow3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/snow4.ogg b/client/src/main/resources/sounds/snow4.ogg deleted file mode 100644 index 63fbd66..0000000 Binary files a/client/src/main/resources/sounds/snow4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/spell.ogg b/client/src/main/resources/sounds/spell.ogg deleted file mode 100644 index 888c676..0000000 Binary files a/client/src/main/resources/sounds/spell.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/splash.ogg b/client/src/main/resources/sounds/splash.ogg deleted file mode 100644 index 4b69fb6..0000000 Binary files a/client/src/main/resources/sounds/splash.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/stone1.ogg b/client/src/main/resources/sounds/stone1.ogg deleted file mode 100644 index 16cd366..0000000 Binary files a/client/src/main/resources/sounds/stone1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/stone2.ogg b/client/src/main/resources/sounds/stone2.ogg deleted file mode 100644 index e9b6867..0000000 Binary files a/client/src/main/resources/sounds/stone2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/stone3.ogg b/client/src/main/resources/sounds/stone3.ogg deleted file mode 100644 index a9ebdc4..0000000 Binary files a/client/src/main/resources/sounds/stone3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/stone4.ogg b/client/src/main/resources/sounds/stone4.ogg deleted file mode 100644 index 630b6a3..0000000 Binary files a/client/src/main/resources/sounds/stone4.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/teleport.ogg b/client/src/main/resources/sounds/teleport.ogg deleted file mode 100644 index 1d49a1a..0000000 Binary files a/client/src/main/resources/sounds/teleport.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/teleport_back.ogg b/client/src/main/resources/sounds/teleport_back.ogg deleted file mode 100644 index d52ef96..0000000 Binary files a/client/src/main/resources/sounds/teleport_back.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/thunder1.ogg b/client/src/main/resources/sounds/thunder1.ogg deleted file mode 100644 index 941968d..0000000 Binary files a/client/src/main/resources/sounds/thunder1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/thunder2.ogg b/client/src/main/resources/sounds/thunder2.ogg deleted file mode 100644 index 4193f81..0000000 Binary files a/client/src/main/resources/sounds/thunder2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/thunder3.ogg b/client/src/main/resources/sounds/thunder3.ogg deleted file mode 100644 index af47393..0000000 Binary files a/client/src/main/resources/sounds/thunder3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/twinkle.ogg b/client/src/main/resources/sounds/twinkle.ogg deleted file mode 100644 index 41a8d4d..0000000 Binary files a/client/src/main/resources/sounds/twinkle.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/twinkle_far.ogg b/client/src/main/resources/sounds/twinkle_far.ogg deleted file mode 100644 index df4a16f..0000000 Binary files a/client/src/main/resources/sounds/twinkle_far.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/water.ogg b/client/src/main/resources/sounds/water.ogg deleted file mode 100644 index c7b77c3..0000000 Binary files a/client/src/main/resources/sounds/water.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_bark1.ogg b/client/src/main/resources/sounds/wolf_bark1.ogg deleted file mode 100644 index a48f426..0000000 Binary files a/client/src/main/resources/sounds/wolf_bark1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_bark2.ogg b/client/src/main/resources/sounds/wolf_bark2.ogg deleted file mode 100644 index 5eea29b..0000000 Binary files a/client/src/main/resources/sounds/wolf_bark2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_bark3.ogg b/client/src/main/resources/sounds/wolf_bark3.ogg deleted file mode 100644 index c97bea4..0000000 Binary files a/client/src/main/resources/sounds/wolf_bark3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_death.ogg b/client/src/main/resources/sounds/wolf_death.ogg deleted file mode 100644 index 5e7461e..0000000 Binary files a/client/src/main/resources/sounds/wolf_death.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_growl1.ogg b/client/src/main/resources/sounds/wolf_growl1.ogg deleted file mode 100644 index 6af013e..0000000 Binary files a/client/src/main/resources/sounds/wolf_growl1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_growl2.ogg b/client/src/main/resources/sounds/wolf_growl2.ogg deleted file mode 100644 index f47dbbc..0000000 Binary files a/client/src/main/resources/sounds/wolf_growl2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_growl3.ogg b/client/src/main/resources/sounds/wolf_growl3.ogg deleted file mode 100644 index bd72a60..0000000 Binary files a/client/src/main/resources/sounds/wolf_growl3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_hurt1.ogg b/client/src/main/resources/sounds/wolf_hurt1.ogg deleted file mode 100644 index 5c16ef7..0000000 Binary files a/client/src/main/resources/sounds/wolf_hurt1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_hurt2.ogg b/client/src/main/resources/sounds/wolf_hurt2.ogg deleted file mode 100644 index 12ffc4f..0000000 Binary files a/client/src/main/resources/sounds/wolf_hurt2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_hurt3.ogg b/client/src/main/resources/sounds/wolf_hurt3.ogg deleted file mode 100644 index 4105709..0000000 Binary files a/client/src/main/resources/sounds/wolf_hurt3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_panting.ogg b/client/src/main/resources/sounds/wolf_panting.ogg deleted file mode 100644 index e2bbc8c..0000000 Binary files a/client/src/main/resources/sounds/wolf_panting.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_shake.ogg b/client/src/main/resources/sounds/wolf_shake.ogg deleted file mode 100644 index bf01cc3..0000000 Binary files a/client/src/main/resources/sounds/wolf_shake.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wolf_whine.ogg b/client/src/main/resources/sounds/wolf_whine.ogg deleted file mode 100644 index 32a5aea..0000000 Binary files a/client/src/main/resources/sounds/wolf_whine.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wood1.ogg b/client/src/main/resources/sounds/wood1.ogg deleted file mode 100644 index 762cfb0..0000000 Binary files a/client/src/main/resources/sounds/wood1.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wood2.ogg b/client/src/main/resources/sounds/wood2.ogg deleted file mode 100644 index ef6f8c4..0000000 Binary files a/client/src/main/resources/sounds/wood2.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wood3.ogg b/client/src/main/resources/sounds/wood3.ogg deleted file mode 100644 index 18c0236..0000000 Binary files a/client/src/main/resources/sounds/wood3.ogg and /dev/null differ diff --git a/client/src/main/resources/sounds/wood4.ogg b/client/src/main/resources/sounds/wood4.ogg deleted file mode 100644 index c493c9e..0000000 Binary files a/client/src/main/resources/sounds/wood4.ogg and /dev/null differ diff --git a/client/src/main/resources/textures/armor/ardite_layer_1.png b/client/src/main/resources/textures/armor/ardite_layer_1.png deleted file mode 100755 index c023172..0000000 Binary files a/client/src/main/resources/textures/armor/ardite_layer_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/ardite_layer_2.png b/client/src/main/resources/textures/armor/ardite_layer_2.png deleted file mode 100755 index d42e019..0000000 Binary files a/client/src/main/resources/textures/armor/ardite_layer_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/chain_layer_1.png b/client/src/main/resources/textures/armor/chain_layer_1.png deleted file mode 100755 index 9f84c18..0000000 Binary files a/client/src/main/resources/textures/armor/chain_layer_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/chain_layer_2.png b/client/src/main/resources/textures/armor/chain_layer_2.png deleted file mode 100755 index 117811c..0000000 Binary files a/client/src/main/resources/textures/armor/chain_layer_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/cloth_layer_1.png b/client/src/main/resources/textures/armor/cloth_layer_1.png deleted file mode 100755 index ebcfc41..0000000 Binary files a/client/src/main/resources/textures/armor/cloth_layer_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/cloth_layer_1_overlay.png b/client/src/main/resources/textures/armor/cloth_layer_1_overlay.png deleted file mode 100755 index 5811b7c..0000000 Binary files a/client/src/main/resources/textures/armor/cloth_layer_1_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/cloth_layer_2.png b/client/src/main/resources/textures/armor/cloth_layer_2.png deleted file mode 100755 index 8d8bba6..0000000 Binary files a/client/src/main/resources/textures/armor/cloth_layer_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/cloth_layer_2_overlay.png b/client/src/main/resources/textures/armor/cloth_layer_2_overlay.png deleted file mode 100755 index 006f553..0000000 Binary files a/client/src/main/resources/textures/armor/cloth_layer_2_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/diamond_layer_1.png b/client/src/main/resources/textures/armor/diamond_layer_1.png deleted file mode 100755 index 14fecf2..0000000 Binary files a/client/src/main/resources/textures/armor/diamond_layer_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/diamond_layer_2.png b/client/src/main/resources/textures/armor/diamond_layer_2.png deleted file mode 100755 index 2cca056..0000000 Binary files a/client/src/main/resources/textures/armor/diamond_layer_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/gold_layer_1.png b/client/src/main/resources/textures/armor/gold_layer_1.png deleted file mode 100755 index 6802e06..0000000 Binary files a/client/src/main/resources/textures/armor/gold_layer_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/gold_layer_2.png b/client/src/main/resources/textures/armor/gold_layer_2.png deleted file mode 100755 index a7cf835..0000000 Binary files a/client/src/main/resources/textures/armor/gold_layer_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/horse_armor_diamond.png b/client/src/main/resources/textures/armor/horse_armor_diamond.png deleted file mode 100755 index 39068f2..0000000 Binary files a/client/src/main/resources/textures/armor/horse_armor_diamond.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/horse_armor_gold.png b/client/src/main/resources/textures/armor/horse_armor_gold.png deleted file mode 100755 index 4a0786d..0000000 Binary files a/client/src/main/resources/textures/armor/horse_armor_gold.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/horse_armor_iron.png b/client/src/main/resources/textures/armor/horse_armor_iron.png deleted file mode 100755 index 533b2dd..0000000 Binary files a/client/src/main/resources/textures/armor/horse_armor_iron.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/iron_layer_1.png b/client/src/main/resources/textures/armor/iron_layer_1.png deleted file mode 100755 index 6da6e84..0000000 Binary files a/client/src/main/resources/textures/armor/iron_layer_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/iron_layer_2.png b/client/src/main/resources/textures/armor/iron_layer_2.png deleted file mode 100755 index fab422a..0000000 Binary files a/client/src/main/resources/textures/armor/iron_layer_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/leather_layer_1.png b/client/src/main/resources/textures/armor/leather_layer_1.png deleted file mode 100755 index 39d58bc..0000000 Binary files a/client/src/main/resources/textures/armor/leather_layer_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/leather_layer_1_overlay.png b/client/src/main/resources/textures/armor/leather_layer_1_overlay.png deleted file mode 100755 index 5811b7c..0000000 Binary files a/client/src/main/resources/textures/armor/leather_layer_1_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/leather_layer_2.png b/client/src/main/resources/textures/armor/leather_layer_2.png deleted file mode 100755 index 5fdccf5..0000000 Binary files a/client/src/main/resources/textures/armor/leather_layer_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/leather_layer_2_overlay.png b/client/src/main/resources/textures/armor/leather_layer_2_overlay.png deleted file mode 100755 index 006f553..0000000 Binary files a/client/src/main/resources/textures/armor/leather_layer_2_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/nichun_layer_1.png b/client/src/main/resources/textures/armor/nichun_layer_1.png deleted file mode 100755 index fe90290..0000000 Binary files a/client/src/main/resources/textures/armor/nichun_layer_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/nichun_layer_2.png b/client/src/main/resources/textures/armor/nichun_layer_2.png deleted file mode 100755 index 4c54048..0000000 Binary files a/client/src/main/resources/textures/armor/nichun_layer_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/thetium_layer_1.png b/client/src/main/resources/textures/armor/thetium_layer_1.png deleted file mode 100755 index 2336d12..0000000 Binary files a/client/src/main/resources/textures/armor/thetium_layer_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/armor/thetium_layer_2.png b/client/src/main/resources/textures/armor/thetium_layer_2.png deleted file mode 100755 index d5f92d1..0000000 Binary files a/client/src/main/resources/textures/armor/thetium_layer_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/background.png b/client/src/main/resources/textures/background.png deleted file mode 100755 index d2ac167..0000000 Binary files a/client/src/main/resources/textures/background.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acacia_door_bottom.png b/client/src/main/resources/textures/blocks/acacia_door_bottom.png deleted file mode 100755 index 2f57508..0000000 Binary files a/client/src/main/resources/textures/blocks/acacia_door_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acacia_door_top.png b/client/src/main/resources/textures/blocks/acacia_door_top.png deleted file mode 100755 index 9b7e742..0000000 Binary files a/client/src/main/resources/textures/blocks/acacia_door_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acacia_leaves_autumn.png b/client/src/main/resources/textures/blocks/acacia_leaves_autumn.png deleted file mode 100755 index c9859e5..0000000 Binary files a/client/src/main/resources/textures/blocks/acacia_leaves_autumn.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acacia_leaves_snowy.png b/client/src/main/resources/textures/blocks/acacia_leaves_snowy.png deleted file mode 100755 index a97a67b..0000000 Binary files a/client/src/main/resources/textures/blocks/acacia_leaves_snowy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acacia_leaves_spring.png b/client/src/main/resources/textures/blocks/acacia_leaves_spring.png deleted file mode 100755 index d54eb17..0000000 Binary files a/client/src/main/resources/textures/blocks/acacia_leaves_spring.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acacia_leaves_summer.png b/client/src/main/resources/textures/blocks/acacia_leaves_summer.png deleted file mode 100755 index c66ab48..0000000 Binary files a/client/src/main/resources/textures/blocks/acacia_leaves_summer.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acacia_leaves_winter.png b/client/src/main/resources/textures/blocks/acacia_leaves_winter.png deleted file mode 100755 index 3a5f4f1..0000000 Binary files a/client/src/main/resources/textures/blocks/acacia_leaves_winter.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acacia_log_bark.png b/client/src/main/resources/textures/blocks/acacia_log_bark.png deleted file mode 100755 index d221210..0000000 Binary files a/client/src/main/resources/textures/blocks/acacia_log_bark.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acacia_log_top.png b/client/src/main/resources/textures/blocks/acacia_log_top.png deleted file mode 100755 index 3d44878..0000000 Binary files a/client/src/main/resources/textures/blocks/acacia_log_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acacia_planks.png b/client/src/main/resources/textures/blocks/acacia_planks.png deleted file mode 100755 index 6858c51..0000000 Binary files a/client/src/main/resources/textures/blocks/acacia_planks.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acacia_sapling.png b/client/src/main/resources/textures/blocks/acacia_sapling.png deleted file mode 100755 index a1215cb..0000000 Binary files a/client/src/main/resources/textures/blocks/acacia_sapling.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acid_flow.png b/client/src/main/resources/textures/blocks/acid_flow.png deleted file mode 100755 index c4f0024..0000000 Binary files a/client/src/main/resources/textures/blocks/acid_flow.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/acid_still.png b/client/src/main/resources/textures/blocks/acid_still.png deleted file mode 100755 index 8193699..0000000 Binary files a/client/src/main/resources/textures/blocks/acid_still.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/activator_rail.png b/client/src/main/resources/textures/blocks/activator_rail.png deleted file mode 100755 index ce115ba..0000000 Binary files a/client/src/main/resources/textures/blocks/activator_rail.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/activator_rail_powered.png b/client/src/main/resources/textures/blocks/activator_rail_powered.png deleted file mode 100755 index a3aaca9..0000000 Binary files a/client/src/main/resources/textures/blocks/activator_rail_powered.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/allium.png b/client/src/main/resources/textures/blocks/allium.png deleted file mode 100755 index b7b5a45..0000000 Binary files a/client/src/main/resources/textures/blocks/allium.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/aluminium_block.png b/client/src/main/resources/textures/blocks/aluminium_block.png deleted file mode 100755 index 7ce12c5..0000000 Binary files a/client/src/main/resources/textures/blocks/aluminium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/aluminium_ore.png b/client/src/main/resources/textures/blocks/aluminium_ore.png deleted file mode 100755 index f660f62..0000000 Binary files a/client/src/main/resources/textures/blocks/aluminium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/antimony_block.png b/client/src/main/resources/textures/blocks/antimony_block.png deleted file mode 100755 index edcec09..0000000 Binary files a/client/src/main/resources/textures/blocks/antimony_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/antimony_ore.png b/client/src/main/resources/textures/blocks/antimony_ore.png deleted file mode 100755 index 456b91e..0000000 Binary files a/client/src/main/resources/textures/blocks/antimony_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/anvil_base.png b/client/src/main/resources/textures/blocks/anvil_base.png deleted file mode 100755 index cfc1fc8..0000000 Binary files a/client/src/main/resources/textures/blocks/anvil_base.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/anvil_top_0.png b/client/src/main/resources/textures/blocks/anvil_top_0.png deleted file mode 100755 index 395dea4..0000000 Binary files a/client/src/main/resources/textures/blocks/anvil_top_0.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/anvil_top_1.png b/client/src/main/resources/textures/blocks/anvil_top_1.png deleted file mode 100755 index eddc47f..0000000 Binary files a/client/src/main/resources/textures/blocks/anvil_top_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/anvil_top_2.png b/client/src/main/resources/textures/blocks/anvil_top_2.png deleted file mode 100755 index 6cade1f..0000000 Binary files a/client/src/main/resources/textures/blocks/anvil_top_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/ardite_block.png b/client/src/main/resources/textures/blocks/ardite_block.png deleted file mode 100755 index 5ffcd4f..0000000 Binary files a/client/src/main/resources/textures/blocks/ardite_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/ardite_ore.png b/client/src/main/resources/textures/blocks/ardite_ore.png deleted file mode 100755 index d459bd6..0000000 Binary files a/client/src/main/resources/textures/blocks/ardite_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/arsenic_block.png b/client/src/main/resources/textures/blocks/arsenic_block.png deleted file mode 100755 index 2d43573..0000000 Binary files a/client/src/main/resources/textures/blocks/arsenic_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/arsenic_ore.png b/client/src/main/resources/textures/blocks/arsenic_ore.png deleted file mode 100755 index 6a38443..0000000 Binary files a/client/src/main/resources/textures/blocks/arsenic_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/ash.png b/client/src/main/resources/textures/blocks/ash.png deleted file mode 100755 index 711c838..0000000 Binary files a/client/src/main/resources/textures/blocks/ash.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner.png b/client/src/main/resources/textures/blocks/banner.png deleted file mode 100755 index e38d28e..0000000 Binary files a/client/src/main/resources/textures/blocks/banner.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_base.png b/client/src/main/resources/textures/blocks/banner_base.png deleted file mode 100755 index bc80603..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_base.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_border.png b/client/src/main/resources/textures/blocks/banner_border.png deleted file mode 100755 index 444aeea..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_border.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_bricks.png b/client/src/main/resources/textures/blocks/banner_bricks.png deleted file mode 100755 index 544cff4..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_bricks.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_circle.png b/client/src/main/resources/textures/blocks/banner_circle.png deleted file mode 100755 index c6d3774..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_circle.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_cross.png b/client/src/main/resources/textures/blocks/banner_cross.png deleted file mode 100755 index c18bf82..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_cross.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_curly_border.png b/client/src/main/resources/textures/blocks/banner_curly_border.png deleted file mode 100755 index 5ea188e..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_curly_border.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_diagonal_left.png b/client/src/main/resources/textures/blocks/banner_diagonal_left.png deleted file mode 100755 index c6f45ff..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_diagonal_left.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_diagonal_right.png b/client/src/main/resources/textures/blocks/banner_diagonal_right.png deleted file mode 100755 index 23280c4..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_diagonal_right.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_diagonal_up_left.png b/client/src/main/resources/textures/blocks/banner_diagonal_up_left.png deleted file mode 100755 index b0955f2..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_diagonal_up_left.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_diagonal_up_right.png b/client/src/main/resources/textures/blocks/banner_diagonal_up_right.png deleted file mode 100755 index e8cd6b1..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_diagonal_up_right.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_flower.png b/client/src/main/resources/textures/blocks/banner_flower.png deleted file mode 100755 index 67dc1ac..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_flower.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_gradient.png b/client/src/main/resources/textures/blocks/banner_gradient.png deleted file mode 100755 index 8ce9832..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_gradient.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_gradient_up.png b/client/src/main/resources/textures/blocks/banner_gradient_up.png deleted file mode 100755 index 38cf516..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_gradient_up.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_half_horizontal.png b/client/src/main/resources/textures/blocks/banner_half_horizontal.png deleted file mode 100755 index 0f6d8a7..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_half_horizontal.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_half_horizontal_bottom.png b/client/src/main/resources/textures/blocks/banner_half_horizontal_bottom.png deleted file mode 100755 index 64fac36..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_half_horizontal_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_half_vertical.png b/client/src/main/resources/textures/blocks/banner_half_vertical.png deleted file mode 100755 index 8178ea7..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_half_vertical.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_half_vertical_right.png b/client/src/main/resources/textures/blocks/banner_half_vertical_right.png deleted file mode 100755 index 74089b6..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_half_vertical_right.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_rhombus.png b/client/src/main/resources/textures/blocks/banner_rhombus.png deleted file mode 100755 index abee982..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_rhombus.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_rune.png b/client/src/main/resources/textures/blocks/banner_rune.png deleted file mode 100755 index 32e7620..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_rune.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_skull.png b/client/src/main/resources/textures/blocks/banner_skull.png deleted file mode 100755 index ddf8653..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_skull.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_small_stripes.png b/client/src/main/resources/textures/blocks/banner_small_stripes.png deleted file mode 100755 index 0abaef0..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_small_stripes.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_square_bottom_left.png b/client/src/main/resources/textures/blocks/banner_square_bottom_left.png deleted file mode 100755 index 5fdd245..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_square_bottom_left.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_square_bottom_right.png b/client/src/main/resources/textures/blocks/banner_square_bottom_right.png deleted file mode 100755 index dd64eca..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_square_bottom_right.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_square_top_left.png b/client/src/main/resources/textures/blocks/banner_square_top_left.png deleted file mode 100755 index 7628998..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_square_top_left.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_square_top_right.png b/client/src/main/resources/textures/blocks/banner_square_top_right.png deleted file mode 100755 index 4197ecb..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_square_top_right.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_straight_cross.png b/client/src/main/resources/textures/blocks/banner_straight_cross.png deleted file mode 100755 index 1b7fa7d..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_straight_cross.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_bottom.png b/client/src/main/resources/textures/blocks/banner_stripe_bottom.png deleted file mode 100755 index 5473f90..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_stripe_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_center.png b/client/src/main/resources/textures/blocks/banner_stripe_center.png deleted file mode 100755 index eddba20..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_stripe_center.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_downleft.png b/client/src/main/resources/textures/blocks/banner_stripe_downleft.png deleted file mode 100755 index d73f9b7..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_stripe_downleft.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_downright.png b/client/src/main/resources/textures/blocks/banner_stripe_downright.png deleted file mode 100755 index 0b610d9..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_stripe_downright.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_left.png b/client/src/main/resources/textures/blocks/banner_stripe_left.png deleted file mode 100755 index 0707d31..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_stripe_left.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_middle.png b/client/src/main/resources/textures/blocks/banner_stripe_middle.png deleted file mode 100755 index bde988b..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_stripe_middle.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_right.png b/client/src/main/resources/textures/blocks/banner_stripe_right.png deleted file mode 100755 index f0a8a25..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_stripe_right.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_top.png b/client/src/main/resources/textures/blocks/banner_stripe_top.png deleted file mode 100755 index 1b8e3f2..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_stripe_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_thing.png b/client/src/main/resources/textures/blocks/banner_thing.png deleted file mode 100755 index 7ae1cbc..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_thing.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_triangle_bottom.png b/client/src/main/resources/textures/blocks/banner_triangle_bottom.png deleted file mode 100755 index bc37930..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_triangle_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_triangle_top.png b/client/src/main/resources/textures/blocks/banner_triangle_top.png deleted file mode 100755 index 77877c0..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_triangle_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_triangles_bottom.png b/client/src/main/resources/textures/blocks/banner_triangles_bottom.png deleted file mode 100755 index fe25db7..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_triangles_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/banner_triangles_top.png b/client/src/main/resources/textures/blocks/banner_triangles_top.png deleted file mode 100755 index f59a121..0000000 Binary files a/client/src/main/resources/textures/blocks/banner_triangles_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/beacon.png b/client/src/main/resources/textures/blocks/beacon.png deleted file mode 100755 index a69e59d..0000000 Binary files a/client/src/main/resources/textures/blocks/beacon.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/beacon_beam.png b/client/src/main/resources/textures/blocks/beacon_beam.png deleted file mode 100755 index 67545b4..0000000 Binary files a/client/src/main/resources/textures/blocks/beacon_beam.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/bedrock.png b/client/src/main/resources/textures/blocks/bedrock.png deleted file mode 100755 index 1643c99..0000000 Binary files a/client/src/main/resources/textures/blocks/bedrock.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/birch_door_bottom.png b/client/src/main/resources/textures/blocks/birch_door_bottom.png deleted file mode 100755 index 2c6f7d3..0000000 Binary files a/client/src/main/resources/textures/blocks/birch_door_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/birch_door_top.png b/client/src/main/resources/textures/blocks/birch_door_top.png deleted file mode 100755 index 1345b41..0000000 Binary files a/client/src/main/resources/textures/blocks/birch_door_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/birch_leaves_autumn.png b/client/src/main/resources/textures/blocks/birch_leaves_autumn.png deleted file mode 100755 index 90998d3..0000000 Binary files a/client/src/main/resources/textures/blocks/birch_leaves_autumn.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/birch_leaves_snowy.png b/client/src/main/resources/textures/blocks/birch_leaves_snowy.png deleted file mode 100755 index cbaf47d..0000000 Binary files a/client/src/main/resources/textures/blocks/birch_leaves_snowy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/birch_leaves_spring.png b/client/src/main/resources/textures/blocks/birch_leaves_spring.png deleted file mode 100755 index a6773af..0000000 Binary files a/client/src/main/resources/textures/blocks/birch_leaves_spring.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/birch_leaves_summer.png b/client/src/main/resources/textures/blocks/birch_leaves_summer.png deleted file mode 100755 index 2becfb1..0000000 Binary files a/client/src/main/resources/textures/blocks/birch_leaves_summer.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/birch_leaves_winter.png b/client/src/main/resources/textures/blocks/birch_leaves_winter.png deleted file mode 100755 index afa1d69..0000000 Binary files a/client/src/main/resources/textures/blocks/birch_leaves_winter.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/birch_log_bark.png b/client/src/main/resources/textures/blocks/birch_log_bark.png deleted file mode 100755 index bfb209d..0000000 Binary files a/client/src/main/resources/textures/blocks/birch_log_bark.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/birch_log_top.png b/client/src/main/resources/textures/blocks/birch_log_top.png deleted file mode 100755 index f9b94f4..0000000 Binary files a/client/src/main/resources/textures/blocks/birch_log_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/birch_planks.png b/client/src/main/resources/textures/blocks/birch_planks.png deleted file mode 100755 index b113e3a..0000000 Binary files a/client/src/main/resources/textures/blocks/birch_planks.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/birch_sapling.png b/client/src/main/resources/textures/blocks/birch_sapling.png deleted file mode 100755 index b0dacc5..0000000 Binary files a/client/src/main/resources/textures/blocks/birch_sapling.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/bismuth_block.png b/client/src/main/resources/textures/blocks/bismuth_block.png deleted file mode 100755 index 0e6fdc0..0000000 Binary files a/client/src/main/resources/textures/blocks/bismuth_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/bismuth_ore.png b/client/src/main/resources/textures/blocks/bismuth_ore.png deleted file mode 100755 index 71f8884..0000000 Binary files a/client/src/main/resources/textures/blocks/bismuth_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_bed_foot_end.png b/client/src/main/resources/textures/blocks/black_bed_foot_end.png deleted file mode 100755 index 0f9a411..0000000 Binary files a/client/src/main/resources/textures/blocks/black_bed_foot_end.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_bed_foot_side.png b/client/src/main/resources/textures/blocks/black_bed_foot_side.png deleted file mode 100755 index 7445d59..0000000 Binary files a/client/src/main/resources/textures/blocks/black_bed_foot_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_bed_foot_top.png b/client/src/main/resources/textures/blocks/black_bed_foot_top.png deleted file mode 100755 index 9813d14..0000000 Binary files a/client/src/main/resources/textures/blocks/black_bed_foot_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_bed_head_end.png b/client/src/main/resources/textures/blocks/black_bed_head_end.png deleted file mode 100755 index 928e4be..0000000 Binary files a/client/src/main/resources/textures/blocks/black_bed_head_end.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_bed_head_side.png b/client/src/main/resources/textures/blocks/black_bed_head_side.png deleted file mode 100755 index 146c073..0000000 Binary files a/client/src/main/resources/textures/blocks/black_bed_head_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_bed_head_top.png b/client/src/main/resources/textures/blocks/black_bed_head_top.png deleted file mode 100755 index c8c5c97..0000000 Binary files a/client/src/main/resources/textures/blocks/black_bed_head_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_brick.png b/client/src/main/resources/textures/blocks/black_brick.png deleted file mode 100755 index 89ef692..0000000 Binary files a/client/src/main/resources/textures/blocks/black_brick.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_glass.png b/client/src/main/resources/textures/blocks/black_glass.png deleted file mode 100755 index 06f3427..0000000 Binary files a/client/src/main/resources/textures/blocks/black_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_glass_pane.png b/client/src/main/resources/textures/blocks/black_glass_pane.png deleted file mode 100755 index 43d60c5..0000000 Binary files a/client/src/main/resources/textures/blocks/black_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_lotus.png b/client/src/main/resources/textures/blocks/black_lotus.png deleted file mode 100755 index 55b4762..0000000 Binary files a/client/src/main/resources/textures/blocks/black_lotus.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_metal_block.png b/client/src/main/resources/textures/blocks/black_metal_block.png deleted file mode 100755 index 9d0f751..0000000 Binary files a/client/src/main/resources/textures/blocks/black_metal_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_metal_ore.png b/client/src/main/resources/textures/blocks/black_metal_ore.png deleted file mode 100755 index 679dbbb..0000000 Binary files a/client/src/main/resources/textures/blocks/black_metal_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_bottom.png b/client/src/main/resources/textures/blocks/black_quartz_block_bottom.png deleted file mode 100755 index 8f6aed0..0000000 Binary files a/client/src/main/resources/textures/blocks/black_quartz_block_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_chiseled.png b/client/src/main/resources/textures/blocks/black_quartz_block_chiseled.png deleted file mode 100755 index eae475e..0000000 Binary files a/client/src/main/resources/textures/blocks/black_quartz_block_chiseled.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_chiseled_top.png b/client/src/main/resources/textures/blocks/black_quartz_block_chiseled_top.png deleted file mode 100755 index bb1c5b9..0000000 Binary files a/client/src/main/resources/textures/blocks/black_quartz_block_chiseled_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_lines.png b/client/src/main/resources/textures/blocks/black_quartz_block_lines.png deleted file mode 100755 index d80fa89..0000000 Binary files a/client/src/main/resources/textures/blocks/black_quartz_block_lines.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_lines_top.png b/client/src/main/resources/textures/blocks/black_quartz_block_lines_top.png deleted file mode 100755 index 384a2ce..0000000 Binary files a/client/src/main/resources/textures/blocks/black_quartz_block_lines_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_side.png b/client/src/main/resources/textures/blocks/black_quartz_block_side.png deleted file mode 100755 index 404830b..0000000 Binary files a/client/src/main/resources/textures/blocks/black_quartz_block_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_ore.png b/client/src/main/resources/textures/blocks/black_quartz_ore.png deleted file mode 100755 index 24b6682..0000000 Binary files a/client/src/main/resources/textures/blocks/black_quartz_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_top.png b/client/src/main/resources/textures/blocks/black_quartz_top.png deleted file mode 100755 index 2eeb1ab..0000000 Binary files a/client/src/main/resources/textures/blocks/black_quartz_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/black_stained_hardened_clay.png deleted file mode 100755 index 59da22c..0000000 Binary files a/client/src/main/resources/textures/blocks/black_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/black_wool.png b/client/src/main/resources/textures/blocks/black_wool.png deleted file mode 100755 index b74d5c9..0000000 Binary files a/client/src/main/resources/textures/blocks/black_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackened_cobble.png b/client/src/main/resources/textures/blocks/blackened_cobble.png deleted file mode 100755 index 4bf9754..0000000 Binary files a/client/src/main/resources/textures/blocks/blackened_cobble.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackened_dirt.png b/client/src/main/resources/textures/blocks/blackened_dirt.png deleted file mode 100755 index 9cf29ee..0000000 Binary files a/client/src/main/resources/textures/blocks/blackened_dirt.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackened_soil_side.png b/client/src/main/resources/textures/blocks/blackened_soil_side.png deleted file mode 100755 index 0620abc..0000000 Binary files a/client/src/main/resources/textures/blocks/blackened_soil_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackened_soil_top.png b/client/src/main/resources/textures/blocks/blackened_soil_top.png deleted file mode 100755 index c27165b..0000000 Binary files a/client/src/main/resources/textures/blocks/blackened_soil_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackened_stone.png b/client/src/main/resources/textures/blocks/blackened_stone.png deleted file mode 100755 index 1d0851e..0000000 Binary files a/client/src/main/resources/textures/blocks/blackened_stone.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackwood_door_bottom.png b/client/src/main/resources/textures/blocks/blackwood_door_bottom.png deleted file mode 100755 index 7d6a3c0..0000000 Binary files a/client/src/main/resources/textures/blocks/blackwood_door_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackwood_door_top.png b/client/src/main/resources/textures/blocks/blackwood_door_top.png deleted file mode 100755 index e949507..0000000 Binary files a/client/src/main/resources/textures/blocks/blackwood_door_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackwood_leaves_autumn.png b/client/src/main/resources/textures/blocks/blackwood_leaves_autumn.png deleted file mode 100755 index 6ceb92c..0000000 Binary files a/client/src/main/resources/textures/blocks/blackwood_leaves_autumn.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackwood_leaves_snowy.png b/client/src/main/resources/textures/blocks/blackwood_leaves_snowy.png deleted file mode 100755 index 7b08e6b..0000000 Binary files a/client/src/main/resources/textures/blocks/blackwood_leaves_snowy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackwood_leaves_spring.png b/client/src/main/resources/textures/blocks/blackwood_leaves_spring.png deleted file mode 100755 index 0c7528a..0000000 Binary files a/client/src/main/resources/textures/blocks/blackwood_leaves_spring.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackwood_leaves_summer.png b/client/src/main/resources/textures/blocks/blackwood_leaves_summer.png deleted file mode 100755 index b0f22cf..0000000 Binary files a/client/src/main/resources/textures/blocks/blackwood_leaves_summer.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackwood_leaves_winter.png b/client/src/main/resources/textures/blocks/blackwood_leaves_winter.png deleted file mode 100755 index 21d5c96..0000000 Binary files a/client/src/main/resources/textures/blocks/blackwood_leaves_winter.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackwood_log_bark.png b/client/src/main/resources/textures/blocks/blackwood_log_bark.png deleted file mode 100755 index 4403aa6..0000000 Binary files a/client/src/main/resources/textures/blocks/blackwood_log_bark.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackwood_log_top.png b/client/src/main/resources/textures/blocks/blackwood_log_top.png deleted file mode 100755 index 9cf9fbd..0000000 Binary files a/client/src/main/resources/textures/blocks/blackwood_log_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackwood_planks.png b/client/src/main/resources/textures/blocks/blackwood_planks.png deleted file mode 100755 index f2a79c4..0000000 Binary files a/client/src/main/resources/textures/blocks/blackwood_planks.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blackwood_sapling.png b/client/src/main/resources/textures/blocks/blackwood_sapling.png deleted file mode 100755 index 572c562..0000000 Binary files a/client/src/main/resources/textures/blocks/blackwood_sapling.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blood_brick.png b/client/src/main/resources/textures/blocks/blood_brick.png deleted file mode 100755 index caaf66f..0000000 Binary files a/client/src/main/resources/textures/blocks/blood_brick.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blood_flow.png b/client/src/main/resources/textures/blocks/blood_flow.png deleted file mode 100755 index 56eb9c9..0000000 Binary files a/client/src/main/resources/textures/blocks/blood_flow.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blood_still.png b/client/src/main/resources/textures/blocks/blood_still.png deleted file mode 100755 index c6c9761..0000000 Binary files a/client/src/main/resources/textures/blocks/blood_still.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blue_glass.png b/client/src/main/resources/textures/blocks/blue_glass.png deleted file mode 100755 index 38885de..0000000 Binary files a/client/src/main/resources/textures/blocks/blue_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blue_glass_pane.png b/client/src/main/resources/textures/blocks/blue_glass_pane.png deleted file mode 100755 index 55c614f..0000000 Binary files a/client/src/main/resources/textures/blocks/blue_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blue_mushroom.png b/client/src/main/resources/textures/blocks/blue_mushroom.png deleted file mode 100755 index cf498fb..0000000 Binary files a/client/src/main/resources/textures/blocks/blue_mushroom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blue_orchid.png b/client/src/main/resources/textures/blocks/blue_orchid.png deleted file mode 100755 index 51d7fd9..0000000 Binary files a/client/src/main/resources/textures/blocks/blue_orchid.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blue_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/blue_stained_hardened_clay.png deleted file mode 100755 index 7e38e27..0000000 Binary files a/client/src/main/resources/textures/blocks/blue_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/blue_wool.png b/client/src/main/resources/textures/blocks/blue_wool.png deleted file mode 100755 index ce9515f..0000000 Binary files a/client/src/main/resources/textures/blocks/blue_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/bookshelf.png b/client/src/main/resources/textures/blocks/bookshelf.png deleted file mode 100755 index 4c87f0f..0000000 Binary files a/client/src/main/resources/textures/blocks/bookshelf.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/brewing_stand.png b/client/src/main/resources/textures/blocks/brewing_stand.png deleted file mode 100755 index 60832aa..0000000 Binary files a/client/src/main/resources/textures/blocks/brewing_stand.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/brewing_stand_base.png b/client/src/main/resources/textures/blocks/brewing_stand_base.png deleted file mode 100755 index 0742fbf..0000000 Binary files a/client/src/main/resources/textures/blocks/brewing_stand_base.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/brick_block.png b/client/src/main/resources/textures/blocks/brick_block.png deleted file mode 100755 index f1b6d7c..0000000 Binary files a/client/src/main/resources/textures/blocks/brick_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/brown_glass.png b/client/src/main/resources/textures/blocks/brown_glass.png deleted file mode 100755 index 259b61c..0000000 Binary files a/client/src/main/resources/textures/blocks/brown_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/brown_glass_pane.png b/client/src/main/resources/textures/blocks/brown_glass_pane.png deleted file mode 100755 index cbd791a..0000000 Binary files a/client/src/main/resources/textures/blocks/brown_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/brown_mushroom.png b/client/src/main/resources/textures/blocks/brown_mushroom.png deleted file mode 100755 index bf33d34..0000000 Binary files a/client/src/main/resources/textures/blocks/brown_mushroom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/brown_mushroom_block_cap.png b/client/src/main/resources/textures/blocks/brown_mushroom_block_cap.png deleted file mode 100755 index 1f52ba8..0000000 Binary files a/client/src/main/resources/textures/blocks/brown_mushroom_block_cap.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/brown_mushroom_block_inside.png b/client/src/main/resources/textures/blocks/brown_mushroom_block_inside.png deleted file mode 100755 index f0e7a04..0000000 Binary files a/client/src/main/resources/textures/blocks/brown_mushroom_block_inside.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/brown_mushroom_block_stem.png b/client/src/main/resources/textures/blocks/brown_mushroom_block_stem.png deleted file mode 100755 index 83c0840..0000000 Binary files a/client/src/main/resources/textures/blocks/brown_mushroom_block_stem.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/brown_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/brown_stained_hardened_clay.png deleted file mode 100755 index f81745f..0000000 Binary files a/client/src/main/resources/textures/blocks/brown_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/brown_wool.png b/client/src/main/resources/textures/blocks/brown_wool.png deleted file mode 100755 index b4dc3c5..0000000 Binary files a/client/src/main/resources/textures/blocks/brown_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cactus_bottom.png b/client/src/main/resources/textures/blocks/cactus_bottom.png deleted file mode 100755 index 6f10bc0..0000000 Binary files a/client/src/main/resources/textures/blocks/cactus_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cactus_side.png b/client/src/main/resources/textures/blocks/cactus_side.png deleted file mode 100755 index 9c55503..0000000 Binary files a/client/src/main/resources/textures/blocks/cactus_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cactus_top.png b/client/src/main/resources/textures/blocks/cactus_top.png deleted file mode 100755 index f182e84..0000000 Binary files a/client/src/main/resources/textures/blocks/cactus_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cake_bottom.png b/client/src/main/resources/textures/blocks/cake_bottom.png deleted file mode 100755 index d93b15a..0000000 Binary files a/client/src/main/resources/textures/blocks/cake_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cake_inner.png b/client/src/main/resources/textures/blocks/cake_inner.png deleted file mode 100755 index ce7ce69..0000000 Binary files a/client/src/main/resources/textures/blocks/cake_inner.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cake_side.png b/client/src/main/resources/textures/blocks/cake_side.png deleted file mode 100755 index 343a023..0000000 Binary files a/client/src/main/resources/textures/blocks/cake_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cake_top.png b/client/src/main/resources/textures/blocks/cake_top.png deleted file mode 100755 index 2947892..0000000 Binary files a/client/src/main/resources/textures/blocks/cake_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/calcium_block.png b/client/src/main/resources/textures/blocks/calcium_block.png deleted file mode 100755 index 8e0a79c..0000000 Binary files a/client/src/main/resources/textures/blocks/calcium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/calcium_ore.png b/client/src/main/resources/textures/blocks/calcium_ore.png deleted file mode 100755 index fa6fef0..0000000 Binary files a/client/src/main/resources/textures/blocks/calcium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/carrot_0.png b/client/src/main/resources/textures/blocks/carrot_0.png deleted file mode 100755 index c1ef732..0000000 Binary files a/client/src/main/resources/textures/blocks/carrot_0.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/carrot_1.png b/client/src/main/resources/textures/blocks/carrot_1.png deleted file mode 100755 index 1275f4f..0000000 Binary files a/client/src/main/resources/textures/blocks/carrot_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/carrot_2.png b/client/src/main/resources/textures/blocks/carrot_2.png deleted file mode 100755 index b7347df..0000000 Binary files a/client/src/main/resources/textures/blocks/carrot_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/carrot_3.png b/client/src/main/resources/textures/blocks/carrot_3.png deleted file mode 100755 index 2391be8..0000000 Binary files a/client/src/main/resources/textures/blocks/carrot_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cauldron_bottom.png b/client/src/main/resources/textures/blocks/cauldron_bottom.png deleted file mode 100755 index 8328307..0000000 Binary files a/client/src/main/resources/textures/blocks/cauldron_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cauldron_inner.png b/client/src/main/resources/textures/blocks/cauldron_inner.png deleted file mode 100755 index d5a30dd..0000000 Binary files a/client/src/main/resources/textures/blocks/cauldron_inner.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cauldron_side.png b/client/src/main/resources/textures/blocks/cauldron_side.png deleted file mode 100755 index df42f98..0000000 Binary files a/client/src/main/resources/textures/blocks/cauldron_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cauldron_top.png b/client/src/main/resources/textures/blocks/cauldron_top.png deleted file mode 100755 index e263fc5..0000000 Binary files a/client/src/main/resources/textures/blocks/cauldron_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cell_rock.png b/client/src/main/resources/textures/blocks/cell_rock.png deleted file mode 100755 index c2a91e3..0000000 Binary files a/client/src/main/resources/textures/blocks/cell_rock.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cherry_door_bottom.png b/client/src/main/resources/textures/blocks/cherry_door_bottom.png deleted file mode 100755 index b8909f7..0000000 Binary files a/client/src/main/resources/textures/blocks/cherry_door_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cherry_door_top.png b/client/src/main/resources/textures/blocks/cherry_door_top.png deleted file mode 100755 index b0160b3..0000000 Binary files a/client/src/main/resources/textures/blocks/cherry_door_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cherry_leaves_autumn.png b/client/src/main/resources/textures/blocks/cherry_leaves_autumn.png deleted file mode 100755 index 262a22f..0000000 Binary files a/client/src/main/resources/textures/blocks/cherry_leaves_autumn.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cherry_leaves_snowy.png b/client/src/main/resources/textures/blocks/cherry_leaves_snowy.png deleted file mode 100755 index 54210a5..0000000 Binary files a/client/src/main/resources/textures/blocks/cherry_leaves_snowy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cherry_leaves_spring.png b/client/src/main/resources/textures/blocks/cherry_leaves_spring.png deleted file mode 100755 index fe79cff..0000000 Binary files a/client/src/main/resources/textures/blocks/cherry_leaves_spring.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cherry_leaves_summer.png b/client/src/main/resources/textures/blocks/cherry_leaves_summer.png deleted file mode 100755 index 6e1b678..0000000 Binary files a/client/src/main/resources/textures/blocks/cherry_leaves_summer.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cherry_leaves_winter.png b/client/src/main/resources/textures/blocks/cherry_leaves_winter.png deleted file mode 100755 index abd4113..0000000 Binary files a/client/src/main/resources/textures/blocks/cherry_leaves_winter.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cherry_log_bark.png b/client/src/main/resources/textures/blocks/cherry_log_bark.png deleted file mode 100755 index 5224cc7..0000000 Binary files a/client/src/main/resources/textures/blocks/cherry_log_bark.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cherry_log_top.png b/client/src/main/resources/textures/blocks/cherry_log_top.png deleted file mode 100755 index e9099e6..0000000 Binary files a/client/src/main/resources/textures/blocks/cherry_log_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cherry_planks.png b/client/src/main/resources/textures/blocks/cherry_planks.png deleted file mode 100755 index 268aac2..0000000 Binary files a/client/src/main/resources/textures/blocks/cherry_planks.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cherry_sapling.png b/client/src/main/resources/textures/blocks/cherry_sapling.png deleted file mode 100755 index 2a149e0..0000000 Binary files a/client/src/main/resources/textures/blocks/cherry_sapling.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/chest_normal.png b/client/src/main/resources/textures/blocks/chest_normal.png deleted file mode 100755 index 2e3d7fd..0000000 Binary files a/client/src/main/resources/textures/blocks/chest_normal.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/chest_normal_double.png b/client/src/main/resources/textures/blocks/chest_normal_double.png deleted file mode 100755 index 0168338..0000000 Binary files a/client/src/main/resources/textures/blocks/chest_normal_double.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/chest_trapped.png b/client/src/main/resources/textures/blocks/chest_trapped.png deleted file mode 100755 index 3aef190..0000000 Binary files a/client/src/main/resources/textures/blocks/chest_trapped.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/chest_trapped_double.png b/client/src/main/resources/textures/blocks/chest_trapped_double.png deleted file mode 100755 index 00eebe5..0000000 Binary files a/client/src/main/resources/textures/blocks/chest_trapped_double.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/chrome_block.png b/client/src/main/resources/textures/blocks/chrome_block.png deleted file mode 100755 index d124793..0000000 Binary files a/client/src/main/resources/textures/blocks/chrome_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/chrome_ore.png b/client/src/main/resources/textures/blocks/chrome_ore.png deleted file mode 100755 index aaac737..0000000 Binary files a/client/src/main/resources/textures/blocks/chrome_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cinnabar_block.png b/client/src/main/resources/textures/blocks/cinnabar_block.png deleted file mode 100755 index 7ba2fe9..0000000 Binary files a/client/src/main/resources/textures/blocks/cinnabar_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cinnabar_ore.png b/client/src/main/resources/textures/blocks/cinnabar_ore.png deleted file mode 100755 index 48f52ba..0000000 Binary files a/client/src/main/resources/textures/blocks/cinnabar_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/clay.png b/client/src/main/resources/textures/blocks/clay.png deleted file mode 100755 index c19e031..0000000 Binary files a/client/src/main/resources/textures/blocks/clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/coal_block.png b/client/src/main/resources/textures/blocks/coal_block.png deleted file mode 100755 index 024404b..0000000 Binary files a/client/src/main/resources/textures/blocks/coal_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/coal_ore.png b/client/src/main/resources/textures/blocks/coal_ore.png deleted file mode 100755 index 49486d2..0000000 Binary files a/client/src/main/resources/textures/blocks/coal_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/coarse_dirt.png b/client/src/main/resources/textures/blocks/coarse_dirt.png deleted file mode 100755 index d646225..0000000 Binary files a/client/src/main/resources/textures/blocks/coarse_dirt.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cobalt_block.png b/client/src/main/resources/textures/blocks/cobalt_block.png deleted file mode 100755 index 63dd0dc..0000000 Binary files a/client/src/main/resources/textures/blocks/cobalt_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cobalt_ore.png b/client/src/main/resources/textures/blocks/cobalt_ore.png deleted file mode 100755 index 1105968..0000000 Binary files a/client/src/main/resources/textures/blocks/cobalt_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cobblestone.png b/client/src/main/resources/textures/blocks/cobblestone.png deleted file mode 100755 index be2a189..0000000 Binary files a/client/src/main/resources/textures/blocks/cobblestone.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cocoa_0.png b/client/src/main/resources/textures/blocks/cocoa_0.png deleted file mode 100755 index 25892eb..0000000 Binary files a/client/src/main/resources/textures/blocks/cocoa_0.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cocoa_1.png b/client/src/main/resources/textures/blocks/cocoa_1.png deleted file mode 100755 index d0098ff..0000000 Binary files a/client/src/main/resources/textures/blocks/cocoa_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cocoa_2.png b/client/src/main/resources/textures/blocks/cocoa_2.png deleted file mode 100755 index db28c7b..0000000 Binary files a/client/src/main/resources/textures/blocks/cocoa_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/comparator_off.png b/client/src/main/resources/textures/blocks/comparator_off.png deleted file mode 100755 index c9527bc..0000000 Binary files a/client/src/main/resources/textures/blocks/comparator_off.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/comparator_on.png b/client/src/main/resources/textures/blocks/comparator_on.png deleted file mode 100755 index 2e4fb7a..0000000 Binary files a/client/src/main/resources/textures/blocks/comparator_on.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/control_block.png b/client/src/main/resources/textures/blocks/control_block.png deleted file mode 100755 index 8dfa75d..0000000 Binary files a/client/src/main/resources/textures/blocks/control_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/copper_block.png b/client/src/main/resources/textures/blocks/copper_block.png deleted file mode 100755 index 3bff2a7..0000000 Binary files a/client/src/main/resources/textures/blocks/copper_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/copper_ore.png b/client/src/main/resources/textures/blocks/copper_ore.png deleted file mode 100755 index a67cb93..0000000 Binary files a/client/src/main/resources/textures/blocks/copper_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/core.png b/client/src/main/resources/textures/blocks/core.png deleted file mode 100755 index 0e44411..0000000 Binary files a/client/src/main/resources/textures/blocks/core.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/crafting_table_front.png b/client/src/main/resources/textures/blocks/crafting_table_front.png deleted file mode 100755 index 11986a4..0000000 Binary files a/client/src/main/resources/textures/blocks/crafting_table_front.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/crafting_table_side.png b/client/src/main/resources/textures/blocks/crafting_table_side.png deleted file mode 100755 index 1c678b4..0000000 Binary files a/client/src/main/resources/textures/blocks/crafting_table_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/crafting_table_top.png b/client/src/main/resources/textures/blocks/crafting_table_top.png deleted file mode 100755 index 5cd53a5..0000000 Binary files a/client/src/main/resources/textures/blocks/crafting_table_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cyan_glass.png b/client/src/main/resources/textures/blocks/cyan_glass.png deleted file mode 100755 index d30caa4..0000000 Binary files a/client/src/main/resources/textures/blocks/cyan_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cyan_glass_pane.png b/client/src/main/resources/textures/blocks/cyan_glass_pane.png deleted file mode 100755 index 9a34b84..0000000 Binary files a/client/src/main/resources/textures/blocks/cyan_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cyan_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/cyan_stained_hardened_clay.png deleted file mode 100755 index b05428c..0000000 Binary files a/client/src/main/resources/textures/blocks/cyan_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/cyan_wool.png b/client/src/main/resources/textures/blocks/cyan_wool.png deleted file mode 100755 index ca0800a..0000000 Binary files a/client/src/main/resources/textures/blocks/cyan_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dandelion.png b/client/src/main/resources/textures/blocks/dandelion.png deleted file mode 100755 index 873e3f5..0000000 Binary files a/client/src/main/resources/textures/blocks/dandelion.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_door_bottom.png b/client/src/main/resources/textures/blocks/dark_oak_door_bottom.png deleted file mode 100755 index 7bb3ff2..0000000 Binary files a/client/src/main/resources/textures/blocks/dark_oak_door_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_door_top.png b/client/src/main/resources/textures/blocks/dark_oak_door_top.png deleted file mode 100755 index 27fa6cc..0000000 Binary files a/client/src/main/resources/textures/blocks/dark_oak_door_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_leaves_autumn.png b/client/src/main/resources/textures/blocks/dark_oak_leaves_autumn.png deleted file mode 100755 index aa5c4cc..0000000 Binary files a/client/src/main/resources/textures/blocks/dark_oak_leaves_autumn.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_leaves_snowy.png b/client/src/main/resources/textures/blocks/dark_oak_leaves_snowy.png deleted file mode 100755 index 3afd95b..0000000 Binary files a/client/src/main/resources/textures/blocks/dark_oak_leaves_snowy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_leaves_spring.png b/client/src/main/resources/textures/blocks/dark_oak_leaves_spring.png deleted file mode 100755 index a6773af..0000000 Binary files a/client/src/main/resources/textures/blocks/dark_oak_leaves_spring.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_leaves_summer.png b/client/src/main/resources/textures/blocks/dark_oak_leaves_summer.png deleted file mode 100755 index 23b96b8..0000000 Binary files a/client/src/main/resources/textures/blocks/dark_oak_leaves_summer.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_leaves_winter.png b/client/src/main/resources/textures/blocks/dark_oak_leaves_winter.png deleted file mode 100755 index 27593e4..0000000 Binary files a/client/src/main/resources/textures/blocks/dark_oak_leaves_winter.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_log_bark.png b/client/src/main/resources/textures/blocks/dark_oak_log_bark.png deleted file mode 100755 index d4da03e..0000000 Binary files a/client/src/main/resources/textures/blocks/dark_oak_log_bark.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_log_top.png b/client/src/main/resources/textures/blocks/dark_oak_log_top.png deleted file mode 100755 index 99137b6..0000000 Binary files a/client/src/main/resources/textures/blocks/dark_oak_log_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_planks.png b/client/src/main/resources/textures/blocks/dark_oak_planks.png deleted file mode 100755 index e3fd4ea..0000000 Binary files a/client/src/main/resources/textures/blocks/dark_oak_planks.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_sapling.png b/client/src/main/resources/textures/blocks/dark_oak_sapling.png deleted file mode 100755 index dcf5588..0000000 Binary files a/client/src/main/resources/textures/blocks/dark_oak_sapling.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/darkstone.png b/client/src/main/resources/textures/blocks/darkstone.png deleted file mode 100755 index db20684..0000000 Binary files a/client/src/main/resources/textures/blocks/darkstone.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/daylight_detector_inverted_top.png b/client/src/main/resources/textures/blocks/daylight_detector_inverted_top.png deleted file mode 100755 index 194a30e..0000000 Binary files a/client/src/main/resources/textures/blocks/daylight_detector_inverted_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/daylight_detector_side.png b/client/src/main/resources/textures/blocks/daylight_detector_side.png deleted file mode 100755 index ac273ea..0000000 Binary files a/client/src/main/resources/textures/blocks/daylight_detector_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/daylight_detector_top.png b/client/src/main/resources/textures/blocks/daylight_detector_top.png deleted file mode 100755 index 3bfb2da..0000000 Binary files a/client/src/main/resources/textures/blocks/daylight_detector_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/deadbush.png b/client/src/main/resources/textures/blocks/deadbush.png deleted file mode 100755 index c64e079..0000000 Binary files a/client/src/main/resources/textures/blocks/deadbush.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_0.png b/client/src/main/resources/textures/blocks/destroy_stage_0.png deleted file mode 100755 index f65b7ed..0000000 Binary files a/client/src/main/resources/textures/blocks/destroy_stage_0.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_1.png b/client/src/main/resources/textures/blocks/destroy_stage_1.png deleted file mode 100755 index 7c91596..0000000 Binary files a/client/src/main/resources/textures/blocks/destroy_stage_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_2.png b/client/src/main/resources/textures/blocks/destroy_stage_2.png deleted file mode 100755 index dadd6b0..0000000 Binary files a/client/src/main/resources/textures/blocks/destroy_stage_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_3.png b/client/src/main/resources/textures/blocks/destroy_stage_3.png deleted file mode 100755 index 52a40b6..0000000 Binary files a/client/src/main/resources/textures/blocks/destroy_stage_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_4.png b/client/src/main/resources/textures/blocks/destroy_stage_4.png deleted file mode 100755 index e37c88a..0000000 Binary files a/client/src/main/resources/textures/blocks/destroy_stage_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_5.png b/client/src/main/resources/textures/blocks/destroy_stage_5.png deleted file mode 100755 index 9590d2f..0000000 Binary files a/client/src/main/resources/textures/blocks/destroy_stage_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_6.png b/client/src/main/resources/textures/blocks/destroy_stage_6.png deleted file mode 100755 index 8e490c0..0000000 Binary files a/client/src/main/resources/textures/blocks/destroy_stage_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_7.png b/client/src/main/resources/textures/blocks/destroy_stage_7.png deleted file mode 100755 index 0b40c78..0000000 Binary files a/client/src/main/resources/textures/blocks/destroy_stage_7.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_8.png b/client/src/main/resources/textures/blocks/destroy_stage_8.png deleted file mode 100755 index c0bf1de..0000000 Binary files a/client/src/main/resources/textures/blocks/destroy_stage_8.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_9.png b/client/src/main/resources/textures/blocks/destroy_stage_9.png deleted file mode 100755 index e3185f8..0000000 Binary files a/client/src/main/resources/textures/blocks/destroy_stage_9.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/detector_rail.png b/client/src/main/resources/textures/blocks/detector_rail.png deleted file mode 100755 index 92c1466..0000000 Binary files a/client/src/main/resources/textures/blocks/detector_rail.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/detector_rail_powered.png b/client/src/main/resources/textures/blocks/detector_rail_powered.png deleted file mode 100755 index a1c6e6b..0000000 Binary files a/client/src/main/resources/textures/blocks/detector_rail_powered.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/diamond_block.png b/client/src/main/resources/textures/blocks/diamond_block.png deleted file mode 100755 index 4aefc68..0000000 Binary files a/client/src/main/resources/textures/blocks/diamond_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/diamond_ore.png b/client/src/main/resources/textures/blocks/diamond_ore.png deleted file mode 100755 index 735ecda..0000000 Binary files a/client/src/main/resources/textures/blocks/diamond_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dirt.png b/client/src/main/resources/textures/blocks/dirt.png deleted file mode 100755 index d225d91..0000000 Binary files a/client/src/main/resources/textures/blocks/dirt.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dirt_podzol_side.png b/client/src/main/resources/textures/blocks/dirt_podzol_side.png deleted file mode 100755 index 5921d37..0000000 Binary files a/client/src/main/resources/textures/blocks/dirt_podzol_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dirt_podzol_top.png b/client/src/main/resources/textures/blocks/dirt_podzol_top.png deleted file mode 100755 index ebeda86..0000000 Binary files a/client/src/main/resources/textures/blocks/dirt_podzol_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dispenser_front_horizontal.png b/client/src/main/resources/textures/blocks/dispenser_front_horizontal.png deleted file mode 100755 index 3e09fde..0000000 Binary files a/client/src/main/resources/textures/blocks/dispenser_front_horizontal.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dispenser_front_vertical.png b/client/src/main/resources/textures/blocks/dispenser_front_vertical.png deleted file mode 100755 index 87a7837..0000000 Binary files a/client/src/main/resources/textures/blocks/dispenser_front_vertical.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/double_fern_bottom.png b/client/src/main/resources/textures/blocks/double_fern_bottom.png deleted file mode 100755 index 6a5fa6a..0000000 Binary files a/client/src/main/resources/textures/blocks/double_fern_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/double_fern_top.png b/client/src/main/resources/textures/blocks/double_fern_top.png deleted file mode 100755 index 393144c..0000000 Binary files a/client/src/main/resources/textures/blocks/double_fern_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/double_grass_bottom.png b/client/src/main/resources/textures/blocks/double_grass_bottom.png deleted file mode 100755 index 5ac15b4..0000000 Binary files a/client/src/main/resources/textures/blocks/double_grass_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/double_grass_top.png b/client/src/main/resources/textures/blocks/double_grass_top.png deleted file mode 100755 index 1ceb3de..0000000 Binary files a/client/src/main/resources/textures/blocks/double_grass_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/double_rose_bottom.png b/client/src/main/resources/textures/blocks/double_rose_bottom.png deleted file mode 100755 index 4d59f44..0000000 Binary files a/client/src/main/resources/textures/blocks/double_rose_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/double_rose_top.png b/client/src/main/resources/textures/blocks/double_rose_top.png deleted file mode 100755 index 028aa80..0000000 Binary files a/client/src/main/resources/textures/blocks/double_rose_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/double_stone_top.png b/client/src/main/resources/textures/blocks/double_stone_top.png deleted file mode 100755 index 090657d..0000000 Binary files a/client/src/main/resources/textures/blocks/double_stone_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dragon_egg.png b/client/src/main/resources/textures/blocks/dragon_egg.png deleted file mode 100755 index 02af123..0000000 Binary files a/client/src/main/resources/textures/blocks/dragon_egg.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dropper_front_horizontal.png b/client/src/main/resources/textures/blocks/dropper_front_horizontal.png deleted file mode 100755 index 7d5f260..0000000 Binary files a/client/src/main/resources/textures/blocks/dropper_front_horizontal.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dropper_front_vertical.png b/client/src/main/resources/textures/blocks/dropper_front_vertical.png deleted file mode 100755 index 68a56c8..0000000 Binary files a/client/src/main/resources/textures/blocks/dropper_front_vertical.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/dry_leaves.png b/client/src/main/resources/textures/blocks/dry_leaves.png deleted file mode 100755 index e355797..0000000 Binary files a/client/src/main/resources/textures/blocks/dry_leaves.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/emerald_block.png b/client/src/main/resources/textures/blocks/emerald_block.png deleted file mode 100755 index dc214ee..0000000 Binary files a/client/src/main/resources/textures/blocks/emerald_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/emerald_ore.png b/client/src/main/resources/textures/blocks/emerald_ore.png deleted file mode 100755 index a26c35f..0000000 Binary files a/client/src/main/resources/textures/blocks/emerald_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/enchanting_table_bottom.png b/client/src/main/resources/textures/blocks/enchanting_table_bottom.png deleted file mode 100755 index 0f492aa..0000000 Binary files a/client/src/main/resources/textures/blocks/enchanting_table_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/enchanting_table_side.png b/client/src/main/resources/textures/blocks/enchanting_table_side.png deleted file mode 100755 index f2f4614..0000000 Binary files a/client/src/main/resources/textures/blocks/enchanting_table_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/enchanting_table_top.png b/client/src/main/resources/textures/blocks/enchanting_table_top.png deleted file mode 100755 index 0d5f68f..0000000 Binary files a/client/src/main/resources/textures/blocks/enchanting_table_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/farmland_0.png b/client/src/main/resources/textures/blocks/farmland_0.png deleted file mode 100755 index d03a0f4..0000000 Binary files a/client/src/main/resources/textures/blocks/farmland_0.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/farmland_1.png b/client/src/main/resources/textures/blocks/farmland_1.png deleted file mode 100755 index 4050940..0000000 Binary files a/client/src/main/resources/textures/blocks/farmland_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/farmland_2.png b/client/src/main/resources/textures/blocks/farmland_2.png deleted file mode 100755 index 54ff5f7..0000000 Binary files a/client/src/main/resources/textures/blocks/farmland_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/farmland_3.png b/client/src/main/resources/textures/blocks/farmland_3.png deleted file mode 100755 index bc7a656..0000000 Binary files a/client/src/main/resources/textures/blocks/farmland_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/farmland_4.png b/client/src/main/resources/textures/blocks/farmland_4.png deleted file mode 100755 index fbe48fd..0000000 Binary files a/client/src/main/resources/textures/blocks/farmland_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/farmland_5.png b/client/src/main/resources/textures/blocks/farmland_5.png deleted file mode 100755 index 56caa32..0000000 Binary files a/client/src/main/resources/textures/blocks/farmland_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/farmland_6.png b/client/src/main/resources/textures/blocks/farmland_6.png deleted file mode 100755 index 29df18e..0000000 Binary files a/client/src/main/resources/textures/blocks/farmland_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/farmland_7.png b/client/src/main/resources/textures/blocks/farmland_7.png deleted file mode 100755 index f8d460d..0000000 Binary files a/client/src/main/resources/textures/blocks/farmland_7.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/fern.png b/client/src/main/resources/textures/blocks/fern.png deleted file mode 100755 index fd76950..0000000 Binary files a/client/src/main/resources/textures/blocks/fern.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/floor_portal.png b/client/src/main/resources/textures/blocks/floor_portal.png deleted file mode 100755 index f319846..0000000 Binary files a/client/src/main/resources/textures/blocks/floor_portal.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/floor_tiles.png b/client/src/main/resources/textures/blocks/floor_tiles.png deleted file mode 100755 index 22a3945..0000000 Binary files a/client/src/main/resources/textures/blocks/floor_tiles.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/floor_tiles_black.png b/client/src/main/resources/textures/blocks/floor_tiles_black.png deleted file mode 100755 index 393c557..0000000 Binary files a/client/src/main/resources/textures/blocks/floor_tiles_black.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/floor_tiles_red.png b/client/src/main/resources/textures/blocks/floor_tiles_red.png deleted file mode 100755 index 4648be2..0000000 Binary files a/client/src/main/resources/textures/blocks/floor_tiles_red.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/floor_tiles_white.png b/client/src/main/resources/textures/blocks/floor_tiles_white.png deleted file mode 100755 index c101721..0000000 Binary files a/client/src/main/resources/textures/blocks/floor_tiles_white.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/flower_paeonia.png b/client/src/main/resources/textures/blocks/flower_paeonia.png deleted file mode 100755 index 01a92ee..0000000 Binary files a/client/src/main/resources/textures/blocks/flower_paeonia.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/flower_pot.png b/client/src/main/resources/textures/blocks/flower_pot.png deleted file mode 100755 index 09c2523..0000000 Binary files a/client/src/main/resources/textures/blocks/flower_pot.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/furnace_front_off.png b/client/src/main/resources/textures/blocks/furnace_front_off.png deleted file mode 100755 index 0570c3a..0000000 Binary files a/client/src/main/resources/textures/blocks/furnace_front_off.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/furnace_front_on.png b/client/src/main/resources/textures/blocks/furnace_front_on.png deleted file mode 100755 index 92c89f3..0000000 Binary files a/client/src/main/resources/textures/blocks/furnace_front_on.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/furnace_side.png b/client/src/main/resources/textures/blocks/furnace_side.png deleted file mode 100755 index 115f73d..0000000 Binary files a/client/src/main/resources/textures/blocks/furnace_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/furnace_top.png b/client/src/main/resources/textures/blocks/furnace_top.png deleted file mode 100755 index a3a5a08..0000000 Binary files a/client/src/main/resources/textures/blocks/furnace_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/glass.png b/client/src/main/resources/textures/blocks/glass.png deleted file mode 100755 index acadb01..0000000 Binary files a/client/src/main/resources/textures/blocks/glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/glass_pane.png b/client/src/main/resources/textures/blocks/glass_pane.png deleted file mode 100755 index 02de587..0000000 Binary files a/client/src/main/resources/textures/blocks/glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/glowstone.png b/client/src/main/resources/textures/blocks/glowstone.png deleted file mode 100755 index c7253b3..0000000 Binary files a/client/src/main/resources/textures/blocks/glowstone.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/gold_block.png b/client/src/main/resources/textures/blocks/gold_block.png deleted file mode 100755 index 4a1fa9b..0000000 Binary files a/client/src/main/resources/textures/blocks/gold_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/gold_ore.png b/client/src/main/resources/textures/blocks/gold_ore.png deleted file mode 100755 index b1a7a55..0000000 Binary files a/client/src/main/resources/textures/blocks/gold_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/golden_rail.png b/client/src/main/resources/textures/blocks/golden_rail.png deleted file mode 100755 index 1fc52c3..0000000 Binary files a/client/src/main/resources/textures/blocks/golden_rail.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/golden_rail_powered.png b/client/src/main/resources/textures/blocks/golden_rail_powered.png deleted file mode 100755 index bd343be..0000000 Binary files a/client/src/main/resources/textures/blocks/golden_rail_powered.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/goo_flow.png b/client/src/main/resources/textures/blocks/goo_flow.png deleted file mode 100755 index 0f5f2cc..0000000 Binary files a/client/src/main/resources/textures/blocks/goo_flow.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/goo_still.png b/client/src/main/resources/textures/blocks/goo_still.png deleted file mode 100755 index 5566246..0000000 Binary files a/client/src/main/resources/textures/blocks/goo_still.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/grass_side.png b/client/src/main/resources/textures/blocks/grass_side.png deleted file mode 100755 index 35c021c..0000000 Binary files a/client/src/main/resources/textures/blocks/grass_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/grass_side_overlay.png b/client/src/main/resources/textures/blocks/grass_side_overlay.png deleted file mode 100755 index fc3fa9d..0000000 Binary files a/client/src/main/resources/textures/blocks/grass_side_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/grass_side_snowed.png b/client/src/main/resources/textures/blocks/grass_side_snowed.png deleted file mode 100755 index 41f6197..0000000 Binary files a/client/src/main/resources/textures/blocks/grass_side_snowed.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/grass_top.png b/client/src/main/resources/textures/blocks/grass_top.png deleted file mode 100755 index db3e364..0000000 Binary files a/client/src/main/resources/textures/blocks/grass_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/gravel.png b/client/src/main/resources/textures/blocks/gravel.png deleted file mode 100755 index d9c5f8f..0000000 Binary files a/client/src/main/resources/textures/blocks/gravel.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/gravel_new.png b/client/src/main/resources/textures/blocks/gravel_new.png deleted file mode 100755 index 388e5c5..0000000 Binary files a/client/src/main/resources/textures/blocks/gravel_new.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/gray_glass.png b/client/src/main/resources/textures/blocks/gray_glass.png deleted file mode 100755 index 3f07a5d..0000000 Binary files a/client/src/main/resources/textures/blocks/gray_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/gray_glass_pane.png b/client/src/main/resources/textures/blocks/gray_glass_pane.png deleted file mode 100755 index bb06114..0000000 Binary files a/client/src/main/resources/textures/blocks/gray_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/gray_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/gray_stained_hardened_clay.png deleted file mode 100755 index 8f86904..0000000 Binary files a/client/src/main/resources/textures/blocks/gray_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/gray_wool.png b/client/src/main/resources/textures/blocks/gray_wool.png deleted file mode 100755 index 6409ff2..0000000 Binary files a/client/src/main/resources/textures/blocks/gray_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/green_glass.png b/client/src/main/resources/textures/blocks/green_glass.png deleted file mode 100755 index 7c1f4e6..0000000 Binary files a/client/src/main/resources/textures/blocks/green_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/green_glass_pane.png b/client/src/main/resources/textures/blocks/green_glass_pane.png deleted file mode 100755 index a7d9fc7..0000000 Binary files a/client/src/main/resources/textures/blocks/green_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/green_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/green_stained_hardened_clay.png deleted file mode 100755 index e89162e..0000000 Binary files a/client/src/main/resources/textures/blocks/green_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/green_wool.png b/client/src/main/resources/textures/blocks/green_wool.png deleted file mode 100755 index a7be6d7..0000000 Binary files a/client/src/main/resources/textures/blocks/green_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/gyriyn_block.png b/client/src/main/resources/textures/blocks/gyriyn_block.png deleted file mode 100755 index 324bc65..0000000 Binary files a/client/src/main/resources/textures/blocks/gyriyn_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/gyriyn_ore.png b/client/src/main/resources/textures/blocks/gyriyn_ore.png deleted file mode 100755 index 463aee9..0000000 Binary files a/client/src/main/resources/textures/blocks/gyriyn_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/hardened_clay.png b/client/src/main/resources/textures/blocks/hardened_clay.png deleted file mode 100755 index 2446380..0000000 Binary files a/client/src/main/resources/textures/blocks/hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/hay_block_side.png b/client/src/main/resources/textures/blocks/hay_block_side.png deleted file mode 100755 index a2b32db..0000000 Binary files a/client/src/main/resources/textures/blocks/hay_block_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/hay_block_top.png b/client/src/main/resources/textures/blocks/hay_block_top.png deleted file mode 100755 index 1d35593..0000000 Binary files a/client/src/main/resources/textures/blocks/hay_block_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/hellrock.png b/client/src/main/resources/textures/blocks/hellrock.png deleted file mode 100755 index 22aadc1..0000000 Binary files a/client/src/main/resources/textures/blocks/hellrock.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/hopper_inside.png b/client/src/main/resources/textures/blocks/hopper_inside.png deleted file mode 100755 index 24e8eae..0000000 Binary files a/client/src/main/resources/textures/blocks/hopper_inside.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/hopper_outside.png b/client/src/main/resources/textures/blocks/hopper_outside.png deleted file mode 100755 index 50ed8d5..0000000 Binary files a/client/src/main/resources/textures/blocks/hopper_outside.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/hopper_top.png b/client/src/main/resources/textures/blocks/hopper_top.png deleted file mode 100755 index e0dbe96..0000000 Binary files a/client/src/main/resources/textures/blocks/hopper_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/houstonia.png b/client/src/main/resources/textures/blocks/houstonia.png deleted file mode 100755 index 2f9127d..0000000 Binary files a/client/src/main/resources/textures/blocks/houstonia.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/hydrogen_flow.png b/client/src/main/resources/textures/blocks/hydrogen_flow.png deleted file mode 100755 index 59f93af..0000000 Binary files a/client/src/main/resources/textures/blocks/hydrogen_flow.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/hydrogen_still.png b/client/src/main/resources/textures/blocks/hydrogen_still.png deleted file mode 100755 index 42916be..0000000 Binary files a/client/src/main/resources/textures/blocks/hydrogen_still.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/ice.png b/client/src/main/resources/textures/blocks/ice.png deleted file mode 100755 index ac946e9..0000000 Binary files a/client/src/main/resources/textures/blocks/ice.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/iodine_block.png b/client/src/main/resources/textures/blocks/iodine_block.png deleted file mode 100755 index f7fd2da..0000000 Binary files a/client/src/main/resources/textures/blocks/iodine_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/iodine_ore.png b/client/src/main/resources/textures/blocks/iodine_ore.png deleted file mode 100755 index 533e62d..0000000 Binary files a/client/src/main/resources/textures/blocks/iodine_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/iron_bars.png b/client/src/main/resources/textures/blocks/iron_bars.png deleted file mode 100755 index 732807f..0000000 Binary files a/client/src/main/resources/textures/blocks/iron_bars.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/iron_block.png b/client/src/main/resources/textures/blocks/iron_block.png deleted file mode 100755 index 7816799..0000000 Binary files a/client/src/main/resources/textures/blocks/iron_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/iron_door_bottom.png b/client/src/main/resources/textures/blocks/iron_door_bottom.png deleted file mode 100755 index dbc33ab..0000000 Binary files a/client/src/main/resources/textures/blocks/iron_door_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/iron_door_top.png b/client/src/main/resources/textures/blocks/iron_door_top.png deleted file mode 100755 index 56878fe..0000000 Binary files a/client/src/main/resources/textures/blocks/iron_door_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/iron_ore.png b/client/src/main/resources/textures/blocks/iron_ore.png deleted file mode 100755 index 250d8bb..0000000 Binary files a/client/src/main/resources/textures/blocks/iron_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/iron_trapdoor.png b/client/src/main/resources/textures/blocks/iron_trapdoor.png deleted file mode 100755 index d3c974c..0000000 Binary files a/client/src/main/resources/textures/blocks/iron_trapdoor.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/itemframe_background.png b/client/src/main/resources/textures/blocks/itemframe_background.png deleted file mode 100755 index b40ad65..0000000 Binary files a/client/src/main/resources/textures/blocks/itemframe_background.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jukebox_side.png b/client/src/main/resources/textures/blocks/jukebox_side.png deleted file mode 100755 index a3c27c1..0000000 Binary files a/client/src/main/resources/textures/blocks/jukebox_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jukebox_top.png b/client/src/main/resources/textures/blocks/jukebox_top.png deleted file mode 100755 index 92ddb15..0000000 Binary files a/client/src/main/resources/textures/blocks/jukebox_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jungle_door_bottom.png b/client/src/main/resources/textures/blocks/jungle_door_bottom.png deleted file mode 100755 index 4edfa3c..0000000 Binary files a/client/src/main/resources/textures/blocks/jungle_door_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jungle_door_top.png b/client/src/main/resources/textures/blocks/jungle_door_top.png deleted file mode 100755 index d5201f8..0000000 Binary files a/client/src/main/resources/textures/blocks/jungle_door_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jungle_leaves_autumn.png b/client/src/main/resources/textures/blocks/jungle_leaves_autumn.png deleted file mode 100755 index 2341d5d..0000000 Binary files a/client/src/main/resources/textures/blocks/jungle_leaves_autumn.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jungle_leaves_snowy.png b/client/src/main/resources/textures/blocks/jungle_leaves_snowy.png deleted file mode 100755 index 0fa30b4..0000000 Binary files a/client/src/main/resources/textures/blocks/jungle_leaves_snowy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jungle_leaves_spring.png b/client/src/main/resources/textures/blocks/jungle_leaves_spring.png deleted file mode 100755 index e0cb935..0000000 Binary files a/client/src/main/resources/textures/blocks/jungle_leaves_spring.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jungle_leaves_summer.png b/client/src/main/resources/textures/blocks/jungle_leaves_summer.png deleted file mode 100755 index b053ee8..0000000 Binary files a/client/src/main/resources/textures/blocks/jungle_leaves_summer.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jungle_leaves_winter.png b/client/src/main/resources/textures/blocks/jungle_leaves_winter.png deleted file mode 100755 index 5fe7115..0000000 Binary files a/client/src/main/resources/textures/blocks/jungle_leaves_winter.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jungle_log_bark.png b/client/src/main/resources/textures/blocks/jungle_log_bark.png deleted file mode 100755 index 0b7120a..0000000 Binary files a/client/src/main/resources/textures/blocks/jungle_log_bark.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jungle_log_top.png b/client/src/main/resources/textures/blocks/jungle_log_top.png deleted file mode 100755 index 26b0361..0000000 Binary files a/client/src/main/resources/textures/blocks/jungle_log_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jungle_planks.png b/client/src/main/resources/textures/blocks/jungle_planks.png deleted file mode 100755 index e3fe82d..0000000 Binary files a/client/src/main/resources/textures/blocks/jungle_planks.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/jungle_sapling.png b/client/src/main/resources/textures/blocks/jungle_sapling.png deleted file mode 100755 index 4e10b35..0000000 Binary files a/client/src/main/resources/textures/blocks/jungle_sapling.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/ladder.png b/client/src/main/resources/textures/blocks/ladder.png deleted file mode 100755 index e2ec5f2..0000000 Binary files a/client/src/main/resources/textures/blocks/ladder.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lamp.png b/client/src/main/resources/textures/blocks/lamp.png deleted file mode 100755 index 9562ef3..0000000 Binary files a/client/src/main/resources/textures/blocks/lamp.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lapis_block.png b/client/src/main/resources/textures/blocks/lapis_block.png deleted file mode 100755 index 0271489..0000000 Binary files a/client/src/main/resources/textures/blocks/lapis_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lapis_ore.png b/client/src/main/resources/textures/blocks/lapis_ore.png deleted file mode 100755 index 6144236..0000000 Binary files a/client/src/main/resources/textures/blocks/lapis_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lava_flow.png b/client/src/main/resources/textures/blocks/lava_flow.png deleted file mode 100755 index af07f91..0000000 Binary files a/client/src/main/resources/textures/blocks/lava_flow.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lava_still.png b/client/src/main/resources/textures/blocks/lava_still.png deleted file mode 100755 index 7d14558..0000000 Binary files a/client/src/main/resources/textures/blocks/lava_still.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lead_block.png b/client/src/main/resources/textures/blocks/lead_block.png deleted file mode 100755 index 1b8b733..0000000 Binary files a/client/src/main/resources/textures/blocks/lead_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lead_ore.png b/client/src/main/resources/textures/blocks/lead_ore.png deleted file mode 100755 index b164d5b..0000000 Binary files a/client/src/main/resources/textures/blocks/lead_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lever.png b/client/src/main/resources/textures/blocks/lever.png deleted file mode 100755 index 051187f..0000000 Binary files a/client/src/main/resources/textures/blocks/lever.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/light_blue_glass.png b/client/src/main/resources/textures/blocks/light_blue_glass.png deleted file mode 100755 index b62703d..0000000 Binary files a/client/src/main/resources/textures/blocks/light_blue_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/light_blue_glass_pane.png b/client/src/main/resources/textures/blocks/light_blue_glass_pane.png deleted file mode 100755 index 6a0e661..0000000 Binary files a/client/src/main/resources/textures/blocks/light_blue_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/light_blue_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/light_blue_stained_hardened_clay.png deleted file mode 100755 index 3d9ebea..0000000 Binary files a/client/src/main/resources/textures/blocks/light_blue_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/light_blue_wool.png b/client/src/main/resources/textures/blocks/light_blue_wool.png deleted file mode 100755 index 72d9d9e..0000000 Binary files a/client/src/main/resources/textures/blocks/light_blue_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lime_glass.png b/client/src/main/resources/textures/blocks/lime_glass.png deleted file mode 100755 index f1d3c46..0000000 Binary files a/client/src/main/resources/textures/blocks/lime_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lime_glass_pane.png b/client/src/main/resources/textures/blocks/lime_glass_pane.png deleted file mode 100755 index 0607d75..0000000 Binary files a/client/src/main/resources/textures/blocks/lime_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lime_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/lime_stained_hardened_clay.png deleted file mode 100755 index b459a0b..0000000 Binary files a/client/src/main/resources/textures/blocks/lime_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lime_wool.png b/client/src/main/resources/textures/blocks/lime_wool.png deleted file mode 100755 index bf56389..0000000 Binary files a/client/src/main/resources/textures/blocks/lime_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lit_redstone_lamp.png b/client/src/main/resources/textures/blocks/lit_redstone_lamp.png deleted file mode 100755 index 9562ef3..0000000 Binary files a/client/src/main/resources/textures/blocks/lit_redstone_lamp.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lithium_block.png b/client/src/main/resources/textures/blocks/lithium_block.png deleted file mode 100755 index fd5428d..0000000 Binary files a/client/src/main/resources/textures/blocks/lithium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/lithium_ore.png b/client/src/main/resources/textures/blocks/lithium_ore.png deleted file mode 100755 index 7a64742..0000000 Binary files a/client/src/main/resources/textures/blocks/lithium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/magenta_glass.png b/client/src/main/resources/textures/blocks/magenta_glass.png deleted file mode 100755 index 5cd9945..0000000 Binary files a/client/src/main/resources/textures/blocks/magenta_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/magenta_glass_pane.png b/client/src/main/resources/textures/blocks/magenta_glass_pane.png deleted file mode 100755 index 5419e52..0000000 Binary files a/client/src/main/resources/textures/blocks/magenta_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/magenta_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/magenta_stained_hardened_clay.png deleted file mode 100755 index 9663106..0000000 Binary files a/client/src/main/resources/textures/blocks/magenta_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/magenta_wool.png b/client/src/main/resources/textures/blocks/magenta_wool.png deleted file mode 100755 index 3af6747..0000000 Binary files a/client/src/main/resources/textures/blocks/magenta_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/magnesium_block.png b/client/src/main/resources/textures/blocks/magnesium_block.png deleted file mode 100755 index e148e89..0000000 Binary files a/client/src/main/resources/textures/blocks/magnesium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/magnesium_ore.png b/client/src/main/resources/textures/blocks/magnesium_ore.png deleted file mode 100755 index a51f29b..0000000 Binary files a/client/src/main/resources/textures/blocks/magnesium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/manganese_block.png b/client/src/main/resources/textures/blocks/manganese_block.png deleted file mode 100755 index a43c937..0000000 Binary files a/client/src/main/resources/textures/blocks/manganese_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/manganese_ore.png b/client/src/main/resources/textures/blocks/manganese_ore.png deleted file mode 100755 index a49642c..0000000 Binary files a/client/src/main/resources/textures/blocks/manganese_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/maple_door_bottom.png b/client/src/main/resources/textures/blocks/maple_door_bottom.png deleted file mode 100755 index 33430bf..0000000 Binary files a/client/src/main/resources/textures/blocks/maple_door_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/maple_door_top.png b/client/src/main/resources/textures/blocks/maple_door_top.png deleted file mode 100755 index 2ff07a9..0000000 Binary files a/client/src/main/resources/textures/blocks/maple_door_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/maple_leaves_autumn.png b/client/src/main/resources/textures/blocks/maple_leaves_autumn.png deleted file mode 100755 index 18df1b2..0000000 Binary files a/client/src/main/resources/textures/blocks/maple_leaves_autumn.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/maple_leaves_snowy.png b/client/src/main/resources/textures/blocks/maple_leaves_snowy.png deleted file mode 100755 index de9abae..0000000 Binary files a/client/src/main/resources/textures/blocks/maple_leaves_snowy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/maple_leaves_spring.png b/client/src/main/resources/textures/blocks/maple_leaves_spring.png deleted file mode 100755 index 81dbf24..0000000 Binary files a/client/src/main/resources/textures/blocks/maple_leaves_spring.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/maple_leaves_summer.png b/client/src/main/resources/textures/blocks/maple_leaves_summer.png deleted file mode 100755 index ef72a94..0000000 Binary files a/client/src/main/resources/textures/blocks/maple_leaves_summer.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/maple_leaves_winter.png b/client/src/main/resources/textures/blocks/maple_leaves_winter.png deleted file mode 100755 index 49230a0..0000000 Binary files a/client/src/main/resources/textures/blocks/maple_leaves_winter.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/maple_log_bark.png b/client/src/main/resources/textures/blocks/maple_log_bark.png deleted file mode 100755 index 3c91d87..0000000 Binary files a/client/src/main/resources/textures/blocks/maple_log_bark.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/maple_log_top.png b/client/src/main/resources/textures/blocks/maple_log_top.png deleted file mode 100755 index 735f2df..0000000 Binary files a/client/src/main/resources/textures/blocks/maple_log_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/maple_planks.png b/client/src/main/resources/textures/blocks/maple_planks.png deleted file mode 100755 index b12dfb8..0000000 Binary files a/client/src/main/resources/textures/blocks/maple_planks.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/maple_sapling.png b/client/src/main/resources/textures/blocks/maple_sapling.png deleted file mode 100755 index 8cae38f..0000000 Binary files a/client/src/main/resources/textures/blocks/maple_sapling.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/melon_side.png b/client/src/main/resources/textures/blocks/melon_side.png deleted file mode 100755 index ec7b430..0000000 Binary files a/client/src/main/resources/textures/blocks/melon_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/melon_stem.png b/client/src/main/resources/textures/blocks/melon_stem.png deleted file mode 100755 index 38065ef..0000000 Binary files a/client/src/main/resources/textures/blocks/melon_stem.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/melon_stem_connected.png b/client/src/main/resources/textures/blocks/melon_stem_connected.png deleted file mode 100755 index 6a5c10e..0000000 Binary files a/client/src/main/resources/textures/blocks/melon_stem_connected.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/melon_top.png b/client/src/main/resources/textures/blocks/melon_top.png deleted file mode 100755 index 65cf169..0000000 Binary files a/client/src/main/resources/textures/blocks/melon_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/mercury_flow.png b/client/src/main/resources/textures/blocks/mercury_flow.png deleted file mode 100755 index da22d57..0000000 Binary files a/client/src/main/resources/textures/blocks/mercury_flow.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/mercury_still.png b/client/src/main/resources/textures/blocks/mercury_still.png deleted file mode 100755 index 20c948f..0000000 Binary files a/client/src/main/resources/textures/blocks/mercury_still.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/mob_spawner.png b/client/src/main/resources/textures/blocks/mob_spawner.png deleted file mode 100755 index c248eec..0000000 Binary files a/client/src/main/resources/textures/blocks/mob_spawner.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/moon_cheese.png b/client/src/main/resources/textures/blocks/moon_cheese.png deleted file mode 100755 index 8050187..0000000 Binary files a/client/src/main/resources/textures/blocks/moon_cheese.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/moon_rock.png b/client/src/main/resources/textures/blocks/moon_rock.png deleted file mode 100755 index f61c65d..0000000 Binary files a/client/src/main/resources/textures/blocks/moon_rock.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/mossy_cobblestone.png b/client/src/main/resources/textures/blocks/mossy_cobblestone.png deleted file mode 100755 index b8030d7..0000000 Binary files a/client/src/main/resources/textures/blocks/mossy_cobblestone.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/mycelium_side.png b/client/src/main/resources/textures/blocks/mycelium_side.png deleted file mode 100755 index 5547425..0000000 Binary files a/client/src/main/resources/textures/blocks/mycelium_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/mycelium_top.png b/client/src/main/resources/textures/blocks/mycelium_top.png deleted file mode 100755 index 088a825..0000000 Binary files a/client/src/main/resources/textures/blocks/mycelium_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/neodymium_block.png b/client/src/main/resources/textures/blocks/neodymium_block.png deleted file mode 100755 index 1faa88b..0000000 Binary files a/client/src/main/resources/textures/blocks/neodymium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/neodymium_ore.png b/client/src/main/resources/textures/blocks/neodymium_ore.png deleted file mode 100755 index 808e448..0000000 Binary files a/client/src/main/resources/textures/blocks/neodymium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/neptunium_block.png b/client/src/main/resources/textures/blocks/neptunium_block.png deleted file mode 100755 index 4befc7a..0000000 Binary files a/client/src/main/resources/textures/blocks/neptunium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/neptunium_ore.png b/client/src/main/resources/textures/blocks/neptunium_ore.png deleted file mode 100755 index 0df34cb..0000000 Binary files a/client/src/main/resources/textures/blocks/neptunium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/nichun_block.png b/client/src/main/resources/textures/blocks/nichun_block.png deleted file mode 100755 index a27a7df..0000000 Binary files a/client/src/main/resources/textures/blocks/nichun_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/nichun_ore.png b/client/src/main/resources/textures/blocks/nichun_ore.png deleted file mode 100755 index 8f40944..0000000 Binary files a/client/src/main/resources/textures/blocks/nichun_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/nickel_block.png b/client/src/main/resources/textures/blocks/nickel_block.png deleted file mode 100755 index 8e5fac4..0000000 Binary files a/client/src/main/resources/textures/blocks/nickel_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/nickel_ore.png b/client/src/main/resources/textures/blocks/nickel_ore.png deleted file mode 100755 index 480adeb..0000000 Binary files a/client/src/main/resources/textures/blocks/nickel_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/noteblock.png b/client/src/main/resources/textures/blocks/noteblock.png deleted file mode 100755 index a3c27c1..0000000 Binary files a/client/src/main/resources/textures/blocks/noteblock.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/nukage_flow.png b/client/src/main/resources/textures/blocks/nukage_flow.png deleted file mode 100755 index 0967a40..0000000 Binary files a/client/src/main/resources/textures/blocks/nukage_flow.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/nukage_still.png b/client/src/main/resources/textures/blocks/nukage_still.png deleted file mode 100755 index 013efee..0000000 Binary files a/client/src/main/resources/textures/blocks/nukage_still.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/nuke_bottom.png b/client/src/main/resources/textures/blocks/nuke_bottom.png deleted file mode 100755 index ed06daa..0000000 Binary files a/client/src/main/resources/textures/blocks/nuke_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/nuke_side.png b/client/src/main/resources/textures/blocks/nuke_side.png deleted file mode 100755 index 4cef1c2..0000000 Binary files a/client/src/main/resources/textures/blocks/nuke_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/nuke_top.png b/client/src/main/resources/textures/blocks/nuke_top.png deleted file mode 100755 index bb0764e..0000000 Binary files a/client/src/main/resources/textures/blocks/nuke_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oak_door_bottom.png b/client/src/main/resources/textures/blocks/oak_door_bottom.png deleted file mode 100755 index cc61731..0000000 Binary files a/client/src/main/resources/textures/blocks/oak_door_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oak_door_top.png b/client/src/main/resources/textures/blocks/oak_door_top.png deleted file mode 100755 index 93319d5..0000000 Binary files a/client/src/main/resources/textures/blocks/oak_door_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oak_leaves_autumn.png b/client/src/main/resources/textures/blocks/oak_leaves_autumn.png deleted file mode 100755 index 2960ba3..0000000 Binary files a/client/src/main/resources/textures/blocks/oak_leaves_autumn.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oak_leaves_snowy.png b/client/src/main/resources/textures/blocks/oak_leaves_snowy.png deleted file mode 100755 index b902f2b..0000000 Binary files a/client/src/main/resources/textures/blocks/oak_leaves_snowy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oak_leaves_spring.png b/client/src/main/resources/textures/blocks/oak_leaves_spring.png deleted file mode 100755 index a6773af..0000000 Binary files a/client/src/main/resources/textures/blocks/oak_leaves_spring.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oak_leaves_summer.png b/client/src/main/resources/textures/blocks/oak_leaves_summer.png deleted file mode 100755 index 01fe6e3..0000000 Binary files a/client/src/main/resources/textures/blocks/oak_leaves_summer.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oak_leaves_winter.png b/client/src/main/resources/textures/blocks/oak_leaves_winter.png deleted file mode 100755 index a732ca7..0000000 Binary files a/client/src/main/resources/textures/blocks/oak_leaves_winter.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oak_log_bark.png b/client/src/main/resources/textures/blocks/oak_log_bark.png deleted file mode 100755 index 914cb5f..0000000 Binary files a/client/src/main/resources/textures/blocks/oak_log_bark.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oak_log_top.png b/client/src/main/resources/textures/blocks/oak_log_top.png deleted file mode 100755 index 7a44e77..0000000 Binary files a/client/src/main/resources/textures/blocks/oak_log_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oak_planks.png b/client/src/main/resources/textures/blocks/oak_planks.png deleted file mode 100755 index 346f77d..0000000 Binary files a/client/src/main/resources/textures/blocks/oak_planks.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oak_sapling.png b/client/src/main/resources/textures/blocks/oak_sapling.png deleted file mode 100755 index 1bf1bfa..0000000 Binary files a/client/src/main/resources/textures/blocks/oak_sapling.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/obsidian.png b/client/src/main/resources/textures/blocks/obsidian.png deleted file mode 100755 index ff0a683..0000000 Binary files a/client/src/main/resources/textures/blocks/obsidian.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/orange_glass.png b/client/src/main/resources/textures/blocks/orange_glass.png deleted file mode 100755 index 3a29e31..0000000 Binary files a/client/src/main/resources/textures/blocks/orange_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/orange_glass_pane.png b/client/src/main/resources/textures/blocks/orange_glass_pane.png deleted file mode 100755 index 2866571..0000000 Binary files a/client/src/main/resources/textures/blocks/orange_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/orange_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/orange_stained_hardened_clay.png deleted file mode 100755 index 40929db..0000000 Binary files a/client/src/main/resources/textures/blocks/orange_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/orange_tulip.png b/client/src/main/resources/textures/blocks/orange_tulip.png deleted file mode 100755 index 6715a62..0000000 Binary files a/client/src/main/resources/textures/blocks/orange_tulip.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/orange_wool.png b/client/src/main/resources/textures/blocks/orange_wool.png deleted file mode 100755 index eefe6de..0000000 Binary files a/client/src/main/resources/textures/blocks/orange_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/oxeye_daisy.png b/client/src/main/resources/textures/blocks/oxeye_daisy.png deleted file mode 100755 index 6d48913..0000000 Binary files a/client/src/main/resources/textures/blocks/oxeye_daisy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/packed_ice.png b/client/src/main/resources/textures/blocks/packed_ice.png deleted file mode 100755 index 50f0f34..0000000 Binary files a/client/src/main/resources/textures/blocks/packed_ice.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/paeonia_bottom.png b/client/src/main/resources/textures/blocks/paeonia_bottom.png deleted file mode 100755 index 21285f5..0000000 Binary files a/client/src/main/resources/textures/blocks/paeonia_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/paeonia_top.png b/client/src/main/resources/textures/blocks/paeonia_top.png deleted file mode 100755 index bc68241..0000000 Binary files a/client/src/main/resources/textures/blocks/paeonia_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/palladium_block.png b/client/src/main/resources/textures/blocks/palladium_block.png deleted file mode 100755 index 58ecb1b..0000000 Binary files a/client/src/main/resources/textures/blocks/palladium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/palladium_ore.png b/client/src/main/resources/textures/blocks/palladium_ore.png deleted file mode 100755 index 92e8ebd..0000000 Binary files a/client/src/main/resources/textures/blocks/palladium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pentagram.png b/client/src/main/resources/textures/blocks/pentagram.png deleted file mode 100755 index fa38f69..0000000 Binary files a/client/src/main/resources/textures/blocks/pentagram.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/phosphor_block.png b/client/src/main/resources/textures/blocks/phosphor_block.png deleted file mode 100755 index bbb3d4e..0000000 Binary files a/client/src/main/resources/textures/blocks/phosphor_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/phosphor_ore.png b/client/src/main/resources/textures/blocks/phosphor_ore.png deleted file mode 100755 index e5e54be..0000000 Binary files a/client/src/main/resources/textures/blocks/phosphor_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pink_glass.png b/client/src/main/resources/textures/blocks/pink_glass.png deleted file mode 100755 index 42d8739..0000000 Binary files a/client/src/main/resources/textures/blocks/pink_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pink_glass_pane.png b/client/src/main/resources/textures/blocks/pink_glass_pane.png deleted file mode 100755 index 6b6cd76..0000000 Binary files a/client/src/main/resources/textures/blocks/pink_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pink_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/pink_stained_hardened_clay.png deleted file mode 100755 index c21c0aa..0000000 Binary files a/client/src/main/resources/textures/blocks/pink_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pink_tulip.png b/client/src/main/resources/textures/blocks/pink_tulip.png deleted file mode 100755 index a757bf5..0000000 Binary files a/client/src/main/resources/textures/blocks/pink_tulip.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pink_wool.png b/client/src/main/resources/textures/blocks/pink_wool.png deleted file mode 100755 index c2785af..0000000 Binary files a/client/src/main/resources/textures/blocks/pink_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/piston_bottom.png b/client/src/main/resources/textures/blocks/piston_bottom.png deleted file mode 100755 index a3a5a08..0000000 Binary files a/client/src/main/resources/textures/blocks/piston_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/piston_inner.png b/client/src/main/resources/textures/blocks/piston_inner.png deleted file mode 100755 index 1043929..0000000 Binary files a/client/src/main/resources/textures/blocks/piston_inner.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/piston_side.png b/client/src/main/resources/textures/blocks/piston_side.png deleted file mode 100755 index 634f54a..0000000 Binary files a/client/src/main/resources/textures/blocks/piston_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/piston_top.png b/client/src/main/resources/textures/blocks/piston_top.png deleted file mode 100755 index eeaadab..0000000 Binary files a/client/src/main/resources/textures/blocks/piston_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/piston_top_sticky.png b/client/src/main/resources/textures/blocks/piston_top_sticky.png deleted file mode 100755 index 6ddd4ad..0000000 Binary files a/client/src/main/resources/textures/blocks/piston_top_sticky.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/platinum_block.png b/client/src/main/resources/textures/blocks/platinum_block.png deleted file mode 100755 index d1e32de..0000000 Binary files a/client/src/main/resources/textures/blocks/platinum_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/platinum_ore.png b/client/src/main/resources/textures/blocks/platinum_ore.png deleted file mode 100755 index 0f496db..0000000 Binary files a/client/src/main/resources/textures/blocks/platinum_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/plutonium_block.png b/client/src/main/resources/textures/blocks/plutonium_block.png deleted file mode 100755 index 0ba7300..0000000 Binary files a/client/src/main/resources/textures/blocks/plutonium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/plutonium_ore.png b/client/src/main/resources/textures/blocks/plutonium_ore.png deleted file mode 100755 index f5681e5..0000000 Binary files a/client/src/main/resources/textures/blocks/plutonium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/poppy.png b/client/src/main/resources/textures/blocks/poppy.png deleted file mode 100755 index 895d78f..0000000 Binary files a/client/src/main/resources/textures/blocks/poppy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/portal.png b/client/src/main/resources/textures/blocks/portal.png deleted file mode 100755 index 805331f..0000000 Binary files a/client/src/main/resources/textures/blocks/portal.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/portal_frame_bottom.png b/client/src/main/resources/textures/blocks/portal_frame_bottom.png deleted file mode 100755 index 9aca3ce..0000000 Binary files a/client/src/main/resources/textures/blocks/portal_frame_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/portal_frame_orb.png b/client/src/main/resources/textures/blocks/portal_frame_orb.png deleted file mode 100755 index b7eb9bb..0000000 Binary files a/client/src/main/resources/textures/blocks/portal_frame_orb.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/portal_frame_side.png b/client/src/main/resources/textures/blocks/portal_frame_side.png deleted file mode 100755 index 799e089..0000000 Binary files a/client/src/main/resources/textures/blocks/portal_frame_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/portal_frame_top.png b/client/src/main/resources/textures/blocks/portal_frame_top.png deleted file mode 100755 index ae41640..0000000 Binary files a/client/src/main/resources/textures/blocks/portal_frame_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/potassium_block.png b/client/src/main/resources/textures/blocks/potassium_block.png deleted file mode 100755 index 3c8ee97..0000000 Binary files a/client/src/main/resources/textures/blocks/potassium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/potassium_ore.png b/client/src/main/resources/textures/blocks/potassium_ore.png deleted file mode 100755 index f5925de..0000000 Binary files a/client/src/main/resources/textures/blocks/potassium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/potato_0.png b/client/src/main/resources/textures/blocks/potato_0.png deleted file mode 100755 index c1ef732..0000000 Binary files a/client/src/main/resources/textures/blocks/potato_0.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/potato_1.png b/client/src/main/resources/textures/blocks/potato_1.png deleted file mode 100755 index 1275f4f..0000000 Binary files a/client/src/main/resources/textures/blocks/potato_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/potato_2.png b/client/src/main/resources/textures/blocks/potato_2.png deleted file mode 100755 index b7347df..0000000 Binary files a/client/src/main/resources/textures/blocks/potato_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/potato_3.png b/client/src/main/resources/textures/blocks/potato_3.png deleted file mode 100755 index d7e8185..0000000 Binary files a/client/src/main/resources/textures/blocks/potato_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/praseodymium_block.png b/client/src/main/resources/textures/blocks/praseodymium_block.png deleted file mode 100755 index ec1e0bd..0000000 Binary files a/client/src/main/resources/textures/blocks/praseodymium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/praseodymium_ore.png b/client/src/main/resources/textures/blocks/praseodymium_ore.png deleted file mode 100755 index cf831ed..0000000 Binary files a/client/src/main/resources/textures/blocks/praseodymium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_face_off.png b/client/src/main/resources/textures/blocks/pumpkin_face_off.png deleted file mode 100755 index ecef025..0000000 Binary files a/client/src/main/resources/textures/blocks/pumpkin_face_off.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_face_on.png b/client/src/main/resources/textures/blocks/pumpkin_face_on.png deleted file mode 100755 index 907f499..0000000 Binary files a/client/src/main/resources/textures/blocks/pumpkin_face_on.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_side.png b/client/src/main/resources/textures/blocks/pumpkin_side.png deleted file mode 100755 index 75dfc47..0000000 Binary files a/client/src/main/resources/textures/blocks/pumpkin_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_stem.png b/client/src/main/resources/textures/blocks/pumpkin_stem.png deleted file mode 100755 index 38065ef..0000000 Binary files a/client/src/main/resources/textures/blocks/pumpkin_stem.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_stem_connected.png b/client/src/main/resources/textures/blocks/pumpkin_stem_connected.png deleted file mode 100755 index 6a5c10e..0000000 Binary files a/client/src/main/resources/textures/blocks/pumpkin_stem_connected.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_top.png b/client/src/main/resources/textures/blocks/pumpkin_top.png deleted file mode 100755 index 297ce3c..0000000 Binary files a/client/src/main/resources/textures/blocks/pumpkin_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_foot_end.png b/client/src/main/resources/textures/blocks/purple_bed_foot_end.png deleted file mode 100755 index 8e4ed34..0000000 Binary files a/client/src/main/resources/textures/blocks/purple_bed_foot_end.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_foot_side.png b/client/src/main/resources/textures/blocks/purple_bed_foot_side.png deleted file mode 100755 index f0d316c..0000000 Binary files a/client/src/main/resources/textures/blocks/purple_bed_foot_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_foot_top.png b/client/src/main/resources/textures/blocks/purple_bed_foot_top.png deleted file mode 100755 index f1274cb..0000000 Binary files a/client/src/main/resources/textures/blocks/purple_bed_foot_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_head_end.png b/client/src/main/resources/textures/blocks/purple_bed_head_end.png deleted file mode 100755 index 5811c48..0000000 Binary files a/client/src/main/resources/textures/blocks/purple_bed_head_end.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_head_side.png b/client/src/main/resources/textures/blocks/purple_bed_head_side.png deleted file mode 100755 index 793b2dc..0000000 Binary files a/client/src/main/resources/textures/blocks/purple_bed_head_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_head_top.png b/client/src/main/resources/textures/blocks/purple_bed_head_top.png deleted file mode 100755 index 4285261..0000000 Binary files a/client/src/main/resources/textures/blocks/purple_bed_head_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/purple_glass.png b/client/src/main/resources/textures/blocks/purple_glass.png deleted file mode 100755 index fcae3d2..0000000 Binary files a/client/src/main/resources/textures/blocks/purple_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/purple_glass_pane.png b/client/src/main/resources/textures/blocks/purple_glass_pane.png deleted file mode 100755 index 23e208e..0000000 Binary files a/client/src/main/resources/textures/blocks/purple_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/purple_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/purple_stained_hardened_clay.png deleted file mode 100755 index edece94..0000000 Binary files a/client/src/main/resources/textures/blocks/purple_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/purple_wool.png b/client/src/main/resources/textures/blocks/purple_wool.png deleted file mode 100755 index 76f68d6..0000000 Binary files a/client/src/main/resources/textures/blocks/purple_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_bottom.png b/client/src/main/resources/textures/blocks/quartz_block_bottom.png deleted file mode 100755 index 7e16c7c..0000000 Binary files a/client/src/main/resources/textures/blocks/quartz_block_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_chiseled.png b/client/src/main/resources/textures/blocks/quartz_block_chiseled.png deleted file mode 100755 index 80465a1..0000000 Binary files a/client/src/main/resources/textures/blocks/quartz_block_chiseled.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_chiseled_top.png b/client/src/main/resources/textures/blocks/quartz_block_chiseled_top.png deleted file mode 100755 index 44073e5..0000000 Binary files a/client/src/main/resources/textures/blocks/quartz_block_chiseled_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_lines.png b/client/src/main/resources/textures/blocks/quartz_block_lines.png deleted file mode 100755 index 184ecd2..0000000 Binary files a/client/src/main/resources/textures/blocks/quartz_block_lines.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_lines_top.png b/client/src/main/resources/textures/blocks/quartz_block_lines_top.png deleted file mode 100755 index 6d20379..0000000 Binary files a/client/src/main/resources/textures/blocks/quartz_block_lines_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_side.png b/client/src/main/resources/textures/blocks/quartz_block_side.png deleted file mode 100755 index a2cd2ca..0000000 Binary files a/client/src/main/resources/textures/blocks/quartz_block_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/quartz_ore.png b/client/src/main/resources/textures/blocks/quartz_ore.png deleted file mode 100755 index 4d758c1..0000000 Binary files a/client/src/main/resources/textures/blocks/quartz_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/quartz_top.png b/client/src/main/resources/textures/blocks/quartz_top.png deleted file mode 100755 index a2cd2ca..0000000 Binary files a/client/src/main/resources/textures/blocks/quartz_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/radium_block.png b/client/src/main/resources/textures/blocks/radium_block.png deleted file mode 100755 index 63b0d26..0000000 Binary files a/client/src/main/resources/textures/blocks/radium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/radium_ore.png b/client/src/main/resources/textures/blocks/radium_ore.png deleted file mode 100755 index f9141f1..0000000 Binary files a/client/src/main/resources/textures/blocks/radium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/rail.png b/client/src/main/resources/textures/blocks/rail.png deleted file mode 100755 index d609236..0000000 Binary files a/client/src/main/resources/textures/blocks/rail.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/rail_turned.png b/client/src/main/resources/textures/blocks/rail_turned.png deleted file mode 100755 index f394a23..0000000 Binary files a/client/src/main/resources/textures/blocks/rail_turned.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_bed_foot_end.png b/client/src/main/resources/textures/blocks/red_bed_foot_end.png deleted file mode 100755 index 6e1a4be..0000000 Binary files a/client/src/main/resources/textures/blocks/red_bed_foot_end.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_bed_foot_side.png b/client/src/main/resources/textures/blocks/red_bed_foot_side.png deleted file mode 100755 index 3ce06f3..0000000 Binary files a/client/src/main/resources/textures/blocks/red_bed_foot_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_bed_foot_top.png b/client/src/main/resources/textures/blocks/red_bed_foot_top.png deleted file mode 100755 index b96d357..0000000 Binary files a/client/src/main/resources/textures/blocks/red_bed_foot_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_bed_head_end.png b/client/src/main/resources/textures/blocks/red_bed_head_end.png deleted file mode 100755 index b684c9a..0000000 Binary files a/client/src/main/resources/textures/blocks/red_bed_head_end.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_bed_head_side.png b/client/src/main/resources/textures/blocks/red_bed_head_side.png deleted file mode 100755 index 3270b4a..0000000 Binary files a/client/src/main/resources/textures/blocks/red_bed_head_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_bed_head_top.png b/client/src/main/resources/textures/blocks/red_bed_head_top.png deleted file mode 100755 index 2ab1090..0000000 Binary files a/client/src/main/resources/textures/blocks/red_bed_head_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_button.png b/client/src/main/resources/textures/blocks/red_button.png deleted file mode 100755 index 29ade3c..0000000 Binary files a/client/src/main/resources/textures/blocks/red_button.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_glass.png b/client/src/main/resources/textures/blocks/red_glass.png deleted file mode 100755 index db4c5eb..0000000 Binary files a/client/src/main/resources/textures/blocks/red_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_glass_pane.png b/client/src/main/resources/textures/blocks/red_glass_pane.png deleted file mode 100755 index 22b69db..0000000 Binary files a/client/src/main/resources/textures/blocks/red_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_mushroom.png b/client/src/main/resources/textures/blocks/red_mushroom.png deleted file mode 100755 index 1b332b7..0000000 Binary files a/client/src/main/resources/textures/blocks/red_mushroom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_mushroom_block_cap.png b/client/src/main/resources/textures/blocks/red_mushroom_block_cap.png deleted file mode 100755 index 66cf12c..0000000 Binary files a/client/src/main/resources/textures/blocks/red_mushroom_block_cap.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_mushroom_block_inside.png b/client/src/main/resources/textures/blocks/red_mushroom_block_inside.png deleted file mode 100755 index f0e7a04..0000000 Binary files a/client/src/main/resources/textures/blocks/red_mushroom_block_inside.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_mushroom_block_stem.png b/client/src/main/resources/textures/blocks/red_mushroom_block_stem.png deleted file mode 100755 index 83c0840..0000000 Binary files a/client/src/main/resources/textures/blocks/red_mushroom_block_stem.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_sand.png b/client/src/main/resources/textures/blocks/red_sand.png deleted file mode 100755 index b216a42..0000000 Binary files a/client/src/main/resources/textures/blocks/red_sand.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/red_stained_hardened_clay.png deleted file mode 100755 index 6561d12..0000000 Binary files a/client/src/main/resources/textures/blocks/red_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_tulip.png b/client/src/main/resources/textures/blocks/red_tulip.png deleted file mode 100755 index 3048b63..0000000 Binary files a/client/src/main/resources/textures/blocks/red_tulip.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/red_wool.png b/client/src/main/resources/textures/blocks/red_wool.png deleted file mode 100755 index 0cff7a9..0000000 Binary files a/client/src/main/resources/textures/blocks/red_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/redstone_block.png b/client/src/main/resources/textures/blocks/redstone_block.png deleted file mode 100755 index fcf6b40..0000000 Binary files a/client/src/main/resources/textures/blocks/redstone_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/redstone_dust_cross.png b/client/src/main/resources/textures/blocks/redstone_dust_cross.png deleted file mode 100755 index 66eba38..0000000 Binary files a/client/src/main/resources/textures/blocks/redstone_dust_cross.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/redstone_dust_cross_overlay.png b/client/src/main/resources/textures/blocks/redstone_dust_cross_overlay.png deleted file mode 100755 index 96729e1..0000000 Binary files a/client/src/main/resources/textures/blocks/redstone_dust_cross_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/redstone_dust_line.png b/client/src/main/resources/textures/blocks/redstone_dust_line.png deleted file mode 100755 index a1ae205..0000000 Binary files a/client/src/main/resources/textures/blocks/redstone_dust_line.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/redstone_dust_line_overlay.png b/client/src/main/resources/textures/blocks/redstone_dust_line_overlay.png deleted file mode 100755 index 9f24cbc..0000000 Binary files a/client/src/main/resources/textures/blocks/redstone_dust_line_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/redstone_lamp.png b/client/src/main/resources/textures/blocks/redstone_lamp.png deleted file mode 100755 index 522765b..0000000 Binary files a/client/src/main/resources/textures/blocks/redstone_lamp.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/redstone_ore.png b/client/src/main/resources/textures/blocks/redstone_ore.png deleted file mode 100755 index 575a488..0000000 Binary files a/client/src/main/resources/textures/blocks/redstone_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/redstone_torch.png b/client/src/main/resources/textures/blocks/redstone_torch.png deleted file mode 100755 index 2983d6c..0000000 Binary files a/client/src/main/resources/textures/blocks/redstone_torch.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/reeds.png b/client/src/main/resources/textures/blocks/reeds.png deleted file mode 100755 index 64bbfe0..0000000 Binary files a/client/src/main/resources/textures/blocks/reeds.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/repeater_off.png b/client/src/main/resources/textures/blocks/repeater_off.png deleted file mode 100755 index 8634669..0000000 Binary files a/client/src/main/resources/textures/blocks/repeater_off.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/repeater_on.png b/client/src/main/resources/textures/blocks/repeater_on.png deleted file mode 100755 index d71d0d9..0000000 Binary files a/client/src/main/resources/textures/blocks/repeater_on.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/rock.png b/client/src/main/resources/textures/blocks/rock.png deleted file mode 100755 index 680a899..0000000 Binary files a/client/src/main/resources/textures/blocks/rock.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/rose.png b/client/src/main/resources/textures/blocks/rose.png deleted file mode 100755 index 15ebba6..0000000 Binary files a/client/src/main/resources/textures/blocks/rose.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/ruby_block.png b/client/src/main/resources/textures/blocks/ruby_block.png deleted file mode 100755 index 2edc4c1..0000000 Binary files a/client/src/main/resources/textures/blocks/ruby_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/ruby_ore.png b/client/src/main/resources/textures/blocks/ruby_ore.png deleted file mode 100755 index 8a104cb..0000000 Binary files a/client/src/main/resources/textures/blocks/ruby_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sand.png b/client/src/main/resources/textures/blocks/sand.png deleted file mode 100755 index cb7f2b9..0000000 Binary files a/client/src/main/resources/textures/blocks/sand.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sandstone_all.png b/client/src/main/resources/textures/blocks/sandstone_all.png deleted file mode 100755 index bb5b157..0000000 Binary files a/client/src/main/resources/textures/blocks/sandstone_all.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sandstone_bottom.png b/client/src/main/resources/textures/blocks/sandstone_bottom.png deleted file mode 100755 index e102220..0000000 Binary files a/client/src/main/resources/textures/blocks/sandstone_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sandstone_carved.png b/client/src/main/resources/textures/blocks/sandstone_carved.png deleted file mode 100755 index 9bd7fa1..0000000 Binary files a/client/src/main/resources/textures/blocks/sandstone_carved.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sandstone_normal.png b/client/src/main/resources/textures/blocks/sandstone_normal.png deleted file mode 100755 index 1b79145..0000000 Binary files a/client/src/main/resources/textures/blocks/sandstone_normal.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sandstone_smooth.png b/client/src/main/resources/textures/blocks/sandstone_smooth.png deleted file mode 100755 index ef118bd..0000000 Binary files a/client/src/main/resources/textures/blocks/sandstone_smooth.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/selenium_block.png b/client/src/main/resources/textures/blocks/selenium_block.png deleted file mode 100755 index 2268527..0000000 Binary files a/client/src/main/resources/textures/blocks/selenium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/selenium_ore.png b/client/src/main/resources/textures/blocks/selenium_ore.png deleted file mode 100755 index fd7f9a4..0000000 Binary files a/client/src/main/resources/textures/blocks/selenium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sign.png b/client/src/main/resources/textures/blocks/sign.png deleted file mode 100755 index e22e2f7..0000000 Binary files a/client/src/main/resources/textures/blocks/sign.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/silicon_block.png b/client/src/main/resources/textures/blocks/silicon_block.png deleted file mode 100755 index a5cd9ec..0000000 Binary files a/client/src/main/resources/textures/blocks/silicon_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/silicon_ore.png b/client/src/main/resources/textures/blocks/silicon_ore.png deleted file mode 100755 index dbd76bb..0000000 Binary files a/client/src/main/resources/textures/blocks/silicon_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/silver_block.png b/client/src/main/resources/textures/blocks/silver_block.png deleted file mode 100755 index 23542a9..0000000 Binary files a/client/src/main/resources/textures/blocks/silver_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/silver_glass.png b/client/src/main/resources/textures/blocks/silver_glass.png deleted file mode 100755 index 8461664..0000000 Binary files a/client/src/main/resources/textures/blocks/silver_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/silver_glass_pane.png b/client/src/main/resources/textures/blocks/silver_glass_pane.png deleted file mode 100755 index f226ecc..0000000 Binary files a/client/src/main/resources/textures/blocks/silver_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/silver_ore.png b/client/src/main/resources/textures/blocks/silver_ore.png deleted file mode 100755 index 305c58c..0000000 Binary files a/client/src/main/resources/textures/blocks/silver_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/silver_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/silver_stained_hardened_clay.png deleted file mode 100755 index eae07f2..0000000 Binary files a/client/src/main/resources/textures/blocks/silver_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/silver_wool.png b/client/src/main/resources/textures/blocks/silver_wool.png deleted file mode 100755 index 756d9b0..0000000 Binary files a/client/src/main/resources/textures/blocks/silver_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/skull_back.png b/client/src/main/resources/textures/blocks/skull_back.png deleted file mode 100644 index eb5bada..0000000 Binary files a/client/src/main/resources/textures/blocks/skull_back.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/skull_bottom.png b/client/src/main/resources/textures/blocks/skull_bottom.png deleted file mode 100644 index 4dcb71b..0000000 Binary files a/client/src/main/resources/textures/blocks/skull_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/skull_front.png b/client/src/main/resources/textures/blocks/skull_front.png deleted file mode 100644 index 12d4a2c..0000000 Binary files a/client/src/main/resources/textures/blocks/skull_front.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/skull_left.png b/client/src/main/resources/textures/blocks/skull_left.png deleted file mode 100644 index 988f674..0000000 Binary files a/client/src/main/resources/textures/blocks/skull_left.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/skull_right.png b/client/src/main/resources/textures/blocks/skull_right.png deleted file mode 100644 index b23ea4c..0000000 Binary files a/client/src/main/resources/textures/blocks/skull_right.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/skull_top.png b/client/src/main/resources/textures/blocks/skull_top.png deleted file mode 100644 index f4a484c..0000000 Binary files a/client/src/main/resources/textures/blocks/skull_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/slime.png b/client/src/main/resources/textures/blocks/slime.png deleted file mode 100755 index 6dbe5cb..0000000 Binary files a/client/src/main/resources/textures/blocks/slime.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/slime_flow.png b/client/src/main/resources/textures/blocks/slime_flow.png deleted file mode 100755 index 83634df..0000000 Binary files a/client/src/main/resources/textures/blocks/slime_flow.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/slime_still.png b/client/src/main/resources/textures/blocks/slime_still.png deleted file mode 100755 index 6de7593..0000000 Binary files a/client/src/main/resources/textures/blocks/slime_still.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/smooth_rock.png b/client/src/main/resources/textures/blocks/smooth_rock.png deleted file mode 100755 index a77809c..0000000 Binary files a/client/src/main/resources/textures/blocks/smooth_rock.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/snow.png b/client/src/main/resources/textures/blocks/snow.png deleted file mode 100755 index 5c146cd..0000000 Binary files a/client/src/main/resources/textures/blocks/snow.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sodium_block.png b/client/src/main/resources/textures/blocks/sodium_block.png deleted file mode 100755 index c4a7e11..0000000 Binary files a/client/src/main/resources/textures/blocks/sodium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sodium_ore.png b/client/src/main/resources/textures/blocks/sodium_ore.png deleted file mode 100755 index aa462ba..0000000 Binary files a/client/src/main/resources/textures/blocks/sodium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/soul_sand.png b/client/src/main/resources/textures/blocks/soul_sand.png deleted file mode 100755 index fca7e8f..0000000 Binary files a/client/src/main/resources/textures/blocks/soul_sand.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/soul_wart_0.png b/client/src/main/resources/textures/blocks/soul_wart_0.png deleted file mode 100755 index 514a95b..0000000 Binary files a/client/src/main/resources/textures/blocks/soul_wart_0.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/soul_wart_1.png b/client/src/main/resources/textures/blocks/soul_wart_1.png deleted file mode 100755 index b4ad0d1..0000000 Binary files a/client/src/main/resources/textures/blocks/soul_wart_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/soul_wart_2.png b/client/src/main/resources/textures/blocks/soul_wart_2.png deleted file mode 100755 index b9b6743..0000000 Binary files a/client/src/main/resources/textures/blocks/soul_wart_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sponge.png b/client/src/main/resources/textures/blocks/sponge.png deleted file mode 100755 index 33062d7..0000000 Binary files a/client/src/main/resources/textures/blocks/sponge.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/springwater_flow.png b/client/src/main/resources/textures/blocks/springwater_flow.png deleted file mode 100755 index 19dcfef..0000000 Binary files a/client/src/main/resources/textures/blocks/springwater_flow.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/springwater_still.png b/client/src/main/resources/textures/blocks/springwater_still.png deleted file mode 100755 index fdd9eab..0000000 Binary files a/client/src/main/resources/textures/blocks/springwater_still.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/spruce_door_bottom.png b/client/src/main/resources/textures/blocks/spruce_door_bottom.png deleted file mode 100755 index 5faa6e7..0000000 Binary files a/client/src/main/resources/textures/blocks/spruce_door_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/spruce_door_top.png b/client/src/main/resources/textures/blocks/spruce_door_top.png deleted file mode 100755 index 38e2717..0000000 Binary files a/client/src/main/resources/textures/blocks/spruce_door_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/spruce_leaves_autumn.png b/client/src/main/resources/textures/blocks/spruce_leaves_autumn.png deleted file mode 100755 index c90d2fa..0000000 Binary files a/client/src/main/resources/textures/blocks/spruce_leaves_autumn.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/spruce_leaves_snowy.png b/client/src/main/resources/textures/blocks/spruce_leaves_snowy.png deleted file mode 100755 index 5498df4..0000000 Binary files a/client/src/main/resources/textures/blocks/spruce_leaves_snowy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/spruce_leaves_spring.png b/client/src/main/resources/textures/blocks/spruce_leaves_spring.png deleted file mode 100755 index 602eab8..0000000 Binary files a/client/src/main/resources/textures/blocks/spruce_leaves_spring.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/spruce_leaves_summer.png b/client/src/main/resources/textures/blocks/spruce_leaves_summer.png deleted file mode 100755 index 44456fb..0000000 Binary files a/client/src/main/resources/textures/blocks/spruce_leaves_summer.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/spruce_leaves_winter.png b/client/src/main/resources/textures/blocks/spruce_leaves_winter.png deleted file mode 100755 index 5db74d9..0000000 Binary files a/client/src/main/resources/textures/blocks/spruce_leaves_winter.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/spruce_log_bark.png b/client/src/main/resources/textures/blocks/spruce_log_bark.png deleted file mode 100755 index dc1aa2f..0000000 Binary files a/client/src/main/resources/textures/blocks/spruce_log_bark.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/spruce_log_top.png b/client/src/main/resources/textures/blocks/spruce_log_top.png deleted file mode 100755 index 280c64e..0000000 Binary files a/client/src/main/resources/textures/blocks/spruce_log_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/spruce_planks.png b/client/src/main/resources/textures/blocks/spruce_planks.png deleted file mode 100755 index f45fa94..0000000 Binary files a/client/src/main/resources/textures/blocks/spruce_planks.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/spruce_sapling.png b/client/src/main/resources/textures/blocks/spruce_sapling.png deleted file mode 100755 index 5767d48..0000000 Binary files a/client/src/main/resources/textures/blocks/spruce_sapling.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/stone.png b/client/src/main/resources/textures/blocks/stone.png deleted file mode 100755 index bf63ad3..0000000 Binary files a/client/src/main/resources/textures/blocks/stone.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/stone_slab_side.png b/client/src/main/resources/textures/blocks/stone_slab_side.png deleted file mode 100755 index fe2a204..0000000 Binary files a/client/src/main/resources/textures/blocks/stone_slab_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/stonebrick_chiseled.png b/client/src/main/resources/textures/blocks/stonebrick_chiseled.png deleted file mode 100755 index b7e88db..0000000 Binary files a/client/src/main/resources/textures/blocks/stonebrick_chiseled.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/stonebrick_cracked.png b/client/src/main/resources/textures/blocks/stonebrick_cracked.png deleted file mode 100755 index 918a884..0000000 Binary files a/client/src/main/resources/textures/blocks/stonebrick_cracked.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/stonebrick_default.png b/client/src/main/resources/textures/blocks/stonebrick_default.png deleted file mode 100755 index 69138cf..0000000 Binary files a/client/src/main/resources/textures/blocks/stonebrick_default.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/stonebrick_mossy.png b/client/src/main/resources/textures/blocks/stonebrick_mossy.png deleted file mode 100755 index 5b9fe37..0000000 Binary files a/client/src/main/resources/textures/blocks/stonebrick_mossy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sulfur_block.png b/client/src/main/resources/textures/blocks/sulfur_block.png deleted file mode 100755 index 868d044..0000000 Binary files a/client/src/main/resources/textures/blocks/sulfur_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sulfur_ore.png b/client/src/main/resources/textures/blocks/sulfur_ore.png deleted file mode 100755 index 27c662f..0000000 Binary files a/client/src/main/resources/textures/blocks/sulfur_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sunflower_back.png b/client/src/main/resources/textures/blocks/sunflower_back.png deleted file mode 100755 index d488923..0000000 Binary files a/client/src/main/resources/textures/blocks/sunflower_back.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sunflower_bottom.png b/client/src/main/resources/textures/blocks/sunflower_bottom.png deleted file mode 100755 index 8a12ebe..0000000 Binary files a/client/src/main/resources/textures/blocks/sunflower_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sunflower_front.png b/client/src/main/resources/textures/blocks/sunflower_front.png deleted file mode 100755 index 699e34f..0000000 Binary files a/client/src/main/resources/textures/blocks/sunflower_front.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/sunflower_top.png b/client/src/main/resources/textures/blocks/sunflower_top.png deleted file mode 100755 index 4d14203..0000000 Binary files a/client/src/main/resources/textures/blocks/sunflower_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/syringa_bottom.png b/client/src/main/resources/textures/blocks/syringa_bottom.png deleted file mode 100755 index 5b880b5..0000000 Binary files a/client/src/main/resources/textures/blocks/syringa_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/syringa_top.png b/client/src/main/resources/textures/blocks/syringa_top.png deleted file mode 100755 index b00751f..0000000 Binary files a/client/src/main/resources/textures/blocks/syringa_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tall_grass.png b/client/src/main/resources/textures/blocks/tall_grass.png deleted file mode 100755 index 2869848..0000000 Binary files a/client/src/main/resources/textures/blocks/tall_grass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/thetium_block.png b/client/src/main/resources/textures/blocks/thetium_block.png deleted file mode 100755 index b71f8d6..0000000 Binary files a/client/src/main/resources/textures/blocks/thetium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/thetium_ore.png b/client/src/main/resources/textures/blocks/thetium_ore.png deleted file mode 100755 index c93156c..0000000 Binary files a/client/src/main/resources/textures/blocks/thetium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian.png b/client/src/main/resources/textures/blocks/tian.png deleted file mode 100755 index 93dd028..0000000 Binary files a/client/src/main/resources/textures/blocks/tian.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_door_bottom.png b/client/src/main/resources/textures/blocks/tian_door_bottom.png deleted file mode 100755 index 9bac389..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_door_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_door_top.png b/client/src/main/resources/textures/blocks/tian_door_top.png deleted file mode 100755 index 23f3d05..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_door_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_leaves_autumn.png b/client/src/main/resources/textures/blocks/tian_leaves_autumn.png deleted file mode 100755 index 5ed6cec..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_leaves_autumn.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_leaves_snowy.png b/client/src/main/resources/textures/blocks/tian_leaves_snowy.png deleted file mode 100755 index dfdd888..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_leaves_snowy.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_leaves_spring.png b/client/src/main/resources/textures/blocks/tian_leaves_spring.png deleted file mode 100755 index d02db7b..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_leaves_spring.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_leaves_summer.png b/client/src/main/resources/textures/blocks/tian_leaves_summer.png deleted file mode 100755 index 77ea69e..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_leaves_summer.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_leaves_winter.png b/client/src/main/resources/textures/blocks/tian_leaves_winter.png deleted file mode 100755 index 148d95b..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_leaves_winter.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_log_bark.png b/client/src/main/resources/textures/blocks/tian_log_bark.png deleted file mode 100755 index 50653f5..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_log_bark.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_log_top.png b/client/src/main/resources/textures/blocks/tian_log_top.png deleted file mode 100755 index b2f0c47..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_log_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_planks.png b/client/src/main/resources/textures/blocks/tian_planks.png deleted file mode 100755 index 74fce78..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_planks.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_reactor_bottom.png b/client/src/main/resources/textures/blocks/tian_reactor_bottom.png deleted file mode 100755 index 3302315..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_reactor_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_reactor_front.png b/client/src/main/resources/textures/blocks/tian_reactor_front.png deleted file mode 100755 index 3c27a73..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_reactor_front.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_reactor_side.png b/client/src/main/resources/textures/blocks/tian_reactor_side.png deleted file mode 100755 index b684f4e..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_reactor_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_reactor_top.png b/client/src/main/resources/textures/blocks/tian_reactor_top.png deleted file mode 100755 index a564e61..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_reactor_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_sapling.png b/client/src/main/resources/textures/blocks/tian_sapling.png deleted file mode 100755 index e1f9383..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_sapling.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_soil_side.png b/client/src/main/resources/textures/blocks/tian_soil_side.png deleted file mode 100755 index 5ca5164..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_soil_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_soil_side_snowed.png b/client/src/main/resources/textures/blocks/tian_soil_side_snowed.png deleted file mode 100755 index 22618b8..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_soil_side_snowed.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tian_soil_top.png b/client/src/main/resources/textures/blocks/tian_soil_top.png deleted file mode 100755 index 07d6a69..0000000 Binary files a/client/src/main/resources/textures/blocks/tian_soil_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tin_block.png b/client/src/main/resources/textures/blocks/tin_block.png deleted file mode 100755 index 8d87037..0000000 Binary files a/client/src/main/resources/textures/blocks/tin_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tin_ore.png b/client/src/main/resources/textures/blocks/tin_ore.png deleted file mode 100755 index b486c3d..0000000 Binary files a/client/src/main/resources/textures/blocks/tin_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/titanium_block.png b/client/src/main/resources/textures/blocks/titanium_block.png deleted file mode 100755 index ae94a63..0000000 Binary files a/client/src/main/resources/textures/blocks/titanium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/titanium_ore.png b/client/src/main/resources/textures/blocks/titanium_ore.png deleted file mode 100755 index 7b7a84e..0000000 Binary files a/client/src/main/resources/textures/blocks/titanium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom.png b/client/src/main/resources/textures/blocks/tnt_bottom.png deleted file mode 100755 index cc2e586..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_bottom.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_1.png b/client/src/main/resources/textures/blocks/tnt_bottom_1.png deleted file mode 100755 index 73b4902..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_bottom_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_2.png b/client/src/main/resources/textures/blocks/tnt_bottom_2.png deleted file mode 100755 index 6b21137..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_bottom_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_3.png b/client/src/main/resources/textures/blocks/tnt_bottom_3.png deleted file mode 100755 index 7760631..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_bottom_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_4.png b/client/src/main/resources/textures/blocks/tnt_bottom_4.png deleted file mode 100755 index c2f6753..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_bottom_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_5.png b/client/src/main/resources/textures/blocks/tnt_bottom_5.png deleted file mode 100755 index 6d28c6f..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_bottom_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_6.png b/client/src/main/resources/textures/blocks/tnt_bottom_6.png deleted file mode 100755 index bc8e98b..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_bottom_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_7.png b/client/src/main/resources/textures/blocks/tnt_bottom_7.png deleted file mode 100755 index 6a15f16..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_bottom_7.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_side.png b/client/src/main/resources/textures/blocks/tnt_side.png deleted file mode 100755 index 21109fb..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_1.png b/client/src/main/resources/textures/blocks/tnt_side_1.png deleted file mode 100755 index d5c8b46..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_side_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_2.png b/client/src/main/resources/textures/blocks/tnt_side_2.png deleted file mode 100755 index d4faa00..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_side_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_3.png b/client/src/main/resources/textures/blocks/tnt_side_3.png deleted file mode 100755 index 26ab9e7..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_side_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_4.png b/client/src/main/resources/textures/blocks/tnt_side_4.png deleted file mode 100755 index bff7a07..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_side_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_5.png b/client/src/main/resources/textures/blocks/tnt_side_5.png deleted file mode 100755 index 25d0cb4..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_side_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_6.png b/client/src/main/resources/textures/blocks/tnt_side_6.png deleted file mode 100755 index 63c727e..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_side_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_7.png b/client/src/main/resources/textures/blocks/tnt_side_7.png deleted file mode 100755 index 68bb687..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_side_7.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_top.png b/client/src/main/resources/textures/blocks/tnt_top.png deleted file mode 100755 index ceb44b6..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_1.png b/client/src/main/resources/textures/blocks/tnt_top_1.png deleted file mode 100755 index 32b478a..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_top_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_2.png b/client/src/main/resources/textures/blocks/tnt_top_2.png deleted file mode 100755 index 35f1973..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_top_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_3.png b/client/src/main/resources/textures/blocks/tnt_top_3.png deleted file mode 100755 index ceb38e6..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_top_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_4.png b/client/src/main/resources/textures/blocks/tnt_top_4.png deleted file mode 100755 index 5dffddb..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_top_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_5.png b/client/src/main/resources/textures/blocks/tnt_top_5.png deleted file mode 100755 index 0768549..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_top_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_6.png b/client/src/main/resources/textures/blocks/tnt_top_6.png deleted file mode 100755 index 85aa03d..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_top_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_7.png b/client/src/main/resources/textures/blocks/tnt_top_7.png deleted file mode 100755 index 17aad64..0000000 Binary files a/client/src/main/resources/textures/blocks/tnt_top_7.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/torch.png b/client/src/main/resources/textures/blocks/torch.png deleted file mode 100755 index a2ce41b..0000000 Binary files a/client/src/main/resources/textures/blocks/torch.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/trapdoor.png b/client/src/main/resources/textures/blocks/trapdoor.png deleted file mode 100755 index 4eadefc..0000000 Binary files a/client/src/main/resources/textures/blocks/trapdoor.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/trip_wire.png b/client/src/main/resources/textures/blocks/trip_wire.png deleted file mode 100755 index 42126b8..0000000 Binary files a/client/src/main/resources/textures/blocks/trip_wire.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tripwire_hook.png b/client/src/main/resources/textures/blocks/tripwire_hook.png deleted file mode 100755 index fbd464d..0000000 Binary files a/client/src/main/resources/textures/blocks/tripwire_hook.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tungsten_block.png b/client/src/main/resources/textures/blocks/tungsten_block.png deleted file mode 100755 index 6e3ff08..0000000 Binary files a/client/src/main/resources/textures/blocks/tungsten_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/tungsten_ore.png b/client/src/main/resources/textures/blocks/tungsten_ore.png deleted file mode 100755 index 662ad3f..0000000 Binary files a/client/src/main/resources/textures/blocks/tungsten_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/unlit_redstone_torch.png b/client/src/main/resources/textures/blocks/unlit_redstone_torch.png deleted file mode 100755 index 635eabd..0000000 Binary files a/client/src/main/resources/textures/blocks/unlit_redstone_torch.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/uranium_block.png b/client/src/main/resources/textures/blocks/uranium_block.png deleted file mode 100755 index 2101f95..0000000 Binary files a/client/src/main/resources/textures/blocks/uranium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/uranium_ore.png b/client/src/main/resources/textures/blocks/uranium_ore.png deleted file mode 100755 index 5930c47..0000000 Binary files a/client/src/main/resources/textures/blocks/uranium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/vanadium_block.png b/client/src/main/resources/textures/blocks/vanadium_block.png deleted file mode 100755 index 0b039e7..0000000 Binary files a/client/src/main/resources/textures/blocks/vanadium_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/vanadium_ore.png b/client/src/main/resources/textures/blocks/vanadium_ore.png deleted file mode 100755 index 82288f2..0000000 Binary files a/client/src/main/resources/textures/blocks/vanadium_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/vine.png b/client/src/main/resources/textures/blocks/vine.png deleted file mode 100755 index df5e435..0000000 Binary files a/client/src/main/resources/textures/blocks/vine.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/warp_chest_front.png b/client/src/main/resources/textures/blocks/warp_chest_front.png deleted file mode 100755 index d7ae02d..0000000 Binary files a/client/src/main/resources/textures/blocks/warp_chest_front.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/warp_chest_side.png b/client/src/main/resources/textures/blocks/warp_chest_side.png deleted file mode 100755 index 4b07cd4..0000000 Binary files a/client/src/main/resources/textures/blocks/warp_chest_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/warp_chest_top.png b/client/src/main/resources/textures/blocks/warp_chest_top.png deleted file mode 100755 index 5b12f22..0000000 Binary files a/client/src/main/resources/textures/blocks/warp_chest_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/waterlily.png b/client/src/main/resources/textures/blocks/waterlily.png deleted file mode 100755 index f6c84f8..0000000 Binary files a/client/src/main/resources/textures/blocks/waterlily.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/web.png b/client/src/main/resources/textures/blocks/web.png deleted file mode 100755 index 7c097f1..0000000 Binary files a/client/src/main/resources/textures/blocks/web.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/wheat_0.png b/client/src/main/resources/textures/blocks/wheat_0.png deleted file mode 100755 index 185af6f..0000000 Binary files a/client/src/main/resources/textures/blocks/wheat_0.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/wheat_1.png b/client/src/main/resources/textures/blocks/wheat_1.png deleted file mode 100755 index 67588c1..0000000 Binary files a/client/src/main/resources/textures/blocks/wheat_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/wheat_2.png b/client/src/main/resources/textures/blocks/wheat_2.png deleted file mode 100755 index 3d33792..0000000 Binary files a/client/src/main/resources/textures/blocks/wheat_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/wheat_3.png b/client/src/main/resources/textures/blocks/wheat_3.png deleted file mode 100755 index 4649f78..0000000 Binary files a/client/src/main/resources/textures/blocks/wheat_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/wheat_4.png b/client/src/main/resources/textures/blocks/wheat_4.png deleted file mode 100755 index ac04b52..0000000 Binary files a/client/src/main/resources/textures/blocks/wheat_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/wheat_5.png b/client/src/main/resources/textures/blocks/wheat_5.png deleted file mode 100755 index 1ea81ac..0000000 Binary files a/client/src/main/resources/textures/blocks/wheat_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/wheat_6.png b/client/src/main/resources/textures/blocks/wheat_6.png deleted file mode 100755 index cb5f195..0000000 Binary files a/client/src/main/resources/textures/blocks/wheat_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/wheat_7.png b/client/src/main/resources/textures/blocks/wheat_7.png deleted file mode 100755 index 7acafb3..0000000 Binary files a/client/src/main/resources/textures/blocks/wheat_7.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/white_bed_foot_end.png b/client/src/main/resources/textures/blocks/white_bed_foot_end.png deleted file mode 100755 index c6e8288..0000000 Binary files a/client/src/main/resources/textures/blocks/white_bed_foot_end.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/white_bed_foot_side.png b/client/src/main/resources/textures/blocks/white_bed_foot_side.png deleted file mode 100755 index 5ff5f6a..0000000 Binary files a/client/src/main/resources/textures/blocks/white_bed_foot_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/white_bed_foot_top.png b/client/src/main/resources/textures/blocks/white_bed_foot_top.png deleted file mode 100755 index dff0b58..0000000 Binary files a/client/src/main/resources/textures/blocks/white_bed_foot_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/white_bed_head_end.png b/client/src/main/resources/textures/blocks/white_bed_head_end.png deleted file mode 100755 index ea6e623..0000000 Binary files a/client/src/main/resources/textures/blocks/white_bed_head_end.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/white_bed_head_side.png b/client/src/main/resources/textures/blocks/white_bed_head_side.png deleted file mode 100755 index b70c1bb..0000000 Binary files a/client/src/main/resources/textures/blocks/white_bed_head_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/white_bed_head_top.png b/client/src/main/resources/textures/blocks/white_bed_head_top.png deleted file mode 100755 index 571ac4e..0000000 Binary files a/client/src/main/resources/textures/blocks/white_bed_head_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/white_glass.png b/client/src/main/resources/textures/blocks/white_glass.png deleted file mode 100755 index 696c5aa..0000000 Binary files a/client/src/main/resources/textures/blocks/white_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/white_glass_pane.png b/client/src/main/resources/textures/blocks/white_glass_pane.png deleted file mode 100755 index 9a273c3..0000000 Binary files a/client/src/main/resources/textures/blocks/white_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/white_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/white_stained_hardened_clay.png deleted file mode 100755 index 8066af0..0000000 Binary files a/client/src/main/resources/textures/blocks/white_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/white_tulip.png b/client/src/main/resources/textures/blocks/white_tulip.png deleted file mode 100755 index 6aa12a9..0000000 Binary files a/client/src/main/resources/textures/blocks/white_tulip.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/white_wool.png b/client/src/main/resources/textures/blocks/white_wool.png deleted file mode 100755 index abc7999..0000000 Binary files a/client/src/main/resources/textures/blocks/white_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/yellow_glass.png b/client/src/main/resources/textures/blocks/yellow_glass.png deleted file mode 100755 index 8e48e12..0000000 Binary files a/client/src/main/resources/textures/blocks/yellow_glass.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/yellow_glass_pane.png b/client/src/main/resources/textures/blocks/yellow_glass_pane.png deleted file mode 100755 index 1c8580f..0000000 Binary files a/client/src/main/resources/textures/blocks/yellow_glass_pane.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/yellow_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/yellow_stained_hardened_clay.png deleted file mode 100755 index 5da4687..0000000 Binary files a/client/src/main/resources/textures/blocks/yellow_stained_hardened_clay.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/yellow_wool.png b/client/src/main/resources/textures/blocks/yellow_wool.png deleted file mode 100755 index 4babaaa..0000000 Binary files a/client/src/main/resources/textures/blocks/yellow_wool.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/zinc_block.png b/client/src/main/resources/textures/blocks/zinc_block.png deleted file mode 100755 index 1d8b62c..0000000 Binary files a/client/src/main/resources/textures/blocks/zinc_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/blocks/zinc_ore.png b/client/src/main/resources/textures/blocks/zinc_ore.png deleted file mode 100755 index 1a696f3..0000000 Binary files a/client/src/main/resources/textures/blocks/zinc_ore.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/alucard_1.png b/client/src/main/resources/textures/entity/alucard_1.png deleted file mode 100755 index dc84802..0000000 Binary files a/client/src/main/resources/textures/entity/alucard_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/alucard_2.png b/client/src/main/resources/textures/entity/alucard_2.png deleted file mode 100755 index 5ba72ff..0000000 Binary files a/client/src/main/resources/textures/entity/alucard_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/arachnoid.png b/client/src/main/resources/textures/entity/arachnoid.png deleted file mode 100755 index ae9d939..0000000 Binary files a/client/src/main/resources/textures/entity/arachnoid.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/arrow.png b/client/src/main/resources/textures/entity/arrow.png deleted file mode 100755 index 3afa604..0000000 Binary files a/client/src/main/resources/textures/entity/arrow.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/bat.png b/client/src/main/resources/textures/entity/bat.png deleted file mode 100755 index 803860e..0000000 Binary files a/client/src/main/resources/textures/entity/bat.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/bloodelf.png b/client/src/main/resources/textures/entity/bloodelf.png deleted file mode 100755 index d84ab98..0000000 Binary files a/client/src/main/resources/textures/entity/bloodelf.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/boat.png b/client/src/main/resources/textures/entity/boat.png deleted file mode 100755 index 9b58965..0000000 Binary files a/client/src/main/resources/textures/entity/boat.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/box.png b/client/src/main/resources/textures/entity/box.png deleted file mode 100755 index 707a8cd..0000000 Binary files a/client/src/main/resources/textures/entity/box.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/box_brittle.png b/client/src/main/resources/textures/entity/box_brittle.png deleted file mode 100755 index 806cedb..0000000 Binary files a/client/src/main/resources/textures/entity/box_brittle.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/bullet.png b/client/src/main/resources/textures/entity/bullet.png deleted file mode 100755 index fe61c93..0000000 Binary files a/client/src/main/resources/textures/entity/bullet.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/cape_bloodelf.png b/client/src/main/resources/textures/entity/cape_bloodelf.png deleted file mode 100755 index 69d039d..0000000 Binary files a/client/src/main/resources/textures/entity/cape_bloodelf.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/cat_black.png b/client/src/main/resources/textures/entity/cat_black.png deleted file mode 100755 index 422908f..0000000 Binary files a/client/src/main/resources/textures/entity/cat_black.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/cat_ocelot.png b/client/src/main/resources/textures/entity/cat_ocelot.png deleted file mode 100755 index 6b5064e..0000000 Binary files a/client/src/main/resources/textures/entity/cat_ocelot.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/cat_red.png b/client/src/main/resources/textures/entity/cat_red.png deleted file mode 100755 index 17b6de5..0000000 Binary files a/client/src/main/resources/textures/entity/cat_red.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/cat_siamese.png b/client/src/main/resources/textures/entity/cat_siamese.png deleted file mode 100755 index cfed948..0000000 Binary files a/client/src/main/resources/textures/entity/cat_siamese.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/char.png b/client/src/main/resources/textures/entity/char.png deleted file mode 100755 index 54aa400..0000000 Binary files a/client/src/main/resources/textures/entity/char.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/charge.png b/client/src/main/resources/textures/entity/charge.png deleted file mode 100755 index 119f6ff..0000000 Binary files a/client/src/main/resources/textures/entity/charge.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/chicken.png b/client/src/main/resources/textures/entity/chicken.png deleted file mode 100755 index e24d550..0000000 Binary files a/client/src/main/resources/textures/entity/chicken.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/cow.png b/client/src/main/resources/textures/entity/cow.png deleted file mode 100755 index f1320c3..0000000 Binary files a/client/src/main/resources/textures/entity/cow.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/crystal.png b/client/src/main/resources/textures/entity/crystal.png deleted file mode 100755 index 94ad169..0000000 Binary files a/client/src/main/resources/textures/entity/crystal.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/crystal_beam.png b/client/src/main/resources/textures/entity/crystal_beam.png deleted file mode 100755 index 1259a5d..0000000 Binary files a/client/src/main/resources/textures/entity/crystal_beam.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/darkmage.png b/client/src/main/resources/textures/entity/darkmage.png deleted file mode 100755 index 7b9c894..0000000 Binary files a/client/src/main/resources/textures/entity/darkmage.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/donkey.png b/client/src/main/resources/textures/entity/donkey.png deleted file mode 100755 index b94bc63..0000000 Binary files a/client/src/main/resources/textures/entity/donkey.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/dracula_1.png b/client/src/main/resources/textures/entity/dracula_1.png deleted file mode 100755 index 873e000..0000000 Binary files a/client/src/main/resources/textures/entity/dracula_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/dracula_2.png b/client/src/main/resources/textures/entity/dracula_2.png deleted file mode 100755 index 186359f..0000000 Binary files a/client/src/main/resources/textures/entity/dracula_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/dracula_3.png b/client/src/main/resources/textures/entity/dracula_3.png deleted file mode 100755 index 26f2892..0000000 Binary files a/client/src/main/resources/textures/entity/dracula_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/dracula_4.png b/client/src/main/resources/textures/entity/dracula_4.png deleted file mode 100755 index 41a1b6f..0000000 Binary files a/client/src/main/resources/textures/entity/dracula_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/dracula_5.png b/client/src/main/resources/textures/entity/dracula_5.png deleted file mode 100755 index 0e127de..0000000 Binary files a/client/src/main/resources/textures/entity/dracula_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/dracula_6.png b/client/src/main/resources/textures/entity/dracula_6.png deleted file mode 100755 index a57b625..0000000 Binary files a/client/src/main/resources/textures/entity/dracula_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/dragon.png b/client/src/main/resources/textures/entity/dragon.png deleted file mode 100755 index b8a680c..0000000 Binary files a/client/src/main/resources/textures/entity/dragon.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/dragon_eyes.png b/client/src/main/resources/textures/entity/dragon_eyes.png deleted file mode 100755 index 147b303..0000000 Binary files a/client/src/main/resources/textures/entity/dragon_eyes.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/dwarf.png b/client/src/main/resources/textures/entity/dwarf.png deleted file mode 100755 index e72cf1a..0000000 Binary files a/client/src/main/resources/textures/entity/dwarf.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/experience_orb.png b/client/src/main/resources/textures/entity/experience_orb.png deleted file mode 100755 index 92f9d0f..0000000 Binary files a/client/src/main/resources/textures/entity/experience_orb.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/explosion.png b/client/src/main/resources/textures/entity/explosion.png deleted file mode 100755 index c309409..0000000 Binary files a/client/src/main/resources/textures/entity/explosion.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/firedemon.png b/client/src/main/resources/textures/entity/firedemon.png deleted file mode 100755 index a4d86f6..0000000 Binary files a/client/src/main/resources/textures/entity/firedemon.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/fox.png b/client/src/main/resources/textures/entity/fox.png deleted file mode 100755 index 61ee1a8..0000000 Binary files a/client/src/main/resources/textures/entity/fox.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/gargoyle.png b/client/src/main/resources/textures/entity/gargoyle.png deleted file mode 100755 index 069000e..0000000 Binary files a/client/src/main/resources/textures/entity/gargoyle.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/goblin.png b/client/src/main/resources/textures/entity/goblin.png deleted file mode 100755 index 6ea2805..0000000 Binary files a/client/src/main/resources/textures/entity/goblin.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/hacker.png b/client/src/main/resources/textures/entity/hacker.png deleted file mode 100755 index 34beb80..0000000 Binary files a/client/src/main/resources/textures/entity/hacker.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/haunter.png b/client/src/main/resources/textures/entity/haunter.png deleted file mode 100755 index 4b2696b..0000000 Binary files a/client/src/main/resources/textures/entity/haunter.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/herobrine.png b/client/src/main/resources/textures/entity/herobrine.png deleted file mode 100755 index f2934fa..0000000 Binary files a/client/src/main/resources/textures/entity/herobrine.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/highelf.png b/client/src/main/resources/textures/entity/highelf.png deleted file mode 100755 index cc90ae2..0000000 Binary files a/client/src/main/resources/textures/entity/highelf.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_black.png b/client/src/main/resources/textures/entity/horse_black.png deleted file mode 100755 index dde716e..0000000 Binary files a/client/src/main/resources/textures/entity/horse_black.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_brown.png b/client/src/main/resources/textures/entity/horse_brown.png deleted file mode 100755 index ec0158f..0000000 Binary files a/client/src/main/resources/textures/entity/horse_brown.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_chestnut.png b/client/src/main/resources/textures/entity/horse_chestnut.png deleted file mode 100755 index 40322ff..0000000 Binary files a/client/src/main/resources/textures/entity/horse_chestnut.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_creamy.png b/client/src/main/resources/textures/entity/horse_creamy.png deleted file mode 100755 index bc42bcc..0000000 Binary files a/client/src/main/resources/textures/entity/horse_creamy.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_darkbrown.png b/client/src/main/resources/textures/entity/horse_darkbrown.png deleted file mode 100755 index b38e914..0000000 Binary files a/client/src/main/resources/textures/entity/horse_darkbrown.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_gray.png b/client/src/main/resources/textures/entity/horse_gray.png deleted file mode 100755 index 4987532..0000000 Binary files a/client/src/main/resources/textures/entity/horse_gray.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_markings_blackdots.png b/client/src/main/resources/textures/entity/horse_markings_blackdots.png deleted file mode 100755 index 7320648..0000000 Binary files a/client/src/main/resources/textures/entity/horse_markings_blackdots.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_markings_white.png b/client/src/main/resources/textures/entity/horse_markings_white.png deleted file mode 100755 index b1f0a69..0000000 Binary files a/client/src/main/resources/textures/entity/horse_markings_white.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_markings_whitedots.png b/client/src/main/resources/textures/entity/horse_markings_whitedots.png deleted file mode 100755 index 20e1954..0000000 Binary files a/client/src/main/resources/textures/entity/horse_markings_whitedots.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_markings_whitefield.png b/client/src/main/resources/textures/entity/horse_markings_whitefield.png deleted file mode 100755 index baa2c06..0000000 Binary files a/client/src/main/resources/textures/entity/horse_markings_whitefield.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_skeleton.png b/client/src/main/resources/textures/entity/horse_skeleton.png deleted file mode 100755 index 29d4ed5..0000000 Binary files a/client/src/main/resources/textures/entity/horse_skeleton.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_white.png b/client/src/main/resources/textures/entity/horse_white.png deleted file mode 100755 index e90e6e7..0000000 Binary files a/client/src/main/resources/textures/entity/horse_white.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/horse_zombie.png b/client/src/main/resources/textures/entity/horse_zombie.png deleted file mode 100755 index 22d55fa..0000000 Binary files a/client/src/main/resources/textures/entity/horse_zombie.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/jiang_cheng.png b/client/src/main/resources/textures/entity/jiang_cheng.png deleted file mode 100755 index 77f3dbe..0000000 Binary files a/client/src/main/resources/textures/entity/jiang_cheng.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/knight_1.png b/client/src/main/resources/textures/entity/knight_1.png deleted file mode 100755 index 95e88b5..0000000 Binary files a/client/src/main/resources/textures/entity/knight_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/knight_2.png b/client/src/main/resources/textures/entity/knight_2.png deleted file mode 100755 index 6f40960..0000000 Binary files a/client/src/main/resources/textures/entity/knight_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/knight_3.png b/client/src/main/resources/textures/entity/knight_3.png deleted file mode 100755 index 75aecd4..0000000 Binary files a/client/src/main/resources/textures/entity/knight_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/knight_4.png b/client/src/main/resources/textures/entity/knight_4.png deleted file mode 100755 index 4628a9e..0000000 Binary files a/client/src/main/resources/textures/entity/knight_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/knight_5.png b/client/src/main/resources/textures/entity/knight_5.png deleted file mode 100755 index 2594ebb..0000000 Binary files a/client/src/main/resources/textures/entity/knight_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/knight_6.png b/client/src/main/resources/textures/entity/knight_6.png deleted file mode 100755 index 56a2faf..0000000 Binary files a/client/src/main/resources/textures/entity/knight_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/knight_7.png b/client/src/main/resources/textures/entity/knight_7.png deleted file mode 100755 index 31d5612..0000000 Binary files a/client/src/main/resources/textures/entity/knight_7.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/knight_8.png b/client/src/main/resources/textures/entity/knight_8.png deleted file mode 100755 index 9920477..0000000 Binary files a/client/src/main/resources/textures/entity/knight_8.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/lan_wangji.png b/client/src/main/resources/textures/entity/lan_wangji.png deleted file mode 100755 index d950a26..0000000 Binary files a/client/src/main/resources/textures/entity/lan_wangji.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/lead_knot.png b/client/src/main/resources/textures/entity/lead_knot.png deleted file mode 100755 index ab4d3b3..0000000 Binary files a/client/src/main/resources/textures/entity/lead_knot.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/luo_binghe.png b/client/src/main/resources/textures/entity/luo_binghe.png deleted file mode 100755 index ac18863..0000000 Binary files a/client/src/main/resources/textures/entity/luo_binghe.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/mage_1.png b/client/src/main/resources/textures/entity/mage_1.png deleted file mode 100755 index bfd2698..0000000 Binary files a/client/src/main/resources/textures/entity/mage_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/mage_2.png b/client/src/main/resources/textures/entity/mage_2.png deleted file mode 100755 index 3540f15..0000000 Binary files a/client/src/main/resources/textures/entity/mage_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/mage_3.png b/client/src/main/resources/textures/entity/mage_3.png deleted file mode 100755 index b7ea9ad..0000000 Binary files a/client/src/main/resources/textures/entity/mage_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/mage_4.png b/client/src/main/resources/textures/entity/mage_4.png deleted file mode 100755 index b4f997a..0000000 Binary files a/client/src/main/resources/textures/entity/mage_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/mage_5.png b/client/src/main/resources/textures/entity/mage_5.png deleted file mode 100755 index 12111f7..0000000 Binary files a/client/src/main/resources/textures/entity/mage_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/mage_6.png b/client/src/main/resources/textures/entity/mage_6.png deleted file mode 100755 index b84d670..0000000 Binary files a/client/src/main/resources/textures/entity/mage_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/magma.png b/client/src/main/resources/textures/entity/magma.png deleted file mode 100755 index 20f0dd6..0000000 Binary files a/client/src/main/resources/textures/entity/magma.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/marine.png b/client/src/main/resources/textures/entity/marine.png deleted file mode 100755 index 29a53f3..0000000 Binary files a/client/src/main/resources/textures/entity/marine.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/marine_black_templar.png b/client/src/main/resources/textures/entity/marine_black_templar.png deleted file mode 100755 index 1d2392c..0000000 Binary files a/client/src/main/resources/textures/entity/marine_black_templar.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead.png b/client/src/main/resources/textures/entity/metalhead.png deleted file mode 100755 index dd94a82..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_1.png b/client/src/main/resources/textures/entity/metalhead_1.png deleted file mode 100755 index f015fb5..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_10.png b/client/src/main/resources/textures/entity/metalhead_10.png deleted file mode 100755 index db8f206..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_10.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_11.png b/client/src/main/resources/textures/entity/metalhead_11.png deleted file mode 100755 index 05e9c9e..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_11.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_12.png b/client/src/main/resources/textures/entity/metalhead_12.png deleted file mode 100755 index c9ff664..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_12.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_13.png b/client/src/main/resources/textures/entity/metalhead_13.png deleted file mode 100755 index 3694463..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_13.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_14.png b/client/src/main/resources/textures/entity/metalhead_14.png deleted file mode 100755 index aae134a..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_14.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_2.png b/client/src/main/resources/textures/entity/metalhead_2.png deleted file mode 100755 index eb1078c..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_3.png b/client/src/main/resources/textures/entity/metalhead_3.png deleted file mode 100755 index 1426644..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_4.png b/client/src/main/resources/textures/entity/metalhead_4.png deleted file mode 100755 index dadacd3..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_5.png b/client/src/main/resources/textures/entity/metalhead_5.png deleted file mode 100755 index b3149ae..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_6.png b/client/src/main/resources/textures/entity/metalhead_6.png deleted file mode 100755 index 177f4d8..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_7.png b/client/src/main/resources/textures/entity/metalhead_7.png deleted file mode 100755 index 422a5a4..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_7.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_8.png b/client/src/main/resources/textures/entity/metalhead_8.png deleted file mode 100755 index f54ef56..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_8.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/metalhead_9.png b/client/src/main/resources/textures/entity/metalhead_9.png deleted file mode 100755 index 363da10..0000000 Binary files a/client/src/main/resources/textures/entity/metalhead_9.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/minecart.png b/client/src/main/resources/textures/entity/minecart.png deleted file mode 100755 index 7ad7b54..0000000 Binary files a/client/src/main/resources/textures/entity/minecart.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/mooshroom.png b/client/src/main/resources/textures/entity/mooshroom.png deleted file mode 100755 index 3d68286..0000000 Binary files a/client/src/main/resources/textures/entity/mooshroom.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/mouse.png b/client/src/main/resources/textures/entity/mouse.png deleted file mode 100755 index f916857..0000000 Binary files a/client/src/main/resources/textures/entity/mouse.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/mule.png b/client/src/main/resources/textures/entity/mule.png deleted file mode 100755 index 241bdaa..0000000 Binary files a/client/src/main/resources/textures/entity/mule.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_1.png b/client/src/main/resources/textures/entity/orc_1.png deleted file mode 100755 index 5dcd58f..0000000 Binary files a/client/src/main/resources/textures/entity/orc_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_10.png b/client/src/main/resources/textures/entity/orc_10.png deleted file mode 100755 index 688d918..0000000 Binary files a/client/src/main/resources/textures/entity/orc_10.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_11.png b/client/src/main/resources/textures/entity/orc_11.png deleted file mode 100755 index e5f1651..0000000 Binary files a/client/src/main/resources/textures/entity/orc_11.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_12.png b/client/src/main/resources/textures/entity/orc_12.png deleted file mode 100755 index 8fb304e..0000000 Binary files a/client/src/main/resources/textures/entity/orc_12.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_2.png b/client/src/main/resources/textures/entity/orc_2.png deleted file mode 100755 index bdfa7eb..0000000 Binary files a/client/src/main/resources/textures/entity/orc_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_3.png b/client/src/main/resources/textures/entity/orc_3.png deleted file mode 100755 index 4f1e74d..0000000 Binary files a/client/src/main/resources/textures/entity/orc_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_4.png b/client/src/main/resources/textures/entity/orc_4.png deleted file mode 100755 index c21e646..0000000 Binary files a/client/src/main/resources/textures/entity/orc_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_5.png b/client/src/main/resources/textures/entity/orc_5.png deleted file mode 100755 index 016a69c..0000000 Binary files a/client/src/main/resources/textures/entity/orc_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_6.png b/client/src/main/resources/textures/entity/orc_6.png deleted file mode 100755 index e1564fc..0000000 Binary files a/client/src/main/resources/textures/entity/orc_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_7.png b/client/src/main/resources/textures/entity/orc_7.png deleted file mode 100755 index 3812f0f..0000000 Binary files a/client/src/main/resources/textures/entity/orc_7.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_8.png b/client/src/main/resources/textures/entity/orc_8.png deleted file mode 100755 index 969fc54..0000000 Binary files a/client/src/main/resources/textures/entity/orc_8.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/orc_9.png b/client/src/main/resources/textures/entity/orc_9.png deleted file mode 100755 index 305bfef..0000000 Binary files a/client/src/main/resources/textures/entity/orc_9.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/peasant_1.png b/client/src/main/resources/textures/entity/peasant_1.png deleted file mode 100755 index e5bd7ae..0000000 Binary files a/client/src/main/resources/textures/entity/peasant_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/peasant_2.png b/client/src/main/resources/textures/entity/peasant_2.png deleted file mode 100755 index d7ad244..0000000 Binary files a/client/src/main/resources/textures/entity/peasant_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/peasant_3.png b/client/src/main/resources/textures/entity/peasant_3.png deleted file mode 100755 index 5896c0b..0000000 Binary files a/client/src/main/resources/textures/entity/peasant_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/peasant_4.png b/client/src/main/resources/textures/entity/peasant_4.png deleted file mode 100755 index 5d0510b..0000000 Binary files a/client/src/main/resources/textures/entity/peasant_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/peasant_5.png b/client/src/main/resources/textures/entity/peasant_5.png deleted file mode 100755 index ff8a65c..0000000 Binary files a/client/src/main/resources/textures/entity/peasant_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/peasant_6.png b/client/src/main/resources/textures/entity/peasant_6.png deleted file mode 100755 index 9d482e0..0000000 Binary files a/client/src/main/resources/textures/entity/peasant_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/pig.png b/client/src/main/resources/textures/entity/pig.png deleted file mode 100755 index 0a9532f..0000000 Binary files a/client/src/main/resources/textures/entity/pig.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/pig_saddle.png b/client/src/main/resources/textures/entity/pig_saddle.png deleted file mode 100755 index 640ea76..0000000 Binary files a/client/src/main/resources/textures/entity/pig_saddle.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/power_rod.png b/client/src/main/resources/textures/entity/power_rod.png deleted file mode 100755 index ef61249..0000000 Binary files a/client/src/main/resources/textures/entity/power_rod.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_black.png b/client/src/main/resources/textures/entity/rabbit_black.png deleted file mode 100755 index 1203cb9..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_black.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_black_splotched.png b/client/src/main/resources/textures/entity/rabbit_black_splotched.png deleted file mode 100755 index d5e626b..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_black_splotched.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_brown.png b/client/src/main/resources/textures/entity/rabbit_brown.png deleted file mode 100755 index ffa0870..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_brown.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_caerbannog.png b/client/src/main/resources/textures/entity/rabbit_caerbannog.png deleted file mode 100755 index 778bfc7..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_caerbannog.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_dark.png b/client/src/main/resources/textures/entity/rabbit_dark.png deleted file mode 100755 index e97f4d8..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_dark.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_dark_gray.png b/client/src/main/resources/textures/entity/rabbit_dark_gray.png deleted file mode 100755 index d0524f4..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_dark_gray.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_gold.png b/client/src/main/resources/textures/entity/rabbit_gold.png deleted file mode 100755 index 595e6f7..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_gold.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_gray.png b/client/src/main/resources/textures/entity/rabbit_gray.png deleted file mode 100755 index 66ee205..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_gray.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_salt.png b/client/src/main/resources/textures/entity/rabbit_salt.png deleted file mode 100755 index 2232ef0..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_salt.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_toast.png b/client/src/main/resources/textures/entity/rabbit_toast.png deleted file mode 100755 index b1bb70d..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_toast.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_white.png b/client/src/main/resources/textures/entity/rabbit_white.png deleted file mode 100755 index bb6cd9e..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_white.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/rabbit_white_splotched.png b/client/src/main/resources/textures/entity/rabbit_white_splotched.png deleted file mode 100755 index 196ac00..0000000 Binary files a/client/src/main/resources/textures/entity/rabbit_white_splotched.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/sen.png b/client/src/main/resources/textures/entity/sen.png deleted file mode 100755 index df769e3..0000000 Binary files a/client/src/main/resources/textures/entity/sen.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/sheep.png b/client/src/main/resources/textures/entity/sheep.png deleted file mode 100755 index d9fe93f..0000000 Binary files a/client/src/main/resources/textures/entity/sheep.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/sheep_fur.png b/client/src/main/resources/textures/entity/sheep_fur.png deleted file mode 100755 index 623340b..0000000 Binary files a/client/src/main/resources/textures/entity/sheep_fur.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/shen_qingqiu.png b/client/src/main/resources/textures/entity/shen_qingqiu.png deleted file mode 100755 index 298ed46..0000000 Binary files a/client/src/main/resources/textures/entity/shen_qingqiu.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/skull.png b/client/src/main/resources/textures/entity/skull.png deleted file mode 100755 index 98b76c7..0000000 Binary files a/client/src/main/resources/textures/entity/skull.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/slime.png b/client/src/main/resources/textures/entity/slime.png deleted file mode 100755 index 96edcf6..0000000 Binary files a/client/src/main/resources/textures/entity/slime.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/spirit.png b/client/src/main/resources/textures/entity/spirit.png deleted file mode 100755 index f50ba0a..0000000 Binary files a/client/src/main/resources/textures/entity/spirit.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/squid.png b/client/src/main/resources/textures/entity/squid.png deleted file mode 100755 index f285388..0000000 Binary files a/client/src/main/resources/textures/entity/squid.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/thranduil.png b/client/src/main/resources/textures/entity/thranduil.png deleted file mode 100755 index cbf1a9c..0000000 Binary files a/client/src/main/resources/textures/entity/thranduil.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/tiefling.png b/client/src/main/resources/textures/entity/tiefling.png deleted file mode 100755 index 85eddec..0000000 Binary files a/client/src/main/resources/textures/entity/tiefling.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/trollface.png b/client/src/main/resources/textures/entity/trollface.png deleted file mode 100755 index dd8da12..0000000 Binary files a/client/src/main/resources/textures/entity/trollface.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/undead_1.png b/client/src/main/resources/textures/entity/undead_1.png deleted file mode 100755 index 68de7d5..0000000 Binary files a/client/src/main/resources/textures/entity/undead_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/undead_2.png b/client/src/main/resources/textures/entity/undead_2.png deleted file mode 100755 index a99da35..0000000 Binary files a/client/src/main/resources/textures/entity/undead_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/undead_3.png b/client/src/main/resources/textures/entity/undead_3.png deleted file mode 100755 index a841c5d..0000000 Binary files a/client/src/main/resources/textures/entity/undead_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/undead_4.png b/client/src/main/resources/textures/entity/undead_4.png deleted file mode 100755 index 69dc132..0000000 Binary files a/client/src/main/resources/textures/entity/undead_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/unknown.png b/client/src/main/resources/textures/entity/unknown.png deleted file mode 100755 index a2b5aad..0000000 Binary files a/client/src/main/resources/textures/entity/unknown.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/vampire_1.png b/client/src/main/resources/textures/entity/vampire_1.png deleted file mode 100755 index db3537e..0000000 Binary files a/client/src/main/resources/textures/entity/vampire_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/vampire_2.png b/client/src/main/resources/textures/entity/vampire_2.png deleted file mode 100755 index 86ef231..0000000 Binary files a/client/src/main/resources/textures/entity/vampire_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/vampire_3.png b/client/src/main/resources/textures/entity/vampire_3.png deleted file mode 100755 index b2b20df..0000000 Binary files a/client/src/main/resources/textures/entity/vampire_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/vampire_4.png b/client/src/main/resources/textures/entity/vampire_4.png deleted file mode 100755 index bee7d07..0000000 Binary files a/client/src/main/resources/textures/entity/vampire_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/vampire_5.png b/client/src/main/resources/textures/entity/vampire_5.png deleted file mode 100755 index f6e1e30..0000000 Binary files a/client/src/main/resources/textures/entity/vampire_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/vampire_6.png b/client/src/main/resources/textures/entity/vampire_6.png deleted file mode 100755 index 91c15a7..0000000 Binary files a/client/src/main/resources/textures/entity/vampire_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/vampire_7.png b/client/src/main/resources/textures/entity/vampire_7.png deleted file mode 100755 index ba901a9..0000000 Binary files a/client/src/main/resources/textures/entity/vampire_7.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/vampire_8.png b/client/src/main/resources/textures/entity/vampire_8.png deleted file mode 100755 index e4023cb..0000000 Binary files a/client/src/main/resources/textures/entity/vampire_8.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/wei_wuxian.png b/client/src/main/resources/textures/entity/wei_wuxian.png deleted file mode 100755 index 763fe53..0000000 Binary files a/client/src/main/resources/textures/entity/wei_wuxian.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/wolf.png b/client/src/main/resources/textures/entity/wolf.png deleted file mode 100755 index f37ef81..0000000 Binary files a/client/src/main/resources/textures/entity/wolf.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/wolf_angry.png b/client/src/main/resources/textures/entity/wolf_angry.png deleted file mode 100755 index 7891ce9..0000000 Binary files a/client/src/main/resources/textures/entity/wolf_angry.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/wolf_collar.png b/client/src/main/resources/textures/entity/wolf_collar.png deleted file mode 100755 index ae1c920..0000000 Binary files a/client/src/main/resources/textures/entity/wolf_collar.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/wolf_tame.png b/client/src/main/resources/textures/entity/wolf_tame.png deleted file mode 100755 index f1236d2..0000000 Binary files a/client/src/main/resources/textures/entity/wolf_tame.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/woodelf.png b/client/src/main/resources/textures/entity/woodelf.png deleted file mode 100755 index 38f1f64..0000000 Binary files a/client/src/main/resources/textures/entity/woodelf.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/zombie_1.png b/client/src/main/resources/textures/entity/zombie_1.png deleted file mode 100755 index f1624f8..0000000 Binary files a/client/src/main/resources/textures/entity/zombie_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/zombie_2.png b/client/src/main/resources/textures/entity/zombie_2.png deleted file mode 100755 index 2560175..0000000 Binary files a/client/src/main/resources/textures/entity/zombie_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/zombie_3.png b/client/src/main/resources/textures/entity/zombie_3.png deleted file mode 100755 index 88f490f..0000000 Binary files a/client/src/main/resources/textures/entity/zombie_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/zombie_4.png b/client/src/main/resources/textures/entity/zombie_4.png deleted file mode 100755 index e2572ca..0000000 Binary files a/client/src/main/resources/textures/entity/zombie_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/zombie_5.png b/client/src/main/resources/textures/entity/zombie_5.png deleted file mode 100755 index 3e61dc0..0000000 Binary files a/client/src/main/resources/textures/entity/zombie_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/entity/zombie_6.png b/client/src/main/resources/textures/entity/zombie_6.png deleted file mode 100755 index 65d110d..0000000 Binary files a/client/src/main/resources/textures/entity/zombie_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/font.png b/client/src/main/resources/textures/font.png deleted file mode 100644 index a100b48..0000000 Binary files a/client/src/main/resources/textures/font.png and /dev/null differ diff --git a/client/src/main/resources/textures/font_tiny.png b/client/src/main/resources/textures/font_tiny.png deleted file mode 100644 index 3d1c6d9..0000000 Binary files a/client/src/main/resources/textures/font_tiny.png and /dev/null differ diff --git a/client/src/main/resources/textures/glint.png b/client/src/main/resources/textures/glint.png deleted file mode 100755 index f9ca97c..0000000 Binary files a/client/src/main/resources/textures/glint.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/acacia_door.png b/client/src/main/resources/textures/items/acacia_door.png deleted file mode 100755 index c903484..0000000 Binary files a/client/src/main/resources/textures/items/acacia_door.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/acid_bucket.png b/client/src/main/resources/textures/items/acid_bucket.png deleted file mode 100755 index b193778..0000000 Binary files a/client/src/main/resources/textures/items/acid_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/ahrd_fragment.png b/client/src/main/resources/textures/items/ahrd_fragment.png deleted file mode 100755 index ae6872c..0000000 Binary files a/client/src/main/resources/textures/items/ahrd_fragment.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/aluminium_ingot.png b/client/src/main/resources/textures/items/aluminium_ingot.png deleted file mode 100755 index 00918f1..0000000 Binary files a/client/src/main/resources/textures/items/aluminium_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/antimony_powder.png b/client/src/main/resources/textures/items/antimony_powder.png deleted file mode 100755 index 1e789ab..0000000 Binary files a/client/src/main/resources/textures/items/antimony_powder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/apple.png b/client/src/main/resources/textures/items/apple.png deleted file mode 100755 index 6f908bb..0000000 Binary files a/client/src/main/resources/textures/items/apple.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/ardite_boots.png b/client/src/main/resources/textures/items/ardite_boots.png deleted file mode 100755 index 9ec9196..0000000 Binary files a/client/src/main/resources/textures/items/ardite_boots.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/ardite_chestplate.png b/client/src/main/resources/textures/items/ardite_chestplate.png deleted file mode 100755 index 6c19842..0000000 Binary files a/client/src/main/resources/textures/items/ardite_chestplate.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/ardite_helmet.png b/client/src/main/resources/textures/items/ardite_helmet.png deleted file mode 100755 index c74ed53..0000000 Binary files a/client/src/main/resources/textures/items/ardite_helmet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/ardite_leggings.png b/client/src/main/resources/textures/items/ardite_leggings.png deleted file mode 100755 index b531357..0000000 Binary files a/client/src/main/resources/textures/items/ardite_leggings.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/ardite_sword.png b/client/src/main/resources/textures/items/ardite_sword.png deleted file mode 100755 index f806379..0000000 Binary files a/client/src/main/resources/textures/items/ardite_sword.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/arrow.png b/client/src/main/resources/textures/items/arrow.png deleted file mode 100755 index 4f748a0..0000000 Binary files a/client/src/main/resources/textures/items/arrow.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/arsenic_powder.png b/client/src/main/resources/textures/items/arsenic_powder.png deleted file mode 100755 index 670d1ac..0000000 Binary files a/client/src/main/resources/textures/items/arsenic_powder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/baked_potato.png b/client/src/main/resources/textures/items/baked_potato.png deleted file mode 100755 index e4d765b..0000000 Binary files a/client/src/main/resources/textures/items/baked_potato.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/banhammer.png b/client/src/main/resources/textures/items/banhammer.png deleted file mode 100755 index 674391b..0000000 Binary files a/client/src/main/resources/textures/items/banhammer.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/beef.png b/client/src/main/resources/textures/items/beef.png deleted file mode 100755 index c9ab891..0000000 Binary files a/client/src/main/resources/textures/items/beef.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/birch_door.png b/client/src/main/resources/textures/items/birch_door.png deleted file mode 100755 index 7c88c41..0000000 Binary files a/client/src/main/resources/textures/items/birch_door.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/bismuth_ingot.png b/client/src/main/resources/textures/items/bismuth_ingot.png deleted file mode 100755 index f2db74b..0000000 Binary files a/client/src/main/resources/textures/items/bismuth_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/black_bed.png b/client/src/main/resources/textures/items/black_bed.png deleted file mode 100755 index b1dea4b..0000000 Binary files a/client/src/main/resources/textures/items/black_bed.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/black_metal_ingot.png b/client/src/main/resources/textures/items/black_metal_ingot.png deleted file mode 100755 index ecd0a75..0000000 Binary files a/client/src/main/resources/textures/items/black_metal_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/black_quartz.png b/client/src/main/resources/textures/items/black_quartz.png deleted file mode 100755 index 67a0ec8..0000000 Binary files a/client/src/main/resources/textures/items/black_quartz.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/blackbrick.png b/client/src/main/resources/textures/items/blackbrick.png deleted file mode 100755 index 63839ad..0000000 Binary files a/client/src/main/resources/textures/items/blackbrick.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/blackwood_door.png b/client/src/main/resources/textures/items/blackwood_door.png deleted file mode 100755 index 7f44747..0000000 Binary files a/client/src/main/resources/textures/items/blackwood_door.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/blaze_powder.png b/client/src/main/resources/textures/items/blaze_powder.png deleted file mode 100755 index 89c57d6..0000000 Binary files a/client/src/main/resources/textures/items/blaze_powder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/blaze_rod.png b/client/src/main/resources/textures/items/blaze_rod.png deleted file mode 100755 index 7050e10..0000000 Binary files a/client/src/main/resources/textures/items/blaze_rod.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/blood_bucket.png b/client/src/main/resources/textures/items/blood_bucket.png deleted file mode 100755 index 793c5bc..0000000 Binary files a/client/src/main/resources/textures/items/blood_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/bloodbrick.png b/client/src/main/resources/textures/items/bloodbrick.png deleted file mode 100755 index e9c14ed..0000000 Binary files a/client/src/main/resources/textures/items/bloodbrick.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/boat.png b/client/src/main/resources/textures/items/boat.png deleted file mode 100755 index 235e0a2..0000000 Binary files a/client/src/main/resources/textures/items/boat.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/bolt.png b/client/src/main/resources/textures/items/bolt.png deleted file mode 100755 index 665dcf2..0000000 Binary files a/client/src/main/resources/textures/items/bolt.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/boltgun.png b/client/src/main/resources/textures/items/boltgun.png deleted file mode 100755 index 096094a..0000000 Binary files a/client/src/main/resources/textures/items/boltgun.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/bone.png b/client/src/main/resources/textures/items/bone.png deleted file mode 100755 index 3faca89..0000000 Binary files a/client/src/main/resources/textures/items/bone.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/book.png b/client/src/main/resources/textures/items/book.png deleted file mode 100755 index f791ae4..0000000 Binary files a/client/src/main/resources/textures/items/book.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/bow.png b/client/src/main/resources/textures/items/bow.png deleted file mode 100755 index d709b9c..0000000 Binary files a/client/src/main/resources/textures/items/bow.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/bow_pulling_0.png b/client/src/main/resources/textures/items/bow_pulling_0.png deleted file mode 100755 index 2022aab..0000000 Binary files a/client/src/main/resources/textures/items/bow_pulling_0.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/bow_pulling_1.png b/client/src/main/resources/textures/items/bow_pulling_1.png deleted file mode 100755 index a132079..0000000 Binary files a/client/src/main/resources/textures/items/bow_pulling_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/bow_pulling_2.png b/client/src/main/resources/textures/items/bow_pulling_2.png deleted file mode 100755 index d459e68..0000000 Binary files a/client/src/main/resources/textures/items/bow_pulling_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/bowl.png b/client/src/main/resources/textures/items/bowl.png deleted file mode 100755 index 63d16ad..0000000 Binary files a/client/src/main/resources/textures/items/bowl.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/bread.png b/client/src/main/resources/textures/items/bread.png deleted file mode 100755 index 5a28f14..0000000 Binary files a/client/src/main/resources/textures/items/bread.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/brewing_stand.png b/client/src/main/resources/textures/items/brewing_stand.png deleted file mode 100755 index 97db9af..0000000 Binary files a/client/src/main/resources/textures/items/brewing_stand.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/brick.png b/client/src/main/resources/textures/items/brick.png deleted file mode 100755 index 11e74be..0000000 Binary files a/client/src/main/resources/textures/items/brick.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/bucket.png b/client/src/main/resources/textures/items/bucket.png deleted file mode 100755 index f8e5369..0000000 Binary files a/client/src/main/resources/textures/items/bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/burning_soul.png b/client/src/main/resources/textures/items/burning_soul.png deleted file mode 100755 index 924cc58..0000000 Binary files a/client/src/main/resources/textures/items/burning_soul.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cake.png b/client/src/main/resources/textures/items/cake.png deleted file mode 100755 index 46e94b8..0000000 Binary files a/client/src/main/resources/textures/items/cake.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/calcium_powder.png b/client/src/main/resources/textures/items/calcium_powder.png deleted file mode 100755 index 1e13afe..0000000 Binary files a/client/src/main/resources/textures/items/calcium_powder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/camera.png b/client/src/main/resources/textures/items/camera.png deleted file mode 100755 index 3ab9d10..0000000 Binary files a/client/src/main/resources/textures/items/camera.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/carrot.png b/client/src/main/resources/textures/items/carrot.png deleted file mode 100755 index 2d08aab..0000000 Binary files a/client/src/main/resources/textures/items/carrot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/carrot_on_a_stick.png b/client/src/main/resources/textures/items/carrot_on_a_stick.png deleted file mode 100755 index 9e88571..0000000 Binary files a/client/src/main/resources/textures/items/carrot_on_a_stick.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cauldron.png b/client/src/main/resources/textures/items/cauldron.png deleted file mode 100755 index e3186eb..0000000 Binary files a/client/src/main/resources/textures/items/cauldron.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/chain.png b/client/src/main/resources/textures/items/chain.png deleted file mode 100755 index f80079d..0000000 Binary files a/client/src/main/resources/textures/items/chain.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/chain_boots.png b/client/src/main/resources/textures/items/chain_boots.png deleted file mode 100755 index 54a4a15..0000000 Binary files a/client/src/main/resources/textures/items/chain_boots.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/chain_chestplate.png b/client/src/main/resources/textures/items/chain_chestplate.png deleted file mode 100755 index cd2115a..0000000 Binary files a/client/src/main/resources/textures/items/chain_chestplate.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/chain_helmet.png b/client/src/main/resources/textures/items/chain_helmet.png deleted file mode 100755 index a143338..0000000 Binary files a/client/src/main/resources/textures/items/chain_helmet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/chain_leggings.png b/client/src/main/resources/textures/items/chain_leggings.png deleted file mode 100755 index dae4b26..0000000 Binary files a/client/src/main/resources/textures/items/chain_leggings.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/charcoal.png b/client/src/main/resources/textures/items/charcoal.png deleted file mode 100755 index 20d5b25..0000000 Binary files a/client/src/main/resources/textures/items/charcoal.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/charge_crystal.png b/client/src/main/resources/textures/items/charge_crystal.png deleted file mode 100755 index 1e03365..0000000 Binary files a/client/src/main/resources/textures/items/charge_crystal.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/charged_orb.png b/client/src/main/resources/textures/items/charged_orb.png deleted file mode 100755 index 75d0d08..0000000 Binary files a/client/src/main/resources/textures/items/charged_orb.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cherry_door.png b/client/src/main/resources/textures/items/cherry_door.png deleted file mode 100755 index f6fa2b8..0000000 Binary files a/client/src/main/resources/textures/items/cherry_door.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/chest_minecart.png b/client/src/main/resources/textures/items/chest_minecart.png deleted file mode 100755 index 78a3778..0000000 Binary files a/client/src/main/resources/textures/items/chest_minecart.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/chick_magnet.png b/client/src/main/resources/textures/items/chick_magnet.png deleted file mode 100755 index ebeb8fa..0000000 Binary files a/client/src/main/resources/textures/items/chick_magnet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/chicken.png b/client/src/main/resources/textures/items/chicken.png deleted file mode 100755 index 6d25922..0000000 Binary files a/client/src/main/resources/textures/items/chicken.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/chrome_ingot.png b/client/src/main/resources/textures/items/chrome_ingot.png deleted file mode 100755 index 74ad0db..0000000 Binary files a/client/src/main/resources/textures/items/chrome_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cinnabar.png b/client/src/main/resources/textures/items/cinnabar.png deleted file mode 100755 index 8e2298a..0000000 Binary files a/client/src/main/resources/textures/items/cinnabar.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/clay_ball.png b/client/src/main/resources/textures/items/clay_ball.png deleted file mode 100755 index 5103d6c..0000000 Binary files a/client/src/main/resources/textures/items/clay_ball.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/clock.png b/client/src/main/resources/textures/items/clock.png deleted file mode 100755 index 1ec0fff..0000000 Binary files a/client/src/main/resources/textures/items/clock.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cloth_boots.png b/client/src/main/resources/textures/items/cloth_boots.png deleted file mode 100755 index 84d8fd9..0000000 Binary files a/client/src/main/resources/textures/items/cloth_boots.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cloth_boots_overlay.png b/client/src/main/resources/textures/items/cloth_boots_overlay.png deleted file mode 100755 index 4a1d868..0000000 Binary files a/client/src/main/resources/textures/items/cloth_boots_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cloth_chestplate.png b/client/src/main/resources/textures/items/cloth_chestplate.png deleted file mode 100755 index e534aef..0000000 Binary files a/client/src/main/resources/textures/items/cloth_chestplate.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cloth_chestplate_overlay.png b/client/src/main/resources/textures/items/cloth_chestplate_overlay.png deleted file mode 100755 index 6fa801f..0000000 Binary files a/client/src/main/resources/textures/items/cloth_chestplate_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cloth_helmet.png b/client/src/main/resources/textures/items/cloth_helmet.png deleted file mode 100755 index 6daf551..0000000 Binary files a/client/src/main/resources/textures/items/cloth_helmet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cloth_helmet_overlay.png b/client/src/main/resources/textures/items/cloth_helmet_overlay.png deleted file mode 100755 index e8a0625..0000000 Binary files a/client/src/main/resources/textures/items/cloth_helmet_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cloth_leggings.png b/client/src/main/resources/textures/items/cloth_leggings.png deleted file mode 100755 index fc38cf2..0000000 Binary files a/client/src/main/resources/textures/items/cloth_leggings.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cloth_leggings_overlay.png b/client/src/main/resources/textures/items/cloth_leggings_overlay.png deleted file mode 100755 index 22598f0..0000000 Binary files a/client/src/main/resources/textures/items/cloth_leggings_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/clownfish.png b/client/src/main/resources/textures/items/clownfish.png deleted file mode 100755 index 41df72f..0000000 Binary files a/client/src/main/resources/textures/items/clownfish.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/coal.png b/client/src/main/resources/textures/items/coal.png deleted file mode 100755 index 5563b6f..0000000 Binary files a/client/src/main/resources/textures/items/coal.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cobalt_ingot.png b/client/src/main/resources/textures/items/cobalt_ingot.png deleted file mode 100755 index a7ddf17..0000000 Binary files a/client/src/main/resources/textures/items/cobalt_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cod.png b/client/src/main/resources/textures/items/cod.png deleted file mode 100755 index 32996bf..0000000 Binary files a/client/src/main/resources/textures/items/cod.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/comparator.png b/client/src/main/resources/textures/items/comparator.png deleted file mode 100755 index 28b8eec..0000000 Binary files a/client/src/main/resources/textures/items/comparator.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cooked_beef.png b/client/src/main/resources/textures/items/cooked_beef.png deleted file mode 100755 index 2df9bbf..0000000 Binary files a/client/src/main/resources/textures/items/cooked_beef.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cooked_chicken.png b/client/src/main/resources/textures/items/cooked_chicken.png deleted file mode 100755 index 890b5b3..0000000 Binary files a/client/src/main/resources/textures/items/cooked_chicken.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cooked_cod.png b/client/src/main/resources/textures/items/cooked_cod.png deleted file mode 100755 index 87564c7..0000000 Binary files a/client/src/main/resources/textures/items/cooked_cod.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cooked_porkchop.png b/client/src/main/resources/textures/items/cooked_porkchop.png deleted file mode 100755 index 605d3f5..0000000 Binary files a/client/src/main/resources/textures/items/cooked_porkchop.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cooked_salmon.png b/client/src/main/resources/textures/items/cooked_salmon.png deleted file mode 100755 index fb765ed..0000000 Binary files a/client/src/main/resources/textures/items/cooked_salmon.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/cookie.png b/client/src/main/resources/textures/items/cookie.png deleted file mode 100755 index 01fe56b..0000000 Binary files a/client/src/main/resources/textures/items/cookie.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/copper_ingot.png b/client/src/main/resources/textures/items/copper_ingot.png deleted file mode 100755 index 22c02cd..0000000 Binary files a/client/src/main/resources/textures/items/copper_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dark_lighter.png b/client/src/main/resources/textures/items/dark_lighter.png deleted file mode 100755 index 60242f4..0000000 Binary files a/client/src/main/resources/textures/items/dark_lighter.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dark_oak_door.png b/client/src/main/resources/textures/items/dark_oak_door.png deleted file mode 100755 index 7862d9a..0000000 Binary files a/client/src/main/resources/textures/items/dark_oak_door.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/darkstone_fragment.png b/client/src/main/resources/textures/items/darkstone_fragment.png deleted file mode 100755 index 4603084..0000000 Binary files a/client/src/main/resources/textures/items/darkstone_fragment.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond.png b/client/src/main/resources/textures/items/diamond.png deleted file mode 100755 index 10e70a0..0000000 Binary files a/client/src/main/resources/textures/items/diamond.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond_axe.png b/client/src/main/resources/textures/items/diamond_axe.png deleted file mode 100755 index 7627f87..0000000 Binary files a/client/src/main/resources/textures/items/diamond_axe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond_boots.png b/client/src/main/resources/textures/items/diamond_boots.png deleted file mode 100755 index 70d9e5f..0000000 Binary files a/client/src/main/resources/textures/items/diamond_boots.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond_chestplate.png b/client/src/main/resources/textures/items/diamond_chestplate.png deleted file mode 100755 index afdff93..0000000 Binary files a/client/src/main/resources/textures/items/diamond_chestplate.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond_helmet.png b/client/src/main/resources/textures/items/diamond_helmet.png deleted file mode 100755 index 1c88592..0000000 Binary files a/client/src/main/resources/textures/items/diamond_helmet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond_hoe.png b/client/src/main/resources/textures/items/diamond_hoe.png deleted file mode 100755 index c9a97e0..0000000 Binary files a/client/src/main/resources/textures/items/diamond_hoe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond_horse_armor.png b/client/src/main/resources/textures/items/diamond_horse_armor.png deleted file mode 100755 index b281aad..0000000 Binary files a/client/src/main/resources/textures/items/diamond_horse_armor.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond_leggings.png b/client/src/main/resources/textures/items/diamond_leggings.png deleted file mode 100755 index a99c896..0000000 Binary files a/client/src/main/resources/textures/items/diamond_leggings.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond_pickaxe.png b/client/src/main/resources/textures/items/diamond_pickaxe.png deleted file mode 100755 index c279828..0000000 Binary files a/client/src/main/resources/textures/items/diamond_pickaxe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond_shears.png b/client/src/main/resources/textures/items/diamond_shears.png deleted file mode 100755 index 775a536..0000000 Binary files a/client/src/main/resources/textures/items/diamond_shears.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond_shovel.png b/client/src/main/resources/textures/items/diamond_shovel.png deleted file mode 100755 index e4a8992..0000000 Binary files a/client/src/main/resources/textures/items/diamond_shovel.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/diamond_sword.png b/client/src/main/resources/textures/items/diamond_sword.png deleted file mode 100755 index 2a1552d..0000000 Binary files a/client/src/main/resources/textures/items/diamond_sword.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d10_side.png b/client/src/main/resources/textures/items/die_d10_side.png deleted file mode 100755 index c928f91..0000000 Binary files a/client/src/main/resources/textures/items/die_d10_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d10_top.png b/client/src/main/resources/textures/items/die_d10_top.png deleted file mode 100755 index 531447a..0000000 Binary files a/client/src/main/resources/textures/items/die_d10_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d12_side.png b/client/src/main/resources/textures/items/die_d12_side.png deleted file mode 100755 index 4ff1b07..0000000 Binary files a/client/src/main/resources/textures/items/die_d12_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d12_top.png b/client/src/main/resources/textures/items/die_d12_top.png deleted file mode 100755 index d9ef587..0000000 Binary files a/client/src/main/resources/textures/items/die_d12_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d20_side.png b/client/src/main/resources/textures/items/die_d20_side.png deleted file mode 100755 index 596b72b..0000000 Binary files a/client/src/main/resources/textures/items/die_d20_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d20_top.png b/client/src/main/resources/textures/items/die_d20_top.png deleted file mode 100755 index ed89d74..0000000 Binary files a/client/src/main/resources/textures/items/die_d20_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d4_side.png b/client/src/main/resources/textures/items/die_d4_side.png deleted file mode 100755 index d7cb196..0000000 Binary files a/client/src/main/resources/textures/items/die_d4_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d4_top.png b/client/src/main/resources/textures/items/die_d4_top.png deleted file mode 100755 index d023ba4..0000000 Binary files a/client/src/main/resources/textures/items/die_d4_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d6_side.png b/client/src/main/resources/textures/items/die_d6_side.png deleted file mode 100755 index 50d4deb..0000000 Binary files a/client/src/main/resources/textures/items/die_d6_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d6_top.png b/client/src/main/resources/textures/items/die_d6_top.png deleted file mode 100755 index 14f29e8..0000000 Binary files a/client/src/main/resources/textures/items/die_d6_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d8_side.png b/client/src/main/resources/textures/items/die_d8_side.png deleted file mode 100755 index 787620d..0000000 Binary files a/client/src/main/resources/textures/items/die_d8_side.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/die_d8_top.png b/client/src/main/resources/textures/items/die_d8_top.png deleted file mode 100755 index e48306a..0000000 Binary files a/client/src/main/resources/textures/items/die_d8_top.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_black.png b/client/src/main/resources/textures/items/dye_black.png deleted file mode 100755 index 162715a..0000000 Binary files a/client/src/main/resources/textures/items/dye_black.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_blue.png b/client/src/main/resources/textures/items/dye_blue.png deleted file mode 100755 index 4713983..0000000 Binary files a/client/src/main/resources/textures/items/dye_blue.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_brown.png b/client/src/main/resources/textures/items/dye_brown.png deleted file mode 100755 index 62eae8d..0000000 Binary files a/client/src/main/resources/textures/items/dye_brown.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_cyan.png b/client/src/main/resources/textures/items/dye_cyan.png deleted file mode 100755 index 901c1a6..0000000 Binary files a/client/src/main/resources/textures/items/dye_cyan.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_gray.png b/client/src/main/resources/textures/items/dye_gray.png deleted file mode 100755 index 38dc3cc..0000000 Binary files a/client/src/main/resources/textures/items/dye_gray.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_green.png b/client/src/main/resources/textures/items/dye_green.png deleted file mode 100755 index 009e058..0000000 Binary files a/client/src/main/resources/textures/items/dye_green.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_light_blue.png b/client/src/main/resources/textures/items/dye_light_blue.png deleted file mode 100755 index ef58a5f..0000000 Binary files a/client/src/main/resources/textures/items/dye_light_blue.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_lime.png b/client/src/main/resources/textures/items/dye_lime.png deleted file mode 100755 index c7c91f9..0000000 Binary files a/client/src/main/resources/textures/items/dye_lime.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_magenta.png b/client/src/main/resources/textures/items/dye_magenta.png deleted file mode 100755 index fbf9f64..0000000 Binary files a/client/src/main/resources/textures/items/dye_magenta.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_orange.png b/client/src/main/resources/textures/items/dye_orange.png deleted file mode 100755 index 1cc564f..0000000 Binary files a/client/src/main/resources/textures/items/dye_orange.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_pink.png b/client/src/main/resources/textures/items/dye_pink.png deleted file mode 100755 index a82bb54..0000000 Binary files a/client/src/main/resources/textures/items/dye_pink.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_purple.png b/client/src/main/resources/textures/items/dye_purple.png deleted file mode 100755 index ebe58dc..0000000 Binary files a/client/src/main/resources/textures/items/dye_purple.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_red.png b/client/src/main/resources/textures/items/dye_red.png deleted file mode 100755 index 2d1a742..0000000 Binary files a/client/src/main/resources/textures/items/dye_red.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_silver.png b/client/src/main/resources/textures/items/dye_silver.png deleted file mode 100755 index d08f399..0000000 Binary files a/client/src/main/resources/textures/items/dye_silver.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_white.png b/client/src/main/resources/textures/items/dye_white.png deleted file mode 100755 index 5b1833b..0000000 Binary files a/client/src/main/resources/textures/items/dye_white.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dye_yellow.png b/client/src/main/resources/textures/items/dye_yellow.png deleted file mode 100755 index 95e0673..0000000 Binary files a/client/src/main/resources/textures/items/dye_yellow.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dynamite.png b/client/src/main/resources/textures/items/dynamite.png deleted file mode 100755 index 868a3dc..0000000 Binary files a/client/src/main/resources/textures/items/dynamite.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dynamite_1.png b/client/src/main/resources/textures/items/dynamite_1.png deleted file mode 100755 index e7c2f6a..0000000 Binary files a/client/src/main/resources/textures/items/dynamite_1.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dynamite_2.png b/client/src/main/resources/textures/items/dynamite_2.png deleted file mode 100755 index df99e60..0000000 Binary files a/client/src/main/resources/textures/items/dynamite_2.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dynamite_3.png b/client/src/main/resources/textures/items/dynamite_3.png deleted file mode 100755 index a2179ff..0000000 Binary files a/client/src/main/resources/textures/items/dynamite_3.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dynamite_4.png b/client/src/main/resources/textures/items/dynamite_4.png deleted file mode 100755 index c748595..0000000 Binary files a/client/src/main/resources/textures/items/dynamite_4.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dynamite_5.png b/client/src/main/resources/textures/items/dynamite_5.png deleted file mode 100755 index d0ad1ae..0000000 Binary files a/client/src/main/resources/textures/items/dynamite_5.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dynamite_6.png b/client/src/main/resources/textures/items/dynamite_6.png deleted file mode 100755 index 249af2e..0000000 Binary files a/client/src/main/resources/textures/items/dynamite_6.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/dynamite_7.png b/client/src/main/resources/textures/items/dynamite_7.png deleted file mode 100755 index e190689..0000000 Binary files a/client/src/main/resources/textures/items/dynamite_7.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/egg.png b/client/src/main/resources/textures/items/egg.png deleted file mode 100755 index a6fe2bf..0000000 Binary files a/client/src/main/resources/textures/items/egg.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/emerald.png b/client/src/main/resources/textures/items/emerald.png deleted file mode 100755 index 98d953e..0000000 Binary files a/client/src/main/resources/textures/items/emerald.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/empty_armor_slot_boots.png b/client/src/main/resources/textures/items/empty_armor_slot_boots.png deleted file mode 100755 index fd7e05f..0000000 Binary files a/client/src/main/resources/textures/items/empty_armor_slot_boots.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/empty_armor_slot_chestplate.png b/client/src/main/resources/textures/items/empty_armor_slot_chestplate.png deleted file mode 100755 index 6e632b9..0000000 Binary files a/client/src/main/resources/textures/items/empty_armor_slot_chestplate.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/empty_armor_slot_helmet.png b/client/src/main/resources/textures/items/empty_armor_slot_helmet.png deleted file mode 100755 index 3a455f3..0000000 Binary files a/client/src/main/resources/textures/items/empty_armor_slot_helmet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/empty_armor_slot_leggings.png b/client/src/main/resources/textures/items/empty_armor_slot_leggings.png deleted file mode 100755 index 28b2c49..0000000 Binary files a/client/src/main/resources/textures/items/empty_armor_slot_leggings.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/enchanted_book.png b/client/src/main/resources/textures/items/enchanted_book.png deleted file mode 100755 index 8742bee..0000000 Binary files a/client/src/main/resources/textures/items/enchanted_book.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/experience_bottle.png b/client/src/main/resources/textures/items/experience_bottle.png deleted file mode 100755 index ae4214f..0000000 Binary files a/client/src/main/resources/textures/items/experience_bottle.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/exterminator.png b/client/src/main/resources/textures/items/exterminator.png deleted file mode 100755 index 33b54c5..0000000 Binary files a/client/src/main/resources/textures/items/exterminator.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/feather.png b/client/src/main/resources/textures/items/feather.png deleted file mode 100755 index d4c3be5..0000000 Binary files a/client/src/main/resources/textures/items/feather.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/fermented_spider_eye.png b/client/src/main/resources/textures/items/fermented_spider_eye.png deleted file mode 100755 index 226ffb8..0000000 Binary files a/client/src/main/resources/textures/items/fermented_spider_eye.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/filled_map.png b/client/src/main/resources/textures/items/filled_map.png deleted file mode 100755 index 1381e21..0000000 Binary files a/client/src/main/resources/textures/items/filled_map.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/fire_charge.png b/client/src/main/resources/textures/items/fire_charge.png deleted file mode 100755 index d62a6f4..0000000 Binary files a/client/src/main/resources/textures/items/fire_charge.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/firework_charge.png b/client/src/main/resources/textures/items/firework_charge.png deleted file mode 100755 index 5c89362..0000000 Binary files a/client/src/main/resources/textures/items/firework_charge.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/firework_charge_overlay.png b/client/src/main/resources/textures/items/firework_charge_overlay.png deleted file mode 100755 index d8b91a9..0000000 Binary files a/client/src/main/resources/textures/items/firework_charge_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/fireworks.png b/client/src/main/resources/textures/items/fireworks.png deleted file mode 100755 index f1e07fd..0000000 Binary files a/client/src/main/resources/textures/items/fireworks.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/fishing_rod.png b/client/src/main/resources/textures/items/fishing_rod.png deleted file mode 100755 index d4b53f0..0000000 Binary files a/client/src/main/resources/textures/items/fishing_rod.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/fishing_rod_cast.png b/client/src/main/resources/textures/items/fishing_rod_cast.png deleted file mode 100755 index a5ab378..0000000 Binary files a/client/src/main/resources/textures/items/fishing_rod_cast.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/flint.png b/client/src/main/resources/textures/items/flint.png deleted file mode 100755 index 5f51093..0000000 Binary files a/client/src/main/resources/textures/items/flint.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/flint_and_steel.png b/client/src/main/resources/textures/items/flint_and_steel.png deleted file mode 100755 index 77bc340..0000000 Binary files a/client/src/main/resources/textures/items/flint_and_steel.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/flower_pot.png b/client/src/main/resources/textures/items/flower_pot.png deleted file mode 100755 index c4f26d2..0000000 Binary files a/client/src/main/resources/textures/items/flower_pot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/furnace_minecart.png b/client/src/main/resources/textures/items/furnace_minecart.png deleted file mode 100755 index 5478f25..0000000 Binary files a/client/src/main/resources/textures/items/furnace_minecart.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/ghast_tear.png b/client/src/main/resources/textures/items/ghast_tear.png deleted file mode 100755 index e5c741f..0000000 Binary files a/client/src/main/resources/textures/items/ghast_tear.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/ghi_fragment.png b/client/src/main/resources/textures/items/ghi_fragment.png deleted file mode 100755 index c89a930..0000000 Binary files a/client/src/main/resources/textures/items/ghi_fragment.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/glowstone_dust.png b/client/src/main/resources/textures/items/glowstone_dust.png deleted file mode 100755 index edd93a6..0000000 Binary files a/client/src/main/resources/textures/items/glowstone_dust.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_axe.png b/client/src/main/resources/textures/items/gold_axe.png deleted file mode 100755 index 0f47b60..0000000 Binary files a/client/src/main/resources/textures/items/gold_axe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_boots.png b/client/src/main/resources/textures/items/gold_boots.png deleted file mode 100755 index f6033d2..0000000 Binary files a/client/src/main/resources/textures/items/gold_boots.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_chestplate.png b/client/src/main/resources/textures/items/gold_chestplate.png deleted file mode 100755 index e36076a..0000000 Binary files a/client/src/main/resources/textures/items/gold_chestplate.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_helmet.png b/client/src/main/resources/textures/items/gold_helmet.png deleted file mode 100755 index 9eb89a0..0000000 Binary files a/client/src/main/resources/textures/items/gold_helmet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_hoe.png b/client/src/main/resources/textures/items/gold_hoe.png deleted file mode 100755 index 1685d47..0000000 Binary files a/client/src/main/resources/textures/items/gold_hoe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_horse_armor.png b/client/src/main/resources/textures/items/gold_horse_armor.png deleted file mode 100755 index 7c5c3a5..0000000 Binary files a/client/src/main/resources/textures/items/gold_horse_armor.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_ingot.png b/client/src/main/resources/textures/items/gold_ingot.png deleted file mode 100755 index ea781e7..0000000 Binary files a/client/src/main/resources/textures/items/gold_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_leggings.png b/client/src/main/resources/textures/items/gold_leggings.png deleted file mode 100755 index da23771..0000000 Binary files a/client/src/main/resources/textures/items/gold_leggings.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_nugget.png b/client/src/main/resources/textures/items/gold_nugget.png deleted file mode 100755 index 3a9a2fe..0000000 Binary files a/client/src/main/resources/textures/items/gold_nugget.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_pickaxe.png b/client/src/main/resources/textures/items/gold_pickaxe.png deleted file mode 100755 index ecccafe..0000000 Binary files a/client/src/main/resources/textures/items/gold_pickaxe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_shears.png b/client/src/main/resources/textures/items/gold_shears.png deleted file mode 100755 index ea1b1ee..0000000 Binary files a/client/src/main/resources/textures/items/gold_shears.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_shovel.png b/client/src/main/resources/textures/items/gold_shovel.png deleted file mode 100755 index 150cbb9..0000000 Binary files a/client/src/main/resources/textures/items/gold_shovel.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gold_sword.png b/client/src/main/resources/textures/items/gold_sword.png deleted file mode 100755 index 0ddef04..0000000 Binary files a/client/src/main/resources/textures/items/gold_sword.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/golden_apple.png b/client/src/main/resources/textures/items/golden_apple.png deleted file mode 100755 index 6201989..0000000 Binary files a/client/src/main/resources/textures/items/golden_apple.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/golden_carrot.png b/client/src/main/resources/textures/items/golden_carrot.png deleted file mode 100755 index e0f1ea6..0000000 Binary files a/client/src/main/resources/textures/items/golden_carrot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/goo_bucket.png b/client/src/main/resources/textures/items/goo_bucket.png deleted file mode 100755 index a67246c..0000000 Binary files a/client/src/main/resources/textures/items/goo_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gunpowder.png b/client/src/main/resources/textures/items/gunpowder.png deleted file mode 100755 index 73cadec..0000000 Binary files a/client/src/main/resources/textures/items/gunpowder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gyriyn_axe.png b/client/src/main/resources/textures/items/gyriyn_axe.png deleted file mode 100755 index cd1a52d..0000000 Binary files a/client/src/main/resources/textures/items/gyriyn_axe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gyriyn_hoe.png b/client/src/main/resources/textures/items/gyriyn_hoe.png deleted file mode 100755 index f7a730e..0000000 Binary files a/client/src/main/resources/textures/items/gyriyn_hoe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gyriyn_pickaxe.png b/client/src/main/resources/textures/items/gyriyn_pickaxe.png deleted file mode 100755 index 9efb11f..0000000 Binary files a/client/src/main/resources/textures/items/gyriyn_pickaxe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gyriyn_shears.png b/client/src/main/resources/textures/items/gyriyn_shears.png deleted file mode 100755 index 1863648..0000000 Binary files a/client/src/main/resources/textures/items/gyriyn_shears.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/gyriyn_shovel.png b/client/src/main/resources/textures/items/gyriyn_shovel.png deleted file mode 100755 index 7769434..0000000 Binary files a/client/src/main/resources/textures/items/gyriyn_shovel.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/hopper.png b/client/src/main/resources/textures/items/hopper.png deleted file mode 100755 index f8b244f..0000000 Binary files a/client/src/main/resources/textures/items/hopper.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/hopper_minecart.png b/client/src/main/resources/textures/items/hopper_minecart.png deleted file mode 100755 index 8a138fb..0000000 Binary files a/client/src/main/resources/textures/items/hopper_minecart.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/hydrogen_bucket.png b/client/src/main/resources/textures/items/hydrogen_bucket.png deleted file mode 100755 index cba7641..0000000 Binary files a/client/src/main/resources/textures/items/hydrogen_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/info_wand.png b/client/src/main/resources/textures/items/info_wand.png deleted file mode 100755 index 63fcda9..0000000 Binary files a/client/src/main/resources/textures/items/info_wand.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iodine_powder.png b/client/src/main/resources/textures/items/iodine_powder.png deleted file mode 100755 index 41cbca1..0000000 Binary files a/client/src/main/resources/textures/items/iodine_powder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_axe.png b/client/src/main/resources/textures/items/iron_axe.png deleted file mode 100755 index 8bf133e..0000000 Binary files a/client/src/main/resources/textures/items/iron_axe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_boots.png b/client/src/main/resources/textures/items/iron_boots.png deleted file mode 100755 index b69ca05..0000000 Binary files a/client/src/main/resources/textures/items/iron_boots.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_chestplate.png b/client/src/main/resources/textures/items/iron_chestplate.png deleted file mode 100755 index e7993ce..0000000 Binary files a/client/src/main/resources/textures/items/iron_chestplate.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_door.png b/client/src/main/resources/textures/items/iron_door.png deleted file mode 100755 index 5dcbe38..0000000 Binary files a/client/src/main/resources/textures/items/iron_door.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_helmet.png b/client/src/main/resources/textures/items/iron_helmet.png deleted file mode 100755 index 65e64cc..0000000 Binary files a/client/src/main/resources/textures/items/iron_helmet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_hoe.png b/client/src/main/resources/textures/items/iron_hoe.png deleted file mode 100755 index 28d4c36..0000000 Binary files a/client/src/main/resources/textures/items/iron_hoe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_horse_armor.png b/client/src/main/resources/textures/items/iron_horse_armor.png deleted file mode 100755 index 5d697d1..0000000 Binary files a/client/src/main/resources/textures/items/iron_horse_armor.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_ingot.png b/client/src/main/resources/textures/items/iron_ingot.png deleted file mode 100755 index 3833fa0..0000000 Binary files a/client/src/main/resources/textures/items/iron_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_leggings.png b/client/src/main/resources/textures/items/iron_leggings.png deleted file mode 100755 index ad53673..0000000 Binary files a/client/src/main/resources/textures/items/iron_leggings.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_pickaxe.png b/client/src/main/resources/textures/items/iron_pickaxe.png deleted file mode 100755 index d21440b..0000000 Binary files a/client/src/main/resources/textures/items/iron_pickaxe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_shears.png b/client/src/main/resources/textures/items/iron_shears.png deleted file mode 100755 index f9c6de1..0000000 Binary files a/client/src/main/resources/textures/items/iron_shears.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_shovel.png b/client/src/main/resources/textures/items/iron_shovel.png deleted file mode 100755 index 079b236..0000000 Binary files a/client/src/main/resources/textures/items/iron_shovel.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/iron_sword.png b/client/src/main/resources/textures/items/iron_sword.png deleted file mode 100755 index 4d49c5a..0000000 Binary files a/client/src/main/resources/textures/items/iron_sword.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/item_frame.png b/client/src/main/resources/textures/items/item_frame.png deleted file mode 100755 index 261c98a..0000000 Binary files a/client/src/main/resources/textures/items/item_frame.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/jungle_door.png b/client/src/main/resources/textures/items/jungle_door.png deleted file mode 100755 index cb3753d..0000000 Binary files a/client/src/main/resources/textures/items/jungle_door.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/key.png b/client/src/main/resources/textures/items/key.png deleted file mode 100755 index 3dbcfb8..0000000 Binary files a/client/src/main/resources/textures/items/key.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/lava_bucket.png b/client/src/main/resources/textures/items/lava_bucket.png deleted file mode 100755 index 13a1957..0000000 Binary files a/client/src/main/resources/textures/items/lava_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/lead.png b/client/src/main/resources/textures/items/lead.png deleted file mode 100755 index 0ef5312..0000000 Binary files a/client/src/main/resources/textures/items/lead.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/lead_ingot.png b/client/src/main/resources/textures/items/lead_ingot.png deleted file mode 100755 index 48d97a9..0000000 Binary files a/client/src/main/resources/textures/items/lead_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/leather.png b/client/src/main/resources/textures/items/leather.png deleted file mode 100755 index 13dc199..0000000 Binary files a/client/src/main/resources/textures/items/leather.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/leather_boots.png b/client/src/main/resources/textures/items/leather_boots.png deleted file mode 100755 index eecca82..0000000 Binary files a/client/src/main/resources/textures/items/leather_boots.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/leather_boots_overlay.png b/client/src/main/resources/textures/items/leather_boots_overlay.png deleted file mode 100755 index 4a1d868..0000000 Binary files a/client/src/main/resources/textures/items/leather_boots_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/leather_chestplate.png b/client/src/main/resources/textures/items/leather_chestplate.png deleted file mode 100755 index d11e2fd..0000000 Binary files a/client/src/main/resources/textures/items/leather_chestplate.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/leather_chestplate_overlay.png b/client/src/main/resources/textures/items/leather_chestplate_overlay.png deleted file mode 100755 index 6fa801f..0000000 Binary files a/client/src/main/resources/textures/items/leather_chestplate_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/leather_helmet.png b/client/src/main/resources/textures/items/leather_helmet.png deleted file mode 100755 index 5f90fc0..0000000 Binary files a/client/src/main/resources/textures/items/leather_helmet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/leather_helmet_overlay.png b/client/src/main/resources/textures/items/leather_helmet_overlay.png deleted file mode 100755 index e8a0625..0000000 Binary files a/client/src/main/resources/textures/items/leather_helmet_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/leather_leggings.png b/client/src/main/resources/textures/items/leather_leggings.png deleted file mode 100755 index 1220322..0000000 Binary files a/client/src/main/resources/textures/items/leather_leggings.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/leather_leggings_overlay.png b/client/src/main/resources/textures/items/leather_leggings_overlay.png deleted file mode 100755 index 22598f0..0000000 Binary files a/client/src/main/resources/textures/items/leather_leggings_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/lightning_wand.png b/client/src/main/resources/textures/items/lightning_wand.png deleted file mode 100755 index b51ed3d..0000000 Binary files a/client/src/main/resources/textures/items/lightning_wand.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/lithium_ingot.png b/client/src/main/resources/textures/items/lithium_ingot.png deleted file mode 100755 index 8da1957..0000000 Binary files a/client/src/main/resources/textures/items/lithium_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/magma_bucket.png b/client/src/main/resources/textures/items/magma_bucket.png deleted file mode 100755 index dc76d26..0000000 Binary files a/client/src/main/resources/textures/items/magma_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/magma_cream.png b/client/src/main/resources/textures/items/magma_cream.png deleted file mode 100755 index b2be210..0000000 Binary files a/client/src/main/resources/textures/items/magma_cream.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/magnesium_powder.png b/client/src/main/resources/textures/items/magnesium_powder.png deleted file mode 100755 index 21098a6..0000000 Binary files a/client/src/main/resources/textures/items/magnesium_powder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/magnet.png b/client/src/main/resources/textures/items/magnet.png deleted file mode 100755 index 93d0518..0000000 Binary files a/client/src/main/resources/textures/items/magnet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/manganese_ingot.png b/client/src/main/resources/textures/items/manganese_ingot.png deleted file mode 100755 index e8b7efa..0000000 Binary files a/client/src/main/resources/textures/items/manganese_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/map.png b/client/src/main/resources/textures/items/map.png deleted file mode 100755 index 8dc6e58..0000000 Binary files a/client/src/main/resources/textures/items/map.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/maple_door.png b/client/src/main/resources/textures/items/maple_door.png deleted file mode 100755 index 4c33b8f..0000000 Binary files a/client/src/main/resources/textures/items/maple_door.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/melon.png b/client/src/main/resources/textures/items/melon.png deleted file mode 100755 index 590f47a..0000000 Binary files a/client/src/main/resources/textures/items/melon.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/melon_stem.png b/client/src/main/resources/textures/items/melon_stem.png deleted file mode 100755 index ef84499..0000000 Binary files a/client/src/main/resources/textures/items/melon_stem.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/mercury_bucket.png b/client/src/main/resources/textures/items/mercury_bucket.png deleted file mode 100755 index 084003b..0000000 Binary files a/client/src/main/resources/textures/items/mercury_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/milk_bucket.png b/client/src/main/resources/textures/items/milk_bucket.png deleted file mode 100755 index c77d92c..0000000 Binary files a/client/src/main/resources/textures/items/milk_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/minecart.png b/client/src/main/resources/textures/items/minecart.png deleted file mode 100755 index 2046f2b..0000000 Binary files a/client/src/main/resources/textures/items/minecart.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/minecart_command_block.png b/client/src/main/resources/textures/items/minecart_command_block.png deleted file mode 100755 index c597ee7..0000000 Binary files a/client/src/main/resources/textures/items/minecart_command_block.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/mushroom_stew.png b/client/src/main/resources/textures/items/mushroom_stew.png deleted file mode 100755 index 5598bc7..0000000 Binary files a/client/src/main/resources/textures/items/mushroom_stew.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/mutton_cooked.png b/client/src/main/resources/textures/items/mutton_cooked.png deleted file mode 100755 index e1b62dc..0000000 Binary files a/client/src/main/resources/textures/items/mutton_cooked.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/mutton_raw.png b/client/src/main/resources/textures/items/mutton_raw.png deleted file mode 100755 index 1222ff4..0000000 Binary files a/client/src/main/resources/textures/items/mutton_raw.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/name_tag.png b/client/src/main/resources/textures/items/name_tag.png deleted file mode 100755 index a88f559..0000000 Binary files a/client/src/main/resources/textures/items/name_tag.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/navigator.png b/client/src/main/resources/textures/items/navigator.png deleted file mode 100755 index 3715ee4..0000000 Binary files a/client/src/main/resources/textures/items/navigator.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/neodymium_ingot.png b/client/src/main/resources/textures/items/neodymium_ingot.png deleted file mode 100755 index b015a96..0000000 Binary files a/client/src/main/resources/textures/items/neodymium_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/neptunium_ingot.png b/client/src/main/resources/textures/items/neptunium_ingot.png deleted file mode 100755 index 0f5070e..0000000 Binary files a/client/src/main/resources/textures/items/neptunium_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nichun_axe.png b/client/src/main/resources/textures/items/nichun_axe.png deleted file mode 100755 index b14dbf8..0000000 Binary files a/client/src/main/resources/textures/items/nichun_axe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nichun_boots.png b/client/src/main/resources/textures/items/nichun_boots.png deleted file mode 100755 index 0755025..0000000 Binary files a/client/src/main/resources/textures/items/nichun_boots.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nichun_chestplate.png b/client/src/main/resources/textures/items/nichun_chestplate.png deleted file mode 100755 index 1da9d89..0000000 Binary files a/client/src/main/resources/textures/items/nichun_chestplate.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nichun_helmet.png b/client/src/main/resources/textures/items/nichun_helmet.png deleted file mode 100755 index 23fd417..0000000 Binary files a/client/src/main/resources/textures/items/nichun_helmet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nichun_hoe.png b/client/src/main/resources/textures/items/nichun_hoe.png deleted file mode 100755 index d7baa35..0000000 Binary files a/client/src/main/resources/textures/items/nichun_hoe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nichun_leggings.png b/client/src/main/resources/textures/items/nichun_leggings.png deleted file mode 100755 index df7722f..0000000 Binary files a/client/src/main/resources/textures/items/nichun_leggings.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nichun_pickaxe.png b/client/src/main/resources/textures/items/nichun_pickaxe.png deleted file mode 100755 index a474eef..0000000 Binary files a/client/src/main/resources/textures/items/nichun_pickaxe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nichun_shears.png b/client/src/main/resources/textures/items/nichun_shears.png deleted file mode 100755 index 683d22a..0000000 Binary files a/client/src/main/resources/textures/items/nichun_shears.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nichun_shovel.png b/client/src/main/resources/textures/items/nichun_shovel.png deleted file mode 100755 index 10316e8..0000000 Binary files a/client/src/main/resources/textures/items/nichun_shovel.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nichun_sword.png b/client/src/main/resources/textures/items/nichun_sword.png deleted file mode 100755 index 6707be1..0000000 Binary files a/client/src/main/resources/textures/items/nichun_sword.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nickel_ingot.png b/client/src/main/resources/textures/items/nickel_ingot.png deleted file mode 100755 index d0ef7b0..0000000 Binary files a/client/src/main/resources/textures/items/nickel_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nieh_fragment.png b/client/src/main/resources/textures/items/nieh_fragment.png deleted file mode 100755 index 5f63fda..0000000 Binary files a/client/src/main/resources/textures/items/nieh_fragment.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/npc_spawner.png b/client/src/main/resources/textures/items/npc_spawner.png deleted file mode 100755 index 8e54c3d..0000000 Binary files a/client/src/main/resources/textures/items/npc_spawner.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/npc_spawner_overlay.png b/client/src/main/resources/textures/items/npc_spawner_overlay.png deleted file mode 100755 index fad661e..0000000 Binary files a/client/src/main/resources/textures/items/npc_spawner_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/nukage_bucket.png b/client/src/main/resources/textures/items/nukage_bucket.png deleted file mode 100755 index 6825ae7..0000000 Binary files a/client/src/main/resources/textures/items/nukage_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/oak_door.png b/client/src/main/resources/textures/items/oak_door.png deleted file mode 100755 index 43683f8..0000000 Binary files a/client/src/main/resources/textures/items/oak_door.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/orb.png b/client/src/main/resources/textures/items/orb.png deleted file mode 100755 index 0bc9b66..0000000 Binary files a/client/src/main/resources/textures/items/orb.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/painting.png b/client/src/main/resources/textures/items/painting.png deleted file mode 100755 index b394f30..0000000 Binary files a/client/src/main/resources/textures/items/painting.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/palladium_ingot.png b/client/src/main/resources/textures/items/palladium_ingot.png deleted file mode 100755 index fad3197..0000000 Binary files a/client/src/main/resources/textures/items/palladium_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/paper.png b/client/src/main/resources/textures/items/paper.png deleted file mode 100755 index a1d9c7e..0000000 Binary files a/client/src/main/resources/textures/items/paper.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/phosphor_powder.png b/client/src/main/resources/textures/items/phosphor_powder.png deleted file mode 100755 index df5d136..0000000 Binary files a/client/src/main/resources/textures/items/phosphor_powder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/platinum_ingot.png b/client/src/main/resources/textures/items/platinum_ingot.png deleted file mode 100755 index d39193e..0000000 Binary files a/client/src/main/resources/textures/items/platinum_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/plutonium_ingot.png b/client/src/main/resources/textures/items/plutonium_ingot.png deleted file mode 100755 index 9ba95db..0000000 Binary files a/client/src/main/resources/textures/items/plutonium_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/poisonous_potato.png b/client/src/main/resources/textures/items/poisonous_potato.png deleted file mode 100755 index 6f154af..0000000 Binary files a/client/src/main/resources/textures/items/poisonous_potato.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/porkchop.png b/client/src/main/resources/textures/items/porkchop.png deleted file mode 100755 index 7e83c1a..0000000 Binary files a/client/src/main/resources/textures/items/porkchop.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/potassium_powder.png b/client/src/main/resources/textures/items/potassium_powder.png deleted file mode 100755 index da32e5d..0000000 Binary files a/client/src/main/resources/textures/items/potassium_powder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/potato.png b/client/src/main/resources/textures/items/potato.png deleted file mode 100755 index c1d8541..0000000 Binary files a/client/src/main/resources/textures/items/potato.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/potion_bottle_drinkable.png b/client/src/main/resources/textures/items/potion_bottle_drinkable.png deleted file mode 100755 index 87339d7..0000000 Binary files a/client/src/main/resources/textures/items/potion_bottle_drinkable.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/potion_bottle_empty.png b/client/src/main/resources/textures/items/potion_bottle_empty.png deleted file mode 100755 index 87339d7..0000000 Binary files a/client/src/main/resources/textures/items/potion_bottle_empty.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/potion_bottle_splash.png b/client/src/main/resources/textures/items/potion_bottle_splash.png deleted file mode 100755 index 03b1f90..0000000 Binary files a/client/src/main/resources/textures/items/potion_bottle_splash.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/potion_overlay.png b/client/src/main/resources/textures/items/potion_overlay.png deleted file mode 100755 index 61864e9..0000000 Binary files a/client/src/main/resources/textures/items/potion_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/praseodymium_ingot.png b/client/src/main/resources/textures/items/praseodymium_ingot.png deleted file mode 100755 index c98d7f8..0000000 Binary files a/client/src/main/resources/textures/items/praseodymium_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/pufferfish.png b/client/src/main/resources/textures/items/pufferfish.png deleted file mode 100755 index aadbd88..0000000 Binary files a/client/src/main/resources/textures/items/pufferfish.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/pumpkin_pie.png b/client/src/main/resources/textures/items/pumpkin_pie.png deleted file mode 100755 index c21a032..0000000 Binary files a/client/src/main/resources/textures/items/pumpkin_pie.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/pumpkin_stem.png b/client/src/main/resources/textures/items/pumpkin_stem.png deleted file mode 100755 index 8d8f076..0000000 Binary files a/client/src/main/resources/textures/items/pumpkin_stem.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/purple_bed.png b/client/src/main/resources/textures/items/purple_bed.png deleted file mode 100755 index 72fddd4..0000000 Binary files a/client/src/main/resources/textures/items/purple_bed.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/quartz.png b/client/src/main/resources/textures/items/quartz.png deleted file mode 100755 index e403446..0000000 Binary files a/client/src/main/resources/textures/items/quartz.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/quiver.png b/client/src/main/resources/textures/items/quiver.png deleted file mode 100755 index 818f728..0000000 Binary files a/client/src/main/resources/textures/items/quiver.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/radium_ingot.png b/client/src/main/resources/textures/items/radium_ingot.png deleted file mode 100755 index 75d7c14..0000000 Binary files a/client/src/main/resources/textures/items/radium_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/record_old.png b/client/src/main/resources/textures/items/record_old.png deleted file mode 100755 index 343ebb5..0000000 Binary files a/client/src/main/resources/textures/items/record_old.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/red_bed.png b/client/src/main/resources/textures/items/red_bed.png deleted file mode 100755 index 22a4cf0..0000000 Binary files a/client/src/main/resources/textures/items/red_bed.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/redstone.png b/client/src/main/resources/textures/items/redstone.png deleted file mode 100755 index 6da938b..0000000 Binary files a/client/src/main/resources/textures/items/redstone.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/reeds.png b/client/src/main/resources/textures/items/reeds.png deleted file mode 100755 index 40872c6..0000000 Binary files a/client/src/main/resources/textures/items/reeds.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/repeater.png b/client/src/main/resources/textures/items/repeater.png deleted file mode 100755 index 7a07381..0000000 Binary files a/client/src/main/resources/textures/items/repeater.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/rotten_flesh.png b/client/src/main/resources/textures/items/rotten_flesh.png deleted file mode 100755 index 3f39998..0000000 Binary files a/client/src/main/resources/textures/items/rotten_flesh.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/ruby.png b/client/src/main/resources/textures/items/ruby.png deleted file mode 100755 index 4f288d9..0000000 Binary files a/client/src/main/resources/textures/items/ruby.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/saddle.png b/client/src/main/resources/textures/items/saddle.png deleted file mode 100755 index b12eafa..0000000 Binary files a/client/src/main/resources/textures/items/saddle.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/salmon.png b/client/src/main/resources/textures/items/salmon.png deleted file mode 100755 index 68bcd69..0000000 Binary files a/client/src/main/resources/textures/items/salmon.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/selenium_powder.png b/client/src/main/resources/textures/items/selenium_powder.png deleted file mode 100755 index 2529161..0000000 Binary files a/client/src/main/resources/textures/items/selenium_powder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/sign.png b/client/src/main/resources/textures/items/sign.png deleted file mode 100755 index 9b6e2ee..0000000 Binary files a/client/src/main/resources/textures/items/sign.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/silicon_ingot.png b/client/src/main/resources/textures/items/silicon_ingot.png deleted file mode 100755 index 814f4b1..0000000 Binary files a/client/src/main/resources/textures/items/silicon_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/silver_ingot.png b/client/src/main/resources/textures/items/silver_ingot.png deleted file mode 100755 index 940067f..0000000 Binary files a/client/src/main/resources/textures/items/silver_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/skull.png b/client/src/main/resources/textures/items/skull.png deleted file mode 100644 index 835979f..0000000 Binary files a/client/src/main/resources/textures/items/skull.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/slime_ball.png b/client/src/main/resources/textures/items/slime_ball.png deleted file mode 100755 index 46478ee..0000000 Binary files a/client/src/main/resources/textures/items/slime_ball.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/slime_bucket.png b/client/src/main/resources/textures/items/slime_bucket.png deleted file mode 100755 index a57c6c2..0000000 Binary files a/client/src/main/resources/textures/items/slime_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/snowball.png b/client/src/main/resources/textures/items/snowball.png deleted file mode 100755 index 340c639..0000000 Binary files a/client/src/main/resources/textures/items/snowball.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/sodium_powder.png b/client/src/main/resources/textures/items/sodium_powder.png deleted file mode 100755 index 1c9e774..0000000 Binary files a/client/src/main/resources/textures/items/sodium_powder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/soul_wart.png b/client/src/main/resources/textures/items/soul_wart.png deleted file mode 100755 index 09da1e3..0000000 Binary files a/client/src/main/resources/textures/items/soul_wart.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/spawn_egg.png b/client/src/main/resources/textures/items/spawn_egg.png deleted file mode 100755 index 26cc6b2..0000000 Binary files a/client/src/main/resources/textures/items/spawn_egg.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/spawn_egg_overlay.png b/client/src/main/resources/textures/items/spawn_egg_overlay.png deleted file mode 100755 index 83ec78f..0000000 Binary files a/client/src/main/resources/textures/items/spawn_egg_overlay.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/speckled_melon.png b/client/src/main/resources/textures/items/speckled_melon.png deleted file mode 100755 index dee1bf5..0000000 Binary files a/client/src/main/resources/textures/items/speckled_melon.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/spider_eye.png b/client/src/main/resources/textures/items/spider_eye.png deleted file mode 100755 index 35d8584..0000000 Binary files a/client/src/main/resources/textures/items/spider_eye.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/springwater_bucket.png b/client/src/main/resources/textures/items/springwater_bucket.png deleted file mode 100755 index 75e0382..0000000 Binary files a/client/src/main/resources/textures/items/springwater_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/spruce_door.png b/client/src/main/resources/textures/items/spruce_door.png deleted file mode 100755 index 4eddb7e..0000000 Binary files a/client/src/main/resources/textures/items/spruce_door.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/stick.png b/client/src/main/resources/textures/items/stick.png deleted file mode 100755 index 6f8ce13..0000000 Binary files a/client/src/main/resources/textures/items/stick.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/stone_axe.png b/client/src/main/resources/textures/items/stone_axe.png deleted file mode 100755 index fb33584..0000000 Binary files a/client/src/main/resources/textures/items/stone_axe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/stone_hoe.png b/client/src/main/resources/textures/items/stone_hoe.png deleted file mode 100755 index d46b272..0000000 Binary files a/client/src/main/resources/textures/items/stone_hoe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/stone_pickaxe.png b/client/src/main/resources/textures/items/stone_pickaxe.png deleted file mode 100755 index 19a8e50..0000000 Binary files a/client/src/main/resources/textures/items/stone_pickaxe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/stone_shovel.png b/client/src/main/resources/textures/items/stone_shovel.png deleted file mode 100755 index 8e1c0c2..0000000 Binary files a/client/src/main/resources/textures/items/stone_shovel.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/stone_sword.png b/client/src/main/resources/textures/items/stone_sword.png deleted file mode 100755 index 5810dfd..0000000 Binary files a/client/src/main/resources/textures/items/stone_sword.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/string.png b/client/src/main/resources/textures/items/string.png deleted file mode 100755 index 0b04ddb..0000000 Binary files a/client/src/main/resources/textures/items/string.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/sugar.png b/client/src/main/resources/textures/items/sugar.png deleted file mode 100755 index 0864df9..0000000 Binary files a/client/src/main/resources/textures/items/sugar.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/sulfur_powder.png b/client/src/main/resources/textures/items/sulfur_powder.png deleted file mode 100755 index 5c1a8f1..0000000 Binary files a/client/src/main/resources/textures/items/sulfur_powder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/thetium_axe.png b/client/src/main/resources/textures/items/thetium_axe.png deleted file mode 100755 index 111c2a6..0000000 Binary files a/client/src/main/resources/textures/items/thetium_axe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/thetium_boots.png b/client/src/main/resources/textures/items/thetium_boots.png deleted file mode 100755 index a6f0540..0000000 Binary files a/client/src/main/resources/textures/items/thetium_boots.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/thetium_chestplate.png b/client/src/main/resources/textures/items/thetium_chestplate.png deleted file mode 100755 index 2f70677..0000000 Binary files a/client/src/main/resources/textures/items/thetium_chestplate.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/thetium_helmet.png b/client/src/main/resources/textures/items/thetium_helmet.png deleted file mode 100755 index 7536212..0000000 Binary files a/client/src/main/resources/textures/items/thetium_helmet.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/thetium_hoe.png b/client/src/main/resources/textures/items/thetium_hoe.png deleted file mode 100755 index 86e8c29..0000000 Binary files a/client/src/main/resources/textures/items/thetium_hoe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/thetium_leggings.png b/client/src/main/resources/textures/items/thetium_leggings.png deleted file mode 100755 index dbf82eb..0000000 Binary files a/client/src/main/resources/textures/items/thetium_leggings.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/thetium_pickaxe.png b/client/src/main/resources/textures/items/thetium_pickaxe.png deleted file mode 100755 index 02054d0..0000000 Binary files a/client/src/main/resources/textures/items/thetium_pickaxe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/thetium_shears.png b/client/src/main/resources/textures/items/thetium_shears.png deleted file mode 100755 index a4014ac..0000000 Binary files a/client/src/main/resources/textures/items/thetium_shears.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/thetium_shovel.png b/client/src/main/resources/textures/items/thetium_shovel.png deleted file mode 100755 index 6a46a34..0000000 Binary files a/client/src/main/resources/textures/items/thetium_shovel.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/thetium_sword.png b/client/src/main/resources/textures/items/thetium_sword.png deleted file mode 100755 index 26591f1..0000000 Binary files a/client/src/main/resources/textures/items/thetium_sword.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/thi_fragment.png b/client/src/main/resources/textures/items/thi_fragment.png deleted file mode 100755 index 90abf54..0000000 Binary files a/client/src/main/resources/textures/items/thi_fragment.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/tian_door.png b/client/src/main/resources/textures/items/tian_door.png deleted file mode 100755 index 0e8353e..0000000 Binary files a/client/src/main/resources/textures/items/tian_door.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/tin_ingot.png b/client/src/main/resources/textures/items/tin_ingot.png deleted file mode 100755 index 95eb514..0000000 Binary files a/client/src/main/resources/textures/items/tin_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/titanium_ingot.png b/client/src/main/resources/textures/items/titanium_ingot.png deleted file mode 100755 index 24fbe4b..0000000 Binary files a/client/src/main/resources/textures/items/titanium_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/tnt_minecart.png b/client/src/main/resources/textures/items/tnt_minecart.png deleted file mode 100755 index 561279b..0000000 Binary files a/client/src/main/resources/textures/items/tnt_minecart.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/tungsten_ingot.png b/client/src/main/resources/textures/items/tungsten_ingot.png deleted file mode 100755 index a10133d..0000000 Binary files a/client/src/main/resources/textures/items/tungsten_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/uranium_ingot.png b/client/src/main/resources/textures/items/uranium_ingot.png deleted file mode 100755 index c8dcafe..0000000 Binary files a/client/src/main/resources/textures/items/uranium_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/vanadium_ingot.png b/client/src/main/resources/textures/items/vanadium_ingot.png deleted file mode 100755 index e6c7044..0000000 Binary files a/client/src/main/resources/textures/items/vanadium_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/wand.png b/client/src/main/resources/textures/items/wand.png deleted file mode 100755 index 2cb6dd7..0000000 Binary files a/client/src/main/resources/textures/items/wand.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/water_bucket.png b/client/src/main/resources/textures/items/water_bucket.png deleted file mode 100755 index 2f36acc..0000000 Binary files a/client/src/main/resources/textures/items/water_bucket.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_chilled.png b/client/src/main/resources/textures/items/weather_token_chilled.png deleted file mode 100755 index 6a28224..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_chilled.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_clear.png b/client/src/main/resources/textures/items/weather_token_clear.png deleted file mode 100755 index 8bb3884..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_clear.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_cold.png b/client/src/main/resources/textures/items/weather_token_cold.png deleted file mode 100755 index 679c1d4..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_cold.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_fire.png b/client/src/main/resources/textures/items/weather_token_fire.png deleted file mode 100755 index 409b12c..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_fire.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_fog.png b/client/src/main/resources/textures/items/weather_token_fog.png deleted file mode 100755 index 0e71a00..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_fog.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_frost.png b/client/src/main/resources/textures/items/weather_token_frost.png deleted file mode 100755 index 8785594..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_frost.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_hail.png b/client/src/main/resources/textures/items/weather_token_hail.png deleted file mode 100755 index 8314060..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_hail.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_hailstorm.png b/client/src/main/resources/textures/items/weather_token_hailstorm.png deleted file mode 100755 index 61a53ad..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_hailstorm.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_hot.png b/client/src/main/resources/textures/items/weather_token_hot.png deleted file mode 100755 index f611325..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_hot.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_ice.png b/client/src/main/resources/textures/items/weather_token_ice.png deleted file mode 100755 index 9f7a9ed..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_ice.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_iceage.png b/client/src/main/resources/textures/items/weather_token_iceage.png deleted file mode 100755 index 8022792..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_iceage.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_inferno.png b/client/src/main/resources/textures/items/weather_token_inferno.png deleted file mode 100755 index c5aadcc..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_inferno.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_rain.png b/client/src/main/resources/textures/items/weather_token_rain.png deleted file mode 100755 index 944670b..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_rain.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_snow.png b/client/src/main/resources/textures/items/weather_token_snow.png deleted file mode 100755 index d6321d9..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_snow.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_snowstorm.png b/client/src/main/resources/textures/items/weather_token_snowstorm.png deleted file mode 100755 index 5a2bb68..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_snowstorm.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_storm.png b/client/src/main/resources/textures/items/weather_token_storm.png deleted file mode 100755 index cad9126..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_storm.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/weather_token_thunder.png b/client/src/main/resources/textures/items/weather_token_thunder.png deleted file mode 100755 index 198988c..0000000 Binary files a/client/src/main/resources/textures/items/weather_token_thunder.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/wheat.png b/client/src/main/resources/textures/items/wheat.png deleted file mode 100755 index 83d23a6..0000000 Binary files a/client/src/main/resources/textures/items/wheat.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/wheats.png b/client/src/main/resources/textures/items/wheats.png deleted file mode 100755 index bbd2fd9..0000000 Binary files a/client/src/main/resources/textures/items/wheats.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/white_bed.png b/client/src/main/resources/textures/items/white_bed.png deleted file mode 100755 index d45a87f..0000000 Binary files a/client/src/main/resources/textures/items/white_bed.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/wood_axe.png b/client/src/main/resources/textures/items/wood_axe.png deleted file mode 100755 index 3a19203..0000000 Binary files a/client/src/main/resources/textures/items/wood_axe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/wood_hoe.png b/client/src/main/resources/textures/items/wood_hoe.png deleted file mode 100755 index de1c7a6..0000000 Binary files a/client/src/main/resources/textures/items/wood_hoe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/wood_pickaxe.png b/client/src/main/resources/textures/items/wood_pickaxe.png deleted file mode 100755 index ebc6756..0000000 Binary files a/client/src/main/resources/textures/items/wood_pickaxe.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/wood_shovel.png b/client/src/main/resources/textures/items/wood_shovel.png deleted file mode 100755 index b057911..0000000 Binary files a/client/src/main/resources/textures/items/wood_shovel.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/wood_sword.png b/client/src/main/resources/textures/items/wood_sword.png deleted file mode 100755 index c04dc0a..0000000 Binary files a/client/src/main/resources/textures/items/wood_sword.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/writable_book.png b/client/src/main/resources/textures/items/writable_book.png deleted file mode 100755 index fa95246..0000000 Binary files a/client/src/main/resources/textures/items/writable_book.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/written_book.png b/client/src/main/resources/textures/items/written_book.png deleted file mode 100755 index b2a2aa8..0000000 Binary files a/client/src/main/resources/textures/items/written_book.png and /dev/null differ diff --git a/client/src/main/resources/textures/items/zinc_ingot.png b/client/src/main/resources/textures/items/zinc_ingot.png deleted file mode 100755 index 10e8650..0000000 Binary files a/client/src/main/resources/textures/items/zinc_ingot.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/clouds.png b/client/src/main/resources/textures/world/clouds.png deleted file mode 100755 index a67c44d..0000000 Binary files a/client/src/main/resources/textures/world/clouds.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/clouds_dense.png b/client/src/main/resources/textures/world/clouds_dense.png deleted file mode 100755 index 992d0f4..0000000 Binary files a/client/src/main/resources/textures/world/clouds_dense.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/foliage.png b/client/src/main/resources/textures/world/foliage.png deleted file mode 100755 index 54c2429..0000000 Binary files a/client/src/main/resources/textures/world/foliage.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/forcefield.png b/client/src/main/resources/textures/world/forcefield.png deleted file mode 100755 index 3129f07..0000000 Binary files a/client/src/main/resources/textures/world/forcefield.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/grass.png b/client/src/main/resources/textures/world/grass.png deleted file mode 100755 index 118a69a..0000000 Binary files a/client/src/main/resources/textures/world/grass.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/hail.png b/client/src/main/resources/textures/world/hail.png deleted file mode 100755 index b354828..0000000 Binary files a/client/src/main/resources/textures/world/hail.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/molten.png b/client/src/main/resources/textures/world/molten.png deleted file mode 100755 index 59678b4..0000000 Binary files a/client/src/main/resources/textures/world/molten.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/moon_phases.png b/client/src/main/resources/textures/world/moon_phases.png deleted file mode 100755 index cdba8d1..0000000 Binary files a/client/src/main/resources/textures/world/moon_phases.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/particles.png b/client/src/main/resources/textures/world/particles.png deleted file mode 100755 index 447156f..0000000 Binary files a/client/src/main/resources/textures/world/particles.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/rain.png b/client/src/main/resources/textures/world/rain.png deleted file mode 100755 index e9dc16c..0000000 Binary files a/client/src/main/resources/textures/world/rain.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/rain_new.png b/client/src/main/resources/textures/world/rain_new.png deleted file mode 100755 index 2dc4b1c..0000000 Binary files a/client/src/main/resources/textures/world/rain_new.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/snow.png b/client/src/main/resources/textures/world/snow.png deleted file mode 100755 index 1898903..0000000 Binary files a/client/src/main/resources/textures/world/snow.png and /dev/null differ diff --git a/client/src/main/resources/textures/world/sun.png b/client/src/main/resources/textures/world/sun.png deleted file mode 100755 index 08de644..0000000 Binary files a/client/src/main/resources/textures/world/sun.png and /dev/null differ diff --git a/common/build.gradle.kts b/common/build.gradle.kts deleted file mode 100644 index 4676aad..0000000 --- a/common/build.gradle.kts +++ /dev/null @@ -1,10 +0,0 @@ - -plugins { - `java-library` -} - -java { - toolchain { - languageVersion = JavaLanguageVersion.of(21) - } -} diff --git a/common/src/main/java/common/ai/AIFireballAttack.java b/common/src/common/ai/AIFireballAttack.java similarity index 100% rename from common/src/main/java/common/ai/AIFireballAttack.java rename to common/src/common/ai/AIFireballAttack.java diff --git a/common/src/main/java/common/ai/AIFlyingBoxAttack.java b/common/src/common/ai/AIFlyingBoxAttack.java similarity index 100% rename from common/src/main/java/common/ai/AIFlyingBoxAttack.java rename to common/src/common/ai/AIFlyingBoxAttack.java diff --git a/common/src/main/java/common/ai/AIRangedAttack.java b/common/src/common/ai/AIRangedAttack.java similarity index 100% rename from common/src/main/java/common/ai/AIRangedAttack.java rename to common/src/common/ai/AIRangedAttack.java diff --git a/common/src/main/java/common/ai/AISmallFireballAttack.java b/common/src/common/ai/AISmallFireballAttack.java similarity index 100% rename from common/src/main/java/common/ai/AISmallFireballAttack.java rename to common/src/common/ai/AISmallFireballAttack.java diff --git a/common/src/main/java/common/ai/EntityAIAttackOnCollide.java b/common/src/common/ai/EntityAIAttackOnCollide.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIAttackOnCollide.java rename to common/src/common/ai/EntityAIAttackOnCollide.java diff --git a/common/src/main/java/common/ai/EntityAIAvoidEntity.java b/common/src/common/ai/EntityAIAvoidEntity.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIAvoidEntity.java rename to common/src/common/ai/EntityAIAvoidEntity.java diff --git a/common/src/main/java/common/ai/EntityAIBase.java b/common/src/common/ai/EntityAIBase.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIBase.java rename to common/src/common/ai/EntityAIBase.java diff --git a/common/src/main/java/common/ai/EntityAIBeg.java b/common/src/common/ai/EntityAIBeg.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIBeg.java rename to common/src/common/ai/EntityAIBeg.java diff --git a/common/src/main/java/common/ai/EntityAIControlledByPlayer.java b/common/src/common/ai/EntityAIControlledByPlayer.java similarity index 95% rename from common/src/main/java/common/ai/EntityAIControlledByPlayer.java rename to common/src/common/ai/EntityAIControlledByPlayer.java index 7b4bed0..320f4d1 100755 --- a/common/src/main/java/common/ai/EntityAIControlledByPlayer.java +++ b/common/src/common/ai/EntityAIControlledByPlayer.java @@ -1,13 +1,13 @@ package common.ai; import common.block.Block; -import common.block.artificial.BlockSlab; -import common.block.artificial.BlockStairs; +import common.block.BlockSlab; +import common.block.BlockStairs; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; -import common.init.Blocks; import common.init.Items; import common.item.ItemStack; +import common.material.Material; import common.pathfinding.WalkNodeProcessor; import common.util.BlockPos; import common.util.ExtMath; @@ -162,7 +162,7 @@ public class EntityAIControlledByPlayer extends EntityAIBase if (i != l || k != i1) { Block block = this.thisEntity.worldObj.getState(new BlockPos(i, j, k)).getBlock(); - boolean flag = !this.isStairOrSlab(block) && (block != Blocks.air || !this.isStairOrSlab(this.thisEntity.worldObj.getState(new BlockPos(i, j - 1, k)).getBlock())); + boolean flag = !this.isStairOrSlab(block) && (block.getMaterial() != Material.air || !this.isStairOrSlab(this.thisEntity.worldObj.getState(new BlockPos(i, j - 1, k)).getBlock())); if (flag && 0 == WalkNodeProcessor.getColliding(this.thisEntity.worldObj, this.thisEntity, l, j, i1, j1, k1, l1, false, false, true) && 1 == WalkNodeProcessor.getColliding(this.thisEntity.worldObj, this.thisEntity, i, j + 1, k, j1, k1, l1, false, false, true) && 1 == WalkNodeProcessor.getColliding(this.thisEntity.worldObj, this.thisEntity, l, j + 1, i1, j1, k1, l1, false, false, true)) { @@ -178,7 +178,7 @@ public class EntityAIControlledByPlayer extends EntityAIBase { itemstack.damageItem(1, entityplayer); - if (itemstack.size == 0) + if (itemstack.stackSize == 0) { ItemStack itemstack1 = new ItemStack(Items.fishing_rod); itemstack1.setTagCompound(itemstack.getTagCompound()); diff --git a/common/src/main/java/common/ai/EntityAIDoorInteract.java b/common/src/common/ai/EntityAIDoorInteract.java similarity index 97% rename from common/src/main/java/common/ai/EntityAIDoorInteract.java rename to common/src/common/ai/EntityAIDoorInteract.java index e98a1f4..c6a7538 100755 --- a/common/src/main/java/common/ai/EntityAIDoorInteract.java +++ b/common/src/common/ai/EntityAIDoorInteract.java @@ -1,9 +1,9 @@ package common.ai; import common.block.Block; -import common.block.Material; -import common.block.artificial.BlockDoor; +import common.block.BlockDoor; import common.entity.types.EntityLiving; +import common.material.Material; import common.pathfinding.PathEntity; import common.pathfinding.PathNavigateGround; import common.pathfinding.PathPoint; @@ -113,6 +113,6 @@ public abstract class EntityAIDoorInteract extends EntityAIBase private BlockDoor getBlockDoor(BlockPos pos) { Block block = this.theEntity.worldObj.getState(pos).getBlock(); - return block instanceof BlockDoor && block.getMaterial() == Material.WOOD ? (BlockDoor)block : null; + return block instanceof BlockDoor && block.getMaterial() == Material.wood ? (BlockDoor)block : null; } } diff --git a/common/src/main/java/common/ai/EntityAIEatGrass.java b/common/src/common/ai/EntityAIEatGrass.java similarity index 77% rename from common/src/main/java/common/ai/EntityAIEatGrass.java rename to common/src/common/ai/EntityAIEatGrass.java index 47e76e4..f04e8fd 100755 --- a/common/src/main/java/common/ai/EntityAIEatGrass.java +++ b/common/src/common/ai/EntityAIEatGrass.java @@ -1,16 +1,22 @@ package common.ai; -import common.block.foliage.BlockTallGrass; +import java.util.function.Predicate; + +import common.block.BlockTallGrass; import common.entity.animal.EntitySheep; import common.init.BlockRegistry; import common.init.Blocks; +import common.init.Config; +import common.pattern.BlockStateHelper; import common.util.BlockPos; -import common.vars.Vars; +import common.util.Predicates; import common.world.State; import common.world.World; public class EntityAIEatGrass extends EntityAIBase { + private static final Predicate field_179505_b = BlockStateHelper.forBlock(Blocks.tallgrass).where(BlockTallGrass.TYPE, Predicates.equalTo(BlockTallGrass.EnumType.GRASS)); + private EntitySheep grassEaterEntity; private World entityWorld; int eatingGrassTimer; @@ -34,9 +40,7 @@ public class EntityAIEatGrass extends EntityAIBase else { BlockPos blockpos = new BlockPos(this.grassEaterEntity.posX, this.grassEaterEntity.posY, this.grassEaterEntity.posZ); - State state = this.entityWorld.getState(blockpos); - return (state.getBlock() == Blocks.tallgrass && state.getValue(BlockTallGrass.TYPE) == BlockTallGrass.EnumType.GRASS) || - this.entityWorld.getState(blockpos.down()).getBlock() == Blocks.grass; + return field_179505_b.test(this.entityWorld.getState(blockpos)) ? true : this.entityWorld.getState(blockpos.down()).getBlock() == Blocks.grass; } } @@ -85,15 +89,14 @@ public class EntityAIEatGrass extends EntityAIBase { BlockPos blockpos = new BlockPos(this.grassEaterEntity.posX, this.grassEaterEntity.posY, this.grassEaterEntity.posZ); - State state = this.entityWorld.getState(blockpos); - if (state.getBlock() == Blocks.tallgrass && state.getValue(BlockTallGrass.TYPE) == BlockTallGrass.EnumType.GRASS) + if (field_179505_b.test(this.entityWorld.getState(blockpos))) { - if (Vars.mobGrief) + if (Config.mobGrief) { this.entityWorld.destroyBlock(blockpos, false); } - this.grassEaterEntity.eatGrass(); + this.grassEaterEntity.eatGrassBonus(); } else { @@ -101,13 +104,13 @@ public class EntityAIEatGrass extends EntityAIBase if (this.entityWorld.getState(blockpos1).getBlock() == Blocks.grass) { - if (Vars.mobGrief) + if (Config.mobGrief) { this.entityWorld.playAuxSFX(2001, blockpos1, BlockRegistry.getIdFromBlock(Blocks.grass)); this.entityWorld.setState(blockpos1, Blocks.dirt.getState(), 2); } - this.grassEaterEntity.eatGrass(); + this.grassEaterEntity.eatGrassBonus(); } } } diff --git a/common/src/main/java/common/ai/EntityAIExplode.java b/common/src/common/ai/EntityAIExplode.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIExplode.java rename to common/src/common/ai/EntityAIExplode.java diff --git a/common/src/main/java/common/ai/EntityAIFindEntityNearest.java b/common/src/common/ai/EntityAIFindEntityNearest.java similarity index 91% rename from common/src/main/java/common/ai/EntityAIFindEntityNearest.java rename to common/src/common/ai/EntityAIFindEntityNearest.java index 5be7b82..87eb994 100755 --- a/common/src/main/java/common/ai/EntityAIFindEntityNearest.java +++ b/common/src/common/ai/EntityAIFindEntityNearest.java @@ -4,6 +4,8 @@ import java.util.Collections; import java.util.List; import java.util.function.Predicate; +import common.attributes.AttributeInstance; +import common.attributes.Attributes; import common.entity.types.EntityLiving; public class EntityAIFindEntityNearest extends EntityAIBase @@ -103,6 +105,7 @@ public class EntityAIFindEntityNearest extends EntityAIBase protected double getFollowRange() { - return (double)this.mob.getPathingRange(); + AttributeInstance iattributeinstance = this.mob.getEntityAttribute(Attributes.FOLLOW_RANGE); + return iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue(); } } diff --git a/common/src/main/java/common/ai/EntityAIFollowOwner.java b/common/src/common/ai/EntityAIFollowOwner.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIFollowOwner.java rename to common/src/common/ai/EntityAIFollowOwner.java diff --git a/common/src/main/java/common/ai/EntityAIFollowParent.java b/common/src/common/ai/EntityAIFollowParent.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIFollowParent.java rename to common/src/common/ai/EntityAIFollowParent.java diff --git a/common/src/main/java/common/ai/EntityAIHarvestFarmland.java b/common/src/common/ai/EntityAIHarvestFarmland.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIHarvestFarmland.java rename to common/src/common/ai/EntityAIHarvestFarmland.java diff --git a/common/src/main/java/common/ai/EntityAIHurtByTarget.java b/common/src/common/ai/EntityAIHurtByTarget.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIHurtByTarget.java rename to common/src/common/ai/EntityAIHurtByTarget.java diff --git a/common/src/main/java/common/ai/EntityAILeapAtTarget.java b/common/src/common/ai/EntityAILeapAtTarget.java similarity index 100% rename from common/src/main/java/common/ai/EntityAILeapAtTarget.java rename to common/src/common/ai/EntityAILeapAtTarget.java diff --git a/common/src/main/java/common/ai/EntityAILookAtTalkingPlayer.java b/common/src/common/ai/EntityAILookAtTalkingPlayer.java similarity index 100% rename from common/src/main/java/common/ai/EntityAILookAtTalkingPlayer.java rename to common/src/common/ai/EntityAILookAtTalkingPlayer.java diff --git a/common/src/main/java/common/ai/EntityAILookIdle.java b/common/src/common/ai/EntityAILookIdle.java similarity index 100% rename from common/src/main/java/common/ai/EntityAILookIdle.java rename to common/src/common/ai/EntityAILookIdle.java diff --git a/common/src/main/java/common/ai/EntityAIMate.java b/common/src/common/ai/EntityAIMate.java similarity index 98% rename from common/src/main/java/common/ai/EntityAIMate.java rename to common/src/common/ai/EntityAIMate.java index be5d9e8..adff92f 100755 --- a/common/src/main/java/common/ai/EntityAIMate.java +++ b/common/src/common/ai/EntityAIMate.java @@ -6,9 +6,9 @@ import common.entity.item.EntityXp; import common.entity.npc.EntityNPC; import common.entity.types.EntityAnimal; import common.entity.types.EntityLiving; +import common.init.Config; import common.model.ParticleType; import common.rng.Random; -import common.vars.Vars; import common.world.World; public class EntityAIMate extends EntityAIBase @@ -158,7 +158,7 @@ public class EntityAIMate extends EntityAIBase this.theWorld.spawnParticle(ParticleType.HEART, this.theAnimal.posX + d3, this.theAnimal.posY + d4, this.theAnimal.posZ + d5, d0, d1, d2); } - if (entityplayer != null && Vars.breedingXP) // FIX xp + if (entityplayer != null && Config.breedingXP) // FIX xp { this.theWorld.spawnEntityInWorld(new EntityXp(this.theWorld, this.theAnimal.posX, this.theAnimal.posY, this.theAnimal.posZ, random.zrange(7) + 1)); } diff --git a/common/src/main/java/common/ai/EntityAIMoveIndoors.java b/common/src/common/ai/EntityAIMoveIndoors.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIMoveIndoors.java rename to common/src/common/ai/EntityAIMoveIndoors.java diff --git a/common/src/main/java/common/ai/EntityAIMoveThroughVillage.java b/common/src/common/ai/EntityAIMoveThroughVillage.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIMoveThroughVillage.java rename to common/src/common/ai/EntityAIMoveThroughVillage.java diff --git a/common/src/main/java/common/ai/EntityAIMoveToBlock.java b/common/src/common/ai/EntityAIMoveToBlock.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIMoveToBlock.java rename to common/src/common/ai/EntityAIMoveToBlock.java diff --git a/common/src/main/java/common/ai/EntityAIMoveTowardsRestriction.java b/common/src/common/ai/EntityAIMoveTowardsRestriction.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIMoveTowardsRestriction.java rename to common/src/common/ai/EntityAIMoveTowardsRestriction.java diff --git a/common/src/main/java/common/ai/EntityAIMoveTowardsTarget.java b/common/src/common/ai/EntityAIMoveTowardsTarget.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIMoveTowardsTarget.java rename to common/src/common/ai/EntityAIMoveTowardsTarget.java diff --git a/common/src/main/java/common/ai/EntityAINagPlayer.java b/common/src/common/ai/EntityAINagPlayer.java similarity index 100% rename from common/src/main/java/common/ai/EntityAINagPlayer.java rename to common/src/common/ai/EntityAINagPlayer.java diff --git a/common/src/main/java/common/ai/EntityAINearestAttackableTarget.java b/common/src/common/ai/EntityAINearestAttackableTarget.java similarity index 100% rename from common/src/main/java/common/ai/EntityAINearestAttackableTarget.java rename to common/src/common/ai/EntityAINearestAttackableTarget.java diff --git a/common/src/main/java/common/ai/EntityAINpcInteract.java b/common/src/common/ai/EntityAINpcInteract.java similarity index 100% rename from common/src/main/java/common/ai/EntityAINpcInteract.java rename to common/src/common/ai/EntityAINpcInteract.java diff --git a/common/src/main/java/common/ai/EntityAINpcMate.java b/common/src/common/ai/EntityAINpcMate.java similarity index 100% rename from common/src/main/java/common/ai/EntityAINpcMate.java rename to common/src/common/ai/EntityAINpcMate.java diff --git a/common/src/main/java/common/ai/EntityAIOcelotAttack.java b/common/src/common/ai/EntityAIOcelotAttack.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIOcelotAttack.java rename to common/src/common/ai/EntityAIOcelotAttack.java diff --git a/common/src/main/java/common/ai/EntityAIOcelotSit.java b/common/src/common/ai/EntityAIOcelotSit.java similarity index 98% rename from common/src/main/java/common/ai/EntityAIOcelotSit.java rename to common/src/common/ai/EntityAIOcelotSit.java index 407c6fd..aa46aa0 100755 --- a/common/src/main/java/common/ai/EntityAIOcelotSit.java +++ b/common/src/common/ai/EntityAIOcelotSit.java @@ -1,7 +1,7 @@ package common.ai; import common.block.Block; -import common.block.artificial.BlockBed; +import common.block.BlockBed; import common.entity.animal.EntityOcelot; import common.init.Blocks; import common.tileentity.TileEntity; diff --git a/common/src/main/java/common/ai/EntityAIOpenDoor.java b/common/src/common/ai/EntityAIOpenDoor.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIOpenDoor.java rename to common/src/common/ai/EntityAIOpenDoor.java diff --git a/common/src/main/java/common/ai/EntityAIOwnerHurtByTarget.java b/common/src/common/ai/EntityAIOwnerHurtByTarget.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIOwnerHurtByTarget.java rename to common/src/common/ai/EntityAIOwnerHurtByTarget.java diff --git a/common/src/main/java/common/ai/EntityAIOwnerHurtTarget.java b/common/src/common/ai/EntityAIOwnerHurtTarget.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIOwnerHurtTarget.java rename to common/src/common/ai/EntityAIOwnerHurtTarget.java diff --git a/common/src/main/java/common/ai/EntityAIPanic.java b/common/src/common/ai/EntityAIPanic.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIPanic.java rename to common/src/common/ai/EntityAIPanic.java diff --git a/common/src/main/java/common/ai/EntityAIPlay.java b/common/src/common/ai/EntityAIPlay.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIPlay.java rename to common/src/common/ai/EntityAIPlay.java diff --git a/common/src/main/java/common/ai/EntityAIRestrictOpenDoor.java b/common/src/common/ai/EntityAIRestrictOpenDoor.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIRestrictOpenDoor.java rename to common/src/common/ai/EntityAIRestrictOpenDoor.java diff --git a/common/src/main/java/common/ai/EntityAIRunAroundLikeCrazy.java b/common/src/common/ai/EntityAIRunAroundLikeCrazy.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIRunAroundLikeCrazy.java rename to common/src/common/ai/EntityAIRunAroundLikeCrazy.java diff --git a/common/src/main/java/common/ai/EntityAIShareItems.java b/common/src/common/ai/EntityAIShareItems.java similarity index 90% rename from common/src/main/java/common/ai/EntityAIShareItems.java rename to common/src/common/ai/EntityAIShareItems.java index a43c792..b22235c 100755 --- a/common/src/main/java/common/ai/EntityAIShareItems.java +++ b/common/src/common/ai/EntityAIShareItems.java @@ -60,21 +60,21 @@ public class EntityAIShareItems extends EntityAIWatchClosest2 { Item item = itemstack.getItem(); - if ((item == Items.bread || item == Items.potato || item == Items.carrot) && itemstack.size > 3) + if ((item == Items.bread || item == Items.potato || item == Items.carrot) && itemstack.stackSize > 3) { - int l = itemstack.size / 2; - itemstack.size -= l; + int l = itemstack.stackSize / 2; + itemstack.stackSize -= l; itemstack1 = new ItemStack(item, l, itemstack.getMetadata()); } - else if (item == Items.wheats && itemstack.size > 5) + else if (item == Items.wheats && itemstack.stackSize > 5) { - int j = itemstack.size / 2 / 3 * 3; + int j = itemstack.stackSize / 2 / 3 * 3; int k = j / 3; - itemstack.size -= j; + itemstack.stackSize -= j; itemstack1 = new ItemStack(Items.bread, k, 0); } - if (itemstack.size <= 0) + if (itemstack.stackSize <= 0) { inventorybasic.setInventorySlotContents(i, (ItemStack)null); } diff --git a/common/src/main/java/common/ai/EntityAISit.java b/common/src/common/ai/EntityAISit.java similarity index 100% rename from common/src/main/java/common/ai/EntityAISit.java rename to common/src/common/ai/EntityAISit.java diff --git a/common/src/main/java/common/ai/EntityAISwimming.java b/common/src/common/ai/EntityAISwimming.java similarity index 100% rename from common/src/main/java/common/ai/EntityAISwimming.java rename to common/src/common/ai/EntityAISwimming.java diff --git a/common/src/main/java/common/ai/EntityAITakePlace.java b/common/src/common/ai/EntityAITakePlace.java similarity index 89% rename from common/src/main/java/common/ai/EntityAITakePlace.java rename to common/src/common/ai/EntityAITakePlace.java index 7741361..e4fc53e 100755 --- a/common/src/main/java/common/ai/EntityAITakePlace.java +++ b/common/src/common/ai/EntityAITakePlace.java @@ -6,12 +6,13 @@ import common.block.Block; import common.collect.Maps; import common.entity.npc.EntityNPC; import common.init.Blocks; +import common.init.Config; import common.init.ItemRegistry; import common.item.ItemStack; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.util.ExtMath; -import common.vars.Vars; import common.world.State; import common.world.World; @@ -28,12 +29,12 @@ public class EntityAITakePlace extends EntityAIBase } public StackKey(ItemStack stack) { - this.item = ItemRegistry.getNameFromItem(stack.getItem()).toString(); + this.item = ItemRegistry.REGISTRY.getNameForObject(stack.getItem()).toString(); this.meta = stack.getItem().getMaxDamage() <= 0 ? stack.getMetadata() : -1; } // public boolean isSame(ItemStack stack) { -// return this.item.equals(ItemRegistry.getNameFromItem(stack.getItem()).toString()) && +// return this.item.equals(ItemRegistry.REGISTRY.getNameForObject(stack.getItem()).toString()) && // (stack.getItem().getMaxDamage() > 0 || stack.getMetadata() == this.meta); // } @@ -79,7 +80,7 @@ public class EntityAITakePlace extends EntityAIBase public boolean shouldExecute() { - if(!Vars.mobGrief || this.entity.getAttackTarget() != null) + if(!Config.mobGrief || this.entity.getAttackTarget() != null) return false; if(this.entity.getHeldItem() == null) { this.place = false; @@ -107,15 +108,15 @@ public class EntityAITakePlace extends EntityAIBase Block replace = world.getState(blockpos).getBlock(); Block below = world.getState(blockpos.down()).getBlock(); State state = PLACEABLE.get(new StackKey(this.entity.getHeldItem())); - if (state.getBlock().canPlaceBlockAt(world, blockpos) && replace == Blocks.air && - below != Blocks.air && below.isFullCube()) + if (state.getBlock().canPlaceBlockAt(world, blockpos) && replace.getMaterial() == Material.air && + below.getMaterial() != Material.air && below.isFullCube()) { this.entity.getLookHelper().setLookPosition((double)i + 0.5, (double)j + 0.5, (double)k + 0.5, 10.0F, (float)this.entity.getVerticalFaceSpeed()); this.entity.swingItem(); world.setState(blockpos, state, 3); - --stack.size; - if(stack.size <= 0) + --stack.stackSize; + if(stack.stackSize <= 0) this.entity.setItemNoUpdate(0, null); } } @@ -125,14 +126,14 @@ public class EntityAITakePlace extends EntityAIBase if (STEALABLE.containsKey(state) && (this.entity.getHeldItem() == null || (ItemStack.areItemsEqual(STEALABLE.get(state), - this.entity.getHeldItem()) && this.entity.getHeldItem().size < this.entity.getHeldItem().getMaxStackSize()))) + this.entity.getHeldItem()) && this.entity.getHeldItem().stackSize < this.entity.getHeldItem().getMaxStackSize()))) { this.entity.getLookHelper().setLookPosition((double)i + 0.5, (double)j + 0.5, (double)k + 0.5, 10.0F, (float)this.entity.getVerticalFaceSpeed()); this.entity.swingItem(); world.setState(blockpos, Blocks.air.getState()); if(this.entity.getHeldItem() != null) - ++this.entity.getHeldItem().size; + ++this.entity.getHeldItem().stackSize; else this.entity.setItemNoUpdate(0, STEALABLE.get(state).copy()); } diff --git a/common/src/main/java/common/ai/EntityAITarget.java b/common/src/common/ai/EntityAITarget.java similarity index 93% rename from common/src/main/java/common/ai/EntityAITarget.java rename to common/src/common/ai/EntityAITarget.java index fae31b0..58d7769 100755 --- a/common/src/main/java/common/ai/EntityAITarget.java +++ b/common/src/common/ai/EntityAITarget.java @@ -1,12 +1,14 @@ package common.ai; +import common.attributes.AttributeInstance; +import common.attributes.Attributes; import common.entity.types.EntityLiving; import common.entity.types.IEntityOwnable; +import common.init.Config; import common.pathfinding.PathEntity; import common.pathfinding.PathPoint; import common.util.BlockPos; import common.util.ExtMath; -import common.vars.Vars; public abstract class EntityAITarget extends EntityAIBase { @@ -97,7 +99,7 @@ public abstract class EntityAITarget extends EntityAIBase } } - return Vars.mobAttacks; + return Config.mobAttacks; } // } } @@ -105,7 +107,8 @@ public abstract class EntityAITarget extends EntityAIBase protected double getTargetDistance() { - return (double)this.taskOwner.getPathingRange(); + AttributeInstance iattributeinstance = this.taskOwner.getEntityAttribute(Attributes.FOLLOW_RANGE); + return iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue(); } /** @@ -143,7 +146,7 @@ public abstract class EntityAITarget extends EntityAIBase { return false; } - else if (!Vars.infight && target.getClass() == attacker.getClass()) + else if (!Config.infight && target.getClass() == attacker.getClass()) { return false; } @@ -171,7 +174,7 @@ public abstract class EntityAITarget extends EntityAIBase return false; // } } - else if (!Vars.mobAttacks) + else if (!Config.mobAttacks) { return false; } diff --git a/common/src/main/java/common/ai/EntityAITargetNonTamed.java b/common/src/common/ai/EntityAITargetNonTamed.java similarity index 100% rename from common/src/main/java/common/ai/EntityAITargetNonTamed.java rename to common/src/common/ai/EntityAITargetNonTamed.java diff --git a/common/src/main/java/common/ai/EntityAITasks.java b/common/src/common/ai/EntityAITasks.java similarity index 100% rename from common/src/main/java/common/ai/EntityAITasks.java rename to common/src/common/ai/EntityAITasks.java diff --git a/common/src/main/java/common/ai/EntityAITempt.java b/common/src/common/ai/EntityAITempt.java similarity index 100% rename from common/src/main/java/common/ai/EntityAITempt.java rename to common/src/common/ai/EntityAITempt.java diff --git a/common/src/main/java/common/ai/EntityAIWander.java b/common/src/common/ai/EntityAIWander.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIWander.java rename to common/src/common/ai/EntityAIWander.java diff --git a/common/src/main/java/common/ai/EntityAIWatchClosest.java b/common/src/common/ai/EntityAIWatchClosest.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIWatchClosest.java rename to common/src/common/ai/EntityAIWatchClosest.java diff --git a/common/src/main/java/common/ai/EntityAIWatchClosest2.java b/common/src/common/ai/EntityAIWatchClosest2.java similarity index 100% rename from common/src/main/java/common/ai/EntityAIWatchClosest2.java rename to common/src/common/ai/EntityAIWatchClosest2.java diff --git a/common/src/main/java/common/ai/EntityJumpHelper.java b/common/src/common/ai/EntityJumpHelper.java similarity index 100% rename from common/src/main/java/common/ai/EntityJumpHelper.java rename to common/src/common/ai/EntityJumpHelper.java diff --git a/common/src/main/java/common/ai/EntityLookHelper.java b/common/src/common/ai/EntityLookHelper.java similarity index 100% rename from common/src/main/java/common/ai/EntityLookHelper.java rename to common/src/common/ai/EntityLookHelper.java diff --git a/common/src/main/java/common/ai/EntityMoveHelper.java b/common/src/common/ai/EntityMoveHelper.java similarity index 95% rename from common/src/main/java/common/ai/EntityMoveHelper.java rename to common/src/common/ai/EntityMoveHelper.java index e5b5e08..74f4f40 100755 --- a/common/src/main/java/common/ai/EntityMoveHelper.java +++ b/common/src/common/ai/EntityMoveHelper.java @@ -1,5 +1,6 @@ package common.ai; +import common.attributes.Attributes; import common.entity.types.EntityLiving; import common.util.ExtMath; @@ -62,7 +63,7 @@ public class EntityMoveHelper { float f = (float)(ExtMath.atan2(d1, d0) * 180.0D / Math.PI) - 90.0F; this.entity.rotYaw = this.limitAngle(this.entity.rotYaw, f, 30.0F); - this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getMovementSpeed())); + this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getEntityAttribute(Attributes.MOVEMENT_SPEED).getAttributeValue())); if (d2 > 0.0D && d0 * d0 + d1 * d1 < 1.0D) { diff --git a/common/src/main/java/common/ai/EntitySenses.java b/common/src/common/ai/EntitySenses.java similarity index 100% rename from common/src/main/java/common/ai/EntitySenses.java rename to common/src/common/ai/EntitySenses.java diff --git a/common/src/main/java/common/ai/RandomPositionGenerator.java b/common/src/common/ai/RandomPositionGenerator.java similarity index 100% rename from common/src/main/java/common/ai/RandomPositionGenerator.java rename to common/src/common/ai/RandomPositionGenerator.java diff --git a/common/src/common/attributes/Attribute.java b/common/src/common/attributes/Attribute.java new file mode 100755 index 0000000..ed6c7e9 --- /dev/null +++ b/common/src/common/attributes/Attribute.java @@ -0,0 +1,84 @@ +package common.attributes; + +import java.util.Map; + +import common.collect.Maps; +import common.util.ExtMath; + +public class Attribute +{ + private static final Map ATTRIBUTES = Maps.newHashMap(); + + private final String name; + private final String display; + private final double defValue; + private final double minValue; + private final double maxValue; + private final boolean shouldWatch; + + public static Attribute getAttribute(String name) { + return ATTRIBUTES.get(name); + } + + public Attribute(String name, String display, double def, double min, double max, boolean watch) + { + this.name = name; + this.display = display; + this.defValue = def; + if(name == null) + throw new IllegalArgumentException("Name cannot be null!"); + this.minValue = min; + this.maxValue = max; + this.shouldWatch = watch; + + if (min > max) + { + throw new IllegalArgumentException("Minimum value cannot be bigger than maximum value!"); + } + else if (def < min) + { + throw new IllegalArgumentException("Default value cannot be lower than minimum value!"); + } + else if (def > max) + { + throw new IllegalArgumentException("Default value cannot be bigger than maximum value!"); + } + + ATTRIBUTES.put(name, this); + } + + public String getUnlocalizedName() + { + return this.name; + } + + public String getDisplayName() + { + return this.display; + } + + public double getDefaultValue() + { + return this.defValue; + } + + public boolean getShouldWatch() + { + return this.shouldWatch; + } + + public double clampValue(double value) + { + return ExtMath.clampd(value, this.minValue, this.maxValue); + } + + public int hashCode() + { + return this.name.hashCode(); + } + + public boolean equals(Object obj) + { + return obj instanceof Attribute && this.name.equals(((Attribute)obj).getUnlocalizedName()); + } +} diff --git a/common/src/common/attributes/AttributeInstance.java b/common/src/common/attributes/AttributeInstance.java new file mode 100755 index 0000000..299161b --- /dev/null +++ b/common/src/common/attributes/AttributeInstance.java @@ -0,0 +1,191 @@ +package common.attributes; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; + +import common.collect.Lists; +import common.collect.Maps; +import common.collect.Sets; + +public class AttributeInstance +{ + private final AttributeMap attributeMap; + private final Attribute genericAttribute; + private final Set additions = Sets.newHashSet(); + private final Set multipliers = Sets.newHashSet(); + private final Map> mapByName = Maps.>newHashMap(); + private final Map mapByID = Maps.newHashMap(); + private double baseValue; + private boolean needsUpdate = true; + private double cachedValue; + + public AttributeInstance(AttributeMap attributeMapIn, Attribute genericAttributeIn) + { + this.attributeMap = attributeMapIn; + this.genericAttribute = genericAttributeIn; + this.baseValue = genericAttributeIn.getDefaultValue(); + } + + public Attribute getAttribute() + { + return this.genericAttribute; + } + + public double getBaseValue() + { + return this.baseValue; + } + + public void setBaseValue(double baseValue) + { + if (baseValue != this.getBaseValue()) + { + this.baseValue = baseValue; + this.flagForUpdate(); + } + } + +// public Collection getModifiersByOperation(AttributeOp operation) +// { +// return (Collection)this.mapByOperation.get(operation); +// } + + public Collection getModifiers() + { + Set set = Sets.newHashSet(); + +// for (AttributeOp op : AttributeOp.values()) +// { +// set.addAll(this.getModifiersByOperation(op)); +// } + set.addAll(this.additions); + set.addAll(this.multipliers); + + return set; + } + + public AttributeModifier getModifier(long id) + { + return (AttributeModifier)this.mapByID.get(id); + } + + public boolean hasModifier(AttributeModifier modifier) + { + return this.mapByID.get(modifier.getID()) != null; + } + + public void applyModifier(AttributeModifier modifier) + { + if (this.getModifier(modifier.getID()) != null) + { + throw new IllegalArgumentException("Modifier is already applied on this attribute!"); + } + else + { + Set set = (Set)this.mapByName.get(modifier.getName()); + + if (set == null) + { + set = Sets.newHashSet(); + this.mapByName.put(modifier.getName(), set); + } + + (modifier.isMultiplied() ? this.multipliers : this.additions).add(modifier); + set.add(modifier); + this.mapByID.put(modifier.getID(), modifier); + this.flagForUpdate(); + } + } + + protected void flagForUpdate() + { + this.needsUpdate = true; + this.attributeMap.flagDirty(this); + } + + public void removeModifier(AttributeModifier modifier) + { +// for (AttributeOp op : AttributeOp.values()) +// { +// Set set = (Set)this.mapByOperation.get(op); +// set.remove(modifier); +// } + this.additions.remove(modifier); + this.multipliers.remove(modifier); + + Set set1 = (Set)this.mapByName.get(modifier.getName()); + + if (set1 != null) + { + set1.remove(modifier); + + if (set1.isEmpty()) + { + this.mapByName.remove(modifier.getName()); + } + } + + this.mapByID.remove(modifier.getID()); + this.flagForUpdate(); + } + + public void removeAllModifiers() + { + Collection collection = this.getModifiers(); + + if (collection != null) + { + for (AttributeModifier attributemodifier : Lists.newArrayList(collection)) + { + this.removeModifier(attributemodifier); + } + } + } + + public double getAttributeValue() + { + if (this.needsUpdate) + { + this.cachedValue = this.computeValue(); + this.needsUpdate = false; + } + + return this.cachedValue; + } + + private double computeValue() + { + double base = this.getBaseValue(); + + for (AttributeModifier attributemodifier : this.additions) + { + base += attributemodifier.getAmount(); + } + + for (AttributeModifier attributemodifier2 : this.multipliers) + { + base *= 1.0D + attributemodifier2.getAmount(); + } + + return this.genericAttribute.clampValue(base); + } + +// private Collection getModifierList(AttributeOp operation) +// { +// // Set set = +// return Sets.newHashSet(this.getModifiersByOperation(operation)); +// +//// for (BaseAttribute iattribute = this.genericAttribute.func_180372_d(); iattribute != null; iattribute = iattribute.func_180372_d()) +//// { +//// ModifiableAttributeInstance iattributeinstance = this.attributeMap.getAttributeInstance(iattribute); +//// +//// if (iattributeinstance != null) +//// { +//// set.addAll(iattributeinstance.getModifiersByOperation(operation)); +//// } +//// } +// +// // return set; +// } +} diff --git a/common/src/common/attributes/AttributeMap.java b/common/src/common/attributes/AttributeMap.java new file mode 100755 index 0000000..c859fd3 --- /dev/null +++ b/common/src/common/attributes/AttributeMap.java @@ -0,0 +1,163 @@ +package common.attributes; + +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; + +import common.collect.Maps; +import common.collect.Sets; +import common.util.LowerStringMap; + +import java.util.Set; + +public class AttributeMap +{ + protected final Map attributes = Maps.newHashMap(); + protected final Map nameMap = new LowerStringMap(); + private final Set dirtyAttributes; + + public AttributeMap(boolean client) { + this.dirtyAttributes = client ? null : Sets.newHashSet(); + } + + public AttributeInstance getAttributeInstance(Attribute attribute) + { + return (AttributeInstance)this.attributes.get(attribute); + } + + public AttributeInstance getAttributeInstanceByName(String attributeName) + { +// AttributeInstance iattributeinstance = + return (AttributeInstance)this.nameMap.get(attributeName); + +// if (iattributeinstance == null) +// { +// iattributeinstance = (AttributeInstance)this.descMap.get(attributeName); +// } +// +// return (AttributeInstance)iattributeinstance; + } + + public AttributeInstance registerAttribute(Attribute attribute) + { + if(this.nameMap.containsKey(attribute.getUnlocalizedName())) + throw new IllegalArgumentException("Attribute is already registered!"); + AttributeInstance inst = new AttributeInstance(this, attribute); + this.nameMap.put(attribute.getUnlocalizedName(), inst); + this.attributes.put(attribute, inst); +// for (BaseAttribute iattribute = attribute.func_180372_d(); iattribute != null; iattribute = iattribute.func_180372_d()) +// { +// this.field_180377_c.put(iattribute, attribute); +// } +// if(attribute.getDescription() != null) +// this.descMap.put(attribute.getDescription(), inst); + return inst; + } + + public Collection getAllAttributes() + { + return this.nameMap.values(); + } + + public void flagDirty(AttributeInstance instance) + { + if (this.dirtyAttributes != null && instance.getAttribute().getShouldWatch()) + { + this.dirtyAttributes.add(instance); + } + +// for (BaseAttribute iattribute : this.field_180377_c.get(instance.getAttribute())) +// { +// ModifiableAttributeInstance modifiableattributeinstance = this.getAttributeInstance(iattribute); +// +// if (modifiableattributeinstance != null) +// { +// modifiableattributeinstance.flagForUpdate(); +// } +// } + } + + public Set getDirty() + { + return this.dirtyAttributes; + } + + public Collection getWatchedAttributes() + { + Set set = Sets.newHashSet(); + + for (AttributeInstance iattributeinstance : this.getAllAttributes()) + { + if (iattributeinstance.getAttribute().getShouldWatch()) + { + set.add(iattributeinstance); + } + } + + return set; + } + + public void removeAttributeModifiers(Map> modifiers) + { + for (Entry> entry : modifiers.entrySet()) + { + AttributeInstance iattributeinstance = this.getAttributeInstanceByName(entry.getKey().getUnlocalizedName()); + + if (iattributeinstance != null) + { + for(AttributeModifier mod : entry.getValue()) { + iattributeinstance.removeModifier(mod); + } + } + } + } + + public void applyAttributeModifiers(Map> modifiers) + { + for (Entry> entry : modifiers.entrySet()) + { + AttributeInstance iattributeinstance = this.getAttributeInstanceByName(entry.getKey().getUnlocalizedName()); + + if (iattributeinstance != null) + { + for(AttributeModifier mod : entry.getValue()) { + iattributeinstance.removeModifier(mod); + iattributeinstance.applyModifier(mod); + } + } + } + } + + public void removeAttributeModifiers(Map> modifiers, int slot, int amount) + { + for (Entry> entry : modifiers.entrySet()) + { + AttributeInstance iattributeinstance = this.getAttributeInstanceByName(entry.getKey().getUnlocalizedName()); + + if (iattributeinstance != null) + { + for(AttributeModifier mod : entry.getValue()) { + AttributeModifier nmod = new AttributeModifier(mod, slot+1, amount); + iattributeinstance.removeModifier(nmod); + } + } + } + } + + public void applyAttributeModifiers(Map> modifiers, int slot, int amount) + { + for (Entry> entry : modifiers.entrySet()) + { + AttributeInstance iattributeinstance = this.getAttributeInstanceByName(entry.getKey().getUnlocalizedName()); + + if (iattributeinstance != null) + { + for(AttributeModifier mod : entry.getValue()) { + AttributeModifier nmod = new AttributeModifier(mod, slot+1, amount); + iattributeinstance.removeModifier(nmod); + iattributeinstance.applyModifier(nmod); + } + } + } + } +} diff --git a/common/src/common/attributes/AttributeModifier.java b/common/src/common/attributes/AttributeModifier.java new file mode 100755 index 0000000..ba4d937 --- /dev/null +++ b/common/src/common/attributes/AttributeModifier.java @@ -0,0 +1,134 @@ +package common.attributes; + +import common.rng.Random; + +public class AttributeModifier +{ + private final double amount; + private final boolean multiply; + private final String name; + private final long id; + private final boolean isSaved; + private final boolean inventory; + + public static long getModifierId(String name) { + if(name.length() > 7) + throw new IllegalArgumentException("Name darf höchstens 7 Zeichen enthalten"); + long id = '@'; + for(int z = 0; z < name.length(); z++) { + id <<= 8; + char c = name.charAt(z); + if(c > 0xff) + throw new IllegalArgumentException("Name darf keine 16-Bit-Zeichen enthalten"); + id |= (long)c; + } +// Log.CONFIG.debug(String.format("Modifikator '%s' -> 0x%016x", name, id)); + return id; + } + + public AttributeModifier(String nameIn, double amountIn, boolean multiplyIn) + { + this(new Random().longv() | 0x8000000000000000L, nameIn, amountIn, multiplyIn, true, false); + } + + public AttributeModifier(long idIn, String nameIn, double amountIn, boolean multiplyIn) { + this(idIn, nameIn, amountIn, multiplyIn, true, false); + } + + public AttributeModifier(long idIn, String nameIn, double amountIn, boolean multiplyIn, boolean saved) { + this(idIn, nameIn, amountIn, multiplyIn, saved, false); + } + + public AttributeModifier(long idIn, String nameIn, double amountIn, boolean multiplyIn, boolean saved, boolean inv) + { + this.isSaved = saved; + this.inventory = inv; + this.id = idIn; + this.name = nameIn; + this.amount = amountIn; + this.multiply = multiplyIn; + if (nameIn == null) { + throw new NullPointerException("Modifier name cannot be empty"); + } + else if (nameIn.length() == 0) { + throw new IllegalArgumentException("Modifier name cannot be empty"); + } +// else if (operationIn == null) { +// throw new IllegalArgumentException("Invalid operation"); +// } + } + + public AttributeModifier(AttributeModifier attr, int slot, int amount) { + this(attr.id + (long)slot, attr.name, attr.amount * (double)amount, attr.multiply, attr.isSaved); + } + + public long getID() + { + return this.id; + } + + public String getName() + { + return this.name; + } + + public boolean isMultiplied() + { + return this.multiply; + } + + public double getAmount() + { + return this.amount; + } + + public boolean isSaved() + { + return this.isSaved; + } + + public boolean isInventory() + { + return this.inventory; + } + + public boolean equals(Object obj) + { + if (this == obj) + { + return true; + } + else if (obj != null && this.getClass() == obj.getClass()) + { + AttributeModifier attributemodifier = (AttributeModifier)obj; + + if (this.id != 0L) + { + if (this.id != attributemodifier.id) + { + return false; + } + } + else if (attributemodifier.id != 0L) + { + return false; + } + + return true; + } + else + { + return false; + } + } + + public int hashCode() + { + return this.id != 0L ? Long.hashCode(this.id) : 0; + } + + public String toString() + { + return "AttributeModifier{amount=" + this.amount + ", multiply=" + this.multiply + ", name=\'" + this.name + '\'' + ", id=" + this.id + ", serialize=" + this.isSaved + '}'; + } +} diff --git a/common/src/common/attributes/Attributes.java b/common/src/common/attributes/Attributes.java new file mode 100755 index 0000000..6a1ccc6 --- /dev/null +++ b/common/src/common/attributes/Attributes.java @@ -0,0 +1,161 @@ +package common.attributes; + +import java.util.Collection; + +import common.log.Log; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; + +public class Attributes +{ + public static final Attribute MAX_HEALTH = (new Attribute("generic.maxHealth", "Maximale Gesundheit", 20.0D, 0.0D, 1024.0D, true)); + public static final Attribute FOLLOW_RANGE = (new Attribute("generic.followRange", "Kreaturen-Folgedistanz", 32.0D, 0.0D, 2048.0D, false)); + public static final Attribute KNOCKBACK_RESISTANCE = (new Attribute("generic.knockbackResistance", "Standfestigkeit", 0.0D, 0.0D, 1.0D, false)); + public static final Attribute MOVEMENT_SPEED = (new Attribute("generic.movementSpeed", "Geschwindigkeit", 0.699999988079071D, 0.0D, 1024.0D, true)); + public static final Attribute ATTACK_DAMAGE = new Attribute("generic.attackDamage", "Angriffsschaden", 2.0D, 0.0D, 2048.0D, false); + public static final Attribute RADIATION = new Attribute("generic.radiation", "Strahlung", 0.0D, 0.0D, 16384.0D, false); + public static final Attribute RADIATION_RESISTANCE = new Attribute("generic.radiationResistance", "Strahlungsresistenz", 10.0D, 0.0D, 16384.0D, false); + public static final Attribute MANA_CAPACITY = new Attribute("generic.manaCapacity", "Mana-Kapazität", 0.0D, 0.0D, 2048.0D, false); + public static final Attribute MAGIC_RESISTANCE = new Attribute("generic.magicResistance", "Magieresistenz", 0.0D, 0.0D, 4096.0D, false); + public static final Attribute REINFORCEMENT_CHANCE = (new Attribute("zombie.spawnReinforcements", "Zombie-Verstärkung", 0.0D, 0.0D, 1.0D, false)); + public static final Attribute HORSE_JUMP_STRENGTH = (new Attribute("horse.jumpStrength", "Pferdesprungstärke", 0.7D, 0.0D, 2.0D, true)); + +// public static final long ATTACK_SPEED_ID = AttributeModifier.getModifierId("EnderSp"); +// public static final AttributeModifier ATTACK_SPEED_MOD = (new AttributeModifier(ATTACK_SPEED_ID, "Attacking speed boost", 0.15000000596046448D, false, false)); + public static final long RUSHING_SPEED_ID = AttributeModifier.getModifierId("RushSpd"); + public static final AttributeModifier RUSHING_SPEED_MOD = (new AttributeModifier(RUSHING_SPEED_ID, "Attacking speed boost", 0.05D, false, false)); + public static final long MAGE_POTSPEED_ID = AttributeModifier.getModifierId("MagePot"); + public static final AttributeModifier MAGE_POTSPEED_MOD = (new AttributeModifier(MAGE_POTSPEED_ID, "Drinking speed penalty", -0.25D, false, false)); + public static final long ZOMBIE_BABY_ID = AttributeModifier.getModifierId("ZombSpd"); + public static final AttributeModifier ZOMBIE_BABY_MOD = new AttributeModifier(ZOMBIE_BABY_ID, "Baby speed boost", 0.5D, true); + public static final long FLEEING_SPEED_ID = AttributeModifier.getModifierId("FleeSpd"); + public static final AttributeModifier FLEEING_SPEED_MOD = (new AttributeModifier(FLEEING_SPEED_ID, "Fleeing speed bonus", 2.0D, true, false)); + public static final long SPRINT_SPEED_ID = AttributeModifier.getModifierId("Sprint"); + public static final AttributeModifier SPRINT_SPEED_MOD = (new AttributeModifier(SPRINT_SPEED_ID, "Sprinting speed boost", 0.30000001192092896D, true, false)); + public static final long ITEM_VAL_ID = AttributeModifier.getModifierId("ItemVal"); + public static final long RADIATION_BASE = AttributeModifier.getModifierId("NukeVal"); + public static final long MOUSE_SPEEDY_ID = AttributeModifier.getModifierId("SpeedyG"); + public static final AttributeModifier MOUSE_SPEEDY_MOD = new AttributeModifier(MOUSE_SPEEDY_ID, "Mouse speed boost", 1.0D, true); + + /** + * Creates an NBTTagList from a BaseAttributeMap, including all its AttributeInstances + */ + public static NBTTagList writeBaseAttributeMapToNBT(AttributeMap map) + { + NBTTagList nbttaglist = new NBTTagList(); + + for (AttributeInstance iattributeinstance : map.getAllAttributes()) + { + nbttaglist.appendTag(writeAttributeInstanceToNBT(iattributeinstance)); + } + + return nbttaglist; + } + + /** + * Creates an NBTTagCompound from an AttributeInstance, including its AttributeModifiers + */ + private static NBTTagCompound writeAttributeInstanceToNBT(AttributeInstance instance) + { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + Attribute iattribute = instance.getAttribute(); + nbttagcompound.setString("Name", iattribute.getUnlocalizedName()); + nbttagcompound.setDouble("Base", instance.getBaseValue()); + Collection collection = instance.getModifiers(); + + if (collection != null && !collection.isEmpty()) + { + NBTTagList nbttaglist = new NBTTagList(); + + for (AttributeModifier attributemodifier : collection) + { + if (attributemodifier.isSaved()) + { + nbttaglist.appendTag(writeAttributeModifierToNBT(attributemodifier)); + } + } + + nbttagcompound.setTag("Modifiers", nbttaglist); + } + + return nbttagcompound; + } + + /** + * Creates an NBTTagCompound from an AttributeModifier + */ + private static NBTTagCompound writeAttributeModifierToNBT(AttributeModifier modifier) + { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setString("Name", modifier.getName()); + nbttagcompound.setDouble("Amount", modifier.getAmount()); + nbttagcompound.setBoolean("Multiply", modifier.isMultiplied()); + nbttagcompound.setLong("AttrId", modifier.getID()); + return nbttagcompound; + } + + public static void setAttributeModifiers(AttributeMap map, NBTTagList list) + { + for (int i = 0; i < list.tagCount(); ++i) + { + NBTTagCompound nbttagcompound = list.getCompoundTagAt(i); + AttributeInstance iattributeinstance = map.getAttributeInstanceByName(nbttagcompound.getString("Name")); + + if (iattributeinstance != null) + { + applyModifiersToAttributeInstance(iattributeinstance, nbttagcompound); + } + else + { + Log.JNI.warn("Ignoriere unbekannte Attribute \'" + nbttagcompound.getString("Name") + "\'"); + } + } + } + + private static void applyModifiersToAttributeInstance(AttributeInstance instance, NBTTagCompound compound) + { + instance.setBaseValue(compound.getDouble("Base")); + + if (compound.hasKey("Modifiers", 9)) + { + NBTTagList nbttaglist = compound.getTagList("Modifiers", 10); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) + { + AttributeModifier attributemodifier = readAttributeModifierFromNBT(nbttaglist.getCompoundTagAt(i)); + + if (attributemodifier != null) + { + AttributeModifier attributemodifier1 = instance.getModifier(attributemodifier.getID()); + + if (attributemodifier1 != null) + { + instance.removeModifier(attributemodifier1); + } + + instance.applyModifier(attributemodifier); + } + } + } + } + + /** + * Creates an AttributeModifier from an NBTTagCompound + */ + public static AttributeModifier readAttributeModifierFromNBT(NBTTagCompound compound) + { + long id = compound.getLong("AttrId"); + if(id == 0L) + return null; + + try + { + return new AttributeModifier(id, compound.getString("Name"), compound.getDouble("Amount"), compound.getBoolean("Multiply")); + } + catch (Exception exception) + { + Log.JNI.warn("Konnte Attribute nicht erstellen: " + exception.getMessage()); + return null; + } + } +} diff --git a/common/src/main/java/common/biome/Biome.java b/common/src/common/biome/Biome.java similarity index 66% rename from common/src/main/java/common/biome/Biome.java rename to common/src/common/biome/Biome.java index 92a4d66..935453e 100644 --- a/common/src/main/java/common/biome/Biome.java +++ b/common/src/common/biome/Biome.java @@ -5,12 +5,10 @@ import java.util.Map; import common.collect.Lists; import common.collect.Maps; -import common.color.Colorizer; import common.log.Log; import common.rng.PerlinGen; import common.rng.Random; import common.util.BlockPos; -import common.util.ExtMath; public enum Biome { NONE(0, "none", "", 0x000000), @@ -19,16 +17,16 @@ public enum Biome { EXTREMEHILLS(3, "extremeHills", "Extremes Bergland", 0x606060, -12.0f, 30.0f), FOREST(4, "forest", "Wald", 0x056621, 8.0f, 80.0f), TAIGA(5, "taiga", "Taiga", 0x0b6659, -10.0f, 80.0f), - SWAMPLAND(6, "swampland", "Sumpf", 0x07f9b2, 12.0f, 90.0f, 0xe0ffae, 0xffffffff, 6975545), + SWAMPLAND(6, "swampland", "Sumpf", 0x07f9b2, 12.0f, 90.0f), RIVER(7, "river", "Fluss", 0x0000ff), - EXTERMINATED(8, "exterminated", "Ausgelöscht", 0x000000, 150.0f, 0.0f, 0x202020, 0x303030, 0x303030, 0x101010, 0x303030, 0x000000), + EXTERMINATED(8, "exterminated", "Ausgelöscht", 0x000000, 150.0f, 0.0f), SPACE(9, "space", "Leere des Weltraums", 0x000000, 0.0f, 0.0f), FROZENSEA(10, "frozenSea", "Vereister See", 0x9090a0, -20.0f), FROZENRIVER(11, "frozenRiver", "Vereister Fluss", 0xa0a0ff, -20.0f), ICEPLAINS(12, "icePlains", "Eisebene", 0xffffff, -20.0f), ICEMOUNTAINS(13, "iceMountains", "Vereistes Bergland", 0xa0a0a0, -20.0f), MUSHROOMPLAINS(14, "mushroomPlains", "Pilzland", 0xff00ff, 16.0f, 100.0f), - BLACKENED(15, "blackened", "Schwarz", 0x000000, 0.0f, 0.0f, 0x000000, 0x303030, 0x303030), + BLACKENED(15, "blackened", "Schwarz", 0x000000, 0.0f, 0.0f), BEACH(16, "beach", "Strand", 0xfade55, 12.0f, 40.0f), DESERTHILLS(17, "desertHills", "Wüsten-Bergland", 0xd25f12, 60.0f, 0.0f), FORESTHILLS(18, "forestHills", "Wald-Bergland", 0x22551c, 8.0f, 80.0f), @@ -50,17 +48,17 @@ public enum Biome { EXTREMEHILLSPLUS(34, "extremeHillsPlus", "Extremes Bergland +", 0x507050, -12.0f, 30.0f), SAVANNA(35, "savanna", "Savanne", 0xbdb25f, 28.0f, 0.0f), SAVANNAPLATEAU(36, "savannaPlateau", "Savannen-Plateau", 0xa79d64, 20.0f, 0.0f), - MESA(37, "mesa", "Mesa", 0xd94515, 0.0f, 0.0f, 0xffffff, 9470285, 10387789), - MESAPLATEAUF(38, "mesaPlateauF", "Mesa-Waldplateau", 0xb09765, 0.0f, 0.0f, 0xffffff, 9470285, 10387789), - MESAPLATEAU(39, "mesaPlateau", "Mesa-Plateau", 0xca8c65, 0.0f, 0.0f, 0xffffff, 9470285, 10387789), + MESA(37, "mesa", "Mesa", 0xd94515, 0.0f, 0.0f), + MESAPLATEAUF(38, "mesaPlateauF", "Mesa-Waldplateau", 0xb09765, 0.0f, 0.0f), + MESAPLATEAU(39, "mesaPlateau", "Mesa-Plateau", 0xca8c65, 0.0f, 0.0f), SNOWLAND(40, "snowLand", "Eisland", 0xffffff, 0.0f, 100.0f), TIAN(41, "tian", "Tian", 0x808080, 0.0f, 80.0f), ELVENFOREST(42, "elvenForest", "Elbenwald", 0x059821, 8.0f, 90.0f), - UPPERHELL(43, "upperHell", "Übergang in die Hölle", 0xff0000, 0.0f, 0.0f, 0x000000, 0x000000, 0x000000), - LOWERHELL(44, "lowerHell", "Abgrund der Hölle", 0xff0000, 0.0f, 0.0f, 0x000000, 0x000000, 0x000000), - HELLHILLS(45, "hellHills", "Bergland der Hölle", 0xff0000, 0.0f, 0.0f, 0x000000, 0x000000, 0x000000), - SOULPLAINS(46, "soulPlains", "Seelenland", 0xff0000, 0.0f, 0.0f, 0x000000, 0x000000, 0x000000), - ASHLAND(47, "ashLand", "Verbrannt", 0xff0000, 0.0f, 0.0f, 0x000000, 0x000000, 0x000000), + UPPERHELL(43, "upperHell", "Übergang in die Hölle", 0xff0000, 0.0f, 0.0f), + LOWERHELL(44, "lowerHell", "Abgrund der Hölle", 0xff0000, 0.0f, 0.0f), + HELLHILLS(45, "hellHills", "Bergland der Hölle", 0xff0000, 0.0f, 0.0f), + SOULPLAINS(46, "soulPlains", "Seelenland", 0xff0000, 0.0f, 0.0f), + ASHLAND(47, "ashLand", "Verbrannt", 0xff0000, 0.0f, 0.0f), MOON(48, "moon", "Mondoberfläche", 0xa0a0a0, 0.0f, 0.0f), CHAOS(49, "chaos", "Chaos", 0xff00ff), @@ -68,7 +66,7 @@ public enum Biome { EXTREMEHILLSM(131, "extremeHillsM", "Extremes Bergland M", 0x606060, -12.0f, 30.0f), FLOWERFOREST(132, "flowerForest", "Blumenwald", 0x6a7425, 8.0f, 80.0f), TAIGAM(133, "taigaM", "Taiga M", 0x0b6659, -10.0f, 80.0f), - SWAMPLANDM(134, "swamplandM", "Sumpf M", 0x07f9b2, 12.0f, 90.0f, 0xe0ffae, 0xffffffff, 6975545), + SWAMPLANDM(134, "swamplandM", "Sumpf M", 0x07f9b2, 12.0f, 90.0f), ICEPLAINSSPIKES(140, "icePlainsSpikes", "Eisebene + Spitzen", 0xd2ffff, -20.0f), JUNGLEM(149, "jungleM", "Urwald M", 0x537b09, 18.0f, 90.0f), JUNGLEEDGEM(151, "jungleEdgeM", "Urwald Gr. M", 0x628b17, 18.0f, 80.0f), @@ -81,28 +79,20 @@ public enum Biome { EXTREMEHILLSPLUSM(162, "extremeHillsPlusM", "Extremes Bergland + M", 0x507050, -12.0f, 30.0f), SAVANNAM(163, "savannaM", "Savanne M", 0xbdb25f, 24.0f, 0.0f), SAVANNAPLATEAUM(164, "savannaPlateauM", "Savannen-Plateau M", 0xa79d64, 20.0f, 0.0f), - MESABRYCE(165, "mesaBryce", "Mesa (Bryce)", 0xd94515, 0.0f, 0.0f, 0xffffff, 9470285, 10387789), - MESAPLATEAUFM(166, "mesaPlateauFM", "Mesa-Waldplateau M", 0xb09765, 0.0f, 0.0f, 0xffffff, 9470285, 10387789), - MESAPLATEAUM(167, "mesaPlateauM", "Mesa-Plateau M", 0xca8c65, 0.0f, 0.0f, 0xffffff, 9470285, 10387789); + MESABRYCE(165, "mesaBryce", "Mesa (Bryce)", 0xd94515, 0.0f, 0.0f), + MESAPLATEAUFM(166, "mesaPlateauFM", "Mesa-Waldplateau M", 0xb09765, 0.0f, 0.0f), + MESAPLATEAUM(167, "mesaPlateauM", "Mesa-Plateau M", 0xca8c65, 0.0f, 0.0f); public static final Biome DEF_BIOME = FOREST; private static final PerlinGen TEMP_NOISE = new PerlinGen(new Random(836430928262265276L), 1); - private static final PerlinGen COLOR_NOISE = new PerlinGen(new Random(6549321755809421L), 1); private static final Biome[] BIOMES = new Biome[256]; private static final Map LOOKUP = Maps.newTreeMap(); public final int id; public final String name; public final String display; - public final int color; public final float temperature; public final float humidity; - public final int waterColor; - public final int grassColor; - public final int foliageColor; - public final int skyColor; - public final int fogColor; - public final int cloudColor; static { for(Biome biome : values()) { @@ -121,7 +111,7 @@ public enum Biome { } else { - Log.TICK.warn("Biom-ID ist nicht im Bereich: " + id + ", verwende " + DEF_BIOME.id + " (" + DEF_BIOME.name + ")"); + Log.JNI.warn("Biom-ID ist nicht im Bereich: " + id + ", verwende " + DEF_BIOME.id + " (" + DEF_BIOME.name + ")"); return DEF_BIOME; } } @@ -135,7 +125,7 @@ public enum Biome { } else { - Log.TICK.warn("Biom-ID ist nicht im Bereich: " + id + ", verwende " + DEF_BIOME.id + " (" + DEF_BIOME.name + ")"); + Log.JNI.warn("Biom-ID ist nicht im Bereich: " + id + ", verwende " + DEF_BIOME.id + " (" + DEF_BIOME.name + ")"); return DEF_BIOME; } } @@ -159,35 +149,20 @@ public enum Biome { return biome; } - private Biome(int id, String name, String display, int color, float temperature, float humidity, int waterColor, int grassColor, int foliageColor, int skyColor, int fogColor, int cloudColor) { + private Biome(int id, String name, String display, int color, float temperature, float humidity) { this.id = id; this.name = name; this.display = display; this.temperature = temperature; this.humidity = humidity; - this.color = color; - this.waterColor = waterColor; - this.grassColor = grassColor; - this.foliageColor = foliageColor; - this.skyColor = skyColor; - this.fogColor = fogColor; - this.cloudColor = cloudColor; } - - private Biome(int id, String name, String display, int color, float temperature, float humidity, int waterColor, int grassColor, int foliageColor) { - this(id, name, display, color, temperature, humidity, waterColor, grassColor, foliageColor, 0xffffffff, 0xffffffff, 0xffffffff); - } - - private Biome(int id, String name, String display, int color, float temperature, float humidity) { - this(id, name, display, color, temperature, humidity, 0xffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff); - } - + private Biome(int id, String name, String display, int color, float temperature) { - this(id, name, display, color, temperature, 50.0f, 0xffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff); + this(id, name, display, color, temperature, 50.0f); } private Biome(int id, String name, String display, int color) { - this(id, name, display, color, 0.0f, 50.0f, 0xffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff); + this(id, name, display, color, 0.0f, 50.0f); } public final float getTemperature(BlockPos pos) { @@ -206,30 +181,4 @@ public enum Biome { public boolean isHighHumidity() { return this.humidity > 85.0f; } - - // skycolor = ((temp + 14) / 40 + 0.15) / 3 - - public int getGrassColorAtPos(BlockPos pos) { - if(this.grassColor != 0xffffffff) - return this.grassColor; - if(this == SWAMPLAND || this == SWAMPLANDM) { - double d0 = COLOR_NOISE.generate((double)pos.getX() * 0.0225D, (double)pos.getZ() * 0.0225D); - return d0 < -0.1D ? 5011004 : 6975545; - } - if(this == ELVENFOREST) - return Colorizer.getGrassColor(1.0f, this.humidity * 0.01f); - double d0 = (double)ExtMath.clampf((this.getTemperature(pos) + 14.0f) / 40.0f + 0.15f, 0.0F, 1.0F); - double d1 = (double)ExtMath.clampf(this.humidity * 0.01f, 0.0F, 1.0F); - return this == ROOFEDFOREST || this == ROOFEDFORESTM ? (Colorizer.getGrassColor(d0, d1) & 16711422) + 2634762 >> 1 : Colorizer.getGrassColor(d0, d1); - } - - public int getFoliageColorAtPos(BlockPos pos) { - if(this.foliageColor != 0xffffffff) - return this.foliageColor; - if(this == ELVENFOREST) - return Colorizer.getFoliageColor(1.0f, this.humidity * 0.01f); - double d0 = (double)ExtMath.clampf((this.getTemperature(pos) + 14.0f) / 40.0f + 0.15f, 0.0F, 1.0F); - double d1 = (double)ExtMath.clampf(this.humidity * 0.01f, 0.0F, 1.0F); - return Colorizer.getFoliageColor(d0, d1); - } } diff --git a/common/src/main/java/common/biome/IBiome.java b/common/src/common/biome/IBiome.java similarity index 100% rename from common/src/main/java/common/biome/IBiome.java rename to common/src/common/biome/IBiome.java diff --git a/common/src/common/block/Block.java b/common/src/common/block/Block.java new file mode 100755 index 0000000..d1c321a --- /dev/null +++ b/common/src/common/block/Block.java @@ -0,0 +1,1446 @@ +package common.block; + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.Function; + +import common.collect.ImmutableList; +import common.collect.ImmutableMap; +import common.collect.Iterables; +import common.collect.Lists; +import common.collect.Maps; +import common.collect.UnmodifiableIterator; +import common.enchantment.EnchantmentHelper; +import common.entity.Entity; +import common.entity.item.EntityItem; +import common.entity.item.EntityXp; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Config; +import common.init.ItemRegistry; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.material.Material; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.properties.IProperty; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Facing; +import common.util.HitPosition; +import common.util.Vec3; +import common.util.HitPosition.ObjectType; +import common.world.Explosion; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; + +public class Block +{ + private static class Product implements Iterable + { + private final Class clazz; + private final Iterable [] iterables; + + private Product(Class clazz, Iterable [] iterables) + { + this.clazz = clazz; + this.iterables = iterables; + } + + public Iterator iterator() + { + return (Iterator)(this.iterables.length <= 0 ? Collections.singletonList((Object[])createArray(this.clazz, 0)).iterator() : new Product.ProductIterator(this.clazz, this.iterables)); + } + + static class ProductIterator extends UnmodifiableIterator + { + private int index; + private final Iterable [] iterables; + private final Iterator [] iterators; + private final T[] results; + + private ProductIterator(Class clazz, Iterable [] iterables) + { + this.index = -2; + this.iterables = iterables; + this.iterators = (Iterator[])createArray(Iterator.class, this.iterables.length); + + for (int i = 0; i < this.iterables.length; ++i) + { + this.iterators[i] = iterables[i].iterator(); + } + + this.results = createArray(clazz, this.iterators.length); + } + + private void endOfData() + { + this.index = -1; + Arrays.fill(this.iterators, (Object)null); + Arrays.fill(this.results, (Object)null); + } + + public boolean hasNext() + { + if (this.index == -2) + { + this.index = 0; + + for (Iterator iterator1 : this.iterators) + { + if (!iterator1.hasNext()) + { + this.endOfData(); + break; + } + } + + return true; + } + else + { + if (this.index >= this.iterators.length) + { + for (this.index = this.iterators.length - 1; this.index >= 0; --this.index) + { + Iterator iterator = this.iterators[this.index]; + + if (iterator.hasNext()) + { + break; + } + + if (this.index == 0) + { + this.endOfData(); + break; + } + + iterator = this.iterables[this.index].iterator(); + this.iterators[this.index] = iterator; + + if (!iterator.hasNext()) + { + this.endOfData(); + break; + } + } + } + + return this.index >= 0; + } + } + + public T[] next() + { + if (!this.hasNext()) + { + throw new NoSuchElementException(); + } + else + { + while (this.index < this.iterators.length) + { + this.results[this.index] = this.iterators[this.index].next(); + ++this.index; + } + + return (T[])((Object[])this.results.clone()); + } + } + } + } + + private static class GetList implements Function> + { + private GetList() + { + } + + public List apply(Object[] p_apply_1_) + { + return Arrays.asList((T[])p_apply_1_); + } + } + + private final ImmutableList properties; + private final ImmutableList states; + protected final Material material; + + protected boolean fullBlock; + protected boolean translucent; + protected boolean sumBrightness; + protected boolean axeHarvest; + protected boolean shovelHarvest; +// protected boolean enableStats; + protected boolean ticked; + protected boolean hasTile; + protected int lightOpacity; + protected int lightValue; + protected int miningLevel; + protected int shearsEfficiency; + protected float blockHardness; + protected float blockResistance; + protected float radiation; + public float slipperiness; + protected double minX; + protected double minY; + protected double minZ; + protected double maxX; + protected double maxY; + protected double maxZ; + private State defaultState; + private String display; + private CheatTab tab; + public SoundType sound; + + private static Iterable> cartesianProduct(Iterable > sets) + { + return arraysAsLists(cartesianProduct(Object.class, sets)); + } + + private static Iterable cartesianProduct(Class clazz, Iterable > sets) + { + return new Product(clazz, (Iterable[])toArray(Iterable.class, sets)); + } + + private static Iterable> arraysAsLists(Iterable arrays) + { + return Iterables.transform(arrays, new GetList()); + } + + private static T[] toArray(Class clazz, Iterable it) + { + List list = Lists.newArrayList(); + + for (T t : it) + { + list.add(t); + } + + return (T[])((Object[])list.toArray(createArray(clazz, list.size()))); + } + + private static T[] createArray(Class p_179319_0_, int p_179319_1_) + { + return (T[])((Object[])((Object[])Array.newInstance(p_179319_0_, p_179319_1_))); + } + + private static Map createMap(Iterable keys, Iterable values) + { + return populateMap(keys, values, Maps.newLinkedHashMap()); + } + + private static Map populateMap(Iterable keys, Iterable values, Map map) + { + Iterator iterator = values.iterator(); + + for (IProperty k : keys) + { + map.put(k, iterator.next()); + } + + if (iterator.hasNext()) + { + throw new NoSuchElementException(); + } + else + { + return map; + } + } + + public Block(Material material) + { + this.miningLevel = (material == Material.rock || material == Material.iron || material == Material.anvil) ? 0 : -1; + this.axeHarvest = material == Material.wood || material == Material.plants || material == Material.vine || + material == Material.gourd; + this.shearsEfficiency = (material == Material.leaves || material == Material.web) ? 3 : -1; +// this.enableStats = true; + this.sound = SoundType.STONE; + this.slipperiness = 0.6F; + this.material = material; +// this.blockMapColor = blockMapColorIn; + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + this.fullBlock = this.isOpaqueCube(); + this.lightOpacity = this.isOpaqueCube() ? 255 : 0; + this.translucent = !material.blocksLight(); +// this.smap = new StateList(this, this.getProperties()); + IProperty[] properties = this.getProperties(); + Arrays.sort(properties, new Comparator() { + public int compare(IProperty p1, IProperty p2) { + return p1.getName().compareTo(p2.getName()); + } + }); + this.properties = ImmutableList.copyOf(properties); + Map, State> map = Maps., State>newLinkedHashMap(); + List list = Lists.newArrayList(); + for(List allowed : cartesianProduct(this.getAllowedValues())) { + Map props = createMap(this.properties, allowed); + State state = new State(this, ImmutableMap.copyOf(props)); + map.put(props, state); + list.add(state); + } + for(State state : list) { + state.buildTable(map); + } + this.states = ImmutableList.copyOf(list); + this.setDefaultState(this.getBaseState()); + } + + /** + * Sets the footstep sound for the block. Returns the object for convenience in constructing. + */ + public Block setStepSound(SoundType sound) + { + this.sound = sound; + return this; + } + + /** + * Sets how much light is blocked going through this block. Returns the object for convenience in constructing. + */ + public Block setLightOpacity(int opacity) + { + this.lightOpacity = opacity; + return this; + } + + /** + * Sets the light value that the block emits. Returns resulting block instance for constructing convenience. Args: + * level + */ + public Block setLightLevel(float value) + { + this.lightValue = (int)(15.0F * value); + return this; + } + + /** + * Sets the the blocks resistance to explosions. Returns the object for convenience in constructing. + */ + public Block setResistance(float resistance) + { + this.blockResistance = resistance * 3.0F; + return this; + } + + /** + * Sets how many hits it takes to break a block. + */ + public Block setHardness(float hardness) + { + this.blockHardness = hardness; + + if (this.blockResistance < hardness * 5.0F) + { + this.blockResistance = hardness * 5.0F; + } + + return this; + } + +// public Block setBlockUnbreakable() +// { +// this.setHardness(-1.0F); +// this.setResistance(6000000.0F); +// return this; +// } + + /** + * Sets whether this block type will receive random update ticks + */ + protected Block setTickRandomly() + { + this.ticked = true; + return this; + } + + public Block setDisplay(String name) + { + this.display = name; + return this; + } + +// public Block disableStats() +// { +// this.enableStats = false; +// return this; +// } + + public Block setTab(CheatTab tab) + { + this.tab = tab; + return this; + } + + public Block setSumBrightness() + { + this.sumBrightness = true; + return this; + } + + public Block setMiningLevel(int level) + { + this.miningLevel = level; + return this; + } + + public Block setAxeHarvestable() + { + this.axeHarvest = true; + return this; + } + + public Block setShovelHarvestable() + { + this.shovelHarvest = true; + return this; + } + + public Block setShearsEfficiency(int efficiency) + { + this.shearsEfficiency = efficiency; + return this; + } + + public Block setRadiation(float value) + { + this.radiation = value; + if(value > 0.0f) + this.ticked = true; + return this; + } + + + + public boolean isFullBlock() + { + return this.fullBlock; + } + + public int getLightOpacity() + { + return this.lightOpacity; + } + + /** + * Used in the renderer to apply ambient occlusion + */ + public boolean isTranslucent() + { + return this.translucent; + } + + public int getLightValue() + { + return this.lightValue; + } + + /** + * Should block use the brightest neighbor light value as its own + */ + public boolean getSumBrightness() + { + return this.sumBrightness; + } + + /** + * Get a material of block + */ + public Material getMaterial() + { + return this.material; + } + + public ImmutableList getValidStates() { + return this.states; + } + + private List> getAllowedValues() { + List> list = Lists.>newArrayList(); + for(int z = 0; z < this.properties.size(); z++) { + list.add((this.properties.get(z)).getAllowedValues()); + } + return list; + } + + public final State getBaseState() { + return this.states.get(0); + } + +// public Block getBlock() { +// return this; +// } + + public Collection getPropertyMap() { + return this.properties; + } + +// public String toString() { +// return Objects.toStringHelper(this).add("block", BlockRegistry.REGISTRY.getNameForObject(this)) +// .add("properties", Iterables.transform(this.properties, GET_NAME_FUNC)).toString(); +// } + +// /** +// * Get the MapColor for this Block and the given BlockState +// */ +// public final MapColor getMapColor(IBlockState state) +// { +// return this.blockMapColor; +// } + + /** + * Convert the given metadata into a BlockState for this Block + */ + public State getStateFromMeta(int meta) + { + return this.getState(); + } + + /** + * Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(State state) + { + if (state != null && !state.getPropertyNames().isEmpty()) + { + throw new IllegalArgumentException("Don\'t know how to convert " + state + " back into data..."); + } + else + { + return 0; + } + } + + /** + * Get the actual Block state of this Block at the given position. This applies properties not visible in the + * metadata, such as fence connections. + */ + public State getActualState(State state, IWorldAccess worldIn, BlockPos pos) + { + return state; + } + + /** + * Indicate if a material is a normal solid opaque cube + */ + public boolean isBlockNormalCube() + { + return this.material.blocksMovement() && this.isFullCube(); + } + + /** + * Used for nearly all game logic (non-rendering) purposes. Use Forge-provided isNormalCube(IBlockAccess, BlockPos) + * instead. + */ + public boolean isNormalCube() + { + return this.material.isOpaque() && this.isFullCube() && !this.canProvidePower(); + } + + public boolean isVisuallyOpaque() + { + return this.material.blocksMovement() && this.isFullCube(); + } + + public boolean isFullCube() + { + return true; + } + + public boolean isPassable(IBlockAccess worldIn, BlockPos pos) + { + return !this.material.blocksMovement(); + } + + /** + * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() + { + return 3; + } + + public boolean isXrayVisible() + { + return false; + } + + /** + * Whether this Block can be replaced directly by other blocks (true for e.g. tall grass) + */ + public boolean isReplaceable(World worldIn, BlockPos pos) + { + return false; + } + + public float getBlockHardness(World worldIn, BlockPos pos) + { + return this.blockHardness; + } + + /** + * Returns whether or not this block is of a type that needs random ticking. Called for ref-counting purposes by + * ExtendedBlockStorage in order to broadly cull a chunk from the random chunk update list for efficiency's sake. + */ + public boolean getTickRandomly() + { + return this.ticked; + } + + public boolean hasTileEntity() + { + return this.hasTile; + } + + protected final void setBlockBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) + { + this.minX = (double)minX; + this.minY = (double)minY; + this.minZ = (double)minZ; + this.maxX = (double)maxX; + this.maxY = (double)maxY; + this.maxZ = (double)maxZ; + } + + public int getMixedBrightnessForBlock(IWorldAccess worldIn, BlockPos pos) + { + Block block = worldIn.getState(pos).getBlock(); + int i = worldIn.getCombinedLight(pos, block.getLightValue()); + + if (i == 0 && block instanceof BlockSlab) + { + pos = pos.down(); + block = worldIn.getState(pos).getBlock(); + return worldIn.getCombinedLight(pos, block.getLightValue()); + } + else + { + return i; + } + } + + public boolean shouldSideBeRendered(IWorldAccess worldIn, BlockPos pos, Facing side) + { + return side == Facing.DOWN && this.minY > 0.0D ? true : (side == Facing.UP && this.maxY < 1.0D ? true : (side == Facing.NORTH && this.minZ > 0.0D ? true : (side == Facing.SOUTH && this.maxZ < 1.0D ? true : (side == Facing.WEST && this.minX > 0.0D ? true : (side == Facing.EAST && this.maxX < 1.0D ? true : !worldIn.getState(pos).getBlock().isOpaqueCube()))))); + } + + /** + * Whether this Block is solid on the given Side + */ + public boolean isBlockSolid(IBlockAccess worldIn, BlockPos pos, Facing side) + { + return worldIn.getState(pos).getBlock().getMaterial().isSolid(); + } + + public BoundingBox getSelectedBoundingBox(World worldIn, BlockPos pos) + { + return new BoundingBox((double)pos.getX() + this.minX, (double)pos.getY() + this.minY, (double)pos.getZ() + this.minZ, (double)pos.getX() + this.maxX, (double)pos.getY() + this.maxY, (double)pos.getZ() + this.maxZ); + } + + /** + * Add all collision boxes of this Block to the list that intersect with the given mask. + */ + public void addCollisionBoxesToList(World worldIn, BlockPos pos, State state, BoundingBox mask, List list, Entity collidingEntity) + { + BoundingBox axisalignedbb = this.getCollisionBoundingBox(worldIn, pos, state); + + if (axisalignedbb != null && mask.intersectsWith(axisalignedbb)) + { + list.add(axisalignedbb); + } + } + + public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) + { + return new BoundingBox((double)pos.getX() + this.minX, (double)pos.getY() + this.minY, (double)pos.getZ() + this.minZ, (double)pos.getX() + this.maxX, (double)pos.getY() + this.maxY, (double)pos.getZ() + this.maxZ); + } + + /** + * Used to determine ambient occlusion and culling when rebuilding chunks for render + */ + public boolean isOpaqueCube() + { + return true; + } + + public boolean canCollideCheck(State state, boolean hitIfLiquid) + { + return this.isCollidable(); + } + + /** + * Returns if this block is collidable (only used by Fire). Args: x, y, z + */ + public boolean isCollidable() + { + return true; + } + + /** + * Called randomly when setTickRandomly is set to true (used by e.g. crops to grow, etc.) + */ + public void randomTick(AWorldServer worldIn, BlockPos pos, State state, Random random) + { + this.updateTick(worldIn, pos, state, random); + if(this.radiation > 0.0f && /* worldIn.getTime() % 5L == 0L && */ random.chance(Config.randomTick / 3)) + this.affectEntities(worldIn, pos, state, this.radiation * 8.0f * 0.25f); + } + + private void affectEntities(AWorldServer worldIn, BlockPos pos, State state, float rad) + { + float r = ExtMath.clampf(rad * 2.0f, 0.0f, 25.0f); + BoundingBox box = this.getCollisionBoundingBox(worldIn, pos, state); + if(box == null) + box = new BoundingBox(pos, pos.add(1, 1, 1)); + for (EntityLiving entity : worldIn.getEntitiesWithinAABB(EntityLiving.class, box.expand(r, r, r))) + { + float effect = rad * 2.0f * (r - ExtMath.sqrtf((float)entity.getDistanceSq(pos))) / r; + if(effect > 0.0f) + entity.addRadiation(effect); + } + } + + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) + { + } + + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) + { + } + + /** + * Called when a player destroys this Block + */ + public void onBlockDestroyedByPlayer(World worldIn, BlockPos pos, State state) + { + } + + /** + * Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) + { + } + + /** + * How many world ticks before ticking + */ + public int tickRate(World worldIn, BlockPos pos) + { + return 10; + } + + public void onBlockAdded(AWorldServer world, BlockPos pos, State state) + { + } + + public void onBlockRemoved(AWorldServer world, BlockPos pos, State state) + { + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(Random random) + { + return 1; + } + + /** + * Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(State state, Random rand, int fortune) + { + return ItemRegistry.getItemFromBlock(this); + } + + /** + * Get the hardness of this Block relative to the ability of the given player + */ + public float getPlayerRelativeBlockHardness(EntityNPC playerIn, World worldIn, BlockPos pos) + { + float f = this.getBlockHardness(worldIn, pos); + return f < 0.0F ? 0.0F : (!playerIn.canHarvestBlock(this) ? playerIn.getToolDigEfficiency(this) / f / 100.0F : playerIn.getToolDigEfficiency(this) / f / 30.0F); + } + + /** + * Spawn this Block's drops into the World as EntityItems + */ + public final void dropBlockAsItem(World worldIn, BlockPos pos, State state, int forture) + { + this.dropBlockAsItemWithChance(worldIn, pos, state, 1.0F, forture); + } + + /** + * Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) + { + if (!worldIn.client) + { + int i = this.quantityDroppedWithBonus(fortune, worldIn.rand); + + for (int j = 0; j < i; ++j) + { + if (worldIn.rand.floatv() <= chance) + { + Item item = this.getItemDropped(state, worldIn.rand, fortune); + + if (item != null) + { + spawnAsEntity(worldIn, pos, new ItemStack(item, 1, this.damageDropped(state))); + } + } + } + } + } + + /** + * Spawns the given ItemStack as an EntityItem into the World at the given position + */ + public static void spawnAsEntity(World worldIn, BlockPos pos, ItemStack stack) + { + if (!worldIn.client && Config.blockDrop) + { + float f = 0.5F; + double d0 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; + double d1 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; + double d2 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; + EntityItem entityitem = new EntityItem(worldIn, (double)pos.getX() + d0, (double)pos.getY() + d1, (double)pos.getZ() + d2, stack); + entityitem.setDefaultPickupDelay(); + worldIn.spawnEntityInWorld(entityitem); + } + } + + /** + * Spawns the given amount of experience into the World as XP orb entities + */ + protected void dropXpOnBlockBreak(World worldIn, BlockPos pos, int amount) + { + if (!worldIn.client && Config.blockXP) + { + while (amount > 0) + { + int i = EntityXp.getXPSplit(amount); + amount -= i; + worldIn.spawnEntityInWorld(new EntityXp(worldIn, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, i)); + } + } + } + + /** + * Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It + * returns the metadata of the dropped item based on the old metadata of the block. + */ + public int damageDropped(State state) + { + return 0; + } + + /** + * Returns how much this block can resist explosions from the passed in entity. + */ + public float getExplosionResistance(Entity exploder) + { + return this.blockResistance / 5.0F; + } + + /** + * Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. + */ + public HitPosition collisionRayTrace(World worldIn, BlockPos pos, Vec3 start, Vec3 end) + { + this.setBlockBoundsBasedOnState(worldIn, pos); + start = start.addVector((double)(-pos.getX()), (double)(-pos.getY()), (double)(-pos.getZ())); + end = end.addVector((double)(-pos.getX()), (double)(-pos.getY()), (double)(-pos.getZ())); + Vec3 vec3 = start.getIntermediateWithXValue(end, this.minX); + Vec3 vec31 = start.getIntermediateWithXValue(end, this.maxX); + Vec3 vec32 = start.getIntermediateWithYValue(end, this.minY); + Vec3 vec33 = start.getIntermediateWithYValue(end, this.maxY); + Vec3 vec34 = start.getIntermediateWithZValue(end, this.minZ); + Vec3 vec35 = start.getIntermediateWithZValue(end, this.maxZ); + + if (!this.isVecInsideYZBounds(vec3)) + { + vec3 = null; + } + + if (!this.isVecInsideYZBounds(vec31)) + { + vec31 = null; + } + + if (!this.isVecInsideXZBounds(vec32)) + { + vec32 = null; + } + + if (!this.isVecInsideXZBounds(vec33)) + { + vec33 = null; + } + + if (!this.isVecInsideXYBounds(vec34)) + { + vec34 = null; + } + + if (!this.isVecInsideXYBounds(vec35)) + { + vec35 = null; + } + + Vec3 vec36 = null; + + if (vec3 != null && (vec36 == null || start.squareDistanceTo(vec3) < start.squareDistanceTo(vec36))) + { + vec36 = vec3; + } + + if (vec31 != null && (vec36 == null || start.squareDistanceTo(vec31) < start.squareDistanceTo(vec36))) + { + vec36 = vec31; + } + + if (vec32 != null && (vec36 == null || start.squareDistanceTo(vec32) < start.squareDistanceTo(vec36))) + { + vec36 = vec32; + } + + if (vec33 != null && (vec36 == null || start.squareDistanceTo(vec33) < start.squareDistanceTo(vec36))) + { + vec36 = vec33; + } + + if (vec34 != null && (vec36 == null || start.squareDistanceTo(vec34) < start.squareDistanceTo(vec36))) + { + vec36 = vec34; + } + + if (vec35 != null && (vec36 == null || start.squareDistanceTo(vec35) < start.squareDistanceTo(vec36))) + { + vec36 = vec35; + } + + if (vec36 == null) + { + return null; + } + else + { + Facing enumfacing = null; + + if (vec36 == vec3) + { + enumfacing = Facing.WEST; + } + + if (vec36 == vec31) + { + enumfacing = Facing.EAST; + } + + if (vec36 == vec32) + { + enumfacing = Facing.DOWN; + } + + if (vec36 == vec33) + { + enumfacing = Facing.UP; + } + + if (vec36 == vec34) + { + enumfacing = Facing.NORTH; + } + + if (vec36 == vec35) + { + enumfacing = Facing.SOUTH; + } + + return new HitPosition(ObjectType.BLOCK, vec36.addVector((double)pos.getX(), (double)pos.getY(), (double)pos.getZ()), enumfacing, pos); + } + } + + /** + * Checks if a vector is within the Y and Z bounds of the block. + */ + private boolean isVecInsideYZBounds(Vec3 point) + { + return point == null ? false : point.yCoord >= this.minY && point.yCoord <= this.maxY && point.zCoord >= this.minZ && point.zCoord <= this.maxZ; + } + + /** + * Checks if a vector is within the X and Z bounds of the block. + */ + private boolean isVecInsideXZBounds(Vec3 point) + { + return point == null ? false : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.zCoord >= this.minZ && point.zCoord <= this.maxZ; + } + + /** + * Checks if a vector is within the X and Y bounds of the block. + */ + private boolean isVecInsideXYBounds(Vec3 point) + { + return point == null ? false : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.yCoord >= this.minY && point.yCoord <= this.maxY; + } + + /** + * Called when this Block is destroyed by an Explosion + */ + public void onBlockDestroyedByExplosion(World worldIn, BlockPos pos, Explosion explosionIn, State prevState) + { + } + + public BlockLayer getBlockLayer() + { + return BlockLayer.SOLID; + } + + public boolean canReplace(World worldIn, BlockPos pos, Facing side, ItemStack stack) + { + return this.canPlaceBlockOnSide(worldIn, pos, side); + } + + /** + * Check whether this Block can be placed on the given side + */ + public boolean canPlaceBlockOnSide(World worldIn, BlockPos pos, Facing side) + { + return this.canPlaceBlockAt(worldIn, pos); + } + + public boolean canPlaceBlockAt(World worldIn, BlockPos pos) + { + return worldIn.getState(pos).getBlock().material.isReplaceable(); + } + + public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) + { + return false; + } + + /** + * Triggered whenever an entity collides with this block (enters into the block) + */ + public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, Entity entityIn) + { + } + + /** + * Called by ItemBlocks just before a block is actually set in the world, to allow for adjustments to the + * IBlockstate + */ + public State onBlockPlaced(World worldIn, BlockPos pos, Facing facing, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) + { + return this.getStateFromMeta(meta); + } + + public void onBlockClicked(World worldIn, BlockPos pos, EntityNPC playerIn) + { + } + + public Vec3 modifyAcceleration(World worldIn, BlockPos pos, Entity entityIn, Vec3 motion) + { + return motion; + } + + public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos) + { + } + + /** + * returns the block bounderies minX value + */ + public final double getBlockBoundsMinX() + { + return this.minX; + } + + /** + * returns the block bounderies maxX value + */ + public final double getBlockBoundsMaxX() + { + return this.maxX; + } + + /** + * returns the block bounderies minY value + */ + public final double getBlockBoundsMinY() + { + return this.minY; + } + + /** + * returns the block bounderies maxY value + */ + public final double getBlockBoundsMaxY() + { + return this.maxY; + } + + /** + * returns the block bounderies minZ value + */ + public final double getBlockBoundsMinZ() + { + return this.minZ; + } + + /** + * returns the block bounderies maxZ value + */ + public final double getBlockBoundsMaxZ() + { + return this.maxZ; + } + +// public int getBlockColor() +// { +// return 16777215; +// } + + public int getRenderColor(State state) + { + return 16777215; + } + + public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass) + { + return 16777215; + } + + public final int colorMultiplier(IWorldAccess worldIn, BlockPos pos) + { + return this.colorMultiplier(worldIn, pos, 0); + } + + public int getWeakPower(IWorldAccess worldIn, BlockPos pos, State state, Facing side) + { + return 0; + } + + /** + * Can this block provide power. Only wire currently seems to have this change based on its state. + */ + public boolean canProvidePower() + { + return false; + } + + /** + * Called When an Entity Collided with the Block + */ + public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, State state, Entity entityIn) + { + } + + public int getStrongPower(IWorldAccess worldIn, BlockPos pos, State state, Facing side) + { + return 0; + } + + /** + * Sets the block's bounds for rendering it as an item + */ + public void setBlockBoundsForItemRender() + { + } + + public void harvestBlock(World worldIn, EntityNPC player, BlockPos pos, State state, TileEntity te) + { +// player.triggerAchievement(StatRegistry.mineBlockStatArray[BlockRegistry.getIdFromBlock(this)]); + + if (this.canSilkHarvest() && EnchantmentHelper.getSilkTouchModifier(player)) + { + ItemStack itemstack = this.createStackedBlock(state); + + if (itemstack != null) + { + spawnAsEntity(worldIn, pos, itemstack); + } + } + else + { + int i = EnchantmentHelper.getFortuneModifier(player); + this.dropBlockAsItem(worldIn, pos, state, i); + } + } + + public boolean canSilkHarvest() + { + return this.isFullCube() && !this.hasTile; + } + + public ItemStack createStackedBlock(State state) + { + int i = 0; + Item item = ItemRegistry.getItemFromBlock(this); + + if (item != null && item.getHasSubtypes()) + { + i = this.getMetaFromState(state); + } + + return new ItemStack(item, 1, i); + } + + /** + * Get the quantity dropped based on the given fortune level + */ + public int quantityDroppedWithBonus(int fortune, Random random) + { + return this.quantityDropped(random); + } + + /** + * Called by ItemBlocks after a block is set in the world, to allow post-place logic + */ + public void onBlockPlacedBy(World worldIn, BlockPos pos, State state, EntityLiving placer, ItemStack stack) + { + } + + /** + * Return true if an entity can be spawned inside the block (used to get the player's bed spawn location) + */ + public boolean canSpawnInBlock() + { + return !this.material.isSolid() && !this.material.isLiquid(); + } + +// /** +// * Gets the localized name of this block. Used for the statistics page. +// */ +// public String getLocalizedName() +// { +// return Strs.get(this.getUnlocalizedName() + ".name"); +// } + + public final String getDisplay() + { + return this.display; + } + + /** + * Called on both Client and Server when World#addBlockEvent is called + */ + public boolean onBlockEventReceived(World worldIn, BlockPos pos, State state, int eventID, int eventParam) + { + return false; + } + +// /** +// * Return the state of blocks statistics flags - if the block is counted for mined and placed. +// */ +// public boolean getEnableStats() +// { +// return this.enableStats; +// } + + public int getMobilityFlag() + { + return this.material.getMaterialMobility(); + } + + /** + * Returns the default ambient occlusion value based on block opacity + */ + public float getAmbientOcclusionLightValue() + { + return this.isBlockNormalCube() ? 0.2F : 1.0F; + } + + /** + * Block's chance to react to a living entity falling on it. + */ + public void onFallenUpon(World worldIn, BlockPos pos, Entity entityIn, float fallDistance) + { + entityIn.fall(fallDistance, 1.0F); + } + + /** + * Called when an Entity lands on this Block. This method *must* update motionY because the entity will not do that + * on its own + */ + public void onLanded(World worldIn, Entity entityIn) + { + entityIn.motionY = 0.0D; + } + + public Item getItem(World worldIn, BlockPos pos) + { + return ItemRegistry.getItemFromBlock(this); + } + + /** + * Gets the meta to use for the Pick Block ItemStack result + */ + public int getDamageValue(World worldIn, BlockPos pos) + { + return this.damageDropped(worldIn.getState(pos)); + } + + /** + * returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks) + */ + public void getSubBlocks(Item itemIn, CheatTab tab, List list) + { + list.add(new ItemStack(itemIn, 1, 0)); + } + + /** + * Returns the tab to display the given block on. + */ + public CheatTab getTab() + { + return this.tab; + } + + public void onBlockHarvested(World worldIn, BlockPos pos, State state, EntityNPC player) + { + } + + /** + * Called similar to random ticks, but only when it is raining. + */ + public void fillWithRain(World worldIn, BlockPos pos) + { + } + + public boolean isPickStrict() + { + return false; + } + + public boolean requiresUpdates() + { + return true; + } + + /** + * Return whether this block can drop from an explosion. + */ + public boolean canDropFromExplosion(Explosion explosionIn) + { + return true; + } + + public boolean isAssociatedBlock(Block other) + { + return this == other; + } + + public static boolean isEqualTo(Block blockIn, Block other) + { + return blockIn != null && other != null ? (blockIn == other ? true : blockIn.isAssociatedBlock(other)) : false; + } + + public boolean hasComparatorInputOverride() + { + return false; + } + + public int getComparatorInputOverride(World worldIn, BlockPos pos) + { + return 0; + } + + /** + * Possibly modify the given BlockState before rendering it on an Entity (Minecarts, Endermen, ...) + */ + public State getStateForEntityRender(State state) + { + return state; + } + + protected IProperty[] getProperties() + { + return new IProperty[0]; + } + + protected final void setDefaultState(State state) + { + this.defaultState = state; + } + + public final State getState() + { + return this.defaultState; + } + +// public EnumOffsetType getOffsetType() +// { +// return EnumOffsetType.NONE; +// } + +// public String toString() +// { +// return "Block{" + BlockRegistry.REGISTRY.getNameForObject(this) + "}"; +// } + + public int getMiningLevel() { + return this.miningLevel; + } + + public boolean canAxeHarvest() { + return this.axeHarvest; + } + + public boolean canShovelHarvest() { + return this.shovelHarvest; + } + + public int getShearsEfficiency() { + return this.shearsEfficiency; + } + + public boolean isMagnetic() { + return false; + } + + public Transforms getTransform() { + return Transforms.BLOCK; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(name).add().all(); + } + + public IProperty[] getIgnoredProperties() { + return null; + } + + public void getAnimatedTextures(Map map) { + } + + public boolean canKeepFire() { + return false; + } + + public void onDestroyedByFire(World world, BlockPos pos, State state) { + } +} diff --git a/common/src/common/block/BlockAir.java b/common/src/common/block/BlockAir.java new file mode 100755 index 0000000..e0a27ff --- /dev/null +++ b/common/src/common/block/BlockAir.java @@ -0,0 +1,56 @@ +package common.block; + +import common.material.Material; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.world.State; +import common.world.World; + +public class BlockAir extends Block +{ + public BlockAir() + { + super(Material.air); + } + + /** + * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() + { + return -1; + } + + public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) + { + return null; + } + + /** + * Used to determine ambient occlusion and culling when rebuilding chunks for render + */ + public boolean isOpaqueCube() + { + return false; + } + + public boolean canCollideCheck(State state, boolean hitIfLiquid) + { + return false; + } + + /** + * Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) + { + } + + /** + * Whether this Block can be replaced directly by other blocks (true for e.g. tall grass) + */ + public boolean isReplaceable(World worldIn, BlockPos pos) + { + return true; + } +} diff --git a/common/src/main/java/common/block/tech/BlockAnvil.java b/common/src/common/block/BlockAnvil.java similarity index 97% rename from common/src/main/java/common/block/tech/BlockAnvil.java rename to common/src/common/block/BlockAnvil.java index 8a00352..6b9406f 100755 --- a/common/src/main/java/common/block/tech/BlockAnvil.java +++ b/common/src/common/block/BlockAnvil.java @@ -1,9 +1,7 @@ -package common.block.tech; +package common.block; import java.util.List; -import common.block.BlockFalling; -import common.block.Material; import common.entity.item.EntityFalling; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; @@ -13,6 +11,7 @@ import common.inventory.InventoryPlayer; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -34,10 +33,10 @@ public class BlockAnvil extends BlockFalling public BlockAnvil() { - super(Material.HEAVY); + super(Material.anvil); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(DAMAGE, Integer.valueOf(0))); this.setLightOpacity(0); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); } public boolean isFullCube() diff --git a/common/src/common/block/BlockBanner.java b/common/src/common/block/BlockBanner.java new file mode 100755 index 0000000..b025774 --- /dev/null +++ b/common/src/common/block/BlockBanner.java @@ -0,0 +1,273 @@ +package common.block; + +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.item.Item; +import common.item.ItemStack; +import common.material.Material; +import common.model.Transforms; +import common.nbt.NBTTagCompound; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityBanner; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; + +public class BlockBanner extends BlockContainer +{ + public static final PropertyDirection FACING = PropertyDirection.create("facing", Facing.Plane.HORIZONTAL); + public static final PropertyInteger ROTATION = PropertyInteger.create("rotation", 0, 15); + + public BlockBanner() + { + super(Material.wood); + float f = 0.25F; + float f1 = 1.0F; + this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); + } + +// /** +// * Gets the localized name of this block. Used for the statistics page. +// */ +// public String getLocalizedName() +// { +// return "Banner"; +// } + + public boolean isPickStrict() + { + return true; + } + + public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) + { + return null; + } + + public BoundingBox getSelectedBoundingBox(World worldIn, BlockPos pos) + { + this.setBlockBoundsBasedOnState(worldIn, pos); + return super.getSelectedBoundingBox(worldIn, pos); + } + + public boolean isFullCube() + { + return false; + } + + public boolean isPassable(IBlockAccess worldIn, BlockPos pos) + { + return true; + } + + /** + * Used to determine ambient occlusion and culling when rebuilding chunks for render + */ + public boolean isOpaqueCube() + { + return false; + } + + /** + * Return true if an entity can be spawned inside the block (used to get the player's bed spawn location) + */ + public boolean canSpawnInBlock() + { + return true; + } + + /** + * Returns a new instance of a block's tile entity class. Called on placing the block. + */ + public TileEntity createNewTileEntity(World worldIn, int meta) + { + return new TileEntityBanner(); + } + + /** + * Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(State state, Random rand, int fortune) + { + return Items.banner; + } + + public Item getItem(World worldIn, BlockPos pos) + { + return Items.banner; + } + + public int getDamageValue(World worldIn, BlockPos pos) + { + TileEntity te = worldIn.getTileEntity(pos); + if(te instanceof TileEntityBanner) + return ((TileEntityBanner)te).getBaseColor(); + return super.getDamageValue(worldIn, pos); + } + + /** + * Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) + { + TileEntity tileentity = worldIn.getTileEntity(pos); + + if (tileentity instanceof TileEntityBanner) + { + ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner)tileentity).getBaseColor()); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + tileentity.writeToNBT(nbttagcompound); + nbttagcompound.removeTag("x"); + nbttagcompound.removeTag("y"); + nbttagcompound.removeTag("z"); + nbttagcompound.removeTag("id"); + itemstack.setTagInfo("BlockEntityTag", nbttagcompound); + spawnAsEntity(worldIn, pos, itemstack); + } + else + { + super.dropBlockAsItemWithChance(worldIn, pos, state, chance, fortune); + } + } + + public boolean canPlaceBlockAt(World worldIn, BlockPos pos) + { + return !this.hasInvalidNeighbor(worldIn, pos) && super.canPlaceBlockAt(worldIn, pos); + } + + public void harvestBlock(World worldIn, EntityNPC player, BlockPos pos, State state, TileEntity te) + { + if (te instanceof TileEntityBanner) + { + TileEntityBanner tileentitybanner = (TileEntityBanner)te; + ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner)te).getBaseColor()); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + TileEntityBanner.setBaseColorAndPatterns(nbttagcompound, tileentitybanner.getBaseColor(), tileentitybanner.getPatterns()); + itemstack.setTagInfo("BlockEntityTag", nbttagcompound); + spawnAsEntity(worldIn, pos, itemstack); + } + else + { + super.harvestBlock(worldIn, player, pos, state, (TileEntity)null); + } + } + + public Transforms getTransform() { + return Transforms.BANNER; + } + + public static class BlockBannerHanging extends BlockBanner + { + public BlockBannerHanging() + { + this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); + } + + public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos) + { + Facing enumfacing = (Facing)worldIn.getState(pos).getValue(FACING); + float f = 0.0F; + float f1 = 0.78125F; + float f2 = 0.0F; + float f3 = 1.0F; + float f4 = 0.125F; + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + + switch (enumfacing) + { + case NORTH: + default: + this.setBlockBounds(f2, f, 1.0F - f4, f3, f1, 1.0F); + break; + + case SOUTH: + this.setBlockBounds(f2, f, 0.0F, f3, f1, f4); + break; + + case WEST: + this.setBlockBounds(1.0F - f4, f, f2, 1.0F, f1, f3); + break; + + case EAST: + this.setBlockBounds(0.0F, f, f2, f4, f1, f3); + } + } + + public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) + { + Facing enumfacing = (Facing)state.getValue(FACING); + + if (!worldIn.getState(pos.offset(enumfacing.getOpposite())).getBlock().getMaterial().isSolid()) + { + this.dropBlockAsItem(worldIn, pos, state, 0); + worldIn.setBlockToAir(pos); + } + + super.onNeighborBlockChange(worldIn, pos, state, neighborBlock); + } + + public State getStateFromMeta(int meta) + { + Facing enumfacing = Facing.getFront(meta); + + if (enumfacing.getAxis() == Facing.Axis.Y) + { + enumfacing = Facing.NORTH; + } + + return this.getState().withProperty(FACING, enumfacing); + } + + public int getMetaFromState(State state) + { + return ((Facing)state.getValue(FACING)).getIndex(); + } + + protected IProperty[] getProperties() + { + return new IProperty[] {FACING}; + } + } + + public static class BlockBannerStanding extends BlockBanner + { + public BlockBannerStanding() + { + this.setDefaultState(this.getBaseState().withProperty(ROTATION, Integer.valueOf(0))); + } + + public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) + { + if (!worldIn.getState(pos.down()).getBlock().getMaterial().isSolid()) + { + this.dropBlockAsItem(worldIn, pos, state, 0); + worldIn.setBlockToAir(pos); + } + + super.onNeighborBlockChange(worldIn, pos, state, neighborBlock); + } + + public State getStateFromMeta(int meta) + { + return this.getState().withProperty(ROTATION, Integer.valueOf(meta)); + } + + public int getMetaFromState(State state) + { + return ((Integer)state.getValue(ROTATION)).intValue(); + } + + protected IProperty[] getProperties() + { + return new IProperty[] {ROTATION}; + } + } +} diff --git a/common/src/main/java/common/block/foliage/BlockBaseFlower.java b/common/src/common/block/BlockBaseFlower.java similarity index 84% rename from common/src/main/java/common/block/foliage/BlockBaseFlower.java rename to common/src/common/block/BlockBaseFlower.java index 413ec6e..5d07b1b 100755 --- a/common/src/main/java/common/block/foliage/BlockBaseFlower.java +++ b/common/src/common/block/BlockBaseFlower.java @@ -1,4 +1,4 @@ -package common.block.foliage; +package common.block; public class BlockBaseFlower extends BlockFlower { diff --git a/common/src/main/java/common/block/tech/BlockBasePressurePlate.java b/common/src/common/block/BlockBasePressurePlate.java similarity index 97% rename from common/src/main/java/common/block/tech/BlockBasePressurePlate.java rename to common/src/common/block/BlockBasePressurePlate.java index a920fbe..b19329d 100755 --- a/common/src/main/java/common/block/tech/BlockBasePressurePlate.java +++ b/common/src/common/block/BlockBasePressurePlate.java @@ -1,11 +1,9 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.Material; -import common.block.artificial.BlockFence; import common.entity.Entity; import common.init.SoundEvent; import common.item.CheatTab; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.rng.Random; @@ -23,7 +21,7 @@ public abstract class BlockBasePressurePlate extends Block public BlockBasePressurePlate(Material p_i46401_1_) { super(p_i46401_1_); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); // this.setTickRandomly(true); } diff --git a/common/src/main/java/common/block/tech/BlockBeacon.java b/common/src/common/block/BlockBeacon.java similarity index 93% rename from common/src/main/java/common/block/tech/BlockBeacon.java rename to common/src/common/block/BlockBeacon.java index 83986bc..2032c67 100755 --- a/common/src/main/java/common/block/tech/BlockBeacon.java +++ b/common/src/common/block/BlockBeacon.java @@ -1,10 +1,8 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.BlockContainer; -import common.block.Material; import common.entity.npc.EntityNPC; import common.item.CheatTab; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -17,7 +15,7 @@ import common.world.World; public class BlockBeacon extends BlockContainer { - private static final Model beacon = ModelProvider.getModelProvider().getModel("glass") + private static final Model beacon = ModelProvider.getModelProvider().getModel("glass").noOcclude() .add(0, 0, 0, 16, 16, 16) .d().uv(0, 0, 16, 16).noCull() .u().uv(0, 0, 16, 16).noCull() @@ -43,15 +41,15 @@ public class BlockBeacon extends BlockContainer public BlockBeacon() { - super(Material.TRANSLUCENT); + super(Material.glass); this.setHardness(3.0F); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); } /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityBeacon(); } diff --git a/common/src/main/java/common/block/artificial/BlockBed.java b/common/src/common/block/BlockBed.java similarity index 97% rename from common/src/main/java/common/block/artificial/BlockBed.java rename to common/src/common/block/BlockBed.java index 371619d..02e759e 100755 --- a/common/src/main/java/common/block/artificial/BlockBed.java +++ b/common/src/common/block/BlockBed.java @@ -1,13 +1,11 @@ -package common.block.artificial; +package common.block; -import common.block.Block; -import common.block.BlockDirectional; -import common.block.Material; import common.color.DyeColor; import common.color.TextColor; import common.entity.npc.EntityNPC; import common.init.ItemRegistry; import common.item.Item; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -50,7 +48,7 @@ public class BlockBed extends BlockDirectional { private final DyeColor color; public BlockBed(DyeColor color) { - super(Material.BURNABLE); + super(Material.cloth); this.color = color; this.setDefaultState(this.getBaseState().withProperty(PART, BlockBed.EnumPartType.FOOT)); this.setBedBounds(); diff --git a/common/src/main/java/common/block/natural/BlockBedrock.java b/common/src/common/block/BlockBedrock.java similarity index 82% rename from common/src/main/java/common/block/natural/BlockBedrock.java rename to common/src/common/block/BlockBedrock.java index a1c0a9b..71ec977 100755 --- a/common/src/main/java/common/block/natural/BlockBedrock.java +++ b/common/src/common/block/BlockBedrock.java @@ -1,7 +1,6 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; +import common.material.Material; import common.model.ParticleType; import common.rng.Random; import common.util.BlockPos; @@ -10,7 +9,7 @@ import common.world.State; public class BlockBedrock extends Block { public BlockBedrock() { - super(Material.SOLID); + super(Material.rock); } public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) diff --git a/common/src/main/java/common/block/natural/BlockBlackenedDirt.java b/common/src/common/block/BlockBlackenedDirt.java similarity index 81% rename from common/src/main/java/common/block/natural/BlockBlackenedDirt.java rename to common/src/common/block/BlockBlackenedDirt.java index c6e0fa0..361c7cb 100644 --- a/common/src/main/java/common/block/natural/BlockBlackenedDirt.java +++ b/common/src/common/block/BlockBlackenedDirt.java @@ -1,13 +1,11 @@ -package common.block.natural; +package common.block; -import common.biome.Biome; -import common.block.Block; -import common.block.Material; import common.init.Blocks; +import common.init.Config; import common.item.CheatTab; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; -import common.vars.Vars; import common.world.State; import common.world.AWorldServer; @@ -15,14 +13,14 @@ public class BlockBlackenedDirt extends Block { public BlockBlackenedDirt() { - super(Material.LOOSE); + super(Material.ground); this.setTickRandomly(); - this.setTab(CheatTab.NATURE); + this.setTab(CheatTab.tabNature); } public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Vars.darkDirtSpread) + if (Config.darkDirtSpread) { for (int i = 0; i < 4; i++) { @@ -37,7 +35,6 @@ public class BlockBlackenedDirt extends Block else if (iblockstate.getBlock() == Blocks.grass && worldIn.getLightFromNeighbors(blockpos.up()) >= 2 && block.getLightOpacity() <= 6) { worldIn.setState(blockpos, Blocks.blackened_soil.getState()); - worldIn.setBiome(blockpos, Biome.BLACKENED); } else if (iblockstate.getBlock() == Blocks.stone && rand.chance(25)) { diff --git a/common/src/main/java/common/block/foliage/BlockBlackenedSoil.java b/common/src/common/block/BlockBlackenedSoil.java similarity index 81% rename from common/src/main/java/common/block/foliage/BlockBlackenedSoil.java rename to common/src/common/block/BlockBlackenedSoil.java index e185c74..3e122f6 100644 --- a/common/src/main/java/common/block/foliage/BlockBlackenedSoil.java +++ b/common/src/common/block/BlockBlackenedSoil.java @@ -1,16 +1,14 @@ -package common.block.foliage; +package common.block; -import common.biome.Biome; -import common.block.Block; -import common.block.Material; import common.init.Blocks; +import common.init.Config; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.rng.Random; import common.util.BlockPos; -import common.vars.Vars; import common.world.State; import common.world.AWorldServer; @@ -18,19 +16,19 @@ public class BlockBlackenedSoil extends Block { public BlockBlackenedSoil() { - super(Material.LOOSE); + super(Material.grass); this.setTickRandomly(); - this.setTab(CheatTab.NATURE); + this.setTab(CheatTab.tabNature); } public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { if (worldIn.getLightFromNeighbors(pos.up()) < 2 && worldIn.getState(pos.up()).getBlock().getLightOpacity() > 6) { - if(Vars.darkSoilDecay) + if(Config.darkSoilDecay) worldIn.setState(pos, Blocks.blackened_dirt.getState()); } - else if (Vars.darkSoilSpread && worldIn.getLightFromNeighbors(pos.up()) >= 1) + else if (Config.darkSoilSpread && worldIn.getLightFromNeighbors(pos.up()) >= 1) { for (int i = 0; i < 4; i++) { @@ -41,7 +39,6 @@ public class BlockBlackenedSoil extends Block if ((iblockstate.getBlock() == Blocks.dirt || iblockstate.getBlock() == Blocks.grass || iblockstate.getBlock() == Blocks.blackened_dirt) && worldIn.getLightFromNeighbors(blockpos.up()) >= 2 && block.getLightOpacity() <= 6) { worldIn.setState(blockpos, Blocks.blackened_soil.getState()); - worldIn.setBiome(blockpos, Biome.BLACKENED); } } } diff --git a/common/src/main/java/common/block/natural/BlockBlackenedStone.java b/common/src/common/block/BlockBlackenedStone.java similarity index 73% rename from common/src/main/java/common/block/natural/BlockBlackenedStone.java rename to common/src/common/block/BlockBlackenedStone.java index bf35ab6..a28fdae 100644 --- a/common/src/main/java/common/block/natural/BlockBlackenedStone.java +++ b/common/src/common/block/BlockBlackenedStone.java @@ -1,18 +1,17 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; import common.init.Blocks; import common.init.ItemRegistry; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.rng.Random; import common.world.State; public class BlockBlackenedStone extends Block { public BlockBlackenedStone() { - super(Material.SOLID); - this.setTab(CheatTab.NATURE); + super(Material.rock); + this.setTab(CheatTab.tabNature); } public Item getItemDropped(State state, Random rand, int fortune) { diff --git a/common/src/main/java/common/block/foliage/BlockBlueShroom.java b/common/src/common/block/BlockBlueShroom.java similarity index 91% rename from common/src/main/java/common/block/foliage/BlockBlueShroom.java rename to common/src/common/block/BlockBlueShroom.java index 816e2cc..648fadf 100755 --- a/common/src/main/java/common/block/foliage/BlockBlueShroom.java +++ b/common/src/common/block/BlockBlueShroom.java @@ -1,12 +1,11 @@ -package common.block.foliage; +package common.block; -import common.block.Block; import common.init.Blocks; +import common.init.Config; import common.model.Model; import common.model.ModelProvider; import common.rng.Random; import common.util.BlockPos; -import common.vars.Vars; import common.world.State; import common.world.World; import common.world.AWorldServer; @@ -22,7 +21,7 @@ public class BlockBlueShroom extends BlockBush public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Vars.blueShroomGrowth > 0 && rand.chance(Vars.blueShroomGrowth)) + if (Config.blueShroomGrowth > 0 && rand.chance(Config.blueShroomGrowth)) { int i = 5; int j = 4; @@ -71,7 +70,7 @@ public class BlockBlueShroom extends BlockBush public boolean canBlockStay(World worldIn, BlockPos pos, State state) { - if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) + if (pos.getY() >= 0 && pos.getY() < 512) { State iblockstate = worldIn.getState(pos.down()); return (iblockstate.getBlock() == Blocks.tian_soil || iblockstate.getBlock() == Blocks.obsidian) ? true : (worldIn.getLight(pos) < 13 && this.canPlaceBlockOn(iblockstate.getBlock())); diff --git a/common/src/main/java/common/block/artificial/BlockBookshelf.java b/common/src/common/block/BlockBookshelf.java similarity index 83% rename from common/src/main/java/common/block/artificial/BlockBookshelf.java rename to common/src/common/block/BlockBookshelf.java index 756f574..a555b4c 100755 --- a/common/src/main/java/common/block/artificial/BlockBookshelf.java +++ b/common/src/common/block/BlockBookshelf.java @@ -1,10 +1,9 @@ -package common.block.artificial; +package common.block; -import common.block.Block; -import common.block.Material; import common.init.Items; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.rng.Random; @@ -14,8 +13,8 @@ public class BlockBookshelf extends Block { public BlockBookshelf() { - super(Material.WOOD); - this.setTab(CheatTab.DECORATION); + super(Material.wood); + this.setTab(CheatTab.tabDeco); } /** diff --git a/common/src/common/block/BlockBreakable.java b/common/src/common/block/BlockBreakable.java new file mode 100755 index 0000000..23a1c5d --- /dev/null +++ b/common/src/common/block/BlockBreakable.java @@ -0,0 +1,48 @@ +package common.block; + +import common.init.Blocks; +import common.material.Material; +import common.util.BlockPos; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; + +public class BlockBreakable extends Block +{ + private boolean ignoreSimilarity; + + public BlockBreakable(Material p_i46393_1_, boolean p_i46393_2_) + { + super(p_i46393_1_); + this.ignoreSimilarity = p_i46393_2_; + } + + /** + * Used to determine ambient occlusion and culling when rebuilding chunks for render + */ + public boolean isOpaqueCube() + { + return false; + } + + public boolean shouldSideBeRendered(IWorldAccess worldIn, BlockPos pos, Facing side) + { + State iblockstate = worldIn.getState(pos); + Block block = iblockstate.getBlock(); + + if (this == Blocks.glass || this == Blocks.stained_glass) + { + if (worldIn.getState(pos.offset(side.getOpposite())) != iblockstate) + { + return true; + } + + if (block == this) + { + return false; + } + } + + return !this.ignoreSimilarity && block == this ? false : super.shouldSideBeRendered(worldIn, pos, side); + } +} diff --git a/common/src/main/java/common/block/tech/BlockBrewingStand.java b/common/src/common/block/BlockBrewingStand.java similarity index 99% rename from common/src/main/java/common/block/tech/BlockBrewingStand.java rename to common/src/common/block/BlockBrewingStand.java index bcde12f..dcd6dc6 100755 --- a/common/src/main/java/common/block/tech/BlockBrewingStand.java +++ b/common/src/common/block/BlockBrewingStand.java @@ -1,9 +1,7 @@ -package common.block.tech; +package common.block; import java.util.List; -import common.block.BlockContainer; -import common.block.Material; import common.entity.Entity; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; @@ -12,6 +10,7 @@ import common.inventory.Container; import common.inventory.InventoryHelper; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -352,7 +351,7 @@ public class BlockBrewingStand extends BlockContainer public BlockBrewingStand() { - super(Material.SOLID); + super(Material.iron); this.setDefaultState(this.getBaseState().withProperty(HAS_BOTTLE[0], Boolean.valueOf(false)).withProperty(HAS_BOTTLE[1], Boolean.valueOf(false)).withProperty(HAS_BOTTLE[2], Boolean.valueOf(false))); } @@ -383,7 +382,7 @@ public class BlockBrewingStand extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityBrewingStand(); } diff --git a/common/src/main/java/common/block/foliage/BlockBush.java b/common/src/common/block/BlockBush.java similarity index 93% rename from common/src/main/java/common/block/foliage/BlockBush.java rename to common/src/common/block/BlockBush.java index acc0c1b..4ff09d6 100755 --- a/common/src/main/java/common/block/foliage/BlockBush.java +++ b/common/src/common/block/BlockBush.java @@ -1,9 +1,8 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; import common.init.Blocks; import common.item.CheatTab; +import common.material.Material; import common.model.BlockLayer; import common.rng.Random; import common.util.BlockPos; @@ -16,7 +15,7 @@ public class BlockBush extends Block { public BlockBush() { - this(Material.PLANT); + this(Material.plants); } public BlockBush(Material p_i46452_1_) @@ -25,7 +24,7 @@ public class BlockBush extends Block this.setTickRandomly(); float f = 0.2F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f * 3.0F, 0.5F + f); - this.setTab(CheatTab.PLANTS); + this.setTab(CheatTab.tabPlants); } public boolean canPlaceBlockAt(World worldIn, BlockPos pos) diff --git a/common/src/main/java/common/block/tech/BlockButton.java b/common/src/common/block/BlockButton.java similarity index 98% rename from common/src/main/java/common/block/tech/BlockButton.java rename to common/src/common/block/BlockButton.java index 956d0fe..28b690c 100755 --- a/common/src/main/java/common/block/tech/BlockButton.java +++ b/common/src/common/block/BlockButton.java @@ -1,9 +1,7 @@ -package common.block.tech; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.collect.Lists; import common.entity.Entity; import common.entity.npc.EntityNPC; @@ -11,6 +9,7 @@ import common.entity.projectile.EntityArrow; import common.entity.types.EntityLiving; import common.init.SoundEvent; import common.item.CheatTab; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -39,10 +38,10 @@ public class BlockButton extends Block public BlockButton(boolean arrows, int onTime, String texture) { - super(Material.SMALL); + super(Material.circuits); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(POWERED, Boolean.valueOf(false))); // this.setTickRandomly(true); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); this.checkArrows = arrows; this.onTime = onTime; this.texture = texture; diff --git a/common/src/main/java/common/block/foliage/BlockCactus.java b/common/src/common/block/BlockCactus.java similarity index 93% rename from common/src/main/java/common/block/foliage/BlockCactus.java rename to common/src/common/block/BlockCactus.java index 204599a..92db3ca 100755 --- a/common/src/main/java/common/block/foliage/BlockCactus.java +++ b/common/src/common/block/BlockCactus.java @@ -1,11 +1,11 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.DamageSource; import common.entity.Entity; import common.init.Blocks; +import common.init.Config; import common.item.CheatTab; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -15,14 +15,13 @@ import common.rng.Random; import common.util.BlockPos; import common.util.BoundingBox; import common.util.Facing; -import common.vars.Vars; import common.world.State; import common.world.World; import common.world.AWorldServer; public class BlockCactus extends Block { - private static final Model cactus = ModelProvider.getModelProvider().getModel("cactus_side") + private static final Model cactus = ModelProvider.getModelProvider().getModel("cactus_side").noOcclude() .add(0, 0, 0, 16, 16, 16) .d("cactus_bottom").uv(0, 0, 16, 16) .u("cactus_top").uv(0, 0, 16, 16) @@ -38,17 +37,17 @@ public class BlockCactus extends Block public BlockCactus() { - super(Material.BLOCKING); + super(Material.cactus); this.setDefaultState(this.getBaseState().withProperty(AGE, Integer.valueOf(0))); this.setTickRandomly(); - this.setTab(CheatTab.PLANTS); + this.setTab(CheatTab.tabPlants); } public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { BlockPos blockpos = pos.up(); - if (Vars.cactusHeight > 0 && worldIn.isAirBlock(blockpos)) + if (Config.cactusHeight > 0 && worldIn.isAirBlock(blockpos)) { int i; @@ -57,7 +56,7 @@ public class BlockCactus extends Block ; } - if (i < Vars.cactusHeight) + if (i < Config.cactusHeight) { int j = ((Integer)state.getValue(AGE)).intValue(); @@ -136,7 +135,7 @@ public class BlockCactus extends Block */ public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, State state, Entity entityIn) { - if(worldIn.client || Vars.cactusDamage) + if(worldIn.client || Config.cactusDamage) entityIn.attackEntityFrom(DamageSource.cactus, 1); } diff --git a/common/src/main/java/common/block/artificial/BlockCake.java b/common/src/common/block/BlockCake.java similarity index 98% rename from common/src/main/java/common/block/artificial/BlockCake.java rename to common/src/common/block/BlockCake.java index 425c641..6422758 100755 --- a/common/src/main/java/common/block/artificial/BlockCake.java +++ b/common/src/common/block/BlockCake.java @@ -1,10 +1,9 @@ -package common.block.artificial; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.npc.EntityNPC; import common.init.Items; import common.item.Item; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -90,7 +89,7 @@ public class BlockCake extends Block public BlockCake() { - super(Material.SOFT); + super(Material.cake); this.setDefaultState(this.getBaseState().withProperty(BITES, Integer.valueOf(0))); // this.setTickRandomly(true); } diff --git a/common/src/main/java/common/block/artificial/BlockCarpet.java b/common/src/common/block/BlockCarpet.java similarity index 96% rename from common/src/main/java/common/block/artificial/BlockCarpet.java rename to common/src/common/block/BlockCarpet.java index 6deb687..9b9a970 100755 --- a/common/src/main/java/common/block/artificial/BlockCarpet.java +++ b/common/src/common/block/BlockCarpet.java @@ -1,13 +1,12 @@ -package common.block.artificial; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.color.DyeColor; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.Transforms; @@ -25,11 +24,11 @@ public class BlockCarpet extends Block public BlockCarpet() { - super(Material.FLEECE); + super(Material.carpet); this.setDefaultState(this.getBaseState().withProperty(COLOR, DyeColor.WHITE)); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F); // this.setTickRandomly(true); - this.setTab(CheatTab.DECORATION); + this.setTab(CheatTab.tabDeco); this.setBlockBoundsFromMeta(0); } diff --git a/common/src/main/java/common/block/foliage/BlockCarrot.java b/common/src/common/block/BlockCarrot.java similarity index 94% rename from common/src/main/java/common/block/foliage/BlockCarrot.java rename to common/src/common/block/BlockCarrot.java index e35b94b..be7f274 100755 --- a/common/src/main/java/common/block/foliage/BlockCarrot.java +++ b/common/src/common/block/BlockCarrot.java @@ -1,4 +1,4 @@ -package common.block.foliage; +package common.block; import common.init.Items; import common.item.Item; diff --git a/common/src/main/java/common/block/tech/BlockCauldron.java b/common/src/common/block/BlockCauldron.java similarity index 97% rename from common/src/main/java/common/block/tech/BlockCauldron.java rename to common/src/common/block/BlockCauldron.java index 087c865..79f5739 100755 --- a/common/src/main/java/common/block/tech/BlockCauldron.java +++ b/common/src/common/block/BlockCauldron.java @@ -1,9 +1,7 @@ -package common.block.tech; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.entity.Entity; import common.entity.item.EntityItem; import common.entity.npc.EntityNPC; @@ -14,6 +12,7 @@ import common.item.Item; import common.item.ItemArmor; import common.item.ItemBanner; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; @@ -29,7 +28,7 @@ import common.world.World; public class BlockCauldron extends Block { - private static final Model cauldron_empty = ModelProvider.getModelProvider().getModel("cauldron_side") + private static final Model cauldron_empty = ModelProvider.getModelProvider().getModel("cauldron_side").noOcclude() .add(0, 3, 0, 2, 16, 16) .d("cauldron_inner").uv(0, 0, 2, 16) .u("cauldron_top").uv(0, 0, 2, 16) @@ -122,7 +121,7 @@ public class BlockCauldron extends Block .w().uv(14, 13, 12, 16).noCull() .e().uv(14, 13, 12, 16).noCull() ; - private static final Model cauldron_level1 = ModelProvider.getModelProvider().getModel("cauldron_side") + private static final Model cauldron_level1 = ModelProvider.getModelProvider().getModel("cauldron_side").noOcclude() .add(0, 3, 0, 2, 16, 16) .d("cauldron_inner").uv(0, 0, 2, 16) .u("cauldron_top").uv(0, 0, 2, 16) @@ -217,7 +216,7 @@ public class BlockCauldron extends Block .add(2, 9, 2, 14, 9, 14) .u("water_still").uv(2, 2, 14, 14).noCull() ; - private static final Model cauldron_level2 = ModelProvider.getModelProvider().getModel("cauldron_side") + private static final Model cauldron_level2 = ModelProvider.getModelProvider().getModel("cauldron_side").noOcclude() .add(0, 3, 0, 2, 16, 16) .d("cauldron_inner").uv(0, 0, 2, 16) .u("cauldron_top").uv(0, 0, 2, 16) @@ -312,7 +311,7 @@ public class BlockCauldron extends Block .add(2, 12, 2, 14, 12, 14) .u("water_still").uv(2, 2, 14, 14).noCull() ; - private static final Model cauldron_level3 = ModelProvider.getModelProvider().getModel("cauldron_side") + private static final Model cauldron_level3 = ModelProvider.getModelProvider().getModel("cauldron_side").noOcclude() .add(0, 3, 0, 2, 16, 16) .d("cauldron_inner").uv(0, 0, 2, 16) .u("cauldron_top").uv(0, 0, 2, 16) @@ -414,7 +413,7 @@ public class BlockCauldron extends Block public BlockCauldron() { - super(Material.SOLID); + super(Material.iron); this.setDefaultState(this.getBaseState().withProperty(LEVEL, Integer.valueOf(0))); } @@ -525,9 +524,9 @@ public class BlockCauldron extends Block } // playerIn.triggerAchievement(StatRegistry.cauldronUsedStat); - --itemstack.size; + --itemstack.stackSize; - if (itemstack.size <= 0) + if (itemstack.stackSize <= 0) { playerIn.inventory.setInventorySlotContents(playerIn.inventory.currentItem, (ItemStack)null); } @@ -556,10 +555,10 @@ public class BlockCauldron extends Block if (i > 0 && item instanceof ItemBanner && TileEntityBanner.getPatterns(itemstack) > 0) { ItemStack itemstack1 = itemstack.copy(); - itemstack1.size = 1; + itemstack1.stackSize = 1; TileEntityBanner.removeBannerData(itemstack1); - if (itemstack.size <= 1) // && !playerIn.creative) + if (itemstack.stackSize <= 1) // && !playerIn.creative) { playerIn.inventory.setInventorySlotContents(playerIn.inventory.currentItem, itemstack1); } @@ -578,7 +577,7 @@ public class BlockCauldron extends Block // if (!playerIn.creative) // { - --itemstack.size; + --itemstack.stackSize; // } } diff --git a/common/src/main/java/common/block/tech/BlockChest.java b/common/src/common/block/BlockChest.java similarity index 95% rename from common/src/main/java/common/block/tech/BlockChest.java rename to common/src/common/block/BlockChest.java index 75d977d..a195e29 100755 --- a/common/src/main/java/common/block/tech/BlockChest.java +++ b/common/src/common/block/BlockChest.java @@ -1,13 +1,11 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.BlockContainer; -import common.block.Material; import common.color.TextColor; import common.entity.Entity; import common.entity.animal.EntityOcelot; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; +import common.init.Config; import common.init.Items; import common.init.SoundEvent; import common.inventory.Container; @@ -16,18 +14,18 @@ import common.inventory.InventoryHelper; import common.inventory.InventoryLargeChest; import common.item.CheatTab; import common.item.ItemStack; -import common.packet.SPacketSoundEffect; +import common.material.Material; +import common.packet.S29PacketSoundEffect; import common.properties.IProperty; import common.properties.PropertyDirection; import common.tileentity.ILockableContainer; -import common.tileentity.Passcode; +import common.tileentity.LockCode; import common.tileentity.TileEntity; import common.tileentity.TileEntityChest; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; import common.util.Facing; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.State; import common.world.World; @@ -42,10 +40,10 @@ public class BlockChest extends BlockContainer public BlockChest(int type) { - super(Material.WOOD); + super(Material.wood); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); this.chestType = type; - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); } @@ -443,22 +441,22 @@ public class BlockChest extends BlockContainer if (ilockablecontainer != null) { - ItemStack stack = Vars.locking ? playerIn.getHeldItem() : null; + ItemStack stack = Config.locking ? playerIn.getHeldItem() : null; if(stack != null && stack.getItem() == Items.key) { if(ilockablecontainer.isLocked()) { - if(stack.hasDisplayName() && stack.getDisplayName().equals(ilockablecontainer.getLockCode().code())) { - ilockablecontainer.setLockCode(Passcode.EMPTY_CODE); + if(stack.hasDisplayName() && stack.getDisplayName().equals(ilockablecontainer.getLockCode().getLock())) { + ilockablecontainer.setLockCode(LockCode.EMPTY_CODE); // playerIn.triggerAchievement(StatRegistry.chestUnlockedStat); playerIn.connection.addHotbar(TextColor.BLUE + "%s wurde entriegelt", ilockablecontainer.getCommandName()); - playerIn.connection.sendPacket(new SPacketSoundEffect(SoundEvent.DOOR, playerIn.posX, playerIn.posY, playerIn.posZ, 1.0F)); + playerIn.connection.sendPacket(new S29PacketSoundEffect(SoundEvent.DOOR, playerIn.posX, playerIn.posY, playerIn.posZ, 1.0F)); return true; } } else if(stack.hasDisplayName()) { - ilockablecontainer.setLockCode(new Passcode(stack.getDisplayName())); + ilockablecontainer.setLockCode(new LockCode(stack.getDisplayName())); // playerIn.triggerAchievement(StatRegistry.chestLockedStat); playerIn.connection.addHotbar(TextColor.ORANGE + "%s wurde verriegelt", ilockablecontainer.getCommandName()); - playerIn.connection.sendPacket(new SPacketSoundEffect(SoundEvent.DOOR, playerIn.posX, playerIn.posY, playerIn.posZ, 1.0F)); + playerIn.connection.sendPacket(new S29PacketSoundEffect(SoundEvent.DOOR, playerIn.posX, playerIn.posY, playerIn.posZ, 1.0F)); return true; } } @@ -532,7 +530,7 @@ public class BlockChest extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityChest(); } diff --git a/common/src/main/java/common/block/natural/BlockClay.java b/common/src/common/block/BlockClay.java similarity index 78% rename from common/src/main/java/common/block/natural/BlockClay.java rename to common/src/common/block/BlockClay.java index 9f15600..c1d0259 100755 --- a/common/src/main/java/common/block/natural/BlockClay.java +++ b/common/src/common/block/BlockClay.java @@ -1,10 +1,9 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; import common.init.Items; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.rng.Random; import common.world.State; @@ -12,8 +11,8 @@ public class BlockClay extends Block { public BlockClay() { - super(Material.LOOSE); - this.setTab(CheatTab.NATURE); + super(Material.clay); + this.setTab(CheatTab.tabNature); } /** diff --git a/common/src/main/java/common/block/foliage/BlockCocoa.java b/common/src/common/block/BlockCocoa.java similarity index 95% rename from common/src/main/java/common/block/foliage/BlockCocoa.java rename to common/src/common/block/BlockCocoa.java index 3f8e27c..7eff652 100755 --- a/common/src/main/java/common/block/foliage/BlockCocoa.java +++ b/common/src/common/block/BlockCocoa.java @@ -1,14 +1,13 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.BlockDirectional; -import common.block.Material; import common.color.DyeColor; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -19,7 +18,6 @@ import common.rng.Random; import common.util.BlockPos; import common.util.BoundingBox; import common.util.Facing; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.State; import common.world.World; @@ -31,7 +29,7 @@ public class BlockCocoa extends BlockDirectional implements IGrowable public BlockCocoa() { - super(Material.PLANT); + super(Material.plants); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(AGE, Integer.valueOf(0))); this.setTickRandomly(); } @@ -42,7 +40,7 @@ public class BlockCocoa extends BlockDirectional implements IGrowable { this.dropBlock(worldIn, pos, state); } - else if (Vars.cocoaGrowth > 0 && worldIn.rand.chance(Vars.cocoaGrowth)) + else if (Config.cocoaGrowth > 0 && worldIn.rand.chance(Config.cocoaGrowth)) { int i = ((Integer)state.getValue(AGE)).intValue(); @@ -237,7 +235,7 @@ public class BlockCocoa extends BlockDirectional implements IGrowable Model model; switch(state.getValue(AGE)) { case 0: - model = provider.getModel("cocoa_0") + model = provider.getModel("cocoa_0").noOcclude() .add(6, 7, 11, 10, 12, 15) .d().uv(0, 0, 4, 4).noCull() .u().uv(0, 0, 4, 4).noCull() @@ -250,7 +248,7 @@ public class BlockCocoa extends BlockDirectional implements IGrowable .e().uv(16, 0, 12, 4).noCull(); break; case 1: - model = provider.getModel("cocoa_1") + model = provider.getModel("cocoa_1").noOcclude() .add(5, 5, 9, 11, 12, 15) .d().uv(0, 0, 6, 6).noCull() .u().uv(0, 0, 6, 6).noCull() @@ -264,7 +262,7 @@ public class BlockCocoa extends BlockDirectional implements IGrowable break; case 2: default: - model = provider.getModel("cocoa_2") + model = provider.getModel("cocoa_2").noOcclude() .add(4, 3, 7, 12, 12, 15) .d().uv(0, 0, 7, 7).noCull() .u().uv(0, 0, 7, 7).noCull() diff --git a/common/src/common/block/BlockColored.java b/common/src/common/block/BlockColored.java new file mode 100755 index 0000000..8516cbc --- /dev/null +++ b/common/src/common/block/BlockColored.java @@ -0,0 +1,79 @@ +package common.block; + +import java.util.List; + +import common.color.DyeColor; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.material.Material; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.world.State; + +public class BlockColored extends Block +{ + public static final PropertyEnum COLOR = PropertyEnum.create("color", DyeColor.class); + + public BlockColored(Material materialIn) + { + super(materialIn); + this.setDefaultState(this.getBaseState().withProperty(COLOR, DyeColor.WHITE)); + this.setTab(CheatTab.tabBlocks); + } + + /** + * Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It + * returns the metadata of the dropped item based on the old metadata of the block. + */ + public int damageDropped(State state) + { + return ((DyeColor)state.getValue(COLOR)).getMetadata(); + } + + /** + * returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks) + */ + public void getSubBlocks(Item itemIn, CheatTab tab, List list) + { + for (DyeColor enumdyecolor : DyeColor.values()) + { + list.add(new ItemStack(itemIn, 1, enumdyecolor.getMetadata())); + } + } + +// /** +// * Get the MapColor for this Block and the given BlockState +// */ +// public MapColor getMapColor(IBlockState state) +// { +// return ((EnumDyeColor)state.getValue(COLOR)).getMapColor(); +// } + + /** + * Convert the given metadata into a BlockState for this Block + */ + public State getStateFromMeta(int meta) + { + return this.getState().withProperty(COLOR, DyeColor.byMetadata(meta)); + } + + /** + * Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(State state) + { + return ((DyeColor)state.getValue(COLOR)).getMetadata(); + } + + protected IProperty[] getProperties() + { + return new IProperty[] {COLOR}; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(state.getValue(COLOR).getName() + "_" + name).add().all(); + } +} diff --git a/common/src/main/java/common/block/artificial/BlockCompressedPowered.java b/common/src/common/block/BlockCompressedPowered.java similarity index 87% rename from common/src/main/java/common/block/artificial/BlockCompressedPowered.java rename to common/src/common/block/BlockCompressedPowered.java index bd2af8d..4168977 100755 --- a/common/src/main/java/common/block/artificial/BlockCompressedPowered.java +++ b/common/src/common/block/BlockCompressedPowered.java @@ -1,7 +1,6 @@ -package common.block.artificial; +package common.block; -import common.block.Block; -import common.block.Material; +import common.material.Material; import common.util.BlockPos; import common.util.Facing; import common.world.IWorldAccess; diff --git a/common/src/common/block/BlockContainer.java b/common/src/common/block/BlockContainer.java new file mode 100755 index 0000000..78a927b --- /dev/null +++ b/common/src/common/block/BlockContainer.java @@ -0,0 +1,52 @@ +package common.block; + +import common.material.Material; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; + +public abstract class BlockContainer extends Block implements ITileEntityProvider +{ + public BlockContainer(Material p_i46402_1_) + { + super(p_i46402_1_); + this.hasTile = true; + } + + protected boolean isInvalidNeighbor(World p_181086_1_, BlockPos p_181086_2_, Facing p_181086_3_) + { + return p_181086_1_.getState(p_181086_2_.offset(p_181086_3_)).getBlock().getMaterial() == Material.cactus; + } + + protected boolean hasInvalidNeighbor(World p_181087_1_, BlockPos p_181087_2_) + { + return this.isInvalidNeighbor(p_181087_1_, p_181087_2_, Facing.NORTH) || this.isInvalidNeighbor(p_181087_1_, p_181087_2_, Facing.SOUTH) || this.isInvalidNeighbor(p_181087_1_, p_181087_2_, Facing.WEST) || this.isInvalidNeighbor(p_181087_1_, p_181087_2_, Facing.EAST); + } + + /** + * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() + { + return -1; + } + + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) + { + super.onBlockRemoved(worldIn, pos, state); + worldIn.removeTileEntity(pos); + } + + /** + * Called on both Client and Server when World#addBlockEvent is called + */ + public boolean onBlockEventReceived(World worldIn, BlockPos pos, State state, int eventID, int eventParam) + { + super.onBlockEventReceived(worldIn, pos, state, eventID, eventParam); + TileEntity tileentity = worldIn.getTileEntity(pos); + return tileentity == null ? false : tileentity.receiveClientEvent(eventID, eventParam); + } +} diff --git a/common/src/main/java/common/block/tech/BlockCore.java b/common/src/common/block/BlockCore.java similarity index 66% rename from common/src/main/java/common/block/tech/BlockCore.java rename to common/src/common/block/BlockCore.java index 131e2e7..d23bada 100755 --- a/common/src/main/java/common/block/tech/BlockCore.java +++ b/common/src/common/block/BlockCore.java @@ -1,28 +1,27 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.Material; +import common.init.Config; import common.item.CheatTab; +import common.material.Material; import common.util.BlockPos; -import common.vars.Vars; import common.world.State; import common.world.AWorldServer; public class BlockCore extends Block { public BlockCore() { - super(Material.SOLID); - this.setTab(CheatTab.TECHNOLOGY); + super(Material.iron); + this.setTab(CheatTab.tabTech); } public void onBlockRemoved(AWorldServer world, BlockPos pos, State state) { - if(Vars.loaders) + if(Config.loaders) world.removeLoader(pos); } public void onBlockAdded(AWorldServer world, BlockPos pos, State state) { - if(Vars.loaders) + if(Config.loaders) world.addLoader(pos); } } diff --git a/common/src/main/java/common/block/foliage/BlockCrops.java b/common/src/common/block/BlockCrops.java similarity index 93% rename from common/src/main/java/common/block/foliage/BlockCrops.java rename to common/src/common/block/BlockCrops.java index db1806e..fbf07d6 100755 --- a/common/src/main/java/common/block/foliage/BlockCrops.java +++ b/common/src/common/block/BlockCrops.java @@ -1,8 +1,7 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.SoundType; import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.item.CheatTab; import common.item.Item; @@ -13,7 +12,6 @@ import common.properties.IProperty; import common.properties.PropertyInteger; import common.rng.Random; import common.util.BlockPos; -import common.vars.Vars; import common.world.State; import common.world.World; import common.world.AWorldServer; @@ -46,7 +44,7 @@ public class BlockCrops extends BlockBush implements IGrowable { super.updateTick(worldIn, pos, state, rand); - if (Vars.cropGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9) + if (Config.cropGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9) { int i = ((Integer)state.getValue(AGE)).intValue(); @@ -54,7 +52,7 @@ public class BlockCrops extends BlockBush implements IGrowable { float f = getGrowthChance(this, worldIn, pos); - if (rand.chance((int)((float)(Vars.cropGrowth - 1) / f) + 1)) + if (rand.chance((int)((float)(Config.cropGrowth - 1) / f) + 1)) { worldIn.setState(pos, state.withProperty(AGE, Integer.valueOf(i + 1)), 2); } @@ -131,7 +129,7 @@ public class BlockCrops extends BlockBush implements IGrowable public boolean canBlockStay(World worldIn, BlockPos pos, State state) { - return (worldIn.getLight(pos) >= 8 || worldIn.canSeeSky(pos)) && this.canPlaceBlockOn(worldIn.getState(pos.down()).getBlock()); + return this.canPlaceBlockOn(worldIn.getState(pos.down()).getBlock()); } protected Item getSeed() @@ -227,7 +225,7 @@ public class BlockCrops extends BlockBush implements IGrowable } public static Model crop(ModelProvider provider, String crop) { - return provider.getModel(crop) + return provider.getModel(crop).noOcclude() .add(4, -1, 0, 4, 15, 16).noShade() .w().uv(0, 0, 16, 16).noCull() .e().uv(0, 0, 16, 16).noCull() diff --git a/common/src/main/java/common/block/tech/BlockDaylightDetector.java b/common/src/common/block/BlockDaylightDetector.java similarity index 93% rename from common/src/main/java/common/block/tech/BlockDaylightDetector.java rename to common/src/common/block/BlockDaylightDetector.java index f35f530..735a4bb 100755 --- a/common/src/main/java/common/block/tech/BlockDaylightDetector.java +++ b/common/src/common/block/BlockDaylightDetector.java @@ -1,16 +1,14 @@ -package common.block.tech; +package common.block; import java.util.List; -import common.block.BlockContainer; -import common.block.Material; -import common.block.SoundType; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.init.ItemRegistry; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.Transforms; @@ -23,7 +21,6 @@ import common.util.BlockPos; import common.util.ExtMath; import common.util.Facing; import common.world.IWorldAccess; -import common.world.LightType; import common.world.State; import common.world.World; import common.world.AWorldServer; @@ -35,11 +32,11 @@ public class BlockDaylightDetector extends BlockContainer public BlockDaylightDetector(boolean inverted) { - super(Material.WOOD); + super(Material.wood); this.inverted = inverted; this.setDefaultState(this.getBaseState().withProperty(POWER, Integer.valueOf(0))); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.375F, 1.0F); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); this.setHardness(0.2F); this.setStepSound(SoundType.WOOD); // this.setDisplay("daylightDetector"); @@ -60,7 +57,7 @@ public class BlockDaylightDetector extends BlockContainer if (!worldIn.dimension.hasNoLight()) { State iblockstate = worldIn.getState(pos); - int i = worldIn.getLightFor(LightType.SKY, pos) - worldIn.getSkylightSubtracted(); + int i = 15 - worldIn.getSkylightSubtracted(); float f = worldIn.getCelestialAngleRadians(1.0F); float f1 = f < (float)Math.PI ? 0.0F : ((float)Math.PI * 2F); f = f + (f1 - f) * 0.2F; @@ -154,7 +151,7 @@ public class BlockDaylightDetector extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityDaylightDetector(); } diff --git a/common/src/main/java/common/block/foliage/BlockDeadBush.java b/common/src/common/block/BlockDeadBush.java similarity index 94% rename from common/src/main/java/common/block/foliage/BlockDeadBush.java rename to common/src/common/block/BlockDeadBush.java index 9e24f13..3e091db 100755 --- a/common/src/main/java/common/block/foliage/BlockDeadBush.java +++ b/common/src/common/block/BlockDeadBush.java @@ -1,13 +1,12 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.init.Items; import common.item.Item; import common.item.ItemShears; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.rng.Random; @@ -20,7 +19,7 @@ public class BlockDeadBush extends BlockBush { public BlockDeadBush() { - super(Material.BUSH); + super(Material.vine); float f = 0.4F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.8F, 0.5F + f); } diff --git a/common/src/common/block/BlockDirectional.java b/common/src/common/block/BlockDirectional.java new file mode 100755 index 0000000..b80351a --- /dev/null +++ b/common/src/common/block/BlockDirectional.java @@ -0,0 +1,15 @@ +package common.block; + +import common.material.Material; +import common.properties.PropertyDirection; +import common.util.Facing; + +public abstract class BlockDirectional extends Block +{ + public static final PropertyDirection FACING = PropertyDirection.create("facing", Facing.Plane.HORIZONTAL); + + public BlockDirectional(Material materialIn) + { + super(materialIn); + } +} diff --git a/common/src/main/java/common/block/natural/BlockDirt.java b/common/src/common/block/BlockDirt.java similarity index 97% rename from common/src/main/java/common/block/natural/BlockDirt.java rename to common/src/common/block/BlockDirt.java index f93a03c..11e24ab 100755 --- a/common/src/main/java/common/block/natural/BlockDirt.java +++ b/common/src/common/block/BlockDirt.java @@ -1,13 +1,12 @@ -package common.block.natural; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.init.Blocks; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; @@ -26,9 +25,9 @@ public class BlockDirt extends Block public BlockDirt() { - super(Material.LOOSE); + super(Material.ground); this.setDefaultState(this.getBaseState().withProperty(VARIANT, BlockDirt.DirtType.DIRT).withProperty(SNOWY, Boolean.valueOf(false))); - this.setTab(CheatTab.NATURE); + this.setTab(CheatTab.tabNature); } // /** diff --git a/common/src/main/java/common/block/tech/BlockDispenser.java b/common/src/common/block/BlockDispenser.java similarity index 95% rename from common/src/main/java/common/block/tech/BlockDispenser.java rename to common/src/common/block/BlockDispenser.java index 4421fbb..1a80d27 100755 --- a/common/src/main/java/common/block/tech/BlockDispenser.java +++ b/common/src/common/block/BlockDispenser.java @@ -1,14 +1,10 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.BlockContainer; -import common.block.Material; import common.dispenser.BehaviorDefaultDispenseItem; import common.dispenser.IBehaviorDispenseItem; import common.dispenser.IBlockSource; import common.dispenser.IPosition; -import common.dispenser.DispenserPos; -import common.dispenser.DispenserSource; +import common.dispenser.PositionImpl; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.DispenserRegistry; @@ -17,6 +13,7 @@ import common.inventory.InventoryHelper; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -42,9 +39,9 @@ public class BlockDispenser extends BlockContainer public BlockDispenser() { - super(Material.SOLID); + super(Material.rock); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(TRIGGERED, Boolean.valueOf(false))); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); } /** @@ -126,7 +123,7 @@ public class BlockDispenser extends BlockContainer protected void dispense(World worldIn, BlockPos pos) { - DispenserSource blocksourceimpl = new DispenserSource(worldIn, pos); + BlockSourceImpl blocksourceimpl = new BlockSourceImpl(worldIn, pos); TileEntityDispenser tileentitydispenser = (TileEntityDispenser)blocksourceimpl.getBlockTileEntity(); if (tileentitydispenser != null) @@ -145,7 +142,7 @@ public class BlockDispenser extends BlockContainer if (ibehaviordispenseitem != IBehaviorDispenseItem.itemDispenseBehaviorProvider) { ItemStack itemstack1 = ibehaviordispenseitem.dispense(blocksourceimpl, itemstack); - tileentitydispenser.setInventorySlotContents(i, itemstack1.size <= 0 ? null : itemstack1); + tileentitydispenser.setInventorySlotContents(i, itemstack1.stackSize <= 0 ? null : itemstack1); } } } @@ -186,7 +183,7 @@ public class BlockDispenser extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityDispenser(); } @@ -240,7 +237,7 @@ public class BlockDispenser extends BlockContainer double d0 = coords.getX() + 0.7D * (double)enumfacing.getFrontOffsetX(); double d1 = coords.getY() + 0.7D * (double)enumfacing.getFrontOffsetY(); double d2 = coords.getZ() + 0.7D * (double)enumfacing.getFrontOffsetZ(); - return new DispenserPos(d0, d1, d2); + return new PositionImpl(d0, d1, d2); } /** diff --git a/common/src/main/java/common/block/artificial/BlockDoor.java b/common/src/common/block/BlockDoor.java similarity index 97% rename from common/src/main/java/common/block/artificial/BlockDoor.java rename to common/src/common/block/BlockDoor.java index eb445ea..8388100 100755 --- a/common/src/main/java/common/block/artificial/BlockDoor.java +++ b/common/src/common/block/BlockDoor.java @@ -1,14 +1,13 @@ -package common.block.artificial; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.collect.Lists; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.init.Items; import common.item.Item; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -163,7 +162,7 @@ public class BlockDoor extends Block public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { - if (this.material == Material.SOLID) + if (this.material == Material.iron) { return true; } @@ -292,7 +291,7 @@ public class BlockDoor extends Block public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { - return pos.getY() >= World.MAX_SIZE_Y - 1 ? false : worldIn.isBlockSolid(pos.down()) && super.canPlaceBlockAt(worldIn, pos) && super.canPlaceBlockAt(worldIn, pos.up()); + return pos.getY() >= 511 ? false : worldIn.isBlockSolid(pos.down()) && super.canPlaceBlockAt(worldIn, pos) && super.canPlaceBlockAt(worldIn, pos.up()); } public int getMobilityFlag() @@ -460,7 +459,7 @@ public class BlockDoor extends Block String top = name + "_top"; if(state.getValue(HALF) == EnumDoorHalf.LOWER) { if(state.getValue(HINGE) == EnumHingePosition.LEFT == state.getValue(OPEN)) - return provider.getModel(bottom) + return provider.getModel(bottom).noOcclude() .add(0, 0, 0, 3, 16, 16) .d().uv(13, 0, 16, 16) .n().uv(3, 0, 0, 16) @@ -469,7 +468,7 @@ public class BlockDoor extends Block .e().uv(0, 0, 16, 16).noCull() .rotate(getRotation(state.getValue(FACING), state.getValue(OPEN) ? 1 : 0)); else - return provider.getModel(bottom) + return provider.getModel(bottom).noOcclude() .add(0, 0, 0, 3, 16, 16) .d().uv(13, 0, 16, 16) .n().uv(3, 0, 0, 16) @@ -480,7 +479,7 @@ public class BlockDoor extends Block } else { if(state.getValue(HINGE) == EnumHingePosition.LEFT == state.getValue(OPEN)) - return provider.getModel(top) + return provider.getModel(top).noOcclude() .add(0, 0, 0, 3, 16, 16) .u(bottom).uv(13, 0, 16, 16) .n().uv(3, 0, 0, 16) @@ -489,7 +488,7 @@ public class BlockDoor extends Block .e().uv(0, 0, 16, 16).noCull() .rotate(getRotation(state.getValue(FACING), state.getValue(OPEN) ? 1 : 0)); else - return provider.getModel(top) + return provider.getModel(top).noOcclude() .add(0, 0, 0, 3, 16, 16) .u(bottom).uv(13, 0, 16, 16) .n().uv(3, 0, 0, 16) diff --git a/common/src/main/java/common/block/foliage/BlockDoublePlant.java b/common/src/common/block/BlockDoublePlant.java similarity index 98% rename from common/src/main/java/common/block/foliage/BlockDoublePlant.java rename to common/src/common/block/BlockDoublePlant.java index 34ef424..2e835f5 100755 --- a/common/src/main/java/common/block/foliage/BlockDoublePlant.java +++ b/common/src/common/block/BlockDoublePlant.java @@ -1,21 +1,19 @@ -package common.block.foliage; +package common.block; import java.util.List; -import common.block.Block; -import common.block.BlockDirectional; -import common.block.Material; -import common.block.SoundType; import common.color.Colorizer; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.init.Config; import common.init.ItemRegistry; import common.init.Items; import common.item.CheatTab; import common.item.Item; import common.item.ItemShears; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; @@ -26,7 +24,6 @@ import common.util.BlockPos; import common.util.Facing; import common.util.Identifyable; import common.util.Facing.Axis; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.State; import common.world.World; @@ -40,7 +37,7 @@ public class BlockDoublePlant extends BlockBush implements IGrowable public BlockDoublePlant() { - super(Material.BUSH); + super(Material.vine); this.setDefaultState(this.getBaseState().withProperty(VARIANT, BlockDoublePlant.EnumPlantType.SUNFLOWER).withProperty(HALF, BlockDoublePlant.EnumBlockHalf.LOWER).withProperty(FACING, Facing.NORTH)); this.setHardness(0.0F); this.setStepSound(SoundType.GRASS); @@ -50,7 +47,7 @@ public class BlockDoublePlant extends BlockBush implements IGrowable public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Vars.plantDry && worldIn.getTemperatureC(pos) >= 50.0f) + if(Config.plantDry && worldIn.getTemperatureC(pos) >= 50.0f) { boolean upper = state.getValue(HALF) == EnumBlockHalf.UPPER; if(!upper) @@ -350,7 +347,7 @@ public class BlockDoublePlant extends BlockBush implements IGrowable public Model getModel(ModelProvider provider, String name, State state) { if(state.getValue(VARIANT) == EnumPlantType.SUNFLOWER && state.getValue(HALF) == EnumBlockHalf.UPPER) - return provider.getModel("sunflower_front") + return provider.getModel("sunflower_front").noOcclude() .add(0.8f, 0f, 8f, 15.2f, 8f, 8f).noShade().rotate(8, 8, 8, Axis.Y, 45, true).ns("sunflower_top") .uv(0, 8, 16, 16).noCull() .add(8f, 0f, 0.8f, 8f, 8f, 15.2f).noShade().rotate(8, 8, 8, Axis.Y, 45, true).we("sunflower_top") diff --git a/common/src/main/java/common/block/artificial/BlockDragonEgg.java b/common/src/common/block/BlockDragonEgg.java similarity index 94% rename from common/src/main/java/common/block/artificial/BlockDragonEgg.java rename to common/src/common/block/BlockDragonEgg.java index cef344c..2d90ee8 100755 --- a/common/src/main/java/common/block/artificial/BlockDragonEgg.java +++ b/common/src/common/block/BlockDragonEgg.java @@ -1,18 +1,15 @@ -package common.block.artificial; +package common.block; -import common.block.Block; -import common.block.BlockFalling; -import common.block.Material; import common.entity.item.EntityFalling; import common.entity.npc.EntityNPC; -import common.init.Blocks; +import common.init.Config; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ParticleType; import common.rng.Random; import common.util.BlockPos; import common.util.Facing; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.State; import common.world.World; @@ -20,7 +17,7 @@ import common.world.AWorldServer; public class BlockDragonEgg extends Block { - private static final Model dragon_egg = ModelProvider.getModelProvider().getModel("dragon_egg") + private static final Model dragon_egg = ModelProvider.getModelProvider().getModel("dragon_egg").noOcclude() .add(6, 15, 6, 10, 16, 10) .d().uv(6, 6, 10, 10).noCull() .u().uv(6, 6, 10, 10).noCull() @@ -81,7 +78,7 @@ public class BlockDragonEgg extends Block public BlockDragonEgg() { - super(Material.SOFT); + super(Material.dragonEgg); this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 1.0F, 0.9375F); } @@ -100,7 +97,7 @@ public class BlockDragonEgg extends Block public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Vars.blockGravity) + if(Config.blockGravity) this.checkFall(worldIn, pos); } @@ -149,7 +146,7 @@ public class BlockDragonEgg extends Block { BlockPos blockpos = pos.add(worldIn.rand.zrange(16) - worldIn.rand.zrange(16), worldIn.rand.zrange(8) - worldIn.rand.zrange(8), worldIn.rand.zrange(16) - worldIn.rand.zrange(16)); - if (worldIn.getState(blockpos).getBlock() == Blocks.air) + if (worldIn.getState(blockpos).getBlock().material == Material.air) { if (worldIn.client) { @@ -168,7 +165,7 @@ public class BlockDragonEgg extends Block else { worldIn.setBlockToAir(pos); - if(!Vars.blockGravity) { + if(!Config.blockGravity) { BlockPos blockpos2; for(blockpos2 = blockpos; BlockFalling.canFallInto(worldIn, blockpos2) && blockpos2.getY() > 0; blockpos2 = blockpos2.down()) { } diff --git a/common/src/main/java/common/block/tech/BlockDropper.java b/common/src/common/block/BlockDropper.java similarity index 89% rename from common/src/main/java/common/block/tech/BlockDropper.java rename to common/src/common/block/BlockDropper.java index 8d2f890..ec42106 100755 --- a/common/src/main/java/common/block/tech/BlockDropper.java +++ b/common/src/common/block/BlockDropper.java @@ -1,7 +1,6 @@ -package common.block.tech; +package common.block; import common.dispenser.BehaviorDefaultDispenseItem; -import common.dispenser.DispenserSource; import common.dispenser.IBehaviorDispenseItem; import common.inventory.IInventory; import common.item.ItemStack; @@ -25,14 +24,14 @@ public class BlockDropper extends BlockDispenser /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityDropper(); } protected void dispense(World worldIn, BlockPos pos) { - DispenserSource blocksourceimpl = new DispenserSource(worldIn, pos); + BlockSourceImpl blocksourceimpl = new BlockSourceImpl(worldIn, pos); TileEntityDispenser tileentitydispenser = (TileEntityDispenser)blocksourceimpl.getBlockTileEntity(); if (tileentitydispenser != null) @@ -58,7 +57,7 @@ public class BlockDropper extends BlockDispenser { itemstack1 = this.dropBehavior.dispense(blocksourceimpl, itemstack); - if (itemstack1 != null && itemstack1.size <= 0) + if (itemstack1 != null && itemstack1.stackSize <= 0) { itemstack1 = null; } @@ -71,7 +70,7 @@ public class BlockDropper extends BlockDispenser { itemstack1 = itemstack.copy(); - if (--itemstack1.size <= 0) + if (--itemstack1.stackSize <= 0) { itemstack1 = null; } diff --git a/common/src/main/java/common/block/foliage/BlockDryLeaves.java b/common/src/common/block/BlockDryLeaves.java similarity index 90% rename from common/src/main/java/common/block/foliage/BlockDryLeaves.java rename to common/src/common/block/BlockDryLeaves.java index a227249..5ed08d6 100755 --- a/common/src/main/java/common/block/foliage/BlockDryLeaves.java +++ b/common/src/common/block/BlockDryLeaves.java @@ -1,10 +1,9 @@ -package common.block.foliage; +package common.block; -import common.block.Material; -import common.block.SoundType; import common.init.Items; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.rng.Random; import common.world.State; @@ -14,8 +13,8 @@ public class BlockDryLeaves extends BlockLeavesBase public BlockDryLeaves() { - super(Material.SOFT); - this.setTab(CheatTab.PLANTS); + super(Material.gourd); + this.setTab(CheatTab.tabPlants); this.setHardness(0.2F); this.setLightOpacity(1); this.setStepSound(SoundType.GRASS); diff --git a/common/src/main/java/common/block/liquid/BlockDynamicLiquid.java b/common/src/common/block/BlockDynamicLiquid.java similarity index 87% rename from common/src/main/java/common/block/liquid/BlockDynamicLiquid.java rename to common/src/common/block/BlockDynamicLiquid.java index 98a4d51..e9a1eda 100755 --- a/common/src/main/java/common/block/liquid/BlockDynamicLiquid.java +++ b/common/src/common/block/BlockDynamicLiquid.java @@ -1,16 +1,14 @@ -package common.block.liquid; +package common.block; import java.util.EnumSet; import java.util.Set; -import common.block.Block; -import common.block.Material; -import common.block.artificial.BlockDoor; import common.init.Blocks; +import common.init.Config; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.util.Facing; -import common.vars.Vars; import common.world.State; import common.world.World; import common.world.AWorldServer; @@ -33,7 +31,7 @@ public class BlockDynamicLiquid extends BlockLiquid public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(!Vars.liquidPhysics) + if(!Config.liquidPhysics) return; int i = ((Integer)state.getValue(LEVEL)).intValue(); int j = 1; @@ -76,10 +74,10 @@ public class BlockDynamicLiquid extends BlockLiquid } } - if (this.adjacentSourceBlocks >= 2 && ((Vars.mergeWater && this.material == Material.WATER) - || (Vars.mergeLava && this.material == Material.LAVA) - || (this.infinite && Vars.mergeInfinite && this.material != Material.WATER && this.material != Material.LAVA) - || (!this.infinite && Vars.mergeFinite && this.material != Material.WATER && this.material != Material.LAVA))) + if (this.adjacentSourceBlocks >= 2 && ((Config.mergeWater && this.material == Material.water) + || (Config.mergeLava && this.material == Material.lava) + || (this.infinite && Config.mergeInfinite && this.material != Material.water && this.material != Material.lava) + || (!this.infinite && Config.mergeFinite && this.material != Material.water && this.material != Material.lava))) { State iblockstate1 = worldIn.getState(pos.down()); @@ -128,7 +126,7 @@ public class BlockDynamicLiquid extends BlockLiquid if (this.canFlowInto(worldIn, pos.down(), iblockstate)) { - if (this.material == Material.LAVA && worldIn.getState(pos.down()).getBlock().getMaterial().isColdLiquid()) + if (this.material == Material.lava && worldIn.getState(pos.down()).getBlock().getMaterial().isColdLiquid()) { worldIn.setState(pos.down(), Blocks.stone.getState()); this.triggerMixEffects(worldIn, pos.down()); @@ -172,7 +170,7 @@ public class BlockDynamicLiquid extends BlockLiquid { if (state.getBlock() != Blocks.air) { - if (this.material == Material.LAVA) + if (this.material == Material.lava) { this.triggerMixEffects(worldIn, pos); } @@ -262,7 +260,7 @@ public class BlockDynamicLiquid extends BlockLiquid private boolean isBlocked(World worldIn, BlockPos pos, State state) { Block block = worldIn.getState(pos).getBlock(); - return !(block instanceof BlockDoor) && block != Blocks.sign && block != Blocks.ladder && block != Blocks.reeds ? (block.getMaterial() == Material.PORTAL ? true : block.getMaterial().blocksMovement()) : true; + return !(block instanceof BlockDoor) && block != Blocks.sign && block != Blocks.ladder && block != Blocks.reeds ? (block.material == Material.portal ? true : block.material.blocksMovement()) : true; } protected int checkAdjacentBlock(World worldIn, BlockPos pos, int currentMinLevel) @@ -292,7 +290,7 @@ public class BlockDynamicLiquid extends BlockLiquid private boolean canFlowInto(World worldIn, BlockPos pos, State state) { Material material = state.getBlock().getMaterial(); - return (this.material == Material.LAVA || !(state.getBlock() instanceof BlockLiquid) || (state.getBlock() instanceof BlockStaticLiquid ? BlockLiquid.getFlowingBlock((BlockStaticLiquid)state.getBlock()) : state.getBlock()) == this) && material != this.material && material != Material.LAVA && !this.isBlocked(worldIn, pos, state); + return material != this.material && material != Material.lava && !this.isBlocked(worldIn, pos, state); } public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) diff --git a/common/src/main/java/common/block/tech/BlockEnchantmentTable.java b/common/src/common/block/BlockEnchantmentTable.java similarity index 95% rename from common/src/main/java/common/block/tech/BlockEnchantmentTable.java rename to common/src/common/block/BlockEnchantmentTable.java index d242f81..c27dbab 100755 --- a/common/src/main/java/common/block/tech/BlockEnchantmentTable.java +++ b/common/src/common/block/BlockEnchantmentTable.java @@ -1,12 +1,11 @@ -package common.block.tech; +package common.block; -import common.block.BlockContainer; -import common.block.Material; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; import common.item.CheatTab; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ParticleType; @@ -33,10 +32,10 @@ public class BlockEnchantmentTable extends BlockContainer public BlockEnchantmentTable() { - super(Material.SOLID); + super(Material.rock); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F); this.setLightOpacity(0); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); } public boolean isFullCube() @@ -97,7 +96,7 @@ public class BlockEnchantmentTable extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityEnchantmentTable(); } diff --git a/common/src/common/block/BlockEventData.java b/common/src/common/block/BlockEventData.java new file mode 100755 index 0000000..e8fdcf4 --- /dev/null +++ b/common/src/common/block/BlockEventData.java @@ -0,0 +1,62 @@ +package common.block; + +import common.util.BlockPos; + +public class BlockEventData +{ + private BlockPos position; + private Block blockType; + + /** Different for each blockID */ + private int eventID; + private int eventParameter; + + public BlockEventData(BlockPos pos, Block blockType, int eventId, int p_i45756_4_) + { + this.position = pos; + this.eventID = eventId; + this.eventParameter = p_i45756_4_; + this.blockType = blockType; + } + + public BlockPos getPosition() + { + return this.position; + } + + /** + * Get the Event ID (different for each BlockID) + */ + public int getEventID() + { + return this.eventID; + } + + public int getEventParameter() + { + return this.eventParameter; + } + + public Block getBlock() + { + return this.blockType; + } + + public boolean equals(Object p_equals_1_) + { + if (!(p_equals_1_ instanceof BlockEventData)) + { + return false; + } + else + { + BlockEventData blockeventdata = (BlockEventData)p_equals_1_; + return this.position.equals(blockeventdata.position) && this.eventID == blockeventdata.eventID && this.eventParameter == blockeventdata.eventParameter && this.blockType == blockeventdata.blockType; + } + } + + public String toString() + { + return "TE(" + this.position + ")," + this.eventID + "," + this.eventParameter + "," + this.blockType; + } +} diff --git a/common/src/common/block/BlockFalling.java b/common/src/common/block/BlockFalling.java new file mode 100755 index 0000000..e483126 --- /dev/null +++ b/common/src/common/block/BlockFalling.java @@ -0,0 +1,103 @@ +package common.block; + +import common.entity.item.EntityFalling; +import common.init.Blocks; +import common.init.Config; +import common.item.CheatTab; +import common.material.Material; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; + +public class BlockFalling extends Block +{ + public static boolean fallInstantly; + + public BlockFalling() + { + super(Material.sand); + this.setTab(CheatTab.tabNature); + } + + public BlockFalling(Material materialIn) + { + super(materialIn); + } + + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) + { + worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn, pos)); + } + + /** + * Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) + { + worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn, pos)); + } + + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) + { + if(/* !worldIn.client && */ Config.blockGravity) + this.checkFallable(worldIn, pos); + } + + private void checkFallable(World worldIn, BlockPos pos) + { + if (canFallInto(worldIn, pos.down()) && pos.getY() >= 0) + { + int i = 32; + + if (!fallInstantly && worldIn.isAreaLoaded(pos.add(-i, -i, -i), pos.add(i, i, i))) + { + if (!worldIn.client) + { + EntityFalling entityfallingblock = new EntityFalling(worldIn, (double)pos.getX() + 0.5D, (double)pos.getY(), (double)pos.getZ() + 0.5D, worldIn.getState(pos)); + this.onStartFalling(entityfallingblock); + worldIn.spawnEntityInWorld(entityfallingblock); + } + } + else + { + worldIn.setBlockToAir(pos); + BlockPos blockpos; + + for (blockpos = pos.down(); canFallInto(worldIn, blockpos) && blockpos.getY() > 0; blockpos = blockpos.down()) + { + ; + } + + if (blockpos.getY() > 0) + { + worldIn.setState(blockpos.up(), this.getState()); + } + } + } + } + + protected void onStartFalling(EntityFalling fallingEntity) + { + } + + /** + * How many world ticks before ticking + */ + public int tickRate(World worldIn, BlockPos pos) + { + return 2; + } + + public static boolean canFallInto(World worldIn, BlockPos pos) + { + Block block = worldIn.getState(pos).getBlock(); + Material material = block.material; + return block == Blocks.fire || material == Material.air || material.isLiquid(); + } + + public void onEndFalling(World worldIn, BlockPos pos) + { + } +} diff --git a/common/src/main/java/common/block/foliage/BlockFarmland.java b/common/src/common/block/BlockFarmland.java similarity index 91% rename from common/src/main/java/common/block/foliage/BlockFarmland.java rename to common/src/common/block/BlockFarmland.java index d4ccd0e..7367cf4 100755 --- a/common/src/main/java/common/block/foliage/BlockFarmland.java +++ b/common/src/common/block/BlockFarmland.java @@ -1,13 +1,12 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; -import common.block.natural.BlockDirt; import common.entity.Entity; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.init.Config; import common.init.ItemRegistry; import common.item.Item; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; @@ -16,7 +15,6 @@ import common.rng.Random; import common.util.BlockPos; import common.util.BoundingBox; import common.util.Facing; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.State; import common.world.World; @@ -28,7 +26,7 @@ public class BlockFarmland extends Block public BlockFarmland() { - super(Material.LOOSE); + super(Material.ground); this.setDefaultState(this.getBaseState().withProperty(MOISTURE, Integer.valueOf(0))); this.setTickRandomly(); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.9375F, 1.0F); @@ -59,18 +57,18 @@ public class BlockFarmland extends Block if (!this.hasWater(worldIn, pos) && !worldIn.isRainingAt(pos.up(), true)) { - if(Vars.cropDrying) { + if(Config.cropDrying) { if (i > 0) { worldIn.setState(pos, state.withProperty(MOISTURE, Integer.valueOf(i - 1)), 2); } - else if (Vars.cropDecay && !this.hasCrops(worldIn, pos)) + else if (Config.cropDecay && !this.hasCrops(worldIn, pos)) { worldIn.setState(pos, Blocks.dirt.getState()); } } } - else if (Vars.cropSoaking && i < 7) + else if (Config.cropSoaking && i < 7) { worldIn.setState(pos, state.withProperty(MOISTURE, Integer.valueOf(7)), 2); } @@ -83,9 +81,9 @@ public class BlockFarmland extends Block { if (entityIn instanceof EntityLiving) { - if (!worldIn.client && Vars.cropTrampling && worldIn.rand.floatv() < fallDistance - 0.5F) + if (!worldIn.client && Config.cropTrampling && worldIn.rand.floatv() < fallDistance - 0.5F) { - if (Vars.mobGrief) + if (Config.mobGrief) worldIn.setState(pos, Blocks.dirt.getState()); } @@ -103,7 +101,7 @@ public class BlockFarmland extends Block { for (BlockPos.MutableBlockPos blockpos$mutableblockpos : BlockPos.getAllInBoxMutable(pos.add(-4, 0, -4), pos.add(4, 1, 4))) { - if (worldIn.getState(blockpos$mutableblockpos).getBlock().getMaterial() == Material.WATER) + if (worldIn.getState(blockpos$mutableblockpos).getBlock().getMaterial() == Material.water) { return true; } diff --git a/common/src/main/java/common/block/artificial/BlockFence.java b/common/src/common/block/BlockFence.java similarity index 96% rename from common/src/main/java/common/block/artificial/BlockFence.java rename to common/src/common/block/BlockFence.java index dfd3cad..3bd2657 100755 --- a/common/src/main/java/common/block/artificial/BlockFence.java +++ b/common/src/common/block/BlockFence.java @@ -1,14 +1,13 @@ -package common.block.artificial; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.collect.Lists; import common.entity.Entity; import common.entity.npc.EntityNPC; import common.item.CheatTab; import common.item.ItemLead; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -44,7 +43,7 @@ public class BlockFence extends Block { super(p_i46395_1_); this.setDefaultState(this.getBaseState().withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false))); - this.setTab(p_i46395_1_ == Material.WOOD ? CheatTab.WOOD : CheatTab.BLOCKS); + this.setTab(p_i46395_1_ == Material.wood ? CheatTab.tabWood : CheatTab.tabBlocks); this.texture = texture; FENCES.add(this); } @@ -166,7 +165,7 @@ public class BlockFence extends Block public boolean canConnectTo(IBlockAccess worldIn, BlockPos pos) { Block block = worldIn.getState(pos).getBlock(); - return ((!(block instanceof BlockFence) || block.getMaterial() != this.material) && !(block instanceof BlockFenceGate) ? (block.getMaterial().isOpaque() && block.isFullCube() ? block.getMaterial() != Material.SOFT : false) : true); + return ((!(block instanceof BlockFence) || block.material != this.material) && !(block instanceof BlockFenceGate) ? (block.material.isOpaque() && block.isFullCube() ? block.material != Material.gourd : false) : true); } public boolean shouldSideBeRendered(IWorldAccess worldIn, BlockPos pos, Facing side) diff --git a/common/src/main/java/common/block/artificial/BlockFenceGate.java b/common/src/common/block/BlockFenceGate.java similarity index 98% rename from common/src/main/java/common/block/artificial/BlockFenceGate.java rename to common/src/common/block/BlockFenceGate.java index 887479f..93421f8 100755 --- a/common/src/main/java/common/block/artificial/BlockFenceGate.java +++ b/common/src/common/block/BlockFenceGate.java @@ -1,13 +1,11 @@ -package common.block.artificial; +package common.block; -import common.block.Block; -import common.block.BlockDirectional; -import common.block.Material; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; import common.init.WoodType; import common.item.CheatTab; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -32,9 +30,9 @@ public class BlockFenceGate extends BlockDirectional public BlockFenceGate(WoodType p_i46394_1_) { - super(Material.WOOD); // , p_i46394_1_.getMapColor()); + super(Material.wood); // , p_i46394_1_.getMapColor()); this.setDefaultState(this.getBaseState().withProperty(OPEN, Boolean.valueOf(false)).withProperty(POWERED, Boolean.valueOf(false)).withProperty(IN_WALL, Boolean.valueOf(false))); - this.setTab(CheatTab.WOOD); + this.setTab(CheatTab.tabWood); this.texture = p_i46394_1_.getName() + "_planks"; } @@ -210,7 +208,7 @@ public class BlockFenceGate extends BlockDirectional } public Model getModel(ModelProvider provider, String name, State state) { - return (state.getValue(IN_WALL) ? (state.getValue(OPEN) ? provider.getModel(this.texture).uvLock() + return (state.getValue(IN_WALL) ? (state.getValue(OPEN) ? provider.getModel(this.texture).noOcclude().uvLock() .add(0, 2, 7, 2, 13, 9) .d().uv(0, 7, 2, 9).noCull() .u().uv(0, 7, 2, 9).noCull() @@ -258,7 +256,7 @@ public class BlockFenceGate extends BlockDirectional .d().uv(14, 9, 16, 13).noCull() .u().uv(14, 9, 16, 13).noCull() .w().uv(13, 1, 15, 4).noCull() - .e().uv(13, 1, 15, 4).noCull() : provider.getModel(this.texture).uvLock() + .e().uv(13, 1, 15, 4).noCull() : provider.getModel(this.texture).noOcclude().uvLock() .add(0, 2, 7, 2, 13, 9) .d().uv(0, 7, 2, 9).noCull() .u().uv(0, 7, 2, 9).noCull() diff --git a/common/src/main/java/common/block/natural/BlockFire.java b/common/src/common/block/BlockFire.java similarity index 75% rename from common/src/main/java/common/block/natural/BlockFire.java rename to common/src/common/block/BlockFire.java index 40002fa..0af399f 100755 --- a/common/src/main/java/common/block/natural/BlockFire.java +++ b/common/src/common/block/BlockFire.java @@ -1,12 +1,12 @@ -package common.block.natural; +package common.block; import java.util.Map; -import common.block.Block; -import common.block.Material; +import common.collect.Maps; import common.init.Blocks; -import common.init.FlammabilityRegistry; +import common.init.Config; import common.init.SoundEvent; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -19,7 +19,6 @@ import common.rng.Random; import common.util.BlockPos; import common.util.BoundingBox; import common.util.Facing; -import common.vars.Vars; import common.world.IBlockAccess; import common.world.IWorldAccess; import common.world.AWorldClient; @@ -37,6 +36,8 @@ public class BlockFire extends Block public static final PropertyBool SOUTH = PropertyBool.create("south"); public static final PropertyBool WEST = PropertyBool.create("west"); public static final PropertyInteger UPPER = PropertyInteger.create("upper", 0, 2); + private final Map encouragements = Maps.newIdentityHashMap(); + private final Map flammabilities = Maps.newIdentityHashMap(); /** * Get the actual Block state of this Block at the given position. This applies properties not visible in the @@ -48,7 +49,7 @@ public class BlockFire extends Block int j = pos.getY(); int k = pos.getZ(); - if (!World.isSolidSurface(worldIn.getState(pos.down())) && !this.canCatchFire(worldIn, pos.down())) + if (!World.isSolidSurface(worldIn.getState(pos.down())) && !Blocks.fire.canCatchFire(worldIn, pos.down())) { boolean flag = (i + j + k & 1) == 1; boolean flag1 = (i / 2 + j / 2 + k / 2 & 1) == 1; @@ -69,11 +70,17 @@ public class BlockFire extends Block public BlockFire() { - super(Material.FIRE); + super(Material.fire); this.setDefaultState(this.getBaseState().withProperty(AGE, Integer.valueOf(0)).withProperty(FLIP, Boolean.valueOf(false)).withProperty(ALT, Boolean.valueOf(false)).withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)).withProperty(UPPER, Integer.valueOf(0))); this.setTickRandomly(); } + public void setFireInfo(Block blockIn, int encouragement, int flammability) + { + this.encouragements.put(blockIn, Integer.valueOf(encouragement)); + this.flammabilities.put(blockIn, Integer.valueOf(flammability)); + } + public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) { return null; @@ -110,7 +117,7 @@ public class BlockFire extends Block public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Vars.fire) + if (Config.fire) { if (!this.canPlaceBlockAt(worldIn, pos)) { @@ -125,7 +132,7 @@ public class BlockFire extends Block // flag = true; // } - if (!flag && this.canDie(worldIn, pos)) + if (!flag && worldIn.isRaining() && this.canDie(worldIn, pos)) { worldIn.setBlockToAir(pos); } @@ -205,7 +212,7 @@ public class BlockFire extends Block l1 /= 2; } - if (l1 > 0 && rand.zrange(j1) <= l1 && !this.canDie(worldIn, blockpos)) + if (l1 > 0 && rand.zrange(j1) <= l1 && (!worldIn.isRaining() || !this.canDie(worldIn, blockpos))) { int i2 = i + rand.zrange(5) / 4; @@ -225,9 +232,9 @@ public class BlockFire extends Block } } - protected boolean canDie(World world, BlockPos pos) + protected boolean canDie(AWorldServer worldIn, BlockPos pos) { - return world.isRaining() && (world.isRainingAt(pos, true) || world.isRainingAt(pos.west(), true) || world.isRainingAt(pos.east(), true) || world.isRainingAt(pos.north(), true) || world.isRainingAt(pos.south(), true)); + return worldIn.isRainingAt(pos, true) || worldIn.isRainingAt(pos.west(), true) || worldIn.isRainingAt(pos.east(), true) || worldIn.isRainingAt(pos.north(), true) || worldIn.isRainingAt(pos.south(), true); } public boolean requiresUpdates() @@ -235,31 +242,43 @@ public class BlockFire extends Block return false; } - protected void catchOnFire(World world, BlockPos pos, int chance, Random rand, int age) + private int getFlammability(Block blockIn) { - int i = FlammabilityRegistry.getFlammability(world.getState(pos).getBlock()); + Integer integer = (Integer)this.flammabilities.get(blockIn); + return integer == null ? 0 : integer.intValue(); + } - if (rand.zrange(chance) < i) + private int getEncouragement(Block blockIn) + { + Integer integer = (Integer)this.encouragements.get(blockIn); + return integer == null ? 0 : integer.intValue(); + } + + private void catchOnFire(AWorldServer worldIn, BlockPos pos, int chance, Random random, int age) + { + int i = this.getFlammability(worldIn.getState(pos).getBlock()); + + if (random.zrange(chance) < i) { - State iblockstate = world.getState(pos); + State iblockstate = worldIn.getState(pos); - if (rand.zrange(age + 10) < 5 && !world.isRainingAt(pos, true)) + if (random.zrange(age + 10) < 5 && !worldIn.isRainingAt(pos, true)) { - int j = age + rand.zrange(5) / 4; + int j = age + random.zrange(5) / 4; if (j > 15) { j = 15; } - world.setState(pos, this.getState().withProperty(AGE, Integer.valueOf(j)), 3); + worldIn.setState(pos, this.getState().withProperty(AGE, Integer.valueOf(j)), 3); } else { - world.setBlockToAir(pos); + worldIn.setBlockToAir(pos); } - iblockstate.getBlock().onDestroyedByFire(world, pos, iblockstate); + iblockstate.getBlock().onDestroyedByFire(worldIn, pos, iblockstate); // if (iblockstate.getBlock() == Blocks.tnt) // { // Blocks.tnt.onBlockDestroyedByPlayer(worldIn, pos, iblockstate.withProperty(BlockTNT.EXPLODE, Boolean.valueOf(true))); @@ -292,7 +311,7 @@ public class BlockFire extends Block for (Facing enumfacing : Facing.values()) { - i = Math.max(FlammabilityRegistry.getEncouragement(worldIn.getState(pos.offset(enumfacing)).getBlock()), i); + i = Math.max(this.getEncouragement(worldIn.getState(pos.offset(enumfacing)).getBlock()), i); } return i; @@ -312,7 +331,7 @@ public class BlockFire extends Block */ public boolean canCatchFire(IBlockAccess worldIn, BlockPos pos) { - return FlammabilityRegistry.getEncouragement(worldIn.getState(pos).getBlock()) > 0; + return this.getEncouragement(worldIn.getState(pos).getBlock()) > 0; } public boolean canPlaceBlockAt(World worldIn, BlockPos pos) @@ -354,9 +373,9 @@ public class BlockFire extends Block worldIn.playSound((double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), SoundEvent.FIRE, 1.0F + rand.floatv()); } - if (!worldIn.isBlockSolid(pos.down()) && !this.canCatchFire(worldIn, pos.down())) + if (!worldIn.isBlockSolid(pos.down()) && !Blocks.fire.canCatchFire(worldIn, pos.down())) { - if (this.canCatchFire(worldIn, pos.west())) + if (Blocks.fire.canCatchFire(worldIn, pos.west())) { for (int j = 0; j < 2; ++j) { @@ -367,7 +386,7 @@ public class BlockFire extends Block } } - if (this.canCatchFire(worldIn, pos.east())) + if (Blocks.fire.canCatchFire(worldIn, pos.east())) { for (int k = 0; k < 2; ++k) { @@ -378,7 +397,7 @@ public class BlockFire extends Block } } - if (this.canCatchFire(worldIn, pos.north())) + if (Blocks.fire.canCatchFire(worldIn, pos.north())) { for (int l = 0; l < 2; ++l) { @@ -389,7 +408,7 @@ public class BlockFire extends Block } } - if (this.canCatchFire(worldIn, pos.south())) + if (Blocks.fire.canCatchFire(worldIn, pos.south())) { for (int i1 = 0; i1 < 2; ++i1) { @@ -400,7 +419,7 @@ public class BlockFire extends Block } } - if (this.canCatchFire(worldIn, pos.up())) + if (Blocks.fire.canCatchFire(worldIn, pos.up())) { for (int j1 = 0; j1 < 2; ++j1) { @@ -458,486 +477,487 @@ public class BlockFire extends Block } private static Model fire_nsu2_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull().tint() + .d().uv(0, 0, 16, 16).rot(180).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull().tint(); + .d().uv(0, 0, 16, 16).noCull(); } private static Model fire_nu1(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull().tint() + .d().uv(0, 0, 16, 16).rot(270).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); + .d().uv(0, 0, 16, 16).rot(90).noCull(); } private static Model fire_nseu2_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint() + .w().uv(16, 0, 0, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull().tint() + .d().uv(0, 0, 16, 16).rot(180).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull().tint(); + .d().uv(0, 0, 16, 16).noCull(); } private static Model fire_neu1_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint() + .w().uv(16, 0, 0, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull().tint() + .d().uv(0, 0, 16, 16).rot(270).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); + .d().uv(0, 0, 16, 16).rot(90).noCull(); } private static Model fire_nsu2(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull().tint() + .d().uv(0, 0, 16, 16).rot(180).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull().tint(); + .d().uv(0, 0, 16, 16).noCull(); } private static Model fire_nu2_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull().tint() + .d().uv(0, 0, 16, 16).rot(180).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull().tint(); + .d().uv(0, 0, 16, 16).noCull(); } private static Model fire_neu2_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint() + .w().uv(16, 0, 0, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull().tint() + .d().uv(0, 0, 16, 16).rot(180).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull().tint(); + .d().uv(0, 0, 16, 16).noCull(); } private static Model fire_nsewu2_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint() + .w().uv(16, 0, 0, 16).noCull() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint() + .w().uv(16, 0, 0, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull().tint() + .d().uv(0, 0, 16, 16).rot(180).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull().tint(); + .d().uv(0, 0, 16, 16).noCull(); } private static Model fire_nsewu2(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint() + .w().uv(0, 0, 16, 16).noCull() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint() + .w().uv(0, 0, 16, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull().tint() + .d().uv(0, 0, 16, 16).rot(180).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull().tint(); + .d().uv(0, 0, 16, 16).noCull(); } private static Model fire_nsew(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint() + .w().uv(0, 0, 16, 16).noCull() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint(); + .w().uv(0, 0, 16, 16).noCull(); } private static Model fire_floor(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 0, 8.8f, 16, 22.4f, 8.8f).noShade().rotate(8, 8, 8, Facing.Axis.X, -22.5f, true) - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 0, 7.2f, 16, 22.4f, 7.2f).noShade().rotate(8, 8, 8, Facing.Axis.X, 22.5f, true) - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(8.8f, 0, 0, 8.8f, 22.4f, 16).noShade().rotate(8, 8, 8, Facing.Axis.Z, -22.5f, true) - .w().uv(0, 0, 16, 16).noCull().tint() + .w().uv(0, 0, 16, 16).noCull() .add(7.2f, 0, 0, 7.2f, 22.4f, 16).noShade().rotate(8, 8, 8, Facing.Axis.Z, 22.5f, true) - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(0, 0, 15.99f, 16, 22.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 0, 0.01f, 16, 22.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0.01f, 0, 0, 0.01f, 22.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint() + .w().uv(0, 0, 16, 16).noCull() .add(15.99f, 0, 0, 15.99f, 22.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint(); + .e().uv(0, 0, 16, 16).noCull(); } private static Model fire_u1(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull().tint() + .d().uv(0, 0, 16, 16).rot(270).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); + .d().uv(0, 0, 16, 16).rot(90).noCull(); } private static Model fire_n_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint(); + .n().uv(16, 0, 0, 16).noCull(); } private static Model fire_ne(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint(); + .w().uv(0, 0, 16, 16).noCull(); } private static Model fire_nsew_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint() + .w().uv(16, 0, 0, 16).noCull() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint(); + .w().uv(16, 0, 0, 16).noCull(); } private static Model fire_nse(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint(); + .w().uv(0, 0, 16, 16).noCull(); } private static Model fire_nse_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint(); + .w().uv(16, 0, 0, 16).noCull(); } private static Model fire_nsu1_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull().tint() + .d().uv(0, 0, 16, 16).rot(270).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); + .d().uv(0, 0, 16, 16).rot(90).noCull(); } private static Model fire_n(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint(); + .n().uv(0, 0, 16, 16).noCull(); } private static Model fire_ns(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint(); + .n().uv(0, 0, 16, 16).noCull(); } private static Model fire_neu1(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint() + .w().uv(0, 0, 16, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull().tint() + .d().uv(0, 0, 16, 16).rot(270).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); + .d().uv(0, 0, 16, 16).rot(90).noCull(); } private static Model fire_u2(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull().tint() + .d().uv(0, 0, 16, 16).rot(180).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull().tint(); + .d().uv(0, 0, 16, 16).noCull(); } private static Model fire_nseu2(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint() + .w().uv(0, 0, 16, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull().tint() + .d().uv(0, 0, 16, 16).rot(180).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull().tint(); + .d().uv(0, 0, 16, 16).noCull(); } private static Model fire_neu2(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint() + .w().uv(0, 0, 16, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull().tint() + .d().uv(0, 0, 16, 16).rot(180).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull().tint(); + .d().uv(0, 0, 16, 16).noCull(); } private static Model fire_nu2(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull().tint() + .d().uv(0, 0, 16, 16).rot(180).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull().tint(); + .d().uv(0, 0, 16, 16).noCull(); } private static Model fire_nseu1(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint() + .w().uv(0, 0, 16, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull().tint() + .d().uv(0, 0, 16, 16).rot(270).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); + .d().uv(0, 0, 16, 16).rot(90).noCull(); } private static Model fire_ns_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint(); + .n().uv(16, 0, 0, 16).noCull(); } private static Model fire_nsewu1(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint() + .w().uv(0, 0, 16, 16).noCull() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull().tint() + .e().uv(0, 0, 16, 16).noCull() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull().tint() + .w().uv(0, 0, 16, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull().tint() + .d().uv(0, 0, 16, 16).rot(270).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); + .d().uv(0, 0, 16, 16).rot(90).noCull(); } private static Model fire_nsu1(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull().tint() + .s().uv(0, 0, 16, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull().tint() + .n().uv(0, 0, 16, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull().tint() + .d().uv(0, 0, 16, 16).rot(270).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); + .d().uv(0, 0, 16, 16).rot(90).noCull(); } private static Model fire_nsewu1_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint() + .w().uv(16, 0, 0, 16).noCull() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint() + .w().uv(16, 0, 0, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull().tint() + .d().uv(0, 0, 16, 16).rot(270).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); + .d().uv(0, 0, 16, 16).rot(90).noCull(); } private static Model fire_ne_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint(); + .w().uv(16, 0, 0, 16).noCull(); } private static Model fire_nseu1_flip(String fire) { - return ModelProvider.getModelProvider().getModel(fire) + return ModelProvider.getModelProvider().getModel(fire).noOcclude() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull().tint() + .s().uv(16, 0, 0, 16).noCull() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull().tint() + .n().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull().tint() + .e().uv(16, 0, 0, 16).noCull() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull().tint() + .w().uv(16, 0, 0, 16).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull().tint() + .d().uv(0, 0, 16, 16).rot(270).noCull() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); + .d().uv(0, 0, 16, 16).rot(90).noCull(); } - protected static Model getFireModel(String tex, boolean flip, int upper, boolean n, boolean s, boolean w, boolean e) { + private static Model getFireModel(boolean alt, boolean flip, int upper, boolean n, boolean s, boolean w, boolean e) { + String tex = alt ? "fire_layer_1" : "fire_layer_0"; if(!e && !flip && !n && !s && upper == 0 && !w) return fire_floor(tex); else if(!e && !flip && !n && s && upper == 0 && !w) @@ -1135,7 +1155,7 @@ public class BlockFire extends Block } public Model getModel(ModelProvider provider, String name, State state) { - return getFireModel(state.getValue(ALT) ? "fire_layer_1" : "fire_layer_0", state.getValue(FLIP), state.getValue(UPPER), + return getFireModel(state.getValue(ALT), state.getValue(FLIP), state.getValue(UPPER), state.getValue(NORTH), state.getValue(SOUTH), state.getValue(WEST), state.getValue(EAST)); } @@ -1147,8 +1167,4 @@ public class BlockFire extends Block map.put("blocks/fire_layer_0", "fire1"); map.put("blocks/fire_layer_1", "fire2"); } - - public boolean canExtinguish() { - return true; - } } diff --git a/common/src/main/java/common/block/artificial/BlockFloorPortal.java b/common/src/common/block/BlockFloorPortal.java similarity index 98% rename from common/src/main/java/common/block/artificial/BlockFloorPortal.java rename to common/src/common/block/BlockFloorPortal.java index c9b3c33..a365a47 100755 --- a/common/src/main/java/common/block/artificial/BlockFloorPortal.java +++ b/common/src/common/block/BlockFloorPortal.java @@ -1,14 +1,13 @@ -package common.block.artificial; +package common.block; import java.util.List; import java.util.Map; import java.util.Set; -import common.block.Block; -import common.block.Material; import common.collect.Sets; import common.entity.Entity; import common.item.Item; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ParticleType; diff --git a/common/src/main/java/common/block/foliage/BlockFlower.java b/common/src/common/block/BlockFlower.java similarity index 98% rename from common/src/main/java/common/block/foliage/BlockFlower.java rename to common/src/common/block/BlockFlower.java index dabe90f..2b2091f 100755 --- a/common/src/main/java/common/block/foliage/BlockFlower.java +++ b/common/src/common/block/BlockFlower.java @@ -1,4 +1,4 @@ -package common.block.foliage; +package common.block; import java.util.Collection; import java.util.List; @@ -7,6 +7,7 @@ import java.util.function.Predicate; import common.collect.Filter; import common.collect.Lists; import common.init.Blocks; +import common.init.Config; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; @@ -17,7 +18,6 @@ import common.properties.PropertyEnum; import common.rng.Random; import common.util.BlockPos; import common.util.Identifyable; -import common.vars.Vars; import common.world.State; import common.world.AWorldServer; @@ -33,7 +33,7 @@ public abstract class BlockFlower extends BlockBush public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Vars.flowerDry && worldIn.getTemperatureC(pos) >= 50.0f) + if(Config.flowerDry && worldIn.getTemperatureC(pos) >= 50.0f) { worldIn.setState(pos, worldIn.rand.chance(3) ? Blocks.air.getState() : Blocks.tallgrass.getState().withProperty(BlockTallGrass.TYPE, BlockTallGrass.EnumType.DEAD_BUSH)); diff --git a/common/src/main/java/common/block/artificial/BlockFlowerPot.java b/common/src/common/block/BlockFlowerPot.java similarity index 97% rename from common/src/main/java/common/block/artificial/BlockFlowerPot.java rename to common/src/common/block/BlockFlowerPot.java index 7c3436b..d25970a 100755 --- a/common/src/main/java/common/block/artificial/BlockFlowerPot.java +++ b/common/src/common/block/BlockFlowerPot.java @@ -1,8 +1,5 @@ -package common.block.artificial; +package common.block; -import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockFlower; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.init.ItemRegistry; @@ -10,6 +7,7 @@ import common.init.Items; import common.item.Item; import common.item.ItemBlock; import common.item.ItemStack; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -24,7 +22,7 @@ import common.world.AWorldServer; public class BlockFlowerPot extends Block // Container { - private static final Model flower_pot_cactus = ModelProvider.getModelProvider().getModel("flower_pot") + private static final Model flower_pot_cactus = ModelProvider.getModelProvider().getModel("flower_pot").noOcclude() .add(5, 0, 5, 6, 6, 11) .d().uv(5, 5, 6, 11) .u().uv(5, 5, 6, 11).noCull() @@ -69,7 +67,7 @@ public class BlockFlowerPot extends Block // Container .w("cactus_side").uv(6, 0, 10, 4).noCull() .e("cactus_side").uv(6, 0, 10, 4).noCull() ; - private static final Model flower_pot = ModelProvider.getModelProvider().getModel("flower_pot") + private static final Model flower_pot = ModelProvider.getModelProvider().getModel("flower_pot").noOcclude() .add(5, 0, 5, 6, 6, 11) .d().uv(5, 5, 6, 11) .u().uv(5, 5, 6, 11).noCull() @@ -103,7 +101,7 @@ public class BlockFlowerPot extends Block // Container public BlockFlowerPot() { - super(Material.SMALL); + super(Material.circuits); this.setDefaultState(this.getBaseState().withProperty(CONTENTS, 0)); // .withProperty(LEGACY_DATA, Integer.valueOf(0))); this.setBlockBoundsForItemRender(); } @@ -191,7 +189,7 @@ public class BlockFlowerPot extends Block // Container // worldIn.markBlockForUpdate(pos); // playerIn.triggerAchievement(StatRegistry.flowerPottedStat); - if (/* !playerIn.creative && */ --itemstack.size <= 0) + if (/* !playerIn.creative && */ --itemstack.stackSize <= 0) { playerIn.inventory.setInventorySlotContents(playerIn.inventory.currentItem, (ItemStack)null); } @@ -357,7 +355,7 @@ public class BlockFlowerPot extends Block // Container // return flower_pot_fern; default: String plant = BlockFlower.EnumFlowerType.getType(BlockFlower.EnumFlowerColor.BASE, state.getValue(CONTENTS) - 2).getName().toLowerCase(); - return provider.getModel("flower_pot") + return provider.getModel("flower_pot").noOcclude() .add(5, 0, 5, 6, 6, 11) .d().uv(5, 5, 6, 11) .u().uv(5, 5, 6, 11).noCull() diff --git a/common/src/main/java/common/block/tech/BlockFurnace.java b/common/src/common/block/BlockFurnace.java similarity index 97% rename from common/src/main/java/common/block/tech/BlockFurnace.java rename to common/src/common/block/BlockFurnace.java index 4a3d9fa..73731a1 100755 --- a/common/src/main/java/common/block/tech/BlockFurnace.java +++ b/common/src/common/block/BlockFurnace.java @@ -1,8 +1,5 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.BlockContainer; -import common.block.Material; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; @@ -11,6 +8,7 @@ import common.inventory.Container; import common.inventory.InventoryHelper; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -35,7 +33,7 @@ public class BlockFurnace extends BlockContainer public BlockFurnace(boolean isBurning) { - super(Material.SOLID); + super(Material.rock); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); this.isBurning = isBurning; } @@ -169,7 +167,7 @@ public class BlockFurnace extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityFurnace(); } diff --git a/common/src/common/block/BlockGlass.java b/common/src/common/block/BlockGlass.java new file mode 100755 index 0000000..adc1e63 --- /dev/null +++ b/common/src/common/block/BlockGlass.java @@ -0,0 +1,38 @@ +package common.block; + +import common.item.CheatTab; +import common.material.Material; +import common.model.BlockLayer; +import common.rng.Random; + +public class BlockGlass extends BlockBreakable +{ + public BlockGlass(Material materialIn, boolean ignoreSimilarity) + { + super(materialIn, ignoreSimilarity); + this.setTab(CheatTab.tabBlocks); + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(Random random) + { + return 0; + } + + public BlockLayer getBlockLayer() + { + return BlockLayer.CUTOUT; + } + + public boolean isFullCube() + { + return false; + } + + public boolean canSilkHarvest() + { + return true; + } +} diff --git a/common/src/main/java/common/block/natural/BlockGlowstone.java b/common/src/common/block/BlockGlowstone.java similarity index 76% rename from common/src/main/java/common/block/natural/BlockGlowstone.java rename to common/src/common/block/BlockGlowstone.java index 77a18c2..ddcdf75 100755 --- a/common/src/main/java/common/block/natural/BlockGlowstone.java +++ b/common/src/common/block/BlockGlowstone.java @@ -1,23 +1,19 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; -import common.entity.Entity; import common.init.Items; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.rng.Random; -import common.util.BlockPos; import common.util.ExtMath; import common.world.State; -import common.world.World; public class BlockGlowstone extends Block { public BlockGlowstone(Material materialIn) { super(materialIn); - this.setTab(CheatTab.NATURE); + this.setTab(CheatTab.tabNature); } /** @@ -43,11 +39,6 @@ public class BlockGlowstone extends Block { return Items.glowstone_dust; } - - public boolean onShot(World world, BlockPos pos, State state, Entity projectile) { - world.destroyBlock(pos, true); - return false; - } // /** // * Get the MapColor for this Block and the given BlockState diff --git a/common/src/main/java/common/block/foliage/BlockGrass.java b/common/src/common/block/BlockGrass.java similarity index 92% rename from common/src/main/java/common/block/foliage/BlockGrass.java rename to common/src/common/block/BlockGrass.java index 9780435..2f1ddcf 100755 --- a/common/src/main/java/common/block/foliage/BlockGrass.java +++ b/common/src/common/block/BlockGrass.java @@ -1,13 +1,12 @@ -package common.block.foliage; +package common.block; import common.biome.IBiome; -import common.block.Block; -import common.block.Material; -import common.block.natural.BlockDirt; import common.color.Colorizer; import common.init.Blocks; +import common.init.Config; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -15,7 +14,6 @@ import common.properties.IProperty; import common.properties.PropertyBool; import common.rng.Random; import common.util.BlockPos; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.State; import common.world.World; @@ -27,10 +25,10 @@ public class BlockGrass extends Block implements IGrowable public BlockGrass() { - super(Material.LOOSE); + super(Material.grass); this.setDefaultState(this.getBaseState().withProperty(SNOWY, Boolean.valueOf(false))); this.setTickRandomly(); - this.setTab(CheatTab.NATURE); + this.setTab(CheatTab.tabNature); } /** @@ -65,12 +63,12 @@ public class BlockGrass extends Block implements IGrowable // { if (worldIn.getLightFromNeighbors(pos.up()) < 4 && worldIn.getState(pos.up()).getBlock().getLightOpacity() > 2) { - if(Vars.grassDecay) + if(Config.grassDecay) worldIn.setState(pos, Blocks.dirt.getState()); } else if(worldIn.getTemperatureC(pos) < 50.0f) { - if (Vars.grassSpread && worldIn.getLightFromNeighbors(pos.up()) >= 9) + if (Config.grassSpread && worldIn.getLightFromNeighbors(pos.up()) >= 9) { for (int i = 0; i < 4; ++i) { @@ -86,7 +84,7 @@ public class BlockGrass extends Block implements IGrowable } } else { - if(Vars.grassDry) + if(Config.grassDry) worldIn.setState(pos, worldIn.rand.chance(20) ? Blocks.dirt.getState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.COARSE_DIRT) : Blocks.dirt.getState()); } diff --git a/common/src/main/java/common/block/natural/BlockGravel.java b/common/src/common/block/BlockGravel.java similarity index 70% rename from common/src/main/java/common/block/natural/BlockGravel.java rename to common/src/common/block/BlockGravel.java index de0466d..9206e53 100755 --- a/common/src/main/java/common/block/natural/BlockGravel.java +++ b/common/src/common/block/BlockGravel.java @@ -1,25 +1,17 @@ -package common.block.natural; +package common.block; -import common.block.BlockFalling; -import common.block.Material; +import common.init.Config; import common.init.ItemRegistry; import common.init.Items; -import common.item.CheatTab; import common.item.Item; import common.rng.Random; -import common.vars.Vars; import common.world.State; public class BlockGravel extends BlockFalling { - public BlockGravel() { - super(Material.LOOSE); - this.setTab(CheatTab.NATURE); - } - public Item getItemDropped(State state, Random rand, int fortune) { - int chance = Vars.flintChance; + int chance = Config.flintChance; if(chance <= 0) return ItemRegistry.getItemFromBlock(this); fortune *= 3; diff --git a/common/src/main/java/common/block/natural/BlockHardenedClay.java b/common/src/common/block/BlockHardenedClay.java similarity index 65% rename from common/src/main/java/common/block/natural/BlockHardenedClay.java rename to common/src/common/block/BlockHardenedClay.java index 93e8b74..d3be1c4 100755 --- a/common/src/main/java/common/block/natural/BlockHardenedClay.java +++ b/common/src/common/block/BlockHardenedClay.java @@ -1,15 +1,14 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; import common.item.CheatTab; +import common.material.Material; public class BlockHardenedClay extends Block { public BlockHardenedClay() { - super(Material.SOLID); - this.setTab(CheatTab.NATURE); + super(Material.rock); + this.setTab(CheatTab.tabNature); } // /** diff --git a/common/src/main/java/common/block/artificial/BlockHay.java b/common/src/common/block/BlockHay.java similarity index 92% rename from common/src/main/java/common/block/artificial/BlockHay.java rename to common/src/common/block/BlockHay.java index eefc04f..a051aa5 100755 --- a/common/src/main/java/common/block/artificial/BlockHay.java +++ b/common/src/common/block/BlockHay.java @@ -1,11 +1,10 @@ -package common.block.artificial; +package common.block; -import common.block.BlockRotatedPillar; -import common.block.Material; import common.entity.types.EntityLiving; import common.init.ItemRegistry; import common.item.CheatTab; import common.item.ItemStack; +import common.material.Material; import common.properties.IProperty; import common.util.BlockPos; import common.util.Facing; @@ -16,9 +15,9 @@ public class BlockHay extends BlockRotatedPillar { public BlockHay() { - super(Material.LOOSE); + super(Material.grass); this.setDefaultState(this.getBaseState().withProperty(AXIS, Facing.Axis.Y)); - this.setTab(CheatTab.BLOCKS); + this.setTab(CheatTab.tabBlocks); } /** diff --git a/common/src/main/java/common/block/natural/BlockHellRock.java b/common/src/common/block/BlockHellRock.java similarity index 70% rename from common/src/main/java/common/block/natural/BlockHellRock.java rename to common/src/common/block/BlockHellRock.java index 63c6b72..26a4859 100755 --- a/common/src/main/java/common/block/natural/BlockHellRock.java +++ b/common/src/common/block/BlockHellRock.java @@ -1,15 +1,14 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; import common.item.CheatTab; +import common.material.Material; public class BlockHellRock extends Block { public BlockHellRock() { - super(Material.SOLID); - this.setTab(CheatTab.NATURE); + super(Material.rock); + this.setTab(CheatTab.tabNature); } // /** diff --git a/common/src/main/java/common/block/tech/BlockHopper.java b/common/src/common/block/BlockHopper.java similarity index 97% rename from common/src/main/java/common/block/tech/BlockHopper.java rename to common/src/common/block/BlockHopper.java index 524a799..88832e8 100755 --- a/common/src/main/java/common/block/tech/BlockHopper.java +++ b/common/src/common/block/BlockHopper.java @@ -1,11 +1,8 @@ -package common.block.tech; +package common.block; import java.util.List; import java.util.function.Predicate; -import common.block.Block; -import common.block.BlockContainer; -import common.block.Material; import common.entity.Entity; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; @@ -13,6 +10,7 @@ import common.inventory.Container; import common.inventory.InventoryHelper; import common.item.CheatTab; import common.item.ItemStack; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -32,7 +30,7 @@ import common.world.AWorldServer; public class BlockHopper extends BlockContainer { - private static final Model hopper_down = ModelProvider.getModelProvider().getModel("hopper_outside") + private static final Model hopper_down = ModelProvider.getModelProvider().getModel("hopper_outside").noOcclude() .add(0, 10, 0, 16, 11, 16) .d().uv(0, 0, 16, 16).noCull() .u("hopper_inside").uv(0, 0, 16, 16).noCull() @@ -95,9 +93,9 @@ public class BlockHopper extends BlockContainer public BlockHopper() { - super(Material.SOLID); + super(Material.iron); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.DOWN).withProperty(ENABLED, Boolean.valueOf(true))); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } @@ -144,7 +142,7 @@ public class BlockHopper extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityHopper(); } @@ -312,7 +310,7 @@ public class BlockHopper extends BlockContainer } public Model getModel(ModelProvider provider, String name, State state) { - return state.getValue(FACING) == Facing.DOWN ? hopper_down : provider.getModel("hopper_outside") + return state.getValue(FACING) == Facing.DOWN ? hopper_down : provider.getModel("hopper_outside").noOcclude() .add(0, 10, 0, 16, 11, 16) .d().uv(0, 0, 16, 16).noCull() .u("hopper_inside").uv(0, 0, 16, 16).noCull() diff --git a/common/src/main/java/common/block/foliage/BlockHugeMushroom.java b/common/src/common/block/BlockHugeMushroom.java similarity index 98% rename from common/src/main/java/common/block/foliage/BlockHugeMushroom.java rename to common/src/common/block/BlockHugeMushroom.java index 873240b..f4d6262 100755 --- a/common/src/main/java/common/block/foliage/BlockHugeMushroom.java +++ b/common/src/common/block/BlockHugeMushroom.java @@ -1,10 +1,9 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.types.EntityLiving; import common.init.ItemRegistry; import common.item.Item; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; diff --git a/common/src/common/block/BlockIce.java b/common/src/common/block/BlockIce.java new file mode 100755 index 0000000..438dd31 --- /dev/null +++ b/common/src/common/block/BlockIce.java @@ -0,0 +1,93 @@ +package common.block; + +import common.enchantment.EnchantmentHelper; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Config; +import common.item.CheatTab; +import common.item.ItemStack; +import common.material.Material; +import common.model.BlockLayer; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; + +public class BlockIce extends BlockBreakable +{ + public BlockIce() + { + super(Material.ice, false); + this.slipperiness = 0.98F; + this.setTickRandomly(); + this.setTab(CheatTab.tabNature); + } + + public BlockLayer getBlockLayer() + { + return BlockLayer.TRANSLUCENT; + } + + public void harvestBlock(World worldIn, EntityNPC player, BlockPos pos, State state, TileEntity te) + { +// player.triggerAchievement(StatRegistry.mineBlockStatArray[BlockRegistry.getIdFromBlock(this)]); + + if (this.canSilkHarvest() && EnchantmentHelper.getSilkTouchModifier(player)) + { + ItemStack itemstack = this.createStackedBlock(state); + + if (itemstack != null) + { + spawnAsEntity(worldIn, pos, itemstack); + } + } + else + { + if (((AWorldServer)worldIn).doesWaterVaporize(pos)) + { + worldIn.setBlockToAir(pos); + return; + } + + int i = EnchantmentHelper.getFortuneModifier(player); + this.dropBlockAsItem(worldIn, pos, state, i); + Material material = worldIn.getState(pos.down()).getBlock().getMaterial(); + + if (material.blocksMovement() || material.isLiquid()) + { + worldIn.setState(pos, Blocks.flowing_water.getState()); + } + } + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(Random random) + { + return 0; + } + + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) + { + if (Config.iceMelt && ((worldIn.getLightFor(pos) > 11 - this.getLightOpacity()) || !worldIn.canFreezeAt(pos))) + { + if (worldIn.doesWaterVaporize(pos)) + { + worldIn.setBlockToAir(pos); + } + else + { + this.dropBlockAsItem(worldIn, pos, worldIn.getState(pos), 0); + worldIn.setState(pos, Blocks.water.getState()); + } + } + } + + public int getMobilityFlag() + { + return 0; + } +} diff --git a/common/src/main/java/common/block/tech/BlockJukebox.java b/common/src/common/block/BlockJukebox.java similarity index 84% rename from common/src/main/java/common/block/tech/BlockJukebox.java rename to common/src/common/block/BlockJukebox.java index cfe625d..87f2fce 100755 --- a/common/src/main/java/common/block/tech/BlockJukebox.java +++ b/common/src/common/block/BlockJukebox.java @@ -1,10 +1,9 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.npc.EntityNPC; import common.init.SoundEvent; import common.item.CheatTab; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.util.BlockPos; @@ -14,8 +13,8 @@ import common.world.World; public class BlockJukebox extends Block { public BlockJukebox() { - super(Material.WOOD); - this.setTab(CheatTab.TECHNOLOGY); + super(Material.wood); + this.setTab(CheatTab.tabTech); } public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { diff --git a/common/src/main/java/common/block/artificial/BlockLadder.java b/common/src/common/block/BlockLadder.java similarity index 95% rename from common/src/main/java/common/block/artificial/BlockLadder.java rename to common/src/common/block/BlockLadder.java index 20c8ac2..ee9d14a 100755 --- a/common/src/main/java/common/block/artificial/BlockLadder.java +++ b/common/src/common/block/BlockLadder.java @@ -1,10 +1,8 @@ -package common.block.artificial; +package common.block; -import common.block.Block; -import common.block.BlockDirectional; -import common.block.Material; import common.entity.types.EntityLiving; import common.item.CheatTab; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -24,9 +22,9 @@ public class BlockLadder extends Block public BlockLadder() { - super(Material.SMALL); + super(Material.circuits); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); - this.setTab(CheatTab.WOOD); + this.setTab(CheatTab.tabWood); } public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) @@ -167,7 +165,7 @@ public class BlockLadder extends Block } public Model getModel(ModelProvider provider, String name, State state) { - return provider.getModel("ladder") + return provider.getModel("ladder").noOcclude() .add(0, 0, 15.2f, 16, 16, 15.2f).noShade() .n().uv(0, 0, 16, 16).noCull() .s().uv(0, 0, 16, 16).noCull() diff --git a/common/src/main/java/common/block/foliage/BlockLeaves.java b/common/src/common/block/BlockLeaves.java similarity index 92% rename from common/src/main/java/common/block/foliage/BlockLeaves.java rename to common/src/common/block/BlockLeaves.java index 1d08150..1c9a795 100755 --- a/common/src/main/java/common/block/foliage/BlockLeaves.java +++ b/common/src/common/block/BlockLeaves.java @@ -1,30 +1,27 @@ -package common.block.foliage; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; -import common.block.SoundType; import common.collect.Lists; import common.color.Colorizer; import common.entity.npc.EntityNPC; import common.init.Blocks; +import common.init.Config; import common.init.ItemRegistry; import common.init.WoodType; import common.item.CheatTab; import common.item.Item; import common.item.ItemShears; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; -import common.model.ParticleType; import common.properties.IProperty; import common.properties.PropertyBool; import common.properties.PropertyEnum; import common.rng.Random; import common.tileentity.TileEntity; import common.util.BlockPos; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.AWorldClient; import common.world.State; @@ -43,11 +40,11 @@ public class BlockLeaves extends BlockLeavesBase public BlockLeaves(WoodType type) { - super(Material.LEAVES); + super(Material.leaves); this.type = type; this.setDefaultState(this.getBaseState().withProperty(TYPE, LeavesType.SPRING).withProperty(DECAY, Boolean.valueOf(true))); this.setTickRandomly(); - this.setTab(CheatTab.PLANTS); + this.setTab(CheatTab.tabPlants); this.setHardness(0.2F); this.setLightOpacity(1); this.setStepSound(SoundType.GRASS); @@ -88,7 +85,7 @@ public class BlockLeaves extends BlockLeavesBase BlockPos blockpos = pos.add(j1, k1, l1); State iblockstate = worldIn.getState(blockpos); - if (iblockstate.getBlock().getMaterial() == Material.LEAVES && !((Boolean)iblockstate.getValue(DECAY)).booleanValue()) + if (iblockstate.getBlock().getMaterial() == Material.leaves && !((Boolean)iblockstate.getValue(DECAY)).booleanValue()) { worldIn.setState(blockpos, iblockstate.withProperty(DECAY, Boolean.valueOf(true)), 4); } @@ -100,15 +97,15 @@ public class BlockLeaves extends BlockLeavesBase public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Vars.seasonLeaves && state.getValue(TYPE) != worldIn.getLeavesGen(pos)) { + if(Config.seasonLeaves && state.getValue(TYPE) != worldIn.getLeavesGen(pos)) { worldIn.setState(pos, state.withProperty(TYPE, worldIn.getLeavesGen(pos)), 2); } - if(Vars.leafDry && worldIn.getTemperatureC(pos) >= 50.0f) { + if(Config.leafDry && worldIn.getTemperatureC(pos) >= 50.0f) { worldIn.setState(pos, worldIn.rand.chance(40) ? Blocks.air.getState() : Blocks.dry_leaves.getState()); } // if (!worldIn.client) // { - else if (Vars.leavesDecay && ((Boolean)state.getValue(DECAY)).booleanValue()) + else if (Config.leavesDecay && ((Boolean)state.getValue(DECAY)).booleanValue()) { int i = 4; int j = i + 1; @@ -138,7 +135,7 @@ public class BlockLeaves extends BlockLeavesBase if (!(block instanceof BlockLog)) { - if (block.getMaterial() == Material.LEAVES) + if (block.getMaterial() == Material.leaves) { this.surroundings[(i2 + l1) * k1 + (j2 + l1) * j1 + k2 + l1] = -2; } @@ -217,13 +214,13 @@ public class BlockLeaves extends BlockLeavesBase public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { - if (worldIn.isRainingAt(pos.up(), true) && !worldIn.isBlockSolid(pos.down()) && rand.chance(15)) // == 1 - { - double d0 = (double)((float)pos.getX() + rand.floatv()); - double d1 = (double)pos.getY() - 0.05D; - double d2 = (double)((float)pos.getZ() + rand.floatv()); - worldIn.spawnParticle(ParticleType.DRIP_WATER, d0, d1, d2, 0.0D, 0.0D, 0.0D); - } +// if (worldIn.isRainingAt(pos.up(), true) && !worldIn.isBlockSolid(pos.down()) && rand.chance(15)) // == 1 TODO: fix particles +// { +// double d0 = (double)((float)pos.getX() + rand.floatv()); +// double d1 = (double)pos.getY() - 0.05D; +// double d2 = (double)((float)pos.getZ() + rand.floatv()); +// worldIn.spawnParticle(ParticleType.DRIP_WATER, d0, d1, d2, 0.0D, 0.0D, 0.0D); +// } } private void destroy(World worldIn, BlockPos pos) diff --git a/common/src/main/java/common/block/foliage/BlockLeavesBase.java b/common/src/common/block/BlockLeavesBase.java similarity index 92% rename from common/src/main/java/common/block/foliage/BlockLeavesBase.java rename to common/src/common/block/BlockLeavesBase.java index 1bf0fd0..2c7a3c2 100755 --- a/common/src/main/java/common/block/foliage/BlockLeavesBase.java +++ b/common/src/common/block/BlockLeavesBase.java @@ -1,7 +1,6 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; +import common.material.Material; import common.model.BlockLayer; public class BlockLeavesBase extends Block diff --git a/common/src/main/java/common/block/tech/BlockLever.java b/common/src/common/block/BlockLever.java similarity index 98% rename from common/src/main/java/common/block/tech/BlockLever.java rename to common/src/common/block/BlockLever.java index 6e5e276..3e33154 100755 --- a/common/src/main/java/common/block/tech/BlockLever.java +++ b/common/src/common/block/BlockLever.java @@ -1,11 +1,10 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.SoundEvent; import common.item.CheatTab; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -28,9 +27,9 @@ public class BlockLever extends Block public BlockLever() { - super(Material.SMALL); + super(Material.circuits); this.setDefaultState(this.getBaseState().withProperty(FACING, BlockLever.EnumOrientation.NORTH).withProperty(POWERED, Boolean.valueOf(false))); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); } public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) @@ -298,7 +297,7 @@ public class BlockLever extends Block } public Model getModel(ModelProvider provider, String name, State state) { - return provider.getModel("cobblestone") + return provider.getModel("cobblestone").noOcclude() .add(5, 0, 4, 11, 3, 12) .d().uv(5, 4, 11, 12).noCull() .u().uv(5, 4, 11, 12).noCull() diff --git a/common/src/main/java/common/block/foliage/BlockLilyPad.java b/common/src/common/block/BlockLilyPad.java similarity index 91% rename from common/src/main/java/common/block/foliage/BlockLilyPad.java rename to common/src/common/block/BlockLilyPad.java index 1102480..25e614d 100755 --- a/common/src/main/java/common/block/foliage/BlockLilyPad.java +++ b/common/src/common/block/BlockLilyPad.java @@ -1,11 +1,7 @@ -package common.block.foliage; +package common.block; import java.util.List; -import common.block.Block; -import common.block.BlockDirectional; -import common.block.liquid.BlockLiquid; -import common.block.liquid.BlockStaticLiquid; import common.entity.Entity; import common.entity.item.EntityBoat; import common.entity.types.EntityLiving; @@ -30,7 +26,7 @@ public class BlockLilyPad extends BlockBush float f1 = 0.015625F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); this.setDefaultState(this.getBaseState().withProperty(BlockDirectional.FACING, Facing.NORTH)); - this.setTab(CheatTab.PLANTS); + this.setTab(CheatTab.tabPlants); } public void addCollisionBoxesToList(World worldIn, BlockPos pos, State state, BoundingBox mask, List list, Entity collidingEntity) @@ -68,7 +64,7 @@ public class BlockLilyPad extends BlockBush public boolean canBlockStay(World worldIn, BlockPos pos, State state) { - if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) + if (pos.getY() >= 0 && pos.getY() < 512) { State iblockstate = worldIn.getState(pos.down()); return (iblockstate.getBlock().getMaterial().isColdLiquid() && ((Integer)iblockstate.getValue(BlockLiquid.LEVEL)).intValue() == 0) @@ -106,7 +102,7 @@ public class BlockLilyPad extends BlockBush } public Model getModel(ModelProvider provider, String name, State state) { - return provider.getModel("waterlily") + return provider.getModel("waterlily").noOcclude() .add(0, 0.25f, 0, 16, 0.25f, 16) .d().uv(16, 16, 0, 0).tint().noCull() .u().uv(16, 0, 0, 16).tint().noCull() diff --git a/common/src/main/java/common/block/liquid/BlockLiquid.java b/common/src/common/block/BlockLiquid.java similarity index 90% rename from common/src/main/java/common/block/liquid/BlockLiquid.java rename to common/src/common/block/BlockLiquid.java index 4643b57..88ad69f 100755 --- a/common/src/main/java/common/block/liquid/BlockLiquid.java +++ b/common/src/common/block/BlockLiquid.java @@ -1,13 +1,13 @@ -package common.block.liquid; +package common.block; -import common.block.Block; -import common.block.Material; import common.color.Colorizer; import common.entity.Entity; import common.init.Blocks; +import common.init.Config; import common.init.FluidRegistry; import common.init.SoundEvent; import common.item.Item; +import common.material.Material; import common.model.BlockLayer; import common.model.ParticleType; import common.properties.IProperty; @@ -18,7 +18,6 @@ import common.util.BoundingBox; import common.util.ExtMath; import common.util.Facing; import common.util.Vec3; -import common.vars.Vars; import common.world.IBlockAccess; import common.world.IWorldAccess; import common.world.AWorldClient; @@ -51,7 +50,7 @@ public abstract class BlockLiquid extends Block public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass) { - return this.material == Material.WATER ? Colorizer.getWaterColor(worldIn, pos) : 16777215; + return this.material == Material.water ? Colorizer.getWaterColor(worldIn, pos) : 16777215; } /** @@ -91,15 +90,18 @@ public abstract class BlockLiquid extends Block return false; } - public boolean canCollideCheck(State state, boolean liquid) + public boolean canCollideCheck(State state, boolean hitIfLiquid) { - return liquid && ((Integer)state.getValue(LEVEL)).intValue() == 0; + return hitIfLiquid && ((Integer)state.getValue(LEVEL)).intValue() == 0; } + /** + * Whether this Block is solid on the given Side + */ public boolean isBlockSolid(IBlockAccess worldIn, BlockPos pos, Facing side) { - Block block = worldIn.getState(pos).getBlock(); - return block.getMaterial() == this.material ? false : (side == Facing.UP ? true : (block != Blocks.ice && worldIn.getState(pos).getBlock().getMaterial().isSolid())); + Material material = worldIn.getState(pos).getBlock().getMaterial(); + return material == this.material ? false : (side == Facing.UP ? true : (material == Material.ice ? false : super.isBlockSolid(worldIn, pos, side))); } public boolean shouldSideBeRendered(IWorldAccess worldIn, BlockPos pos, Facing side) @@ -213,7 +215,7 @@ public abstract class BlockLiquid extends Block */ public int tickRate(World worldIn, BlockPos pos) { - return this.flowRate >= 0 ? this.flowRate : (worldIn.isLavaFaster(pos) ? (-this.flowRate / 3) : (-this.flowRate)); + return this.flowRate >= 0 ? this.flowRate : (!worldIn.client && ((AWorldServer)worldIn).isLavaFaster(pos) ? (-this.flowRate / 3) : (-this.flowRate)); } public int getMixedBrightnessForBlock(IWorldAccess worldIn, BlockPos pos) @@ -238,7 +240,7 @@ public abstract class BlockLiquid extends Block double d1 = (double)pos.getY(); double d2 = (double)pos.getZ(); - if (this.material == Material.WATER) + if (this.material == Material.water) { int i = ((Integer)state.getValue(LEVEL)).intValue(); @@ -255,7 +257,7 @@ public abstract class BlockLiquid extends Block } } - if (this.material == Material.LAVA && worldIn.getState(pos.up()).getBlock() == Blocks.air && !worldIn.getState(pos.up()).getBlock().isOpaqueCube()) + if (this.material == Material.lava && worldIn.getState(pos.up()).getBlock().getMaterial() == Material.air && !worldIn.getState(pos.up()).getBlock().isOpaqueCube()) { if (rand.chance(100)) { @@ -282,7 +284,7 @@ public abstract class BlockLiquid extends Block double d5 = d1 - 1.05D; double d7 = d2 + (double)rand.floatv(); - if (this.material == Material.WATER) + if (this.material == Material.water) { worldIn.spawnParticle(ParticleType.DRIP_WATER, d3, d5, d7, 0.0D, 0.0D, 0.0D); } @@ -315,9 +317,9 @@ public abstract class BlockLiquid extends Block public boolean checkForMixing(World worldIn, BlockPos pos, State state) { - if(worldIn.client || !Vars.liquidPhysics) + if(worldIn.client || !Config.liquidPhysics) return true; - if (this.material == Material.LAVA) + if (this.material == Material.lava) { boolean flag = false; @@ -394,11 +396,11 @@ public abstract class BlockLiquid extends Block public static BlockDynamicLiquid getFlowingBlock(BlockStaticLiquid block) { - if (block.getMaterial() == Material.WATER) + if (block.getMaterial() == Material.water) { return Blocks.flowing_water; } - else if (block.getMaterial() == Material.LAVA) + else if (block.getMaterial() == Material.lava) { return Blocks.flowing_lava; } @@ -410,11 +412,11 @@ public abstract class BlockLiquid extends Block public static BlockStaticLiquid getStaticBlock(BlockDynamicLiquid block) { - if (block.getMaterial() == Material.WATER) + if (block.getMaterial() == Material.water) { return Blocks.water; } - else if (block.getMaterial() == Material.LAVA) + else if (block.getMaterial() == Material.lava) { return Blocks.lava; } diff --git a/common/src/main/java/common/block/foliage/BlockLog.java b/common/src/common/block/BlockLog.java similarity index 95% rename from common/src/main/java/common/block/foliage/BlockLog.java rename to common/src/common/block/BlockLog.java index 8c9fbab..1646cf3 100755 --- a/common/src/main/java/common/block/foliage/BlockLog.java +++ b/common/src/common/block/BlockLog.java @@ -1,10 +1,8 @@ -package common.block.foliage; +package common.block; -import common.block.BlockRotatedPillar; -import common.block.Material; -import common.block.SoundType; import common.entity.types.EntityLiving; import common.item.CheatTab; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -23,9 +21,9 @@ public class BlockLog extends BlockRotatedPillar public BlockLog() { - super(Material.WOOD); + super(Material.wood); this.setDefaultState(this.getBaseState().withProperty(LOG_AXIS, BlockLog.EnumAxis.Y)); - this.setTab(CheatTab.WOOD); + this.setTab(CheatTab.tabWood); this.setHardness(2.0F); this.setStepSound(SoundType.WOOD); } @@ -41,7 +39,7 @@ public class BlockLog extends BlockRotatedPillar { State iblockstate = worldIn.getState(blockpos); - if (iblockstate.getBlock().getMaterial() == Material.LEAVES && !((Boolean)iblockstate.getValue(BlockLeaves.DECAY)).booleanValue()) + if (iblockstate.getBlock().getMaterial() == Material.leaves && !((Boolean)iblockstate.getValue(BlockLeaves.DECAY)).booleanValue()) { worldIn.setState(blockpos, iblockstate.withProperty(BlockLeaves.DECAY, Boolean.valueOf(true)), 4); } diff --git a/common/src/main/java/common/block/tech/BlockMachine.java b/common/src/common/block/BlockMachine.java similarity index 83% rename from common/src/main/java/common/block/tech/BlockMachine.java rename to common/src/common/block/BlockMachine.java index efdf9c3..782ab21 100755 --- a/common/src/main/java/common/block/tech/BlockMachine.java +++ b/common/src/common/block/BlockMachine.java @@ -1,17 +1,14 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.BlockDirectional; -import common.block.ITileEntityProvider; -import common.block.Material; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.inventory.Container; import common.inventory.InventoryHelper; import common.item.CheatTab; +import common.material.Material; import common.properties.IProperty; import common.tileentity.TileEntity; -import common.tileentity.TileEntityDevice; +import common.tileentity.TileEntityMachine; import common.util.BlockPos; import common.util.Facing; import common.world.State; @@ -20,13 +17,13 @@ import common.world.AWorldServer; public abstract class BlockMachine extends BlockDirectional implements ITileEntityProvider { public BlockMachine() { - super(Material.SOLID); + super(Material.iron); this.hasTile = true; this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); } - public abstract TileEntity createNewTileEntity(World worldIn); + public abstract TileEntity createNewTileEntity(World worldIn, int meta); public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { this.updateState(worldIn, pos, state); @@ -37,8 +34,8 @@ public abstract class BlockMachine extends BlockDirectional implements ITileEnti if(worldIn.client) return true; TileEntity tileentity = worldIn.getTileEntity(pos); - if(tileentity instanceof TileEntityDevice) { - playerIn.displayGUIChest((TileEntityDevice)tileentity); + if(tileentity instanceof TileEntityMachine) { + playerIn.displayGUIChest((TileEntityMachine)tileentity); // playerIn.triggerAchievement(StatList.hopperStat); } return true; @@ -59,8 +56,8 @@ public abstract class BlockMachine extends BlockDirectional implements ITileEnti public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { TileEntity tileentity = worldIn.getTileEntity(pos); - if(tileentity instanceof TileEntityDevice) { - InventoryHelper.dropInventoryItems(worldIn, pos, (TileEntityDevice)tileentity); + if(tileentity instanceof TileEntityMachine) { + InventoryHelper.dropInventoryItems(worldIn, pos, (TileEntityMachine)tileentity); worldIn.updateComparatorOutputLevel(pos, this); } super.onBlockRemoved(worldIn, pos, state); diff --git a/common/src/main/java/common/block/foliage/BlockMelon.java b/common/src/common/block/BlockMelon.java similarity index 87% rename from common/src/main/java/common/block/foliage/BlockMelon.java rename to common/src/common/block/BlockMelon.java index ea81ba1..53e8c84 100755 --- a/common/src/main/java/common/block/foliage/BlockMelon.java +++ b/common/src/common/block/BlockMelon.java @@ -1,10 +1,9 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; import common.init.Items; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.rng.Random; @@ -14,8 +13,8 @@ public class BlockMelon extends Block { public BlockMelon() { - super(Material.SOFT); - this.setTab(CheatTab.PLANTS); + super(Material.gourd); + this.setTab(CheatTab.tabPlants); } /** diff --git a/common/src/common/block/BlockMobSpawner.java b/common/src/common/block/BlockMobSpawner.java new file mode 100755 index 0000000..e8d4f46 --- /dev/null +++ b/common/src/common/block/BlockMobSpawner.java @@ -0,0 +1,90 @@ +package common.block; + +import common.item.CheatTab; +import common.item.Item; +import common.material.Material; +import common.model.BlockLayer; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityMobSpawner; +import common.util.BlockPos; +import common.world.State; +import common.world.World; + +public class BlockMobSpawner extends BlockContainer +{ + public BlockMobSpawner() + { + super(Material.rock); + this.setTab(CheatTab.tabTech); + } + + /** + * Returns a new instance of a block's tile entity class. Called on placing the block. + */ + public TileEntity createNewTileEntity(World worldIn, int meta) + { + return new TileEntityMobSpawner(); + } + + /** + * Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(State state, Random rand, int fortune) + { + return null; + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(Random random) + { + return 0; + } + + /** + * Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) + { + super.dropBlockAsItemWithChance(worldIn, pos, state, chance, fortune); + int i = worldIn.rand.rangeBonus(15, 29, 14); + this.dropXpOnBlockBreak(worldIn, pos, i); + } + + /** + * Used to determine ambient occlusion and culling when rebuilding chunks for render + */ + public boolean isOpaqueCube() + { + return false; + } + + /** + * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() + { + return 3; + } + + public BlockLayer getBlockLayer() + { + return BlockLayer.CUTOUT; + } + + public Item getItem(World worldIn, BlockPos pos) + { + return null; + } + + public boolean isXrayVisible() + { + return true; + } + + public boolean isMagnetic() { + return true; + } +} diff --git a/common/src/main/java/common/block/foliage/BlockMushroom.java b/common/src/common/block/BlockMushroom.java similarity index 92% rename from common/src/main/java/common/block/foliage/BlockMushroom.java rename to common/src/common/block/BlockMushroom.java index 24a8fb4..aedd4e5 100755 --- a/common/src/main/java/common/block/foliage/BlockMushroom.java +++ b/common/src/common/block/BlockMushroom.java @@ -1,14 +1,12 @@ -package common.block.foliage; +package common.block; import common.biome.IBiome; -import common.block.Block; -import common.block.natural.BlockDirt; import common.init.Blocks; +import common.init.Config; import common.model.Model; import common.model.ModelProvider; import common.rng.Random; import common.util.BlockPos; -import common.vars.Vars; import common.world.State; import common.world.World; import common.world.AWorldServer; @@ -24,7 +22,7 @@ public class BlockMushroom extends BlockBush implements IGrowable public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Vars.shroomGrowth > 0 && rand.chance(Vars.shroomGrowth)) + if (Config.shroomGrowth > 0 && rand.chance(Config.shroomGrowth)) { int i = 5; int j = 4; @@ -76,7 +74,7 @@ public class BlockMushroom extends BlockBush implements IGrowable public boolean canBlockStay(World worldIn, BlockPos pos, State state) { - if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) + if (pos.getY() >= 0 && pos.getY() < 512) { State iblockstate = worldIn.getState(pos.down()); return iblockstate.getBlock() == Blocks.mycelium ? true : (iblockstate.getBlock() == Blocks.dirt && iblockstate.getValue(BlockDirt.VARIANT) == BlockDirt.DirtType.PODZOL ? true : worldIn.getLight(pos) < 13 && this.canPlaceBlockOn(iblockstate.getBlock())); diff --git a/common/src/main/java/common/block/foliage/BlockMycelium.java b/common/src/common/block/BlockMycelium.java similarity index 92% rename from common/src/main/java/common/block/foliage/BlockMycelium.java rename to common/src/common/block/BlockMycelium.java index 65e5ce3..977c979 100755 --- a/common/src/main/java/common/block/foliage/BlockMycelium.java +++ b/common/src/common/block/BlockMycelium.java @@ -1,11 +1,10 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; -import common.block.natural.BlockDirt; import common.init.Blocks; +import common.init.Config; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ParticleType; @@ -13,7 +12,6 @@ import common.properties.IProperty; import common.properties.PropertyBool; import common.rng.Random; import common.util.BlockPos; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.AWorldClient; import common.world.State; @@ -25,10 +23,10 @@ public class BlockMycelium extends Block public BlockMycelium() { - super(Material.LOOSE); + super(Material.grass); this.setDefaultState(this.getBaseState().withProperty(SNOWY, Boolean.valueOf(false))); this.setTickRandomly(); - this.setTab(CheatTab.NATURE); + this.setTab(CheatTab.tabNature); } /** @@ -47,10 +45,10 @@ public class BlockMycelium extends Block // { if (worldIn.getLightFromNeighbors(pos.up()) < 4 && worldIn.getState(pos.up()).getBlock().getLightOpacity() > 2) { - if(Vars.mycelDecay) + if(Config.mycelDecay) worldIn.setState(pos, Blocks.dirt.getState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.DIRT)); } - else if(Vars.mycelSpread) + else if(Config.mycelSpread) { if (worldIn.getLightFromNeighbors(pos.up()) >= 9) { diff --git a/common/src/common/block/BlockNote.java b/common/src/common/block/BlockNote.java new file mode 100755 index 0000000..d1711a0 --- /dev/null +++ b/common/src/common/block/BlockNote.java @@ -0,0 +1,125 @@ +package common.block; + +import common.entity.npc.EntityNPC; +import common.init.SoundEvent; +import common.item.CheatTab; +import common.material.Material; +import common.model.ParticleType; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityNote; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; + +public class BlockNote extends BlockContainer +{ +// private static final List INSTRUMENTS = Lists.newArrayList("harp", "bd", "snare", "hat", "bassattack"); + + public BlockNote() + { + super(Material.wood); + this.setTab(CheatTab.tabTech); + } + + /** + * Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) + { + boolean flag = worldIn.isBlockPowered(pos); + TileEntity tileentity = worldIn.getTileEntity(pos); + + if (tileentity instanceof TileEntityNote) + { + TileEntityNote tileentitynote = (TileEntityNote)tileentity; + + if (tileentitynote.previousRedstoneState != flag) + { + if (flag) + { + tileentitynote.triggerNote(worldIn, pos); + } + + tileentitynote.previousRedstoneState = flag; + } + } + } + + public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) + { + if (worldIn.client) + { + return true; + } + else + { + TileEntity tileentity = worldIn.getTileEntity(pos); + + if (tileentity instanceof TileEntityNote) + { + TileEntityNote tileentitynote = (TileEntityNote)tileentity; + tileentitynote.changePitch(); + tileentitynote.triggerNote(worldIn, pos); +// playerIn.triggerAchievement(StatRegistry.noteblockTuneStat); + } + + return true; + } + } + + public void onBlockClicked(World worldIn, BlockPos pos, EntityNPC playerIn) + { + if (!worldIn.client) + { + TileEntity tileentity = worldIn.getTileEntity(pos); + + if (tileentity instanceof TileEntityNote) + { + ((TileEntityNote)tileentity).triggerNote(worldIn, pos); +// playerIn.triggerAchievement(StatRegistry.noteblockPlayStat); + } + } + } + + /** + * Returns a new instance of a block's tile entity class. Called on placing the block. + */ + public TileEntity createNewTileEntity(World worldIn, int meta) + { + return new TileEntityNote(); + } + +// private String getInstrument(int id) +// { +// if (id < 0 || id >= INSTRUMENTS.size()) +// { +// id = 0; +// } +// +// return (String)INSTRUMENTS.get(id); +// } + + /** + * Called on both Client and Server when World#addBlockEvent is called + */ + public boolean onBlockEventReceived(World worldIn, BlockPos pos, State state, int eventID, int eventParam) + { + float f = (float)Math.pow(2.0D, (double)(eventParam - 12) / 12.0D); + worldIn.playSound(SoundEvent.NOTE, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, 3.0F); + worldIn.spawnParticle(ParticleType.NOTE, (double)pos.getX() + 0.5D, (double)pos.getY() + 1.2D, (double)pos.getZ() + 0.5D, (double)eventParam / 24.0D, 0.0D, 0.0D); + return true; + } + + /** + * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() + { + return 3; + } + + public boolean isMagnetic() { + return true; + } +} diff --git a/common/src/main/java/common/block/tech/BlockNuke.java b/common/src/common/block/BlockNuke.java similarity index 92% rename from common/src/main/java/common/block/tech/BlockNuke.java rename to common/src/common/block/BlockNuke.java index 1413eed..7f70ced 100755 --- a/common/src/main/java/common/block/tech/BlockNuke.java +++ b/common/src/common/block/BlockNuke.java @@ -1,11 +1,10 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.item.EntityNuke; import common.init.Blocks; import common.init.SoundEvent; import common.item.CheatTab; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.util.BlockPos; @@ -18,8 +17,8 @@ public class BlockNuke extends Block { public BlockNuke() { - super(Material.EXPLOSIVE); - this.setTab(CheatTab.TECHNOLOGY); + super(Material.tnt); + this.setTab(CheatTab.tabTech); } public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) diff --git a/common/src/main/java/common/block/natural/BlockObsidian.java b/common/src/common/block/BlockObsidian.java similarity index 81% rename from common/src/main/java/common/block/natural/BlockObsidian.java rename to common/src/common/block/BlockObsidian.java index 97cdf05..b2c80f9 100755 --- a/common/src/main/java/common/block/natural/BlockObsidian.java +++ b/common/src/common/block/BlockObsidian.java @@ -1,11 +1,10 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; import common.init.Blocks; import common.init.ItemRegistry; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.rng.Random; import common.world.State; @@ -13,8 +12,8 @@ public class BlockObsidian extends Block { public BlockObsidian() { - super(Material.SOLID); - this.setTab(CheatTab.NATURE); + super(Material.rock); + this.setTab(CheatTab.tabNature); } /** diff --git a/common/src/main/java/common/block/natural/BlockOre.java b/common/src/common/block/BlockOre.java similarity index 91% rename from common/src/main/java/common/block/natural/BlockOre.java rename to common/src/common/block/BlockOre.java index bcf4df1..e83b028 100755 --- a/common/src/main/java/common/block/natural/BlockOre.java +++ b/common/src/common/block/BlockOre.java @@ -1,14 +1,13 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; +import common.init.Config; import common.init.ItemRegistry; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; -import common.vars.Vars; import common.world.State; import common.world.World; @@ -22,8 +21,8 @@ public class BlockOre extends Block public BlockOre() { - super(Material.SOLID); - this.setTab(CheatTab.GEMS); + super(Material.rock); + this.setTab(CheatTab.tabGems); } public void setDropItem(ItemStack item, int chance, int minXp) { @@ -60,7 +59,7 @@ public class BlockOre extends Block public int quantityDropped(Random random) { - return this.dropItem == null ? 1 : (this.dropItem.size + (this.dropChance > 0 ? random.zrange(this.dropChance + 1) : 0)); + return this.dropItem == null ? 1 : (this.dropItem.stackSize + (this.dropChance > 0 ? random.zrange(this.dropChance + 1) : 0)); // this == Blocks.lapis_ore ? 4 + random.nextInt(5) : 1; } @@ -86,7 +85,7 @@ public class BlockOre extends Block public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) { - if(!worldIn.client && this.smeltItem != null && Vars.cleanCut) { + if(!worldIn.client && this.smeltItem != null && Config.cleanCut) { if (worldIn.rand.floatv() <= chance) { spawnAsEntity(worldIn, pos, this.smeltItem.copy()); diff --git a/common/src/main/java/common/block/natural/BlockPackedIce.java b/common/src/common/block/BlockPackedIce.java similarity index 68% rename from common/src/main/java/common/block/natural/BlockPackedIce.java rename to common/src/common/block/BlockPackedIce.java index 59ddc47..c21ff05 100755 --- a/common/src/main/java/common/block/natural/BlockPackedIce.java +++ b/common/src/common/block/BlockPackedIce.java @@ -1,17 +1,16 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; import common.item.CheatTab; +import common.material.Material; import common.rng.Random; public class BlockPackedIce extends Block { public BlockPackedIce() { - super(Material.LOOSE); + super(Material.packedIce); this.slipperiness = 0.98F; - this.setTab(CheatTab.NATURE); + this.setTab(CheatTab.tabNature); } /** diff --git a/common/src/main/java/common/block/artificial/BlockPane.java b/common/src/common/block/BlockPane.java similarity index 94% rename from common/src/main/java/common/block/artificial/BlockPane.java rename to common/src/common/block/BlockPane.java index 2125ba3..5de8821 100755 --- a/common/src/main/java/common/block/artificial/BlockPane.java +++ b/common/src/common/block/BlockPane.java @@ -1,13 +1,12 @@ -package common.block.artificial; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.entity.Entity; import common.init.Blocks; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -35,7 +34,7 @@ public class BlockPane extends Block super(materialIn); this.setDefaultState(this.getBaseState().withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false))); this.canDrop = canDrop; - this.setTab(CheatTab.BLOCKS); + this.setTab(CheatTab.tabBlocks); } /** @@ -207,14 +206,8 @@ public class BlockPane extends Block } public boolean isMagnetic() { - return this.material == Material.SOLID; + return this.material == Material.iron; } - - public boolean onShot(World world, BlockPos pos, State state, Entity projectile) { - if(this.material != Material.SOLID) - world.destroyBlock(pos, true); - return this.material == Material.SOLID; - } protected String getPaneBase(State state) { return "glass"; @@ -232,7 +225,7 @@ public class BlockPane extends Block int sides = (n ? 1 : 0) + (s ? 1 : 0) + (w ? 1 : 0) + (e ? 1 : 0); if(this.canDrop) { if(sides == 0 || sides == 4) - return provider.getModel(name) + return provider.getModel(name).noOcclude() .add(8, 0, 0, 8, 16, 16) .w().uv(0, 0, 16, 16).noCull() .e().uv(0, 0, 16, 16).noCull() @@ -255,7 +248,7 @@ public class BlockPane extends Block .d().uv(9, 0, 7, 7).rot(90).noCull() .u().uv(7, 0, 9, 7).rot(90).noCull(); else if(sides == 1) - return provider.getModel(name) + return provider.getModel(name).noOcclude() .add(8, 0, 0, 8, 16, 8) .w().uv(8, 0, 16, 16).noCull() .e().uv(8, 0, 16, 16).noCull() @@ -267,7 +260,7 @@ public class BlockPane extends Block .u().uv(7, 0, 9, 9).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return provider.getModel(name) + return provider.getModel(name).noOcclude() .add(8, 0, 0, 8, 16, 8) .w().uv(0, 0, 8, 16).noCull() .e().uv(8, 0, 16, 16).noCull() @@ -287,7 +280,7 @@ public class BlockPane extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2) - return provider.getModel(name) + return provider.getModel(name).noOcclude() .add(8, 0, 0, 8, 16, 16) .w().uv(0, 0, 16, 16).noCull() .e().uv(0, 0, 16, 16).noCull() @@ -299,7 +292,7 @@ public class BlockPane extends Block .u().uv(9, 0, 7, 16).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else - return provider.getModel(name) + return provider.getModel(name).noOcclude() .add(8, 0, 0, 8, 16, 16) .w().uv(0, 0, 16, 16).noCull() .e().uv(0, 0, 16, 16).noCull() @@ -323,7 +316,7 @@ public class BlockPane extends Block String pane = this.getPaneBase(state); String edge = this.getPaneEdge(state); if(sides == 0 || sides == 4) - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 0, 9, 16, 16).noShade() .d(edge).uv(7, 0, 9, 16).noCull() .u(edge).uv(7, 0, 9, 16).noCull() @@ -339,7 +332,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16) .e(edge).uv(7, 0, 9, 16); else if(sides == 1 && (n || e)) - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 0, 9, 16, 9).noShade() .d(edge).uv(7, 0, 9, 9).noCull() .u(edge).uv(7, 0, 9, 9).noCull() @@ -349,7 +342,7 @@ public class BlockPane extends Block .e().uv(7, 0, 16, 16).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(sides == 1) - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 7, 9, 16, 16).noShade() .d(edge).uv(7, 7, 9, 16).noCull() .u(edge).uv(7, 7, 9, 16).noCull() @@ -359,7 +352,7 @@ public class BlockPane extends Block .e().uv(0, 0, 9, 16).noCull() .rotate(s ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(e && n && !s && !w) - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 0, 9, 16, 9).noShade() .d(edge).uv(7, 0, 9, 9).noCull() .u(edge).uv(7, 0, 9, 9).noCull() @@ -375,7 +368,7 @@ public class BlockPane extends Block .w().uv(7, 0, 9, 16).noCull() .e(edge).uv(7, 0, 9, 16); else if(e && !n && s && !w) - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 7, 9, 16, 16).noShade() .d(edge).uv(7, 7, 9, 16).noCull() .u(edge).uv(7, 7, 9, 16).noCull() @@ -391,7 +384,7 @@ public class BlockPane extends Block .w().uv(7, 0, 9, 16).noCull() .e(edge).uv(7, 0, 9, 16); else if(!e && !n && s && w) - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 7, 9, 16, 16).noShade() .d(edge).uv(7, 7, 9, 16).noCull() .u(edge).uv(7, 7, 9, 16).noCull() @@ -407,7 +400,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16) .e().uv(7, 0, 9, 16).noCull(); else if(!e && n && !s && w) - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 0, 9, 16, 9).noShade() .d(edge).uv(7, 0, 9, 9).noCull() .u(edge).uv(7, 0, 9, 9).noCull() @@ -423,7 +416,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16) .e().uv(7, 0, 9, 16).noCull(); else if((!e && n && s && !w) || (e && !n && !s && w)) - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 0, 9, 16, 16).noShade() .d(edge).uv(7, 0, 9, 16).noCull() .u(edge).uv(7, 0, 9, 16).noCull() @@ -433,7 +426,7 @@ public class BlockPane extends Block .e().uv(0, 0, 16, 16).noCull() .rotate(s ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(!w) - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 0, 9, 16, 16).noShade() .d(edge).uv(7, 0, 9, 16).noCull() .u(edge).uv(7, 0, 9, 16).noCull() @@ -449,7 +442,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16).noCull() .e(edge).uv(7, 0, 9, 16); else if(!n) - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 9, 9, 16, 16).noShade() .d(edge).uv(7, 9, 9, 16).noCull() .u(edge).uv(7, 9, 9, 16).noCull() @@ -465,7 +458,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16) .e(edge).uv(7, 0, 9, 16); else if(!e) - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 0, 9, 16, 16).noShade() .d(edge).uv(7, 0, 9, 16).noCull() .u(edge).uv(7, 0, 9, 16).noCull() @@ -481,7 +474,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16).cull(Facing.EAST) .e(edge).uv(7, 0, 9, 16).noCull(); else - return provider.getModel(pane) + return provider.getModel(pane).noOcclude() .add(7, 0, 0, 9, 16, 7).noShade() .d(edge).uv(7, 0, 9, 7).noCull() .u(edge).uv(7, 0, 9, 7).noCull() diff --git a/common/src/main/java/common/block/tech/BlockPistonBase.java b/common/src/common/block/BlockPistonBase.java similarity index 95% rename from common/src/main/java/common/block/tech/BlockPistonBase.java rename to common/src/common/block/BlockPistonBase.java index cc6a061..e09a0e3 100755 --- a/common/src/main/java/common/block/tech/BlockPistonBase.java +++ b/common/src/common/block/BlockPistonBase.java @@ -1,18 +1,16 @@ -package common.block.tech; +package common.block; import java.util.List; -import common.block.Block; -import common.block.ITileEntityProvider; -import common.block.Material; -import common.block.SoundType; import common.collect.Lists; import common.entity.Entity; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.init.Config; import common.init.SoundEvent; import common.item.CheatTab; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -25,7 +23,6 @@ import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; import common.util.Facing; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.State; import common.world.World; @@ -101,7 +98,7 @@ public class BlockPistonBase extends Block { Block block = this.world.getState(origin).getBlock(); - if (block == Blocks.air) + if (block.getMaterial() == Material.air) { return true; } @@ -121,7 +118,7 @@ public class BlockPistonBase extends Block { int i = 1; - if (i + this.toMove.size() > Vars.pistonLimit) + if (i + this.toMove.size() > Config.pistonLimit) { return false; } @@ -132,14 +129,14 @@ public class BlockPistonBase extends Block BlockPos blockpos = origin.offset(this.moveDirection.getOpposite(), i); block = this.world.getState(blockpos).getBlock(); - if (block == Blocks.air || !BlockPistonBase.canPush(block, this.world, blockpos, this.moveDirection, false) || blockpos.equals(this.pistonPos)) + if (block.getMaterial() == Material.air || !BlockPistonBase.canPush(block, this.world, blockpos, this.moveDirection, false) || blockpos.equals(this.pistonPos)) { break; } ++i; - if (i + this.toMove.size() > Vars.pistonLimit) + if (i + this.toMove.size() > Config.pistonLimit) { return false; } @@ -179,7 +176,7 @@ public class BlockPistonBase extends Block block = this.world.getState(blockpos1).getBlock(); - if (block == Blocks.air) + if (block.getMaterial() == Material.air) { return true; } @@ -195,7 +192,7 @@ public class BlockPistonBase extends Block return true; } - if (this.toMove.size() >= Vars.pistonLimit) + if (this.toMove.size() >= Config.pistonLimit) { return false; } @@ -254,12 +251,12 @@ public class BlockPistonBase extends Block public BlockPistonBase(boolean isSticky) { - super(Material.PISTON); + super(Material.piston); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(EXTENDED, Boolean.valueOf(false))); this.isSticky = isSticky; this.setStepSound(SoundType.STONE); this.setHardness(0.5F); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); } /** @@ -427,7 +424,7 @@ public class BlockPistonBase extends Block } } - if (!flag1 && block != Blocks.air && canPush(block, worldIn, blockpos, enumfacing.getOpposite(), false) && (block.getMobilityFlag() == 0 || block == Blocks.piston || block == Blocks.sticky_piston)) + if (!flag1 && block.getMaterial() != Material.air && canPush(block, worldIn, blockpos, enumfacing.getOpposite(), false) && (block.getMobilityFlag() == 0 || block == Blocks.piston || block == Blocks.sticky_piston)) { this.doMove(worldIn, pos, enumfacing, false); } @@ -551,9 +548,9 @@ public class BlockPistonBase extends Block { return false; } - else if (pos.getY() >= -World.MAX_SIZE_Y && (direction != Facing.DOWN || pos.getY() != -World.MAX_SIZE_Y)) + else if (pos.getY() >= 0 && (direction != Facing.DOWN || pos.getY() != 0)) { - if (pos.getY() <= World.MAX_SIZE_Y - 1 && (direction != Facing.UP || pos.getY() != World.MAX_SIZE_Y - 1)) + if (pos.getY() <= World.HEIGHT - 1 && (direction != Facing.UP || pos.getY() != World.HEIGHT - 1)) { if (blockIn != Blocks.piston && blockIn != Blocks.sticky_piston) { diff --git a/common/src/main/java/common/block/tech/BlockPistonHead.java b/common/src/common/block/BlockPistonHead.java similarity index 98% rename from common/src/main/java/common/block/tech/BlockPistonHead.java rename to common/src/common/block/BlockPistonHead.java index 21aa5e2..fff8415 100755 --- a/common/src/main/java/common/block/tech/BlockPistonHead.java +++ b/common/src/common/block/BlockPistonHead.java @@ -1,14 +1,12 @@ -package common.block.tech; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; -import common.block.SoundType; import common.entity.Entity; import common.init.Blocks; import common.init.ItemRegistry; import common.item.Item; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -34,7 +32,7 @@ public class BlockPistonHead extends Block public BlockPistonHead() { - super(Material.PISTON); + super(Material.piston); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(TYPE, BlockPistonHead.EnumPistonType.DEFAULT).withProperty(SHORT, Boolean.valueOf(false))); this.setStepSound(SoundType.STONE); this.setHardness(0.5F); diff --git a/common/src/main/java/common/block/tech/BlockPistonMoving.java b/common/src/common/block/BlockPistonMoving.java similarity index 97% rename from common/src/main/java/common/block/tech/BlockPistonMoving.java rename to common/src/common/block/BlockPistonMoving.java index 666061d..8047a3c 100755 --- a/common/src/main/java/common/block/tech/BlockPistonMoving.java +++ b/common/src/common/block/BlockPistonMoving.java @@ -1,11 +1,9 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.BlockContainer; -import common.block.Material; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.item.Item; +import common.material.Material; import common.properties.IProperty; import common.properties.PropertyDirection; import common.properties.PropertyEnum; @@ -29,7 +27,7 @@ public class BlockPistonMoving extends BlockContainer public BlockPistonMoving() { - super(Material.PISTON); + super(Material.piston); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(TYPE, BlockPistonHead.EnumPistonType.DEFAULT)); this.setHardness(-1.0F); } @@ -37,7 +35,7 @@ public class BlockPistonMoving extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return null; } @@ -188,7 +186,7 @@ public class BlockPistonMoving extends BlockContainer State iblockstate = tileentitypiston.getPistonState(); Block block = iblockstate.getBlock(); - if (block == this || block == Blocks.air) + if (block == this || block.getMaterial() == Material.air) { return; } @@ -219,7 +217,7 @@ public class BlockPistonMoving extends BlockContainer public BoundingBox getBoundingBox(World worldIn, BlockPos pos, State extendingBlock, float progress, Facing direction) { - if (extendingBlock.getBlock() != this && extendingBlock.getBlock() != Blocks.air) + if (extendingBlock.getBlock() != this && extendingBlock.getBlock().getMaterial() != Material.air) { BoundingBox axisalignedbb = extendingBlock.getBlock().getCollisionBoundingBox(worldIn, pos, extendingBlock); diff --git a/common/src/main/java/common/block/artificial/BlockPortal.java b/common/src/common/block/BlockPortal.java similarity index 97% rename from common/src/main/java/common/block/artificial/BlockPortal.java rename to common/src/common/block/BlockPortal.java index a140f4b..190f899 100755 --- a/common/src/main/java/common/block/artificial/BlockPortal.java +++ b/common/src/common/block/BlockPortal.java @@ -1,13 +1,11 @@ -package common.block.artificial; +package common.block; import java.util.Map; -import common.block.Block; -import common.block.Material; -import common.block.natural.BlockFire; import common.entity.Entity; import common.init.Blocks; import common.item.Item; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -25,7 +23,7 @@ import common.world.AWorldClient; import common.world.State; import common.world.World; -public class BlockPortal extends Block +public class BlockPortal extends BlockBreakable { public static final PropertyEnum AXIS = PropertyEnum.create("axis", Facing.Axis.class, Facing.Axis.X, Facing.Axis.Z); public static final PropertyInteger DIM = PropertyInteger.create("dim", 0, 7); @@ -34,7 +32,7 @@ public class BlockPortal extends Block public BlockPortal() { - super(Material.PORTAL); + super(Material.portal, false); this.setDefaultState(this.getBaseState().withProperty(AXIS, Facing.Axis.X).withProperty(DIM, 0)); // this.setTickRandomly(); } @@ -99,14 +97,6 @@ public class BlockPortal extends Block return false; } - public boolean isOpaqueCube() { - return false; - } - - public BlockLayer getBlockLayer() { - return BlockLayer.TRANSLUCENT; - } - public boolean tryIgnitePortal(World worldIn, BlockPos pos, int dim) { BlockPortal.Size size = new BlockPortal.Size(worldIn, pos, Facing.Axis.X, dim); @@ -202,6 +192,11 @@ public class BlockPortal extends Block return 0; } + public BlockLayer getBlockLayer() + { + return BlockLayer.TRANSLUCENT; + } + /** * Called When an Entity Collided with the Block */ @@ -328,7 +323,7 @@ public class BlockPortal extends Block // { // BlockWorldState blockworldstate = blockpattern$patternhelper.translateOffset(i, j, 1); // -// if (blockworldstate.getBlockState() != null && blockworldstate.getBlockState().getBlock() != Blocks.air) +// if (blockworldstate.getBlockState() != null && blockworldstate.getBlockState().getBlock().getMaterial() != Material.air) // { // ++aint[enumfacing$axisdirection.ordinal()]; // } @@ -498,7 +493,7 @@ public class BlockPortal extends Block protected boolean func_150857_a(Block p_150857_1_) { - return p_150857_1_ == Blocks.air || p_150857_1_ instanceof BlockFire || p_150857_1_ == Blocks.portal; + return p_150857_1_.material == Material.air || p_150857_1_ == Blocks.fire || p_150857_1_ == Blocks.portal; } public boolean func_150860_b() diff --git a/common/src/main/java/common/block/artificial/BlockPortalFrame.java b/common/src/common/block/BlockPortalFrame.java similarity index 97% rename from common/src/main/java/common/block/artificial/BlockPortalFrame.java rename to common/src/common/block/BlockPortalFrame.java index 0c5a300..2f2d61e 100755 --- a/common/src/main/java/common/block/artificial/BlockPortalFrame.java +++ b/common/src/common/block/BlockPortalFrame.java @@ -1,9 +1,7 @@ -package common.block.artificial; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.entity.Entity; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; @@ -12,6 +10,7 @@ import common.init.ItemRegistry; import common.init.Items; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -33,7 +32,7 @@ public class BlockPortalFrame extends Block public BlockPortalFrame() { - super(Material.SOLID); + super(Material.rock); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(ORB, Boolean.valueOf(false))); } diff --git a/common/src/main/java/common/block/foliage/BlockPotato.java b/common/src/common/block/BlockPotato.java similarity index 97% rename from common/src/main/java/common/block/foliage/BlockPotato.java rename to common/src/common/block/BlockPotato.java index 2083b27..bc74922 100755 --- a/common/src/main/java/common/block/foliage/BlockPotato.java +++ b/common/src/common/block/BlockPotato.java @@ -1,4 +1,4 @@ -package common.block.foliage; +package common.block; import common.init.Items; import common.item.Item; diff --git a/common/src/main/java/common/block/tech/BlockPressurePlate.java b/common/src/common/block/BlockPressurePlate.java similarity index 97% rename from common/src/main/java/common/block/tech/BlockPressurePlate.java rename to common/src/common/block/BlockPressurePlate.java index b17b4b0..3efdea7 100755 --- a/common/src/main/java/common/block/tech/BlockPressurePlate.java +++ b/common/src/common/block/BlockPressurePlate.java @@ -1,10 +1,10 @@ -package common.block.tech; +package common.block; import java.util.List; -import common.block.Material; import common.entity.Entity; import common.entity.types.EntityLiving; +import common.material.Material; import common.properties.IProperty; import common.properties.PropertyBool; import common.util.BlockPos; diff --git a/common/src/main/java/common/block/tech/BlockPressurePlateWeighted.java b/common/src/common/block/BlockPressurePlateWeighted.java similarity index 97% rename from common/src/main/java/common/block/tech/BlockPressurePlateWeighted.java rename to common/src/common/block/BlockPressurePlateWeighted.java index eeac2ec..be01b35 100755 --- a/common/src/main/java/common/block/tech/BlockPressurePlateWeighted.java +++ b/common/src/common/block/BlockPressurePlateWeighted.java @@ -1,7 +1,7 @@ -package common.block.tech; +package common.block; -import common.block.Material; import common.entity.Entity; +import common.material.Material; import common.properties.IProperty; import common.properties.PropertyInteger; import common.util.BlockPos; diff --git a/common/src/common/block/BlockPumpkin.java b/common/src/common/block/BlockPumpkin.java new file mode 100755 index 0000000..53866ad --- /dev/null +++ b/common/src/common/block/BlockPumpkin.java @@ -0,0 +1,191 @@ +package common.block; + +import common.entity.types.EntityLiving; +import common.item.CheatTab; +import common.material.Material; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; + +public class BlockPumpkin extends BlockDirectional +{ +// private BlockPattern snowmanBasePattern; +// private BlockPattern snowmanPattern; +// private BlockPattern golemBasePattern; +// private BlockPattern golemPattern; +// private static final Predicate field_181085_Q = new Predicate() +// { +// public boolean test(IBlockState p_apply_1_) +// { +// return p_apply_1_ != null && (p_apply_1_.getBlock() == Blocks.pumpkin || p_apply_1_.getBlock() == Blocks.lit_pumpkin); +// } +// }; + + public BlockPumpkin() + { + super(Material.gourd); + this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); +// this.setTickRandomly(true); + this.setTab(CheatTab.tabPlants); + } + +// public void onBlockAdded(IWorldServer worldIn, BlockPos pos, IBlockState state) +// { +// super.onBlockAdded(worldIn, pos, state); +// this.trySpawnGolem(worldIn, pos); +// } + +// public boolean canDispenserPlace(World worldIn, BlockPos pos) +// { +// return this.getSnowmanBasePattern().match(worldIn, pos) != null; // || this.getGolemBasePattern().match(worldIn, pos) != null; +// } + +// private void trySpawnGolem(World worldIn, BlockPos pos) +// { +// if(!Config.createSnowman) { +// return; +// } +// +// BlockPattern.PatternHelper blockpattern$patternhelper; +// +// if ((blockpattern$patternhelper = this.getSnowmanPattern().match(worldIn, pos)) != null) +// { +// for (int i = 0; i < this.getSnowmanPattern().getThumbLength(); ++i) +// { +// BlockWorldState blockworldstate = blockpattern$patternhelper.translateOffset(0, i, 0); +// worldIn.setBlockState(blockworldstate.getPos(), Blocks.air.getDefaultState(), 2); +// } +// +// EntitySnowman entitysnowman = new EntitySnowman(worldIn); +// BlockPos blockpos1 = blockpattern$patternhelper.translateOffset(0, 2, 0).getPos(); +// entitysnowman.setLocationAndAngles((double)blockpos1.getX() + 0.5D, (double)blockpos1.getY() + 0.05D, (double)blockpos1.getZ() + 0.5D, 0.0F, 0.0F); +// worldIn.spawnEntityInWorld(entitysnowman); +// +// for (int j = 0; j < 120; ++j) +// { +// worldIn.spawnParticle(EnumParticleTypes.SNOW_SHOVEL, (double)blockpos1.getX() + worldIn.rand.doublev(), (double)blockpos1.getY() + worldIn.rand.doublev() * 2.5D, (double)blockpos1.getZ() + worldIn.rand.doublev(), 0.0D, 0.0D, 0.0D); +// } +// +// for (int i1 = 0; i1 < this.getSnowmanPattern().getThumbLength(); ++i1) +// { +// BlockWorldState blockworldstate1 = blockpattern$patternhelper.translateOffset(0, i1, 0); +// worldIn.notifyNeighborsRespectDebug(blockworldstate1.getPos(), Blocks.air); +// } +// } +//// else if ((blockpattern$patternhelper = this.getGolemPattern().match(worldIn, pos)) != null) +//// { +//// for (int k = 0; k < this.getGolemPattern().getPalmLength(); ++k) +//// { +//// for (int l = 0; l < this.getGolemPattern().getThumbLength(); ++l) +//// { +//// worldIn.setBlockState(blockpattern$patternhelper.translateOffset(k, l, 0).getPos(), Blocks.air.getDefaultState(), 2); +//// } +//// } +//// +//// BlockPos blockpos = blockpattern$patternhelper.translateOffset(1, 2, 0).getPos(); +//// EntityIronGolem entityirongolem = new EntityIronGolem(worldIn); +////// entityirongolem.setPlayerCreated(true); +//// entityirongolem.setLocationAndAngles((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.05D, (double)blockpos.getZ() + 0.5D, 0.0F, 0.0F); +//// worldIn.spawnEntityInWorld(entityirongolem); +//// +//// for (int j1 = 0; j1 < 120; ++j1) +//// { +//// worldIn.spawnParticle(EnumParticleTypes.SNOWBALL, (double)blockpos.getX() + worldIn.rand.doublev(), (double)blockpos.getY() + worldIn.rand.doublev() * 3.9D, (double)blockpos.getZ() + worldIn.rand.doublev(), 0.0D, 0.0D, 0.0D); +//// } +//// +//// for (int k1 = 0; k1 < this.getGolemPattern().getPalmLength(); ++k1) +//// { +//// for (int l1 = 0; l1 < this.getGolemPattern().getThumbLength(); ++l1) +//// { +//// BlockWorldState blockworldstate2 = blockpattern$patternhelper.translateOffset(k1, l1, 0); +//// worldIn.notifyNeighborsRespectDebug(blockworldstate2.getPos(), Blocks.air); +//// } +//// } +//// } +// } + + public boolean canPlaceBlockAt(World worldIn, BlockPos pos) + { + return worldIn.getState(pos).getBlock().material.isReplaceable() && worldIn.isBlockSolid(pos.down()); + } + + /** + * Called by ItemBlocks just before a block is actually set in the world, to allow for adjustments to the + * IBlockstate + */ + public State onBlockPlaced(World worldIn, BlockPos pos, Facing facing, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) + { + return this.getState().withProperty(FACING, placer.getHorizontalFacing().getOpposite()); + } + + /** + * Convert the given metadata into a BlockState for this Block + */ + public State getStateFromMeta(int meta) + { + return this.getState().withProperty(FACING, Facing.getHorizontal(meta)); + } + + /** + * Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(State state) + { + return ((Facing)state.getValue(FACING)).getHorizontalIndex(); + } + + protected IProperty[] getProperties() + { + return new IProperty[] {FACING}; + } + +// protected BlockPattern getSnowmanBasePattern() +// { +// if (this.snowmanBasePattern == null) +// { +// this.snowmanBasePattern = FactoryBlockPattern.start().aisle(" ", "#", "#").where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.snow))).build(); +// } +// +// return this.snowmanBasePattern; +// } +// +// protected BlockPattern getSnowmanPattern() +// { +// if (this.snowmanPattern == null) +// { +// this.snowmanPattern = FactoryBlockPattern.start().aisle("^", "#", "#").where('^', BlockWorldState.hasState(field_181085_Q)).where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.snow))).build(); +// } +// +// return this.snowmanPattern; +// } + +// protected BlockPattern getGolemBasePattern() +// { +// if (this.golemBasePattern == null) +// { +// this.golemBasePattern = FactoryBlockPattern.start().aisle("~ ~", "###", "~#~").where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.iron_block))).where('~', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.air))).build(); +// } +// +// return this.golemBasePattern; +// } + +// protected BlockPattern getGolemPattern() +// { +// if (this.golemPattern == null) +// { +// this.golemPattern = FactoryBlockPattern.start().aisle("~^~", "###", "~#~").where('^', BlockWorldState.hasState(field_181085_Q)).where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.iron_block))).where('~', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.air))).build(); +// } +// +// return this.golemPattern; +// } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("pumpkin_side").add().du("pumpkin_top").n("pumpkin_face_" + (this.getLightValue() == 0 ? "off" : "on")) + .s().we().rotate(ModelRotation.getNorthRot(state.getValue(FACING))); + } +} diff --git a/common/src/main/java/common/block/artificial/BlockQuartz.java b/common/src/common/block/BlockQuartz.java similarity index 97% rename from common/src/main/java/common/block/artificial/BlockQuartz.java rename to common/src/common/block/BlockQuartz.java index 5e78fc2..d8e6619 100755 --- a/common/src/main/java/common/block/artificial/BlockQuartz.java +++ b/common/src/common/block/BlockQuartz.java @@ -1,14 +1,13 @@ -package common.block.artificial; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.entity.types.EntityLiving; import common.init.ItemRegistry; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -28,9 +27,9 @@ public class BlockQuartz extends Block public BlockQuartz(String prefix) { - super(Material.SOLID); + super(Material.rock); this.setDefaultState(this.getBaseState().withProperty(VARIANT, BlockQuartz.EnumType.DEFAULT)); - this.setTab(CheatTab.BLOCKS); + this.setTab(CheatTab.tabBlocks); this.prefix = prefix; } diff --git a/common/src/main/java/common/block/tech/BlockRail.java b/common/src/common/block/BlockRail.java similarity index 96% rename from common/src/main/java/common/block/tech/BlockRail.java rename to common/src/common/block/BlockRail.java index de178aa..db02ca7 100755 --- a/common/src/main/java/common/block/tech/BlockRail.java +++ b/common/src/common/block/BlockRail.java @@ -1,6 +1,5 @@ -package common.block.tech; +package common.block; -import common.block.Block; import common.properties.IProperty; import common.properties.PropertyEnum; import common.util.BlockPos; diff --git a/common/src/main/java/common/block/tech/BlockRailBase.java b/common/src/common/block/BlockRailBase.java similarity index 98% rename from common/src/main/java/common/block/tech/BlockRailBase.java rename to common/src/common/block/BlockRailBase.java index df3e43c..01c0256 100755 --- a/common/src/main/java/common/block/tech/BlockRailBase.java +++ b/common/src/common/block/BlockRailBase.java @@ -1,12 +1,11 @@ -package common.block.tech; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.collect.Lists; import common.init.Blocks; import common.item.CheatTab; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -40,10 +39,10 @@ public abstract class BlockRailBase extends Block public BlockRailBase(boolean isPowered) { - super(Material.SMALL); + super(Material.circuits); this.isPowered = isPowered; this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); } public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) @@ -195,7 +194,7 @@ public abstract class BlockRailBase extends Block case NORTH_SOUTH: case EAST_WEST: default: - return provider.getModel(name) + return provider.getModel(name).noOcclude() .add(0, 1, 0, 16, 1, 16) .d().uv(0, 16, 16, 0).noCull() .u().uv(0, 0, 16, 16).noCull() @@ -204,7 +203,7 @@ public abstract class BlockRailBase extends Block case NORTH_WEST: case SOUTH_EAST: case SOUTH_WEST: - return provider.getModel(name + "_turned") + return provider.getModel(name + "_turned").noOcclude() .add(0, 1, 0, 16, 1, 16) .d().uv(0, 16, 16, 0).noCull() .u().uv(0, 0, 16, 16).noCull() @@ -212,14 +211,14 @@ public abstract class BlockRailBase extends Block ModelRotation.X0_Y180 : (dir == EnumRailDirection.NORTH_EAST ? ModelRotation.X0_Y270 : ModelRotation.X0_Y0))); case ASCENDING_NORTH: case ASCENDING_EAST: - return provider.getModel(name) + return provider.getModel(name).noOcclude() .add(0, 9, 0, 16, 9, 16).rotate(8, 9, 8, Facing.Axis.X, 45, true) .d().uv(0, 16, 16, 0).noCull() .u().uv(0, 0, 16, 16).noCull() .rotate(dir == EnumRailDirection.ASCENDING_EAST ? ModelRotation.X0_Y90 : ModelRotation.X0_Y0); case ASCENDING_SOUTH: case ASCENDING_WEST: - return provider.getModel(name) + return provider.getModel(name).noOcclude() .add(0, 9, 0, 16, 9, 16).rotate(8, 9, 8, Facing.Axis.X, -45, true) .d().uv(0, 16, 16, 0).noCull() .u().uv(0, 0, 16, 16).noCull() diff --git a/common/src/main/java/common/block/tech/BlockRailDetector.java b/common/src/common/block/BlockRailDetector.java similarity index 99% rename from common/src/main/java/common/block/tech/BlockRailDetector.java rename to common/src/common/block/BlockRailDetector.java index 330cc6c..1c2fbd6 100755 --- a/common/src/main/java/common/block/tech/BlockRailDetector.java +++ b/common/src/common/block/BlockRailDetector.java @@ -1,4 +1,4 @@ -package common.block.tech; +package common.block; import java.util.List; import java.util.function.Predicate; diff --git a/common/src/main/java/common/block/tech/BlockRailPowered.java b/common/src/common/block/BlockRailPowered.java similarity index 99% rename from common/src/main/java/common/block/tech/BlockRailPowered.java rename to common/src/common/block/BlockRailPowered.java index 727800b..5989b95 100755 --- a/common/src/main/java/common/block/tech/BlockRailPowered.java +++ b/common/src/common/block/BlockRailPowered.java @@ -1,8 +1,7 @@ -package common.block.tech; +package common.block; import java.util.function.Predicate; -import common.block.Block; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; diff --git a/common/src/main/java/common/block/tech/BlockRedstoneComparator.java b/common/src/common/block/BlockRedstoneComparator.java similarity index 98% rename from common/src/main/java/common/block/tech/BlockRedstoneComparator.java rename to common/src/common/block/BlockRedstoneComparator.java index 635d9f4..b44b3dc 100755 --- a/common/src/main/java/common/block/tech/BlockRedstoneComparator.java +++ b/common/src/common/block/BlockRedstoneComparator.java @@ -1,7 +1,5 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.ITileEntityProvider; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; @@ -134,7 +132,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile { i = block.getComparatorInputOverride(worldIn, blockpos); } -// else if (block == Blocks.air) +// else if (block.getMaterial() == Material.air) // { // EntityFrame entityitemframe = this.findItemFrame(worldIn, enumfacing, blockpos); // @@ -244,7 +242,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { super.onBlockAdded(worldIn, pos, state); - worldIn.setTileEntity(pos, this.createNewTileEntity(worldIn)); + worldIn.setTileEntity(pos, this.createNewTileEntity(worldIn, 0)); } public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) @@ -267,7 +265,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityComparator(); } @@ -316,7 +314,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile } public Model getModel(ModelProvider provider, String name, State state) { - return (state.getValue(POWERED) ? (state.getValue(MODE) == Mode.SUBTRACT ? provider.getModel("comparator_on") + return (state.getValue(POWERED) ? (state.getValue(MODE) == Mode.SUBTRACT ? provider.getModel("comparator_on").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -347,7 +345,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile .e("redstone_torch").uv(6, 5, 10, 9).noCull() .add(6, 2, 2, 10, 6, 4) .n("redstone_torch").uv(6, 5, 10, 9).noCull() - .s("redstone_torch").uv(6, 5, 10, 9).noCull() : provider.getModel("comparator_on") + .s("redstone_torch").uv(6, 5, 10, 9).noCull() : provider.getModel("comparator_on").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -378,7 +376,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile .s("unlit_redstone_torch").uv(7, 6, 9, 8).noCull() .w("unlit_redstone_torch").uv(7, 6, 9, 8).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 8).noCull()) - : (state.getValue(MODE) == Mode.SUBTRACT ? provider.getModel("comparator_off") + : (state.getValue(MODE) == Mode.SUBTRACT ? provider.getModel("comparator_off").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -407,7 +405,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile .e("redstone_torch").uv(6, 5, 10, 9).noCull() .add(6, 2, 2, 10, 6, 4) .n("redstone_torch").uv(6, 5, 10, 9).noCull() - .s("redstone_torch").uv(6, 5, 10, 9).noCull() : provider.getModel("comparator_off") + .s("redstone_torch").uv(6, 5, 10, 9).noCull() : provider.getModel("comparator_off").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() diff --git a/common/src/main/java/common/block/tech/BlockRedstoneDiode.java b/common/src/common/block/BlockRedstoneDiode.java similarity index 98% rename from common/src/main/java/common/block/tech/BlockRedstoneDiode.java rename to common/src/common/block/BlockRedstoneDiode.java index 5c61033..7be2128 100755 --- a/common/src/main/java/common/block/tech/BlockRedstoneDiode.java +++ b/common/src/common/block/BlockRedstoneDiode.java @@ -1,11 +1,9 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.BlockDirectional; -import common.block.Material; import common.entity.types.EntityLiving; import common.init.Blocks; import common.item.ItemStack; +import common.material.Material; import common.model.BlockLayer; import common.rng.Random; import common.util.BlockPos; @@ -22,7 +20,7 @@ public abstract class BlockRedstoneDiode extends BlockDirectional public BlockRedstoneDiode(boolean powered) { - super(Material.SMALL); + super(Material.circuits); this.isRepeaterPowered = powered; this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); } diff --git a/common/src/main/java/common/block/tech/BlockRedstoneLight.java b/common/src/common/block/BlockRedstoneLight.java similarity index 95% rename from common/src/main/java/common/block/tech/BlockRedstoneLight.java rename to common/src/common/block/BlockRedstoneLight.java index dad8d50..579156b 100755 --- a/common/src/main/java/common/block/tech/BlockRedstoneLight.java +++ b/common/src/common/block/BlockRedstoneLight.java @@ -1,11 +1,10 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.Material; import common.init.Blocks; import common.init.ItemRegistry; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.world.State; @@ -18,7 +17,7 @@ public class BlockRedstoneLight extends Block public BlockRedstoneLight(boolean isOn) { - super(Material.LOOSE); + super(Material.redstoneLight); this.isOn = isOn; if (isOn) diff --git a/common/src/main/java/common/block/natural/BlockRedstoneOre.java b/common/src/common/block/BlockRedstoneOre.java similarity index 97% rename from common/src/main/java/common/block/natural/BlockRedstoneOre.java rename to common/src/common/block/BlockRedstoneOre.java index f42bba2..13eb609 100755 --- a/common/src/main/java/common/block/natural/BlockRedstoneOre.java +++ b/common/src/common/block/BlockRedstoneOre.java @@ -1,7 +1,5 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.Entity; import common.entity.npc.EntityNPC; import common.init.Blocks; @@ -9,6 +7,7 @@ import common.init.ItemRegistry; import common.init.Items; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ParticleType; @@ -26,7 +25,7 @@ public class BlockRedstoneOre extends Block public BlockRedstoneOre(boolean isOn) { - super(Material.SOLID); + super(Material.rock); if (isOn) { diff --git a/common/src/main/java/common/block/tech/BlockRedstoneRepeater.java b/common/src/common/block/BlockRedstoneRepeater.java similarity index 98% rename from common/src/main/java/common/block/tech/BlockRedstoneRepeater.java rename to common/src/common/block/BlockRedstoneRepeater.java index 07499f2..a98316f 100755 --- a/common/src/main/java/common/block/tech/BlockRedstoneRepeater.java +++ b/common/src/common/block/BlockRedstoneRepeater.java @@ -1,6 +1,5 @@ -package common.block.tech; +package common.block; -import common.block.Block; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.init.Items; @@ -162,7 +161,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode switch(delay) { case 1: default: - return ModelProvider.getModelProvider().getModel("repeater_off") + return ModelProvider.getModelProvider().getModel("repeater_off").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -185,7 +184,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 2: - return ModelProvider.getModelProvider().getModel("repeater_off") + return ModelProvider.getModelProvider().getModel("repeater_off").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -208,7 +207,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 3: - return ModelProvider.getModelProvider().getModel("repeater_off") + return ModelProvider.getModelProvider().getModel("repeater_off").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -231,7 +230,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 4: - return ModelProvider.getModelProvider().getModel("repeater_off") + return ModelProvider.getModelProvider().getModel("repeater_off").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -260,7 +259,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode switch(delay) { case 1: default: - return ModelProvider.getModelProvider().getModel("repeater_on") + return ModelProvider.getModelProvider().getModel("repeater_on").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -285,7 +284,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 2: - return ModelProvider.getModelProvider().getModel("repeater_on") + return ModelProvider.getModelProvider().getModel("repeater_on").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -310,7 +309,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 3: - return ModelProvider.getModelProvider().getModel("repeater_on") + return ModelProvider.getModelProvider().getModel("repeater_on").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -335,7 +334,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 4: - return ModelProvider.getModelProvider().getModel("repeater_on") + return ModelProvider.getModelProvider().getModel("repeater_on").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -366,7 +365,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode switch(delay) { case 1: default: - return ModelProvider.getModelProvider().getModel("repeater_off") + return ModelProvider.getModelProvider().getModel("repeater_off").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -389,7 +388,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 2: - return ModelProvider.getModelProvider().getModel("repeater_off") + return ModelProvider.getModelProvider().getModel("repeater_off").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -412,7 +411,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 3: - return ModelProvider.getModelProvider().getModel("repeater_off") + return ModelProvider.getModelProvider().getModel("repeater_off").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -435,7 +434,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 4: - return ModelProvider.getModelProvider().getModel("repeater_off") + return ModelProvider.getModelProvider().getModel("repeater_off").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -464,7 +463,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode switch(delay) { case 1: default: - return ModelProvider.getModelProvider().getModel("repeater_on") + return ModelProvider.getModelProvider().getModel("repeater_on").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -488,7 +487,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 2: - return ModelProvider.getModelProvider().getModel("repeater_on") + return ModelProvider.getModelProvider().getModel("repeater_on").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -512,7 +511,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 3: - return ModelProvider.getModelProvider().getModel("repeater_on") + return ModelProvider.getModelProvider().getModel("repeater_on").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -536,7 +535,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 4: - return ModelProvider.getModelProvider().getModel("repeater_on") + return ModelProvider.getModelProvider().getModel("repeater_on").noOcclude() .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() diff --git a/common/src/main/java/common/block/tech/BlockRedstoneTorch.java b/common/src/common/block/BlockRedstoneTorch.java similarity index 99% rename from common/src/main/java/common/block/tech/BlockRedstoneTorch.java rename to common/src/common/block/BlockRedstoneTorch.java index 7f73f2b..1de1741 100755 --- a/common/src/main/java/common/block/tech/BlockRedstoneTorch.java +++ b/common/src/common/block/BlockRedstoneTorch.java @@ -1,9 +1,8 @@ -package common.block.tech; +package common.block; import java.util.List; import java.util.Map; -import common.block.Block; import common.collect.Lists; import common.collect.Maps; import common.init.Blocks; diff --git a/common/src/main/java/common/block/tech/BlockRedstoneWire.java b/common/src/common/block/BlockRedstoneWire.java similarity index 97% rename from common/src/main/java/common/block/tech/BlockRedstoneWire.java rename to common/src/common/block/BlockRedstoneWire.java index 514b546..a77e77a 100755 --- a/common/src/main/java/common/block/tech/BlockRedstoneWire.java +++ b/common/src/common/block/BlockRedstoneWire.java @@ -1,16 +1,15 @@ -package common.block.tech; +package common.block; import java.util.EnumSet; import java.util.List; import java.util.Set; -import common.block.Block; -import common.block.Material; import common.collect.Lists; import common.collect.Sets; import common.init.Blocks; import common.init.Items; import common.item.Item; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -34,19 +33,19 @@ import common.world.AWorldServer; public class BlockRedstoneWire extends Block { - private static final Model redstone_none = ModelProvider.getModelProvider().getModel("redstone_dust_cross") + private static final Model redstone_none = ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude() .add(5, 0.25f, 5, 11, 0.25f, 11).noShade() .u().uv(5, 5, 11, 11).tint().noCull() .add(5, 0.25f, 5, 11, 0.25f, 11).noShade() .u("redstone_dust_cross_overlay").uv(5, 5, 11, 11).noCull() ; - private static final Model redstone_nsew = ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + private static final Model redstone_nsew = ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_cross_overlay").uv(0, 0, 16, 16).noCull() ; - private static final Model redstone_unusueuw = ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + private static final Model redstone_unusueuw = ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -68,7 +67,7 @@ public class BlockRedstoneWire extends Block .add(0.25f, 0, 0, 0.25f, 16, 16).noShade() .e("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() ; - private static final Model redstone_unus = ModelProvider.getModelProvider().getModel("redstone_dust_cross") + private static final Model redstone_unus = ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_line").uv(0, 0, 16, 16).rot(90).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -82,7 +81,7 @@ public class BlockRedstoneWire extends Block .add(0, 0, 15.75f, 16, 16, 15.75f).noShade() .n("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() ; - private static final Model redstone_ueuw = ModelProvider.getModelProvider().getModel("redstone_dust_cross") + private static final Model redstone_ueuw = ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_line").uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -98,7 +97,7 @@ public class BlockRedstoneWire extends Block ; private static Model redstone_n(boolean rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross") + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_line").uv(0, 0, 16, 16).rot(90).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -107,7 +106,7 @@ public class BlockRedstoneWire extends Block } private static Model redstone_ne(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() .u().uv(5, 0, 16, 11).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() @@ -116,7 +115,7 @@ public class BlockRedstoneWire extends Block } private static Model redstone_uew(boolean rot) { - Model model = ModelProvider.getModelProvider().getModel("redstone_dust_cross") + Model model = ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_line").uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -128,7 +127,7 @@ public class BlockRedstoneWire extends Block return rot ? model.uvLock().rotate(ModelRotation.X0_Y180) : model; } private static Model redstone_nue(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() .u().uv(5, 0, 16, 11).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() @@ -140,7 +139,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_une(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() .u().uv(5, 0, 16, 11).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() @@ -152,7 +151,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_nse(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -160,7 +159,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_uns(boolean lock, ModelRotation rot) { - Model model = ModelProvider.getModelProvider().getModel("redstone_dust_cross") + Model model = ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_line").uv(0, 0, 16, 16).rot(90).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -174,7 +173,7 @@ public class BlockRedstoneWire extends Block } private static Model redstone_nsue(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -186,7 +185,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_unse(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -198,7 +197,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_nuse(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -210,7 +209,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_unue(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() .u().uv(5, 0, 16, 11).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() @@ -227,7 +226,7 @@ public class BlockRedstoneWire extends Block } private static Model redstone_unusue(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -247,7 +246,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_unusew(boolean rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -263,7 +262,7 @@ public class BlockRedstoneWire extends Block .rotate(rot ? ModelRotation.X0_Y90 : ModelRotation.X0_Y0); } private static Model redstone_unusuew(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -283,7 +282,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_unuse(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -299,7 +298,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_nusue(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -315,7 +314,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_unsew(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -327,7 +326,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_unsuew(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -343,7 +342,7 @@ public class BlockRedstoneWire extends Block .rotate(rot); } private static Model redstone_unsue(ModelRotation rot) { - return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").noOcclude().uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -369,7 +368,7 @@ public class BlockRedstoneWire extends Block public BlockRedstoneWire() { - super(Material.SMALL); + super(Material.circuits); this.setDefaultState(this.getBaseState().withProperty(NORTH, BlockRedstoneWire.EnumAttachPosition.NONE).withProperty(EAST, BlockRedstoneWire.EnumAttachPosition.NONE).withProperty(SOUTH, BlockRedstoneWire.EnumAttachPosition.NONE).withProperty(WEST, BlockRedstoneWire.EnumAttachPosition.NONE).withProperty(POWER, Integer.valueOf(0))); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F); } diff --git a/common/src/main/java/common/block/foliage/BlockReed.java b/common/src/common/block/BlockReed.java similarity index 91% rename from common/src/main/java/common/block/foliage/BlockReed.java rename to common/src/common/block/BlockReed.java index e581de9..216f4dd 100755 --- a/common/src/main/java/common/block/foliage/BlockReed.java +++ b/common/src/common/block/BlockReed.java @@ -1,10 +1,11 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; +import common.color.Colorizer; import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.item.Item; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -14,7 +15,6 @@ import common.rng.Random; import common.util.BlockPos; import common.util.BoundingBox; import common.util.Facing; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.State; import common.world.World; @@ -26,7 +26,7 @@ public class BlockReed extends Block public BlockReed() { - super(Material.PLANT); + super(Material.plants); this.setDefaultState(this.getBaseState().withProperty(AGE, Integer.valueOf(0))); float f = 0.375F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 1.0F, 0.5F + f); @@ -35,14 +35,14 @@ public class BlockReed extends Block public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Vars.reedDry && worldIn.getTemperatureC(pos) >= 50.0f) + if(Config.reedDry && worldIn.getTemperatureC(pos) >= 50.0f) { worldIn.destroyBlock(pos, true); return; } if (worldIn.getState(pos.down()).getBlock() == Blocks.reeds || this.checkForDrop(worldIn, pos, state)) { - if (Vars.reedHeight > 0 && worldIn.isAirBlock(pos.up())) + if (Config.reedHeight > 0 && worldIn.isAirBlock(pos.up())) { int i; @@ -51,7 +51,7 @@ public class BlockReed extends Block ; } - if (i < Vars.reedHeight) + if (i < Config.reedHeight) { int j = ((Integer)state.getValue(AGE)).intValue(); @@ -85,7 +85,7 @@ public class BlockReed extends Block { for (Facing enumfacing : Facing.Plane.HORIZONTAL) { - if (worldIn.getState(pos.offset(enumfacing).down()).getBlock().getMaterial() == Material.WATER) + if (worldIn.getState(pos.offset(enumfacing).down()).getBlock().getMaterial() == Material.water) { return true; } @@ -155,7 +155,7 @@ public class BlockReed extends Block public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass) { - return worldIn.getBiomeGenForCoords(pos).getGrassColorAtPos(pos); + return Colorizer.getGrassColor(1.0f, 0.9f); } public BlockLayer getBlockLayer() diff --git a/common/src/main/java/common/block/natural/BlockRock.java b/common/src/common/block/BlockRock.java similarity index 89% rename from common/src/main/java/common/block/natural/BlockRock.java rename to common/src/common/block/BlockRock.java index 92b0352..a6f0e4d 100755 --- a/common/src/main/java/common/block/natural/BlockRock.java +++ b/common/src/common/block/BlockRock.java @@ -1,12 +1,11 @@ -package common.block.natural; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; @@ -17,9 +16,9 @@ public class BlockRock extends Block { public static final PropertyBool SMOOTH = PropertyBool.create("smooth"); public BlockRock() { - super(Material.SOLID); + super(Material.rock); this.setDefaultState(this.getBaseState().withProperty(SMOOTH, false)); - this.setTab(CheatTab.NATURE); + this.setTab(CheatTab.tabNature); } public int damageDropped(State state) { diff --git a/common/src/main/java/common/block/BlockRotatedPillar.java b/common/src/common/block/BlockRotatedPillar.java similarity index 66% rename from common/src/main/java/common/block/BlockRotatedPillar.java rename to common/src/common/block/BlockRotatedPillar.java index 5071e8a..232db9c 100755 --- a/common/src/main/java/common/block/BlockRotatedPillar.java +++ b/common/src/common/block/BlockRotatedPillar.java @@ -1,5 +1,6 @@ package common.block; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -7,14 +8,16 @@ import common.properties.PropertyEnum; import common.util.Facing; import common.world.State; -public abstract class BlockRotatedPillar extends Block { - public static final PropertyEnum AXIS = PropertyEnum.create("axis", Facing.Axis.class); +public abstract class BlockRotatedPillar extends Block +{ + public static final PropertyEnum AXIS = PropertyEnum.create("axis", Facing.Axis.class); - public BlockRotatedPillar(Material material) { - super(material); - } + public BlockRotatedPillar(Material materialIn) + { + super(materialIn); + } - public Model getModel(ModelProvider provider, String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { switch(state.getValue(AXIS)) { case X: return provider.getModel(name + "_side").add().d().rot(180).u() @@ -28,5 +31,5 @@ public abstract class BlockRotatedPillar extends Block { .n(name + "_top").rot(180).s(name + "_top").w().rot(270) .e().rot(90); } - } + } } diff --git a/common/src/main/java/common/block/natural/BlockSand.java b/common/src/common/block/BlockSand.java similarity index 95% rename from common/src/main/java/common/block/natural/BlockSand.java rename to common/src/common/block/BlockSand.java index ae5d6cb..147941b 100755 --- a/common/src/main/java/common/block/natural/BlockSand.java +++ b/common/src/common/block/BlockSand.java @@ -1,9 +1,7 @@ -package common.block.natural; +package common.block; import java.util.List; -import common.block.BlockFalling; -import common.block.Material; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; @@ -20,9 +18,7 @@ public class BlockSand extends BlockFalling public BlockSand() { - super(Material.LOOSE); this.setDefaultState(this.getBaseState().withProperty(VARIANT, BlockSand.EnumType.SAND)); - this.setTab(CheatTab.NATURE); } /** diff --git a/common/src/main/java/common/block/natural/BlockSandStone.java b/common/src/common/block/BlockSandStone.java similarity index 96% rename from common/src/main/java/common/block/natural/BlockSandStone.java rename to common/src/common/block/BlockSandStone.java index ca1bcac..3ed7fcc 100755 --- a/common/src/main/java/common/block/natural/BlockSandStone.java +++ b/common/src/common/block/BlockSandStone.java @@ -1,12 +1,11 @@ -package common.block.natural; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; @@ -20,9 +19,9 @@ public class BlockSandStone extends Block public BlockSandStone() { - super(Material.SOLID); + super(Material.rock); this.setDefaultState(this.getBaseState().withProperty(TYPE, BlockSandStone.EnumType.DEFAULT)); - this.setTab(CheatTab.NATURE); + this.setTab(CheatTab.tabNature); } /** diff --git a/common/src/main/java/common/block/foliage/BlockSapling.java b/common/src/common/block/BlockSapling.java similarity index 94% rename from common/src/main/java/common/block/foliage/BlockSapling.java rename to common/src/common/block/BlockSapling.java index df3ca7d..f03ba37 100755 --- a/common/src/main/java/common/block/foliage/BlockSapling.java +++ b/common/src/common/block/BlockSapling.java @@ -1,10 +1,11 @@ -package common.block.foliage; +package common.block; import java.util.List; import common.biome.IBiome; import common.collect.Lists; import common.init.Blocks; +import common.init.Config; import common.init.WoodType; import common.item.CheatTab; import common.model.Model; @@ -13,7 +14,6 @@ import common.properties.IProperty; import common.properties.PropertyInteger; import common.rng.Random; import common.util.BlockPos; -import common.vars.Vars; import common.world.State; import common.world.World; import common.world.AWorldServer; @@ -31,7 +31,7 @@ public class BlockSapling extends BlockBush implements IGrowable this.setDefaultState(this.getBaseState() /* .withProperty(TYPE, BlockPlanks.EnumType.OAK) */ .withProperty(STAGE, Integer.valueOf(0))); float f = 0.4F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f * 2.0F, 0.5F + f); - this.setTab(CheatTab.PLANTS); + this.setTab(CheatTab.tabPlants); this.type = type; SAPLINGS.add(this); } @@ -46,7 +46,7 @@ public class BlockSapling extends BlockBush implements IGrowable public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Vars.saplingDry && worldIn.getTemperatureC(pos) >= 50.0f) + if(Config.saplingDry && worldIn.getTemperatureC(pos) >= 50.0f) { worldIn.setState(pos, worldIn.rand.chance(25) ? Blocks.air.getState() : Blocks.tallgrass.getState().withProperty(BlockTallGrass.TYPE, BlockTallGrass.EnumType.DEAD_BUSH)); @@ -56,7 +56,7 @@ public class BlockSapling extends BlockBush implements IGrowable // { super.updateTick(worldIn, pos, state, rand); - if (Vars.treeGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9 && rand.chance(Vars.treeGrowth)) + if (Config.treeGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9 && rand.chance(Config.treeGrowth)) { this.grow(worldIn, pos, state, rand); } diff --git a/common/src/main/java/common/block/tile/BlockSign.java b/common/src/common/block/BlockSign.java similarity index 93% rename from common/src/main/java/common/block/tile/BlockSign.java rename to common/src/common/block/BlockSign.java index d467d32..aa1aedf 100755 --- a/common/src/main/java/common/block/tile/BlockSign.java +++ b/common/src/common/block/BlockSign.java @@ -1,17 +1,16 @@ -package common.block.tile; +package common.block; -import common.block.BlockContainer; -import common.block.Material; import common.entity.npc.EntityNPC; +import common.init.Config; import common.init.Items; import common.item.Item; +import common.material.Material; import common.rng.Random; import common.tileentity.TileEntity; import common.tileentity.TileEntitySign; import common.util.BlockPos; import common.util.BoundingBox; import common.util.Facing; -import common.vars.Vars; import common.world.IBlockAccess; import common.world.State; import common.world.World; @@ -20,7 +19,7 @@ public class BlockSign extends BlockContainer { public BlockSign() { - super(Material.WOOD); + super(Material.wood); float f = 0.25F; float f1 = 1.0F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); @@ -28,7 +27,7 @@ public class BlockSign extends BlockContainer public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { - if (!worldIn.client && Vars.editSigns) + if (!worldIn.client && Config.editSigns) { TileEntity tileentity = worldIn.getTileEntity(pos); @@ -80,7 +79,7 @@ public class BlockSign extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn) + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntitySign(); } diff --git a/common/src/common/block/BlockSkull.java b/common/src/common/block/BlockSkull.java new file mode 100755 index 0000000..97d44ec --- /dev/null +++ b/common/src/common/block/BlockSkull.java @@ -0,0 +1,153 @@ +package common.block; + +import common.entity.types.EntityLiving; +import common.init.Items; +import common.item.Item; +import common.item.ItemStack; +import common.material.Material; +import common.model.Transforms; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.tileentity.TileEntitySkull; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; + +public class BlockSkull extends BlockContainer +{ + public static final PropertyDirection FACING = PropertyDirection.create("facing"); + + public BlockSkull() + { + super(Material.circuits); + this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); + this.setBlockBounds(0.25F, 0.0F, 0.25F, 0.75F, 0.5F, 0.75F); + } + + public boolean isOpaqueCube() + { + return false; + } + + public boolean isFullCube() + { + return false; + } + + public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos) + { + switch ((Facing)worldIn.getState(pos).getValue(FACING)) + { + case UP: + default: + this.setBlockBounds(0.25F, 0.0F, 0.25F, 0.75F, 0.5F, 0.75F); + break; + + case NORTH: + this.setBlockBounds(0.25F, 0.25F, 0.5F, 0.75F, 0.75F, 1.0F); + break; + + case SOUTH: + this.setBlockBounds(0.25F, 0.25F, 0.0F, 0.75F, 0.75F, 0.5F); + break; + + case WEST: + this.setBlockBounds(0.5F, 0.25F, 0.25F, 1.0F, 0.75F, 0.75F); + break; + + case EAST: + this.setBlockBounds(0.0F, 0.25F, 0.25F, 0.5F, 0.75F, 0.75F); + } + } + + public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) + { + this.setBlockBoundsBasedOnState(worldIn, pos); + return super.getCollisionBoundingBox(worldIn, pos, state); + } + + public State onBlockPlaced(World worldIn, BlockPos pos, Facing facing, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) + { + return this.getState().withProperty(FACING, placer.getHorizontalFacing()); + } + + public TileEntity createNewTileEntity(World worldIn, int meta) + { + return new TileEntitySkull(); + } + + public Item getItem(World worldIn, BlockPos pos) + { + return Items.skull; + } + + public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) + { + } + +// public void onBlockHarvested(World worldIn, BlockPos pos, State state, EntityNPC player) +// { +// if (player.creative) +// { +// if(!worldIn.client) +// worldIn.removeTileEntity(pos); +// } +// +// super.onBlockHarvested(worldIn, pos, state, player); +// } + + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) + { + if (!worldIn.client) + { + TileEntity tileentity = worldIn.getTileEntity(pos); + if (tileentity instanceof TileEntitySkull) + { +// TileEntitySkull tileentityskull = (TileEntitySkull)tileentity; + ItemStack itemstack = new ItemStack(Items.skull, 1, 0); +// if (tileentityskull.getUser() != null) +// { +// itemstack.setTagCompound(new NBTTagCompound()); +// itemstack.getTagCompound().setString("SkullOwner", tileentityskull.getUser()); +// } + spawnAsEntity(worldIn, pos, itemstack); + } + super.onBlockRemoved(worldIn, pos, state); + } + } + + public Item getItemDropped(State state, Random rand, int fortune) + { + return Items.skull; + } + + public State getStateFromMeta(int meta) + { + return this.getState().withProperty(FACING, Facing.getFront(meta)); + } + + public int getMetaFromState(State state) + { + return ((Facing)state.getValue(FACING)).getIndex(); + } + + protected IProperty[] getProperties() + { + return new IProperty[] {FACING}; + } + + public boolean isXrayVisible() + { + return true; + } + + public Transforms getTransform() { + return Transforms.SKULL; + } +} diff --git a/common/src/main/java/common/block/artificial/BlockSlab.java b/common/src/common/block/BlockSlab.java similarity index 98% rename from common/src/main/java/common/block/artificial/BlockSlab.java rename to common/src/common/block/BlockSlab.java index 223745c..1daa63d 100755 --- a/common/src/main/java/common/block/artificial/BlockSlab.java +++ b/common/src/common/block/BlockSlab.java @@ -1,15 +1,14 @@ -package common.block.artificial; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.collect.Lists; import common.entity.Entity; import common.entity.types.EntityLiving; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; @@ -44,7 +43,7 @@ public class BlockSlab extends Block super(materialIn); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.DOWN).withProperty(DOUBLE, false) .withProperty(SEAMLESS, false)); - this.setTab(materialIn == Material.WOOD ? CheatTab.WOOD : CheatTab.BLOCKS); + this.setTab(materialIn == Material.wood ? CheatTab.tabWood : CheatTab.tabBlocks); // this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.5F); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); diff --git a/common/src/common/block/BlockSlime.java b/common/src/common/block/BlockSlime.java new file mode 100755 index 0000000..64ba03a --- /dev/null +++ b/common/src/common/block/BlockSlime.java @@ -0,0 +1,93 @@ +package common.block; + +import common.entity.Entity; +import common.item.CheatTab; +import common.material.Material; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.util.BlockPos; +import common.world.State; +import common.world.World; + +public class BlockSlime extends BlockBreakable +{ + private static final Model slime = ModelProvider.getModelProvider().getModel("slime") + .add(0, 0, 0, 16, 16, 16) + .d().uv(0, 0, 16, 16).noCull() + .u().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull() + .add(3, 3, 3, 13, 13, 13) + .d().uv(3, 3, 13, 13).noCull() + .u().uv(3, 3, 13, 13).noCull() + .n().uv(3, 3, 13, 13).noCull() + .s().uv(3, 3, 13, 13).noCull() + .w().uv(3, 3, 13, 13).noCull() + .e().uv(3, 3, 13, 13).noCull() + ; + + public BlockSlime() + { + super(Material.clay, false); + this.setTab(CheatTab.tabTech); + this.slipperiness = 0.8F; + } + + public BlockLayer getBlockLayer() + { + return BlockLayer.TRANSLUCENT; + } + + /** + * Block's chance to react to a living entity falling on it. + */ + public void onFallenUpon(World worldIn, BlockPos pos, Entity entityIn, float fallDistance) + { + if (entityIn.isSneaking()) + { + super.onFallenUpon(worldIn, pos, entityIn, fallDistance); + } + else + { + entityIn.fall(fallDistance, 0.0F); + } + } + + /** + * Called when an Entity lands on this Block. This method *must* update motionY because the entity will not do that + * on its own + */ + public void onLanded(World worldIn, Entity entityIn) + { + if (entityIn.isSneaking()) + { + super.onLanded(worldIn, entityIn); + } + else if (entityIn.motionY < 0.0D) + { + entityIn.motionY = -entityIn.motionY; + } + } + + /** + * Triggered whenever an entity collides with this block (enters into the block) + */ + public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, Entity entityIn) + { + if (Math.abs(entityIn.motionY) < 0.1D && !entityIn.isSneaking()) + { + double d0 = 0.4D + Math.abs(entityIn.motionY) * 0.2D; + entityIn.motionX *= d0; + entityIn.motionZ *= d0; + } + + super.onEntityCollidedWithBlock(worldIn, pos, entityIn); + } + + public Model getModel(ModelProvider provider, String name, State state) { + return slime; + } +} diff --git a/common/src/main/java/common/block/natural/BlockSnow.java b/common/src/common/block/BlockSnow.java similarity index 92% rename from common/src/main/java/common/block/natural/BlockSnow.java rename to common/src/common/block/BlockSnow.java index 4a41240..02c193a 100755 --- a/common/src/main/java/common/block/natural/BlockSnow.java +++ b/common/src/common/block/BlockSnow.java @@ -1,13 +1,13 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.npc.EntityNPC; import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.Transforms; @@ -18,10 +18,8 @@ import common.tileentity.TileEntity; import common.util.BlockPos; import common.util.BoundingBox; import common.util.Facing; -import common.vars.Vars; import common.world.IBlockAccess; import common.world.IWorldAccess; -import common.world.LightType; import common.world.State; import common.world.World; import common.world.AWorldServer; @@ -32,11 +30,11 @@ public class BlockSnow extends Block public BlockSnow() { - super(Material.POWDER); + super(Material.snow); this.setDefaultState(this.getBaseState().withProperty(LAYERS, Integer.valueOf(1))); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); this.setTickRandomly(); - this.setTab(CheatTab.DECORATION); + this.setTab(CheatTab.tabDeco); this.setBlockBoundsForItemRender(); } @@ -88,7 +86,7 @@ public class BlockSnow extends Block { State iblockstate = worldIn.getState(pos.down()); Block block = iblockstate.getBlock(); - return block != Blocks.ice && block != Blocks.packed_ice ? (block.getMaterial() == Material.LEAVES ? true : (block == this && ((Integer)iblockstate.getValue(LAYERS)).intValue() >= 7 ? true : block.isOpaqueCube() && block.getMaterial().blocksMovement())) : false; + return block != Blocks.ice && block != Blocks.packed_ice ? (block.getMaterial() == Material.leaves ? true : (block == this && ((Integer)iblockstate.getValue(LAYERS)).intValue() >= 7 ? true : block.isOpaqueCube() && block.material.blocksMovement())) : false; } /** @@ -138,7 +136,7 @@ public class BlockSnow extends Block public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Vars.snowMelt && (worldIn.getLightFor(LightType.BLOCK, pos) > 11 || !worldIn.canFreezeAt(pos))) + if (Config.snowMelt && ((worldIn.getLightFor(pos) > 11) || !worldIn.canFreezeAt(pos))) { this.dropBlockAsItem(worldIn, pos, worldIn.getState(pos), 0); worldIn.setBlockToAir(pos); diff --git a/common/src/common/block/BlockSnowBlock.java b/common/src/common/block/BlockSnowBlock.java new file mode 100755 index 0000000..da6fd2f --- /dev/null +++ b/common/src/common/block/BlockSnowBlock.java @@ -0,0 +1,46 @@ +package common.block; + +import common.init.Config; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.material.Material; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import common.world.AWorldServer; + +public class BlockSnowBlock extends Block +{ + public BlockSnowBlock() + { + super(Material.craftedSnow); + this.setTickRandomly(); + this.setTab(CheatTab.tabNature); + } + + /** + * Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(State state, Random rand, int fortune) + { + return Items.snowball; + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(Random random) + { + return 4; + } + + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) + { + if (Config.snowFullMelt && worldIn.getLightFor(pos) > 11) + { + this.dropBlockAsItem(worldIn, pos, worldIn.getState(pos), 0); + worldIn.setBlockToAir(pos); + } + } +} diff --git a/common/src/main/java/common/block/natural/BlockSoulSand.java b/common/src/common/block/BlockSoulSand.java similarity index 84% rename from common/src/main/java/common/block/natural/BlockSoulSand.java rename to common/src/common/block/BlockSoulSand.java index e521c5f..b9aa80a 100755 --- a/common/src/main/java/common/block/natural/BlockSoulSand.java +++ b/common/src/common/block/BlockSoulSand.java @@ -1,9 +1,8 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.Entity; import common.item.CheatTab; +import common.material.Material; import common.util.BlockPos; import common.util.BoundingBox; import common.world.State; @@ -13,8 +12,8 @@ public class BlockSoulSand extends Block { public BlockSoulSand() { - super(Material.LOOSE); - this.setTab(CheatTab.NATURE); + super(Material.sand); + this.setTab(CheatTab.tabNature); } public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) diff --git a/common/src/common/block/BlockSourceImpl.java b/common/src/common/block/BlockSourceImpl.java new file mode 100755 index 0000000..c5e241e --- /dev/null +++ b/common/src/common/block/BlockSourceImpl.java @@ -0,0 +1,55 @@ +package common.block; + +import common.dispenser.IBlockSource; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.world.State; +import common.world.World; + +public class BlockSourceImpl implements IBlockSource +{ + private final World worldObj; + private final BlockPos pos; + + public BlockSourceImpl(World worldIn, BlockPos posIn) + { + this.worldObj = worldIn; + this.pos = posIn; + } + + public World getWorld() + { + return this.worldObj; + } + + public double getX() + { + return (double)this.pos.getX() + 0.5D; + } + + public double getY() + { + return (double)this.pos.getY() + 0.5D; + } + + public double getZ() + { + return (double)this.pos.getZ() + 0.5D; + } + + public BlockPos getBlockPos() + { + return this.pos; + } + + public int getBlockMetadata() + { + State iblockstate = this.worldObj.getState(this.pos); + return iblockstate.getBlock().getMetaFromState(iblockstate); + } + + public T getBlockTileEntity() + { + return (T)this.worldObj.getTileEntity(this.pos); + } +} diff --git a/common/src/common/block/BlockStainedGlass.java b/common/src/common/block/BlockStainedGlass.java new file mode 100755 index 0000000..de0f6a2 --- /dev/null +++ b/common/src/common/block/BlockStainedGlass.java @@ -0,0 +1,120 @@ +package common.block; + +import java.util.List; + +import common.color.DyeColor; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.material.Material; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.world.State; + +public class BlockStainedGlass extends BlockBreakable +{ + public static final PropertyEnum COLOR = PropertyEnum.create("color", DyeColor.class); + + public BlockStainedGlass(Material materialIn) + { + super(materialIn, false); + this.setDefaultState(this.getBaseState().withProperty(COLOR, DyeColor.WHITE)); + this.setTab(CheatTab.tabBlocks); + } + + /** + * Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It + * returns the metadata of the dropped item based on the old metadata of the block. + */ + public int damageDropped(State state) + { + return ((DyeColor)state.getValue(COLOR)).getMetadata(); + } + + /** + * returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks) + */ + public void getSubBlocks(Item itemIn, CheatTab tab, List list) + { + for (DyeColor enumdyecolor : DyeColor.values()) + { + list.add(new ItemStack(itemIn, 1, enumdyecolor.getMetadata())); + } + } + +// /** +// * Get the MapColor for this Block and the given BlockState +// */ +// public MapColor getMapColor(IBlockState state) +// { +// return ((EnumDyeColor)state.getValue(COLOR)).getMapColor(); +// } + + public BlockLayer getBlockLayer() + { + return BlockLayer.TRANSLUCENT; + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(Random random) + { + return 0; + } + + public boolean canSilkHarvest() + { + return true; + } + + public boolean isFullCube() + { + return false; + } + + /** + * Convert the given metadata into a BlockState for this Block + */ + public State getStateFromMeta(int meta) + { + return this.getState().withProperty(COLOR, DyeColor.byMetadata(meta)); + } + +// public void onBlockAdded(IWorldServer worldIn, BlockPos pos, State state) +// { +// if (!worldIn.client) +// { +// BlockBeacon.updateColorAsync(worldIn, pos); +// } +// } +// +// public void onBlockRemoved(IWorldServer worldIn, BlockPos pos, State state) +// { +// if (!worldIn.client) +// { +// BlockBeacon.updateColorAsync(worldIn, pos); +// } +// } + + /** + * Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(State state) + { + return ((DyeColor)state.getValue(COLOR)).getMetadata(); + } + + protected IProperty[] getProperties() + { + return new IProperty[] {COLOR}; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(state.getValue(COLOR).getName() + "_glass").add().all(); + } +} diff --git a/common/src/main/java/common/block/artificial/BlockStainedGlassPane.java b/common/src/common/block/BlockStainedGlassPane.java similarity index 95% rename from common/src/main/java/common/block/artificial/BlockStainedGlassPane.java rename to common/src/common/block/BlockStainedGlassPane.java index 9c29581..254d120 100755 --- a/common/src/main/java/common/block/artificial/BlockStainedGlassPane.java +++ b/common/src/common/block/BlockStainedGlassPane.java @@ -1,12 +1,12 @@ -package common.block.artificial; +package common.block; import java.util.List; -import common.block.Material; import common.color.DyeColor; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.BlockLayer; import common.properties.IProperty; import common.properties.PropertyEnum; @@ -18,9 +18,9 @@ public class BlockStainedGlassPane extends BlockPane public BlockStainedGlassPane() { - super(Material.TRANSLUCENT, false); + super(Material.glass, false); this.setDefaultState(this.getBaseState().withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)).withProperty(COLOR, DyeColor.WHITE)); - this.setTab(CheatTab.BLOCKS); + this.setTab(CheatTab.tabBlocks); } /** diff --git a/common/src/main/java/common/block/artificial/BlockStairs.java b/common/src/common/block/BlockStairs.java similarity index 98% rename from common/src/main/java/common/block/artificial/BlockStairs.java rename to common/src/common/block/BlockStairs.java index 337f715..8c6f5d9 100755 --- a/common/src/main/java/common/block/artificial/BlockStairs.java +++ b/common/src/common/block/BlockStairs.java @@ -1,16 +1,15 @@ -package common.block.artificial; +package common.block; import java.util.Arrays; import java.util.List; -import common.block.Block; -import common.block.Material; import common.entity.Entity; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.BlockRegistry; import common.init.Blocks; import common.item.CheatTab; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -53,15 +52,15 @@ public class BlockStairs extends Block public BlockStairs(State modelState, String down, String up) { - super(modelState.getBlock().getMaterial()); + super(modelState.getBlock().material); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(HALF, BlockStairs.EnumHalf.BOTTOM).withProperty(SHAPE, BlockStairs.EnumShape.STRAIGHT)); this.modelBlock = modelState.getBlock(); this.modelState = modelState; - this.setHardness(this.modelBlock.getRawHardness()); - this.setResistance(this.modelBlock.getRawResistance() / 3.0F); + this.setHardness(this.modelBlock.blockHardness); + this.setResistance(this.modelBlock.blockResistance / 3.0F); this.setStepSound(this.modelBlock.sound); this.setLightOpacity(255); - this.setTab(modelState.getBlock().getMaterial() == Material.WOOD ? CheatTab.WOOD : CheatTab.BLOCKS); + this.setTab(modelState.getBlock().material == Material.wood ? CheatTab.tabWood : CheatTab.tabBlocks); this.downTex = down; this.upTex = up; } @@ -624,9 +623,9 @@ public class BlockStairs extends Block return this.modelBlock.isCollidable(); } - public boolean canCollideCheck(State state, boolean liquid) + public boolean canCollideCheck(State state, boolean hitIfLiquid) { - return this.modelBlock.canCollideCheck(state, liquid); + return this.modelBlock.canCollideCheck(state, hitIfLiquid); } public boolean canPlaceBlockAt(World worldIn, BlockPos pos) @@ -815,7 +814,7 @@ public class BlockStairs extends Block } public Model getModel(ModelProvider provider, String name, State state) { - String primary = this.modelBlock.getModel(provider, BlockRegistry.getNameFromBlock(this.modelBlock).toString(), this.modelState) + String primary = this.modelBlock.getModel(provider, BlockRegistry.REGISTRY.getNameForObject(this.modelBlock).toString(), this.modelState) .getPrimary(); return provider.getModel(primary) .stairs(state.getValue(HALF) == EnumHalf.TOP, state.getValue(SHAPE) == EnumShape.INNER_RIGHT || diff --git a/common/src/main/java/common/block/tile/BlockStandingSign.java b/common/src/common/block/BlockStandingSign.java similarity index 96% rename from common/src/main/java/common/block/tile/BlockStandingSign.java rename to common/src/common/block/BlockStandingSign.java index f6a616a..156dabe 100755 --- a/common/src/main/java/common/block/tile/BlockStandingSign.java +++ b/common/src/common/block/BlockStandingSign.java @@ -1,6 +1,5 @@ -package common.block.tile; +package common.block; -import common.block.Block; import common.properties.IProperty; import common.properties.PropertyInteger; import common.util.BlockPos; diff --git a/common/src/main/java/common/block/liquid/BlockStaticLiquid.java b/common/src/common/block/BlockStaticLiquid.java similarity index 88% rename from common/src/main/java/common/block/liquid/BlockStaticLiquid.java rename to common/src/common/block/BlockStaticLiquid.java index 85946e7..5b5b29f 100755 --- a/common/src/main/java/common/block/liquid/BlockStaticLiquid.java +++ b/common/src/common/block/BlockStaticLiquid.java @@ -1,12 +1,11 @@ -package common.block.liquid; +package common.block; -import common.block.Block; -import common.block.Material; import common.init.Blocks; +import common.init.Config; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.util.Facing; -import common.vars.Vars; import common.world.State; import common.world.World; import common.world.AWorldServer; @@ -15,7 +14,7 @@ public class BlockStaticLiquid extends BlockLiquid { public BlockStaticLiquid(Material materialIn, boolean opaque, int rate) { - super(materialIn, materialIn == Material.LAVA, opaque, rate); + super(materialIn, materialIn == Material.lava, opaque, rate); // this.setTickRandomly(false); // // if (materialIn == Material.lava) @@ -44,9 +43,9 @@ public class BlockStaticLiquid extends BlockLiquid public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Vars.lavaFire && this.material == Material.LAVA) + if (Config.lavaFire && this.material == Material.lava) { - if (Vars.fire) + if (Config.fire) { int i = rand.zrange(3); @@ -59,7 +58,7 @@ public class BlockStaticLiquid extends BlockLiquid blockpos = blockpos.add(rand.zrange(3) - 1, 1, rand.zrange(3) - 1); Block block = worldIn.getState(blockpos).getBlock(); - if (block == Blocks.air) + if (block.material == Material.air) { if (this.isSurroundingBlockFlammable(worldIn, blockpos)) { @@ -67,7 +66,7 @@ public class BlockStaticLiquid extends BlockLiquid return; } } - else if (block.getMaterial().blocksMovement()) + else if (block.material.blocksMovement()) { return; } diff --git a/common/src/main/java/common/block/foliage/BlockStem.java b/common/src/common/block/BlockStem.java similarity index 92% rename from common/src/main/java/common/block/foliage/BlockStem.java rename to common/src/common/block/BlockStem.java index e647e19..d42ae2b 100755 --- a/common/src/main/java/common/block/foliage/BlockStem.java +++ b/common/src/common/block/BlockStem.java @@ -1,13 +1,14 @@ -package common.block.foliage; +package common.block; import java.util.function.Predicate; -import common.block.Block; import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -17,7 +18,6 @@ import common.properties.PropertyInteger; import common.rng.Random; import common.util.BlockPos; import common.util.Facing; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.State; import common.world.World; @@ -77,11 +77,11 @@ public class BlockStem extends BlockBush implements IGrowable { super.updateTick(worldIn, pos, state, rand); - if (Vars.stemGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9) + if (Config.stemGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9) { float f = BlockCrops.getGrowthChance(this, worldIn, pos); - if (rand.chance((int)((float)(Vars.stemGrowth - 1) / f) + 1)) + if (rand.chance((int)((float)(Config.stemGrowth - 1) / f) + 1)) { int i = ((Integer)state.getValue(AGE)).intValue(); @@ -103,7 +103,7 @@ public class BlockStem extends BlockBush implements IGrowable pos = pos.offset(Facing.Plane.HORIZONTAL.random(rand)); Block block = worldIn.getState(pos.down()).getBlock(); - if (worldIn.getState(pos).getBlock() == Blocks.air && (block == Blocks.farmland || block == Blocks.dirt || block == Blocks.grass)) + if (worldIn.getState(pos).getBlock().material == Material.air && (block == Blocks.farmland || block == Blocks.dirt || block == Blocks.grass)) { worldIn.setState(pos, this.crop.getState()); } @@ -245,7 +245,7 @@ public class BlockStem extends BlockBush implements IGrowable if(state.getValue(FACING) == Facing.UP) { switch(state.getValue(AGE)) { case 0: - return provider.getModel(stem) + return provider.getModel(stem).noOcclude() .add(0, -1, 8, 16, 1, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 2).tint().noCull() .s().uv(16, 0, 0, 2).tint().noCull() @@ -253,7 +253,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 2).tint().noCull() .e().uv(16, 0, 0, 2).tint().noCull(); case 1: - return provider.getModel(stem) + return provider.getModel(stem).noOcclude() .add(0, -1, 8, 16, 3, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 4).tint().noCull() .s().uv(16, 0, 0, 4).tint().noCull() @@ -261,7 +261,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 4).tint().noCull() .e().uv(16, 0, 0, 4).tint().noCull(); case 2: - return provider.getModel(stem) + return provider.getModel(stem).noOcclude() .add(0, -1, 8, 16, 5, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 6).tint().noCull() .s().uv(16, 0, 0, 6).tint().noCull() @@ -269,7 +269,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 6).tint().noCull() .e().uv(16, 0, 0, 6).tint().noCull(); case 3: - return provider.getModel(stem) + return provider.getModel(stem).noOcclude() .add(0, -1, 8, 16, 7, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 8).tint().noCull() .s().uv(16, 0, 0, 8).tint().noCull() @@ -277,7 +277,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 8).tint().noCull() .e().uv(16, 0, 0, 8).tint().noCull(); case 4: - return provider.getModel(stem) + return provider.getModel(stem).noOcclude() .add(0, -1, 8, 16, 9, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 10).tint().noCull() .s().uv(16, 0, 0, 10).tint().noCull() @@ -285,7 +285,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 10).tint().noCull() .e().uv(16, 0, 0, 10).tint().noCull(); case 5: - return provider.getModel(stem) + return provider.getModel(stem).noOcclude() .add(0, -1, 8, 16, 11, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 12).tint().noCull() .s().uv(16, 0, 0, 12).tint().noCull() @@ -293,7 +293,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 12).tint().noCull() .e().uv(16, 0, 0, 12).tint().noCull(); case 6: - return provider.getModel(stem) + return provider.getModel(stem).noOcclude() .add(0, -1, 8, 16, 13, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 14).tint().noCull() .s().uv(16, 0, 0, 14).tint().noCull() @@ -302,7 +302,7 @@ public class BlockStem extends BlockBush implements IGrowable .e().uv(16, 0, 0, 14).tint().noCull(); case 7: default: - return provider.getModel(stem) + return provider.getModel(stem).noOcclude() .add(0, -1, 8, 16, 15, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 16).tint().noCull() .s().uv(16, 0, 0, 16).tint().noCull() @@ -312,7 +312,7 @@ public class BlockStem extends BlockBush implements IGrowable } } else { - return provider.getModel(stem) + return provider.getModel(stem).noOcclude() .add(0, -1, 8, 16, 7, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 8).tint().noCull() .s().uv(16, 0, 0, 8).tint().noCull() diff --git a/common/src/main/java/common/block/natural/BlockStone.java b/common/src/common/block/BlockStone.java similarity index 71% rename from common/src/main/java/common/block/natural/BlockStone.java rename to common/src/common/block/BlockStone.java index 7bb352a..bbfe84c 100755 --- a/common/src/main/java/common/block/natural/BlockStone.java +++ b/common/src/common/block/BlockStone.java @@ -1,18 +1,17 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; import common.init.Blocks; import common.init.ItemRegistry; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.rng.Random; import common.world.State; public class BlockStone extends Block { public BlockStone() { - super(Material.SOLID); - this.setTab(CheatTab.NATURE); + super(Material.rock); + this.setTab(CheatTab.tabNature); } public Item getItemDropped(State state, Random rand, int fortune) { diff --git a/common/src/main/java/common/block/artificial/BlockStoneBrick.java b/common/src/common/block/BlockStoneBrick.java similarity index 96% rename from common/src/main/java/common/block/artificial/BlockStoneBrick.java rename to common/src/common/block/BlockStoneBrick.java index f0a7508..0d38a04 100755 --- a/common/src/main/java/common/block/artificial/BlockStoneBrick.java +++ b/common/src/common/block/BlockStoneBrick.java @@ -1,12 +1,11 @@ -package common.block.artificial; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; @@ -24,9 +23,9 @@ public class BlockStoneBrick extends Block public BlockStoneBrick() { - super(Material.SOLID); + super(Material.rock); this.setDefaultState(this.getBaseState().withProperty(VARIANT, BlockStoneBrick.EnumType.DEFAULT)); - this.setTab(CheatTab.BLOCKS); + this.setTab(CheatTab.tabBlocks); } /** diff --git a/common/src/main/java/common/block/tech/BlockTNT.java b/common/src/common/block/BlockTNT.java similarity index 96% rename from common/src/main/java/common/block/tech/BlockTNT.java rename to common/src/common/block/BlockTNT.java index 45c5fbf..1dfc2a3 100755 --- a/common/src/main/java/common/block/tech/BlockTNT.java +++ b/common/src/common/block/BlockTNT.java @@ -1,9 +1,7 @@ -package common.block.tech; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.entity.Entity; import common.entity.item.EntityTnt; import common.entity.npc.EntityNPC; @@ -14,6 +12,7 @@ import common.init.SoundEvent; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; @@ -33,9 +32,9 @@ public class BlockTNT extends Block public BlockTNT() { - super(Material.EXPLOSIVE); + super(Material.tnt); this.setDefaultState(this.getBaseState().withProperty(EXPLODE, Boolean.valueOf(false))); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); } public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) @@ -112,7 +111,7 @@ public class BlockTNT extends Block } else // if (!playerIn.creative) { - --playerIn.getCurrentEquippedItem().size; + --playerIn.getCurrentEquippedItem().stackSize; } return true; diff --git a/common/src/main/java/common/block/foliage/BlockTallGrass.java b/common/src/common/block/BlockTallGrass.java similarity index 95% rename from common/src/main/java/common/block/foliage/BlockTallGrass.java rename to common/src/common/block/BlockTallGrass.java index be708d5..1e169ee 100755 --- a/common/src/main/java/common/block/foliage/BlockTallGrass.java +++ b/common/src/common/block/BlockTallGrass.java @@ -1,16 +1,17 @@ -package common.block.foliage; +package common.block; import java.util.List; -import common.block.Material; import common.color.Colorizer; import common.entity.npc.EntityNPC; import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.item.CheatTab; import common.item.Item; import common.item.ItemShears; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; @@ -19,7 +20,6 @@ import common.rng.Random; import common.tileentity.TileEntity; import common.util.BlockPos; import common.util.Identifyable; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.State; import common.world.World; @@ -31,7 +31,7 @@ public class BlockTallGrass extends BlockBush implements IGrowable public BlockTallGrass() { - super(Material.BUSH); + super(Material.vine); this.setDefaultState(this.getBaseState().withProperty(TYPE, BlockTallGrass.EnumType.DEAD_BUSH)); float f = 0.4F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.8F, 0.5F + f); @@ -40,7 +40,7 @@ public class BlockTallGrass extends BlockBush implements IGrowable public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Vars.tallgrassDry && worldIn.getTemperatureC(pos) >= 50.0f && state.getValue(TYPE) != EnumType.DEAD_BUSH) + if(Config.tallgrassDry && worldIn.getTemperatureC(pos) >= 50.0f && state.getValue(TYPE) != EnumType.DEAD_BUSH) { worldIn.setState(pos, state.getValue(TYPE) == EnumType.GRASS || worldIn.rand.chance(20) ? Blocks.air.getState() : this.getState().withProperty(TYPE, EnumType.DEAD_BUSH)); @@ -82,7 +82,7 @@ public class BlockTallGrass extends BlockBush implements IGrowable public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass) { - return worldIn.getBiomeGenForCoords(pos).getGrassColorAtPos(pos); + return Colorizer.getGrassColor(1.0f, 0.9f); } /** diff --git a/common/src/main/java/common/block/tech/BlockTianReactor.java b/common/src/common/block/BlockTianReactor.java similarity index 89% rename from common/src/main/java/common/block/tech/BlockTianReactor.java rename to common/src/common/block/BlockTianReactor.java index 9d3ae88..a073032 100755 --- a/common/src/main/java/common/block/tech/BlockTianReactor.java +++ b/common/src/common/block/BlockTianReactor.java @@ -1,4 +1,4 @@ -package common.block.tech; +package common.block; import java.util.Map; @@ -11,7 +11,7 @@ import common.world.State; import common.world.World; public class BlockTianReactor extends BlockMachine { - public TileEntity createNewTileEntity(World world) { + public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityTianReactor(); } diff --git a/common/src/main/java/common/block/foliage/BlockTianSoil.java b/common/src/common/block/BlockTianSoil.java similarity index 90% rename from common/src/main/java/common/block/foliage/BlockTianSoil.java rename to common/src/common/block/BlockTianSoil.java index bf7aa44..ac03fd9 100755 --- a/common/src/main/java/common/block/foliage/BlockTianSoil.java +++ b/common/src/common/block/BlockTianSoil.java @@ -1,10 +1,9 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; import common.init.Blocks; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; @@ -20,9 +19,9 @@ public class BlockTianSoil extends Block public BlockTianSoil() { - super(Material.SOLID); + super(Material.rock); this.setDefaultState(this.getBaseState().withProperty(SNOWY, Boolean.valueOf(false))); - this.setTab(CheatTab.NATURE); + this.setTab(CheatTab.tabNature); } public State getActualState(State state, IWorldAccess worldIn, BlockPos pos) diff --git a/common/src/main/java/common/block/tech/BlockTorch.java b/common/src/common/block/BlockTorch.java similarity index 95% rename from common/src/main/java/common/block/tech/BlockTorch.java rename to common/src/common/block/BlockTorch.java index 91d82e4..a249b7e 100755 --- a/common/src/main/java/common/block/tech/BlockTorch.java +++ b/common/src/common/block/BlockTorch.java @@ -1,14 +1,11 @@ -package common.block.tech; +package common.block; import java.util.function.Predicate; -import common.block.Block; -import common.block.BlockDirectional; -import common.block.Material; -import common.block.artificial.BlockFence; import common.entity.types.EntityLiving; import common.init.Blocks; import common.item.CheatTab; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -22,6 +19,7 @@ import common.util.BoundingBox; import common.util.Facing; import common.util.HitPosition; import common.util.Vec3; +import common.world.Chunk; import common.world.AWorldClient; import common.world.State; import common.world.World; @@ -38,18 +36,28 @@ public class BlockTorch extends Block }); private static boolean isBlockNormalCube(World world, BlockPos pos, boolean def) { - if(!World.isValid(pos) || (world.client && !world.isBlockLoaded(pos, false))) + if(!World.isValid(pos)) { return def; - Block block = world.getState(pos).getBlock(); - return block.getMaterial().isOpaque() && block.isFullCube(); + } + else { + Chunk chunk = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4); + + if(chunk.isEmpty()) { + return def; + } + else { + Block block = world.getState(pos).getBlock(); + return block.getMaterial().isOpaque() && block.isFullCube(); + } + } } public BlockTorch() { - super(Material.SMALL); + super(Material.circuits); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.UP)); // this.setTickRandomly(true); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); } public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) @@ -327,7 +335,7 @@ public class BlockTorch extends Block public Model getModel(ModelProvider provider, String name, State state) { if(state.getValue(FACING) == Facing.UP) - return provider.getModel(name) + return provider.getModel(name).noOcclude() .add(7, 0, 7, 9, 10, 9).noShade() .d().uv(7, 13, 9, 15).noCull() .u().uv(7, 6, 9, 8).noCull() @@ -338,7 +346,7 @@ public class BlockTorch extends Block .n().uv(0, 0, 16, 16).noCull() .s().uv(0, 0, 16, 16).noCull(); else - return provider.getModel(name) + return provider.getModel(name).noOcclude() .add(-1, 3.5f, 7, 1, 13.5f, 9).noShade().rotate(0, 3.5f, 8, Facing.Axis.Z, -22.5f, false) .d().uv(7, 13, 9, 15).noCull() .u().uv(7, 6, 9, 8).noCull() diff --git a/common/src/main/java/common/block/artificial/BlockTrapDoor.java b/common/src/common/block/BlockTrapDoor.java similarity index 95% rename from common/src/main/java/common/block/artificial/BlockTrapDoor.java rename to common/src/common/block/BlockTrapDoor.java index 3f970d6..c8fc2d7 100755 --- a/common/src/main/java/common/block/artificial/BlockTrapDoor.java +++ b/common/src/common/block/BlockTrapDoor.java @@ -1,11 +1,10 @@ -package common.block.artificial; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; import common.item.CheatTab; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -39,7 +38,7 @@ public class BlockTrapDoor extends Block float f = 0.5F; float f1 = 1.0F; this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - this.setTab(materialIn == Material.WOOD ? CheatTab.WOOD : CheatTab.TECHNOLOGY); + this.setTab(materialIn == Material.wood ? CheatTab.tabWood : CheatTab.tabTech); } /** @@ -131,7 +130,7 @@ public class BlockTrapDoor extends Block public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { - if (this.material == Material.SOLID) + if (this.material == Material.iron) { return true; } @@ -250,7 +249,7 @@ public class BlockTrapDoor extends Block private static boolean isValidSupportBlock(Block blockIn) { - return blockIn.getMaterial().isOpaque() && blockIn.isFullCube() || blockIn == Blocks.glass || blockIn == Blocks.stained_glass || blockIn == Blocks.glowstone || blockIn instanceof BlockSlab || blockIn instanceof BlockStairs; + return blockIn.material.isOpaque() && blockIn.isFullCube() || blockIn == Blocks.glass || blockIn == Blocks.stained_glass || blockIn == Blocks.glowstone || blockIn instanceof BlockSlab || blockIn instanceof BlockStairs; } public BlockLayer getBlockLayer() @@ -293,7 +292,7 @@ public class BlockTrapDoor extends Block } public boolean isMagnetic() { - return this.material == Material.SOLID; + return this.material == Material.iron; } public Transforms getTransform() { diff --git a/common/src/main/java/common/block/BlockTreasure.java b/common/src/common/block/BlockTreasure.java similarity index 55% rename from common/src/main/java/common/block/BlockTreasure.java rename to common/src/common/block/BlockTreasure.java index b5548e0..7f79172 100755 --- a/common/src/main/java/common/block/BlockTreasure.java +++ b/common/src/common/block/BlockTreasure.java @@ -1,8 +1,10 @@ package common.block; +import common.material.Material; + public class BlockTreasure extends Block { - public BlockTreasure(Material material) { - super(material); + public BlockTreasure(Material materialIn) { + super(materialIn); } public boolean isXrayVisible() { diff --git a/common/src/main/java/common/block/tech/BlockTripWire.java b/common/src/common/block/BlockTripWire.java similarity index 98% rename from common/src/main/java/common/block/tech/BlockTripWire.java rename to common/src/common/block/BlockTripWire.java index 8ed734d..e02e941 100755 --- a/common/src/main/java/common/block/tech/BlockTripWire.java +++ b/common/src/common/block/BlockTripWire.java @@ -1,15 +1,14 @@ -package common.block.tech; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; import common.entity.Entity; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.init.Items; import common.item.Item; import common.item.ItemShears; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -39,7 +38,7 @@ public class BlockTripWire extends Block public BlockTripWire() { - super(Material.SMALL); + super(Material.circuits); this.setDefaultState(this.getBaseState().withProperty(POWERED, Boolean.valueOf(false)).withProperty(SUSPENDED, Boolean.valueOf(false)).withProperty(ATTACHED, Boolean.valueOf(false)).withProperty(DISARMED, Boolean.valueOf(false)).withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false))); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.15625F, 1.0F); // this.setTickRandomly(true); @@ -307,7 +306,7 @@ public class BlockTripWire extends Block private static Model getModelDetached(boolean n, boolean s, boolean w, boolean e, int sides) { if(sides == 1) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -319,7 +318,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -335,7 +334,7 @@ public class BlockTripWire extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -350,7 +349,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(sides == 3) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -371,7 +370,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).noCull() .rotate(!w ? ModelRotation.X0_Y0 : (!e ? ModelRotation.X0_Y180 : (!s ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -400,7 +399,7 @@ public class BlockTripWire extends Block private static Model getModelAttached(boolean n, boolean s, boolean w, boolean e, int sides) { if(sides == 1) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -412,7 +411,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -428,7 +427,7 @@ public class BlockTripWire extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -443,7 +442,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(sides == 3) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -464,7 +463,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).noCull() .rotate(!w ? ModelRotation.X0_Y0 : (!e ? ModelRotation.X0_Y180 : (!s ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -493,7 +492,7 @@ public class BlockTripWire extends Block private static Model getModelDetSuspend(boolean n, boolean s, boolean w, boolean e, int sides) { if(sides == 1) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -505,7 +504,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -521,7 +520,7 @@ public class BlockTripWire extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -536,7 +535,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(sides == 3) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -557,7 +556,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).noCull() .rotate(!w ? ModelRotation.X0_Y0 : (!e ? ModelRotation.X0_Y180 : (!s ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -586,7 +585,7 @@ public class BlockTripWire extends Block private static Model getModelAttSuspend(boolean n, boolean s, boolean w, boolean e, int sides) { if(sides == 1) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -598,7 +597,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -614,7 +613,7 @@ public class BlockTripWire extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -629,7 +628,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(sides == 3) - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -650,7 +649,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).noCull() .rotate(!w ? ModelRotation.X0_Y0 : (!e ? ModelRotation.X0_Y180 : (!s ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else - return ModelProvider.getModelProvider().getModel("trip_wire") + return ModelProvider.getModelProvider().getModel("trip_wire").noOcclude() .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() diff --git a/common/src/main/java/common/block/tech/BlockTripWireHook.java b/common/src/common/block/BlockTripWireHook.java similarity index 99% rename from common/src/main/java/common/block/tech/BlockTripWireHook.java rename to common/src/common/block/BlockTripWireHook.java index 95cb387..778de6c 100755 --- a/common/src/main/java/common/block/tech/BlockTripWireHook.java +++ b/common/src/common/block/BlockTripWireHook.java @@ -1,12 +1,11 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.types.EntityLiving; import common.init.Blocks; import common.init.SoundEvent; import common.item.CheatTab; import common.item.ItemStack; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -32,9 +31,9 @@ public class BlockTripWireHook extends Block public BlockTripWireHook() { - super(Material.SMALL); + super(Material.circuits); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(POWERED, Boolean.valueOf(false)).withProperty(ATTACHED, Boolean.valueOf(false)).withProperty(SUSPENDED, Boolean.valueOf(false))); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); // this.setTickRandomly(true); } diff --git a/common/src/main/java/common/block/foliage/BlockVine.java b/common/src/common/block/BlockVine.java similarity index 96% rename from common/src/main/java/common/block/foliage/BlockVine.java rename to common/src/common/block/BlockVine.java index 5e0b4e7..968a396 100755 --- a/common/src/main/java/common/block/foliage/BlockVine.java +++ b/common/src/common/block/BlockVine.java @@ -1,15 +1,15 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; import common.color.Colorizer; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.init.Config; import common.item.CheatTab; import common.item.Item; import common.item.ItemShears; import common.item.ItemStack; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -21,7 +21,6 @@ import common.tileentity.TileEntity; import common.util.BlockPos; import common.util.BoundingBox; import common.util.Facing; -import common.vars.Vars; import common.world.IWorldAccess; import common.world.State; import common.world.World; @@ -38,10 +37,10 @@ public class BlockVine extends Block public BlockVine() { - super(Material.BUSH); + super(Material.vine); this.setDefaultState(this.getBaseState().withProperty(UP, Boolean.valueOf(false)).withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false))); this.setTickRandomly(); - this.setTab(CheatTab.PLANTS); + this.setTab(CheatTab.tabPlants); } /** @@ -178,7 +177,7 @@ public class BlockVine extends Block private boolean canPlaceOn(Block blockIn) { - return blockIn.isFullCube() && blockIn.getMaterial().blocksMovement(); + return blockIn.isFullCube() && blockIn.material.blocksMovement(); } private boolean recheckGrownSides(World worldIn, BlockPos pos, State state) @@ -227,7 +226,7 @@ public class BlockVine extends Block public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass) { - return worldIn.getBiomeGenForCoords(pos).getFoliageColorAtPos(pos); + return Colorizer.getFoliageColor(1.0f, 0.9f); } /** @@ -244,14 +243,14 @@ public class BlockVine extends Block public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Vars.vineDry && worldIn.getTemperatureC(pos) >= 50.0f) + if(Config.vineDry && worldIn.getTemperatureC(pos) >= 50.0f) { worldIn.setBlockToAir(pos); return; } // if (!worldIn.client) // { - if (Vars.vineGrowth > 0 && worldIn.rand.chance(Vars.vineGrowth)) + if (Config.vineGrowth > 0 && worldIn.rand.chance(Config.vineGrowth)) { int i = 4; int j = 5; @@ -281,7 +280,7 @@ public class BlockVine extends Block Facing enumfacing1 = Facing.random(rand); BlockPos blockpos1 = pos.up(); - if (enumfacing1 == Facing.UP && pos.getY() < World.MAX_SIZE_Y - 1 && worldIn.isAirBlock(blockpos1)) + if (enumfacing1 == Facing.UP && pos.getY() < 511 && worldIn.isAirBlock(blockpos1)) { if (!flag) { @@ -308,7 +307,7 @@ public class BlockVine extends Block BlockPos blockpos3 = pos.offset(enumfacing1); Block block1 = worldIn.getState(blockpos3).getBlock(); - if (block1 == Blocks.air) + if (block1.material == Material.air) { Facing enumfacing2 = enumfacing1.rotateY(); Facing enumfacing4 = enumfacing1.rotateYCCW(); @@ -338,7 +337,7 @@ public class BlockVine extends Block worldIn.setState(blockpos3, this.getState(), 2); } } - else if (block1.getMaterial().isOpaque() && block1.isFullCube()) + else if (block1.material.isOpaque() && block1.isFullCube()) { worldIn.setState(pos, state.withProperty(getPropertyFor(enumfacing1), Boolean.valueOf(true)), 2); } @@ -352,7 +351,7 @@ public class BlockVine extends Block State iblockstate = worldIn.getState(blockpos2); Block block = iblockstate.getBlock(); - if (block == Blocks.air) + if (block.material == Material.air) { State iblockstate1 = state; @@ -521,7 +520,7 @@ public class BlockVine extends Block } public Model getModel(ModelProvider provider, String name, State state) { - Model model = provider.getModel("vine"); + Model model = provider.getModel("vine").noOcclude(); if(state.getValue(UP)) model.add(0, 15.2f, 0, 16, 15.2f, 16).noShade() .d().uv(0, 0, 16, 16).tint().noCull() diff --git a/common/src/main/java/common/block/artificial/BlockWall.java b/common/src/common/block/BlockWall.java similarity index 94% rename from common/src/main/java/common/block/artificial/BlockWall.java rename to common/src/common/block/BlockWall.java index 703eed4..41ad2bf 100755 --- a/common/src/main/java/common/block/artificial/BlockWall.java +++ b/common/src/common/block/BlockWall.java @@ -1,13 +1,11 @@ -package common.block.artificial; +package common.block; import java.util.List; -import common.block.Block; -import common.block.Material; -import common.init.Blocks; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -34,12 +32,12 @@ public class BlockWall extends Block public BlockWall(Block modelBlock) { - super(modelBlock.getMaterial()); + super(modelBlock.material); this.setDefaultState(this.getBaseState().withProperty(UP, Boolean.valueOf(false)).withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)).withProperty(VARIANT, BlockWall.EnumType.NORMAL)); - this.setHardness(modelBlock.getRawHardness()); - this.setResistance(modelBlock.getRawResistance() / 3.0F); + this.setHardness(modelBlock.blockHardness); + this.setResistance(modelBlock.blockResistance / 3.0F); this.setStepSound(modelBlock.sound); - this.setTab(CheatTab.BLOCKS); + this.setTab(CheatTab.tabBlocks); } // /** @@ -126,7 +124,7 @@ public class BlockWall extends Block public boolean canConnectTo(IBlockAccess worldIn, BlockPos pos) { Block block = worldIn.getState(pos).getBlock(); - return (block != this && !(block instanceof BlockFenceGate) ? (block.getMaterial().isOpaque() && block.isFullCube() ? block.getMaterial() != Material.SOFT : false) : true); + return (block != this && !(block instanceof BlockFenceGate) ? (block.material.isOpaque() && block.isFullCube() ? block.material != Material.gourd : false) : true); } /** @@ -176,7 +174,7 @@ public class BlockWall extends Block */ public State getActualState(State state, IWorldAccess worldIn, BlockPos pos) { - return state.withProperty(UP, Boolean.valueOf(worldIn.getState(pos.up()).getBlock() != Blocks.air)).withProperty(NORTH, Boolean.valueOf(this.canConnectTo(worldIn, pos.north()))).withProperty(EAST, Boolean.valueOf(this.canConnectTo(worldIn, pos.east()))).withProperty(SOUTH, Boolean.valueOf(this.canConnectTo(worldIn, pos.south()))).withProperty(WEST, Boolean.valueOf(this.canConnectTo(worldIn, pos.west()))); + return state.withProperty(UP, Boolean.valueOf(worldIn.getState(pos.up()).getBlock().getMaterial() != Material.air)).withProperty(NORTH, Boolean.valueOf(this.canConnectTo(worldIn, pos.north()))).withProperty(EAST, Boolean.valueOf(this.canConnectTo(worldIn, pos.east()))).withProperty(SOUTH, Boolean.valueOf(this.canConnectTo(worldIn, pos.south()))).withProperty(WEST, Boolean.valueOf(this.canConnectTo(worldIn, pos.west()))); } protected IProperty[] getProperties() diff --git a/common/src/main/java/common/block/tile/BlockWallSign.java b/common/src/common/block/BlockWallSign.java similarity index 97% rename from common/src/main/java/common/block/tile/BlockWallSign.java rename to common/src/common/block/BlockWallSign.java index b390bd6..29da816 100755 --- a/common/src/main/java/common/block/tile/BlockWallSign.java +++ b/common/src/common/block/BlockWallSign.java @@ -1,6 +1,5 @@ -package common.block.tile; +package common.block; -import common.block.Block; import common.properties.IProperty; import common.properties.PropertyDirection; import common.util.BlockPos; diff --git a/common/src/main/java/common/block/tech/BlockWarpChest.java b/common/src/common/block/BlockWarpChest.java similarity index 97% rename from common/src/main/java/common/block/tech/BlockWarpChest.java rename to common/src/common/block/BlockWarpChest.java index e1cfa54..f3aab50 100755 --- a/common/src/main/java/common/block/tech/BlockWarpChest.java +++ b/common/src/common/block/BlockWarpChest.java @@ -1,7 +1,5 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; @@ -10,6 +8,7 @@ import common.inventory.InventoryWarpChest; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ModelRotation; @@ -29,9 +28,9 @@ public class BlockWarpChest extends Block public BlockWarpChest() { - super(Material.SOLID); + super(Material.rock); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); } diff --git a/common/src/main/java/common/block/foliage/BlockWart.java b/common/src/common/block/BlockWart.java similarity index 93% rename from common/src/main/java/common/block/foliage/BlockWart.java rename to common/src/common/block/BlockWart.java index 30771d8..3937dbe 100755 --- a/common/src/main/java/common/block/foliage/BlockWart.java +++ b/common/src/common/block/BlockWart.java @@ -1,19 +1,18 @@ -package common.block.foliage; +package common.block; -import common.block.Block; -import common.block.Material; import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.item.CheatTab; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.properties.IProperty; import common.properties.PropertyInteger; import common.rng.Random; import common.util.BlockPos; -import common.vars.Vars; import common.world.State; import common.world.World; import common.world.AWorldServer; @@ -24,7 +23,7 @@ public class BlockWart extends BlockBush public BlockWart() { - super(Material.PLANT); + super(Material.plants); this.setDefaultState(this.getBaseState().withProperty(AGE, Integer.valueOf(0))); this.setTickRandomly(); float f = 0.5F; @@ -47,10 +46,10 @@ public class BlockWart extends BlockBush public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Vars.wartGrowth > 0) { + if(Config.wartGrowth > 0) { int i = ((Integer)state.getValue(AGE)).intValue(); - if (i < 3 && rand.chance(Vars.wartGrowth)) + if (i < 3 && rand.chance(Config.wartGrowth)) { state = state.withProperty(AGE, Integer.valueOf(i + 1)); worldIn.setState(pos, state, 2); diff --git a/common/src/main/java/common/block/natural/BlockWeb.java b/common/src/common/block/BlockWeb.java similarity index 90% rename from common/src/main/java/common/block/natural/BlockWeb.java rename to common/src/common/block/BlockWeb.java index 4dbaf5d..9778a73 100755 --- a/common/src/main/java/common/block/natural/BlockWeb.java +++ b/common/src/common/block/BlockWeb.java @@ -1,11 +1,10 @@ -package common.block.natural; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.Entity; import common.init.Items; import common.item.CheatTab; import common.item.Item; +import common.material.Material; import common.model.BlockLayer; import common.model.Model; import common.model.ModelProvider; @@ -19,8 +18,8 @@ public class BlockWeb extends Block { public BlockWeb() { - super(Material.FLUFF); - this.setTab(CheatTab.DECORATION); + super(Material.web); + this.setTab(CheatTab.tabDeco); } /** diff --git a/common/src/main/java/common/block/tech/BlockWorkbench.java b/common/src/common/block/BlockWorkbench.java similarity index 74% rename from common/src/main/java/common/block/tech/BlockWorkbench.java rename to common/src/common/block/BlockWorkbench.java index 5e803da..3ac24c8 100755 --- a/common/src/main/java/common/block/tech/BlockWorkbench.java +++ b/common/src/common/block/BlockWorkbench.java @@ -1,13 +1,11 @@ -package common.block.tech; +package common.block; -import common.block.Block; -import common.block.Material; import common.entity.npc.EntityNPC; -import common.init.BlockRegistry; import common.inventory.Container; import common.inventory.ContainerWorkbench; import common.inventory.InventoryPlayer; import common.item.CheatTab; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.tileentity.IInteractionObject; @@ -18,18 +16,11 @@ import common.world.World; public class BlockWorkbench extends Block { - private final int size; - - public BlockWorkbench(int size) + public BlockWorkbench() { - super(Material.WOOD); - this.setTab(CheatTab.TECHNOLOGY); - this.size = size; + super(Material.wood); + this.setTab(CheatTab.tabTech); } - - public int getSize() { - return this.size; - } public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { @@ -39,7 +30,7 @@ public class BlockWorkbench extends Block } else { - playerIn.displayGui(new BlockWorkbench.InterfaceCraftingTable(worldIn, pos, this)); + playerIn.displayGui(new BlockWorkbench.InterfaceCraftingTable(worldIn, pos)); // playerIn.triggerAchievement(StatRegistry.craftingTableStat); return true; } @@ -54,28 +45,36 @@ public class BlockWorkbench extends Block { private final World world; private final BlockPos position; - private final BlockWorkbench block; - public InterfaceCraftingTable(World worldIn, BlockPos pos, BlockWorkbench block) + public InterfaceCraftingTable(World worldIn, BlockPos pos) { this.world = worldIn; this.position = pos; - this.block = block; } - + + public String getName() + { + return null; + } + + public boolean hasCustomName() + { + return false; + } + public String getCommandName() { - return this.block.getDisplay(); + return "Werkbank"; } public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) { - return new ContainerWorkbench(playerInventory, this.world, this.position, this.block); + return new ContainerWorkbench(playerInventory, this.world, this.position); } public String getGuiID() { - return BlockRegistry.getNameFromBlock(this.block); + return "crafting_table"; } } } diff --git a/common/src/main/java/common/block/foliage/IGrowable.java b/common/src/common/block/IGrowable.java similarity index 93% rename from common/src/main/java/common/block/foliage/IGrowable.java rename to common/src/common/block/IGrowable.java index 87ca9b8..9bb72c7 100755 --- a/common/src/main/java/common/block/foliage/IGrowable.java +++ b/common/src/common/block/IGrowable.java @@ -1,4 +1,4 @@ -package common.block.foliage; +package common.block; import common.rng.Random; import common.util.BlockPos; diff --git a/common/src/common/block/ITileEntityProvider.java b/common/src/common/block/ITileEntityProvider.java new file mode 100755 index 0000000..f4628a7 --- /dev/null +++ b/common/src/common/block/ITileEntityProvider.java @@ -0,0 +1,12 @@ +package common.block; + +import common.tileentity.TileEntity; +import common.world.World; + +public interface ITileEntityProvider +{ + /** + * Returns a new instance of a block's tile entity class. Called on placing the block. + */ + TileEntity createNewTileEntity(World worldIn, int meta); +} diff --git a/common/src/main/java/common/block/foliage/LeavesType.java b/common/src/common/block/LeavesType.java similarity index 93% rename from common/src/main/java/common/block/foliage/LeavesType.java rename to common/src/common/block/LeavesType.java index 0a918bf..25b730d 100755 --- a/common/src/main/java/common/block/foliage/LeavesType.java +++ b/common/src/common/block/LeavesType.java @@ -1,4 +1,4 @@ -package common.block.foliage; +package common.block; import common.util.Identifyable; diff --git a/common/src/main/java/common/block/SoundType.java b/common/src/common/block/SoundType.java similarity index 100% rename from common/src/main/java/common/block/SoundType.java rename to common/src/common/block/SoundType.java diff --git a/common/src/main/java/common/collect/AbstractBiMap.java b/common/src/common/collect/AbstractBiMap.java similarity index 100% rename from common/src/main/java/common/collect/AbstractBiMap.java rename to common/src/common/collect/AbstractBiMap.java diff --git a/common/src/main/java/common/collect/AbstractIndexedListIterator.java b/common/src/common/collect/AbstractIndexedListIterator.java similarity index 100% rename from common/src/main/java/common/collect/AbstractIndexedListIterator.java rename to common/src/common/collect/AbstractIndexedListIterator.java diff --git a/common/src/main/java/common/collect/AbstractIterator.java b/common/src/common/collect/AbstractIterator.java similarity index 100% rename from common/src/main/java/common/collect/AbstractIterator.java rename to common/src/common/collect/AbstractIterator.java diff --git a/common/src/main/java/common/collect/AbstractMapEntry.java b/common/src/common/collect/AbstractMapEntry.java similarity index 100% rename from common/src/main/java/common/collect/AbstractMapEntry.java rename to common/src/common/collect/AbstractMapEntry.java diff --git a/common/src/main/java/common/collect/AbstractTable.java b/common/src/common/collect/AbstractTable.java similarity index 100% rename from common/src/main/java/common/collect/AbstractTable.java rename to common/src/common/collect/AbstractTable.java diff --git a/common/src/main/java/common/collect/BiMap.java b/common/src/common/collect/BiMap.java similarity index 100% rename from common/src/main/java/common/collect/BiMap.java rename to common/src/common/collect/BiMap.java diff --git a/common/src/main/java/common/collect/CollectPreconditions.java b/common/src/common/collect/CollectPreconditions.java similarity index 100% rename from common/src/main/java/common/collect/CollectPreconditions.java rename to common/src/common/collect/CollectPreconditions.java diff --git a/common/src/main/java/common/collect/DenseImmutableTable.java b/common/src/common/collect/DenseImmutableTable.java similarity index 100% rename from common/src/main/java/common/collect/DenseImmutableTable.java rename to common/src/common/collect/DenseImmutableTable.java diff --git a/common/src/main/java/common/collect/EmptyImmutableMap.java b/common/src/common/collect/EmptyImmutableMap.java similarity index 100% rename from common/src/main/java/common/collect/EmptyImmutableMap.java rename to common/src/common/collect/EmptyImmutableMap.java diff --git a/common/src/main/java/common/collect/EmptyImmutableSet.java b/common/src/common/collect/EmptyImmutableSet.java similarity index 100% rename from common/src/main/java/common/collect/EmptyImmutableSet.java rename to common/src/common/collect/EmptyImmutableSet.java diff --git a/common/src/main/java/common/collect/Filter.java b/common/src/common/collect/Filter.java similarity index 99% rename from common/src/main/java/common/collect/Filter.java rename to common/src/common/collect/Filter.java index c403295..a9f4fd1 100644 --- a/common/src/main/java/common/collect/Filter.java +++ b/common/src/common/collect/Filter.java @@ -183,12 +183,12 @@ public final class Filter { @Override public boolean removeAll(final Collection collection) { - return Iterables.removeIf(unfiltered, and(predicate, in((Collection)collection))); + return Iterables.removeIf(unfiltered, and(predicate, in(collection))); } @Override public boolean retainAll(final Collection collection) { - return Iterables.removeIf(unfiltered, and(predicate, not(in((Collection)collection)))); + return Iterables.removeIf(unfiltered, and(predicate, not(in(collection)))); } @Override diff --git a/common/src/main/java/common/collect/ForwardingCollection.java b/common/src/common/collect/ForwardingCollection.java similarity index 100% rename from common/src/main/java/common/collect/ForwardingCollection.java rename to common/src/common/collect/ForwardingCollection.java diff --git a/common/src/main/java/common/collect/ForwardingMap.java b/common/src/common/collect/ForwardingMap.java similarity index 100% rename from common/src/main/java/common/collect/ForwardingMap.java rename to common/src/common/collect/ForwardingMap.java diff --git a/common/src/main/java/common/collect/ForwardingMapEntry.java b/common/src/common/collect/ForwardingMapEntry.java similarity index 100% rename from common/src/main/java/common/collect/ForwardingMapEntry.java rename to common/src/common/collect/ForwardingMapEntry.java diff --git a/common/src/main/java/common/collect/ForwardingObject.java b/common/src/common/collect/ForwardingObject.java similarity index 100% rename from common/src/main/java/common/collect/ForwardingObject.java rename to common/src/common/collect/ForwardingObject.java diff --git a/common/src/main/java/common/collect/ForwardingSet.java b/common/src/common/collect/ForwardingSet.java similarity index 100% rename from common/src/main/java/common/collect/ForwardingSet.java rename to common/src/common/collect/ForwardingSet.java diff --git a/common/src/main/java/common/collect/HashBiMap.java b/common/src/common/collect/HashBiMap.java similarity index 100% rename from common/src/main/java/common/collect/HashBiMap.java rename to common/src/common/collect/HashBiMap.java diff --git a/common/src/main/java/common/collect/Hashing.java b/common/src/common/collect/Hashing.java similarity index 100% rename from common/src/main/java/common/collect/Hashing.java rename to common/src/common/collect/Hashing.java diff --git a/common/src/main/java/common/collect/ImmutableAsList.java b/common/src/common/collect/ImmutableAsList.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableAsList.java rename to common/src/common/collect/ImmutableAsList.java diff --git a/common/src/main/java/common/collect/ImmutableCollection.java b/common/src/common/collect/ImmutableCollection.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableCollection.java rename to common/src/common/collect/ImmutableCollection.java diff --git a/common/src/main/java/common/collect/ImmutableEntry.java b/common/src/common/collect/ImmutableEntry.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableEntry.java rename to common/src/common/collect/ImmutableEntry.java diff --git a/common/src/main/java/common/collect/ImmutableEnumMap.java b/common/src/common/collect/ImmutableEnumMap.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableEnumMap.java rename to common/src/common/collect/ImmutableEnumMap.java diff --git a/common/src/main/java/common/collect/ImmutableEnumSet.java b/common/src/common/collect/ImmutableEnumSet.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableEnumSet.java rename to common/src/common/collect/ImmutableEnumSet.java diff --git a/common/src/main/java/common/collect/ImmutableList.java b/common/src/common/collect/ImmutableList.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableList.java rename to common/src/common/collect/ImmutableList.java diff --git a/common/src/main/java/common/collect/ImmutableMap.java b/common/src/common/collect/ImmutableMap.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableMap.java rename to common/src/common/collect/ImmutableMap.java diff --git a/common/src/main/java/common/collect/ImmutableMapEntry.java b/common/src/common/collect/ImmutableMapEntry.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableMapEntry.java rename to common/src/common/collect/ImmutableMapEntry.java diff --git a/common/src/main/java/common/collect/ImmutableMapEntrySet.java b/common/src/common/collect/ImmutableMapEntrySet.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableMapEntrySet.java rename to common/src/common/collect/ImmutableMapEntrySet.java diff --git a/common/src/main/java/common/collect/ImmutableMapKeySet.java b/common/src/common/collect/ImmutableMapKeySet.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableMapKeySet.java rename to common/src/common/collect/ImmutableMapKeySet.java diff --git a/common/src/main/java/common/collect/ImmutableMapValues.java b/common/src/common/collect/ImmutableMapValues.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableMapValues.java rename to common/src/common/collect/ImmutableMapValues.java diff --git a/common/src/main/java/common/collect/ImmutableSet.java b/common/src/common/collect/ImmutableSet.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableSet.java rename to common/src/common/collect/ImmutableSet.java diff --git a/common/src/main/java/common/collect/ImmutableTable.java b/common/src/common/collect/ImmutableTable.java similarity index 100% rename from common/src/main/java/common/collect/ImmutableTable.java rename to common/src/common/collect/ImmutableTable.java diff --git a/common/src/main/java/common/collect/Iterables.java b/common/src/common/collect/Iterables.java similarity index 90% rename from common/src/main/java/common/collect/Iterables.java rename to common/src/common/collect/Iterables.java index 06dce11..4a71710 100644 --- a/common/src/main/java/common/collect/Iterables.java +++ b/common/src/common/collect/Iterables.java @@ -45,6 +45,104 @@ import java.util.function.Predicate; public final class Iterables { private Iterables() {} + /** Returns an unmodifiable view of {@code iterable}. */ +// public static Iterable unmodifiableIterable( +// final Iterable iterable) { +// checkNotNull(iterable); +// if (iterable instanceof UnmodifiableIterable || +// iterable instanceof ImmutableCollection) { +// return iterable; +// } +// return new UnmodifiableIterable(iterable); +// } + + /** + * Simply returns its argument. + * + * @deprecated no need to use this + * @since 10.0 + */ +// @Deprecated public static Iterable unmodifiableIterable( +// ImmutableCollection iterable) { +// return checkNotNull(iterable); +// } + +// private static final class UnmodifiableIterable extends FluentIterable { +// private final Iterable iterable; +// +// private UnmodifiableIterable(Iterable iterable) { +// this.iterable = iterable; +// } +// +// @Override +// public Iterator iterator() { +// return Iterators.unmodifiableIterator(iterable.iterator()); +// } +// +// @Override +// public String toString() { +// return iterable.toString(); +// } +// // no equals and hashCode; it would break the contract! +// } + + /** + * Returns the number of elements in {@code iterable}. + */ +// public static int size(Iterable iterable) { +// return (iterable instanceof Collection) +// ? ((Collection) iterable).size() +// : Iterators.size(iterable.iterator()); +// } + + /** + * Returns {@code true} if {@code iterable} contains any object for which {@code equals(element)} + * is true. + */ +// public static boolean contains(Iterable iterable, Object element) { +// if (iterable instanceof Collection) { +// Collection collection = (Collection) iterable; +// return Filter.safeContains(collection, element); +// } +// return Iterators.contains(iterable.iterator(), element); +// } + + /** + * Removes, from an iterable, every element that belongs to the provided + * collection. + * + *

This method calls {@link Collection#removeAll} if {@code iterable} is a + * collection, and {@link Iterators#removeAll} otherwise. + * + * @param removeFrom the iterable to (potentially) remove elements from + * @param elementsToRemove the elements to remove + * @return {@code true} if any element was removed from {@code iterable} + */ +// public static boolean removeAll( +// Iterable removeFrom, Collection elementsToRemove) { +// return (removeFrom instanceof Collection) +// ? ((Collection) removeFrom).removeAll(checkNotNull(elementsToRemove)) +// : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); +// } + + /** + * Removes, from an iterable, every element that does not belong to the + * provided collection. + * + *

This method calls {@link Collection#retainAll} if {@code iterable} is a + * collection, and {@link Iterators#retainAll} otherwise. + * + * @param removeFrom the iterable to (potentially) remove elements from + * @param elementsToRetain the elements to retain + * @return {@code true} if any element was removed from {@code iterable} + */ +// public static boolean retainAll( +// Iterable removeFrom, Collection elementsToRetain) { +// return (removeFrom instanceof Collection) +// ? ((Collection) removeFrom).retainAll(checkNotNull(elementsToRetain)) +// : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); +// } + /** * Removes, from an iterable, every element that satisfies the provided * predicate. diff --git a/common/src/main/java/common/collect/Iterators.java b/common/src/common/collect/Iterators.java similarity index 80% rename from common/src/main/java/common/collect/Iterators.java rename to common/src/common/collect/Iterators.java index c92d91c..350c9ef 100644 --- a/common/src/main/java/common/collect/Iterators.java +++ b/common/src/common/collect/Iterators.java @@ -148,6 +148,17 @@ public final class Iterators { }; } + /** + * Simply returns its argument. + * + * @deprecated no need to use this + * @since 10.0 + */ +// @Deprecated public static UnmodifiableIterator unmodifiableIterator( +// UnmodifiableIterator iterator) { +// return checkNotNull(iterator); +// } + /** * Returns the number of elements remaining in {@code iterator}. The iterator * will be left exhausted: its {@code hasNext()} method will return @@ -1029,6 +1040,253 @@ public final class Iterators { }; } + /** + * Returns an iterator containing only {@code value}. + * + *

The {@link Iterable} equivalent of this method is {@link + * Collections#singleton}. + */ +// public static UnmodifiableIterator singletonIterator( +// final T value) { +// return new UnmodifiableIterator() { +// boolean done; +// @Override +// public boolean hasNext() { +// return !done; +// } +// @Override +// public T next() { +// if (done) { +// throw new NoSuchElementException(); +// } +// done = true; +// return value; +// } +// }; +// } + + /** + * Adapts an {@code Enumeration} to the {@code Iterator} interface. + * + *

This method has no equivalent in {@link Iterables} because viewing an + * {@code Enumeration} as an {@code Iterable} is impossible. However, the + * contents can be copied into a collection using {@link + * Collections#list}. + */ +// public static UnmodifiableIterator forEnumeration( +// final Enumeration enumeration) { +// checkNotNull(enumeration); +// return new UnmodifiableIterator() { +// @Override +// public boolean hasNext() { +// return enumeration.hasMoreElements(); +// } +// @Override +// public T next() { +// return enumeration.nextElement(); +// } +// }; +// } + + /** + * Adapts an {@code Iterator} to the {@code Enumeration} interface. + * + *

The {@code Iterable} equivalent of this method is either {@link + * Collections#enumeration} (if you have a {@link Collection}), or + * {@code Iterators.asEnumeration(collection.iterator())}. + */ +// public static Enumeration asEnumeration(final Iterator iterator) { +// checkNotNull(iterator); +// return new Enumeration() { +// @Override +// public boolean hasMoreElements() { +// return iterator.hasNext(); +// } +// @Override +// public T nextElement() { +// return iterator.next(); +// } +// }; +// } + + /** + * Implementation of PeekingIterator that avoids peeking unless necessary. + */ +// private static class PeekingImpl implements PeekingIterator { +// +// private final Iterator iterator; +// private boolean hasPeeked; +// private E peekedElement; +// +// public PeekingImpl(Iterator iterator) { +// this.iterator = checkNotNull(iterator); +// } +// +// @Override +// public boolean hasNext() { +// return hasPeeked || iterator.hasNext(); +// } +// +// @Override +// public E next() { +// if (!hasPeeked) { +// return iterator.next(); +// } +// E result = peekedElement; +// hasPeeked = false; +// peekedElement = null; +// return result; +// } +// +// @Override +// public void remove() { +// checkState(!hasPeeked, "Can't remove after you've peeked at next"); +// iterator.remove(); +// } +// +// @Override +// public E peek() { +// if (!hasPeeked) { +// peekedElement = iterator.next(); +// hasPeeked = true; +// } +// return peekedElement; +// } +// } + + /** + * Returns a {@code PeekingIterator} backed by the given iterator. + * + *

Calls to the {@code peek} method with no intervening calls to {@code + * next} do not affect the iteration, and hence return the same object each + * time. A subsequent call to {@code next} is guaranteed to return the same + * object again. For example:

   {@code
+   *
+   *   PeekingIterator peekingIterator =
+   *       Iterators.peekingIterator(Iterators.forArray("a", "b"));
+   *   String a1 = peekingIterator.peek(); // returns "a"
+   *   String a2 = peekingIterator.peek(); // also returns "a"
+   *   String a3 = peekingIterator.next(); // also returns "a"}
+ * + *

Any structural changes to the underlying iteration (aside from those + * performed by the iterator's own {@link PeekingIterator#remove()} method) + * will leave the iterator in an undefined state. + * + *

The returned iterator does not support removal after peeking, as + * explained by {@link PeekingIterator#remove()}. + * + *

Note: If the given iterator is already a {@code PeekingIterator}, + * it might be returned to the caller, although this is neither + * guaranteed to occur nor required to be consistent. For example, this + * method might choose to pass through recognized implementations of + * {@code PeekingIterator} when the behavior of the implementation is + * known to meet the contract guaranteed by this method. + * + *

There is no {@link Iterable} equivalent to this method, so use this + * method to wrap each individual iterator as it is generated. + * + * @param iterator the backing iterator. The {@link PeekingIterator} assumes + * ownership of this iterator, so users should cease making direct calls + * to it after calling this method. + * @return a peeking iterator backed by that iterator. Apart from the + * additional {@link PeekingIterator#peek()} method, this iterator behaves + * exactly the same as {@code iterator}. + */ +// public static PeekingIterator peekingIterator( +// Iterator iterator) { +// if (iterator instanceof PeekingImpl) { +// // Safe to cast to because PeekingImpl only uses T +// // covariantly (and cannot be subclassed to add non-covariant uses). +// +// PeekingImpl peeking = (PeekingImpl) iterator; +// return peeking; +// } +// return new PeekingImpl(iterator); +// } + + /** + * Simply returns its argument. + * + * @deprecated no need to use this + * @since 10.0 + */ +// @Deprecated public static PeekingIterator peekingIterator( +// PeekingIterator iterator) { +// return checkNotNull(iterator); +// } + + /** + * Returns an iterator over the merged contents of all given + * {@code iterators}, traversing every element of the input iterators. + * Equivalent entries will not be de-duplicated. + * + *

Callers must ensure that the source {@code iterators} are in + * non-descending order as this method does not sort its input. + * + *

For any equivalent elements across all {@code iterators}, it is + * undefined which element is returned first. + * + * @since 11.0 + */ +// @Beta +// public static UnmodifiableIterator mergeSorted( +// Iterable> iterators, +// Comparator comparator) { +// checkNotNull(iterators, "iterators"); +// checkNotNull(comparator, "comparator"); +// +// return new MergingIterator(iterators, comparator); +// } + + /** + * An iterator that performs a lazy N-way merge, calculating the next value + * each time the iterator is polled. This amortizes the sorting cost over the + * iteration and requires less memory than sorting all elements at once. + * + *

Retrieving a single element takes approximately O(log(M)) time, where M + * is the number of iterators. (Retrieving all elements takes approximately + * O(N*log(M)) time, where N is the total number of elements.) + */ +// private static class MergingIterator extends UnmodifiableIterator { +// final Queue> queue; +// +// public MergingIterator(Iterable> iterators, +// final Comparator itemComparator) { +// // A comparator that's used by the heap, allowing the heap +// // to be sorted based on the top of each iterator. +// Comparator> heapComparator = +// new Comparator>() { +// @Override +// public int compare(PeekingIterator o1, PeekingIterator o2) { +// return itemComparator.compare(o1.peek(), o2.peek()); +// } +// }; +// +// queue = new PriorityQueue>(2, heapComparator); +// +// for (Iterator iterator : iterators) { +// if (iterator.hasNext()) { +// queue.add(Iterators.peekingIterator(iterator)); +// } +// } +// } +// +// @Override +// public boolean hasNext() { +// return !queue.isEmpty(); +// } +// +// @Override +// public T next() { +// PeekingIterator nextIter = queue.remove(); +// T next = nextIter.next(); +// if (nextIter.hasNext()) { +// queue.add(nextIter); +// } +// return next; +// } +// } + /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ diff --git a/common/src/main/java/common/collect/Lists.java b/common/src/common/collect/Lists.java similarity index 100% rename from common/src/main/java/common/collect/Lists.java rename to common/src/common/collect/Lists.java diff --git a/common/src/main/java/common/collect/Maps.java b/common/src/common/collect/Maps.java similarity index 100% rename from common/src/main/java/common/collect/Maps.java rename to common/src/common/collect/Maps.java diff --git a/common/src/main/java/common/collect/ObjectArrays.java b/common/src/common/collect/ObjectArrays.java similarity index 100% rename from common/src/main/java/common/collect/ObjectArrays.java rename to common/src/common/collect/ObjectArrays.java diff --git a/common/src/main/java/common/collect/Preconditions.java b/common/src/common/collect/Preconditions.java similarity index 100% rename from common/src/main/java/common/collect/Preconditions.java rename to common/src/common/collect/Preconditions.java diff --git a/common/src/main/java/common/collect/RegularImmutableAsList.java b/common/src/common/collect/RegularImmutableAsList.java similarity index 100% rename from common/src/main/java/common/collect/RegularImmutableAsList.java rename to common/src/common/collect/RegularImmutableAsList.java diff --git a/common/src/main/java/common/collect/RegularImmutableList.java b/common/src/common/collect/RegularImmutableList.java similarity index 100% rename from common/src/main/java/common/collect/RegularImmutableList.java rename to common/src/common/collect/RegularImmutableList.java diff --git a/common/src/main/java/common/collect/RegularImmutableMap.java b/common/src/common/collect/RegularImmutableMap.java similarity index 100% rename from common/src/main/java/common/collect/RegularImmutableMap.java rename to common/src/common/collect/RegularImmutableMap.java diff --git a/common/src/main/java/common/collect/RegularImmutableSet.java b/common/src/common/collect/RegularImmutableSet.java similarity index 100% rename from common/src/main/java/common/collect/RegularImmutableSet.java rename to common/src/common/collect/RegularImmutableSet.java diff --git a/common/src/main/java/common/collect/RegularImmutableTable.java b/common/src/common/collect/RegularImmutableTable.java similarity index 100% rename from common/src/main/java/common/collect/RegularImmutableTable.java rename to common/src/common/collect/RegularImmutableTable.java diff --git a/common/src/main/java/common/collect/Sets.java b/common/src/common/collect/Sets.java similarity index 100% rename from common/src/main/java/common/collect/Sets.java rename to common/src/common/collect/Sets.java diff --git a/common/src/main/java/common/collect/SparseImmutableTable.java b/common/src/common/collect/SparseImmutableTable.java similarity index 100% rename from common/src/main/java/common/collect/SparseImmutableTable.java rename to common/src/common/collect/SparseImmutableTable.java diff --git a/common/src/main/java/common/collect/StandardTable.java b/common/src/common/collect/StandardTable.java similarity index 100% rename from common/src/main/java/common/collect/StandardTable.java rename to common/src/common/collect/StandardTable.java diff --git a/common/src/main/java/common/collect/Table.java b/common/src/common/collect/Table.java similarity index 100% rename from common/src/main/java/common/collect/Table.java rename to common/src/common/collect/Table.java diff --git a/common/src/main/java/common/collect/TransformedIterator.java b/common/src/common/collect/TransformedIterator.java similarity index 100% rename from common/src/main/java/common/collect/TransformedIterator.java rename to common/src/common/collect/TransformedIterator.java diff --git a/common/src/main/java/common/collect/UnmodifiableIterator.java b/common/src/common/collect/UnmodifiableIterator.java similarity index 100% rename from common/src/main/java/common/collect/UnmodifiableIterator.java rename to common/src/common/collect/UnmodifiableIterator.java diff --git a/common/src/main/java/common/collect/UnmodifiableListIterator.java b/common/src/common/collect/UnmodifiableListIterator.java similarity index 100% rename from common/src/main/java/common/collect/UnmodifiableListIterator.java rename to common/src/common/collect/UnmodifiableListIterator.java diff --git a/common/src/main/java/common/color/Colorizer.java b/common/src/common/color/Colorizer.java similarity index 82% rename from common/src/main/java/common/color/Colorizer.java rename to common/src/common/color/Colorizer.java index dcae2c9..9e58742 100755 --- a/common/src/main/java/common/color/Colorizer.java +++ b/common/src/common/color/Colorizer.java @@ -1,6 +1,5 @@ package common.color; -import common.biome.Biome; import common.util.BlockPos; import common.world.IWorldAccess; @@ -8,22 +7,22 @@ public enum Colorizer { NONE(0xffffff), BASIC(0x37b500), PINE(0x3f993f), BIRCH(0x68a723); private interface ColorResolver { - int getColorAtPos(Biome biome, BlockPos pos); + int getColorAtPos(BlockPos pos); } private static final ColorResolver GRASS_COLOR = new ColorResolver() { - public int getColorAtPos(Biome biome, BlockPos pos) { - return biome.getGrassColorAtPos(pos); + public int getColorAtPos(BlockPos pos) { + return Colorizer.getGrassColor(1.0f, 0.9f); } }; private static final ColorResolver FOLIAGE_COLOR = new ColorResolver() { - public int getColorAtPos(Biome biome, BlockPos pos) { - return biome.getFoliageColorAtPos(pos); + public int getColorAtPos(BlockPos pos) { + return Colorizer.getFoliageColor(1.0f, 0.9f); } }; private static final ColorResolver WATER_COLOR_MULTIPLIER = new ColorResolver() { - public int getColorAtPos(Biome biome, BlockPos pos) { - return biome.waterColor; + public int getColorAtPos(BlockPos pos) { + return 0xffffff; } }; private static final int[] GRASS = new int[65536]; @@ -60,7 +59,7 @@ public enum Colorizer { int b = 0; for(BlockPos.MutableBlockPos loc : BlockPos.getAllInBoxMutable(pos.add(-1, 0, -1), pos.add(1, 0, 1))) { - int c = resolver.getColorAtPos(access.getBiomeGenForCoords(loc), loc); + int c = resolver.getColorAtPos(loc); r += (c & 16711680) >> 16; g += (c & 65280) >> 8; b += c & 255; diff --git a/common/src/main/java/common/color/DyeColor.java b/common/src/common/color/DyeColor.java similarity index 100% rename from common/src/main/java/common/color/DyeColor.java rename to common/src/common/color/DyeColor.java diff --git a/common/src/main/java/common/color/TextColor.java b/common/src/common/color/TextColor.java similarity index 100% rename from common/src/main/java/common/color/TextColor.java rename to common/src/common/color/TextColor.java diff --git a/common/src/main/java/common/dimension/Area.java b/common/src/common/dimension/Area.java similarity index 100% rename from common/src/main/java/common/dimension/Area.java rename to common/src/common/dimension/Area.java diff --git a/common/src/main/java/common/dimension/DimType.java b/common/src/common/dimension/DimType.java similarity index 100% rename from common/src/main/java/common/dimension/DimType.java rename to common/src/common/dimension/DimType.java diff --git a/common/src/main/java/common/dimension/Dimension.java b/common/src/common/dimension/Dimension.java similarity index 64% rename from common/src/main/java/common/dimension/Dimension.java rename to common/src/common/dimension/Dimension.java index 42b720c..bcb9137 100755 --- a/common/src/main/java/common/dimension/Dimension.java +++ b/common/src/common/dimension/Dimension.java @@ -2,21 +2,28 @@ package common.dimension; import java.util.List; import java.util.Map; +import java.util.Set; + import common.biome.Biome; import common.biome.IBiome; -import common.block.Block; -import common.block.foliage.LeavesType; +import common.block.LeavesType; import common.collect.Lists; import common.collect.Maps; +import common.collect.Sets; import common.init.BlockRegistry; import common.init.Blocks; import common.init.MetalType; import common.init.UniverseRegistry; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; +import common.nbt.NBTTagString; import common.util.ExtMath; import common.util.Vec3; import common.world.State; import common.world.Weather; +import common.worldgen.FeatureLake; +import common.worldgen.FeatureLiquid; +import common.worldgen.FeatureOre; public abstract class Dimension extends Nameable implements Comparable { public class GeneratorSettings { @@ -38,6 +45,59 @@ public abstract class Dimension extends Nameable implements Comparable SAFE_CHARS = Sets.newHashSet(); + +// private static final FeatureOres[] DEFAULT_ORES; +// +// static { +// List ores = Lists.newArrayList(); +// OreRegistry.populateDefault(ores); +// DEFAULT_ORES = new FeatureOres[ores.size()]; +// for(int z = 0; z < DEFAULT_ORES.length; z++) { +// DEFAULT_ORES[z] = ores.get(z).createGenerator(); +// } +// } private final int id; private final String name; @@ -155,8 +226,8 @@ public abstract class Dimension extends Nameable implements Comparable ores = Lists.newArrayList(); - private final List lakes = Lists.newArrayList(); - private final List liquids = Lists.newArrayList(); + private final List ores = Lists.newArrayList(); + private final List lakes = Lists.newArrayList(); + private final List liquids = Lists.newArrayList(); private long seed = 0L; - public static void writeState(TagObject tag, String name, String dname, State state) { - if(state == null) - return; - tag.setString(name, BlockRegistry.getNameFromBlock(state.getBlock())); - if(state != state.getBlock().getState()) - tag.setByte(dname, (byte)state.getBlock().getMetaFromState(state)); - } - - public static void writeState(TagObject tag, String name, State state) { - writeState(tag, name, name + "Data", state); - } - - public static void writeState(TagObject tag, State state) { - writeState(tag, "Block", "Data", state); - } - - public static State readState(TagObject tag, String name, String dname, State def) { - if(!tag.hasString(name)) - return def; - Block block = BlockRegistry.getRegisteredBlock(tag.getString(name)); - if(tag.hasByte(dname)) { - byte data = tag.getByte(dname); - return data < 0 || data >= 16 ? block.getState() : block.getStateFromMeta(data); + static { + final String safe = "0123456789abcdefghijklmnopqrstuvwxyz_"; + for(int z = 0; z < safe.length(); z++) { + SAFE_CHARS.add(safe.charAt(z)); } - return block.getState(); } - public static State readState(TagObject tag, String name, State def) { - return readState(tag, name, name + "Data", def); + private static String getSafeFilename(String name, String fallback) { + if(name.length() < 1 || name.length() > 32) + return fallback; + for(int z = 0; z < name.length(); z++) { + if(!SAFE_CHARS.contains(name.charAt(z))) { + return fallback; + } + } + return name; } - - public static State readState(TagObject tag, State def) { - return readState(tag, "Block", "Data", def); - } - + public Dimension(int id, String name) { this.id = id; this.name = name; @@ -268,7 +324,11 @@ public abstract class Dimension extends Nameable implements Comparable= UniverseRegistry.MORE_DIM_ID) { - this.seaLevel = tag.getInt("SeaLevel"); - this.filler = readState(tag, "FillerBlock", Blocks.stone.getState()); - this.liquid = readState(tag, "LiquidBlock", Blocks.water.getState()); - } - } if(generator) { + this.seed = tag.getLong("Seed"); if(all || this.id >= UniverseRegistry.MORE_DIM_ID) { this.noiseGen.coordinateScale = tag.getFloat("CoordScale"); this.noiseGen.heightScale = tag.getFloat("HeightScale"); @@ -925,117 +992,120 @@ public abstract class Dimension extends Nameable implements Comparable list = tag.getList("Ores"); - for(int z = 0; z < list.size(); z++) { - TagObject gen = list.get(z); - this.ores.add(new Ore(readState(gen, Blocks.iron_ore.getState()), - gen.getInt("Count"), gen.getInt("Add"), gen.getInt("Size"), - gen.getInt("MinC"), gen.getInt("MaxS"), gen.getBool("Distrib"))); + if(tag.hasKey("Ores", 9)) { + NBTTagList list = tag.getTagList("Ores", 10); + for(int z = 0; z < list.tagCount(); z++) { + NBTTagCompound gen = list.getCompoundTagAt(z); + this.ores.add(new FeatureOre(BlockRegistry.getFromIdName(gen.getString("Block"), Blocks.iron_ore.getState()), + gen.getInteger("Count"), gen.getInteger("Add"), gen.getInteger("Size"), + gen.getInteger("MinC"), gen.getInteger("MaxS"), gen.getBoolean("Distrib"))); } } this.lakes.clear(); - if(tag.hasList("Lakes")) { - List list = tag.getList("Lakes"); - for(int z = 0; z < list.size(); z++) { - TagObject gen = list.get(z); - this.lakes.add(new Lake( - readState(gen, Blocks.water.getState()), - readState(gen, "Filler", null), readState(gen, "Top", null), - gen.getInt("Chance"), gen.getInt("Min"), gen.getInt("Max"), gen.getBool("Ratiod"))); + if(tag.hasKey("Lakes", 9)) { + NBTTagList list = tag.getTagList("Lakes", 10); + for(int z = 0; z < list.tagCount(); z++) { + NBTTagCompound gen = list.getCompoundTagAt(z); + this.lakes.add(new FeatureLake( + BlockRegistry.getFromIdName(gen.getString("Block"), Blocks.iron_ore.getState()), + gen.hasKey("Filler", 8) ? BlockRegistry.getFromIdName(gen.getString("Filler"), null) : null, + gen.hasKey("Top", 8) ? BlockRegistry.getFromIdName(gen.getString("Top"), null) : null, + gen.getInteger("Chance"), gen.getInteger("Min"), gen.getInteger("Max"), gen.getBoolean("Ratiod"))); } } this.liquids.clear(); - if(tag.hasList("Liquids")) { - List list = tag.getList("Liquids"); - for(int z = 0; z < list.size(); z++) { - TagObject gen = list.get(z); - this.liquids.add(new Liquid( - readState(gen, Blocks.flowing_water.getState()), - gen.getInt("Chance"), gen.getInt("Min"), gen.getInt("Max"), gen.getBool("Lower"))); + if(tag.hasKey("Liquids", 9)) { + NBTTagList list = tag.getTagList("Liquids", 10); + for(int z = 0; z < list.tagCount(); z++) { + NBTTagCompound gen = list.getCompoundTagAt(z); + this.liquids.add(new FeatureLiquid( + BlockRegistry.getFromIdName(gen.getString("Block"), Blocks.iron_ore.getState()), + gen.getInteger("Chance"), gen.getInteger("Min"), gen.getInteger("Max"), gen.getBoolean("Lower"))); } } - this.populated = !tag.hasBool("NoPopulation") || !tag.getBool("NoPopulation"); + this.populated = !tag.hasKey("NoPopulation", 1) || !tag.getBoolean("NoPopulation"); } } else { this.fullName = tag.getString("FullName"); - this.readTags(tag); + this.readNbt(tag); } -// this.customName = tag.hasString("CustomName") ? tag.getString("CustomName") : null; +// this.readNbt(tag); +// this.customName = tag.hasKey("CustomName", 8) ? tag.getString("CustomName") : null; if(all || !generator || this.id >= UniverseRegistry.MORE_DIM_ID) { - this.denseFog = tag.getBool("DenseFog"); - this.timeQualifier = tag.getInt("ImperialTime"); - this.brightness = tag.getInt("Brightness"); - this.skyColor = tag.getInt("SkyColor"); - this.fogColor = tag.getInt("FogColor"); - this.cloudColor = tag.getInt("CloudColor"); + this.denseFog = tag.getBoolean("DenseFog"); + this.timeQualifier = tag.getInteger("ImperialTime"); + this.brightness = tag.getInteger("Brightness"); + this.skyColor = tag.getInteger("SkyColor"); + this.fogColor = tag.getInteger("FogColor"); + this.cloudColor = tag.getInteger("CloudColor"); this.gravity = tag.getFloat("Gravity"); this.temperature = tag.getFloat("Temperature"); this.orbitOffset = tag.getFloat("OrbitOffset"); @@ -1096,27 +1168,27 @@ public abstract class Dimension extends Nameable implements Comparable= UniverseRegistry.MORE_DIM_ID) ? this.toTags() : new TagObject(); + private final NBTTagCompound toNbt(boolean generator, boolean all) { + NBTTagCompound tag = (all || !generator || this.id >= UniverseRegistry.MORE_DIM_ID) ? this.toNbt() : new NBTTagCompound(); if(this == Space.INSTANCE) { - if(generator || partialGen) + if(generator) tag.setLong("Seed", this.seed); return tag; } - if(generator || partialGen) { - tag.setLong("Seed", this.seed); - if(partialGen || all || this.id >= UniverseRegistry.MORE_DIM_ID) { - tag.setInt("SeaLevel", this.seaLevel); - writeState(tag, "FillerBlock", this.filler); - writeState(tag, "LiquidBlock", this.liquid); - } - } if(generator) { + tag.setLong("Seed", this.seed); if(all || this.id >= UniverseRegistry.MORE_DIM_ID) { tag.setFloat("CoordScale", this.noiseGen.coordinateScale); tag.setFloat("HeightScale", this.noiseGen.heightScale); @@ -1167,144 +1228,146 @@ public abstract class Dimension extends Nameable implements Comparable list = Lists.newArrayList(); - for(Ore gen : this.ores) { - TagObject ore = new TagObject(); - writeState(ore, gen.state()); - ore.setBool("Distrib", gen.dist()); - ore.setInt("Size", gen.size()); - ore.setInt("Count", gen.count()); - ore.setInt("Add", gen.more()); - ore.setInt("MinC", gen.min()); - ore.setInt("MaxS", gen.max()); - list.add(ore); + NBTTagList list = new NBTTagList(); + for(FeatureOre gen : this.ores) { + NBTTagCompound ore = new NBTTagCompound(); + ore.setString("Block", BlockRegistry.toIdName(gen.state)); + ore.setBoolean("Distrib", gen.dist); + ore.setInteger("Size", gen.size); + ore.setInteger("Count", gen.count); + ore.setInteger("Add", gen.more); + ore.setInteger("MinC", gen.min); + ore.setInteger("MaxS", gen.max); + list.appendTag(ore); } - tag.setList("Ores", list); + tag.setTag("Ores", list); } if(!this.lakes.isEmpty()) { - List list = Lists.newArrayList(); - for(Lake gen : this.lakes) { - TagObject lake = new TagObject(); - writeState(lake, gen.state()); - writeState(lake, "Filler", gen.filler()); - writeState(lake, "Top", gen.top()); - lake.setBool("Ratiod", gen.ratiod()); - lake.setInt("Chance", gen.chance()); - lake.setInt("Min", gen.minHeight()); - lake.setInt("Max", gen.maxHeight()); - list.add(lake); + NBTTagList list = new NBTTagList(); + for(FeatureLake gen : this.lakes) { + NBTTagCompound lake = new NBTTagCompound(); + lake.setString("Block", BlockRegistry.toIdName(gen.state)); + if(gen.filler != null) + lake.setString("Filler", BlockRegistry.toIdName(gen.filler)); + if(gen.top != null) + lake.setString("Top", BlockRegistry.toIdName(gen.top)); + lake.setBoolean("Ratiod", gen.ratiod); + lake.setInteger("Chance", gen.chance); + lake.setInteger("Min", gen.minHeight); + lake.setInteger("Max", gen.maxHeight); + list.appendTag(lake); } - tag.setList("Lakes", list); + tag.setTag("Lakes", list); } if(!this.liquids.isEmpty()) { - List list = Lists.newArrayList(); - for(Liquid gen : this.liquids) { - TagObject liquid = new TagObject(); - writeState(liquid, gen.state()); - liquid.setBool("Lower", gen.lower()); - liquid.setInt("Chance", gen.chance()); - liquid.setInt("Min", gen.minHeight()); - liquid.setInt("Max", gen.maxHeight()); - list.add(liquid); + NBTTagList list = new NBTTagList(); + for(FeatureLiquid gen : this.liquids) { + NBTTagCompound liquid = new NBTTagCompound(); + liquid.setString("Block", BlockRegistry.toIdName(gen.state)); + liquid.setBoolean("Lower", gen.lower); + liquid.setInteger("Chance", gen.chance); + liquid.setInteger("Min", gen.minHeight); + liquid.setInteger("Max", gen.maxHeight); + list.appendTag(liquid); } - tag.setList("Liquids", list); + tag.setTag("Liquids", list); } if(!this.populated) - tag.setBool("NoPopulation", true); + tag.setBoolean("NoPopulation", true); } } else { tag.setString("FullName", this.getFormattedName(true)); - this.writeTags(tag); + this.writeNbt(tag); } +// this.writeNbt(tag); // if(this.customName != null) // tag.setString("CustomName", this.customName); if(all || !generator || this.id >= UniverseRegistry.MORE_DIM_ID) { - tag.setBool("DenseFog", this.denseFog); - tag.setInt("ImperialTime", this.timeQualifier); - tag.setInt("Brightness", this.brightness); - tag.setInt("SkyColor", this.skyColor); - tag.setInt("FogColor", this.fogColor); - tag.setInt("CloudColor", this.cloudColor); + tag.setBoolean("DenseFog", this.denseFog); + tag.setInteger("ImperialTime", this.timeQualifier); + tag.setInteger("Brightness", this.brightness); + tag.setInteger("SkyColor", this.skyColor); + tag.setInteger("FogColor", this.fogColor); + tag.setInteger("CloudColor", this.cloudColor); tag.setFloat("Gravity", this.gravity); tag.setFloat("Temperature", this.temperature); tag.setFloat("OrbitOffset", this.orbitOffset); @@ -1313,42 +1376,42 @@ public abstract class Dimension extends Nameable implements Comparable getOres() { + public List getOres() { return this.ores; } - public List getLakes() { + public List getLakes() { return this.lakes; } - public List getLiquids() { + public List getLiquids() { return this.liquids; } } diff --git a/common/src/main/java/common/dimension/Domain.java b/common/src/common/dimension/Domain.java similarity index 100% rename from common/src/main/java/common/dimension/Domain.java rename to common/src/common/dimension/Domain.java diff --git a/common/src/main/java/common/dimension/Galaxy.java b/common/src/common/dimension/Galaxy.java similarity index 100% rename from common/src/main/java/common/dimension/Galaxy.java rename to common/src/common/dimension/Galaxy.java diff --git a/common/src/main/java/common/dimension/Moon.java b/common/src/common/dimension/Moon.java similarity index 100% rename from common/src/main/java/common/dimension/Moon.java rename to common/src/common/dimension/Moon.java diff --git a/common/src/main/java/common/dimension/Nameable.java b/common/src/common/dimension/Nameable.java similarity index 59% rename from common/src/main/java/common/dimension/Nameable.java rename to common/src/common/dimension/Nameable.java index 17cd47a..922630d 100755 --- a/common/src/main/java/common/dimension/Nameable.java +++ b/common/src/common/dimension/Nameable.java @@ -1,6 +1,6 @@ package common.dimension; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; public abstract class Nameable { protected String customName = null; @@ -13,11 +13,11 @@ public abstract class Nameable { this.customName = name; } - public void readTags(TagObject tag) { - this.customName = tag.hasString("CustomName") ? tag.getString("CustomName") : null; + public void readNbt(NBTTagCompound tag) { + this.customName = tag.hasKey("CustomName", 8) ? tag.getString("CustomName") : null; } - public void writeTags(TagObject tag) { + public void writeNbt(NBTTagCompound tag) { if(this.customName != null) tag.setString("CustomName", this.customName); } @@ -32,4 +32,12 @@ public abstract class Nameable { String.format(this.getNameIdentifier(), this.customName)) : String.format(this.getNameIdentifier(), this.getIdentifier()); } + +// public final Text getNameComponent() { +// return this.customName != null && !this.customName.isEmpty() +// ? (this.customName.startsWith("'") && this.customName.endsWith("'") && this.customName.length() > 2 +// ? new Text(this.customName.substring(1, this.customName.length() - 1)) : +// new Text(this.getNameIdentifier(), this.customName)) : +// new Text(this.getNameIdentifier(), this.getIdentifier()); +// } } diff --git a/common/src/main/java/common/dimension/Planet.java b/common/src/common/dimension/Planet.java similarity index 100% rename from common/src/main/java/common/dimension/Planet.java rename to common/src/common/dimension/Planet.java diff --git a/common/src/main/java/common/dimension/Sector.java b/common/src/common/dimension/Sector.java similarity index 100% rename from common/src/main/java/common/dimension/Sector.java rename to common/src/common/dimension/Sector.java diff --git a/common/src/main/java/common/dimension/Semi.java b/common/src/common/dimension/Semi.java similarity index 100% rename from common/src/main/java/common/dimension/Semi.java rename to common/src/common/dimension/Semi.java diff --git a/common/src/main/java/common/dimension/Space.java b/common/src/common/dimension/Space.java similarity index 100% rename from common/src/main/java/common/dimension/Space.java rename to common/src/common/dimension/Space.java diff --git a/common/src/main/java/common/dimension/Star.java b/common/src/common/dimension/Star.java similarity index 100% rename from common/src/main/java/common/dimension/Star.java rename to common/src/common/dimension/Star.java diff --git a/common/src/main/java/common/dispenser/BehaviorDefaultDispenseItem.java b/common/src/common/dispenser/BehaviorDefaultDispenseItem.java similarity index 98% rename from common/src/main/java/common/dispenser/BehaviorDefaultDispenseItem.java rename to common/src/common/dispenser/BehaviorDefaultDispenseItem.java index e8c65a5..e4aea80 100755 --- a/common/src/main/java/common/dispenser/BehaviorDefaultDispenseItem.java +++ b/common/src/common/dispenser/BehaviorDefaultDispenseItem.java @@ -1,6 +1,6 @@ package common.dispenser; -import common.block.tech.BlockDispenser; +import common.block.BlockDispenser; import common.entity.item.EntityItem; import common.item.ItemStack; import common.util.Facing; diff --git a/common/src/main/java/common/dispenser/BehaviorProjectileDispense.java b/common/src/common/dispenser/BehaviorProjectileDispense.java similarity index 97% rename from common/src/main/java/common/dispenser/BehaviorProjectileDispense.java rename to common/src/common/dispenser/BehaviorProjectileDispense.java index 96d6eb1..dc4dbaa 100755 --- a/common/src/main/java/common/dispenser/BehaviorProjectileDispense.java +++ b/common/src/common/dispenser/BehaviorProjectileDispense.java @@ -1,6 +1,6 @@ package common.dispenser; -import common.block.tech.BlockDispenser; +import common.block.BlockDispenser; import common.entity.Entity; import common.entity.types.IProjectile; import common.item.ItemStack; diff --git a/common/src/main/java/common/dispenser/IBehaviorDispenseItem.java b/common/src/common/dispenser/IBehaviorDispenseItem.java similarity index 100% rename from common/src/main/java/common/dispenser/IBehaviorDispenseItem.java rename to common/src/common/dispenser/IBehaviorDispenseItem.java diff --git a/common/src/main/java/common/dispenser/IBlockSource.java b/common/src/common/dispenser/IBlockSource.java similarity index 72% rename from common/src/main/java/common/dispenser/IBlockSource.java rename to common/src/common/dispenser/IBlockSource.java index 21cb62e..c56f8c3 100755 --- a/common/src/main/java/common/dispenser/IBlockSource.java +++ b/common/src/common/dispenser/IBlockSource.java @@ -2,17 +2,14 @@ package common.dispenser; import common.tileentity.TileEntity; import common.util.BlockPos; -import common.world.World; -public interface IBlockSource extends IPosition +public interface IBlockSource extends ILocatableSource { double getX(); double getY(); double getZ(); - - World getWorld(); BlockPos getBlockPos(); diff --git a/common/src/common/dispenser/ILocatableSource.java b/common/src/common/dispenser/ILocatableSource.java new file mode 100755 index 0000000..b0875cb --- /dev/null +++ b/common/src/common/dispenser/ILocatableSource.java @@ -0,0 +1,5 @@ +package common.dispenser; + +public interface ILocatableSource extends ILocation +{ +} diff --git a/common/src/common/dispenser/ILocation.java b/common/src/common/dispenser/ILocation.java new file mode 100755 index 0000000..e4eb4ae --- /dev/null +++ b/common/src/common/dispenser/ILocation.java @@ -0,0 +1,8 @@ +package common.dispenser; + +import common.world.World; + +public interface ILocation extends IPosition +{ + World getWorld(); +} diff --git a/common/src/main/java/common/dispenser/IPosition.java b/common/src/common/dispenser/IPosition.java similarity index 100% rename from common/src/main/java/common/dispenser/IPosition.java rename to common/src/common/dispenser/IPosition.java diff --git a/common/src/common/dispenser/PositionImpl.java b/common/src/common/dispenser/PositionImpl.java new file mode 100755 index 0000000..9150126 --- /dev/null +++ b/common/src/common/dispenser/PositionImpl.java @@ -0,0 +1,30 @@ +package common.dispenser; + +public class PositionImpl implements IPosition +{ + protected final double x; + protected final double y; + protected final double z; + + public PositionImpl(double xCoord, double yCoord, double zCoord) + { + this.x = xCoord; + this.y = yCoord; + this.z = zCoord; + } + + public double getX() + { + return this.x; + } + + public double getY() + { + return this.y; + } + + public double getZ() + { + return this.z; + } +} diff --git a/common/src/common/enchantment/Enchantment.java b/common/src/common/enchantment/Enchantment.java new file mode 100755 index 0000000..a83fe87 --- /dev/null +++ b/common/src/common/enchantment/Enchantment.java @@ -0,0 +1,221 @@ +package common.enchantment; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import common.collect.Lists; +import common.collect.Maps; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.item.ItemStack; + +public abstract class Enchantment +{ + private static final String[] LEVELS = new String[] {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"}; + private static final Enchantment[] enchantmentsList = new Enchantment[256]; + public static final Enchantment[] enchantmentsBookList; + private static final Map locationEnchantments = Maps.newHashMap(); + + public static final Enchantment protection = new EnchantmentProtection(0, "protection", 10, 0); + public static final Enchantment fireProtection = new EnchantmentProtection(1, "fire_protection", 5, 1); + public static final Enchantment featherFalling = new EnchantmentProtection(2, "feather_falling", 5, 2); + public static final Enchantment blastProtection = new EnchantmentProtection(3, "blast_protection", 2, 3); + public static final Enchantment projectileProtection = new EnchantmentProtection(4, "projectile_protection", 5, 4); +// public static final Enchantment respiration = new EnchantmentOxygen(5, "respiration", 2); +// public static final Enchantment aquaAffinity = new EnchantmentWaterWorker(6, "aqua_affinity", 2); + public static final Enchantment thorns = new EnchantmentThorns(7, "thorns", 1); +// public static final Enchantment depthStrider = new EnchantmentWaterWalker(8, "depth_strider", 2); + public static final Enchantment sharpness = new EnchantmentDamage(16, "sharpness", 10); +// public static final Enchantment smite = new EnchantmentDamage(17, "smite", 5, 1); +// public static final Enchantment baneOfArthropods = new EnchantmentDamage(18, "bane_of_arthropods", 5, 2); + public static final Enchantment knockback = new EnchantmentKnockback(19, "knockback", 5); + public static final Enchantment fireAspect = new EnchantmentFireAspect(20, "fire_aspect", 2); + public static final Enchantment looting = new EnchantmentLootBonus(21, "looting", 2, EnumEnchantmentType.WEAPON); + public static final Enchantment efficiency = new EnchantmentDigging(32, "efficiency", 10); + public static final Enchantment silkTouch = new EnchantmentUntouching(33, "silk_touch", 1); + public static final Enchantment unbreaking = new EnchantmentDurability(34, "unbreaking", 5); + public static final Enchantment fortune = new EnchantmentLootBonus(35, "fortune", 2, EnumEnchantmentType.DIGGER); + public static final Enchantment power = new EnchantmentArrowDamage(48, "power", 10); + public static final Enchantment punch = new EnchantmentArrowKnockback(49, "punch", 2); + public static final Enchantment flame = new EnchantmentArrowFire(50, "flame", 2); + public static final Enchantment infinity = new EnchantmentArrowInfinite(51, "infinity", 1); + public static final Enchantment luckOfTheSea = new EnchantmentLootBonus(61, "luck_of_the_sea", 2, EnumEnchantmentType.FISHING_ROD); + public static final Enchantment lure = new EnchantmentFishingSpeed(62, "lure", 2, EnumEnchantmentType.FISHING_ROD); + + public static final Enchantment draining = new EnchantmentDraining(64, "draining", 1); + + public final int effectId; + private final int weight; + + /** The EnumEnchantmentType given to this Enchantment. */ + public EnumEnchantmentType type; + + /** Used in localisation and stats. */ + protected String name; + + /** + * Retrieves an Enchantment from the enchantmentsList + */ + public static Enchantment getEnchantmentById(int enchID) + { + return enchID >= 0 && enchID < enchantmentsList.length ? enchantmentsList[enchID] : null; + } + + protected Enchantment(int enchID, String enchName, int enchWeight, EnumEnchantmentType enchType) + { + this.effectId = enchID; + this.weight = enchWeight; + this.type = enchType; + + if (enchantmentsList[enchID] != null) + { + throw new IllegalArgumentException("Duplicate enchantment id!"); + } + else + { + enchantmentsList[enchID] = this; + locationEnchantments.put(enchName, this); + } + } + + /** + * Retrieves an enchantment by using its location name. + */ + public static Enchantment getEnchantmentByLocation(String location) + { + return locationEnchantments.get(location); + } + + public static Set getNames() + { + return locationEnchantments.keySet(); + } + + /** + * Retrieves the weight value of an Enchantment. This weight value is used within vanilla to determine how rare an + * enchantment is. + */ + public int getWeight() + { + return this.weight; + } + + /** + * Returns the minimum level that the enchantment can have. + */ + public int getMinLevel() + { + return 1; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 1; + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 1 + enchantmentLevel * 10; + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 5; + } + + /** + * Calculates the damage protection of the enchantment based on level and damage source passed. + */ + public int calcDamageReduction(int level, DamageSource source) + { + return 0; + } + + /** + * Calculates the additional damage that will be dealt by an item with this enchantment. This alternative to + * calcModifierDamage is sensitive to the targets EnumCreatureAttribute. + */ + public int calcAdditionalDamage(int level) + { + return 0; + } + + /** + * Determines if the enchantment passed can be applyied together with this enchantment. + */ + public boolean canApplyTogether(Enchantment ench) + { + return this != ench; + } + + /** + * Sets the enchantment name + */ + public Enchantment setName(String enchName) + { + this.name = enchName; + return this; + } + + /** + * Return the name of key of this enchantment. + */ + public String getName() + { + return this.name; + } + + public String getFormattedName(int level) + { + return this.getName() + " " + ((level >= 1 && level <= 10) ? LEVELS[level - 1] : "" + level); + } + + /** + * Determines if this enchantment can be applied to a specific ItemStack. + */ + public boolean canApply(ItemStack stack) + { + return this.type.canEnchantItem(stack.getItem()); + } + + /** + * Called whenever a mob is damaged with an item that has this enchantment on it. + */ + public void onEntityDamaged(EntityLiving user, Entity target, int level) + { + } + + /** + * Whenever an entity that has this enchantment on one of its associated items is damaged this method will be + * called. + */ + public void onUserHurt(EntityLiving user, Entity attacker, int level) + { + } + + static + { + List list = Lists.newArrayList(); + + for (Enchantment enchantment : enchantmentsList) + { + if (enchantment != null) + { + list.add(enchantment); + } + } + + enchantmentsBookList = (Enchantment[])list.toArray(new Enchantment[list.size()]); + } +} diff --git a/common/src/common/enchantment/EnchantmentArrowDamage.java b/common/src/common/enchantment/EnchantmentArrowDamage.java new file mode 100755 index 0000000..0525e6a --- /dev/null +++ b/common/src/common/enchantment/EnchantmentArrowDamage.java @@ -0,0 +1,36 @@ +package common.enchantment; + + + +public class EnchantmentArrowDamage extends Enchantment +{ + public EnchantmentArrowDamage(int enchID, String enchName, int enchWeight) + { + super(enchID, enchName, enchWeight, EnumEnchantmentType.BOW); + this.setName("Stärke"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 1 + (enchantmentLevel - 1) * 10; + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 15; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 5; + } +} diff --git a/common/src/common/enchantment/EnchantmentArrowFire.java b/common/src/common/enchantment/EnchantmentArrowFire.java new file mode 100755 index 0000000..e5e2658 --- /dev/null +++ b/common/src/common/enchantment/EnchantmentArrowFire.java @@ -0,0 +1,36 @@ +package common.enchantment; + + + +public class EnchantmentArrowFire extends Enchantment +{ + public EnchantmentArrowFire(int enchID, String enchName, int enchWeight) + { + super(enchID, enchName, enchWeight, EnumEnchantmentType.BOW); + this.setName("Flamme"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 20; + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return 50; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 1; + } +} diff --git a/common/src/common/enchantment/EnchantmentArrowInfinite.java b/common/src/common/enchantment/EnchantmentArrowInfinite.java new file mode 100755 index 0000000..860a44a --- /dev/null +++ b/common/src/common/enchantment/EnchantmentArrowInfinite.java @@ -0,0 +1,36 @@ +package common.enchantment; + + + +public class EnchantmentArrowInfinite extends Enchantment +{ + public EnchantmentArrowInfinite(int enchID, String enchName, int enchWeight) + { + super(enchID, enchName, enchWeight, EnumEnchantmentType.BOW); + this.setName("Unendlich"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 20; + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return 50; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 1; + } +} diff --git a/common/src/common/enchantment/EnchantmentArrowKnockback.java b/common/src/common/enchantment/EnchantmentArrowKnockback.java new file mode 100755 index 0000000..2e15fae --- /dev/null +++ b/common/src/common/enchantment/EnchantmentArrowKnockback.java @@ -0,0 +1,36 @@ +package common.enchantment; + + + +public class EnchantmentArrowKnockback extends Enchantment +{ + public EnchantmentArrowKnockback(int enchID, String enchName, int enchWeight) + { + super(enchID, enchName, enchWeight, EnumEnchantmentType.BOW); + this.setName("Schlag"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 12 + (enchantmentLevel - 1) * 20; + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 25; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 2; + } +} diff --git a/common/src/common/enchantment/EnchantmentDamage.java b/common/src/common/enchantment/EnchantmentDamage.java new file mode 100755 index 0000000..9be0458 --- /dev/null +++ b/common/src/common/enchantment/EnchantmentDamage.java @@ -0,0 +1,80 @@ +package common.enchantment; + +import common.item.ItemAxe; +import common.item.ItemStack; + + +public class EnchantmentDamage extends Enchantment +{ + public EnchantmentDamage(int enchID, String enchName, int enchWeight) + { + super(enchID, enchName, enchWeight, EnumEnchantmentType.WEAPON); + this.setName("Schärfe"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 1 + (enchantmentLevel - 1) * 11; + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 20; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 5; + } + + /** + * Calculates the additional damage that will be dealt by an item with this enchantment. This alternative to + * calcModifierDamage is sensitive to the targets EnumCreatureAttribute. + */ + public int calcAdditionalDamage(int level) + { + return (int)(/*this.damageType == 0 ? */ (float)level * 1.25F); // : (this.damageType == 1 && creatureType == CreatureType.UNDEAD ? (float)level * 2.5F : (this.damageType == 2 && creatureType == CreatureType.ARTHROPOD ? (float)level * 2.5F : 0.0F))); + } + + /** + * Determines if the enchantment passed can be applyied together with this enchantment. + */ + public boolean canApplyTogether(Enchantment ench) + { + return !(ench instanceof EnchantmentDamage); + } + + /** + * Determines if this enchantment can be applied to a specific ItemStack. + */ + public boolean canApply(ItemStack stack) + { + return stack.getItem() instanceof ItemAxe ? true : super.canApply(stack); + } + +// /** +// * Called whenever a mob is damaged with an item that has this enchantment on it. +// */ +// public void onEntityDamaged(EntityLivingBase user, Entity target, int level) +// { +// if (target instanceof EntityLivingBase) +// { +// EntityLivingBase entitylivingbase = (EntityLivingBase)target; +// +// if (this.damageType == 2 && entitylivingbase.getCreatureType() == CreatureType.ARTHROPOD) +// { +// int i = 20 + user.getRNG().zrange(10 * level); +// entitylivingbase.addEffect(new PotionEffect(Potion.moveSlowdown.id, i, 3)); +// } +// } +// } +} diff --git a/common/src/common/enchantment/EnchantmentDigging.java b/common/src/common/enchantment/EnchantmentDigging.java new file mode 100755 index 0000000..a504816 --- /dev/null +++ b/common/src/common/enchantment/EnchantmentDigging.java @@ -0,0 +1,46 @@ +package common.enchantment; + +import common.item.ItemShears; +import common.item.ItemStack; + + +public class EnchantmentDigging extends Enchantment +{ + protected EnchantmentDigging(int enchID, String enchName, int enchWeight) + { + super(enchID, enchName, enchWeight, EnumEnchantmentType.DIGGER); + this.setName("Effizienz"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 1 + 10 * (enchantmentLevel - 1); + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 5; + } + + /** + * Determines if this enchantment can be applied to a specific ItemStack. + */ + public boolean canApply(ItemStack stack) + { + return stack.getItem() instanceof ItemShears ? true : super.canApply(stack); + } +} diff --git a/common/src/common/enchantment/EnchantmentDraining.java b/common/src/common/enchantment/EnchantmentDraining.java new file mode 100755 index 0000000..ec8be82 --- /dev/null +++ b/common/src/common/enchantment/EnchantmentDraining.java @@ -0,0 +1,44 @@ +package common.enchantment; + +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.item.ItemAxe; +import common.item.ItemStack; + + +public class EnchantmentDraining extends Enchantment { + public EnchantmentDraining(int enchID, String enchName, int enchWeight) { + super(enchID, enchName, enchWeight, EnumEnchantmentType.WEAPON); + this.setName("Seelenentzug"); + } + + public int getMinEnchantability(int enchantmentLevel) { + return 2 + (enchantmentLevel - 1) * 11; + } + + public int getMaxEnchantability(int enchantmentLevel) { + return this.getMinEnchantability(enchantmentLevel) + 20; + } + + public int getMaxLevel() { + return 16; + } + +// public boolean canApplyTogether(Enchantment ench) +// { +// return !(ench instanceof EnchantmentDraining); +// } + + public boolean canApply(ItemStack stack) { + return stack.getItem() instanceof ItemAxe ? true : super.canApply(stack); + } + + public void onEntityDamaged(EntityLiving user, Entity target, int level) { + if(target instanceof EntityLiving) { + EntityLiving entity = (EntityLiving)target; + entity.attackEntityFrom(DamageSource.causeIndirectMagicDamage(user, user), (int)((float)level * 1.25F)); + user.heal((int)((entity.arePotionsInverted() ? 0.2f : 1.0f) * (float)level)); + } + } +} diff --git a/common/src/common/enchantment/EnchantmentDurability.java b/common/src/common/enchantment/EnchantmentDurability.java new file mode 100755 index 0000000..8181411 --- /dev/null +++ b/common/src/common/enchantment/EnchantmentDurability.java @@ -0,0 +1,57 @@ +package common.enchantment; + +import common.item.ItemArmor; +import common.item.ItemStack; +import common.rng.Random; + + +public class EnchantmentDurability extends Enchantment +{ + protected EnchantmentDurability(int enchID, String enchName, int enchWeight) + { + super(enchID, enchName, enchWeight, EnumEnchantmentType.BREAKABLE); + this.setName("Haltbarkeit"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 5 + (enchantmentLevel - 1) * 8; + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 3; + } + + /** + * Determines if this enchantment can be applied to a specific ItemStack. + */ + public boolean canApply(ItemStack stack) + { + return stack.isItemStackDamageable() ? true : super.canApply(stack); + } + + /** + * Used by ItemStack.attemptDamageItem. Randomly determines if a point of damage should be negated using the + * enchantment level (par1). If the ItemStack is Armor then there is a flat 60% chance for damage to be negated no + * matter the enchantment level, otherwise there is a 1-(par/1) chance for damage to be negated. + */ + public static boolean negateDamage(ItemStack stack, int level, Random rand) + { + return stack.getItem() instanceof ItemArmor && rand.floatv() < 0.6F ? false : rand.rarity(level + 1); + } +} diff --git a/common/src/common/enchantment/EnchantmentFireAspect.java b/common/src/common/enchantment/EnchantmentFireAspect.java new file mode 100755 index 0000000..0e91e40 --- /dev/null +++ b/common/src/common/enchantment/EnchantmentFireAspect.java @@ -0,0 +1,36 @@ +package common.enchantment; + + + +public class EnchantmentFireAspect extends Enchantment +{ + protected EnchantmentFireAspect(int enchID, String enchName, int enchWeight) + { + super(enchID, enchName, enchWeight, EnumEnchantmentType.WEAPON); + this.setName("Verbrennung"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 10 + 20 * (enchantmentLevel - 1); + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 2; + } +} diff --git a/common/src/common/enchantment/EnchantmentFishingSpeed.java b/common/src/common/enchantment/EnchantmentFishingSpeed.java new file mode 100755 index 0000000..0ba0dd0 --- /dev/null +++ b/common/src/common/enchantment/EnchantmentFishingSpeed.java @@ -0,0 +1,36 @@ +package common.enchantment; + + + +public class EnchantmentFishingSpeed extends Enchantment +{ + protected EnchantmentFishingSpeed(int enchID, String enchName, int enchWeight, EnumEnchantmentType enchType) + { + super(enchID, enchName, enchWeight, enchType); + this.setName("Köder"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 15 + (enchantmentLevel - 1) * 9; + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 3; + } +} diff --git a/common/src/main/java/common/enchantment/EnchantmentHelper.java b/common/src/common/enchantment/EnchantmentHelper.java similarity index 75% rename from common/src/main/java/common/enchantment/EnchantmentHelper.java rename to common/src/common/enchantment/EnchantmentHelper.java index a7a6edf..a6ce979 100755 --- a/common/src/main/java/common/enchantment/EnchantmentHelper.java +++ b/common/src/common/enchantment/EnchantmentHelper.java @@ -12,19 +12,32 @@ import common.entity.types.EntityLiving; import common.init.Items; import common.item.Item; import common.item.ItemStack; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.rng.Random; import common.rng.WeightedList; -import common.tags.TagObject; public class EnchantmentHelper { + /** Is the random seed of enchantment effects. */ private static final Random enchantmentRand = new Random(); + + /** + * Used to calculate the extra armor of enchantments on armors equipped on player. + */ private static final EnchantmentHelper.ModifierDamage enchantmentModifierDamage = new EnchantmentHelper.ModifierDamage(); + + /** + * Used to calculate the (magic) extra damage done by enchantments on current equipped item of player. + */ private static final EnchantmentHelper.ModifierLiving enchantmentModifierLiving = new EnchantmentHelper.ModifierLiving(); private static final EnchantmentHelper.HurtIterator ENCHANTMENT_ITERATOR_HURT = new EnchantmentHelper.HurtIterator(); private static final EnchantmentHelper.DamageIterator ENCHANTMENT_ITERATOR_DAMAGE = new EnchantmentHelper.DamageIterator(); - public static int getEnchantmentLevel(Enchantment enchID, ItemStack stack) + /** + * Returns the level of enchantment on the ItemStack passed. + */ + public static int getEnchantmentLevel(int enchID, ItemStack stack) { if (stack == null) { @@ -32,21 +45,21 @@ public class EnchantmentHelper } else { - List list = stack.getEnchantmentTagList(); + NBTTagList nbttaglist = stack.getEnchantmentTagList(); - if (list == null) + if (nbttaglist == null) { return 0; } else { - for (int i = 0; i < list.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - Enchantment j = Enchantment.getEnchantment(list.get(i).getString("id")); + int j = nbttaglist.getCompoundTagAt(i).getShort("id"); + int k = nbttaglist.getCompoundTagAt(i).getShort("lvl"); if (j == enchID) { - int k = list.get(i).getShort("lvl"); return k; } } @@ -56,63 +69,68 @@ public class EnchantmentHelper } } - public static Map getEnchantments(ItemStack stack) + public static Map getEnchantments(ItemStack stack) { - Map map = Maps.newLinkedHashMap(); - List list = stack.getItem() == Items.enchanted_book ? Items.enchanted_book.getEnchantments(stack) : stack.getEnchantmentTagList(); + Map map = Maps.newLinkedHashMap(); + NBTTagList nbttaglist = stack.getItem() == Items.enchanted_book ? Items.enchanted_book.getEnchantments(stack) : stack.getEnchantmentTagList(); - if (list != null) + if (nbttaglist != null) { - for (int i = 0; i < list.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - Enchantment j = Enchantment.getEnchantment(list.get(i).getString("id")); - if(j != null) { - int k = list.get(i).getShort("lvl"); - map.put(j, k); - } + int j = nbttaglist.getCompoundTagAt(i).getShort("id"); + int k = nbttaglist.getCompoundTagAt(i).getShort("lvl"); + map.put(j, k); } } return map; } - public static void setEnchantments(Map enchMap, ItemStack stack) + /** + * Set the enchantments for the specified stack. + */ + public static void setEnchantments(Map enchMap, ItemStack stack) { - List list = Lists.newArrayList(); - Iterator iterator = enchMap.keySet().iterator(); + NBTTagList nbttaglist = new NBTTagList(); + Iterator iterator = enchMap.keySet().iterator(); while (iterator.hasNext()) { - Enchantment enchantment = iterator.next(); + int i = ((Integer)iterator.next()).intValue(); + Enchantment enchantment = Enchantment.getEnchantmentById(i); - TagObject tag = new TagObject(); - tag.setString("id", enchantment.getName()); - tag.setShort("lvl", (short)enchMap.get(enchantment).intValue()); - list.add(tag); - - if (stack.getItem() == Items.enchanted_book) + if (enchantment != null) { - Items.enchanted_book.addEnchantment(stack, new RngEnchantment(enchantment, enchMap.get(enchantment).intValue())); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setShort("id", (short)i); + nbttagcompound.setShort("lvl", (short)enchMap.get(i).intValue()); + nbttaglist.appendTag(nbttagcompound); + + if (stack.getItem() == Items.enchanted_book) + { + Items.enchanted_book.addEnchantment(stack, new RngEnchantment(enchantment, enchMap.get(i).intValue())); + } } } - if (list.size() > 0) + if (nbttaglist.tagCount() > 0) { if (stack.getItem() != Items.enchanted_book) { - stack.setTagInfo("ench", list); + stack.setTagInfo("ench", nbttaglist); } } else if (stack.hasTagCompound()) { - stack.getTagCompound().remove("ench"); + stack.getTagCompound().removeTag("ench"); } } /** * Returns the biggest level of the enchantment on the array of ItemStack passed. */ - public static int getMaxEnchantmentLevel(Enchantment enchID, ItemStack[] stacks) + public static int getMaxEnchantmentLevel(int enchID, ItemStack[] stacks) { if (stacks == null) { @@ -143,18 +161,18 @@ public class EnchantmentHelper { if (stack != null) { - List list = stack.getEnchantmentTagList(); + NBTTagList nbttaglist = stack.getEnchantmentTagList(); - if (list != null) + if (nbttaglist != null) { - for (int i = 0; i < list.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - String j = list.get(i).getString("id"); - int k = list.get(i).getShort("lvl"); + int j = nbttaglist.getCompoundTagAt(i).getShort("id"); + int k = nbttaglist.getCompoundTagAt(i).getShort("lvl"); - if (Enchantment.getEnchantment(j) != null) + if (Enchantment.getEnchantmentById(j) != null) { - modifier.calculateModifier(Enchantment.getEnchantment(j), k); + modifier.calculateModifier(Enchantment.getEnchantmentById(j), k); } } } @@ -237,7 +255,7 @@ public class EnchantmentHelper */ public static int getKnockbackModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.KNOCKBACK, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.knockback.effectId, player.getHeldItem()); } /** @@ -245,7 +263,7 @@ public class EnchantmentHelper */ public static int getFireAspectModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.FIRE_ASPECT, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.fireAspect.effectId, player.getHeldItem()); } // /** @@ -269,7 +287,7 @@ public class EnchantmentHelper */ public static int getEfficiencyModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.EFFICIENCY, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.efficiency.effectId, player.getHeldItem()); } /** @@ -277,7 +295,7 @@ public class EnchantmentHelper */ public static boolean getSilkTouchModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.SILK_TOUCH, player.getHeldItem()) > 0; + return getEnchantmentLevel(Enchantment.silkTouch.effectId, player.getHeldItem()) > 0; } /** @@ -285,7 +303,7 @@ public class EnchantmentHelper */ public static int getFortuneModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.FORTUNE, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.fortune.effectId, player.getHeldItem()); } /** @@ -293,7 +311,7 @@ public class EnchantmentHelper */ public static int getLuckOfSeaModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.LUCK_OF_THE_SEA, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.luckOfTheSea.effectId, player.getHeldItem()); } /** @@ -301,7 +319,7 @@ public class EnchantmentHelper */ public static int getLureModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.LURE, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.lure.effectId, player.getHeldItem()); } /** @@ -309,7 +327,7 @@ public class EnchantmentHelper */ public static int getLootingModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.LOOTING, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.looting.effectId, player.getHeldItem()); } // /** @@ -324,7 +342,7 @@ public class EnchantmentHelper { for (ItemStack itemstack : p_92099_1_.getInventory()) { - if (itemstack != null && getEnchantmentLevel(p_92099_0_, itemstack) > 0) + if (itemstack != null && getEnchantmentLevel(p_92099_0_.effectId, itemstack) > 0) { return itemstack; } @@ -381,7 +399,7 @@ public class EnchantmentHelper } else { - p_77504_1_.addEnchantment(enchantmentdata.enchantment, enchantmentdata.level); + p_77504_1_.addEnchantment(enchantmentdata.enchantmentobj, enchantmentdata.enchantmentLevel); } } } @@ -412,7 +430,7 @@ public class EnchantmentHelper } List list = null; - Map map = mapEnchantmentData(k, itemStackIn); + Map map = mapEnchantmentData(k, itemStackIn); if (map != null && !map.isEmpty()) { @@ -425,16 +443,16 @@ public class EnchantmentHelper for (int l = k; randomIn.zrange(50) <= l; l >>= 1) { - Iterator iterator = map.keySet().iterator(); + Iterator iterator = map.keySet().iterator(); while (iterator.hasNext()) { - Enchantment ench = iterator.next(); + Integer integer = (Integer)iterator.next(); boolean flag = true; for (RngEnchantment enchantmentdata1 : list) { - if (!enchantmentdata1.enchantment.canApplyTogether(ench)) + if (!enchantmentdata1.enchantmentobj.canApplyTogether(Enchantment.getEnchantmentById(integer.intValue()))) { flag = false; break; @@ -460,15 +478,15 @@ public class EnchantmentHelper } } - public static Map mapEnchantmentData(int p_77505_0_, ItemStack p_77505_1_) + public static Map mapEnchantmentData(int p_77505_0_, ItemStack p_77505_1_) { Item item = p_77505_1_.getItem(); - Map map = null; + Map map = null; boolean flag = p_77505_1_.getItem() == Items.book; - for (Enchantment enchantment : Enchantment.values()) + for (Enchantment enchantment : Enchantment.enchantmentsBookList) { - if (enchantment != null && (enchantment.getType().canEnchantItem(item) || flag)) + if (enchantment != null && (enchantment.type.canEnchantItem(item) || flag)) { for (int i = enchantment.getMinLevel(); i <= enchantment.getMaxLevel(); ++i) { @@ -476,10 +494,10 @@ public class EnchantmentHelper { if (map == null) { - map = Maps.newEnumMap(Enchantment.class); + map = Maps.newHashMap(); } - map.put(enchantment, new RngEnchantment(enchantment, i)); + map.put(enchantment.effectId, new RngEnchantment(enchantment, i)); } } } diff --git a/common/src/common/enchantment/EnchantmentKnockback.java b/common/src/common/enchantment/EnchantmentKnockback.java new file mode 100755 index 0000000..5fd4642 --- /dev/null +++ b/common/src/common/enchantment/EnchantmentKnockback.java @@ -0,0 +1,36 @@ +package common.enchantment; + + + +public class EnchantmentKnockback extends Enchantment +{ + protected EnchantmentKnockback(int p_i45768_1_, String p_i45768_2_, int p_i45768_3_) + { + super(p_i45768_1_, p_i45768_2_, p_i45768_3_, EnumEnchantmentType.WEAPON); + this.setName("Rückstoß"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 5 + 20 * (enchantmentLevel - 1); + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 2; + } +} diff --git a/common/src/common/enchantment/EnchantmentLootBonus.java b/common/src/common/enchantment/EnchantmentLootBonus.java new file mode 100755 index 0000000..036fdb8 --- /dev/null +++ b/common/src/common/enchantment/EnchantmentLootBonus.java @@ -0,0 +1,56 @@ +package common.enchantment; + + + +public class EnchantmentLootBonus extends Enchantment +{ + protected EnchantmentLootBonus(int p_i45767_1_, String p_i45767_2_, int p_i45767_3_, EnumEnchantmentType p_i45767_4_) + { + super(p_i45767_1_, p_i45767_2_, p_i45767_3_, p_i45767_4_); + + if (p_i45767_4_ == EnumEnchantmentType.DIGGER) + { + this.setName("Glück"); + } + else if (p_i45767_4_ == EnumEnchantmentType.FISHING_ROD) + { + this.setName("Glück des Meeres"); + } + else + { + this.setName("Plünderung"); + } + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 15 + (enchantmentLevel - 1) * 9; + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 3; + } + + /** + * Determines if the enchantment passed can be applyied together with this enchantment. + */ + public boolean canApplyTogether(Enchantment ench) + { + return super.canApplyTogether(ench) && ench.effectId != silkTouch.effectId; + } +} diff --git a/common/src/common/enchantment/EnchantmentProtection.java b/common/src/common/enchantment/EnchantmentProtection.java new file mode 100755 index 0000000..6cfe6bc --- /dev/null +++ b/common/src/common/enchantment/EnchantmentProtection.java @@ -0,0 +1,132 @@ +package common.enchantment; + +import common.entity.DamageSource; +import common.entity.Entity; +import common.util.ExtMath; + + +public class EnchantmentProtection extends Enchantment +{ + private static final String[] NAMES = new String[] {"Schutz", "Feuerschutz", "Federfall", "Explosionsschutz", "Schusssicher"}; + + /** + * Holds the base factor of enchantability needed to be able to use the enchant. + */ + private static final int[] baseEnchantability = new int[] {1, 10, 5, 5, 3}; + + /** + * Holds how much each level increased the enchantability factor to be able to use this enchant. + */ + private static final int[] levelEnchantability = new int[] {11, 8, 6, 8, 6}; + + /** + * Used on the formula of base enchantability, this is the 'window' factor of values to be able to use thing + * enchant. + */ + private static final int[] thresholdEnchantability = new int[] {20, 12, 10, 12, 15}; + + /** + * Defines the type of protection of the enchantment, 0 = all, 1 = fire, 2 = fall (feather fall), 3 = explosion and + * 4 = projectile. + */ + public final int protectionType; + + public EnchantmentProtection(int id, String name, int weight, int type) + { + super(id, name, weight, EnumEnchantmentType.ARMOR); + this.protectionType = type; + + if (type == 2) + { + this.type = EnumEnchantmentType.ARMOR_FEET; + } + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return baseEnchantability[this.protectionType] + (enchantmentLevel - 1) * levelEnchantability[this.protectionType]; + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + thresholdEnchantability[this.protectionType]; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 4; + } + + /** + * Calculates the damage protection of the enchantment based on level and damage source passed. + */ + public int calcDamageReduction(int level, DamageSource source) + { + if (source == DamageSource.outOfWorld) + { + return 0; + } + else + { + float f = (float)(6 + level * level) / 3.0F; + return this.protectionType == 0 ? ExtMath.floorf(f * 0.75F) : (this.protectionType == 1 && source.isFireDamage() ? ExtMath.floorf(f * 1.25F) : (this.protectionType == 2 && source == DamageSource.fall ? ExtMath.floorf(f * 2.5F) : (this.protectionType == 3 && source.isExplosion() ? ExtMath.floorf(f * 1.5F) : (this.protectionType == 4 && source.isProjectile() ? ExtMath.floorf(f * 1.5F) : 0)))); + } + } + + public String getName() + { + return NAMES[this.protectionType]; + } + + /** + * Determines if the enchantment passed can be applyied together with this enchantment. + */ + public boolean canApplyTogether(Enchantment ench) + { + if (ench instanceof EnchantmentProtection) + { + EnchantmentProtection enchantmentprotection = (EnchantmentProtection)ench; + return enchantmentprotection.protectionType == this.protectionType ? false : this.protectionType == 2 || enchantmentprotection.protectionType == 2; + } + else + { + return super.canApplyTogether(ench); + } + } + + /** + * Gets the amount of ticks an entity should be set fire, adjusted for fire protection. + */ + public static int getFireTimeForEntity(Entity entity, int duration) + { + int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.fireProtection.effectId, entity.getInventory()); + + if (i > 0) + { + duration -= ExtMath.floorf((float)duration * (float)i * 0.15F); + } + + return duration; + } + + public static double getKnockbackFactor(Entity entity, double strength) + { + int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.blastProtection.effectId, entity.getInventory()); + + if (i > 0) + { + strength -= (double)ExtMath.floord(strength * (double)((float)i * 0.15F)); + } + + return strength; + } +} diff --git a/common/src/common/enchantment/EnchantmentThorns.java b/common/src/common/enchantment/EnchantmentThorns.java new file mode 100755 index 0000000..3693045 --- /dev/null +++ b/common/src/common/enchantment/EnchantmentThorns.java @@ -0,0 +1,88 @@ +package common.enchantment; + +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.init.Config; +import common.item.ItemArmor; +import common.item.ItemStack; +import common.rng.Random; + +public class EnchantmentThorns extends Enchantment +{ + public EnchantmentThorns(int p_i45764_1_, String p_i45764_2_, int p_i45764_3_) + { + super(p_i45764_1_, p_i45764_2_, p_i45764_3_, EnumEnchantmentType.ARMOR_TORSO); + this.setName("Dornen"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 10 + 20 * (enchantmentLevel - 1); + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 3; + } + + /** + * Determines if this enchantment can be applied to a specific ItemStack. + */ + public boolean canApply(ItemStack stack) + { + return stack.getItem() instanceof ItemArmor ? true : super.canApply(stack); + } + + /** + * Whenever an entity that has this enchantment on one of its associated items is damaged this method will be + * called. + */ + public void onUserHurt(EntityLiving user, Entity attacker, int level) + { + Random random = user.getRNG(); + ItemStack itemstack = EnchantmentHelper.getEnchantedItem(Enchantment.thorns, user); + + if ((user.worldObj.client || Config.damageThorns) && isHurting(level, random)) + { + if (attacker != null) + { + attacker.attackEntityFrom(DamageSource.causeThornsDamage(user), getDamage(level, random)); +// attacker.playSound("damage.thorns", 0.5F, 1.0F); + } + + if (itemstack != null) + { + itemstack.damageItem(3, user); + } + } + else if (itemstack != null) + { + itemstack.damageItem(1, user); + } + } + + public static boolean isHurting(int level, Random rand) + { + return level <= 0 ? false : rand.floatv() < 0.15F * (float)level; + } + + public static int getDamage(int level, Random rand) + { + return level > 10 ? level - 10 : rand.roll(4); + } +} diff --git a/common/src/common/enchantment/EnchantmentUntouching.java b/common/src/common/enchantment/EnchantmentUntouching.java new file mode 100755 index 0000000..3508fca --- /dev/null +++ b/common/src/common/enchantment/EnchantmentUntouching.java @@ -0,0 +1,54 @@ +package common.enchantment; + +import common.item.ItemShears; +import common.item.ItemStack; + + +public class EnchantmentUntouching extends Enchantment +{ + protected EnchantmentUntouching(int p_i45763_1_, String p_i45763_2_, int p_i45763_3_) + { + super(p_i45763_1_, p_i45763_2_, p_i45763_3_, EnumEnchantmentType.DIGGER); + this.setName("Behutsamkeit"); + } + + /** + * Returns the minimal value of enchantability needed on the enchantment level passed. + */ + public int getMinEnchantability(int enchantmentLevel) + { + return 15; + } + + /** + * Returns the maximum value of enchantability nedded on the enchantment level passed. + */ + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + /** + * Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() + { + return 1; + } + + /** + * Determines if the enchantment passed can be applyied together with this enchantment. + */ + public boolean canApplyTogether(Enchantment ench) + { + return super.canApplyTogether(ench) && ench.effectId != fortune.effectId; + } + + /** + * Determines if this enchantment can be applied to a specific ItemStack. + */ + public boolean canApply(ItemStack stack) + { + return stack.getItem() instanceof ItemShears ? true : super.canApply(stack); + } +} diff --git a/common/src/common/enchantment/EnumEnchantmentType.java b/common/src/common/enchantment/EnumEnchantmentType.java new file mode 100755 index 0000000..7c7e2c9 --- /dev/null +++ b/common/src/common/enchantment/EnumEnchantmentType.java @@ -0,0 +1,54 @@ +package common.enchantment; + +import common.item.Item; +import common.item.ItemArmor; +import common.item.ItemBow; +import common.item.ItemFishingRod; +import common.item.ItemSword; +import common.item.ItemTool; + +public enum EnumEnchantmentType +{ + ALL, + ARMOR, + ARMOR_FEET, + ARMOR_LEGS, + ARMOR_TORSO, + ARMOR_HEAD, + WEAPON, + DIGGER, + FISHING_ROD, + BREAKABLE, + BOW; + + /** + * Return true if the item passed can be enchanted by a enchantment of this type. + */ + public boolean canEnchantItem(Item p_77557_1_) + { + if (this == ALL) + { + return true; + } + else if (this == BREAKABLE && p_77557_1_.isDamageable()) + { + return true; + } + else if (p_77557_1_ instanceof ItemArmor) + { + if (this == ARMOR) + { + return true; + } + else + { + ItemArmor itemarmor = (ItemArmor)p_77557_1_; + return itemarmor.armorType == 0 ? this == ARMOR_HEAD : (itemarmor.armorType == 2 ? this == ARMOR_LEGS : (itemarmor.armorType == 1 ? this == ARMOR_TORSO : (itemarmor.armorType == 3 ? this == ARMOR_FEET : false))); + } + } + else + { + return p_77557_1_ instanceof ItemSword ? this == WEAPON : (p_77557_1_ instanceof ItemTool ? this == DIGGER : (p_77557_1_ instanceof ItemBow ? this == BOW : (p_77557_1_ instanceof ItemFishingRod ? this == FISHING_ROD : false))); + } + } +} diff --git a/common/src/common/enchantment/RngEnchantment.java b/common/src/common/enchantment/RngEnchantment.java new file mode 100755 index 0000000..d517860 --- /dev/null +++ b/common/src/common/enchantment/RngEnchantment.java @@ -0,0 +1,19 @@ +package common.enchantment; + +import common.rng.RngItem; + +public class RngEnchantment extends RngItem +{ + /** Enchantment object associated with this EnchantmentData */ + public final Enchantment enchantmentobj; + + /** Enchantment level associated with this EnchantmentData */ + public final int enchantmentLevel; + + public RngEnchantment(Enchantment enchantmentObj, int enchLevel) + { + super(enchantmentObj.getWeight()); + this.enchantmentobj = enchantmentObj; + this.enchantmentLevel = enchLevel; + } +} diff --git a/common/src/main/java/common/entity/DamageSource.java b/common/src/common/entity/DamageSource.java similarity index 100% rename from common/src/main/java/common/entity/DamageSource.java rename to common/src/common/entity/DamageSource.java diff --git a/common/src/main/java/common/entity/DataWatcher.java b/common/src/common/entity/DataWatcher.java similarity index 98% rename from common/src/main/java/common/entity/DataWatcher.java rename to common/src/common/entity/DataWatcher.java index 222676a..e4b9a7e 100755 --- a/common/src/main/java/common/entity/DataWatcher.java +++ b/common/src/common/entity/DataWatcher.java @@ -202,7 +202,7 @@ public class DataWatcher { case 5: ItemStack itemstack = (ItemStack)object.getObject(); - buffer.writeItemStack(itemstack); + buffer.writeItemStackToBuffer(itemstack); break; case 6: @@ -250,11 +250,11 @@ public class DataWatcher { break; case 4: - datawatcher$watchableobject = new DataWatcher.WatchableObject(j, k, buffer.readString(32767)); + datawatcher$watchableobject = new DataWatcher.WatchableObject(j, k, buffer.readStringFromBuffer(32767)); break; case 5: - datawatcher$watchableobject = new DataWatcher.WatchableObject(j, k, buffer.readItemStack()); + datawatcher$watchableobject = new DataWatcher.WatchableObject(j, k, buffer.readItemStackFromBuffer()); break; case 6: diff --git a/common/src/main/java/common/entity/Entity.java b/common/src/common/entity/Entity.java similarity index 90% rename from common/src/main/java/common/entity/Entity.java rename to common/src/common/entity/Entity.java index 15a3e9d..04d12af 100755 --- a/common/src/main/java/common/entity/Entity.java +++ b/common/src/common/entity/Entity.java @@ -3,31 +3,35 @@ package common.entity; import java.util.List; import common.block.Block; -import common.block.Material; +import common.block.BlockFence; +import common.block.BlockFenceGate; +import common.block.BlockLiquid; +import common.block.BlockWall; import common.block.SoundType; -import common.block.artificial.BlockFence; -import common.block.artificial.BlockFenceGate; -import common.block.artificial.BlockWall; -import common.block.liquid.BlockLiquid; import common.color.TextColor; import common.dimension.DimType; -import common.enchantment.Enchantment; import common.enchantment.EnchantmentHelper; +import common.enchantment.EnchantmentProtection; import common.entity.effect.EntityLightning; import common.entity.item.EntityItem; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.BlockRegistry; import common.init.Blocks; +import common.init.Config; import common.init.EntityRegistry; import common.init.ItemRegistry; import common.init.SoundEvent; import common.init.UniverseRegistry; import common.item.Item; import common.item.ItemStack; +import common.material.Material; import common.model.ParticleType; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagDouble; +import common.nbt.NBTTagFloat; +import common.nbt.NBTTagList; import common.rng.Random; -import common.tags.TagObject; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; @@ -36,7 +40,6 @@ import common.util.HitPosition; import common.util.PortalType; import common.util.Position; import common.util.Vec3; -import common.vars.Vars; import common.world.Explosion; import common.world.State; import common.world.World; @@ -147,7 +150,10 @@ public abstract class Entity this.dataWatcher = new DataWatcher(this); this.dataWatcher.addObject(0, Byte.valueOf((byte)0)); +// this.dataWatcher.addObject(1, Short.valueOf((short)300)); +// this.dataWatcher.addObject(3, Byte.valueOf((byte)0)); this.dataWatcher.addObject(1, ""); +// this.dataWatcher.addObject(4, Byte.valueOf((byte)0)); this.entityInit(); } @@ -267,7 +273,7 @@ public abstract class Entity protected void checkPortal() { if(this.inPortal != null) { - if(this.vehicle == null && this.passenger == null && Vars.portals) { + if(this.vehicle == null && this.passenger == null && Config.portals) { int current = this.worldObj.dimension.getDimensionId(); int dest = UniverseRegistry.getPortalDest(current, this.inPortal); if(dest != current) { @@ -322,7 +328,7 @@ public abstract class Entity } else { - if (Vars.damageFire && this.fire % 20 == 0) + if (Config.damageFire && this.fire % 20 == 0) { this.attackEntityFrom(DamageSource.onFire, 1); } @@ -336,11 +342,11 @@ public abstract class Entity this.setOnFireFromLava(); this.fallDistance *= 0.5F; } - else if(this.worldObj.canBurnAt(this.getPosition()) && this.isInDownfall()) { + else if(!this.worldObj.client && ((AWorldServer)this.worldObj).canBurnAt(this.getPosition()) && this.isInDownfall()) { this.setOnFireFromMolten(); } - if (this.posY < (double)(-World.MAX_SIZE_Y) - 64.0) + if (this.posY < -64.0D) { this.onVoidUpdate(); } @@ -358,7 +364,7 @@ public abstract class Entity if(!this.worldObj.client && this.worldObj.dimension.getType() != DimType.SPACE) { // this.worldObj.profiler.start("descent"); int current = this.worldObj.dimension.getDimensionId(); - int dim = Vars.voidPortal ? UniverseRegistry.getPortalDest(current, PortalType.VOID) : current; + int dim = Config.voidPortal ? UniverseRegistry.getPortalDest(current, PortalType.VOID) : current; if(dim == current) { // && (!(this.isPlayer()) || !((EntityNPCMP)this).creative)) { this.kill(); } @@ -368,7 +374,7 @@ public abstract class Entity // } else if(this.vehicle == null && this.passenger == null) { Entity ent = this.travelToDimension(dim, - new BlockPos(this.posX, (float)ExtMath.clampi(Vars.portalHeight, 0, 16384), this.posZ), + new BlockPos(this.posX, (float)ExtMath.clampi(Config.portalHeight, 0, 16384), this.posZ), this.rotYaw, this.rotPitch, PortalType.VOID); ent.ignoreFall = true; } @@ -394,7 +400,7 @@ public abstract class Entity { if (!this.isImmuneToFire()) { - if(Vars.damageLava) + if(Config.damageLava) this.attackEntityFrom(DamageSource.hotLiquid, 4); this.setFire(15); } @@ -404,7 +410,7 @@ public abstract class Entity { if (!this.isImmuneToFire()) { - if(Vars.damageMolten) + if(Config.damageMolten) this.attackEntityFrom(DamageSource.molten, 2); this.setFire(10); } @@ -422,7 +428,7 @@ public abstract class Entity public void setFire(int seconds) { int i = seconds * 20; - i = Enchantment.getFireTimeForEntity(this, i); + i = EnchantmentProtection.getFireTimeForEntity(this, i); if (this.fire < i) { @@ -698,7 +704,7 @@ public abstract class Entity BlockPos blockpos = new BlockPos(i, j, k); Block block1 = this.worldObj.getState(blockpos).getBlock(); - if (block1 == Blocks.air) + if (block1.getMaterial() == Material.air) { Block block = this.worldObj.getState(blockpos.down()).getBlock(); @@ -745,7 +751,7 @@ public abstract class Entity this.walkDistMod = (float)((double)this.walkDistMod + (double)ExtMath.sqrtd(d12 * d12 + d14 * d14) * 0.6D); this.stepDistMod = (float)((double)this.stepDistMod + (double)ExtMath.sqrtd(d12 * d12 + d13 * d13 + d14 * d14) * 0.6D); - if (this.stepDistMod > (float)this.nextStepDist && block1 != Blocks.air) + if (this.stepDistMod > (float)this.nextStepDist && block1.getMaterial() != Material.air) { this.nextStepDist = (int)this.stepDistMod + 1; @@ -767,7 +773,7 @@ public abstract class Entity this.doBlockCollisions(); - boolean flag2 = this.isWet(); + boolean flag2 = !this.worldObj.client && this.isWet(); if (this.worldObj.isFlammableWithin(this.getEntityBoundingBox().contract(0.001D, 0.001D, 0.001D))) { @@ -926,7 +932,7 @@ public abstract class Entity */ protected void dealFireDamage(int amount) { - if(!this.isImmuneToFire() && Vars.damageFire) + if(!this.isImmuneToFire() && Config.damageFire) this.attackEntityFrom(DamageSource.inFire, amount); } @@ -943,17 +949,14 @@ public abstract class Entity } } - /** - * Checks if this entity is either in water or on an open air block in rain (used in wolves). - */ public boolean isWet() { - return this.inLiquid || this.worldObj.isRainingAt(new BlockPos(this.posX, this.posY, this.posZ), true) || this.worldObj.isRainingAt(new BlockPos(this.posX, this.posY + (double)this.height, this.posZ), true); + return this.inLiquid || ((AWorldServer)this.worldObj).isRainingAt(new BlockPos(this.posX, this.posY, this.posZ), true) || ((AWorldServer)this.worldObj).isRainingAt(new BlockPos(this.posX, this.posY + (double)this.height, this.posZ), true); } public boolean isInDownfall() { - return this.worldObj.isRainingAt(new BlockPos(this.posX, this.posY, this.posZ), false) || this.worldObj.isRainingAt(new BlockPos(this.posX, this.posY + (double)this.height, this.posZ), false); + return ((AWorldServer)this.worldObj).isRainingAt(new BlockPos(this.posX, this.posY, this.posZ), false) || ((AWorldServer)this.worldObj).isRainingAt(new BlockPos(this.posX, this.posY + (double)this.height, this.posZ), false); } /** @@ -1008,7 +1011,7 @@ public abstract class Entity this.worldObj.spawnParticle(ParticleType.WATER_BUBBLE, this.posX + (double)f2, (double)(f1 + 1.0F), this.posZ + (double)f3, this.motionX, this.motionY - (double)(this.rand.floatv() * 0.2F), this.motionZ); } - if(this.worldObj.getState(new BlockPos(this.posX, this.posY, this.posZ)).getBlock().getMaterial() == Material.WATER) { + if(this.worldObj.getState(new BlockPos(this.posX, this.posY, this.posZ)).getBlock().getMaterial() == Material.water) { for (int j = 0; (float)j < 1.0F + this.width * 20.0F; ++j) { float f4 = (this.rand.floatv() * 2.0F - 1.0F) * this.width; @@ -1293,7 +1296,7 @@ public abstract class Entity public void addKnockback(double x, double y, double z) { - float mult = this.worldObj.client ? 1.0f : Vars.knockback; + float mult = this.worldObj.client ? 1.0f : Config.knockback; this.addVelocity(x * mult, y * mult, z * mult); } @@ -1416,17 +1419,17 @@ public abstract class Entity } /** - * Like writeOptional but does not check if the entity is ridden. Used for saving ridden entities with their + * Like writeToNBTOptional but does not check if the entity is ridden. Used for saving ridden entities with their * riders. */ - public boolean writeMount(TagObject tag) + public boolean writeMountToNBT(NBTTagCompound tagCompund) { String s = EntityRegistry.getEntityString(this); if (!this.dead && !this.isPlayer() && s != null) { - tag.setString("id", s); - this.writeTags(tag); + tagCompund.setString("id", s); + this.writeToNBT(tagCompund); return true; } else @@ -1436,18 +1439,18 @@ public abstract class Entity } /** - * Either write this entity to the tag given and return true, or return false without doing anything. If this + * Either write this entity to the NBT tag given and return true, or return false without doing anything. If this * returns false the entity is not saved on disk. Ridden entities return false here as they are saved with their * rider. */ - public boolean writeOptional(TagObject tag) + public boolean writeToNBTOptional(NBTTagCompound tagCompund) { String s = EntityRegistry.getEntityString(this); if (!this.dead && !this.isPlayer() && s != null && (this.passenger == null || this.passenger.isPlayer())) { - tag.setString("id", s); - this.writeTags(tag); + tagCompund.setString("id", s); + this.writeToNBT(tagCompund); return true; } else @@ -1481,9 +1484,9 @@ public abstract class Entity // } /** - * Save the entity to tags (calls an abstract helper method to write extra data) + * Save the entity to NBT (calls an abstract helper method to write extra data) */ - public void writeTags(TagObject tag) + public void writeToNBT(NBTTagCompound tagCompund) { // if(this.persistentId != 0L) { // tagCompund.setLong("PersistID", this.persistentId); @@ -1491,25 +1494,20 @@ public abstract class Entity // if(this.tag != null) { // tagCompund.setString("ObjectTag", this.tag); // } - - tag.setDouble("PosX", this.posX); - tag.setDouble("PosY", this.posY); - tag.setDouble("PosZ", this.posZ); - tag.setDouble("MotionX", this.motionX); - tag.setDouble("MotionY", this.motionY); - tag.setDouble("MotionZ", this.motionZ); - tag.setFloat("Yaw", this.rotYaw); - tag.setFloat("Pitch", this.rotPitch); - tag.setFloat("FallDistance", this.fallDistance); - tag.setShort("Fire", (short)this.fire); + + tagCompund.setTag("Pos", this.newDoubleNBTList(this.posX, this.posY, this.posZ)); + tagCompund.setTag("Motion", this.newDoubleNBTList(this.motionX, this.motionY, this.motionZ)); + tagCompund.setTag("Rotation", this.newFloatNBTList(this.rotYaw, this.rotPitch)); + tagCompund.setFloat("FallDistance", this.fallDistance); + tagCompund.setShort("Fire", (short)this.fire); // tagCompund.setShort("Air", (short)this.getAir()); - tag.setBool("OnGround", this.onGround); + tagCompund.setBoolean("OnGround", this.onGround); // tagCompund.setBoolean("Invulnerable", this.invulnerable); // tagCompund.setInteger("PortalCooldown", this.portalTimer); if (this.getCustomNameTag() != null && this.getCustomNameTag().length() > 0) { - tag.setString("CustomName", this.getCustomNameTag()); + tagCompund.setString("CustomName", this.getCustomNameTag()); // tagCompund.setBoolean("CustomNameVisible", this.getAlwaysRenderNameTag()); } @@ -1519,33 +1517,36 @@ public abstract class Entity // } if(this.ignoreFall) - tag.setBool("IgnoreFall", this.ignoreFall); + tagCompund.setBoolean("IgnoreFall", this.ignoreFall); - this.writeEntity(tag); + this.writeEntityToNBT(tagCompund); if (this.vehicle != null && !(this.isPlayer())) { - TagObject mount = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); - if (this.vehicle.writeMount(mount)) + if (this.vehicle.writeMountToNBT(nbttagcompound)) { - tag.setObject("Riding", mount); + tagCompund.setTag("Riding", nbttagcompound); } } } /** - * Reads the entity from tags (calls an abstract helper method to read specialized data) + * Reads the entity from NBT (calls an abstract helper method to read specialized data) */ - public void readTags(TagObject tag) + public void readFromNBT(NBTTagCompound tagCompund) { -// if(tagCompund.hasLong("PersistID")) +// if(tagCompund.hasKey("PersistID", 4)) // this.setPersistentId(tagCompund.getLong("PersistID")); // this.setTag(tagCompund.getString("ObjectTag")); - this.motionX = tag.getDouble("MotionX"); - this.motionY = tag.getDouble("MotionY"); - this.motionZ = tag.getDouble("MotionZ"); + NBTTagList nbttaglist = tagCompund.getTagList("Pos", 6); + NBTTagList nbttaglist1 = tagCompund.getTagList("Motion", 6); + NBTTagList nbttaglist2 = tagCompund.getTagList("Rotation", 5); + this.motionX = nbttaglist1.getDoubleAt(0); + this.motionY = nbttaglist1.getDoubleAt(1); + this.motionZ = nbttaglist1.getDoubleAt(2); if (Math.abs(this.motionX) > 10.0D) { @@ -1562,32 +1563,32 @@ public abstract class Entity this.motionZ = 0.0D; } - this.prevX = this.lastTickPosX = this.posX = tag.getDouble("PosX"); - this.prevY = this.lastTickPosY = this.posY = tag.getDouble("PosY"); - this.prevZ = this.lastTickPosZ = this.posZ = tag.getDouble("PosZ"); - this.prevYaw = this.rotYaw = tag.getFloat("Yaw"); - this.prevPitch = this.rotPitch = tag.getFloat("Pitch"); + this.prevX = this.lastTickPosX = this.posX = nbttaglist.getDoubleAt(0); + this.prevY = this.lastTickPosY = this.posY = nbttaglist.getDoubleAt(1); + this.prevZ = this.lastTickPosZ = this.posZ = nbttaglist.getDoubleAt(2); + this.prevYaw = this.rotYaw = nbttaglist2.getFloatAt(0); + this.prevPitch = this.rotPitch = nbttaglist2.getFloatAt(1); this.setRotationYawHead(this.rotYaw); this.setRenderYawOffset(this.rotYaw); - this.fallDistance = tag.getFloat("FallDistance"); - this.fire = tag.getShort("Fire"); + this.fallDistance = tagCompund.getFloat("FallDistance"); + this.fire = tagCompund.getShort("Fire"); // this.setAir(tagCompund.getShort("Air")); - this.onGround = tag.getBool("OnGround"); + this.onGround = tagCompund.getBoolean("OnGround"); // this.invulnerable = tagCompund.getBoolean("Invulnerable"); // this.portalTimer = tagCompund.getInteger("PortalCooldown"); this.setPosition(this.posX, this.posY, this.posZ); this.setRotation(this.rotYaw, this.rotPitch); - if (tag.hasString("CustomName") && tag.getString("CustomName").length() > 0) + if (tagCompund.hasKey("CustomName", 8) && tagCompund.getString("CustomName").length() > 0) { - this.setCustomNameTag(tag.getString("CustomName")); + this.setCustomNameTag(tagCompund.getString("CustomName")); } // this.setAlwaysRenderNameTag(tagCompund.getBoolean("CustomNameVisible")); // this.setSilent(tagCompund.getBoolean("Silent")); - this.ignoreFall = tag.getBool("IgnoreFall"); - this.readEntity(tag); + this.ignoreFall = tagCompund.getBoolean("IgnoreFall"); + this.readEntityFromNBT(tagCompund); if (this.shouldSetPosAfterLoading()) { @@ -1609,19 +1610,49 @@ public abstract class Entity // } /** - * (abstract) Protected helper method to read subclass entity data from tags. + * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected abstract void readEntity(TagObject tag); + protected abstract void readEntityFromNBT(NBTTagCompound tagCompund); /** - * (abstract) Protected helper method to write subclass entity data to tags. + * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected abstract void writeEntity(TagObject tag); + protected abstract void writeEntityToNBT(NBTTagCompound tagCompound); public void onChunkLoad() { } + /** + * creates a NBT list from the array of doubles passed to this function + */ + protected NBTTagList newDoubleNBTList(double... numbers) + { + NBTTagList nbttaglist = new NBTTagList(); + + for (double d0 : numbers) + { + nbttaglist.appendTag(new NBTTagDouble(d0)); + } + + return nbttaglist; + } + + /** + * Returns a new NBTTagList filled with the specified floats + */ + protected NBTTagList newFloatNBTList(float... numbers) + { + NBTTagList nbttaglist = new NBTTagList(); + + for (float f : numbers) + { + nbttaglist.appendTag(new NBTTagFloat(f)); + } + + return nbttaglist; + } + public EntityItem dropItem(Item itemIn, int size) { return this.dropItemWithOffset(itemIn, size, 0.0F); @@ -1637,7 +1668,7 @@ public abstract class Entity */ public EntityItem entityDropItem(ItemStack itemStackIn, float offsetY) { - if (itemStackIn.size != 0 && itemStackIn.getItem() != null) + if (itemStackIn.stackSize != 0 && itemStackIn.getItem() != null) { EntityItem entityitem = new EntityItem(this.worldObj, this.posX, this.posY + (double)offsetY, this.posZ, itemStackIn); entityitem.setDefaultPickupDelay(); @@ -1823,7 +1854,7 @@ public abstract class Entity // } public final void teleport(Position pos) { - this.teleport(pos.x(), pos.y(), pos.z(), pos.yaw(), pos.pitch(), pos.dim()); + this.teleport(pos.x, pos.y, pos.z, pos.yaw, pos.pitch, pos.dim); } public final void teleport(BlockPos pos, int dim) { @@ -1875,7 +1906,7 @@ public abstract class Entity } } - public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) { this.setPosition(x, y, z); this.setRotation(yaw, pitch); @@ -2110,7 +2141,7 @@ public abstract class Entity */ public void onStruckByLightning(EntityLightning bolt) { - if((this.worldObj.client || Vars.damageLightning) && bolt.damage > 0) + if((this.worldObj.client || Config.damageLightning) && bolt.damage > 0) this.attackEntityFrom(DamageSource.causeLightningDamage(bolt.summoner), this.worldObj.rand.range(bolt.damage, ((bolt.damage * 3) / 2))); if(bolt.fire) { ++this.fire; @@ -2313,13 +2344,13 @@ public abstract class Entity } /** - * Prepares this entity in new dimension by copying data from entity in old dimension + * Prepares this entity in new dimension by copying NBT data from entity in old dimension */ public void copyDataFromOld(Entity entityIn) { - TagObject tag = new TagObject(); - entityIn.writeTags(tag); - this.readTags(tag); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + entityIn.writeToNBT(nbttagcompound); + this.readFromNBT(nbttagcompound); // this.portalTimer = entityIn.portalTimer; // this.portalPos = entityIn.portalPos; // this.portalVec = entityIn.portalVec; @@ -2516,6 +2547,25 @@ public abstract class Entity return Facing.getHorizontal(ExtMath.floord((double)(this.rotYaw * 4.0F / 360.0F) + 0.5D) & 3); } +// protected HoverEvent getHoverEvent() +// { +// NBTTagCompound nbttagcompound = new NBTTagCompound(); +// String s = EntityRegistry.getEntityString(this); +// nbttagcompound.setString("id", "#" + this.getId()); +// if(this.hasPersistentId()) +// nbttagcompound.setString("pid", String.format("$%016x", this.getPersistentId())); +// if(this.hasTag()) +// nbttagcompound.setString("otag", this.getTag()); +// +// if (s != null) +// { +// nbttagcompound.setString("type", s); +// } +// +// nbttagcompound.setString("name", IChatComponent.Serializer.componentToJson(this.getTypeName())); +// return new HoverEvent(HoverEvent.Action.SHOW_ENTITY, new ChatComponentText(nbttagcompound.toString())); +// } + public boolean isVisibleTo(EntityNPC player) { return true; @@ -2560,15 +2610,15 @@ public abstract class Entity return new BlockPos(this.posX, this.posY + 0.5D, this.posZ); } - public TagObject getTag() + public NBTTagCompound getNBTTagCompound() { return null; } /** - * Called when client receives entity's tags from server. + * Called when client receives entity's NBTTagCompound from server. */ - public void clientUpdateEntityTags(TagObject compound) + public void clientUpdateEntityNBT(NBTTagCompound compound) { } diff --git a/common/src/main/java/common/entity/EntityDamageSource.java b/common/src/common/entity/EntityDamageSource.java similarity index 100% rename from common/src/main/java/common/entity/EntityDamageSource.java rename to common/src/common/entity/EntityDamageSource.java diff --git a/common/src/main/java/common/entity/EntityDamageSourceIndirect.java b/common/src/common/entity/EntityDamageSourceIndirect.java similarity index 100% rename from common/src/main/java/common/entity/EntityDamageSourceIndirect.java rename to common/src/common/entity/EntityDamageSourceIndirect.java diff --git a/common/src/main/java/common/entity/EntityTrackerEntry.java b/common/src/common/entity/EntityTrackerEntry.java similarity index 83% rename from common/src/main/java/common/entity/EntityTrackerEntry.java rename to common/src/common/entity/EntityTrackerEntry.java index 1ed7535..9b3a96f 100755 --- a/common/src/main/java/common/entity/EntityTrackerEntry.java +++ b/common/src/common/entity/EntityTrackerEntry.java @@ -1,31 +1,33 @@ package common.entity; +import java.util.Collection; import java.util.List; import java.util.Set; +import common.attributes.AttributeInstance; +import common.attributes.AttributeMap; import common.collect.Sets; import common.entity.npc.EntityNPC; import common.entity.projectile.EntityArrow; import common.entity.types.EntityLiving; import common.item.ItemStack; import common.log.Log; +import common.nbt.NBTTagCompound; import common.network.Packet; -import common.packet.SPacketEntityRelMove; -import common.packet.SPacketEntityLook; -import common.packet.SPacketEntityLookMove; -import common.packet.SPacketEntityTeleport; -import common.packet.SPacketEntityHeadLook; -import common.packet.SPacketEntityAttach; -import common.packet.SPacketEntityMetadata; -import common.packet.SPacketEntityEffect; -import common.packet.SPacketUpdateEntityTags; +import common.packet.S14PacketEntity; +import common.packet.S18PacketEntityTeleport; +import common.packet.S19PacketEntityHeadLook; +import common.packet.S1BPacketEntityAttach; +import common.packet.S1CPacketEntityMetadata; +import common.packet.S1DPacketEntityEffect; +import common.packet.S20PacketEntityProperties; +import common.packet.S43PacketUpdateEntityNBT; import common.packet.SPacketEntityEquipment; import common.packet.SPacketEntityVelocity; import common.packet.SPacketSpawnMob; import common.packet.SPacketSpawnObject; import common.packet.SPacketSpawnPlayer; import common.potion.PotionEffect; -import common.tags.TagObject; import common.util.ExtMath; public class EntityTrackerEntry { @@ -94,7 +96,7 @@ public class EntityTrackerEntry { if(this.lastRiding != this.trackedEntity.vehicle || this.trackedEntity.vehicle != null && this.updateCounter % 60 == 0) { this.lastRiding = this.trackedEntity.vehicle; - this.sendPacketToTrackedPlayers(new SPacketEntityAttach(0, this.trackedEntity, this.trackedEntity.vehicle)); + this.sendPacketToTrackedPlayers(new S1BPacketEntityAttach(0, this.trackedEntity, this.trackedEntity.vehicle)); } // if(this.trackedEntity instanceof EntityFrame && this.updateCounter % 10 == 0) { @@ -139,23 +141,23 @@ public class EntityTrackerEntry { && !this.ridingEntity && this.onGround == this.trackedEntity.onGround) { if((!flag || !flag1) && !(this.trackedEntity instanceof EntityArrow)) { if(flag) { - packet1 = new SPacketEntityRelMove(this.trackedEntity.getId(), (byte)j2, (byte)k2, (byte)i, + packet1 = new S14PacketEntity.S15PacketEntityRelMove(this.trackedEntity.getId(), (byte)j2, (byte)k2, (byte)i, this.trackedEntity.onGround); } else if(flag1) { - packet1 = new SPacketEntityLook(this.trackedEntity.getId(), (byte)l1, (byte)i2, + packet1 = new S14PacketEntity.S16PacketEntityLook(this.trackedEntity.getId(), (byte)l1, (byte)i2, this.trackedEntity.onGround); } } else { - packet1 = new SPacketEntityLookMove(this.trackedEntity.getId(), (byte)j2, (byte)k2, (byte)i, + packet1 = new S14PacketEntity.S17PacketEntityLookMove(this.trackedEntity.getId(), (byte)j2, (byte)k2, (byte)i, (byte)l1, (byte)i2, this.trackedEntity.onGround); } } else { this.onGround = this.trackedEntity.onGround; this.ticksSinceLastForcedTeleport = 0; - packet1 = new SPacketEntityTeleport(this.trackedEntity.getId(), k, j1, k1, (byte)l1, (byte)i2, + packet1 = new S18PacketEntityTeleport(this.trackedEntity.getId(), k, j1, k1, (byte)l1, (byte)i2, this.trackedEntity.onGround); } } @@ -202,7 +204,7 @@ public class EntityTrackerEntry { boolean flag2 = Math.abs(j - this.encodedRotationYaw) >= 4 || Math.abs(i1 - this.encodedRotationPitch) >= 4; if(flag2) { - this.sendPacketToTrackedPlayers(new SPacketEntityLook(this.trackedEntity.getId(), (byte)j, (byte)i1, + this.sendPacketToTrackedPlayers(new S14PacketEntity.S16PacketEntityLook(this.trackedEntity.getId(), (byte)j, (byte)i1, this.trackedEntity.onGround)); this.encodedRotationYaw = j; this.encodedRotationPitch = i1; @@ -218,7 +220,7 @@ public class EntityTrackerEntry { int l = ExtMath.floorf(this.trackedEntity.getRotationYawHead() * 256.0F / 360.0F); if(Math.abs(l - this.lastHeadMotion) >= 4) { - this.sendPacketToTrackedPlayers(new SPacketEntityHeadLook(this.trackedEntity, (byte)l)); + this.sendPacketToTrackedPlayers(new S19PacketEntityHeadLook(this.trackedEntity, (byte)l)); this.lastHeadMotion = l; } @@ -237,7 +239,18 @@ public class EntityTrackerEntry { DataWatcher datawatcher = this.trackedEntity.getDataWatcher(); if(datawatcher.hasObjectChanged()) { - this.sendPacketToTrackedAndSelf(new SPacketEntityMetadata(this.trackedEntity.getId(), datawatcher, false)); + this.sendPacketToTrackedAndSelf(new S1CPacketEntityMetadata(this.trackedEntity.getId(), datawatcher, false)); + } + + if(this.trackedEntity instanceof EntityLiving) { + AttributeMap serversideattributemap = ((EntityLiving)this.trackedEntity).getAttributeMap(); + Set set = serversideattributemap.getDirty(); + + if(!set.isEmpty()) { + this.sendPacketToTrackedAndSelf(new S20PacketEntityProperties(this.trackedEntity.getId(), set)); + } + + set.clear(); } } @@ -278,13 +291,22 @@ public class EntityTrackerEntry { if(!this.trackedEntity.getDataWatcher().isBlank()) { playerMP.connection - .sendPacket(new SPacketEntityMetadata(this.trackedEntity.getId(), this.trackedEntity.getDataWatcher(), true)); + .sendPacket(new S1CPacketEntityMetadata(this.trackedEntity.getId(), this.trackedEntity.getDataWatcher(), true)); } - TagObject nbttagcompound = this.trackedEntity.getTag(); + NBTTagCompound nbttagcompound = this.trackedEntity.getNBTTagCompound(); if(nbttagcompound != null) { - playerMP.connection.sendPacket(new SPacketUpdateEntityTags(this.trackedEntity.getId(), nbttagcompound)); + playerMP.connection.sendPacket(new S43PacketUpdateEntityNBT(this.trackedEntity.getId(), nbttagcompound)); + } + + if(this.trackedEntity instanceof EntityLiving) { + AttributeMap serversideattributemap = ((EntityLiving)this.trackedEntity).getAttributeMap(); + Collection collection = serversideattributemap.getWatchedAttributes(); + + if(!collection.isEmpty()) { + playerMP.connection.sendPacket(new S20PacketEntityProperties(this.trackedEntity.getId(), collection)); + } } this.lastTrackedEntityMotionX = this.trackedEntity.motionX; @@ -300,12 +322,12 @@ public class EntityTrackerEntry { } if(this.trackedEntity.vehicle != null) { - playerMP.connection.sendPacket(new SPacketEntityAttach(0, this.trackedEntity, this.trackedEntity.vehicle)); + playerMP.connection.sendPacket(new S1BPacketEntityAttach(0, this.trackedEntity, this.trackedEntity.vehicle)); } if(this.trackedEntity instanceof EntityLiving && ((EntityLiving)this.trackedEntity).getLeashedTo() != null) { playerMP.connection.sendPacket( - new SPacketEntityAttach(1, this.trackedEntity, ((EntityLiving)this.trackedEntity).getLeashedTo())); + new S1BPacketEntityAttach(1, this.trackedEntity, ((EntityLiving)this.trackedEntity).getLeashedTo())); } if(this.trackedEntity instanceof EntityLiving) { @@ -331,7 +353,7 @@ public class EntityTrackerEntry { EntityLiving entitylivingbase = (EntityLiving)this.trackedEntity; for(PotionEffect potioneffect : entitylivingbase.getEffects()) { - playerMP.connection.sendPacket(new SPacketEntityEffect(this.trackedEntity.getId(), potioneffect)); + playerMP.connection.sendPacket(new S1DPacketEntityEffect(this.trackedEntity.getId(), potioneffect)); } } } @@ -364,7 +386,7 @@ public class EntityTrackerEntry { private Packet createSpawnPacket() { if(this.trackedEntity.dead) { - Log.TICK.warn("Erstelle Spawn-Paket für entferntes Objekt"); + Log.JNI.warn("Erstelle Spawn-Paket für entferntes Objekt"); } SPacketSpawnObject packet = null; diff --git a/common/src/main/java/common/entity/EntityType.java b/common/src/common/entity/EntityType.java similarity index 100% rename from common/src/main/java/common/entity/EntityType.java rename to common/src/common/entity/EntityType.java diff --git a/common/src/main/java/common/entity/animal/EntityBat.java b/common/src/common/entity/animal/EntityBat.java similarity index 97% rename from common/src/main/java/common/entity/animal/EntityBat.java rename to common/src/common/entity/animal/EntityBat.java index 14297ea..a6c0d96 100755 --- a/common/src/main/java/common/entity/animal/EntityBat.java +++ b/common/src/common/entity/animal/EntityBat.java @@ -8,7 +8,7 @@ import common.entity.npc.Alignment; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.SoundEvent; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BlockPos; import common.util.ExtMath; import common.world.World; @@ -248,18 +248,18 @@ public class EntityBat extends EntityLiving /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); + super.readEntityFromNBT(tagCompund); this.dataWatcher.updateObject(16, Byte.valueOf(tagCompund.getByte("BatFlags"))); } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); + super.writeEntityToNBT(tagCompound); tagCompound.setByte("BatFlags", this.dataWatcher.getWatchableObjectByte(16)); } diff --git a/common/src/common/entity/animal/EntityChicken.java b/common/src/common/entity/animal/EntityChicken.java new file mode 100755 index 0000000..aaec6ab --- /dev/null +++ b/common/src/common/entity/animal/EntityChicken.java @@ -0,0 +1,249 @@ +package common.entity.animal; + +import common.ai.EntityAIFollowParent; +import common.ai.EntityAILookIdle; +import common.ai.EntityAIMate; +import common.ai.EntityAIPanic; +import common.ai.EntityAISwimming; +import common.ai.EntityAITempt; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.attributes.Attributes; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.init.Config; +import common.init.Items; +import common.init.SoundEvent; +import common.item.Item; +import common.item.ItemStack; +import common.nbt.NBTTagCompound; +import common.util.ExtMath; +import common.world.World; + +public class EntityChicken extends EntityAnimal +{ + public float wingRotation; + public float destPos; + public float field_70884_g; + public float field_70888_h; + public float wingRotDelta = 1.0F; + + /** The time until the next egg is spawned. */ + public int timeUntilNextEgg; + public boolean chickenJockey; + + public EntityChicken(World worldIn) + { + super(worldIn); + this.setSize(0.4F, 0.7F); + this.timeUntilNextEgg = worldIn.client || Config.eggTimer <= 0 ? 1000 : this.rand.excl(Config.eggTimer, Config.eggTimer * 2); + this.tasks.addTask(0, new EntityAISwimming(this)); + this.tasks.addTask(1, new EntityAIPanic(this, 1.4D)); + this.tasks.addTask(2, new EntityAIMate(this, 1.0D)); + this.tasks.addTask(3, new EntityAITempt(this, 1.0D, Items.wheat, false)); + this.tasks.addTask(4, new EntityAIFollowParent(this, 1.1D)); + this.tasks.addTask(5, new EntityAIWander(this, 1.0D)); + this.tasks.addTask(6, new EntityAIWatchClosest(this, null, 6.0F)); + this.tasks.addTask(7, new EntityAILookIdle(this)); + } + + public float getEyeHeight() + { + return this.height; + } + + protected void applyEntityAttributes() + { + super.applyEntityAttributes(); + this.setMaxHealth(4); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.25D); + } + + /** + * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons + * use this to react to sunlight and start to burn. + */ + public void onLivingUpdate() + { + super.onLivingUpdate(); + this.field_70888_h = this.wingRotation; + this.field_70884_g = this.destPos; + this.destPos = (float)((double)this.destPos + (double)(this.onGround ? -1 : 4) * 0.3D); + this.destPos = ExtMath.clampf(this.destPos, 0.0F, 1.0F); + + if (!this.onGround && this.wingRotDelta < 1.0F) + { + this.wingRotDelta = 1.0F; + } + + this.wingRotDelta = (float)((double)this.wingRotDelta * 0.9D); + + if (!this.onGround && this.motionY < 0.0D) + { + this.motionY *= 0.6D; + } + + this.wingRotation += this.wingRotDelta * 2.0F; + + if (!this.worldObj.client && Config.eggTimer > 0 && !this.isChild() && !this.isChickenJockey() && --this.timeUntilNextEgg <= 0) + { + this.playSound(SoundEvent.PLOP, 1.0F); + this.dropItem(Items.egg, 1); + this.timeUntilNextEgg = this.rand.excl(Config.eggTimer, Config.eggTimer * 2); + } + } + + public void fall(float distance, float damageMultiplier) + { + } + + /** + * Returns the sound this mob makes while it's alive. + */ + protected SoundEvent getLivingSound() + { + return SoundEvent.CHICKEN_IDLE; + } + + /** + * Returns the sound this mob makes when it is hurt. + */ + protected SoundEvent getHurtSound() + { + return SoundEvent.CHICKEN_HIT; + } + + /** + * Returns the sound this mob makes on death. + */ + protected SoundEvent getDeathSound() + { + return SoundEvent.CHICKEN_HIT; + } + +// protected void playStepSound(BlockPos pos, Block blockIn) +// { +// this.playSound("mob.chicken.step", 0.15F, 1.0F); +// } + + protected Item getDropItem() + { + return Items.feather; + } + + /** + * Drop 0-2 items of this living's type + * + * @param wasRecentlyHit true if this this entity was recently hit by appropriate entity (generally only if player + * or tameable) + * @param lootingModifier level of enchanment to be applied to this drop + */ + protected void dropFewItems(boolean wasRecentlyHit, int lootingModifier) + { + int i = this.rand.zrange(3) + this.rand.zrange(1 + lootingModifier); + + for (int j = 0; j < i; ++j) + { + this.dropItem(Items.feather, 1); + } + + if (this.isBurning()) + { + this.dropItem(Items.cooked_chicken, 1); + } + else + { + this.dropItem(Items.chicken, 1); + } + } + + public EntityChicken createChild(EntityLiving ageable) + { + return new EntityChicken(this.worldObj); + } + + /** + * Checks if the parameter is an item which this animal can be fed to breed it (wheat, carrots or seeds depending on + * the animal type) + */ + public boolean isBreedingItem(ItemStack stack) + { + return stack != null && stack.getItem() == Items.wheat; + } + + /** + * (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound tagCompund) + { + super.readEntityFromNBT(tagCompund); + this.chickenJockey = tagCompund.getBoolean("IsChickenJockey"); + + if (tagCompund.hasKey("EggLayTime")) + { + this.timeUntilNextEgg = tagCompund.getInteger("EggLayTime"); + } + } + + /** + * Get the experience points the entity currently has. + */ + protected int getExperiencePoints(EntityNPC player) + { + return this.isChickenJockey() ? 10 : super.getExperiencePoints(player); + } + + /** + * (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound tagCompound) + { + super.writeEntityToNBT(tagCompound); + tagCompound.setBoolean("IsChickenJockey", this.chickenJockey); + tagCompound.setInteger("EggLayTime", this.timeUntilNextEgg); + } + +// /** +// * Determines if an entity can be despawned, used on idle far away entities +// */ +// protected boolean canDespawn() +// { +// return this.isChickenJockey() && this.passenger == null; +// } + + public void updateRiderPosition() + { + super.updateRiderPosition(); + float f = ExtMath.sin(this.yawOffset * (float)Math.PI / 180.0F); + float f1 = ExtMath.cos(this.yawOffset * (float)Math.PI / 180.0F); + float f2 = 0.1F; + float f3 = 0.0F; + this.passenger.setPosition(this.posX + (double)(f2 * f), this.posY + (double)(this.height * 0.5F) + this.passenger.getYOffset() + (double)f3, this.posZ - (double)(f2 * f1)); + + if (this.passenger instanceof EntityLiving) + { + ((EntityLiving)this.passenger).yawOffset = this.yawOffset; + } + } + + /** + * Determines if this chicken is a jokey with a zombie riding it. + */ + public boolean isChickenJockey() + { + return this.chickenJockey; + } + + /** + * Sets whether this chicken is a jockey or not. + */ + public void setChickenJockey(boolean jockey) + { + this.chickenJockey = jockey; + } + + public int getColor() { + return 0xdb5152; + } +} diff --git a/common/src/main/java/common/entity/animal/EntityCow.java b/common/src/common/entity/animal/EntityCow.java similarity index 96% rename from common/src/main/java/common/entity/animal/EntityCow.java rename to common/src/common/entity/animal/EntityCow.java index 4e14119..4d3df31 100755 --- a/common/src/main/java/common/entity/animal/EntityCow.java +++ b/common/src/common/entity/animal/EntityCow.java @@ -8,6 +8,7 @@ import common.ai.EntityAISwimming; import common.ai.EntityAITempt; import common.ai.EntityAIWander; import common.ai.EntityAIWatchClosest; +import common.attributes.Attributes; import common.entity.npc.EntityNPC; import common.entity.types.EntityAnimal; import common.entity.types.EntityLiving; @@ -39,7 +40,7 @@ public class EntityCow extends EntityAnimal { super.applyEntityAttributes(); this.setMaxHealth(10); - this.setSpeedBase(0.20000000298023224f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.20000000298023224D); } /** @@ -124,7 +125,7 @@ public class EntityCow extends EntityAnimal if (itemstack != null && itemstack.getItem() == Items.bucket /* && !player.creative */ && !this.isChild()) { - if (itemstack.size-- == 1) + if (itemstack.stackSize-- == 1) { player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(Items.milk_bucket)); } diff --git a/common/src/main/java/common/entity/animal/EntityDragon.java b/common/src/common/entity/animal/EntityDragon.java similarity index 99% rename from common/src/main/java/common/entity/animal/EntityDragon.java rename to common/src/common/entity/animal/EntityDragon.java index 04bb342..b02ea8e 100755 --- a/common/src/main/java/common/entity/animal/EntityDragon.java +++ b/common/src/common/entity/animal/EntityDragon.java @@ -10,12 +10,11 @@ import common.entity.npc.Alignment; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.entity.types.IEntityMultiPart; +import common.init.Config; import common.init.SoundEvent; import common.model.ParticleType; -import common.potion.Potion; import common.util.ExtMath; import common.util.Vec3; -import common.vars.Vars; import common.world.AWorldClient; import common.world.World; @@ -57,10 +56,6 @@ public class EntityDragon extends EntityLiving implements IEntityMultiPart return true; } - public boolean isPotionApplicable(Potion potion, int amplifier) { - return false; - } - protected void applyEntityAttributes() { super.applyEntityAttributes(); @@ -134,7 +129,7 @@ public class EntityDragon extends EntityLiving implements IEntityMultiPart this.rotYaw = ExtMath.wrapf(this.rotYaw); // if (this.isAIDisabled() || - if(!this.worldObj.client && !Vars.mobTick) // ) + if(!this.worldObj.client && !Config.mobTick) // ) { this.animTime = 0.5F; } @@ -287,7 +282,7 @@ public class EntityDragon extends EntityLiving implements IEntityMultiPart { this.collideWithEntities(this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.dragonPartWing1.getEntityBoundingBox().expand(4.0D, 2.0D, 4.0D).offset(0.0D, -2.0D, 0.0D))); this.collideWithEntities(this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.dragonPartWing2.getEntityBoundingBox().expand(4.0D, 2.0D, 4.0D).offset(0.0D, -2.0D, 0.0D))); - if(Vars.damageMobs) + if(Config.damageMobs) this.attackEntitiesInList(this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.dragonPartHead.getEntityBoundingBox().expand(1.0D, 1.0D, 1.0D))); } diff --git a/common/src/main/java/common/entity/animal/EntityDragonPart.java b/common/src/common/entity/animal/EntityDragonPart.java similarity index 91% rename from common/src/main/java/common/entity/animal/EntityDragonPart.java rename to common/src/common/entity/animal/EntityDragonPart.java index 74ce40a..c78dc53 100755 --- a/common/src/main/java/common/entity/animal/EntityDragonPart.java +++ b/common/src/common/entity/animal/EntityDragonPart.java @@ -4,7 +4,7 @@ import common.entity.DamageSource; import common.entity.Entity; import common.entity.EntityType; import common.entity.types.IEntityMultiPart; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; public class EntityDragonPart extends Entity { @@ -27,14 +27,14 @@ public class EntityDragonPart extends Entity /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntity(TagObject tagCompund) + protected void readEntityFromNBT(NBTTagCompound tagCompund) { } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntity(TagObject tagCompound) + protected void writeEntityToNBT(NBTTagCompound tagCompound) { } diff --git a/common/src/main/java/common/entity/animal/EntityHorse.java b/common/src/common/entity/animal/EntityHorse.java similarity index 90% rename from common/src/main/java/common/entity/animal/EntityHorse.java rename to common/src/common/entity/animal/EntityHorse.java index e58770d..b26f87e 100755 --- a/common/src/main/java/common/entity/animal/EntityHorse.java +++ b/common/src/common/entity/animal/EntityHorse.java @@ -10,15 +10,17 @@ import common.ai.EntityAIRunAroundLikeCrazy; import common.ai.EntityAISwimming; import common.ai.EntityAIWander; import common.ai.EntityAIWatchClosest; +import common.attributes.AttributeInstance; +import common.attributes.Attributes; import common.block.Block; import common.block.SoundType; -import common.collect.Lists; import common.entity.DamageSource; import common.entity.Entity; import common.entity.npc.EntityNPC; import common.entity.types.EntityAnimal; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.init.Config; import common.init.ItemRegistry; import common.init.Items; import common.init.SoundEvent; @@ -28,14 +30,15 @@ import common.inventory.InventoryBasic; import common.item.Item; import common.item.ItemMonsterPlacer; import common.item.ItemStack; +import common.material.Material; import common.model.ParticleType; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.pathfinding.PathNavigateGround; import common.potion.Potion; -import common.tags.TagObject; -import java.util.List; import common.util.BlockPos; import common.util.ExtMath; -import common.vars.Vars; +import common.world.AWorldServer; import common.world.World; public class EntityHorse extends EntityAnimal implements IInvBasic @@ -106,7 +109,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic this.dataWatcher.addObject(16, Integer.valueOf(0)); this.dataWatcher.addObject(19, Byte.valueOf((byte)0)); this.dataWatcher.addObject(20, Integer.valueOf(0)); - this.dataWatcher.addObject(21, 0.7f); +// this.dataWatcher.addObject(21, String.valueOf((Object)"")); this.dataWatcher.addObject(22, Integer.valueOf(0)); } @@ -388,7 +391,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { int i = ExtMath.floord(this.posX); int j = ExtMath.floord(this.posZ); - this.worldObj.getBiomeGenForCoords(new BlockPos(i, 0, j)); + ((AWorldServer)this.worldObj).getBiomeGenForCoords(new BlockPos(i, 0, j)); return true; } @@ -423,7 +426,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (i > 0) { - if(Vars.damageFall) { + if(Config.damageFall) { this.attackEntityFrom(DamageSource.fall, i); if (this.passenger != null) @@ -434,7 +437,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic Block block = this.worldObj.getState(new BlockPos(this.posX, this.posY - 0.2D - (double)this.prevYaw, this.posZ)).getBlock(); - if (block != Blocks.air) // && !this.isSilent()) + if (block.getMaterial() != Material.air) // && !this.isSilent()) { SoundType block$soundtype = block.sound; if(block$soundtype.getStepSound() != null) @@ -549,14 +552,9 @@ public class EntityHorse extends EntityAnimal implements IInvBasic return (EntityHorse)entity; } - public float getHorseJumpStrength() + public double getHorseJumpStrength() { - return this.dataWatcher.getWatchableObjectFloat(21); - } - - public void setHorseJumpStrength(float value) - { - this.dataWatcher.updateObject(21, value); + return this.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).getAttributeValue(); } /** @@ -666,8 +664,9 @@ public class EntityHorse extends EntityAnimal implements IInvBasic protected void applyEntityAttributes() { super.applyEntityAttributes(); + this.getAttributeMap().registerAttribute(Attributes.HORSE_JUMP_STRENGTH); this.setMaxHealth(53); - this.setSpeedBase(0.22499999403953552f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.22499999403953552D); } /** @@ -791,7 +790,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (!this.worldObj.client && (this.passenger == null || this.passenger == playerEntity) && this.isTame()) { this.horseChest.setCustomName(this.getName()); - playerEntity.displayEntityGui(this, this.horseChest); + playerEntity.displayGUIHorse(this, this.horseChest); } } @@ -961,7 +960,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (flag) { - if (/* !player.creative && */ --itemstack.size == 0) + if (/* !player.creative && */ --itemstack.stackSize == 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } @@ -1356,7 +1355,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (!this.worldObj.client) { - this.setAIMoveSpeed(this.getMovementSpeed()); + this.setAIMoveSpeed((float)this.getEntityAttribute(Attributes.MOVEMENT_SPEED).getAttributeValue()); super.moveEntityWithHeading(strafe, forward); } @@ -1390,23 +1389,22 @@ public class EntityHorse extends EntityAnimal implements IInvBasic /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setBool("EatingHaystack", this.isEatingHaystack()); - tagCompound.setBool("ChestedHorse", this.isChested()); - tagCompound.setBool("HasReproduced", this.getHasReproduced()); - tagCompound.setBool("Bred", this.isBreeding()); - tagCompound.setInt("Type", this.getHorseType()); - tagCompound.setInt("Variant", this.getHorseVariant()); - tagCompound.setInt("Temper", this.getTemper()); - tagCompound.setBool("Tame", this.isTame()); - tagCompound.setFloat("JumpStrength", this.getHorseJumpStrength()); + super.writeEntityToNBT(tagCompound); + tagCompound.setBoolean("EatingHaystack", this.isEatingHaystack()); + tagCompound.setBoolean("ChestedHorse", this.isChested()); + tagCompound.setBoolean("HasReproduced", this.getHasReproduced()); + tagCompound.setBoolean("Bred", this.isBreeding()); + tagCompound.setInteger("Type", this.getHorseType()); + tagCompound.setInteger("Variant", this.getHorseVariant()); + tagCompound.setInteger("Temper", this.getTemper()); + tagCompound.setBoolean("Tame", this.isTame()); // tagCompound.setString("Owner", this.getOwnerId()); if (this.isChested()) { - List nbttaglist = Lists.newArrayList(); + NBTTagList nbttaglist = new NBTTagList(); for (int i = 2; i < this.horseChest.getSizeInventory(); ++i) { @@ -1414,45 +1412,44 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (itemstack != null) { - TagObject nbttagcompound = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setByte("Slot", (byte)i); - itemstack.writeTags(nbttagcompound); - nbttaglist.add(nbttagcompound); + itemstack.writeToNBT(nbttagcompound); + nbttaglist.appendTag(nbttagcompound); } } - tagCompound.setList("Items", nbttaglist); + tagCompound.setTag("Items", nbttaglist); } if (this.horseChest.getStackInSlot(1) != null) { - tagCompound.setObject("ArmorItem", this.horseChest.getStackInSlot(1).writeTags(new TagObject())); + tagCompound.setTag("ArmorItem", this.horseChest.getStackInSlot(1).writeToNBT(new NBTTagCompound())); } if (this.horseChest.getStackInSlot(0) != null) { - tagCompound.setObject("SaddleItem", this.horseChest.getStackInSlot(0).writeTags(new TagObject())); + tagCompound.setTag("SaddleItem", this.horseChest.getStackInSlot(0).writeToNBT(new NBTTagCompound())); } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.setEatingHaystack(tagCompund.getBool("EatingHaystack")); - this.setBreeding(tagCompund.getBool("Bred")); - this.setChested(tagCompund.getBool("ChestedHorse")); - this.setHasReproduced(tagCompund.getBool("HasReproduced")); - this.setHorseType(tagCompund.getInt("Type")); - this.setHorseVariant(tagCompund.getInt("Variant")); - this.setTemper(tagCompund.getInt("Temper")); - this.setHorseTamed(tagCompund.getBool("Tame")); - this.setHorseJumpStrength(tagCompund.getFloat("JumpStrength")); + super.readEntityFromNBT(tagCompund); + this.setEatingHaystack(tagCompund.getBoolean("EatingHaystack")); + this.setBreeding(tagCompund.getBoolean("Bred")); + this.setChested(tagCompund.getBoolean("ChestedHorse")); + this.setHasReproduced(tagCompund.getBoolean("HasReproduced")); + this.setHorseType(tagCompund.getInteger("Type")); + this.setHorseVariant(tagCompund.getInteger("Variant")); + this.setTemper(tagCompund.getInteger("Temper")); + this.setHorseTamed(tagCompund.getBoolean("Tame")); // String s = ""; // -// if (tagCompund.hasString("Owner")) +// if (tagCompund.hasKey("Owner", 8)) // { // s = tagCompund.getString("Owner"); // } @@ -1462,33 +1459,33 @@ public class EntityHorse extends EntityAnimal implements IInvBasic // this.setOwnerId(s); // } -// AttributeInstance iattributeinstance = this.getAttributeMap().getAttributeInstanceByName("Speed"); -// -// if (iattributeinstance != null) -// { -// this.getEntityAttribute(Attribute.MOVEMENT_SPEED).setBaseValue(iattributeinstance.getBaseValue() * 0.25D); -// } + AttributeInstance iattributeinstance = this.getAttributeMap().getAttributeInstanceByName("Speed"); + + if (iattributeinstance != null) + { + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(iattributeinstance.getBaseValue() * 0.25D); + } if (this.isChested()) { - List nbttaglist = tagCompund.getList("Items"); + NBTTagList nbttaglist = tagCompund.getTagList("Items", 10); this.initHorseChest(); - for (int i = 0; i < nbttaglist.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject nbttagcompound = nbttaglist.get(i); + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); int j = nbttagcompound.getByte("Slot") & 255; if (j >= 2 && j < this.horseChest.getSizeInventory()) { - this.horseChest.setInventorySlotContents(j, ItemStack.readFromTag(nbttagcompound)); + this.horseChest.setInventorySlotContents(j, ItemStack.loadItemStackFromNBT(nbttagcompound)); } } } - if (tagCompund.hasObject("ArmorItem")) + if (tagCompund.hasKey("ArmorItem", 10)) { - ItemStack itemstack = ItemStack.readFromTag(tagCompund.getObject("ArmorItem")); + ItemStack itemstack = ItemStack.loadItemStackFromNBT(tagCompund.getCompoundTag("ArmorItem")); if (itemstack != null && isArmorItem(itemstack.getItem())) { @@ -1496,16 +1493,16 @@ public class EntityHorse extends EntityAnimal implements IInvBasic } } - if (tagCompund.hasObject("SaddleItem")) + if (tagCompund.hasKey("SaddleItem", 10)) { - ItemStack itemstack1 = ItemStack.readFromTag(tagCompund.getObject("SaddleItem")); + ItemStack itemstack1 = ItemStack.loadItemStackFromNBT(tagCompund.getCompoundTag("SaddleItem")); if (itemstack1 != null && itemstack1.getItem() == Items.saddle) { this.horseChest.setInventorySlotContents(0, itemstack1); } } - else if (tagCompund.getBool("Saddle")) + else if (tagCompund.getBoolean("Saddle")) { this.horseChest.setInventorySlotContents(0, new ItemStack(Items.saddle)); } @@ -1597,12 +1594,12 @@ public class EntityHorse extends EntityAnimal implements IInvBasic } entityhorse1.setHorseType(k); - int d1 = this.getMaxHealth() + ageable.getMaxHealth() + this.getModifiedMaxHealth(); + int d1 = this.getRawMaxHealth() + ageable.getRawMaxHealth() + this.getModifiedMaxHealth(); entityhorse1.setMaxHealth(d1 / 3); - float d2 = this.getHorseJumpStrength() + entityhorse.getHorseJumpStrength() + this.getModifiedJumpStrength(); - entityhorse1.setHorseJumpStrength(d2 / 3.0f); - float d0 = this.getSpeedBase() + ageable.getSpeedBase() + this.getModifiedMovementSpeed(); - entityhorse1.setSpeedBase(d0 / 3.0f); + double d2 = this.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).getBaseValue() + ageable.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).getBaseValue() + this.getModifiedJumpStrength(); + entityhorse1.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).setBaseValue(d2 / 3.0D); + double d0 = this.getEntityAttribute(Attributes.MOVEMENT_SPEED).getBaseValue() + ageable.getEntityAttribute(Attributes.MOVEMENT_SPEED).getBaseValue() + this.getModifiedMovementSpeed(); + entityhorse1.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(d0 / 3.0D); return entityhorse1; } @@ -1652,26 +1649,26 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (i == 0) { - this.setSpeedBase(this.getModifiedMovementSpeed()); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(this.getModifiedMovementSpeed()); } else { - this.setSpeedBase(0.17499999701976776f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.17499999701976776D); } } else { this.setMaxHealth(15); - this.setSpeedBase(0.20000000298023224f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.20000000298023224D); } if (i != 2 && i != 1) { - this.setHorseJumpStrength(this.getModifiedJumpStrength()); + this.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).setBaseValue(this.getModifiedJumpStrength()); } else { - this.setHorseJumpStrength(0.5f); + this.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).setBaseValue(0.5D); } this.setHealth(this.getMaxHealth()); @@ -1780,17 +1777,17 @@ public class EntityHorse extends EntityAnimal implements IInvBasic /** * Returns randomized jump strength */ - private float getModifiedJumpStrength() + private double getModifiedJumpStrength() { - return 0.4000000059604645f + this.rand.floatv() * 0.2f + this.rand.floatv() * 0.2f + this.rand.floatv() * 0.2f; + return 0.4000000059604645D + this.rand.doublev() * 0.2D + this.rand.doublev() * 0.2D + this.rand.doublev() * 0.2D; } /** * Returns randomized movement speed */ - private float getModifiedMovementSpeed() + private double getModifiedMovementSpeed() { - return (0.44999998807907104f + this.rand.floatv() * 0.3f + this.rand.floatv() * 0.3f + this.rand.floatv() * 0.3f) * 0.25f; + return (0.44999998807907104D + this.rand.doublev() * 0.3D + this.rand.doublev() * 0.3D + this.rand.doublev() * 0.3D) * 0.25D; } /** diff --git a/common/src/main/java/common/entity/animal/EntityMooshroom.java b/common/src/common/entity/animal/EntityMooshroom.java similarity index 98% rename from common/src/main/java/common/entity/animal/EntityMooshroom.java rename to common/src/common/entity/animal/EntityMooshroom.java index 76747d4..b87afa5 100755 --- a/common/src/main/java/common/entity/animal/EntityMooshroom.java +++ b/common/src/common/entity/animal/EntityMooshroom.java @@ -30,7 +30,7 @@ public class EntityMooshroom extends EntityCow if (itemstack != null && itemstack.getItem() == Items.bowl && !this.isChild()) { - if (itemstack.size == 1) + if (itemstack.stackSize == 1) { player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(Items.mushroom_stew)); return true; diff --git a/common/src/main/java/common/entity/animal/EntityMouse.java b/common/src/common/entity/animal/EntityMouse.java similarity index 86% rename from common/src/main/java/common/entity/animal/EntityMouse.java rename to common/src/common/entity/animal/EntityMouse.java index 2564c4d..e304a0f 100755 --- a/common/src/main/java/common/entity/animal/EntityMouse.java +++ b/common/src/common/entity/animal/EntityMouse.java @@ -10,6 +10,8 @@ import common.ai.EntityAISwimming; import common.ai.EntityAITempt; import common.ai.EntityAIWander; import common.ai.EntityAIWatchClosest; +import common.attributes.AttributeInstance; +import common.attributes.Attributes; import common.block.Block; import common.entity.npc.EntityNPC; import common.entity.types.EntityAnimal; @@ -44,7 +46,7 @@ public class EntityMouse extends EntityAnimal { protected void applyEntityAttributes() { super.applyEntityAttributes(); this.setMaxHealth(1); - this.setSpeedBase(0.25f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.25D); } // protected String getLivingSound() { @@ -116,8 +118,12 @@ public class EntityMouse extends EntityAnimal { public void setCustomNameTag(String name) { super.setCustomNameTag(name); - if(this.worldObj != null && !this.worldObj.client) - this.setSpeedBase(name.equals("Gonzales") || name.equals("Gonzalez") ? 0.5f : 0.25f); + if(this.worldObj != null && !this.worldObj.client) { + AttributeInstance speed = this.getEntityAttribute(Attributes.MOVEMENT_SPEED); + speed.removeModifier(Attributes.MOUSE_SPEEDY_MOD); + if(name.equals("Gonzales") || name.equals("Gonzalez")) + speed.applyModifier(Attributes.MOUSE_SPEEDY_MOD); + } } public int getColor() { diff --git a/common/src/main/java/common/entity/animal/EntityOcelot.java b/common/src/common/entity/animal/EntityOcelot.java similarity index 94% rename from common/src/main/java/common/entity/animal/EntityOcelot.java rename to common/src/common/entity/animal/EntityOcelot.java index 67483ae..12d53c2 100755 --- a/common/src/main/java/common/entity/animal/EntityOcelot.java +++ b/common/src/common/entity/animal/EntityOcelot.java @@ -13,6 +13,7 @@ import common.ai.EntityAITargetNonTamed; import common.ai.EntityAITempt; import common.ai.EntityAIWander; import common.ai.EntityAIWatchClosest; +import common.attributes.Attributes; import common.entity.DamageSource; import common.entity.Entity; import common.entity.npc.Alignment; @@ -20,13 +21,13 @@ import common.entity.npc.EntityNPC; import common.entity.types.EntityAnimal; import common.entity.types.EntityLiving; import common.entity.types.EntityTameable; +import common.init.Config; import common.init.Items; import common.init.SoundEvent; import common.item.Item; import common.item.ItemStack; +import common.nbt.NBTTagCompound; import common.pathfinding.PathNavigateGround; -import common.tags.TagObject; -import common.vars.Vars; import common.world.World; public class EntityOcelot extends EntityTameable @@ -112,7 +113,7 @@ public class EntityOcelot extends EntityTameable { super.applyEntityAttributes(); this.setMaxHealth(10); - this.setSpeedBase(0.30000001192092896f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.30000001192092896D); } public void fall(float distance, float damageMultiplier) @@ -122,19 +123,19 @@ public class EntityOcelot extends EntityTameable /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setInt("CatType", this.getTameSkin()); + super.writeEntityToNBT(tagCompound); + tagCompound.setInteger("CatType", this.getTameSkin()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.setTameSkin(tagCompund.getInt("CatType")); + super.readEntityFromNBT(tagCompund); + this.setTameSkin(tagCompund.getInteger("CatType")); } /** @@ -176,7 +177,7 @@ public class EntityOcelot extends EntityTameable public boolean attackEntityAsMob(Entity entityIn) { - if(!this.worldObj.client && !Vars.damageMobs) + if(!this.worldObj.client && !Config.damageMobs) return false; return entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), 3); } @@ -226,10 +227,10 @@ public class EntityOcelot extends EntityTameable { // if (!player.creative) // { - --itemstack.size; + --itemstack.stackSize; // } - if (itemstack.size <= 0) + if (itemstack.stackSize <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } diff --git a/common/src/main/java/common/entity/animal/EntityPig.java b/common/src/common/entity/animal/EntityPig.java similarity index 93% rename from common/src/main/java/common/entity/animal/EntityPig.java rename to common/src/common/entity/animal/EntityPig.java index 512e6f7..52e04b3 100755 --- a/common/src/main/java/common/entity/animal/EntityPig.java +++ b/common/src/common/entity/animal/EntityPig.java @@ -9,6 +9,7 @@ import common.ai.EntityAISwimming; import common.ai.EntityAITempt; import common.ai.EntityAIWander; import common.ai.EntityAIWatchClosest; +import common.attributes.Attributes; import common.entity.npc.EntityNPC; import common.entity.types.EntityAnimal; import common.entity.types.EntityLiving; @@ -16,8 +17,8 @@ import common.init.Items; import common.init.SoundEvent; import common.item.Item; import common.item.ItemStack; +import common.nbt.NBTTagCompound; import common.pathfinding.PathNavigateGround; -import common.tags.TagObject; import common.world.World; public class EntityPig extends EntityAnimal @@ -46,7 +47,7 @@ public class EntityPig extends EntityAnimal { super.applyEntityAttributes(); this.setMaxHealth(10); - this.setSpeedBase(0.25f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.25D); } /** @@ -68,19 +69,19 @@ public class EntityPig extends EntityAnimal /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setBool("Saddle", this.getSaddled()); + super.writeEntityToNBT(tagCompound); + tagCompound.setBoolean("Saddle", this.getSaddled()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.setSaddled(tagCompund.getBool("Saddle")); + super.readEntityFromNBT(tagCompund); + this.setSaddled(tagCompund.getBoolean("Saddle")); } /** diff --git a/common/src/main/java/common/entity/animal/EntityRabbit.java b/common/src/common/entity/animal/EntityRabbit.java similarity index 93% rename from common/src/main/java/common/entity/animal/EntityRabbit.java rename to common/src/common/entity/animal/EntityRabbit.java index 4b34e12..93ce36f 100755 --- a/common/src/main/java/common/entity/animal/EntityRabbit.java +++ b/common/src/common/entity/animal/EntityRabbit.java @@ -15,8 +15,9 @@ import common.ai.EntityAIWander; import common.ai.EntityAIWatchClosest; import common.ai.EntityJumpHelper; import common.ai.EntityMoveHelper; +import common.attributes.Attributes; import common.block.Block; -import common.block.foliage.BlockTallGrass; +import common.block.BlockTallGrass; import common.entity.DamageSource; import common.entity.Entity; import common.entity.npc.Alignment; @@ -25,21 +26,21 @@ import common.entity.types.EntityAnimal; import common.entity.types.EntityLiving; import common.init.BlockRegistry; import common.init.Blocks; +import common.init.Config; import common.init.ItemRegistry; import common.init.Items; import common.init.SoundEvent; import common.item.Item; import common.item.ItemStack; import common.model.ParticleType; +import common.nbt.NBTTagCompound; import common.pathfinding.PathEntity; import common.pathfinding.PathNavigateGround; import common.potion.Potion; import common.potion.PotionEffect; -import common.tags.TagObject; import common.util.BlockPos; import common.util.ExtMath; import common.util.Vec3; -import common.vars.Vars; import common.world.State; import common.world.World; @@ -84,10 +85,6 @@ public class EntityRabbit extends EntityAnimal { return this.moveHelper.isUpdating() && this.moveHelper.getY() > this.posY + 0.5D ? 0.5F : this.moveType.getUpwardsMotion(); } - public boolean isPotionApplicable(Potion potion, int amplifier) { - return super.isPotionApplicable(potion, amplifier) || potion == Potion.JUMP; - } - public void setMoveType(EntityRabbit.EnumMoveType type) { this.moveType = type; } @@ -198,19 +195,19 @@ public class EntityRabbit extends EntityAnimal { protected void applyEntityAttributes() { super.applyEntityAttributes(); this.setMaxHealth(5); - this.setSpeedBase(0.30000001192092896f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.30000001192092896D); } - public void writeEntity(TagObject tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setInt("RabbitType", this.getRabbitType()); - tagCompound.setInt("MoreCarrotTicks", this.foodCooldown); + public void writeEntityToNBT(NBTTagCompound tagCompound) { + super.writeEntityToNBT(tagCompound); + tagCompound.setInteger("RabbitType", this.getRabbitType()); + tagCompound.setInteger("MoreCarrotTicks", this.foodCooldown); } - public void readEntity(TagObject tagCompund) { - super.readEntity(tagCompund); - this.setRabbitType(tagCompund.getInt("RabbitType")); - this.foodCooldown = tagCompund.getInt("MoreCarrotTicks"); + public void readEntityFromNBT(NBTTagCompound tagCompund) { + super.readEntityFromNBT(tagCompund); + this.setRabbitType(tagCompund.getInteger("RabbitType")); + this.foodCooldown = tagCompund.getInteger("MoreCarrotTicks"); } // protected String getJumpingSound() { @@ -230,7 +227,7 @@ public class EntityRabbit extends EntityAnimal { } public boolean attackEntityAsMob(Entity entityIn) { - if(!this.worldObj.client && !Vars.damageMobs) + if(!this.worldObj.client && !Config.damageMobs) return false; if(this.getRabbitType() == 99) { // this.playSound("mob.attack", 1.0F, (this.rand.floatv() - this.rand.floatv()) * 0.2F + 1.0F); @@ -305,7 +302,7 @@ public class EntityRabbit extends EntityAnimal { public Object onInitialSpawn(Object livingdata) { livingdata = super.onInitialSpawn(livingdata); - int type = Vars.killerBunnyChance > 0 && this.rand.chance(Vars.killerBunnyChance) ? 99 : this.rand.zrange(TYPES); + int type = Config.killerBunnyChance > 0 && this.rand.chance(Config.killerBunnyChance) ? 99 : this.rand.zrange(TYPES); boolean typeSet = false; if(livingdata instanceof EntityRabbit.RabbitTypeData) { type = ((EntityRabbit.RabbitTypeData)livingdata).typeData; @@ -337,7 +334,7 @@ public class EntityRabbit extends EntityAnimal { this.foodCooldown = this.rand.excl(10, this.isChild() ? 20 : 50); if(this.isChild()) this.grow(this.rand.range(250, 350)); - if(Vars.rabbitMateChance > 0 && this.rand.chance(Vars.rabbitMateChance) && this.getGrowingAge() == 0 && !this.isInLove() && + if(Config.rabbitMateChance > 0 && this.rand.chance(Config.rabbitMateChance) && this.getGrowingAge() == 0 && !this.isInLove() && !this.worldObj.getEntitiesWithinAABB(EntityRabbit.class, this.getEntityBoundingBox().expand(15.0f, 15.0f, 15.0f), new Predicate() { public boolean test(EntityRabbit entity) { return entity != EntityRabbit.this && entity.getGrowingAge() == 0; @@ -426,7 +423,7 @@ public class EntityRabbit extends EntityAnimal { public boolean shouldExecute() { if(this.runDelay <= 0) { - if(!Vars.mobGrief) + if(!Config.mobGrief) return false; this.foodFound = false; this.isHungry = this.entity.canEatMore(); @@ -459,10 +456,10 @@ public class EntityRabbit extends EntityAnimal { (double)this.destinationBlock.getZ() + 0.5D, 10.0F, (float)this.entity.getVerticalFaceSpeed()); if(this.getIsAboveDestination()) { World world = this.entity.worldObj; - BlockPos pos = Vars.rabidRabbits ? this.destinationBlock : this.destinationBlock.up(); + BlockPos pos = Config.rabidRabbits ? this.destinationBlock : this.destinationBlock.up(); State state = world.getState(pos); // Block block = iblockstate.getBlock(); - if(this.foodFound && canEat(state) && Vars.mobGrief) // block instanceof BlockCarrot && ((Integer)iblockstate.getValue(BlockCarrot.AGE)).intValue() == 7) { + if(this.foodFound && canEat(state) && Config.mobGrief) // block instanceof BlockCarrot && ((Integer)iblockstate.getValue(BlockCarrot.AGE)).intValue() == 7) { this.entity.consumeBlock(pos, state); this.foodFound = false; this.runDelay = 10; @@ -486,7 +483,7 @@ public class EntityRabbit extends EntityAnimal { private static boolean canEat(State state) { Block block = state.getBlock(); - if(Vars.rabidRabbits) + if(Config.rabidRabbits) return block != Blocks.bedrock; return block == Blocks.carrot || block == Blocks.potato || block == Blocks.wheat || block == Blocks.brown_mushroom || block == Blocks.flower || block == Blocks.blue_mushroom || diff --git a/common/src/main/java/common/entity/animal/EntitySheep.java b/common/src/common/entity/animal/EntitySheep.java similarity index 95% rename from common/src/main/java/common/entity/animal/EntitySheep.java rename to common/src/common/entity/animal/EntitySheep.java index a2250da..ab6c7ba 100755 --- a/common/src/main/java/common/entity/animal/EntitySheep.java +++ b/common/src/common/entity/animal/EntitySheep.java @@ -11,6 +11,7 @@ import common.ai.EntityAISwimming; import common.ai.EntityAITempt; import common.ai.EntityAIWander; import common.ai.EntityAIWatchClosest; +import common.attributes.Attributes; import common.biome.Biome; import common.collect.Maps; import common.color.DyeColor; @@ -28,10 +29,11 @@ import common.inventory.InventoryCrafting; import common.item.Item; import common.item.ItemShears; import common.item.ItemStack; +import common.nbt.NBTTagCompound; import common.pathfinding.PathNavigateGround; import common.rng.Random; -import common.tags.TagObject; import common.util.ExtMath; +import common.world.AWorldServer; import common.world.World; public class EntitySheep extends EntityAnimal @@ -103,7 +105,7 @@ public class EntitySheep extends EntityAnimal { super.applyEntityAttributes(); this.setMaxHealth(8); - this.setSpeedBase(0.23000000417232513f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.23000000417232513D); } protected void entityInit() @@ -209,20 +211,20 @@ public class EntitySheep extends EntityAnimal /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setBool("Sheared", this.getSheared()); + super.writeEntityToNBT(tagCompound); + tagCompound.setBoolean("Sheared", this.getSheared()); tagCompound.setByte("Color", (byte)this.getFleeceColor().getMetadata()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.setSheared(tagCompund.getBool("Sheared")); + super.readEntityFromNBT(tagCompund); + this.setSheared(tagCompund.getBoolean("Sheared")); this.setFleeceColor(DyeColor.byMetadata(tagCompund.getByte("Color"))); } @@ -329,7 +331,7 @@ public class EntitySheep extends EntityAnimal * This function applies the benefits of growing back wool and faster growing up to the acting entity. (This * function is used in the AIEatGrass) */ - public void eatGrass() + public void eatGrassBonus() { this.setSheared(false); @@ -346,7 +348,7 @@ public class EntitySheep extends EntityAnimal public Object onInitialSpawn(Object livingdata) { livingdata = super.onInitialSpawn(livingdata); - this.setFleeceColor(getRandomSheepColor(this.worldObj.rand, this.worldObj.getBiomeGenForCoords(this.getPosition()))); + this.setFleeceColor(getRandomSheepColor(this.worldObj.rand, ((AWorldServer)this.worldObj).getBiomeGenForCoords(this.getPosition()))); return livingdata; } diff --git a/common/src/main/java/common/entity/animal/EntitySquid.java b/common/src/common/entity/animal/EntitySquid.java similarity index 100% rename from common/src/main/java/common/entity/animal/EntitySquid.java rename to common/src/common/entity/animal/EntitySquid.java diff --git a/common/src/main/java/common/entity/animal/EntityWolf.java b/common/src/common/entity/animal/EntityWolf.java similarity index 78% rename from common/src/main/java/common/entity/animal/EntityWolf.java rename to common/src/common/entity/animal/EntityWolf.java index cf694c0..c10da66 100755 --- a/common/src/main/java/common/entity/animal/EntityWolf.java +++ b/common/src/common/entity/animal/EntityWolf.java @@ -15,6 +15,7 @@ import common.ai.EntityAISwimming; import common.ai.EntityAITargetNonTamed; import common.ai.EntityAIWander; import common.ai.EntityAIWatchClosest; +import common.attributes.Attributes; import common.color.DyeColor; import common.entity.DamageSource; import common.entity.Entity; @@ -23,36 +24,21 @@ import common.entity.npc.EntityNPC; import common.entity.types.EntityAnimal; import common.entity.types.EntityLiving; import common.entity.types.EntityTameable; +import common.init.Config; import common.init.Items; import common.init.SoundEvent; import common.item.Item; import common.item.ItemFood; import common.item.ItemStack; -import common.model.ParticleType; +import common.nbt.NBTTagCompound; import common.pathfinding.PathNavigateGround; -import common.tags.TagObject; -import common.util.ExtMath; -import common.vars.Vars; import common.world.World; public class EntityWolf extends EntityTameable { - /** Float used to smooth the rotation of the wolf head */ private float headRotationCourse; private float headRotationCourseOld; - - /** true is the wolf is wet else false */ - private boolean isWet; - - /** True if the wolf is shaking else False */ - private boolean isShaking; - - /** - * This time increases while wolf is shaking and emitting water particles. - */ - private float timeWolfIsShaking; - private float prevTimeWolfIsShaking; - + public EntityWolf(World worldIn) { super(worldIn); @@ -85,8 +71,19 @@ public class EntityWolf extends EntityTameable protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setSpeedBase(0.30000001192092896f); - this.setMaxHealth(8); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.30000001192092896D); + + if (this.isTamed()) + { + this.setMaxHealth(20); + } + else + { + this.setMaxHealth(8); + } + + this.getAttributeMap().registerAttribute(Attributes.ATTACK_DAMAGE); + this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(2.0D); } /** @@ -127,21 +124,25 @@ public class EntityWolf extends EntityTameable /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setBool("Angry", this.isAngry()); + super.writeEntityToNBT(tagCompound); + tagCompound.setBoolean("Angry", this.isAngry()); tagCompound.setByte("CollarColor", (byte)this.getCollarColor().getDyeDamage()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.setAngry(tagCompund.getBool("Angry")); - this.setCollarColor(DyeColor.byDyeDamage(tagCompund.getByte("CollarColor"))); + super.readEntityFromNBT(tagCompund); + this.setAngry(tagCompund.getBoolean("Angry")); + + if (tagCompund.hasKey("CollarColor", 99)) + { + this.setCollarColor(DyeColor.byDyeDamage(tagCompund.getByte("CollarColor"))); + } } /** @@ -188,15 +189,7 @@ public class EntityWolf extends EntityTameable public void onLivingUpdate() { super.onLivingUpdate(); - - if (!this.worldObj.client && this.isWet && !this.isShaking && !this.hasPath() && this.onGround) - { - this.isShaking = true; - this.timeWolfIsShaking = 0.0F; - this.prevTimeWolfIsShaking = 0.0F; - this.worldObj.setEntityState(this, (byte)8); - } - + if (!this.worldObj.client && this.getAttackTarget() == null && this.isAngry()) { this.setAngry(false); @@ -219,79 +212,8 @@ public class EntityWolf extends EntityTameable { this.headRotationCourse += (0.0F - this.headRotationCourse) * 0.4F; } - - if (this.isWet()) - { - this.isWet = true; - this.isShaking = false; - this.timeWolfIsShaking = 0.0F; - this.prevTimeWolfIsShaking = 0.0F; - } - else if ((this.isWet || this.isShaking) && this.isShaking) - { - if (this.timeWolfIsShaking == 0.0F) - { - this.playSound(SoundEvent.WOLF_SHAKE, this.getSoundVolume()); - } - - this.prevTimeWolfIsShaking = this.timeWolfIsShaking; - this.timeWolfIsShaking += 0.05F; - - if (this.prevTimeWolfIsShaking >= 2.0F) - { - this.isWet = false; - this.isShaking = false; - this.prevTimeWolfIsShaking = 0.0F; - this.timeWolfIsShaking = 0.0F; - } - - if (this.timeWolfIsShaking > 0.4F) - { - float f = (float)this.getEntityBoundingBox().minY; - int i = (int)(ExtMath.sin((this.timeWolfIsShaking - 0.4F) * (float)Math.PI) * 7.0F); - - for (int j = 0; j < i; ++j) - { - float f1 = (this.rand.floatv() * 2.0F - 1.0F) * this.width * 0.5F; - float f2 = (this.rand.floatv() * 2.0F - 1.0F) * this.width * 0.5F; - this.worldObj.spawnParticle(ParticleType.WATER_SPLASH, this.posX + (double)f1, (double)(f + 0.8F), this.posZ + (double)f2, this.motionX, this.motionY, this.motionZ); - } - } - } } - - /** - * True if the wolf is wet - */ - public boolean isWolfWet() - { - return this.isWet; - } - - /** - * Used when calculating the amount of shading to apply while the wolf is wet. - */ - public float getShadingWhileWet(float p_70915_1_) - { - return 0.75F + (this.prevTimeWolfIsShaking + (this.timeWolfIsShaking - this.prevTimeWolfIsShaking) * p_70915_1_) / 2.0F * 0.25F; - } - - public float getShakeAngle(float p_70923_1_, float p_70923_2_) - { - float f = (this.prevTimeWolfIsShaking + (this.timeWolfIsShaking - this.prevTimeWolfIsShaking) * p_70923_1_ + p_70923_2_) / 1.8F; - - if (f < 0.0F) - { - f = 0.0F; - } - else if (f > 1.0F) - { - f = 1.0F; - } - - return ExtMath.sin(f * (float)Math.PI) * ExtMath.sin(f * (float)Math.PI * 11.0F) * 0.15F * (float)Math.PI; - } - + public float getInterestedAngle(float p_70917_1_) { return (this.headRotationCourseOld + (this.headRotationCourse - this.headRotationCourseOld) * p_70917_1_) * 0.15F * (float)Math.PI; @@ -336,9 +258,9 @@ public class EntityWolf extends EntityTameable public boolean attackEntityAsMob(Entity entityIn) { - if(!this.worldObj.client && !Vars.damageMobs) + if(!this.worldObj.client && !Config.damageMobs) return false; - boolean flag = entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), this.rand.chance(2, 3, 8)); + boolean flag = entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), ((int)this.getEntityAttribute(Attributes.ATTACK_DAMAGE).getAttributeValue())); if (flag) { @@ -348,6 +270,22 @@ public class EntityWolf extends EntityTameable return flag; } + public void setTamed(boolean tamed) + { + super.setTamed(tamed); + + if (tamed) + { + this.setMaxHealth(20); + } + else + { + this.setMaxHealth(8); + } + + this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(4.0D); + } + /** * Called when a player interacts with a mob. e.g. gets milk from a cow, gets into the saddle on a pig. */ @@ -367,12 +305,12 @@ public class EntityWolf extends EntityTameable { // if (!player.creative) // { - --itemstack.size; + --itemstack.stackSize; // } this.heal(itemfood.getHealAmount(itemstack)); - if (itemstack.size <= 0) + if (itemstack.stackSize <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } @@ -388,7 +326,7 @@ public class EntityWolf extends EntityTameable { this.setCollarColor(enumdyecolor); - if (/* !player.creative && */ --itemstack.size <= 0) + if (/* !player.creative && */ --itemstack.stackSize <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } @@ -410,10 +348,10 @@ public class EntityWolf extends EntityTameable { // if (!player.creative) // { - --itemstack.size; + --itemstack.stackSize; // } - if (itemstack.size <= 0) + if (itemstack.stackSize <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } @@ -443,21 +381,7 @@ public class EntityWolf extends EntityTameable return super.interact(player); } - - public void handleStatusUpdate(byte id) - { - if (id == 8) - { - this.isShaking = true; - this.timeWolfIsShaking = 0.0F; - this.prevTimeWolfIsShaking = 0.0F; - } - else - { - super.handleStatusUpdate(id); - } - } - + public float getTailRotation() { return this.isAngry() ? 1.5393804F : (this.isTamed() ? (0.55F - (20.0F - (float)this.dataWatcher.getWatchableObjectInt(18)) * 0.02F) * (float)Math.PI : ((float)Math.PI / 5F)); diff --git a/common/src/main/java/common/entity/effect/EntityLightning.java b/common/src/common/entity/effect/EntityLightning.java similarity index 90% rename from common/src/main/java/common/entity/effect/EntityLightning.java rename to common/src/common/entity/effect/EntityLightning.java index 04176fc..4de8d0f 100755 --- a/common/src/main/java/common/entity/effect/EntityLightning.java +++ b/common/src/common/entity/effect/EntityLightning.java @@ -6,10 +6,11 @@ import common.entity.Entity; import common.entity.types.EntityLiving; import common.entity.types.EntityWeatherEffect; import common.init.Blocks; +import common.init.Config; import common.init.SoundEvent; +import common.material.Material; import common.util.BlockPos; import common.util.BoundingBox; -import common.vars.Vars; import common.world.AWorldClient; import common.world.World; @@ -65,7 +66,7 @@ public class EntityLightning extends EntityWeatherEffect this.boltVertex = this.rand.longv(); BlockPos blockpos = new BlockPos(this); - if (!this.worldObj.client && this.fire && Vars.fire && this.worldObj.isAreaLoaded(blockpos, 10) && this.worldObj.getState(blockpos).getBlock() == Blocks.air && Blocks.fire.canPlaceBlockAt(this.worldObj, blockpos)) + if (!this.worldObj.client && this.fire && Config.fire && this.worldObj.isAreaLoaded(blockpos, 10) && this.worldObj.getState(blockpos).getBlock().getMaterial() == Material.air && Blocks.fire.canPlaceBlockAt(this.worldObj, blockpos)) { this.worldObj.setState(blockpos, Blocks.fire.getState()); } diff --git a/common/src/main/java/common/entity/item/EntityBoat.java b/common/src/common/entity/item/EntityBoat.java similarity index 97% rename from common/src/main/java/common/entity/item/EntityBoat.java rename to common/src/common/entity/item/EntityBoat.java index 1a17e85..7fb57b2 100755 --- a/common/src/main/java/common/entity/item/EntityBoat.java +++ b/common/src/common/entity/item/EntityBoat.java @@ -10,15 +10,15 @@ import common.entity.EntityType; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.init.Config; import common.init.ItemRegistry; import common.init.Items; import common.item.Item; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; -import common.vars.Vars; import common.world.World; public class EntityBoat extends Entity @@ -137,7 +137,7 @@ public class EntityBoat extends Entity this.passenger.mountEntity(this); } - if (/* !flag && */ Vars.objectDrop) + if (/* !flag && */ Config.objectDrop) { this.dropItemWithOffset(Items.boat, 1, 0.0F); } @@ -172,9 +172,9 @@ public class EntityBoat extends Entity return !this.dead; } - public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) { - if (teleport && this.passenger != null) + if (p_180426_10_ && this.passenger != null) { this.prevX = this.posX = x; this.prevY = this.posY = y; @@ -191,7 +191,7 @@ public class EntityBoat extends Entity { if (this.isBoatEmpty) { - this.boatPosRotationIncrements = 8; + this.boatPosRotationIncrements = posRotationIncrements + 5; } else { @@ -417,7 +417,7 @@ public class EntityBoat extends Entity { this.setDead(); - if (Vars.objectDrop) + if (Config.objectDrop) { for (int j1 = 0; j1 < 3; ++j1) { @@ -501,14 +501,14 @@ public class EntityBoat extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntity(TagObject tagCompound) + protected void writeEntityToNBT(NBTTagCompound tagCompound) { } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntity(TagObject tagCompund) + protected void readEntityFromNBT(NBTTagCompound tagCompund) { } @@ -548,7 +548,7 @@ public class EntityBoat extends Entity { this.setDead(); - if (Vars.objectDrop) + if (Config.objectDrop) { for (int i = 0; i < 3; ++i) { diff --git a/common/src/main/java/common/entity/item/EntityCart.java b/common/src/common/entity/item/EntityCart.java similarity index 94% rename from common/src/main/java/common/entity/item/EntityCart.java rename to common/src/common/entity/item/EntityCart.java index 612c4ce..a9222fe 100755 --- a/common/src/main/java/common/entity/item/EntityCart.java +++ b/common/src/common/entity/item/EntityCart.java @@ -1,24 +1,24 @@ package common.entity.item; import common.block.Block; -import common.block.tech.BlockRailBase; -import common.block.tech.BlockRailPowered; +import common.block.BlockRailBase; +import common.block.BlockRailPowered; import common.entity.DamageSource; import common.entity.Entity; import common.entity.EntityType; import common.entity.types.EntityLiving; import common.init.BlockRegistry; import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.item.Item; import common.item.ItemStack; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.tileentity.IWorldNameable; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; import common.util.Vec3; -import common.vars.Vars; import common.world.State; import common.world.World; @@ -188,7 +188,7 @@ public abstract class EntityCart extends Entity implements IWorldNameable { this.setDead(); - if (Vars.objectDrop) + if (Config.objectDrop) { ItemStack itemstack = new ItemStack(Items.minecart, 1); @@ -242,7 +242,7 @@ public abstract class EntityCart extends Entity implements IWorldNameable this.setDamage(this.getDamage() - 1); } - if (this.posY < (double)(-World.MAX_SIZE_Y) - 64.0) + if (this.posY < -64.0D) { this.onVoidUpdate(); } @@ -753,27 +753,43 @@ public abstract class EntityCart extends Entity implements IWorldNameable /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntity(TagObject tagCompund) + protected void readEntityFromNBT(NBTTagCompound tagCompund) { - if (tagCompund.getBool("CustomDisplayTile")) + if (tagCompund.getBoolean("CustomDisplayTile")) { - int i = tagCompund.getInt("DisplayData"); + int i = tagCompund.getInteger("DisplayData"); - if (tagCompund.hasString("DisplayTile")) + if (tagCompund.hasKey("DisplayTile", 8)) { - Block block = BlockRegistry.getRegisteredBlock(tagCompund.getString("DisplayTile")); + Block block = BlockRegistry.getByIdFallback(tagCompund.getString("DisplayTile")); - this.func_174899_a(block.getStateFromMeta(i)); + if (block == null) + { + this.func_174899_a(Blocks.air.getState()); + } + else + { + this.func_174899_a(block.getStateFromMeta(i)); + } } else { - this.func_174899_a(Blocks.air.getState()); + Block block1 = BlockRegistry.getBlockById(tagCompund.getInteger("DisplayTile")); + + if (block1 == null) + { + this.func_174899_a(Blocks.air.getState()); + } + else + { + this.func_174899_a(block1.getStateFromMeta(i)); + } } - this.setDisplayTileOffset(tagCompund.getInt("DisplayOffset")); + this.setDisplayTileOffset(tagCompund.getInteger("DisplayOffset")); } - if (tagCompund.hasString("CustomName") && tagCompund.getString("CustomName").length() > 0) + if (tagCompund.hasKey("CustomName", 8) && tagCompund.getString("CustomName").length() > 0) { this.entityName = tagCompund.getString("CustomName"); } @@ -782,16 +798,16 @@ public abstract class EntityCart extends Entity implements IWorldNameable /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntity(TagObject tagCompound) + protected void writeEntityToNBT(NBTTagCompound tagCompound) { if (this.hasDisplayTile()) { - tagCompound.setBool("CustomDisplayTile", true); + tagCompound.setBoolean("CustomDisplayTile", true); State iblockstate = this.getDisplayTile(); - String resourcelocation = BlockRegistry.getNameFromBlock(iblockstate.getBlock()); - tagCompound.setString("DisplayTile", resourcelocation == null ? "" : resourcelocation); - tagCompound.setInt("DisplayData", iblockstate.getBlock().getMetaFromState(iblockstate)); - tagCompound.setInt("DisplayOffset", this.getDisplayTileOffset()); + String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(iblockstate.getBlock()); + tagCompound.setString("DisplayTile", resourcelocation == null ? "" : resourcelocation.toString()); + tagCompound.setInteger("DisplayData", iblockstate.getBlock().getMetaFromState(iblockstate)); + tagCompound.setInteger("DisplayOffset", this.getDisplayTileOffset()); } if (this.entityName != null && this.entityName.length() > 0) @@ -896,14 +912,14 @@ public abstract class EntityCart extends Entity implements IWorldNameable } } - public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) { this.minecartX = x; this.minecartY = y; this.minecartZ = z; this.minecartYaw = (double)yaw; this.minecartPitch = (double)pitch; - this.turnProgress = 5; + this.turnProgress = posRotationIncrements + 2; this.motionX = this.velocityX; this.motionY = this.velocityY; this.motionZ = this.velocityZ; diff --git a/common/src/main/java/common/entity/item/EntityCartContainer.java b/common/src/common/entity/item/EntityCartContainer.java similarity index 82% rename from common/src/main/java/common/entity/item/EntityCartContainer.java rename to common/src/common/entity/item/EntityCartContainer.java index 90ed0e7..4afb8f5 100755 --- a/common/src/main/java/common/entity/item/EntityCartContainer.java +++ b/common/src/common/entity/item/EntityCartContainer.java @@ -1,19 +1,18 @@ package common.entity.item; -import common.collect.Lists; import common.entity.DamageSource; import common.entity.Entity; import common.entity.npc.EntityNPC; +import common.init.Config; import common.inventory.Container; import common.inventory.InventoryHelper; import common.item.ItemStack; -import common.tags.TagObject; -import java.util.List; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.tileentity.ILockableContainer; -import common.tileentity.Passcode; +import common.tileentity.LockCode; import common.util.BlockPos; import common.util.PortalType; -import common.vars.Vars; import common.world.World; public abstract class EntityCartContainer extends EntityCart implements ILockableContainer @@ -40,7 +39,7 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl { super.killMinecart(source); - if (Vars.objectDrop) + if (Config.objectDrop) { InventoryHelper.dropInventoryItems(this.worldObj, this, this); } @@ -61,7 +60,7 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl { if (this.minecartContainerItems[index] != null) { - if (this.minecartContainerItems[index].size <= count) + if (this.minecartContainerItems[index].stackSize <= count) { ItemStack itemstack1 = this.minecartContainerItems[index]; this.minecartContainerItems[index] = null; @@ -71,7 +70,7 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl { ItemStack itemstack = this.minecartContainerItems[index].splitStack(count); - if (this.minecartContainerItems[index].size == 0) + if (this.minecartContainerItems[index].stackSize == 0) { this.minecartContainerItems[index] = null; } @@ -109,9 +108,9 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl { this.minecartContainerItems[index] = stack; - if (stack != null && stack.size > this.getInventoryStackLimit()) + if (stack != null && stack.stackSize > this.getInventoryStackLimit()) { - stack.size = this.getInventoryStackLimit(); + stack.stackSize = this.getInventoryStackLimit(); } } @@ -188,42 +187,42 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntity(TagObject tagCompound) + protected void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - List nbttaglist = Lists.newArrayList(); + super.writeEntityToNBT(tagCompound); + NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < this.minecartContainerItems.length; ++i) { if (this.minecartContainerItems[i] != null) { - TagObject nbttagcompound = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setByte("Slot", (byte)i); - this.minecartContainerItems[i].writeTags(nbttagcompound); - nbttaglist.add(nbttagcompound); + this.minecartContainerItems[i].writeToNBT(nbttagcompound); + nbttaglist.appendTag(nbttagcompound); } } - tagCompound.setList("Items", nbttaglist); + tagCompound.setTag("Items", nbttaglist); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntity(TagObject tagCompund) + protected void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - List nbttaglist = tagCompund.getList("Items"); + super.readEntityFromNBT(tagCompund); + NBTTagList nbttaglist = tagCompund.getTagList("Items", 10); this.minecartContainerItems = new ItemStack[this.getSizeInventory()]; - for (int i = 0; i < nbttaglist.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject nbttagcompound = nbttaglist.get(i); + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); int j = nbttagcompound.getByte("Slot") & 255; if (j >= 0 && j < this.minecartContainerItems.length) { - this.minecartContainerItems[j] = ItemStack.readFromTag(nbttagcompound); + this.minecartContainerItems[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); } } } @@ -269,13 +268,13 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl return false; } - public void setLockCode(Passcode code) + public void setLockCode(LockCode code) { } - public Passcode getLockCode() + public LockCode getLockCode() { - return Passcode.EMPTY_CODE; + return LockCode.EMPTY_CODE; } public void clear() diff --git a/common/src/main/java/common/entity/item/EntityChestCart.java b/common/src/common/entity/item/EntityChestCart.java similarity index 94% rename from common/src/main/java/common/entity/item/EntityChestCart.java rename to common/src/common/entity/item/EntityChestCart.java index f110cf0..73d7966 100755 --- a/common/src/main/java/common/entity/item/EntityChestCart.java +++ b/common/src/common/entity/item/EntityChestCart.java @@ -1,15 +1,15 @@ package common.entity.item; -import common.block.tech.BlockChest; +import common.block.BlockChest; import common.entity.DamageSource; import common.entity.npc.EntityNPC; import common.init.Blocks; +import common.init.Config; import common.init.ItemRegistry; import common.inventory.Container; import common.inventory.ContainerChest; import common.inventory.InventoryPlayer; import common.util.Facing; -import common.vars.Vars; import common.world.State; import common.world.World; @@ -29,7 +29,7 @@ public class EntityChestCart extends EntityCartContainer { super.killMinecart(source); - if (Vars.objectDrop) + if (Config.objectDrop) { this.dropItemWithOffset(ItemRegistry.getItemFromBlock(Blocks.chest), 1, 0.0F); } diff --git a/common/src/main/java/common/entity/item/EntityCrystal.java b/common/src/common/entity/item/EntityCrystal.java similarity index 95% rename from common/src/main/java/common/entity/item/EntityCrystal.java rename to common/src/common/entity/item/EntityCrystal.java index 855697f..d7b4073 100755 --- a/common/src/main/java/common/entity/item/EntityCrystal.java +++ b/common/src/common/entity/item/EntityCrystal.java @@ -3,7 +3,7 @@ package common.entity.item; import common.entity.DamageSource; import common.entity.Entity; import common.entity.EntityType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.world.World; public class EntityCrystal extends Entity @@ -63,14 +63,14 @@ public class EntityCrystal extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntity(TagObject tagCompound) + protected void writeEntityToNBT(NBTTagCompound tagCompound) { } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntity(TagObject tagCompund) + protected void readEntityFromNBT(NBTTagCompound tagCompund) { } diff --git a/common/src/main/java/common/entity/item/EntityExplosion.java b/common/src/common/entity/item/EntityExplosion.java similarity index 82% rename from common/src/main/java/common/entity/item/EntityExplosion.java rename to common/src/common/entity/item/EntityExplosion.java index f457c71..e8892bf 100755 --- a/common/src/main/java/common/entity/item/EntityExplosion.java +++ b/common/src/common/entity/item/EntityExplosion.java @@ -2,7 +2,7 @@ package common.entity.item; import common.entity.Entity; import common.entity.EntityType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.world.Explosion; import common.world.World; @@ -62,16 +62,16 @@ public class EntityExplosion extends Entity Explosion.doExplosionAlgo3(this.worldObj, this.posX, this.posY + (double)(this.height / 2.0F), this.posZ, this.rand, min + 6.0d, min); } - protected void writeEntity(TagObject tagCompound) + protected void writeEntityToNBT(NBTTagCompound tagCompound) { - tagCompound.setInt("Progress", this.progress); - tagCompound.setInt("Radius", this.radius); + tagCompound.setInteger("Progress", this.progress); + tagCompound.setInteger("Radius", this.radius); } - protected void readEntity(TagObject tagCompund) + protected void readEntityFromNBT(NBTTagCompound tagCompund) { - this.progress = tagCompund.getInt("Progress"); - this.radius = tagCompund.getInt("Radius"); + this.progress = tagCompund.getInteger("Progress"); + this.radius = tagCompund.getInteger("Radius"); } public float getEyeHeight() diff --git a/common/src/main/java/common/entity/item/EntityFalling.java b/common/src/common/entity/item/EntityFalling.java similarity index 66% rename from common/src/main/java/common/entity/item/EntityFalling.java rename to common/src/common/entity/item/EntityFalling.java index 75d3c6b..97b135e 100755 --- a/common/src/main/java/common/entity/item/EntityFalling.java +++ b/common/src/common/entity/item/EntityFalling.java @@ -3,8 +3,9 @@ package common.entity.item; import java.util.List; import common.block.Block; +import common.block.BlockAnvil; import common.block.BlockFalling; -import common.block.tech.BlockAnvil; +import common.block.ITileEntityProvider; import common.collect.Lists; import common.entity.DamageSource; import common.entity.Entity; @@ -12,12 +13,15 @@ import common.entity.EntityType; import common.entity.types.IObjectData; import common.init.BlockRegistry; import common.init.Blocks; +import common.init.Config; import common.item.ItemStack; -import common.tags.TagObject; +import common.material.Material; +import common.nbt.NBTBase; +import common.nbt.NBTTagCompound; +import common.tileentity.TileEntity; import common.util.BlockPos; import common.util.ExtMath; import common.util.Facing; -import common.vars.Vars; import common.world.State; import common.world.World; @@ -30,6 +34,7 @@ public class EntityFalling extends Entity implements IObjectData private boolean hurtEntities; private int fallHurtMax = 40; private float fallHurtAmount = 2.0F; + public NBTTagCompound tileEntityData; public EntityFalling(World worldIn) { @@ -84,7 +89,7 @@ public class EntityFalling extends Entity implements IObjectData { Block block = this.fallTile.getBlock(); - if (block == Blocks.air) + if (block.getMaterial() == Material.air) { this.setDead(); } @@ -137,17 +142,41 @@ public class EntityFalling extends Entity implements IObjectData { ((BlockFalling)block).onEndFalling(this.worldObj, blockpos1); } + + if (this.tileEntityData != null && block instanceof ITileEntityProvider) + { + TileEntity tileentity = this.worldObj.getTileEntity(blockpos1); + + if (tileentity != null) + { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + tileentity.writeToNBT(nbttagcompound); + + for (String s : this.tileEntityData.getKeySet()) + { + NBTBase nbtbase = this.tileEntityData.getTag(s); + + if (!s.equals("x") && !s.equals("y") && !s.equals("z")) + { + nbttagcompound.setTag(s, nbtbase.copy()); + } + } + + tileentity.readFromNBT(nbttagcompound); + tileentity.markDirty(); + } + } } - else if (this.shouldDropItem && Vars.objectDrop) + else if (this.shouldDropItem && Config.objectDrop) { this.entityDropItem(new ItemStack(block, 1, block.damageDropped(this.fallTile)), 0.0F); } } } } - else if (this.fallTime > 100 && !this.worldObj.client && (blockpos1.getY() < -World.MAX_SIZE_Y + 1 || blockpos1.getY() > World.MAX_SIZE_Y) || this.fallTime > 600) + else if (this.fallTime > 100 && !this.worldObj.client && (blockpos1.getY() < 1 || blockpos1.getY() > 512) || this.fallTime > 600) { - if (this.shouldDropItem && Vars.objectDrop) + if (this.shouldDropItem && Config.objectDrop) { this.entityDropItem(new ItemStack(block, 1, block.damageDropped(this.fallTile)), 0.0F); } @@ -172,14 +201,14 @@ public class EntityFalling extends Entity implements IObjectData boolean flag = block == Blocks.anvil; DamageSource damagesource = flag ? DamageSource.anvil : DamageSource.fallingBlock; - if(this.worldObj.client || (flag ? Vars.damageAcme : Vars.damageSquish)) { + if(this.worldObj.client || (flag ? Config.damageAcme : Config.damageSquish)) { for (Entity entity : list) { entity.attackEntityFrom(damagesource, Math.min(ExtMath.floorf((float)i * this.fallHurtAmount), this.fallHurtMax)); } } - if (flag && (this.worldObj.client || Vars.anvilFallDecay) && (double)this.rand.floatv() < 0.05000000074505806D + (double)i * 0.05D) + if (flag && (this.worldObj.client || Config.anvilFallDecay) && (double)this.rand.floatv() < 0.05000000074505806D + (double)i * 0.05D) { int j = ((Integer)this.fallTile.getValue(BlockAnvil.DAMAGE)).intValue(); ++j; @@ -200,45 +229,69 @@ public class EntityFalling extends Entity implements IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntity(TagObject tagCompound) + protected void writeEntityToNBT(NBTTagCompound tagCompound) { Block block = this.fallTile != null ? this.fallTile.getBlock() : Blocks.air; - String resourcelocation = BlockRegistry.getNameFromBlock(block); + String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(block); tagCompound.setString("Block", resourcelocation == null ? "" : resourcelocation.toString()); tagCompound.setByte("Data", (byte)block.getMetaFromState(this.fallTile)); tagCompound.setByte("Time", (byte)this.fallTime); - tagCompound.setBool("DropItem", this.shouldDropItem); - tagCompound.setBool("HurtEntities", this.hurtEntities); + tagCompound.setBoolean("DropItem", this.shouldDropItem); + tagCompound.setBoolean("HurtEntities", this.hurtEntities); tagCompound.setFloat("FallHurtAmount", this.fallHurtAmount); - tagCompound.setInt("FallHurtMax", this.fallHurtMax); + tagCompound.setInteger("FallHurtMax", this.fallHurtMax); + + if (this.tileEntityData != null) + { + tagCompound.setTag("TileEntityData", this.tileEntityData); + } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntity(TagObject tagCompund) + protected void readEntityFromNBT(NBTTagCompound tagCompund) { int i = tagCompund.getByte("Data") & 255; - if (tagCompund.hasString("Block")) + if (tagCompund.hasKey("Block", 8)) { - this.fallTile = BlockRegistry.getRegisteredBlock(tagCompund.getString("Block")).getStateFromMeta(i); + this.fallTile = BlockRegistry.getByIdFallback(tagCompund.getString("Block")).getStateFromMeta(i); + } + else if (tagCompund.hasKey("TileID", 99)) + { + this.fallTile = BlockRegistry.getBlockById(tagCompund.getInteger("TileID")).getStateFromMeta(i); } else { - this.fallTile = Blocks.sand.getState(); + this.fallTile = BlockRegistry.getBlockById(tagCompund.getByte("Tile") & 255).getStateFromMeta(i); } this.fallTime = tagCompund.getByte("Time") & 255; Block block = this.fallTile.getBlock(); - this.hurtEntities = tagCompund.getBool("HurtEntities"); - this.fallHurtAmount = tagCompund.getFloat("FallHurtAmount"); - this.fallHurtMax = tagCompund.getInt("FallHurtMax"); + if (tagCompund.hasKey("HurtEntities", 99)) + { + this.hurtEntities = tagCompund.getBoolean("HurtEntities"); + this.fallHurtAmount = tagCompund.getFloat("FallHurtAmount"); + this.fallHurtMax = tagCompund.getInteger("FallHurtMax"); + } + else if (block == Blocks.anvil) + { + this.hurtEntities = true; + } - this.shouldDropItem = tagCompund.getBool("DropItem"); + if (tagCompund.hasKey("DropItem", 99)) + { + this.shouldDropItem = tagCompund.getBoolean("DropItem"); + } - if (block == null || block == Blocks.air) + if (tagCompund.hasKey("TileEntityData", 10)) + { + this.tileEntityData = tagCompund.getCompoundTag("TileEntityData"); + } + + if (block == null || block.getMaterial() == Material.air) { this.fallTile = Blocks.sand.getState(); } diff --git a/common/src/main/java/common/entity/item/EntityFireworks.java b/common/src/common/entity/item/EntityFireworks.java similarity index 85% rename from common/src/main/java/common/entity/item/EntityFireworks.java rename to common/src/common/entity/item/EntityFireworks.java index d2cb725..56951a5 100755 --- a/common/src/main/java/common/entity/item/EntityFireworks.java +++ b/common/src/common/entity/item/EntityFireworks.java @@ -5,7 +5,7 @@ import common.entity.EntityType; import common.init.SoundEvent; import common.item.ItemStack; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.ExtMath; import common.world.AWorldClient; import common.world.World; @@ -51,8 +51,8 @@ public class EntityFireworks extends Entity if (givenItem != null && givenItem.hasTagCompound()) { this.dataWatcher.updateObject(8, givenItem); - TagObject nbttagcompound = givenItem.getTagCompound(); - TagObject nbttagcompound1 = nbttagcompound.getObject("Fireworks"); + NBTTagCompound nbttagcompound = givenItem.getTagCompound(); + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("Fireworks"); if (nbttagcompound1 != null) { @@ -151,11 +151,11 @@ public class EntityFireworks extends Entity if (id == 17 && this.worldObj.client) { ItemStack itemstack = this.dataWatcher.getWatchableObjectItemStack(8); - TagObject nbttagcompound = null; + NBTTagCompound nbttagcompound = null; if (itemstack != null && itemstack.hasTagCompound()) { - nbttagcompound = itemstack.getTagCompound().getObject("Fireworks"); + nbttagcompound = itemstack.getTagCompound().getCompoundTag("Fireworks"); } ((AWorldClient)this.worldObj).makeFireworks(this.posX, this.posY, this.posZ, this.motionX, this.motionY, this.motionZ, nbttagcompound); @@ -167,32 +167,32 @@ public class EntityFireworks extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - tagCompound.setInt("Life", this.fireworkAge); - tagCompound.setInt("LifeTime", this.lifetime); + tagCompound.setInteger("Life", this.fireworkAge); + tagCompound.setInteger("LifeTime", this.lifetime); ItemStack itemstack = this.dataWatcher.getWatchableObjectItemStack(8); if (itemstack != null) { - TagObject nbttagcompound = new TagObject(); - itemstack.writeTags(nbttagcompound); - tagCompound.setObject("FireworksItem", nbttagcompound); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + itemstack.writeToNBT(nbttagcompound); + tagCompound.setTag("FireworksItem", nbttagcompound); } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - this.fireworkAge = tagCompund.getInt("Life"); - this.lifetime = tagCompund.getInt("LifeTime"); - TagObject nbttagcompound = tagCompund.getObject("FireworksItem"); + this.fireworkAge = tagCompund.getInteger("Life"); + this.lifetime = tagCompund.getInteger("LifeTime"); + NBTTagCompound nbttagcompound = tagCompund.getCompoundTag("FireworksItem"); if (nbttagcompound != null) { - ItemStack itemstack = ItemStack.readFromTag(nbttagcompound); + ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttagcompound); if (itemstack != null) { diff --git a/common/src/main/java/common/entity/item/EntityHopperCart.java b/common/src/common/entity/item/EntityHopperCart.java similarity index 91% rename from common/src/main/java/common/entity/item/EntityHopperCart.java rename to common/src/common/entity/item/EntityHopperCart.java index 0c287ae..398eccf 100755 --- a/common/src/main/java/common/entity/item/EntityHopperCart.java +++ b/common/src/common/entity/item/EntityHopperCart.java @@ -6,15 +6,15 @@ import java.util.function.Predicate; import common.entity.DamageSource; import common.entity.npc.EntityNPC; import common.init.Blocks; +import common.init.Config; import common.init.ItemRegistry; import common.inventory.Container; import common.inventory.ContainerHopper; import common.inventory.InventoryPlayer; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.tileentity.IHopper; import common.tileentity.TileEntityHopper; import common.util.BlockPos; -import common.vars.Vars; import common.world.State; import common.world.World; @@ -158,7 +158,7 @@ public class EntityHopperCart extends EntityCartContainer implements IHopper if (this.collectItems()) { - this.setTransferTicker(Vars.hopperCartDelay); + this.setTransferTicker(Config.hopperCartDelay); this.markDirty(); } } @@ -192,7 +192,7 @@ public class EntityHopperCart extends EntityCartContainer implements IHopper { super.killMinecart(source); - if (Vars.objectDrop) + if (Config.objectDrop) { this.dropItemWithOffset(ItemRegistry.getItemFromBlock(Blocks.hopper), 1, 0.0F); } @@ -201,19 +201,19 @@ public class EntityHopperCart extends EntityCartContainer implements IHopper /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntity(TagObject tagCompound) + protected void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setInt("TransferCooldown", this.transferTicker); + super.writeEntityToNBT(tagCompound); + tagCompound.setInteger("TransferCooldown", this.transferTicker); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntity(TagObject tagCompund) + protected void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.transferTicker = tagCompund.getInt("TransferCooldown"); + super.readEntityFromNBT(tagCompund); + this.transferTicker = tagCompund.getInteger("TransferCooldown"); } /** diff --git a/common/src/main/java/common/entity/item/EntityItem.java b/common/src/common/entity/item/EntityItem.java similarity index 92% rename from common/src/main/java/common/entity/item/EntityItem.java rename to common/src/common/entity/item/EntityItem.java index 00e1f5a..6b7abf7 100755 --- a/common/src/main/java/common/entity/item/EntityItem.java +++ b/common/src/common/entity/item/EntityItem.java @@ -1,6 +1,5 @@ package common.entity.item; -import common.block.Material; import common.color.TextColor; import common.entity.DamageSource; import common.entity.Entity; @@ -8,16 +7,17 @@ import common.entity.EntityType; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.init.Config; import common.init.ItemRegistry; import common.init.SoundEvent; import common.item.ItemStack; import common.log.Log; +import common.material.Material; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BlockPos; import common.util.ExtMath; import common.util.PortalType; -import common.vars.Vars; import common.world.World; import common.world.AWorldServer; @@ -63,7 +63,7 @@ public class EntityItem extends Entity public void fall(float distance, float damageMultiplier) { - if(!this.worldObj.client && Vars.itemFallDamage && distance >= 1.0f && this.getEntityItem().getItem().isFragile()) { + if(!this.worldObj.client && Config.itemFallDamage && distance >= 1.0f && this.getEntityItem().getItem().isFragile()) { // for(int z = 0; z < 8; z++) { ((AWorldServer)this.worldObj).spawnParticle(ParticleType.ITEM_CRACK, this.posX, this.posY, this.posZ, 8, this.rand.gaussian() * 0.15D, this.rand.doublev() * 0.2D, this.rand.gaussian() * 0.15D, 0.1f, @@ -125,7 +125,7 @@ public class EntityItem extends Entity if (flag || this.ticksExisted % 25 == 0) { - if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() == Material.LAVA) + if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() == Material.lava) { this.motionY = 0.20000000298023224D; this.motionX = (double)((this.rand.floatv() - this.rand.floatv()) * 0.2F); @@ -237,17 +237,17 @@ public class EntityItem extends Entity { return false; } - else if (itemstack1.size < itemstack.size) + else if (itemstack1.stackSize < itemstack.stackSize) { return other.combineItems(this); } - else if (itemstack1.size + itemstack.size > itemstack1.getMaxStackSize()) + else if (itemstack1.stackSize + itemstack.stackSize > itemstack1.getMaxStackSize()) { return false; } else { - itemstack1.size += itemstack.size; + itemstack1.stackSize += itemstack.stackSize; other.delayBeforeCanPickup = Math.max(other.delayBeforeCanPickup, this.delayBeforeCanPickup); other.age = Math.min(other.age, this.age); other.setEntityItemStack(itemstack1); @@ -308,7 +308,7 @@ public class EntityItem extends Entity */ protected void dealFireDamage(int amount) { - if(Vars.itemBurn) + if(Config.itemBurn) this.attackEntityFrom(DamageSource.inFire, amount); } @@ -342,7 +342,7 @@ public class EntityItem extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { tagCompound.setShort("Health", (short)((byte)this.health)); tagCompound.setShort("Age", (short)this.age); @@ -360,19 +360,22 @@ public class EntityItem extends Entity if (this.getEntityItem() != null) { - tagCompound.setObject("Item", this.getEntityItem().writeTags(new TagObject())); + tagCompound.setTag("Item", this.getEntityItem().writeToNBT(new NBTTagCompound())); } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { this.health = tagCompund.getShort("Health") & 255; this.age = tagCompund.getShort("Age"); - this.delayBeforeCanPickup = tagCompund.getShort("PickupDelay"); + if (tagCompund.hasKey("PickupDelay")) + { + this.delayBeforeCanPickup = tagCompund.getShort("PickupDelay"); + } // if (tagCompund.hasKey("Owner")) // { @@ -384,8 +387,8 @@ public class EntityItem extends Entity // this.thrower = tagCompund.getString("Thrower"); // } - TagObject nbttagcompound = tagCompund.getObject("Item"); - this.setEntityItemStack(ItemStack.readFromTag(nbttagcompound)); + NBTTagCompound nbttagcompound = tagCompund.getCompoundTag("Item"); + this.setEntityItemStack(ItemStack.loadItemStackFromNBT(nbttagcompound)); if (this.getEntityItem() == null) { @@ -401,7 +404,7 @@ public class EntityItem extends Entity if (!this.worldObj.client) { ItemStack itemstack = this.getEntityItem(); - int i = itemstack.size; + int i = itemstack.stackSize; if (this.delayBeforeCanPickup == 0 // && (this.owner == null || 6000 - this.age <= 200 || this.owner.equals(entityIn.getUser())) && entityIn.inventory.addItemStackToInventory(itemstack)) @@ -448,7 +451,7 @@ public class EntityItem extends Entity entityIn.onItemPickup(this, i); - if (itemstack.size <= 0) + if (itemstack.stackSize <= 0) { this.setDead(); } @@ -464,8 +467,8 @@ public class EntityItem extends Entity if(this.hasCustomName()) return this.getCustomNameTag(); String comp = super.getTypeName(); - comp += " (" + this.getEntityItem().size + " * " + - ItemRegistry.getNameFromItem(this.getEntityItem().getItem()) + ":" + this.getEntityItem().getMetadata() + ")"; + comp += " (" + this.getEntityItem().stackSize + " * " + + ItemRegistry.REGISTRY.getNameForObject(this.getEntityItem().getItem()) + ":" + this.getEntityItem().getMetadata() + ")"; return comp; } @@ -504,7 +507,7 @@ public class EntityItem extends Entity { if (this.worldObj != null) { - Log.TICK.warn("Gegenstand-Objekt " + this.getId() + " hat kein Item?!"); + Log.JNI.warn("Gegenstand-Objekt " + this.getId() + " hat kein Item?!"); } return new ItemStack(Blocks.stone); @@ -612,9 +615,9 @@ public class EntityItem extends Entity public String getDisplayName() { ItemStack stack = this.getEntityItem(); - if(stack.size <= 1) + if(stack.stackSize <= 1) return null; - return TextColor.DGREEN + "" + stack.size; + return TextColor.DGREEN + "" + stack.stackSize; } public EntityType getType() { diff --git a/common/src/main/java/common/entity/item/EntityLeashKnot.java b/common/src/common/entity/item/EntityLeashKnot.java similarity index 98% rename from common/src/main/java/common/entity/item/EntityLeashKnot.java rename to common/src/common/entity/item/EntityLeashKnot.java index d5c74e7..764cc21 100755 --- a/common/src/main/java/common/entity/item/EntityLeashKnot.java +++ b/common/src/common/entity/item/EntityLeashKnot.java @@ -1,6 +1,6 @@ package common.entity.item; -import common.block.artificial.BlockFence; +import common.block.BlockFence; import common.entity.DamageSource; import common.entity.Entity; import common.entity.EntityType; @@ -9,7 +9,7 @@ import common.entity.types.EntityLiving; import common.init.Items; import common.item.Item; import common.item.ItemStack; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; @@ -375,7 +375,7 @@ public class EntityLeashKnot extends Entity * returns false the entity is not saved on disk. Ridden entities return false here as they are saved with their * rider. */ - public boolean writeOptional(TagObject tagCompund) + public boolean writeToNBTOptional(NBTTagCompound tagCompund) { return false; } @@ -383,14 +383,14 @@ public class EntityLeashKnot extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { } diff --git a/common/src/main/java/common/entity/item/EntityMinecart.java b/common/src/common/entity/item/EntityMinecart.java similarity index 100% rename from common/src/main/java/common/entity/item/EntityMinecart.java rename to common/src/common/entity/item/EntityMinecart.java diff --git a/common/src/main/java/common/entity/item/EntityNuke.java b/common/src/common/entity/item/EntityNuke.java similarity index 91% rename from common/src/main/java/common/entity/item/EntityNuke.java rename to common/src/common/entity/item/EntityNuke.java index a94953d..75ee50c 100755 --- a/common/src/main/java/common/entity/item/EntityNuke.java +++ b/common/src/common/entity/item/EntityNuke.java @@ -3,7 +3,7 @@ package common.entity.item; import common.entity.Entity; import common.entity.EntityType; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.world.World; public class EntityNuke extends Entity @@ -93,14 +93,14 @@ public class EntityNuke extends Entity // Explosion.doExplosionAlgo3(this.worldObj, this.posX, this.posY + (double)(this.height / 2.0F), this.posZ, this.rand, min + 6.0d, min); // } - protected void writeEntity(TagObject tagCompound) + protected void writeEntityToNBT(NBTTagCompound tagCompound) { - tagCompound.setInt("Fuse", this.fuse); + tagCompound.setInteger("Fuse", this.fuse); } - protected void readEntity(TagObject tagCompund) + protected void readEntityFromNBT(NBTTagCompound tagCompund) { - this.fuse = tagCompund.getInt("Fuse"); + this.fuse = tagCompund.getInteger("Fuse"); } public float getEyeHeight() diff --git a/common/src/main/java/common/entity/item/EntityOrb.java b/common/src/common/entity/item/EntityOrb.java similarity index 94% rename from common/src/main/java/common/entity/item/EntityOrb.java rename to common/src/common/entity/item/EntityOrb.java index 1c0e462..055206c 100755 --- a/common/src/main/java/common/entity/item/EntityOrb.java +++ b/common/src/common/entity/item/EntityOrb.java @@ -4,9 +4,9 @@ import common.entity.DamageSource; import common.entity.Entity; import common.entity.types.EntityLiving; import common.entity.types.EntityThrowable; +import common.init.Config; import common.model.ParticleType; import common.util.HitPosition; -import common.vars.Vars; import common.world.World; public class EntityOrb extends EntityThrowable @@ -52,7 +52,7 @@ public class EntityOrb extends EntityThrowable // return; // } - if(Vars.telefrag) { + if(Config.telefrag) { x = pos.entity.posX; y = pos.entity.posY; z = pos.entity.posZ; @@ -92,8 +92,8 @@ public class EntityOrb extends EntityThrowable entitylivingbase.setPositionAndUpdate(x, y, z); entitylivingbase.fallDistance = 0.0F; - if(Vars.orbDamageSelf > 0) - entitylivingbase.attackEntityFrom(DamageSource.fall, Vars.orbDamageSelf); + if(Config.orbDamageSelf > 0) + entitylivingbase.attackEntityFrom(DamageSource.fall, Config.orbDamageSelf); } } // else if (entitylivingbase != null) @@ -109,13 +109,13 @@ public class EntityOrb extends EntityThrowable if (pos.entity != null) { - if(Vars.telefrag) { + if(Config.telefrag) { pos.entity.attackEntityFrom(DamageSource.causeTeleFragDamage(this, entitylivingbase), 10000); if(!this.worldObj.client) this.worldObj.playAuxSFX(1017, pos.entity.getPosition(), 0); } - else if(Vars.knockOrb) { - pos.entity.attackEntityFrom(DamageSource.causeThrownDamage(this, entitylivingbase), Vars.orbDamageOther); + else if(Config.knockOrb) { + pos.entity.attackEntityFrom(DamageSource.causeThrownDamage(this, entitylivingbase), Config.orbDamageOther); } } } diff --git a/common/src/main/java/common/entity/item/EntityTnt.java b/common/src/common/entity/item/EntityTnt.java similarity index 96% rename from common/src/main/java/common/entity/item/EntityTnt.java rename to common/src/common/entity/item/EntityTnt.java index 84e398c..b68cb74 100755 --- a/common/src/main/java/common/entity/item/EntityTnt.java +++ b/common/src/common/entity/item/EntityTnt.java @@ -5,7 +5,7 @@ import common.entity.EntityType; import common.entity.types.EntityLiving; import common.entity.types.IObjectData; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.world.World; public class EntityTnt extends Entity implements IObjectData @@ -109,7 +109,7 @@ public class EntityTnt extends Entity implements IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntity(TagObject tagCompound) + protected void writeEntityToNBT(NBTTagCompound tagCompound) { tagCompound.setByte("Fuse", (byte)this.fuse); tagCompound.setByte("Power", (byte)this.explosionSize); @@ -118,7 +118,7 @@ public class EntityTnt extends Entity implements IObjectData /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntity(TagObject tagCompund) + protected void readEntityFromNBT(NBTTagCompound tagCompund) { this.fuse = tagCompund.getByte("Fuse"); this.explosionSize = ((int)tagCompund.getByte("Power")) & 7; diff --git a/common/src/main/java/common/entity/item/EntityTntCart.java b/common/src/common/entity/item/EntityTntCart.java similarity index 90% rename from common/src/main/java/common/entity/item/EntityTntCart.java rename to common/src/common/entity/item/EntityTntCart.java index 7d872c4..3f9005c 100755 --- a/common/src/main/java/common/entity/item/EntityTntCart.java +++ b/common/src/common/entity/item/EntityTntCart.java @@ -1,16 +1,16 @@ package common.entity.item; -import common.block.tech.BlockRailBase; +import common.block.BlockRailBase; import common.entity.DamageSource; import common.entity.Entity; import common.entity.projectile.EntityArrow; import common.init.Blocks; +import common.init.Config; import common.init.SoundEvent; import common.item.ItemStack; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BlockPos; -import common.vars.Vars; import common.world.Explosion; import common.world.State; import common.world.World; @@ -92,7 +92,7 @@ public class EntityTntCart extends EntityCart super.killMinecart(source); double d0 = this.motionX * this.motionX + this.motionZ * this.motionZ; - if (!source.isExplosion() && Vars.objectDrop) + if (!source.isExplosion() && Config.objectDrop) { this.entityDropItem(new ItemStack(Blocks.tnt, 1), 0.0F); } @@ -206,18 +206,22 @@ public class EntityTntCart extends EntityCart /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntity(TagObject tagCompund) + protected void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.minecartTNTFuse = tagCompund.getInt("TNTFuse"); + super.readEntityFromNBT(tagCompund); + + if (tagCompund.hasKey("TNTFuse", 99)) + { + this.minecartTNTFuse = tagCompund.getInteger("TNTFuse"); + } } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntity(TagObject tagCompound) + protected void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setInt("TNTFuse", this.minecartTNTFuse); + super.writeEntityToNBT(tagCompound); + tagCompound.setInteger("TNTFuse", this.minecartTNTFuse); } } diff --git a/common/src/main/java/common/entity/item/EntityXp.java b/common/src/common/entity/item/EntityXp.java similarity index 97% rename from common/src/main/java/common/entity/item/EntityXp.java rename to common/src/common/entity/item/EntityXp.java index 06d1342..43a5e6a 100755 --- a/common/src/main/java/common/entity/item/EntityXp.java +++ b/common/src/common/entity/item/EntityXp.java @@ -1,19 +1,19 @@ package common.entity.item; -import common.block.Material; import common.color.TextColor; import common.entity.DamageSource; import common.entity.Entity; import common.entity.EntityType; import common.entity.npc.EntityNPC; import common.entity.types.IObjectData; +import common.init.Config; import common.init.SoundEvent; +import common.material.Material; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BlockPos; import common.util.ExtMath; import common.util.PortalType; -import common.vars.Vars; import common.world.World; public class EntityXp extends Entity implements IObjectData @@ -106,7 +106,7 @@ public class EntityXp extends Entity implements IObjectData this.prevZ = this.posZ; this.motionY -= 0.029999999329447746D; - if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() == Material.LAVA) + if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() == Material.lava) { this.motionY = 0.20000000298023224D; this.motionX = (double)((this.rand.floatv() - this.rand.floatv()) * 0.2F); @@ -263,7 +263,7 @@ public class EntityXp extends Entity implements IObjectData */ protected void dealFireDamage(int amount) { - if(Vars.xpOrbBurn) + if(Config.xpOrbBurn) this.attackEntityFrom(DamageSource.inFire, amount); } @@ -293,7 +293,7 @@ public class EntityXp extends Entity implements IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { tagCompound.setShort("Health", (short)((byte)this.xpOrbHealth)); tagCompound.setShort("Age", (short)this.xpOrbAge); @@ -303,7 +303,7 @@ public class EntityXp extends Entity implements IObjectData /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { this.xpOrbHealth = tagCompund.getShort("Health") & 255; this.xpOrbAge = tagCompund.getShort("Age"); @@ -320,7 +320,7 @@ public class EntityXp extends Entity implements IObjectData { if (this.delayBeforeCanPickup == 0 && entityIn.xpCooldown == 0) { - entityIn.xpCooldown = Vars.xpDelay; + entityIn.xpCooldown = Config.xpDelay; this.worldObj.playSoundAtEntity(entityIn, SoundEvent.ORB, 0.1F); entityIn.onItemPickup(this, this.xpValue); entityIn.addExperience(this.xpValue); diff --git a/common/src/main/java/common/entity/item/EntityXpBottle.java b/common/src/common/entity/item/EntityXpBottle.java similarity index 100% rename from common/src/main/java/common/entity/item/EntityXpBottle.java rename to common/src/common/entity/item/EntityXpBottle.java diff --git a/common/src/main/java/common/entity/npc/Alignment.java b/common/src/common/entity/npc/Alignment.java similarity index 100% rename from common/src/main/java/common/entity/npc/Alignment.java rename to common/src/common/entity/npc/Alignment.java diff --git a/common/src/main/java/common/entity/npc/CharacterInfo.java b/common/src/common/entity/npc/CharacterInfo.java similarity index 100% rename from common/src/main/java/common/entity/npc/CharacterInfo.java rename to common/src/common/entity/npc/CharacterInfo.java diff --git a/common/src/common/entity/npc/ClassInfo.java b/common/src/common/entity/npc/ClassInfo.java new file mode 100755 index 0000000..e4561a0 --- /dev/null +++ b/common/src/common/entity/npc/ClassInfo.java @@ -0,0 +1,9 @@ +package common.entity.npc; + +public class ClassInfo { + public final Enum type; + + public ClassInfo(Enum type) { + this.type = type; + } +} diff --git a/common/src/main/java/common/entity/npc/Energy.java b/common/src/common/entity/npc/Energy.java similarity index 100% rename from common/src/main/java/common/entity/npc/Energy.java rename to common/src/common/entity/npc/Energy.java diff --git a/common/src/main/java/common/entity/npc/EntityArachnoid.java b/common/src/common/entity/npc/EntityArachnoid.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityArachnoid.java rename to common/src/common/entity/npc/EntityArachnoid.java diff --git a/common/src/main/java/common/entity/npc/EntityBloodElf.java b/common/src/common/entity/npc/EntityBloodElf.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityBloodElf.java rename to common/src/common/entity/npc/EntityBloodElf.java diff --git a/common/src/main/java/common/entity/npc/EntityChaosMarine.java b/common/src/common/entity/npc/EntityChaosMarine.java similarity index 96% rename from common/src/main/java/common/entity/npc/EntityChaosMarine.java rename to common/src/common/entity/npc/EntityChaosMarine.java index 69966f5..13790fa 100755 --- a/common/src/main/java/common/entity/npc/EntityChaosMarine.java +++ b/common/src/common/entity/npc/EntityChaosMarine.java @@ -2,6 +2,7 @@ package common.entity.npc; import java.util.List; +import common.attributes.Attributes; import common.collect.Lists; import common.init.Items; import common.init.SpeciesRegistry; @@ -117,7 +118,7 @@ public class EntityChaosMarine extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setAttackDamageBase(12); + this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(12.0D); } protected ItemStack pickItem() { diff --git a/common/src/main/java/common/entity/npc/EntityCpu.java b/common/src/common/entity/npc/EntityCpu.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityCpu.java rename to common/src/common/entity/npc/EntityCpu.java diff --git a/common/src/main/java/common/entity/npc/EntityCultivator.java b/common/src/common/entity/npc/EntityCultivator.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityCultivator.java rename to common/src/common/entity/npc/EntityCultivator.java diff --git a/common/src/main/java/common/entity/npc/EntityDarkMage.java b/common/src/common/entity/npc/EntityDarkMage.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityDarkMage.java rename to common/src/common/entity/npc/EntityDarkMage.java diff --git a/common/src/main/java/common/entity/npc/EntityDwarf.java b/common/src/common/entity/npc/EntityDwarf.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityDwarf.java rename to common/src/common/entity/npc/EntityDwarf.java diff --git a/common/src/main/java/common/entity/npc/EntityElf.java b/common/src/common/entity/npc/EntityElf.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityElf.java rename to common/src/common/entity/npc/EntityElf.java diff --git a/common/src/main/java/common/entity/npc/EntityFireDemon.java b/common/src/common/entity/npc/EntityFireDemon.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityFireDemon.java rename to common/src/common/entity/npc/EntityFireDemon.java diff --git a/common/src/main/java/common/entity/npc/EntityFlyingNPC.java b/common/src/common/entity/npc/EntityFlyingNPC.java similarity index 95% rename from common/src/main/java/common/entity/npc/EntityFlyingNPC.java rename to common/src/common/entity/npc/EntityFlyingNPC.java index 0218e90..9934394 100755 --- a/common/src/main/java/common/entity/npc/EntityFlyingNPC.java +++ b/common/src/common/entity/npc/EntityFlyingNPC.java @@ -2,6 +2,7 @@ package common.entity.npc; import common.ai.EntityAIBase; import common.ai.EntityMoveHelper; +import common.attributes.Attributes; import common.block.Block; import common.entity.types.EntityLiving; import common.potion.Potion; @@ -20,10 +21,12 @@ public abstract class EntityFlyingNPC extends EntityNPC this.tasks.addTask(5, new AIRandomFly(this)); this.tasks.addTask(7, new AILookAround(this)); } - - public int getPathingRange() { - return 48; - } + + protected void applyEntityAttributes() + { + super.applyEntityAttributes(); + this.getEntityAttribute(Attributes.FOLLOW_RANGE).setBaseValue(48.0D); + } public float getArmRotation() { return 0.0f; @@ -126,9 +129,10 @@ public abstract class EntityFlyingNPC extends EntityNPC return false; } - public boolean isPotionApplicable(Potion potion, int amplifier) { - return (potion != Potion.FLYING || amplifier > 0) && super.isPotionApplicable(potion, amplifier); - } + public boolean isPotionApplicable(Potion potion) + { + return potion != Potion.FLYING && super.isPotionApplicable(potion); + } static class AILookAround extends EntityAIBase { diff --git a/common/src/main/java/common/entity/npc/EntityGargoyle.java b/common/src/common/entity/npc/EntityGargoyle.java similarity index 90% rename from common/src/main/java/common/entity/npc/EntityGargoyle.java rename to common/src/common/entity/npc/EntityGargoyle.java index 065e07e..6b5e72a 100755 --- a/common/src/main/java/common/entity/npc/EntityGargoyle.java +++ b/common/src/common/entity/npc/EntityGargoyle.java @@ -1,12 +1,13 @@ package common.entity.npc; import common.ai.AIFlyingBoxAttack; +import common.attributes.Attributes; import common.entity.DamageSource; +import common.init.Config; import common.item.ItemStack; import common.model.ParticleType; +import common.nbt.NBTTagCompound; import common.rng.Random; -import common.tags.TagObject; -import common.vars.Vars; import common.world.World; public class EntityGargoyle extends EntityFlyingNPC @@ -34,16 +35,16 @@ public class EntityGargoyle extends EntityFlyingNPC this.dataWatcher.addObject(23, 0); } - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setInt("Invul", this.getInvulTime()); + super.writeEntityToNBT(tagCompound); + tagCompound.setInteger("Invul", this.getInvulTime()); } - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.setInvulTime(tagCompund.getInt("Invul")); + super.readEntityFromNBT(tagCompund); + this.setInvulTime(tagCompund.getInteger("Invul")); } public void onLivingUpdate() @@ -111,7 +112,7 @@ public class EntityGargoyle extends EntityFlyingNPC if (j1 <= 0) { this.worldObj.newExplosion(this, this.posX, this.posY + (double)this.getEyeHeight(), this.posZ, 7.0F, false, - Vars.mobGrief, false); + Config.mobGrief, false); // this.worldObj.broadcastSound(1013, new BlockPos(this), 0); } @@ -164,12 +165,9 @@ public class EntityGargoyle extends EntityFlyingNPC protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setSpeedBase(0.6000000238418579f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.6000000238418579D); + this.getEntityAttribute(Attributes.FOLLOW_RANGE).setBaseValue(40.0D); } - - public int getPathingRange() { - return 40; - } public int getInvulTime() { diff --git a/common/src/main/java/common/entity/npc/EntityGoblin.java b/common/src/common/entity/npc/EntityGoblin.java similarity index 91% rename from common/src/main/java/common/entity/npc/EntityGoblin.java rename to common/src/common/entity/npc/EntityGoblin.java index 55a0ac8..b80ef9a 100755 --- a/common/src/main/java/common/entity/npc/EntityGoblin.java +++ b/common/src/common/entity/npc/EntityGoblin.java @@ -1,5 +1,6 @@ package common.entity.npc; +import common.attributes.Attributes; import common.entity.types.EntityLiving; import common.rng.Random; import common.world.World; @@ -43,7 +44,7 @@ public class EntityGoblin extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setAttackDamageBase(1); + this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(1.0D); } public boolean canAmbush(EntityLiving entity) { diff --git a/common/src/main/java/common/entity/npc/EntityHaunter.java b/common/src/common/entity/npc/EntityHaunter.java similarity index 91% rename from common/src/main/java/common/entity/npc/EntityHaunter.java rename to common/src/common/entity/npc/EntityHaunter.java index ad266ed..4f5165d 100755 --- a/common/src/main/java/common/entity/npc/EntityHaunter.java +++ b/common/src/common/entity/npc/EntityHaunter.java @@ -1,15 +1,16 @@ package common.entity.npc; import common.ai.EntityAIExplode; +import common.attributes.Attributes; import common.entity.Entity; import common.entity.effect.EntityLightning; import common.entity.types.EntityLiving; +import common.init.Config; import common.init.Items; import common.init.SoundEvent; import common.item.ItemStack; +import common.nbt.NBTTagCompound; import common.rng.Random; -import common.tags.TagObject; -import common.vars.Vars; import common.world.World; import common.world.AWorldServer; @@ -27,7 +28,7 @@ public class EntityHaunter extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setSpeedBase(0.25f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.25D); } public int getMaxFallHeight() @@ -57,30 +58,33 @@ public class EntityHaunter extends EntityNPC { /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); + super.writeEntityToNBT(tagCompound); if (this.isCharged()) { - tagCompound.setBool("Charge", true); + tagCompound.setBoolean("Charge", true); } tagCompound.setShort("Fuse", (short)this.fuseTime); - tagCompound.setBool("ignited", this.hasIgnited()); + tagCompound.setBoolean("ignited", this.hasIgnited()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.setCharged(tagCompund.getBool("Charge")); + super.readEntityFromNBT(tagCompund); + this.setCharged(tagCompund.getBoolean("Charge")); - this.fuseTime = tagCompund.getShort("Fuse"); + if (tagCompund.hasKey("Fuse", 99)) + { + this.fuseTime = tagCompund.getShort("Fuse"); + } - if (tagCompund.getBool("ignited")) + if (tagCompund.getBoolean("ignited")) { this.ignite(); } @@ -223,7 +227,7 @@ public class EntityHaunter extends EntityNPC { public void onStruckByLightning(EntityLightning lightningBolt) { // super.onStruckByLightning(lightningBolt); - if(!this.worldObj.client && Vars.chargeHaunter) { + if(!this.worldObj.client && Config.chargeHaunter) { // int power = this.getPower(); // if(++power < 256) // this.dataWatcher.updateObject(24, (byte)power); @@ -255,7 +259,7 @@ public class EntityHaunter extends EntityNPC { { if (!this.worldObj.client) { - boolean flag = Vars.mobGrief; + boolean flag = Config.mobGrief; float f = 1.0F + (float)(this.isCharged() ? this.rand.range(3, 5) : 0) / 8.0f; this.worldObj.createAltExplosion(this, this.posX, this.posY, this.posZ, (float)this.rand.range(3, 5) * f, flag); this.setDead(); diff --git a/common/src/main/java/common/entity/npc/EntityHoveringNPC.java b/common/src/common/entity/npc/EntityHoveringNPC.java similarity index 97% rename from common/src/main/java/common/entity/npc/EntityHoveringNPC.java rename to common/src/common/entity/npc/EntityHoveringNPC.java index a4b0887..4781923 100755 --- a/common/src/main/java/common/entity/npc/EntityHoveringNPC.java +++ b/common/src/common/entity/npc/EntityHoveringNPC.java @@ -1,5 +1,6 @@ package common.entity.npc; +import common.attributes.Attributes; import common.entity.types.EntityLiving; import common.packet.CPacketAction; import common.world.World; @@ -29,10 +30,12 @@ public abstract class EntityHoveringNPC extends EntityNPC // { // return true; // } - - public int getPathingRange() { - return 32; - } + + protected void applyEntityAttributes() + { + super.applyEntityAttributes(); + this.getEntityAttribute(Attributes.FOLLOW_RANGE).setBaseValue(32.0D); + } public boolean isSneakingVisually() { return false; diff --git a/common/src/main/java/common/entity/npc/EntityHuman.java b/common/src/common/entity/npc/EntityHuman.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityHuman.java rename to common/src/common/entity/npc/EntityHuman.java diff --git a/common/src/main/java/common/entity/npc/EntityMage.java b/common/src/common/entity/npc/EntityMage.java similarity index 88% rename from common/src/main/java/common/entity/npc/EntityMage.java rename to common/src/common/entity/npc/EntityMage.java index 4811eb2..4abe982 100755 --- a/common/src/main/java/common/entity/npc/EntityMage.java +++ b/common/src/common/entity/npc/EntityMage.java @@ -2,6 +2,8 @@ package common.entity.npc; import java.util.List; +import common.attributes.AttributeInstance; +import common.attributes.Attributes; import common.entity.effect.EntityLightning; import common.entity.types.EntityLiving; import common.init.Items; @@ -27,7 +29,7 @@ public class EntityMage extends EntityNPC public void onLivingUpdate() { - if (!this.worldObj.client && !this.isPlayer()) + if (!this.worldObj.client) { if (this.drinking) { @@ -45,15 +47,12 @@ public class EntityMage extends EntityNPC { for (PotionEffect potioneffect : list) { - if(potioneffect.getPotion().isInstant()) - potioneffect.getPotion().onImpact(null, null, this, potioneffect.getAmplifier(), 1.0); - else - this.addEffect(new PotionEffect(potioneffect)); + this.addEffect(new PotionEffect(potioneffect)); } } } - this.setSpeedMod(1.0f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).removeModifier(Attributes.MAGE_POTSPEED_MOD); } } else @@ -87,7 +86,9 @@ public class EntityMage extends EntityNPC this.setItem(0, new ItemStack(Items.potion, 1, i)); this.attackTimer = this.getHeldItem().getMaxItemUseDuration(); this.drinking = true; - this.setSpeedMod(0.165f); + AttributeInstance iattributeinstance = this.getEntityAttribute(Attributes.MOVEMENT_SPEED); + iattributeinstance.removeModifier(Attributes.MAGE_POTSPEED_MOD); + iattributeinstance.applyModifier(Attributes.MAGE_POTSPEED_MOD); } else if(this.rand.chance(80)) { boolean far = this.getAttackTarget() != null && this.getAttackTarget().getDistanceSqToEntity(this) >= 256.0; diff --git a/common/src/main/java/common/entity/npc/EntityMagma.java b/common/src/common/entity/npc/EntityMagma.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityMagma.java rename to common/src/common/entity/npc/EntityMagma.java diff --git a/common/src/main/java/common/entity/npc/EntityMetalhead.java b/common/src/common/entity/npc/EntityMetalhead.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityMetalhead.java rename to common/src/common/entity/npc/EntityMetalhead.java diff --git a/common/src/main/java/common/entity/npc/EntityMobNPC.java b/common/src/common/entity/npc/EntityMobNPC.java similarity index 91% rename from common/src/main/java/common/entity/npc/EntityMobNPC.java rename to common/src/common/entity/npc/EntityMobNPC.java index a8f1be8..4504a52 100755 --- a/common/src/main/java/common/entity/npc/EntityMobNPC.java +++ b/common/src/common/entity/npc/EntityMobNPC.java @@ -1,10 +1,12 @@ package common.entity.npc; import common.ai.EntityAIHurtByTarget; +import common.attributes.AttributeInstance; +import common.attributes.Attributes; import common.entity.DamageSource; import common.entity.Entity; import common.entity.types.EntityLiving; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.world.World; public abstract class EntityMobNPC extends EntityNPC @@ -60,15 +62,20 @@ public abstract class EntityMobNPC extends EntityNPC protected void updateAITasks() { + AttributeInstance iattributeinstance = this.getEntityAttribute(Attributes.MOVEMENT_SPEED); + if (this.isAngry()) { - this.setSpeedMod(1.05f); + if (/* !this.isChild() && */ !iattributeinstance.hasModifier(Attributes.RUSHING_SPEED_MOD)) + { + iattributeinstance.applyModifier(Attributes.RUSHING_SPEED_MOD); + } --this.angerLevel; } - else + else if (iattributeinstance.hasModifier(Attributes.RUSHING_SPEED_MOD)) { - this.setSpeedMod(1.0f); + iattributeinstance.removeModifier(Attributes.RUSHING_SPEED_MOD); } // if (this.randomSoundDelay > 0 && --this.randomSoundDelay == 0) @@ -100,9 +107,9 @@ public abstract class EntityMobNPC extends EntityNPC /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); + super.writeEntityToNBT(tagCompound); tagCompound.setShort("Anger", (short)this.angerLevel); // if (this.angerTarget != null) @@ -118,9 +125,9 @@ public abstract class EntityMobNPC extends EntityNPC /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); + super.readEntityFromNBT(tagCompund); this.angerLevel = tagCompund.getShort("Anger"); // String s = tagCompund.getString("HurtBy"); // diff --git a/common/src/main/java/common/entity/npc/EntityNPC.java b/common/src/common/entity/npc/EntityNPC.java similarity index 88% rename from common/src/main/java/common/entity/npc/EntityNPC.java rename to common/src/common/entity/npc/EntityNPC.java index 74452db..9bd5118 100755 --- a/common/src/main/java/common/entity/npc/EntityNPC.java +++ b/common/src/common/entity/npc/EntityNPC.java @@ -19,11 +19,10 @@ import common.ai.EntityAISwimming; import common.ai.EntityAIWander; import common.ai.EntityAIWatchClosest; import common.ai.EntityAIWatchClosest2; -import common.attributes.UsageSlot; +import common.attributes.AttributeInstance; +import common.attributes.Attributes; import common.block.Block; -import common.block.artificial.BlockBed; -import common.collect.Lists; -import common.color.TextColor; +import common.block.BlockBed; import common.dimension.Space; import common.enchantment.Enchantment; import common.enchantment.EnchantmentHelper; @@ -33,6 +32,7 @@ import common.entity.EntityType; import common.entity.animal.EntityDragonPart; import common.entity.animal.EntityHorse; import common.entity.animal.EntityPig; +import common.entity.item.EntityBoat; import common.entity.item.EntityCart; import common.entity.item.EntityItem; import common.entity.projectile.EntityArrow; @@ -42,6 +42,7 @@ import common.entity.projectile.EntityPotion; import common.entity.projectile.EntitySnowball; import common.entity.types.EntityLiving; import common.entity.types.IEntityMultiPart; +import common.init.Config; import common.init.ItemRegistry; import common.init.Items; import common.init.NameRegistry; @@ -66,11 +67,10 @@ import common.item.ItemStack; import common.item.ItemSword; import common.item.ItemTool; import common.model.ParticleType; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.network.IClientPlayer; import common.network.IPlayer; -import common.packet.CPacketPlayerPosition; -import common.packet.CPacketPlayerLook; -import common.packet.CPacketPlayerPosLook; import common.packet.CPacketAction; import common.packet.CPacketBreak; import common.packet.CPacketInput; @@ -82,9 +82,8 @@ import common.potion.Potion; import common.potion.PotionEffect; import common.rng.Random; import common.sound.MovingSoundMinecartRiding; -import common.tags.TagObject; import common.tileentity.IInteractionObject; -import common.tileentity.Passcode; +import common.tileentity.LockCode; import common.tileentity.TileEntitySign; import common.util.BlockPos; import common.util.BoundingBox; @@ -93,7 +92,6 @@ import common.util.Facing; import common.util.PortalType; import common.util.Vec3; import common.util.WorldPos; -import common.vars.Vars; import common.village.MerchantRecipeList; import common.world.AWorldClient; import common.world.World; @@ -208,10 +206,11 @@ public abstract class EntityNPC extends EntityLiving public double chasingPosZ; private WorldPos originPos = new WorldPos(0, 64, 0, Space.INSTANCE.getDimensionId()); private WorldPos spawnPos; +// private BlockPos startMinecartRidingCoordinate; public int experienceLevel; public int experienceTotal; public float experience; - protected int enchSeed; + protected int xpSeed; private ItemStack itemInUse; private int itemInUseCount; protected float speedInAir = 0.02F; @@ -244,8 +243,8 @@ public abstract class EntityNPC extends EntityLiving public float prevRenderArmPitch; private int horseJumpPowerCounter; private float horseJumpPower; - private long movedDistance; - private int attackDamageBase = 2; +// public float nausea; +// public float prevNausea; public EntityNPC(World worldIn) { @@ -383,7 +382,7 @@ public abstract class EntityNPC extends EntityLiving this.fireResistance = 20; this.noPickup = true; // this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(1.0D); -// this.getEntityAttribute(Attribute.MOVEMENT_SPEED).setBaseValue(this.getEntityAttribute(Attribute.MOVEMENT_SPEED).getBaseValue() / 3.0); // 0.10000000149011612D); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(this.getEntityAttribute(Attributes.MOVEMENT_SPEED).getBaseValue() / 3.0); // 0.10000000149011612D); } public final void setServerPlayer(IPlayer connection) { @@ -438,8 +437,8 @@ public abstract class EntityNPC extends EntityLiving public boolean shouldFlee(EntityLiving entity) { return (this.getHealth() <= (this.getMaxHealth() / 4) || !this.canCounter(entity)) && - ((entity instanceof EntityNPC && ((((EntityNPC)entity).canAttack(this)) || - (entity == this.getAttackedBy() && ((EntityNPC)entity).canCounter(this))))); + ((entity instanceof EntityNPC && (((EntityNPC)entity).canAttack(this)) || + (entity == this.getAttackedBy() && ((EntityNPC)entity).canCounter(this)))); } // public void setCombatTask() @@ -543,19 +542,13 @@ public abstract class EntityNPC extends EntityLiving protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setSpeedBase(0.3f); + this.getEntityAttribute(Attributes.FOLLOW_RANGE).setBaseValue(20.0D); + this.getAttributeMap().registerAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(2.0D); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.3D); this.setMaxHealth(this.getBaseHealth(this.rand)); - if(this.canUseMagic()) - this.setMaxMana(20); + this.getAttributeMap().registerAttribute(Attributes.MANA_CAPACITY); + this.getEntityAttribute(Attributes.MANA_CAPACITY).setBaseValue(20.0D); } - - public int getPathingRange() { - return 20; - } - - public boolean isPotionApplicable(Potion potion, int amplifier) { - return true; - } // protected int getExperiencePoints(EntityNPC player) // { @@ -566,9 +559,9 @@ public abstract class EntityNPC extends EntityLiving { // if (!player.creative) // { - --stack.size; + --stack.stackSize; - if (stack.size <= 0) + if (stack.stackSize <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } @@ -599,7 +592,7 @@ public abstract class EntityNPC extends EntityLiving { super.onLivingUpdate(); - if(!this.worldObj.client && /* this.canPickUpLoot() && */ !this.noPickup && Vars.mobGrief) { + if(!this.worldObj.client && /* this.canPickUpLoot() && */ !this.noPickup && Config.mobGrief) { for(EntityItem entityitem : this.worldObj.getEntitiesWithinAABB(EntityItem.class, this.getEntityBoundingBox().expand(1.0D, 0.0D, 1.0D))) { if(!entityitem.dead && entityitem.getEntityItem() != null && !entityitem.cannotPickup()) { this.updateEquipmentIfNeeded(entityitem); @@ -684,9 +677,9 @@ public abstract class EntityNPC extends EntityLiving public boolean attackEntityAsMob(Entity entityIn) { - if(!this.worldObj.client && !Vars.damageMobs) + if(!this.worldObj.client && !Config.damageMobs) return false; - int f = this.getAttackDamage(); + int f = (int)this.getEntityAttribute(Attributes.ATTACK_DAMAGE).getAttributeValue(); int i = 0; if (entityIn instanceof EntityLiving) @@ -726,8 +719,8 @@ public abstract class EntityNPC extends EntityLiving return; if(stack.getItem() == Items.bow) { EntityArrow entityarrow = new EntityArrow(this.worldObj, this, target, 1.6F, 2.0f); - int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.POWER, this.getHeldItem()); - int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.PUNCH, this.getHeldItem()); + int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, this.getHeldItem()); + int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, this.getHeldItem()); entityarrow.setDamage((double)(range * 2.0F) + this.rand.gaussian() * 0.25D + (double)(/* (float)this.worldObj.getDifficulty().getId() */ 3.0f * 0.11F)); if (i > 0) @@ -740,7 +733,7 @@ public abstract class EntityNPC extends EntityLiving entityarrow.setKnockbackStrength(j); } - if (EnchantmentHelper.getEnchantmentLevel(Enchantment.FLAME, this.getHeldItem()) > 0) + if (EnchantmentHelper.getEnchantmentLevel(Enchantment.flame.effectId, this.getHeldItem()) > 0) { entityarrow.setFire(100); } @@ -750,7 +743,7 @@ public abstract class EntityNPC extends EntityLiving } else if(stack.getItem() instanceof ItemGunBase) { EntityBullet bullet = new EntityBullet(this.worldObj, this, target, ((ItemGunBase)stack.getItem()).getVelocity(), 0.75f); - int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.POWER, this.getHeldItem()); + int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, this.getHeldItem()); // int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, this.getHeldItem()); bullet.setDamage(((ItemGunBase)stack.getItem()).getAmmo().getDamage(stack)); @@ -839,12 +832,12 @@ public abstract class EntityNPC extends EntityLiving public void setChar(String character) { - this.dataWatcher.updateObject(9, character); + this.dataWatcher.updateObject(16, character); } public String getChar() { - return this.dataWatcher.getWatchableObjectString(9); + return this.dataWatcher.getWatchableObjectString(16); } public void setCape(String cape) @@ -859,12 +852,12 @@ public abstract class EntityNPC extends EntityLiving public void setNpcClass(Enum type) { - this.dataWatcher.updateObject(10, (byte)(type == null ? -1 : type.ordinal())); + this.dataWatcher.updateObject(22, (byte)(type == null ? -1 : type.ordinal())); } public Enum getNpcClass() { - byte n = this.dataWatcher.getWatchableObjectByte(10); + byte n = this.dataWatcher.getWatchableObjectByte(22); return n < 0 || this.species == null || this.species.classEnum == null ? null : this.species.classEnum.getEnumConstants()[n % this.species.classEnum.getEnumConstants().length]; } @@ -872,22 +865,22 @@ public abstract class EntityNPC extends EntityLiving public void setAlignment(Alignment align) { this.alignment = align; - this.dataWatcher.updateObject(8, (byte)align.ordinal()); + this.dataWatcher.updateObject(18, (byte)align.ordinal()); } public Alignment getAlignment() { - return Alignment.values()[this.dataWatcher.getWatchableObjectByte(8) % Alignment.values().length]; + return Alignment.values()[this.dataWatcher.getWatchableObjectByte(18) % Alignment.values().length]; } public void setHeight(float height) { - this.dataWatcher.updateObject(11, ExtMath.clampf(height, 0.2f, 10.0f)); + this.dataWatcher.updateObject(29, ExtMath.clampf(height, 0.2f, 10.0f)); } public float getHeight() { - return this.dataWatcher.getWatchableObjectFloat(11); + return this.dataWatcher.getWatchableObjectFloat(29); } public SpeciesInfo getSpecies() { @@ -897,7 +890,7 @@ public abstract class EntityNPC extends EntityLiving public void setAttackedBy(EntityLiving livingBase) { if(livingBase != null && /* livingBase.isPlayer() && */ this.isEntityAlive() && /* !this.isPeaceful() && */ this.getAttackedBy() != livingBase && - Vars.mobAttacks && !this.isPlayer()) { + Config.mobAttacks) { this.worldObj.setEntityState(this, (byte)13); } super.setAttackedBy(livingBase); @@ -1080,11 +1073,11 @@ public abstract class EntityNPC extends EntityLiving } public int getManaPoints() { - return this.dataWatcher.getWatchableObjectInt(14); + return this.dataWatcher.getWatchableObjectInt(21); } public void setManaPoints(int pts) { - this.dataWatcher.updateObject(14, pts); + this.dataWatcher.updateObject(21, pts); } // public final boolean isAggressive() { @@ -1190,21 +1183,8 @@ public abstract class EntityNPC extends EntityLiving // return air; // } - public final int getMaxMana() { - return this.dataWatcher.getWatchableObjectInt(13); - } - - public final void setMaxMana(int mana) { - this.dataWatcher.updateObject(13, mana); - } - - public void healMana(int amount) { - if(this.client == null) - this.setManaPoints(ExtMath.clampi(this.getManaPoints() + amount, 0, this.getMaxMana())); - } - - public String formatStats() { - return super.formatStats() + (this.getManaPoints() == 0 ? "" : TextColor.GRAY + " [" + TextColor.MIDNIGHT + this.getManaPoints() + TextColor.GRAY + "]"); + public int getMaxMana() { + return (int)this.getEntityAttribute(Attributes.MANA_CAPACITY).getAttributeValue(); } public MerchantRecipeList getTrades(EntityNPC player) { @@ -1462,7 +1442,7 @@ public abstract class EntityNPC extends EntityLiving } else { - stack.size = remain.size; + stack.stackSize = remain.stackSize; } } } @@ -1701,12 +1681,12 @@ public abstract class EntityNPC extends EntityLiving if (itemstack != null) { - this.attributes.remove(itemstack.getAttributeModifiers(UsageSlot.getByIndex(j)), -1 - j); + this.getAttributeMap().removeAttributeModifiers(itemstack.getAttributeModifiers(1)); } if (itemstack1 != null) { - this.attributes.add(itemstack1.getAttributeModifiers(UsageSlot.getByIndex(j)), -1 - j, itemstack1.size); + this.getAttributeMap().applyAttributeModifiers(itemstack1.getAttributeModifiers(1)); } this.prevEquipment[j] = itemstack1 == null ? null : itemstack1.copy(); @@ -1714,7 +1694,7 @@ public abstract class EntityNPC extends EntityLiving } } super.onUpdate(); - if(!this.worldObj.client && Vars.regeneration && this.shouldHeal()) { + if(!this.worldObj.client && Config.regeneration && this.shouldHeal()) { ++this.healTimer; if(this.healTimer >= 80) { @@ -1733,8 +1713,8 @@ public abstract class EntityNPC extends EntityLiving // } protected boolean shouldHeal() { - return this.canRegenerateHealth() && Vars.healChance > 0 && this.getHealth() > 0 && this.getHealth() < this.getMaxHealth() - && this.rand.chance(Vars.healChance); + return this.canRegenerateHealth() && Config.healChance > 0 && this.getHealth() > 0 && this.getHealth() < this.getMaxHealth() + && this.rand.chance(Config.healChance); } public byte[] getSkin() { @@ -1782,6 +1762,12 @@ public abstract class EntityNPC extends EntityLiving if(this.client == null) super.heal(healAmount); } + + public void healMana(int amount) + { + if(this.client == null) + super.healMana(amount); + } /** * Called when a player mounts an entity. e.g. mounts a pig, mounts a boat. @@ -1813,7 +1799,7 @@ public abstract class EntityNPC extends EntityLiving if (this.isRiding()) { - this.client.addToSendQueue(new CPacketPlayerLook(this.rotYaw, this.rotPitch, this.onGround)); + this.client.addToSendQueue(new CPacketPlayer.C05PacketPlayerLook(this.rotYaw, this.rotPitch, this.onGround)); this.client.addToSendQueue(new CPacketInput(this.moveStrafe, this.moveForward, this.client.isJumping(), this.client.isSneaking())); } else @@ -1984,7 +1970,7 @@ public abstract class EntityNPC extends EntityLiving this.client.addToSendQueue(new CPacketBreak(c07packetplayerdigging$action, BlockPos.ORIGIN, Facing.DOWN)); return null; } - return this.dropItem(this.inventory.decrStackSize(this.inventory.currentItem, dropAll && this.inventory.getCurrentItem() != null ? this.inventory.getCurrentItem().size : 1), false, true); + return this.dropItem(this.inventory.decrStackSize(this.inventory.currentItem, dropAll && this.inventory.getCurrentItem() != null ? this.inventory.getCurrentItem().stackSize : 1), false, true); } /** @@ -2063,6 +2049,12 @@ public abstract class EntityNPC extends EntityLiving { if(this.connection != null) this.connection.closeScreen(); + else if(this.client != null) { +// this.setScreenClosed(); +// this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.CLOSE_CONTAINER)); // , this.openContainer.windowId)); +// this.closeScreenAndDropStack(); + this.client.closeGui(); + } else this.openContainer = this.inventoryContainer; } @@ -2167,13 +2159,15 @@ public abstract class EntityNPC extends EntityLiving public boolean isTicked() { - return (!this.worldObj.client && (Vars.mobTick || this.connection != null)) || this.client != null; + return (!this.worldObj.client && (Config.mobTick || this.connection != null)) || this.client != null; } public void openEditSign(TileEntitySign signTile) { if(this.connection != null) this.connection.openEditSign(signTile); + else if(this.client != null) + this.client.displayGuiSign(signTile.getPos(), signTile.signText); } /** @@ -2200,18 +2194,26 @@ public abstract class EntityNPC extends EntityLiving { if(this.connection != null) this.connection.displayGUIChest(chestInventory); + else if(this.client != null) { + this.client.displayGUIChest(chestInventory, this.inventory); + } } - public void displayEntityGui(Entity entity, IInventory inventory) + public void displayGUIHorse(EntityHorse horse, IInventory horseInventory) { if(this.connection != null) - this.connection.displayEntityGui(entity, inventory); + this.connection.displayGUIHorse(horse, horseInventory); + else if(this.client != null) + this.client.displayGuiHorse(horse, this.inventory, horseInventory); } public void displayGui(IInteractionObject guiOwner) { if(this.connection != null) this.connection.displayGui(guiOwner); + else if(this.client != null) { + this.client.displayGui(guiOwner, this.inventory, this.worldObj); + } } /** @@ -2548,6 +2550,7 @@ public abstract class EntityNPC extends EntityLiving this.prevCameraYaw = this.cameraYaw; // super.onLivingUpdate(); this.onNpcUpdate(); + AttributeInstance iattributeinstance = this.getEntityAttribute(Attributes.MOVEMENT_SPEED); this.jumpMovement = this.speedInAir; @@ -2556,7 +2559,7 @@ public abstract class EntityNPC extends EntityLiving this.jumpMovement = (float)((double)this.jumpMovement + (double)this.speedInAir * 0.3D); } - this.setAIMoveSpeed(this.getMovementSpeed() / 3.0f); + this.setAIMoveSpeed((float)iattributeinstance.getAttributeValue()); float f = ExtMath.sqrtd(this.motionX * this.motionX + this.motionZ * this.motionZ); float f1 = (float)(Math.atan(-this.motionY * 0.20000000298023224D) * 15.0D); @@ -2664,15 +2667,15 @@ public abstract class EntityNPC extends EntityLiving { if (flag2 && flag3) { - this.client.addToSendQueue(new CPacketPlayerPosLook(this.posX, this.getEntityBoundingBox().minY, this.posZ, this.rotYaw, this.rotPitch, this.onGround)); + this.client.addToSendQueue(new CPacketPlayer.C06PacketPlayerPosLook(this.posX, this.getEntityBoundingBox().minY, this.posZ, this.rotYaw, this.rotPitch, this.onGround)); } else if (flag2) { - this.client.addToSendQueue(new CPacketPlayerPosition(this.posX, this.getEntityBoundingBox().minY, this.posZ, this.onGround)); + this.client.addToSendQueue(new CPacketPlayer.C04PacketPlayerPosition(this.posX, this.getEntityBoundingBox().minY, this.posZ, this.onGround)); } else if (flag3) { - this.client.addToSendQueue(new CPacketPlayerLook(this.rotYaw, this.rotPitch, this.onGround)); + this.client.addToSendQueue(new CPacketPlayer.C05PacketPlayerLook(this.rotYaw, this.rotPitch, this.onGround)); } else { @@ -2681,7 +2684,7 @@ public abstract class EntityNPC extends EntityLiving } else { - this.client.addToSendQueue(new CPacketPlayerPosLook(this.motionX, -99999999.0D, this.motionZ, this.rotYaw, this.rotPitch, this.onGround)); + this.client.addToSendQueue(new CPacketPlayer.C06PacketPlayerPosLook(this.motionX, -999.0D, this.motionZ, this.rotYaw, this.rotPitch, this.onGround)); flag2 = false; } @@ -2768,6 +2771,9 @@ public abstract class EntityNPC extends EntityLiving return !this.worldObj.getState(pos).getBlock().isNormalCube() && (this.height <= 1.0f || !this.worldObj.getState(pos.up()).getBlock().isNormalCube()); } + /** + * Sets the current XP, total XP, and level number. + */ public void setXPStats(float currentXP, int maxXP, int level) { this.experience = currentXP; @@ -2785,13 +2791,18 @@ public abstract class EntityNPC extends EntityLiving return this.horseJumpPower; } + public void displayTradeGui(String title) + { + this.client.displayGuiMerchant(title, this.inventory, this.worldObj); + } + // END SP SPEC // START OTHER - public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) { if(this.slave && this.client == null) { this.otherPlayerMPX = x; @@ -2799,10 +2810,10 @@ public abstract class EntityNPC extends EntityLiving this.otherPlayerMPZ = z; this.otherPlayerMPYaw = (double)yaw; this.otherPlayerMPPitch = (double)pitch; - this.otherPlayerMPPosRotationIncrements = 3; + this.otherPlayerMPPosRotationIncrements = posRotationIncrements; } else { - super.setClientPosition(x, y, z, yaw, pitch, teleport); + super.setPositionAndRotation2(x, y, z, yaw, pitch, posRotationIncrements, p_180426_10_); } } @@ -2829,7 +2840,7 @@ public abstract class EntityNPC extends EntityLiving // START MP - private void addExperienceLevel(int levels) { + public void addExperienceLevel(int levels) { this.experienceLevel += levels; if (this.experienceLevel < 0) @@ -2850,8 +2861,20 @@ public abstract class EntityNPC extends EntityLiving this.connection.resetLastExperience(); } - public void updateEnchSeed() { - this.enchSeed = this.rand.intv(); + public void removeExperienceLevel(int levels) { + this.experienceLevel -= levels; + + if (this.experienceLevel < 0) + { + this.experienceLevel = 0; + this.experience = 0.0F; + this.experienceTotal = 0; + } + + this.xpSeed = this.rand.intv(); +// super.removeExperienceLevel(levels); + if(this.connection != null) + this.connection.resetLastExperience(); } public void onDeath(DamageSource cause) { @@ -2871,7 +2894,7 @@ public abstract class EntityNPC extends EntityLiving this.setPosition(this.posX, this.posY, this.posZ); this.motionY = 0.10000000149011612D; - if (this.worldObj.client || (!Vars.keepInventory && Vars.playerDrop)) + if (this.worldObj.client || (!Config.keepInventory && Config.playerDrop)) { this.inventory.dropAllItems(); } @@ -2915,14 +2938,16 @@ public abstract class EntityNPC extends EntityLiving super.updateFallState(y, onGroundIn, blockIn, pos); } - public void addMoved(int amount) { - this.movedDistance += (long)amount; - } - - public long getMovedDistance() { - return this.movedDistance; + public void addStat(int amount) { +// if(this.connection != null) +// this.connection.addStat(amount); } +// public void removeStat(StatBase stat) { +// if(this.connection != null) +// this.connection.removeStat(stat); +// } + protected void onItemUseFinish() { if(this.connection != null) this.connection.onItemUseFinish(); @@ -2930,14 +2955,14 @@ public abstract class EntityNPC extends EntityLiving if (this.itemInUse != null) { this.updateItemUse(this.itemInUse, 16); - int i = this.itemInUse.size; + int i = this.itemInUse.stackSize; ItemStack itemstack = this.itemInUse.onItemUseFinish(this.worldObj, this); - if (itemstack != this.itemInUse || itemstack != null && itemstack.size != i) + if (itemstack != this.itemInUse || itemstack != null && itemstack.stackSize != i) { this.inventory.mainInventory[this.inventory.currentItem] = itemstack; - if (itemstack.size == 0) + if (itemstack.stackSize == 0) { this.inventory.mainInventory[this.inventory.currentItem] = null; } @@ -3012,16 +3037,17 @@ public abstract class EntityNPC extends EntityLiving protected void entityInit() { super.entityInit(); - this.dataWatcher.addObject(8, (byte)Alignment.NEUTRAL.ordinal()); // alignment - this.dataWatcher.addObject(9, ""); // character - this.dataWatcher.addObject(10, (byte)-1); // class - this.dataWatcher.addObject(11, 1.0f); // height - this.dataWatcher.addObject(12, 0); // absorption - this.dataWatcher.addObject(13, 0); // max mana - this.dataWatcher.addObject(14, 0); // mana - this.dataWatcher.addObject(15, 0.7f); - - this.dataWatcher.addObject(17, ""); // TODO: remove capes + this.dataWatcher.addObject(16, ""); + this.dataWatcher.addObject(17, ""); + this.dataWatcher.addObject(18, Byte.valueOf((byte)Alignment.NEUTRAL.ordinal())); +// this.dataWatcher.addObject(20, Byte.valueOf((byte)0)); + this.dataWatcher.addObject(21, 0); + this.dataWatcher.addObject(22, Byte.valueOf((byte)-1)); + this.dataWatcher.addObject(29, 1.0f); +// super.entityInit(); + this.dataWatcher.addObject(30, Integer.valueOf(0)); +// this.dataWatcher.addObject(10, Integer.valueOf(~ModelPart.ARMS_SLIM.getMask())); +// this.dataWatcher.addObject(11, Byte.valueOf((byte)0)); } /** @@ -3150,7 +3176,7 @@ public abstract class EntityNPC extends EntityLiving super.updateRidden(); this.prevCameraYaw = this.cameraYaw; this.cameraYaw = 0.0F; - this.addMountedMovement(this.posX - d0, this.posY - d1, this.posZ - d2); + this.addMountedMovementStat(this.posX - d0, this.posY - d1, this.posZ - d2); if (this.vehicle instanceof EntityPig) { @@ -3179,7 +3205,7 @@ public abstract class EntityNPC extends EntityLiving } public void onDataWatcherUpdate(int data) { - if(this.isPlayer() && data == 11) // (data == 29 || data == 11)) // && this.worldObj.client) + if(this.isPlayer() && data == 29) // (data == 29 || data == 11)) // && this.worldObj.client) this.updateSize(); } @@ -3206,7 +3232,7 @@ public abstract class EntityNPC extends EntityLiving protected float getJumpUpwardsMotion() { - return 0.42F * ((this.height < 1.9f ? 1.9f : this.height) /* this.getHeight() * 1.8f */ + 2.2f) / 4.0f; + return 0.42F * (this.height /* this.getHeight() * 1.8f */ + 2.2f) / 4.0f; } public void setAIMoveSpeed(float speedIn) @@ -3235,7 +3261,7 @@ public abstract class EntityNPC extends EntityLiving { return null; } - else if (droppedItem.size == 0) + else if (droppedItem.stackSize == 0) { return null; } @@ -3347,44 +3373,31 @@ public abstract class EntityNPC extends EntityLiving { return this.inventory.canHeldItemHarvest(blockToHarvest); } - - public int getAttackDamage() { - int damage = this.attackDamageBase + (this.getHeldItem() == null ? 0 : this.getHeldItem().getItem().getAttackDamageBonus()); - return Math.max(0, damage + (this.hasEffect(Potion.STRENGTH) ? (damage / 2) * (this.getEffect(Potion.STRENGTH).getAmplifier() + 1) : 0) - (this.hasEffect(Potion.WEAKNESS) ? (damage / 5) * (this.getEffect(Potion.WEAKNESS).getAmplifier() + 1) : 0)); - } - - public int getAttackDamageBase() { - return this.attackDamageBase; - } - - public void setAttackDamageBase(int value) { - this.attackDamageBase = value; - } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { // super.readEntityFromNBT(tagCompund); - super.readEntity(tagCompund); + super.readEntityFromNBT(tagCompund); -// if(tagCompund.hasBoolean("CanPickUpLoot")) { +// if(tagCompund.hasKey("CanPickUpLoot", 1)) { // this.setCanPickUpLoot(tagCompund.getBoolean("CanPickUpLoot")); // } - if(tagCompund.hasList("Equipment")) { - List nbttaglist = tagCompund.getList("Equipment"); + if(tagCompund.hasKey("Equipment", 9)) { + NBTTagList nbttaglist = tagCompund.getTagList("Equipment", 10); for(int i = 0; i < this.equipment.length; ++i) { - this.equipment[i] = ItemStack.readFromTag(nbttaglist.get(i)); + this.equipment[i] = ItemStack.loadItemStackFromNBT(nbttaglist.getCompoundTagAt(i)); } } // this.setSpecies(tagCompund.getString("Species")); this.setChar(tagCompund.getString("Char")); this.setCape(tagCompund.getString("Cape")); - this.isWilling = tagCompund.getBool("Willing"); - this.setMating(tagCompund.getBool("Mating")); + this.isWilling = tagCompund.getBoolean("Willing"); + this.setMating(tagCompund.getBoolean("Mating")); Alignment // align; // try { align = Alignment.getByName(tagCompund.getString("Align")); @@ -3393,11 +3406,9 @@ public abstract class EntityNPC extends EntityLiving // align = this.getNaturalAlign(this.rand); // } this.setAlignment(align); - this.setMaxMana(Math.max(0, tagCompund.getInt("MaxMana"))); - this.setManaPoints(tagCompund.getInt("Mana")); - this.attackDamageBase = tagCompund.getInt("AttackDmg"); + this.setManaPoints(tagCompund.getInteger("Mana")); Enum type = null; - if(tagCompund.hasString("ClassType") && this.species != null && this.species.classEnum != null) { + if(tagCompund.hasKey("ClassType", 8) && this.species != null && this.species.classEnum != null) { type = this.species.classnames.get(tagCompund.getString("ClassType")); // try { // type = Enum.valueOf(this.species.classEnum, tagCompund.getString("ClassType").toUpperCase()); @@ -3407,13 +3418,13 @@ public abstract class EntityNPC extends EntityLiving // } } this.setNpcClass(type); - this.setHeight(tagCompund.hasFloat("Height") ? tagCompund.getFloat("Height") : this.getBaseSize()); + this.setHeight(tagCompund.hasKey("Height", 5) ? tagCompund.getFloat("Height") : this.getBaseSize()); - List nbttaglist = tagCompund.getList("Items"); + NBTTagList nbttaglist = tagCompund.getTagList("Items", 10); - for (int i = 0; i < nbttaglist.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - ItemStack itemstack = ItemStack.readFromTag(nbttaglist.get(i)); + ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttaglist.getCompoundTagAt(i)); if (itemstack != null) { @@ -3421,12 +3432,10 @@ public abstract class EntityNPC extends EntityLiving } } - if(tagCompund.hasList("Offers")) { - this.trades = new MerchantRecipeList(); - this.trades.fromTags(tagCompund.getList("Offers")); - } - this.healTimer = tagCompund.getInt("healTimer"); - if(tagCompund.hasByteArray("Skin")) + if(tagCompund.hasKey("Offers", 10)) + this.trades = new MerchantRecipeList(tagCompund.getCompoundTag("Offers")); + this.healTimer = tagCompund.getInteger("healTimer"); + if(tagCompund.hasKey("Skin", 7)) this.skin = tagCompund.getByteArray("Skin"); // this.setCanPickUpLoot(true); @@ -3434,19 +3443,19 @@ public abstract class EntityNPC extends EntityLiving if(this.isPlayer()) { // this.entityUniqueID = getOfflineUUID(this.user); - List nbttaglist0 = tagCompund.getList("Inventory"); + NBTTagList nbttaglist0 = tagCompund.getTagList("Inventory", 10); this.inventory.readFromNBT(nbttaglist0); - this.inventory.currentItem = tagCompund.getInt("SelectedItemSlot"); + this.inventory.currentItem = tagCompund.getInteger("SelectedItemSlot"); // this.sleeping = tagCompund.getBoolean("Sleeping"); // this.sleepTimer = tagCompund.getShort("SleepTimer"); this.experience = tagCompund.getFloat("XpP"); - this.experienceLevel = tagCompund.getInt("XpLevel"); - this.experienceTotal = tagCompund.getInt("XpTotal"); - this.enchSeed = tagCompund.getInt("EnchSeed"); + this.experienceLevel = tagCompund.getInteger("XpLevel"); + this.experienceTotal = tagCompund.getInteger("XpTotal"); + this.xpSeed = tagCompund.getInteger("XpSeed"); - if (this.enchSeed == 0) + if (this.xpSeed == 0) { - this.enchSeed = this.rand.intv(); + this.xpSeed = this.rand.intv(); } // this.setScore(tagCompund.getInteger("Score")); @@ -3458,37 +3467,35 @@ public abstract class EntityNPC extends EntityLiving // this.wakeUpPlayer(); // } - if (tagCompund.hasInt("SpawnX") && tagCompund.hasInt("SpawnY") && tagCompund.hasInt("SpawnZ")) + if (tagCompund.hasKey("SpawnX", 99) && tagCompund.hasKey("SpawnY", 99) && tagCompund.hasKey("SpawnZ", 99)) { - this.spawnPos = new WorldPos(tagCompund.getInt("SpawnX"), tagCompund.getInt("SpawnY"), - tagCompund.getInt("SpawnZ"), tagCompund.getInt("SpawnDim")); + this.spawnPos = new WorldPos(tagCompund.getInteger("SpawnX"), tagCompund.getInteger("SpawnY"), + tagCompund.getInteger("SpawnZ"), tagCompund.getInteger("SpawnDim")); // this.spawnForced = tagCompund.getBoolean("SpawnForced"); } - if (tagCompund.hasInt("OriginX") && tagCompund.hasInt("OriginY") && tagCompund.hasInt("OriginZ")) + if (tagCompund.hasKey("OriginX", 99) && tagCompund.hasKey("OriginY", 99) && tagCompund.hasKey("OriginZ", 99)) { - this.originPos = new WorldPos(tagCompund.getInt("OriginX"), tagCompund.getInt("OriginY"), - tagCompund.getInt("OriginZ"), tagCompund.getInt("OriginDim")); + this.originPos = new WorldPos(tagCompund.getInteger("OriginX"), tagCompund.getInteger("OriginY"), + tagCompund.getInteger("OriginZ"), tagCompund.getInteger("OriginDim")); } // this.foodStats.readNBT(tagCompund); // this.readCapabilitiesFromNBT(tagCompund); - this.flying = tagCompund.getBool("flying") && (this.hasEffect(Potion.FLYING) || this.canNaturallyFly()); + this.flying = tagCompund.getBoolean("flying") && (this.hasEffect(Potion.FLYING) || this.canNaturallyFly()); // if(tagCompund.hasKey("speed", 99)) // this.speed = tagCompund.getFloat("speed"); // this.disableDamagePersist = tagCompund.getBoolean("alwaysInvulnerable"); // this.disableTargetPersist = tagCompund.getBoolean("neverTarget"); // this.allowFlyingPersist = tagCompund.getBoolean("alwaysFly"); - this.noclip = tagCompund.getBool("noClip"); + this.noclip = tagCompund.getBoolean("noClip"); - if (tagCompund.hasList("WarpItems")) + if (tagCompund.hasKey("WarpItems", 9)) { - List nbttaglist1 = tagCompund.getList("WarpItems"); - this.warpChest.readTags(nbttaglist1); + NBTTagList nbttaglist1 = tagCompund.getTagList("WarpItems", 10); + this.warpChest.loadInventoryFromNBT(nbttaglist1); } - this.movedDistance = tagCompund.getLong("MovedDist"); - // ModelType // model; // try { // model = ModelType.getByName(tagCompund.getString("Model")); @@ -3497,8 +3504,8 @@ public abstract class EntityNPC extends EntityLiving // model = ModelType.HUMANOID; // } // this.setModel(model); -// this.setModelParts(tagCompund.hasInt("PartFlags") ? tagCompund.getInteger("PartFlags") : ~ModelPart.ARMS_SLIM.getMask()); - // if(tagCompund.hasFloat("PlayerScale")) +// this.setModelParts(tagCompund.hasKey("PartFlags", 3) ? tagCompund.getInteger("PartFlags") : ~ModelPart.ARMS_SLIM.getMask()); + // if(tagCompund.hasKey("PlayerScale", 5)) // this.setPlayerHeight(tagCompund.getFloat("PlayerScale")); } } @@ -3506,40 +3513,48 @@ public abstract class EntityNPC extends EntityLiving /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { + if(this.isPlayer()) { + for (int z = 0; z < this.inventory.mainInventory.length; z++) + { + ItemStack itemstack = this.inventory.mainInventory[z]; + if (itemstack != null) + { + this.getAttributeMap().removeAttributeModifiers(itemstack.getAttributeModifiers(2), z, itemstack.stackSize); + } + } + } // super.writeEntityToNBT(tagCompound); - super.writeEntity(tagCompound); + super.writeEntityToNBT(tagCompound); // tagCompound.setBoolean("CanPickUpLoot", this.canPickUpLoot()); - List nbttaglist0 = Lists.newArrayList(); + NBTTagList nbttaglist0 = new NBTTagList(); for(int i = 0; i < this.equipment.length; ++i) { - TagObject nbttagcompound = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); if(this.equipment[i] != null) { - this.equipment[i].writeTags(nbttagcompound); + this.equipment[i].writeToNBT(nbttagcompound); } - nbttaglist0.add(nbttagcompound); + nbttaglist0.appendTag(nbttagcompound); } - tagCompound.setList("Equipment", nbttaglist0); + tagCompound.setTag("Equipment", nbttaglist0); // tagCompound.setString("Species", this.getSpecies()); tagCompound.setString("Char", this.getChar()); tagCompound.setString("Cape", this.getCape()); - tagCompound.setBool("Willing", this.isWilling); - tagCompound.setBool("Mating", this.isMating()); + tagCompound.setBoolean("Willing", this.isWilling); + tagCompound.setBoolean("Mating", this.isMating()); tagCompound.setString("Align", this.alignment.name); tagCompound.setFloat("Height", this.getHeight()); - tagCompound.setInt("MaxMana", this.getMaxMana()); - tagCompound.setInt("Mana", this.getManaPoints()); - tagCompound.setInt("AttackDmg", this.attackDamageBase); + tagCompound.setInteger("Mana", this.getManaPoints()); Enum type = this.getNpcClass(); if(type != null) tagCompound.setString("ClassType", this.species.classnames.inverse().get(type)); - List nbttaglist = Lists.newArrayList(); + NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < this.extraInventory.getSizeInventory(); ++i) { @@ -3547,65 +3562,71 @@ public abstract class EntityNPC extends EntityLiving if (itemstack != null) { - nbttaglist.add(itemstack.writeTags(new TagObject())); + nbttaglist.appendTag(itemstack.writeToNBT(new NBTTagCompound())); } } - tagCompound.setList("Items", nbttaglist); + tagCompound.setTag("Items", nbttaglist); if(this.trades != null) - tagCompound.setList("Offers", this.trades.toTags()); - tagCompound.setInt("healTimer", this.healTimer); + tagCompound.setTag("Offers", this.trades.getRecipiesAsTags()); + tagCompound.setInteger("healTimer", this.healTimer); if(this.skin != null) tagCompound.setByteArray("Skin", this.skin); if(this.isPlayer()) { - tagCompound.setList("Inventory", this.inventory.writeToNBT(Lists.newArrayList())); - tagCompound.setInt("SelectedItemSlot", this.inventory.currentItem); + for (int z = 0; z < this.inventory.mainInventory.length; z++) + { + ItemStack itemstack = this.inventory.mainInventory[z]; + if (itemstack != null) + { + this.getAttributeMap().applyAttributeModifiers(itemstack.getAttributeModifiers(2), z, itemstack.stackSize); + } + } + tagCompound.setTag("Inventory", this.inventory.writeToNBT(new NBTTagList())); + tagCompound.setInteger("SelectedItemSlot", this.inventory.currentItem); // tagCompound.setBoolean("Sleeping", this.sleeping); // tagCompound.setShort("SleepTimer", (short)this.sleepTimer); tagCompound.setFloat("XpP", this.experience); - tagCompound.setInt("XpLevel", this.experienceLevel); - tagCompound.setInt("XpTotal", this.experienceTotal); - tagCompound.setInt("EnchSeed", this.enchSeed); + tagCompound.setInteger("XpLevel", this.experienceLevel); + tagCompound.setInteger("XpTotal", this.experienceTotal); + tagCompound.setInteger("XpSeed", this.xpSeed); // tagCompound.setInteger("Score", this.getScore()); // tagCompound.setInteger("Mana", this.getManaPoints()); if (this.spawnPos != null) { - tagCompound.setInt("SpawnX", this.spawnPos.getX()); - tagCompound.setInt("SpawnY", this.spawnPos.getY()); - tagCompound.setInt("SpawnZ", this.spawnPos.getZ()); - tagCompound.setInt("SpawnDim", this.spawnPos.getDimension()); + tagCompound.setInteger("SpawnX", this.spawnPos.getX()); + tagCompound.setInteger("SpawnY", this.spawnPos.getY()); + tagCompound.setInteger("SpawnZ", this.spawnPos.getZ()); + tagCompound.setInteger("SpawnDim", this.spawnPos.getDimension()); // tagCompound.setBoolean("SpawnForced", this.spawnForced); } if (this.originPos != null) { - tagCompound.setInt("OriginX", this.originPos.getX()); - tagCompound.setInt("OriginY", this.originPos.getY()); - tagCompound.setInt("OriginZ", this.originPos.getZ()); - tagCompound.setInt("OriginDim", this.originPos.getDimension()); + tagCompound.setInteger("OriginX", this.originPos.getX()); + tagCompound.setInteger("OriginY", this.originPos.getY()); + tagCompound.setInteger("OriginZ", this.originPos.getZ()); + tagCompound.setInteger("OriginDim", this.originPos.getDimension()); } // this.foodStats.writeNBT(tagCompound); // this.writeCapabilitiesToNBT(tagCompound); - tagCompound.setBool("flying", this.flying); + tagCompound.setBoolean("flying", this.flying); // tagCompound.setFloat("speed", this.speed); // tagCompound.setBoolean("alwaysInvulnerable", this.disableDamagePersist); // tagCompound.setBoolean("neverTarget", this.disableTargetPersist); // tagCompound.setBoolean("alwaysFly", this.allowFlyingPersist); - tagCompound.setBool("noClip", this.noclip); + tagCompound.setBoolean("noClip", this.noclip); - tagCompound.setList("WarpItems", this.warpChest.writeTags()); + tagCompound.setTag("WarpItems", this.warpChest.saveInventoryToNBT()); ItemStack itemstack = this.inventory.getCurrentItem(); if (itemstack != null && itemstack.getItem() != null) { - tagCompound.setObject("SelectedItem", itemstack.writeTags(new TagObject())); + tagCompound.setTag("SelectedItem", itemstack.writeToNBT(new NBTTagCompound())); } - tagCompound.setLong("MovedDist", this.movedDistance); - // tagCompound.setString("Model", this.getModel().name); // tagCompound.setInteger("PartFlags", this.getModelParts()); // tagCompound.setFloat("PlayerScale", this.getPlayerHeight()); @@ -3653,7 +3674,7 @@ public abstract class EntityNPC extends EntityLiving if (itemstack.interactWithEntity(this, (EntityLiving)targetEntity)) { - if (itemstack.size <= 0) // && !this.creative) + if (itemstack.stackSize <= 0) // && !this.creative) { this.destroyCurrentEquippedItem(); } @@ -3668,7 +3689,7 @@ public abstract class EntityNPC extends EntityLiving { if (itemstack != null && itemstack == this.getCurrentEquippedItem()) { - if (itemstack.size <= 0) // && !this.creative) + if (itemstack.stackSize <= 0) // && !this.creative) { this.destroyCurrentEquippedItem(); } @@ -3714,7 +3735,7 @@ public abstract class EntityNPC extends EntityLiving public void attackTargetEntityWithCurrentItem(Entity targetEntity) { if(!this.worldObj.client) { - if(/* !this.creative && */ this.sinceLastAttack < Vars.attackDelay) + if(/* !this.creative && */ this.sinceLastAttack < Config.attackDelay) return; this.sinceLastAttack = 0; } @@ -3722,7 +3743,7 @@ public abstract class EntityNPC extends EntityLiving { if (!targetEntity.hitByEntity(this)) { - int f = this.getAttackDamage(); + int f = (int)this.getEntityAttribute(Attributes.ATTACK_DAMAGE).getAttributeValue(); int i = 0; int f1 = // 0; @@ -3765,7 +3786,7 @@ public abstract class EntityNPC extends EntityLiving double d0 = targetEntity.motionX; double d1 = targetEntity.motionY; double d2 = targetEntity.motionZ; - boolean flag2 = (this.worldObj.client || Vars.attack) && targetEntity.attackEntityFrom(DamageSource.causeMobDamage(this), f); + boolean flag2 = (this.worldObj.client || Config.attack) && targetEntity.attackEntityFrom(DamageSource.causeMobDamage(this), f); if (flag2) { @@ -3821,7 +3842,7 @@ public abstract class EntityNPC extends EntityLiving { itemstack.hitEntity((EntityLiving)entity, this); - if (itemstack.size <= 0) + if (itemstack.stackSize <= 0) { this.destroyCurrentEquippedItem(); } @@ -3934,7 +3955,7 @@ public abstract class EntityNPC extends EntityLiving { double d3 = this.motionY; float f = this.jumpMovement; - this.jumpMovement = this.landMovement * (this.canFlyFullSpeed() ? 0.5f : 0.2f) * (this.isSprinting() ? (this.canFlyFullSpeed() ? 2.0f : 1.3f) : 1.0f); + this.jumpMovement = this.landMovement * (this.canFlyFullSpeed() ? 0.5f : 0.2f) * (float)(this.isSprinting() ? 2 : 1); super.moveEntityWithHeading(strafe, forward); this.motionY = d3 * 0.6D; this.jumpMovement = f; @@ -3944,17 +3965,7 @@ public abstract class EntityNPC extends EntityLiving super.moveEntityWithHeading(strafe, forward); } - if(!this.worldObj.client) - this.addMovement(this.posX - d0, this.posY - d1, this.posZ - d2); - } - - public float getSpeedBase() { - return this.worldObj.client ? this.dataWatcher.getWatchableObjectFloat(15) : super.getSpeedBase(); - } - - public void setSpeedBase(float value) { - super.setSpeedBase(value); - this.dataWatcher.updateObject(15, value); + this.addMovementStat(this.posX - d0, this.posY - d1, this.posZ - d2); } /** @@ -3962,68 +3973,106 @@ public abstract class EntityNPC extends EntityLiving */ public float getAIMoveSpeed() { - return this.isPlayer() ? this.getMovementSpeed() / 3.0f : super.getAIMoveSpeed(); + return this.isPlayer() ? (float)this.getEntityAttribute(Attributes.MOVEMENT_SPEED).getAttributeValue() : super.getAIMoveSpeed(); } - public void addMovement(double x, double y, double z) + /** + * Adds a value to a movement statistic field - like run, walk, swin or climb. + */ + public void addMovementStat(double p_71000_1_, double p_71000_3_, double p_71000_5_) { if (this.vehicle == null) { if (this.isInsideOfLiquid()) { - int i = Math.round(ExtMath.sqrtd(x * x + y * y + z * z) * 100.0F); + int i = Math.round(ExtMath.sqrtd(p_71000_1_ * p_71000_1_ + p_71000_3_ * p_71000_3_ + p_71000_5_ * p_71000_5_) * 100.0F); if (i > 0) { - this.addMoved(i); + this.addStat(i); } } else if (this.isInLiquid()) { - int j = Math.round(ExtMath.sqrtd(x * x + z * z) * 100.0F); + int j = Math.round(ExtMath.sqrtd(p_71000_1_ * p_71000_1_ + p_71000_5_ * p_71000_5_) * 100.0F); if (j > 0) { - this.addMoved(j); + this.addStat(j); } } else if (this.isOnLadder()) { - if (y > 0.0D) + if (p_71000_3_ > 0.0D) { - this.addMoved((int)Math.round(y * 100.0D)); + this.addStat((int)Math.round(p_71000_3_ * 100.0D)); } } else if (this.onGround) { - int k = Math.round(ExtMath.sqrtd(x * x + z * z) * 100.0F); + int k = Math.round(ExtMath.sqrtd(p_71000_1_ * p_71000_1_ + p_71000_5_ * p_71000_5_) * 100.0F); if (k > 0) { - this.addMoved(k); + this.addStat(k); + +// if (this.isSprinting()) +// { +// this.addStat(StatRegistry.distanceSprintedStat, k); +// } +// else +// { +// if (this.isSneaking()) +// { +// this.addStat(StatRegistry.distanceCrouchedStat, k); +// } +// } } } else { - int l = Math.round(ExtMath.sqrtd(x * x + z * z) * 100.0F); + int l = Math.round(ExtMath.sqrtd(p_71000_1_ * p_71000_1_ + p_71000_5_ * p_71000_5_) * 100.0F); if (l > 25) { - this.addMoved(l); + this.addStat(l); } } } } - private void addMountedMovement(double x, double y, double z) + /** + * Adds a value to a mounted movement statistic field - by minecart, boat, or pig. + */ + private void addMountedMovementStat(double p_71015_1_, double p_71015_3_, double p_71015_5_) { if (this.vehicle != null) { - int i = Math.round(ExtMath.sqrtd(x * x + y * y + z * z) * 100.0F); + int i = Math.round(ExtMath.sqrtd(p_71015_1_ * p_71015_1_ + p_71015_3_ * p_71015_3_ + p_71015_5_ * p_71015_5_) * 100.0F); if (i > 0) { - this.addMoved(i); + if (this.vehicle instanceof EntityCart) + { + this.addStat(i); + +// if (this.startMinecartRidingCoordinate == null) +// { +// this.startMinecartRidingCoordinate = new BlockPos(this); +// } + } + else if (this.vehicle instanceof EntityBoat) + { + this.addStat(i); + } + else if (this.vehicle instanceof EntityPig) + { + this.addStat(i); + } + else if (this.vehicle instanceof EntityHorse) + { + this.addStat(i); + } } } } @@ -4038,7 +4087,7 @@ public abstract class EntityNPC extends EntityLiving { if (distance >= 2.0F) { - this.addMoved((int)Math.round((double)distance * 100.0D)); + this.addStat((int)Math.round((double)distance * 100.0D)); } if(!this.hasEffect(Potion.FLYING)) @@ -4092,12 +4141,10 @@ public abstract class EntityNPC extends EntityLiving { return this.isPlayer() ? this.inventory.armorItemInSlot(slot) : this.equipment[slot + 1]; } - - public void setExperience(int points) { - this.setXPStats(0.0f, 0, 0); - this.addExperience(points); - } + /** + * Add experience points to player. + */ public void addExperience(int amount) { int i = Integer.MAX_VALUE - this.experienceTotal; @@ -4116,14 +4163,14 @@ public abstract class EntityNPC extends EntityLiving } } - public int getEnchSeed() + public int getXPSeed() { - return this.enchSeed; + return this.xpSeed; } - public void setEnchSeed(int seed) + public void setXPSeed(int xpSeed) { - this.enchSeed = seed; + this.xpSeed = xpSeed; } /** @@ -4262,22 +4309,22 @@ public abstract class EntityNPC extends EntityLiving amount = 0; } - this.getDataWatcher().updateObject(12, Integer.valueOf(amount)); + this.getDataWatcher().updateObject(30, Integer.valueOf(amount)); } } public int getAbsorptionAmount() { - return this.isPlayer() ? this.getDataWatcher().getWatchableObjectInt(12) : super.getAbsorptionAmount(); + return this.isPlayer() ? this.getDataWatcher().getWatchableObjectInt(30) : super.getAbsorptionAmount(); } - public boolean canOpen(Passcode code) + public boolean canOpen(LockCode code) { - if (code.empty()) + if (code.isEmpty()) return true; ItemStack stack = this.getCurrentEquippedItem(); return stack != null && stack.getItem() == Items.key && - stack.hasDisplayName() && stack.getDisplayName().equals(code.code()); + stack.hasDisplayName() && stack.getDisplayName().equals(code.getLock()); } // public boolean isWearing(ModelPart part) @@ -4317,7 +4364,7 @@ public abstract class EntityNPC extends EntityLiving } public boolean canFlyFullSpeed() { - return this.hasEffect(Potion.FLYING) && this.getEffect(Potion.FLYING).getAmplifier() > 0; + return this.flying; } public int getEnergy(Energy type) { // TODO @@ -4368,7 +4415,7 @@ public abstract class EntityNPC extends EntityLiving if(info.items != null) { for(ItemStack stack : info.items) { if(stack.getItem() instanceof ItemArmor) - this.setItem(((ItemArmor)stack.getItem()).armorType.getIndex(), stack); + this.setItem(1 + ((ItemArmor)stack.getItem()).armorType, stack); else if(stack.getItem().canBeWielded()) this.setItem(0, stack); else @@ -4630,36 +4677,4 @@ public abstract class EntityNPC extends EntityLiving public EntityType getType() { return EntityType.NPC; } - - public void setGodMode(boolean god) { - this.fallDistance = 0.0F; - if(!god) { - this.removeEffect(Potion.HASTE); - this.removeEffect(Potion.RESISTANCE); - this.removeEffect(Potion.FIRE_RESISTANCE); - this.removeEffect(Potion.FLYING); - this.removeEffect(Potion.MANA_GENERATION); - } - else { - this.extinguish(); - this.setHealth(this.getMaxHealth()); - this.setManaPoints(this.getMaxMana()); - this.clearEffects(false); - this.addEffect(new PotionEffect(Potion.HASTE, Integer.MAX_VALUE, 255, false, false)); - this.addEffect(new PotionEffect(Potion.RESISTANCE, Integer.MAX_VALUE, 255, false, false)); - this.addEffect(new PotionEffect(Potion.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, false, false)); - this.addEffect(new PotionEffect(Potion.FLYING, Integer.MAX_VALUE, 1, false, false)); - this.addEffect(new PotionEffect(Potion.MANA_GENERATION, Integer.MAX_VALUE, 255, false, false)); - } - } - - public void setNoclip(boolean noclip) { - if(noclip) - this.mountEntity(null); - this.noclip = noclip; - this.flying &= this.hasEffect(Potion.FLYING) || this.noclip || this.canNaturallyFly(); - this.fallDistance = 0.0F; - if(this.connection != null) - this.connection.sendPlayerAbilities(); - } } diff --git a/common/src/main/java/common/entity/npc/EntityOrc.java b/common/src/common/entity/npc/EntityOrc.java similarity index 93% rename from common/src/main/java/common/entity/npc/EntityOrc.java rename to common/src/common/entity/npc/EntityOrc.java index b6a7bb3..96cdb66 100755 --- a/common/src/main/java/common/entity/npc/EntityOrc.java +++ b/common/src/common/entity/npc/EntityOrc.java @@ -1,5 +1,6 @@ package common.entity.npc; +import common.attributes.Attributes; import common.rng.Random; import common.world.World; @@ -71,6 +72,6 @@ public class EntityOrc extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setAttackDamageBase(4); + this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(4.0D); } } diff --git a/common/src/main/java/common/entity/npc/EntityPrimarch.java b/common/src/common/entity/npc/EntityPrimarch.java similarity index 98% rename from common/src/main/java/common/entity/npc/EntityPrimarch.java rename to common/src/common/entity/npc/EntityPrimarch.java index 682d756..e4c29f8 100755 --- a/common/src/main/java/common/entity/npc/EntityPrimarch.java +++ b/common/src/common/entity/npc/EntityPrimarch.java @@ -2,6 +2,7 @@ package common.entity.npc; import java.util.List; +import common.attributes.Attributes; import common.collect.Lists; import common.rng.Random; import common.util.Identifyable; @@ -153,7 +154,7 @@ public class EntityPrimarch extends EntityMobNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setAttackDamageBase(20); + this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(20.0D); } // public TextComponent getPrefix() { diff --git a/common/src/main/java/common/entity/npc/EntitySlime.java b/common/src/common/entity/npc/EntitySlime.java similarity index 94% rename from common/src/main/java/common/entity/npc/EntitySlime.java rename to common/src/common/entity/npc/EntitySlime.java index 73fe074..08e36f8 100755 --- a/common/src/main/java/common/entity/npc/EntitySlime.java +++ b/common/src/common/entity/npc/EntitySlime.java @@ -2,18 +2,20 @@ package common.entity.npc; import common.ai.EntityAIBase; import common.ai.EntityMoveHelper; +import common.attributes.Attributes; import common.biome.Biome; import common.entity.DamageSource; import common.entity.Entity; import common.entity.types.EntityLiving; +import common.init.Config; import common.init.SoundEvent; import common.model.ParticleType; +import common.nbt.NBTTagCompound; import common.pathfinding.PathNavigateGround; import common.rng.Random; -import common.tags.TagObject; import common.util.BlockPos; import common.util.ExtMath; -import common.vars.Vars; +import common.world.Chunk; import common.world.World; import common.world.AWorldServer; @@ -133,19 +135,19 @@ public class EntitySlime extends EntityNPC /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); + super.writeEntityToNBT(tagCompound); // tagCompound.setInteger("Size", this.getSlimeSize() - 1); - tagCompound.setBool("wasOnGround", this.wasOnGround); + tagCompound.setBoolean("wasOnGround", this.wasOnGround); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); + super.readEntityFromNBT(tagCompund); // int i = tagCompund.getInteger("Size"); // // if (i < 0) @@ -154,7 +156,7 @@ public class EntitySlime extends EntityNPC // } // // this.setSlimeSize(i + 1); - this.wasOnGround = tagCompund.getBool("wasOnGround"); + this.wasOnGround = tagCompund.getBoolean("wasOnGround"); } protected ParticleType getParticleType() @@ -257,7 +259,7 @@ public class EntitySlime extends EntityNPC { int i = 1; - if (!this.worldObj.client && this.getHeight() >= 0.5f && this.getHealth() <= 0 && Vars.mobs && Vars.spawnSplitSlime) + if (!this.worldObj.client && this.getHeight() >= 0.5f && this.getHealth() <= 0 && Config.mobs && Config.spawnSplitSlime) { int j = this.rand.range(2, 4); float size = this.getHeight() / 2.0f; @@ -319,7 +321,7 @@ public class EntitySlime extends EntityNPC { double i = this.width * 2.0f; - if ((this.worldObj.client || Vars.damageMobs) && this.canEntityBeSeen(p_175451_1_) + if ((this.worldObj.client || Config.damageMobs) && this.canEntityBeSeen(p_175451_1_) && this.getDistanceSqToEntity(p_175451_1_) < 0.6D * i * 0.6D * i && this.canAttack(p_175451_1_) && p_175451_1_.attackEntityFrom(DamageSource.causeMobDamage(this), this.rand.range(1, 3))) { @@ -384,7 +386,8 @@ public class EntitySlime extends EntityNPC public boolean getCanSpawnHere() { BlockPos blockpos = new BlockPos(ExtMath.floord(this.posX), 0, ExtMath.floord(this.posZ)); - + Chunk chunk = this.worldObj.getChunk(blockpos); + // if (this.worldObj.getWorldInfo().getTerrainType() == WorldType.FLAT && this.rand.nextInt(4) != 1) // { // return false; @@ -393,14 +396,14 @@ public class EntitySlime extends EntityNPC // { // if (this.worldObj.getDifficulty() != Difficulty.PEACEFUL) // { - Biome biomegenbase = this.worldObj.getBiomeGenForCoords(blockpos); + Biome biomegenbase = ((AWorldServer)this.worldObj).getBiomeGenForCoords(blockpos); if (biomegenbase == Biome.SWAMPLAND && this.posY > 50.0D && this.posY < 70.0D && this.rand.floatv() < 0.5F && this.rand.floatv() < this.worldObj.getCurrentMoonPhaseFactor() && this.worldObj.getLightFromNeighbors(new BlockPos(this)) <= this.rand.zrange(8)) { return super.getCanSpawnHere(); } - if (this.rand.zrange(10) == 0 && getRandomWithSeed((AWorldServer)this.worldObj, blockpos.getX() >> 4, blockpos.getZ() >> 4, 987234911L).zrange(10) == 0 && this.posY < 40.0D) + if (this.rand.zrange(10) == 0 && getRandomWithSeed((AWorldServer)this.worldObj, chunk.xPos, chunk.zPos, 987234911L).zrange(10) == 0 && this.posY < 40.0D) { return super.getCanSpawnHere(); } @@ -520,7 +523,7 @@ public class EntitySlime extends EntityNPC public boolean shouldExecute() { EntityLiving entitylivingbase = this.slime.getAttackTarget(); - return entitylivingbase == null ? false : (!entitylivingbase.isEntityAlive() ? false : Vars.mobAttacks); + return entitylivingbase == null ? false : (!entitylivingbase.isEntityAlive() ? false : Config.mobAttacks); } public void startExecuting() @@ -532,7 +535,7 @@ public class EntitySlime extends EntityNPC public boolean continueExecuting() { EntityLiving entitylivingbase = this.slime.getAttackTarget(); - return entitylivingbase == null ? false : (!entitylivingbase.isEntityAlive() ? false : (!Vars.mobAttacks ? false : --this.attackTimer > 0)); + return entitylivingbase == null ? false : (!entitylivingbase.isEntityAlive() ? false : (!Config.mobAttacks ? false : --this.attackTimer > 0)); } public void updateTask() @@ -660,7 +663,7 @@ public class EntitySlime extends EntityNPC if (this.entity.onGround) { - this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getMovementSpeed())); + this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getEntityAttribute(Attributes.MOVEMENT_SPEED).getAttributeValue())); if (this.jumpDelay-- <= 0) { @@ -687,7 +690,7 @@ public class EntitySlime extends EntityNPC } else { - this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getMovementSpeed())); + this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getEntityAttribute(Attributes.MOVEMENT_SPEED).getAttributeValue())); } } } diff --git a/common/src/main/java/common/entity/npc/EntitySpaceMarine.java b/common/src/common/entity/npc/EntitySpaceMarine.java similarity index 96% rename from common/src/main/java/common/entity/npc/EntitySpaceMarine.java rename to common/src/common/entity/npc/EntitySpaceMarine.java index 841ee67..566360c 100755 --- a/common/src/main/java/common/entity/npc/EntitySpaceMarine.java +++ b/common/src/common/entity/npc/EntitySpaceMarine.java @@ -2,6 +2,7 @@ package common.entity.npc; import java.util.List; +import common.attributes.Attributes; import common.collect.Lists; import common.init.Items; import common.init.SpeciesRegistry; @@ -117,7 +118,7 @@ public class EntitySpaceMarine extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setAttackDamageBase(12); + this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(12.0D); } protected ItemStack pickItem() { diff --git a/common/src/main/java/common/entity/npc/EntitySpirit.java b/common/src/common/entity/npc/EntitySpirit.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntitySpirit.java rename to common/src/common/entity/npc/EntitySpirit.java diff --git a/common/src/main/java/common/entity/npc/EntityTiefling.java b/common/src/common/entity/npc/EntityTiefling.java similarity index 93% rename from common/src/main/java/common/entity/npc/EntityTiefling.java rename to common/src/common/entity/npc/EntityTiefling.java index fb52552..f3134f1 100755 --- a/common/src/main/java/common/entity/npc/EntityTiefling.java +++ b/common/src/common/entity/npc/EntityTiefling.java @@ -1,5 +1,6 @@ package common.entity.npc; +import common.attributes.Attributes; import common.rng.Random; import common.world.World; @@ -79,6 +80,6 @@ public class EntityTiefling extends EntityMobNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setAttackDamageBase(3); + this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(3.0D); } } diff --git a/common/src/main/java/common/entity/npc/EntityUndead.java b/common/src/common/entity/npc/EntityUndead.java similarity index 95% rename from common/src/main/java/common/entity/npc/EntityUndead.java rename to common/src/common/entity/npc/EntityUndead.java index b16db28..af39d58 100755 --- a/common/src/main/java/common/entity/npc/EntityUndead.java +++ b/common/src/common/entity/npc/EntityUndead.java @@ -1,6 +1,7 @@ package common.entity.npc; import common.ai.EntityAIAvoidEntity; +import common.attributes.Attributes; import common.entity.animal.EntityWolf; import common.entity.types.EntityLiving; import common.init.Items; @@ -20,7 +21,7 @@ public class EntityUndead extends EntityNPC protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setSpeedBase(0.25f); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.25D); } // protected String getLivingSound() diff --git a/common/src/main/java/common/entity/npc/EntityVampire.java b/common/src/common/entity/npc/EntityVampire.java similarity index 93% rename from common/src/main/java/common/entity/npc/EntityVampire.java rename to common/src/common/entity/npc/EntityVampire.java index 507976e..0733ab9 100755 --- a/common/src/main/java/common/entity/npc/EntityVampire.java +++ b/common/src/common/entity/npc/EntityVampire.java @@ -1,5 +1,6 @@ package common.entity.npc; +import common.attributes.Attributes; import common.entity.effect.EntityLightning; import common.rng.Random; import common.world.World; @@ -74,6 +75,6 @@ public class EntityVampire extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setAttackDamageBase(5); + this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(5.0D); } } diff --git a/common/src/main/java/common/entity/npc/EntityWoodElf.java b/common/src/common/entity/npc/EntityWoodElf.java similarity index 100% rename from common/src/main/java/common/entity/npc/EntityWoodElf.java rename to common/src/common/entity/npc/EntityWoodElf.java diff --git a/common/src/main/java/common/entity/npc/EntityZombie.java b/common/src/common/entity/npc/EntityZombie.java similarity index 84% rename from common/src/main/java/common/entity/npc/EntityZombie.java rename to common/src/common/entity/npc/EntityZombie.java index 1378a88..a38a61f 100755 --- a/common/src/main/java/common/entity/npc/EntityZombie.java +++ b/common/src/common/entity/npc/EntityZombie.java @@ -4,13 +4,15 @@ import java.util.List; import java.util.function.Predicate; import common.ai.EntityAIMoveThroughVillage; +import common.attributes.AttributeModifier; +import common.attributes.Attributes; import common.entity.DamageSource; import common.entity.animal.EntityChicken; import common.entity.types.EntityLiving; +import common.init.Config; import common.rng.Random; import common.util.BlockPos; import common.util.ExtMath; -import common.vars.Vars; import common.world.World; import common.world.AWorldServer; @@ -25,13 +27,11 @@ public class EntityZombie extends EntityNPC protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.setSpeedBase(0.23000000417232513f); - this.setAttackDamageBase(3); + this.getEntityAttribute(Attributes.FOLLOW_RANGE).setBaseValue(28.0D); + this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.23000000417232513D); + this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(3.0D); + this.getAttributeMap().registerAttribute(Attributes.REINFORCEMENT_CHANCE).setBaseValue(this.rand.doublev() * 0.10000000149011612D); } - - public int getPathingRange() { - return 28; - } public void onLivingUpdate() { @@ -53,7 +53,7 @@ public class EntityZombie extends EntityNPC entitylivingbase = (EntityLiving)source.getEntity(); } - if (entitylivingbase != null && Vars.mobs && Vars.spawnMoreZombie > 0 && this.rand.chance(Vars.spawnMoreZombie)) + if (entitylivingbase != null && /* this.worldObj.getDifficulty() == Difficulty.HARD && */ (double)this.rand.floatv() < this.getEntityAttribute(Attributes.REINFORCEMENT_CHANCE).getAttributeValue() && Config.mobs && Config.spawnMoreZombie) { int i = ExtMath.floord(this.posX); int j = ExtMath.floord(this.posY); @@ -75,6 +75,8 @@ public class EntityZombie extends EntityNPC this.worldObj.spawnEntityInWorld(entityzombie); entityzombie.setAttackTarget(entitylivingbase); entityzombie.onInitialSpawn(null); + this.getEntityAttribute(Attributes.REINFORCEMENT_CHANCE).applyModifier(new AttributeModifier("Zombie reinforcement caller charge", -0.05000000074505806D, false)); + entityzombie.getEntityAttribute(Attributes.REINFORCEMENT_CHANCE).applyModifier(new AttributeModifier("Zombie reinforcement callee charge", -0.05000000074505806D, false)); break; } } @@ -139,7 +141,7 @@ public class EntityZombie extends EntityNPC { super.onKillEntity(entityLivingIn); - if (/* (this.worldObj.getDifficulty() == Difficulty.NORMAL || this.worldObj.getDifficulty() == Difficulty.HARD) && */ entityLivingIn instanceof EntityNPC && !(entityLivingIn.isPlayer()) && Vars.convertZombie) + if (/* (this.worldObj.getDifficulty() == Difficulty.NORMAL || this.worldObj.getDifficulty() == Difficulty.HARD) && */ entityLivingIn instanceof EntityNPC && !(entityLivingIn.isPlayer()) && Config.convertZombie) { // if (this.worldObj.getDifficulty() != Difficulty.HARD && this.rand.chance()) // { @@ -217,7 +219,7 @@ public class EntityZombie extends EntityNPC if (!list.isEmpty()) { EntityChicken entitychicken = (EntityChicken)list.get(0); - entitychicken.setNotLaying(true); + entitychicken.setChickenJockey(true); this.mountEntity(entitychicken); } } @@ -226,7 +228,7 @@ public class EntityZombie extends EntityNPC EntityChicken entitychicken1 = new EntityChicken(this.worldObj); entitychicken1.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotYaw, 0.0F); entitychicken1.onInitialSpawn(null); - entitychicken1.setNotLaying(true); + entitychicken1.setChickenJockey(true); this.worldObj.spawnEntityInWorld(entitychicken1); this.mountEntity(entitychicken1); } @@ -248,19 +250,24 @@ public class EntityZombie extends EntityNPC // } // } + this.getEntityAttribute(Attributes.KNOCKBACK_RESISTANCE).applyModifier(new AttributeModifier("Random spawn bonus", this.rand.doublev() * 0.05000000074505806D, false)); + double d0 = this.rand.doublev() * 15.0; + + if (d0 > 1.0D) + { + this.getEntityAttribute(Attributes.FOLLOW_RANGE).applyModifier(new AttributeModifier("Random zombie-spawn bonus", d0, false)); + } + if (this.rand.chance(30)) { - this.setMaxHealth(this.getMaxHealth() + this.rand.roll(12)); + this.getEntityAttribute(Attributes.REINFORCEMENT_CHANCE).applyModifier(new AttributeModifier("Leader zombie bonus", this.rand.doublev() * 0.25D + 0.5D, false)); + this.getEntityAttribute(Attributes.MAX_HEALTH).applyModifier(new AttributeModifier("Leader zombie bonus", this.rand.roll(4), true)); // this.setBreakDoorsAItask(true); } return livingdata; } - public double getKnockBackResistance() { - return 0.05; - } - public int getColor() { return 0xff0000; } diff --git a/common/src/main/java/common/entity/npc/NpcInfo.java b/common/src/common/entity/npc/NpcInfo.java similarity index 100% rename from common/src/main/java/common/entity/npc/NpcInfo.java rename to common/src/common/entity/npc/NpcInfo.java diff --git a/common/src/common/entity/npc/PlayerCharacter.java b/common/src/common/entity/npc/PlayerCharacter.java new file mode 100644 index 0000000..c9e6c74 --- /dev/null +++ b/common/src/common/entity/npc/PlayerCharacter.java @@ -0,0 +1,23 @@ +package common.entity.npc; + +import common.util.BlockPos; + +public class PlayerCharacter { + public final String name; + public final String info; + public final Alignment align; + public final String dim; + public final BlockPos pos; + public final String type; + public final int level; + + public PlayerCharacter(String name, String info, Alignment align, String dim, BlockPos pos, String type, int level) { + this.name = name; + this.info = info; + this.align = align; + this.dim = dim; + this.pos = pos; + this.type = type; + this.level = level; + } +} diff --git a/common/src/main/java/common/entity/npc/SpeciesInfo.java b/common/src/common/entity/npc/SpeciesInfo.java similarity index 100% rename from common/src/main/java/common/entity/npc/SpeciesInfo.java rename to common/src/common/entity/npc/SpeciesInfo.java diff --git a/common/src/main/java/common/entity/projectile/EntityArrow.java b/common/src/common/entity/projectile/EntityArrow.java similarity index 93% rename from common/src/main/java/common/entity/projectile/EntityArrow.java rename to common/src/common/entity/projectile/EntityArrow.java index 46ef690..507198b 100755 --- a/common/src/main/java/common/entity/projectile/EntityArrow.java +++ b/common/src/common/entity/projectile/EntityArrow.java @@ -12,18 +12,18 @@ import common.entity.types.EntityLiving; import common.entity.types.IObjectData; import common.entity.types.IProjectile; import common.init.BlockRegistry; -import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.init.SoundEvent; import common.item.ItemStack; +import common.material.Material; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; import common.util.HitPosition; import common.util.Vec3; -import common.vars.Vars; import common.world.State; import common.world.World; @@ -156,7 +156,7 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData this.ticksInGround = 0; } - public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) { this.setPosition(x, y, z); this.setRotation(yaw, pitch); @@ -201,7 +201,7 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData State iblockstate = this.worldObj.getState(blockpos); Block block = iblockstate.getBlock(); - if (block != Blocks.air) + if (block.getMaterial() != Material.air) { block.setBlockBoundsBasedOnState(this.worldObj, blockpos); BoundingBox axisalignedbb = block.getCollisionBoundingBox(this.worldObj, blockpos, iblockstate); @@ -324,7 +324,7 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData movingobjectposition.entity.setFire(5); } - if ((this.worldObj.client || Vars.damageArrow) && movingobjectposition.entity.attackEntityFrom(damagesource, l)) + if ((this.worldObj.client || Config.damageArrow) && movingobjectposition.entity.attackEntityFrom(damagesource, l)) { if (movingobjectposition.entity instanceof EntityLiving) { @@ -397,7 +397,7 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData this.arrowShake = 7; this.setIsCritical(false); - if (this.inTile != Blocks.air) + if (this.inTile.getMaterial() != Material.air) { this.inTile.onEntityCollidedWithBlock(this.worldObj, blockpos1, iblockstate1, this); } @@ -454,7 +454,7 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData f4 = 0.6F; } - if (this.isWet()) + if (!this.worldObj.client && this.isWet()) { this.extinguish(); } @@ -471,19 +471,17 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { tagCompound.setShort("xTile", (short)this.xTile); tagCompound.setShort("yTile", (short)this.yTile); tagCompound.setShort("zTile", (short)this.zTile); tagCompound.setShort("life", (short)this.ticksInGround); - if(this.inTile != null) { - String id = BlockRegistry.getNameFromBlock(this.inTile); - tagCompound.setString("inTile", id == null ? "" : id.toString()); - } + String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(this.inTile); + tagCompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); tagCompound.setByte("inData", (byte)this.inData); tagCompound.setByte("shake", (byte)this.arrowShake); - tagCompound.setBool("inGround", this.inGround); + tagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0)); tagCompound.setByte("pickup", (byte)this.canBePickedUp); tagCompound.setDouble("damage", this.damage); } @@ -491,29 +489,39 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { this.xTile = tagCompund.getShort("xTile"); this.yTile = tagCompund.getShort("yTile"); this.zTile = tagCompund.getShort("zTile"); this.ticksInGround = tagCompund.getShort("life"); - if (tagCompund.hasString("inTile")) + if (tagCompund.hasKey("inTile", 8)) { - this.inTile = BlockRegistry.getRegisteredBlock(tagCompund.getString("inTile")); + this.inTile = BlockRegistry.getByIdFallback(tagCompund.getString("inTile")); } else { - this.inTile = null; + this.inTile = BlockRegistry.getBlockById(tagCompund.getByte("inTile") & 255); } this.inData = tagCompund.getByte("inData") & 255; this.arrowShake = tagCompund.getByte("shake") & 255; - this.inGround = tagCompund.getBool("inGround"); + this.inGround = tagCompund.getByte("inGround") == 1; - this.damage = tagCompund.getDouble("damage"); + if (tagCompund.hasKey("damage", 99)) + { + this.damage = tagCompund.getDouble("damage"); + } - this.canBePickedUp = tagCompund.getByte("pickup"); + if (tagCompund.hasKey("pickup", 99)) + { + this.canBePickedUp = tagCompund.getByte("pickup"); + } + else if (tagCompund.hasKey("player", 99)) + { + this.canBePickedUp = tagCompund.getBoolean("player") ? 1 : 0; + } } /** diff --git a/common/src/main/java/common/entity/projectile/EntityBox.java b/common/src/common/entity/projectile/EntityBox.java similarity index 98% rename from common/src/main/java/common/entity/projectile/EntityBox.java rename to common/src/common/entity/projectile/EntityBox.java index 0f094c5..de13b19 100755 --- a/common/src/main/java/common/entity/projectile/EntityBox.java +++ b/common/src/common/entity/projectile/EntityBox.java @@ -3,10 +3,10 @@ package common.entity.projectile; import common.entity.DamageSource; import common.entity.npc.EntityGargoyle; import common.entity.types.EntityLiving; +import common.init.Config; import common.potion.Potion; import common.potion.PotionEffect; import common.util.HitPosition; -import common.vars.Vars; import common.world.World; public class EntityBox extends EntityProjectile @@ -71,7 +71,7 @@ public class EntityBox extends EntityProjectile { if (movingObject.entity != null) { - if(Vars.damageFlyingBox) { + if(Config.damageFlyingBox) { if (this.shootingEntity != null) { if (movingObject.entity.attackEntityFrom(DamageSource.causeMobDamage(this.shootingEntity), diff --git a/common/src/common/entity/projectile/EntityBullet.java b/common/src/common/entity/projectile/EntityBullet.java new file mode 100755 index 0000000..51f2f9a --- /dev/null +++ b/common/src/common/entity/projectile/EntityBullet.java @@ -0,0 +1,411 @@ +package common.entity.projectile; + +import java.util.List; + +import common.enchantment.EnchantmentHelper; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.types.EntityLiving; +import common.entity.types.IObjectData; +import common.entity.types.IProjectile; +import common.init.Config; +import common.init.SoundEvent; +import common.nbt.NBTTagCompound; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.HitPosition; +import common.util.Vec3; +import common.world.World; + +public class EntityBullet extends Entity implements IProjectile, IObjectData +{ + public Entity shootingEntity; + private int ticksInAir; + private int age; + private int damage = 5; + + public EntityBullet(World worldIn) + { + super(worldIn); + this.renderDistWeight = 10.0D; + this.setSize(0.5F, 0.5F); + } + + public EntityBullet(World worldIn, double x, double y, double z) + { + super(worldIn); + this.renderDistWeight = 10.0D; + this.setSize(0.5F, 0.5F); + this.setPosition(x, y, z); + } + + public EntityBullet(World worldIn, double x, double y, double z, int data) + { + this(worldIn, x, y, z); + Entity entity2 = worldIn.getEntityByID(data); + if(entity2 instanceof EntityLiving) { + this.shootingEntity = entity2; + } + } + + public EntityBullet(World worldIn, EntityLiving shooter, EntityLiving target, float velocity, float innacuracy) + { + super(worldIn); + this.renderDistWeight = 10.0D; + this.shootingEntity = shooter; + + this.posY = shooter.posY + (double)shooter.getEyeHeight() - 0.10000000149011612D; + double d0 = target.posX - shooter.posX; + double d1 = target.getEntityBoundingBox().minY + (double)(target.height * 0.7f) - this.posY; + double d2 = target.posZ - shooter.posZ; + double d3 = (double)ExtMath.sqrtd(d0 * d0 + d2 * d2); + + if (d3 >= 1.0E-7D) + { + float f = (float)(ExtMath.atan2(d2, d0) * 180.0D / Math.PI) - 90.0F; + float f1 = (float)(-(ExtMath.atan2(d1, d3) * 180.0D / Math.PI)); + double d4 = d0 / d3; + double d5 = d2 / d3; + this.setLocationAndAngles(shooter.posX + d4, this.posY, shooter.posZ + d5, f, f1); +// float f2 = (float)(d3 * 0.20000000298023224D); + this.setThrowableHeading(d0, d1 /* + (double)f2 */ , d2, velocity, innacuracy); + } + } + + public EntityBullet(World worldIn, EntityLiving shooter, float velocity) + { + super(worldIn); + this.renderDistWeight = 10.0D; + this.shootingEntity = shooter; + + this.setSize(0.5F, 0.5F); + this.setLocationAndAngles(shooter.posX, shooter.posY + (double)shooter.getEyeHeight(), shooter.posZ, shooter.rotYaw, shooter.rotPitch); + this.posX -= (double)(ExtMath.cos(this.rotYaw / 180.0F * (float)Math.PI) * 0.16F); + this.posY -= 0.10000000149011612D; + this.posZ -= (double)(ExtMath.sin(this.rotYaw / 180.0F * (float)Math.PI) * 0.16F); + this.setPosition(this.posX, this.posY, this.posZ); + this.motionX = (double)(-ExtMath.sin(this.rotYaw / 180.0F * (float)Math.PI) * ExtMath.cos(this.rotPitch / 180.0F * (float)Math.PI)); + this.motionZ = (double)(ExtMath.cos(this.rotYaw / 180.0F * (float)Math.PI) * ExtMath.cos(this.rotPitch / 180.0F * (float)Math.PI)); + this.motionY = (double)(-ExtMath.sin(this.rotPitch / 180.0F * (float)Math.PI)); + this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, velocity, 0.5F); + } + + protected void entityInit() + { + } + + /** + * Similar to setArrowHeading, it's point the throwable entity to a x, y, z direction. + */ + public void setThrowableHeading(double x, double y, double z, float velocity, float inaccuracy) + { + float f = ExtMath.sqrtd(x * x + y * y + z * z); + x = x / (double)f; + y = y / (double)f; + z = z / (double)f; + x = x + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; + y = y + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; + z = z + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; + x = x * (double)velocity; + y = y * (double)velocity; + z = z * (double)velocity; + this.motionX = x; + this.motionY = y; + this.motionZ = z; + float f1 = ExtMath.sqrtd(x * x + z * z); + this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(x, z) * 180.0D / Math.PI); + this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(y, (double)f1) * 180.0D / Math.PI); + } + + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) + { + this.setPosition(x, y, z); + this.setRotation(yaw, pitch); + } + + /** + * Sets the velocity to the args. Args: x, y, z + */ + public void setVelocity(double x, double y, double z) + { + this.motionX = x; + this.motionY = y; + this.motionZ = z; + + if (this.prevPitch == 0.0F && this.prevYaw == 0.0F) + { + float f = ExtMath.sqrtd(x * x + z * z); + this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(x, z) * 180.0D / Math.PI); + this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(y, (double)f) * 180.0D / Math.PI); + this.prevPitch = this.rotPitch; + this.prevYaw = this.rotYaw; + this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotYaw, this.rotPitch); + } + } + + /** + * Called to update the entity's position/logic. + */ + public void onUpdate() + { + super.onUpdate(); + + if (this.prevPitch == 0.0F && this.prevYaw == 0.0F) + { + float f = ExtMath.sqrtd(this.motionX * this.motionX + this.motionZ * this.motionZ); + this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI); + this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(this.motionY, (double)f) * 180.0D / Math.PI); + } + + if(!this.worldObj.client && ++this.age >= 200) { + this.setDead(); + return; + } + ++this.ticksInAir; + Vec3 vec31 = new Vec3(this.posX, this.posY, this.posZ); + Vec3 vec3 = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); + HitPosition movingobjectposition = this.worldObj.rayTraceBlocks(vec31, vec3, false, true, false); + vec31 = new Vec3(this.posX, this.posY, this.posZ); + vec3 = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); + + if (movingobjectposition != null) + { + vec3 = new Vec3(movingobjectposition.vec.xCoord, movingobjectposition.vec.yCoord, movingobjectposition.vec.zCoord); + } + + Entity entity = null; + List list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox().addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D)); + double d0 = 0.0D; + + for (int i = 0; i < list.size(); ++i) + { + Entity entity1 = (Entity)list.get(i); + + if (entity1.canBeCollidedWith() && (entity1 != this.shootingEntity || this.ticksInAir >= 5)) + { + float f1 = 0.3F; + BoundingBox axisalignedbb1 = entity1.getEntityBoundingBox().expand((double)f1, (double)f1, (double)f1); + HitPosition movingobjectposition1 = axisalignedbb1.calculateIntercept(vec31, vec3); + + if (movingobjectposition1 != null) + { + double d1 = vec31.squareDistanceTo(movingobjectposition1.vec); + + if (d1 < d0 || d0 == 0.0D) + { + entity = entity1; + d0 = d1; + } + } + } + } + + if (entity != null) + { + movingobjectposition = new HitPosition(entity); + } + +// if (movingobjectposition != null && movingobjectposition.entity != null && movingobjectposition.entity.isPlayer()) +// { +// EntityNPC entityplayer = (EntityNPC)movingobjectposition.entity; +// +// if (entityplayer.creative || this.shootingEntity.isPlayer() && !((EntityNPC)this.shootingEntity).canAttackPlayer(entityplayer)) +// { +// movingobjectposition = null; +// } +// } + + if (movingobjectposition != null) + { + if (movingobjectposition.entity != null) + { + float f2 = ExtMath.sqrtd(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ); + int l = ExtMath.ceild((double)f2 * (double)this.damage); + + DamageSource damagesource; + + if (this.shootingEntity == null) + { + damagesource = DamageSource.causeShotDamage(this, this); + } + else + { + damagesource = DamageSource.causeShotDamage(this, this.shootingEntity); + } + + if ((this.worldObj.client || Config.damageBullet) && movingobjectposition.entity.attackEntityFrom(damagesource, l)) + { + if (movingobjectposition.entity instanceof EntityLiving) + { + EntityLiving entitylivingbase = (EntityLiving)movingobjectposition.entity; + +// if (!this.worldObj.client) +// { +// entitylivingbase.setArrowCountInEntity(entitylivingbase.getArrowCountInEntity() + 1); +// } + +// if (this.knockbackStrength > 0) +// { +// float f7 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ); +// +// if (f7 > 0.0F) +// { +// movingobjectposition.entityHit.addKnockback(this.motionX * (double)this.knockbackStrength * 0.6000000238418579D / (double)f7, 0.1D, this.motionZ * (double)this.knockbackStrength * 0.6000000238418579D / (double)f7); +// } +// } + + if (this.shootingEntity instanceof EntityLiving) + { + EnchantmentHelper.applyThornEnchantments(entitylivingbase, this.shootingEntity); + EnchantmentHelper.applyArthropodEnchantments((EntityLiving)this.shootingEntity, entitylivingbase); + } + +// if (this.shootingEntity != null && movingobjectposition.entityHit != this.shootingEntity && movingobjectposition.entityHit.isPlayer() && this.shootingEntity.isPlayer()) +// { +// ((EntityNPCMP)this.shootingEntity).netHandler.sendPacket(new S29PacketSoundEffect( +// "random.successful_hit", shootingEntity.posX, +// shootingEntity.posY + (double)shootingEntity.getEyeHeight(), shootingEntity.posZ, 0.18F, 0.45F)); +// } + } + + this.playSound(SoundEvent.METALHIT, 0.2F); + +// this.setDead(); + } +// else +// { + this.setDead(); +// this.motionX *= -0.10000000149011612D; +// this.motionY *= -0.10000000149011612D; +// this.motionZ *= -0.10000000149011612D; +// this.rotYaw += 180.0F; +// this.prevYaw += 180.0F; +// this.ticksInAir = 0; +// } + } + else + { + this.playSound(SoundEvent.METALHIT, 0.5F); + + this.setDead(); + } + } + + this.posX += this.motionX; + this.posY += this.motionY; + this.posZ += this.motionZ; + float f3 = ExtMath.sqrtd(this.motionX * this.motionX + this.motionZ * this.motionZ); + this.rotYaw = (float)(ExtMath.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI); + + for (this.rotPitch = (float)(ExtMath.atan2(this.motionY, (double)f3) * 180.0D / Math.PI); this.rotPitch - this.prevPitch < -180.0F; this.prevPitch -= 360.0F) + { + ; + } + + while (this.rotPitch - this.prevPitch >= 180.0F) + { + this.prevPitch += 360.0F; + } + + while (this.rotYaw - this.prevYaw < -180.0F) + { + this.prevYaw -= 360.0F; + } + + while (this.rotYaw - this.prevYaw >= 180.0F) + { + this.prevYaw += 360.0F; + } + + this.rotPitch = this.prevPitch + (this.rotPitch - this.prevPitch) * 0.2F; + this.rotYaw = this.prevYaw + (this.rotYaw - this.prevYaw) * 0.2F; +// float f4 = 0.99F; +// float f6 = 0.001F; + +// if (this.isInLiquid()) +// { +// for (int i1 = 0; i1 < 4; ++i1) +// { +// float f8 = 0.25F; +// this.worldObj.spawnParticle(ParticleType.WATER_BUBBLE, this.posX - this.motionX * (double)f8, this.posY - this.motionY * (double)f8, this.posZ - this.motionZ * (double)f8, this.motionX, this.motionY, this.motionZ); +// } +// +// f4 = 0.85F; +// } + +// if (this.isWet()) +// { +// this.extinguish(); +// } + +// this.motionX *= (double)f4; +// this.motionY *= (double)f4; +// this.motionZ *= (double)f4; +// this.motionY -= (double)f6; + this.setPosition(this.posX, this.posY, this.posZ); +// this.doBlockCollisions(); + } + + public void writeEntityToNBT(NBTTagCompound tagCompound) + { + tagCompound.setInteger("damage", this.damage); + tagCompound.setInteger("age", this.age); + } + + public void readEntityFromNBT(NBTTagCompound tagCompund) + { + if(tagCompund.hasKey("damage", 99)) + this.damage = tagCompund.getInteger("damage"); + this.age = tagCompund.getInteger("age"); + } + + protected boolean canTriggerWalking() + { + return false; + } + + public void setDamage(int damageIn) + { + this.damage = damageIn; + } + + public int getDamage() + { + return this.damage; + } + + public boolean canAttackWithItem() + { + return false; + } + + public float getEyeHeight() + { + return 0.0F; + } + + public int getTrackingRange() { + return 96; + } + + public int getUpdateFrequency() { + return 1; + } + + public boolean isSendingVeloUpdates() { + return false; + } + + public int getPacketData() { + return this.shootingEntity != null ? this.shootingEntity.getId() : this.getId(); + } + + public boolean hasSpawnVelocity() { + return true; + } + + public EntityType getType() { + return EntityType.PROJECTILE; + } +} diff --git a/common/src/main/java/common/entity/projectile/EntityDie.java b/common/src/common/entity/projectile/EntityDie.java similarity index 86% rename from common/src/main/java/common/entity/projectile/EntityDie.java rename to common/src/common/entity/projectile/EntityDie.java index bc655a6..1407ba2 100755 --- a/common/src/main/java/common/entity/projectile/EntityDie.java +++ b/common/src/common/entity/projectile/EntityDie.java @@ -9,7 +9,7 @@ import common.init.Items; import common.init.SoundEvent; import common.item.ItemDie; import common.item.ItemStack; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.HitPosition; import common.world.World; @@ -64,20 +64,20 @@ public class EntityDie extends EntityThrowable implements IObjectData return this.dataWatcher.getWatchableObjectInt(16); } - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setInt("Sides", this.sides); - tagCompound.setInt("Value", this.getValue()); - tagCompound.setBool("NoPickup", this.noPickup); + super.writeEntityToNBT(tagCompound); + tagCompound.setInteger("Sides", this.sides); + tagCompound.setInteger("Value", this.getValue()); + tagCompound.setBoolean("NoPickup", this.noPickup); } - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.sides = tagCompund.getInt("Sides"); - this.setValue(tagCompund.getInt("Value")); - this.noPickup = tagCompund.getBool("NoPickup"); + super.readEntityFromNBT(tagCompund); + this.sides = tagCompund.getInteger("Sides"); + this.setValue(tagCompund.getInteger("Value")); + this.noPickup = tagCompund.getBoolean("NoPickup"); } public int getPacketData() { diff --git a/common/src/main/java/common/entity/projectile/EntityDynamite.java b/common/src/common/entity/projectile/EntityDynamite.java similarity index 87% rename from common/src/main/java/common/entity/projectile/EntityDynamite.java rename to common/src/common/entity/projectile/EntityDynamite.java index e33b81e..1146bdb 100755 --- a/common/src/main/java/common/entity/projectile/EntityDynamite.java +++ b/common/src/common/entity/projectile/EntityDynamite.java @@ -5,12 +5,12 @@ import common.entity.EntityType; import common.entity.types.EntityLiving; import common.entity.types.EntityThrowable; import common.entity.types.IObjectData; +import common.init.Config; import common.init.ItemRegistry; import common.init.Items; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.HitPosition; -import common.vars.Vars; import common.world.World; public class EntityDynamite extends EntityThrowable implements IObjectData @@ -36,7 +36,7 @@ public class EntityDynamite extends EntityThrowable implements IObjectData protected void onImpact(HitPosition pos) { - if (pos.entity != null && Vars.knockDynamite) + if (pos.entity != null && Config.knockDynamite) { pos.entity.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()), 0); } @@ -59,15 +59,15 @@ public class EntityDynamite extends EntityThrowable implements IObjectData } } - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); + super.writeEntityToNBT(tagCompound); tagCompound.setByte("Power", (byte)this.explosionSize); } - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); + super.readEntityFromNBT(tagCompund); this.explosionSize = ((int)tagCompund.getByte("Power")) & 7; } diff --git a/common/src/main/java/common/entity/projectile/EntityEgg.java b/common/src/common/entity/projectile/EntityEgg.java similarity index 91% rename from common/src/main/java/common/entity/projectile/EntityEgg.java rename to common/src/common/entity/projectile/EntityEgg.java index f010a1b..0f7ef77 100755 --- a/common/src/main/java/common/entity/projectile/EntityEgg.java +++ b/common/src/common/entity/projectile/EntityEgg.java @@ -4,11 +4,11 @@ import common.entity.DamageSource; import common.entity.animal.EntityChicken; import common.entity.types.EntityLiving; import common.entity.types.EntityThrowable; +import common.init.Config; import common.init.ItemRegistry; import common.init.Items; import common.model.ParticleType; import common.util.HitPosition; -import common.vars.Vars; import common.world.World; public class EntityEgg extends EntityThrowable @@ -33,12 +33,12 @@ public class EntityEgg extends EntityThrowable */ protected void onImpact(HitPosition p_70184_1_) { - if (p_70184_1_.entity != null && Vars.knockEgg) + if (p_70184_1_.entity != null && Config.knockEgg) { p_70184_1_.entity.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()), 0); } - if (!this.worldObj.client && this.rand.chance(8) && Vars.mobs && Vars.spawnEggChicken) + if (!this.worldObj.client && this.rand.chance(8) && Config.mobs && Config.spawnEggChicken) { int i = this.rand.chance(1, 4, 32); diff --git a/common/src/main/java/common/entity/projectile/EntityFireCharge.java b/common/src/common/entity/projectile/EntityFireCharge.java similarity index 95% rename from common/src/main/java/common/entity/projectile/EntityFireCharge.java rename to common/src/common/entity/projectile/EntityFireCharge.java index 36459ad..0a27a2c 100755 --- a/common/src/main/java/common/entity/projectile/EntityFireCharge.java +++ b/common/src/common/entity/projectile/EntityFireCharge.java @@ -3,9 +3,9 @@ package common.entity.projectile; import common.entity.DamageSource; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.init.Config; import common.util.BlockPos; import common.util.HitPosition; -import common.vars.Vars; import common.world.World; public class EntityFireCharge extends EntityProjectile @@ -43,7 +43,7 @@ public class EntityFireCharge extends EntityProjectile { if (movingObject.entity != null) { - boolean flag = Vars.damageFireball && + boolean flag = Config.damageFireball && movingObject.entity.attackEntityFrom(DamageSource.causeFireballDamage(this, this.shootingEntity), 6); if (flag) @@ -62,7 +62,7 @@ public class EntityFireCharge extends EntityProjectile if (this.shootingEntity != null && this.shootingEntity instanceof EntityLiving) // && !(this.shootingEntity.isPlayer())) { - flag1 = Vars.mobGrief; + flag1 = Config.mobGrief; } if (flag1) diff --git a/common/src/main/java/common/entity/projectile/EntityFireball.java b/common/src/common/entity/projectile/EntityFireball.java similarity index 73% rename from common/src/main/java/common/entity/projectile/EntityFireball.java rename to common/src/common/entity/projectile/EntityFireball.java index 6ea5e9a..04ad023 100755 --- a/common/src/main/java/common/entity/projectile/EntityFireball.java +++ b/common/src/common/entity/projectile/EntityFireball.java @@ -2,9 +2,9 @@ package common.entity.projectile; import common.entity.DamageSource; import common.entity.types.EntityLiving; -import common.tags.TagObject; +import common.init.Config; +import common.nbt.NBTTagCompound; import common.util.HitPosition; -import common.vars.Vars; import common.world.World; public class EntityFireball extends EntityProjectile @@ -36,13 +36,13 @@ public class EntityFireball extends EntityProjectile { if (!this.worldObj.client) { - if (Vars.damageFireball && movingObject.entity != null) + if (Config.damageFireball && movingObject.entity != null) { movingObject.entity.attackEntityFrom(DamageSource.causeFireballDamage(this, this.shootingEntity), 8); this.applyEnchantments(this.shootingEntity, movingObject.entity); } - boolean flag = Vars.mobGrief; + boolean flag = Config.mobGrief; this.worldObj.newExplosion(this.shootingEntity, this.posX, this.posY, this.posZ, (float)this.explosionPower, flag, false, true); this.setDead(); } @@ -56,18 +56,22 @@ public class EntityFireball extends EntityProjectile /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setInt("ExplosionPower", this.explosionPower); + super.writeEntityToNBT(tagCompound); + tagCompound.setInteger("ExplosionPower", this.explosionPower); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.explosionPower = tagCompund.getInt("ExplosionPower"); + super.readEntityFromNBT(tagCompund); + + if (tagCompund.hasKey("ExplosionPower", 99)) + { + this.explosionPower = tagCompund.getInteger("ExplosionPower"); + } } } diff --git a/common/src/main/java/common/entity/projectile/EntityHook.java b/common/src/common/entity/projectile/EntityHook.java similarity index 94% rename from common/src/main/java/common/entity/projectile/EntityHook.java rename to common/src/common/entity/projectile/EntityHook.java index f01f65e..6f44d35 100755 --- a/common/src/main/java/common/entity/projectile/EntityHook.java +++ b/common/src/common/entity/projectile/EntityHook.java @@ -13,17 +13,17 @@ import common.entity.npc.EntityNPC; import common.entity.types.IObjectData; import common.init.BlockRegistry; import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.init.SoundEvent; import common.item.ItemStack; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; import common.util.HitPosition; import common.util.Vec3; -import common.vars.Vars; import common.world.World; import common.world.AWorldServer; @@ -121,7 +121,7 @@ public class EntityHook extends Entity implements IObjectData { } - public boolean writeOptional(TagObject tagCompund) + public boolean writeToNBTOptional(NBTTagCompound tagCompund) { return false; } @@ -164,14 +164,14 @@ public class EntityHook extends Entity implements IObjectData this.ticksInGround = 0; } - public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) { this.fishX = x; this.fishY = y; this.fishZ = z; this.fishYaw = (double)yaw; this.fishPitch = (double)pitch; - this.fishPosRotationIncrements = 3; + this.fishPosRotationIncrements = posRotationIncrements; this.motionX = this.clientMotionX; this.motionY = this.clientMotionY; this.motionZ = this.clientMotionZ; @@ -316,10 +316,10 @@ public class EntityHook extends Entity implements IObjectData { if (movingobjectposition.entity != null) { - if (this.worldObj.client || !Vars.knockHook || movingobjectposition.entity.attackEntityFrom( - DamageSource.causeThrownDamage(this, this.angler), 0) || !Vars.hookCheckDamage) + if (this.worldObj.client || !Config.knockHook || movingobjectposition.entity.attackEntityFrom( + DamageSource.causeThrownDamage(this, this.angler), 0) || !Config.hookCheckDamage) { - if(this.worldObj.client || Vars.hookEntity) // && (!(movingobjectposition.entity.isPlayer()) + if(this.worldObj.client || Config.hookEntity) // && (!(movingobjectposition.entity.isPlayer()) // || !((EntityNPC)movingobjectposition.entity).creative))) this.caughtEntity = movingobjectposition.entity; } @@ -388,16 +388,11 @@ public class EntityHook extends Entity implements IObjectData int l = 1; BlockPos blockpos = (new BlockPos(this)).up(); - if (this.rand.floatv() < 0.25F && this.worldObj.isRainingAt(blockpos, true)) + if (this.rand.floatv() < 0.25F && worldserver.isRainingAt(blockpos, true)) { l = 2; } - if (this.rand.floatv() < 0.5F && !this.worldObj.canSeeSky(blockpos)) - { - --l; - } - if (this.ticksCatchable > 0) { --this.ticksCatchable; @@ -517,39 +512,37 @@ public class EntityHook extends Entity implements IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { tagCompound.setShort("xTile", (short)this.xTile); tagCompound.setShort("yTile", (short)this.yTile); tagCompound.setShort("zTile", (short)this.zTile); - if(this.inTile != null) { - String id = BlockRegistry.getNameFromBlock(this.inTile); - tagCompound.setString("inTile", id == null ? "" : id.toString()); - } + String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(this.inTile); + tagCompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); tagCompound.setByte("shake", (byte)this.shake); - tagCompound.setBool("inGround", this.inGround); + tagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0)); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { this.xTile = tagCompund.getShort("xTile"); this.yTile = tagCompund.getShort("yTile"); this.zTile = tagCompund.getShort("zTile"); - if (tagCompund.hasString("inTile")) + if (tagCompund.hasKey("inTile", 8)) { - this.inTile = BlockRegistry.getRegisteredBlock(tagCompund.getString("inTile")); + this.inTile = BlockRegistry.getByIdFallback(tagCompund.getString("inTile")); } else { - this.inTile = null; + this.inTile = BlockRegistry.getBlockById(tagCompund.getByte("inTile") & 255); } this.shake = tagCompund.getByte("shake") & 255; - this.inGround = tagCompund.getBool("inGround"); + this.inGround = tagCompund.getByte("inGround") == 1; } public int handleHookRetraction() @@ -586,7 +579,7 @@ public class EntityHook extends Entity implements IObjectData entityitem.motionY = d3 * d9 + (double)ExtMath.sqrtd(d7) * 0.08D; entityitem.motionZ = d5 * d9; this.worldObj.spawnEntityInWorld(entityitem); - if(Vars.fishingXP) + if(Config.fishingXP) this.angler.worldObj.spawnEntityInWorld(new EntityXp(this.angler.worldObj, this.angler.posX, this.angler.posY + 0.5D, this.angler.posZ + 0.5D, this.rand.roll(6))); i = 1; } diff --git a/common/src/main/java/common/entity/projectile/EntityPotion.java b/common/src/common/entity/projectile/EntityPotion.java similarity index 90% rename from common/src/main/java/common/entity/projectile/EntityPotion.java rename to common/src/common/entity/projectile/EntityPotion.java index bcee549..3d477f6 100755 --- a/common/src/main/java/common/entity/projectile/EntityPotion.java +++ b/common/src/common/entity/projectile/EntityPotion.java @@ -7,9 +7,9 @@ import common.entity.types.EntityThrowable; import common.entity.types.IObjectData; import common.init.Items; import common.item.ItemStack; +import common.nbt.NBTTagCompound; import common.potion.Potion; import common.potion.PotionEffect; -import common.tags.TagObject; import common.util.BlockPos; import common.util.BoundingBox; import common.util.HitPosition; @@ -125,7 +125,7 @@ public class EntityPotion extends EntityThrowable implements IObjectData for (PotionEffect potioneffect : list) { Potion i = potioneffect.getPotion(); - if(!entitylivingbase.isPotionApplicable(i, potioneffect.getAmplifier())) + if(!entitylivingbase.isPotionApplicable(i)) continue; if (i.isInstant()) @@ -158,17 +158,17 @@ public class EntityPotion extends EntityThrowable implements IObjectData /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); + super.readEntityFromNBT(tagCompund); - if (tagCompund.hasObject("Potion")) + if (tagCompund.hasKey("Potion", 10)) { - this.potionDamage = ItemStack.readFromTag(tagCompund.getObject("Potion")); + this.potionDamage = ItemStack.loadItemStackFromNBT(tagCompund.getCompoundTag("Potion")); } else { - this.setPotionDamage(tagCompund.getInt("potionValue")); + this.setPotionDamage(tagCompund.getInteger("potionValue")); } if (this.potionDamage == null) @@ -180,13 +180,13 @@ public class EntityPotion extends EntityThrowable implements IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); + super.writeEntityToNBT(tagCompound); if (this.potionDamage != null) { - tagCompound.setObject("Potion", this.potionDamage.writeTags(new TagObject())); + tagCompound.setTag("Potion", this.potionDamage.writeToNBT(new NBTTagCompound())); } } diff --git a/common/src/main/java/common/entity/projectile/EntityProjectile.java b/common/src/common/entity/projectile/EntityProjectile.java similarity index 90% rename from common/src/main/java/common/entity/projectile/EntityProjectile.java rename to common/src/common/entity/projectile/EntityProjectile.java index 394801e..32dd6d5 100755 --- a/common/src/main/java/common/entity/projectile/EntityProjectile.java +++ b/common/src/common/entity/projectile/EntityProjectile.java @@ -9,7 +9,8 @@ import common.entity.EntityType; import common.entity.types.EntityLiving; import common.init.BlockRegistry; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; @@ -253,53 +254,50 @@ public abstract class EntityProjectile extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { tagCompound.setShort("xTile", (short)this.xTile); tagCompound.setShort("yTile", (short)this.yTile); tagCompound.setShort("zTile", (short)this.zTile); - if(this.inTile != null) { - String id = BlockRegistry.getNameFromBlock(this.inTile); - tagCompound.setString("inTile", id == null ? "" : id.toString()); - } - tagCompound.setBool("inGround", this.inGround); - tagCompound.setDouble("dirX", this.motionX); - tagCompound.setDouble("dirY", this.motionY); - tagCompound.setDouble("dirZ", this.motionZ); - tagCompound.setInt("Age", this.age); + String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(this.inTile); + tagCompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); + tagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0)); + tagCompound.setTag("direction", this.newDoubleNBTList(this.motionX, this.motionY, this.motionZ)); + tagCompound.setInteger("Age", this.age); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { this.xTile = tagCompund.getShort("xTile"); this.yTile = tagCompund.getShort("yTile"); this.zTile = tagCompund.getShort("zTile"); - if (tagCompund.hasString("inTile")) + if (tagCompund.hasKey("inTile", 8)) { - this.inTile = BlockRegistry.getRegisteredBlock(tagCompund.getString("inTile")); + this.inTile = BlockRegistry.getByIdFallback(tagCompund.getString("inTile")); } else { - this.inTile = null; + this.inTile = BlockRegistry.getBlockById(tagCompund.getByte("inTile") & 255); } - this.inGround = tagCompund.getBool("inGround"); + this.inGround = tagCompund.getByte("inGround") == 1; - if (tagCompund.hasDouble("dirX") && tagCompund.hasDouble("dirY") && tagCompund.hasDouble("dirZ")) + if (tagCompund.hasKey("direction", 9)) { - this.motionX = tagCompund.getDouble("dirX"); - this.motionY = tagCompund.getDouble("dirY"); - this.motionZ = tagCompund.getDouble("dirZ"); + NBTTagList nbttaglist = tagCompund.getTagList("direction", 6); + this.motionX = nbttaglist.getDoubleAt(0); + this.motionY = nbttaglist.getDoubleAt(1); + this.motionZ = nbttaglist.getDoubleAt(2); } else { this.setDead(); } - this.age = tagCompund.getInt("Age"); + this.age = tagCompund.getInteger("Age"); } /** diff --git a/common/src/main/java/common/entity/projectile/EntitySnowball.java b/common/src/common/entity/projectile/EntitySnowball.java similarity index 95% rename from common/src/main/java/common/entity/projectile/EntitySnowball.java rename to common/src/common/entity/projectile/EntitySnowball.java index b2aa02c..6e4a137 100755 --- a/common/src/main/java/common/entity/projectile/EntitySnowball.java +++ b/common/src/common/entity/projectile/EntitySnowball.java @@ -3,9 +3,9 @@ package common.entity.projectile; import common.entity.DamageSource; import common.entity.types.EntityLiving; import common.entity.types.EntityThrowable; +import common.init.Config; import common.model.ParticleType; import common.util.HitPosition; -import common.vars.Vars; import common.world.World; public class EntitySnowball extends EntityThrowable @@ -39,7 +39,7 @@ public class EntitySnowball extends EntityThrowable // i = 3; // } - if(Vars.knockSnowball) + if(Config.knockSnowball) p_70184_1_.entity.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()), 0); } diff --git a/common/src/main/java/common/entity/projectile/FishConstants.java b/common/src/common/entity/projectile/FishConstants.java similarity index 100% rename from common/src/main/java/common/entity/projectile/FishConstants.java rename to common/src/common/entity/projectile/FishConstants.java diff --git a/common/src/main/java/common/entity/projectile/RngFishable.java b/common/src/common/entity/projectile/RngFishable.java similarity index 100% rename from common/src/main/java/common/entity/projectile/RngFishable.java rename to common/src/common/entity/projectile/RngFishable.java diff --git a/common/src/common/entity/types/CombatEntry.java b/common/src/common/entity/types/CombatEntry.java new file mode 100755 index 0000000..d630ff5 --- /dev/null +++ b/common/src/common/entity/types/CombatEntry.java @@ -0,0 +1,33 @@ +package common.entity.types; + +import common.entity.DamageSource; + +public class CombatEntry { + private final DamageSource source; + private final int damage; + private final String blockType; + private final float fallDistance; + + public CombatEntry(DamageSource source, int damage, String blockType, float fallDistance) { + this.source = source; + this.damage = damage; + this.blockType = blockType; + this.fallDistance = fallDistance; + } + + public DamageSource getSource() { + return this.source; + } + + public int getDamage() { + return this.damage; + } + + public String getBlockType() { + return this.blockType; + } + + public float getFallDistance() { + return this.source == DamageSource.outOfWorld ? Float.MAX_VALUE : this.fallDistance; + } +} diff --git a/common/src/main/java/common/entity/types/EntityAnimal.java b/common/src/common/entity/types/EntityAnimal.java similarity index 95% rename from common/src/main/java/common/entity/types/EntityAnimal.java rename to common/src/common/entity/types/EntityAnimal.java index e8a0542..3cfde3a 100755 --- a/common/src/main/java/common/entity/types/EntityAnimal.java +++ b/common/src/common/entity/types/EntityAnimal.java @@ -12,7 +12,7 @@ import common.init.Blocks; import common.init.Items; import common.item.ItemStack; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BlockPos; import common.util.ExtMath; import common.world.World; @@ -100,19 +100,19 @@ public abstract class EntityAnimal extends EntityLiving /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); - tagCompound.setInt("InLove", this.inLove); + super.writeEntityToNBT(tagCompound); + tagCompound.setInteger("InLove", this.inLove); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); - this.setInLove(tagCompund.getInt("InLove"), true); + super.readEntityFromNBT(tagCompund); + this.setInLove(tagCompund.getInteger("InLove"), true); } /** @@ -200,9 +200,9 @@ public abstract class EntityAnimal extends EntityLiving { // if (!player.creative) // { - --stack.size; + --stack.stackSize; - if (stack.size <= 0) + if (stack.stackSize <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } diff --git a/common/src/main/java/common/entity/types/EntityBodyHelper.java b/common/src/common/entity/types/EntityBodyHelper.java similarity index 100% rename from common/src/main/java/common/entity/types/EntityBodyHelper.java rename to common/src/common/entity/types/EntityBodyHelper.java diff --git a/common/src/main/java/common/entity/types/EntityLiving.java b/common/src/common/entity/types/EntityLiving.java similarity index 89% rename from common/src/main/java/common/entity/types/EntityLiving.java rename to common/src/common/entity/types/EntityLiving.java index 46a66ca..abcd0db 100755 --- a/common/src/main/java/common/entity/types/EntityLiving.java +++ b/common/src/common/entity/types/EntityLiving.java @@ -14,7 +14,10 @@ import common.ai.EntityLookHelper; import common.ai.EntityMoveHelper; import common.ai.EntitySenses; import common.attributes.Attribute; +import common.attributes.AttributeInstance; import common.attributes.AttributeMap; +import common.attributes.AttributeModifier; +import common.attributes.Attributes; import common.block.Block; import common.block.SoundType; import common.collect.Lists; @@ -34,6 +37,7 @@ import common.entity.npc.EntityNPC; import common.entity.projectile.EntityArrow; import common.init.BlockRegistry; import common.init.Blocks; +import common.init.Config; import common.init.EntityRegistry; import common.init.ItemRegistry; import common.init.Items; @@ -42,9 +46,12 @@ import common.item.Item; import common.item.ItemArmor; import common.item.ItemMonsterPlacer; import common.item.ItemStack; +import common.material.Material; import common.model.ParticleType; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.network.IPlayer; -import common.packet.SPacketEntityAttach; +import common.packet.S1BPacketEntityAttach; import common.packet.SPacketAnimation; import common.packet.SPacketCollectItem; import common.pathfinding.PathNavigate; @@ -53,12 +60,10 @@ import common.potion.Potion; import common.potion.PotionEffect; import common.potion.PotionHelper; import common.rng.Random; -import common.tags.TagObject; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; import common.util.Vec3; -import common.vars.Vars; import common.world.State; import common.world.World; import common.world.AWorldServer; @@ -67,7 +72,7 @@ public abstract class EntityLiving extends Entity { private static final ItemStack[] EMPTY_INV = new ItemStack[5]; - protected AttributeMap attributes = new AttributeMap(); + private AttributeMap attributes; private final List combat = Lists.newArrayList(); private final Map effects = Maps.newEnumMap(Potion.class); public int soundTimer; @@ -83,7 +88,7 @@ public abstract class EntityLiving extends Entity private EntitySenses senses; private boolean leashed; private Entity leashedTo; - private TagObject leashTag; + private NBTTagCompound leashTag; public float prevCamPitch; public float camPitch; @@ -153,8 +158,6 @@ public abstract class EntityLiving extends Entity private float ageHeight; private EntityAIBase aiBase = new EntityAIMoveTowardsRestriction(this, 1.0D); private boolean isMovementAITaskSet; - private float baseSpeed = 0.7f; - private float modSpeed = 1.0f; public EntityLiving(World worldIn) { @@ -181,16 +184,23 @@ public abstract class EntityLiving extends Entity protected void entityInit() { - this.dataWatcher.addObject(2, 0); // potion color - this.dataWatcher.addObject(3, (byte)0); // potion ambient - this.dataWatcher.addObject(4, (byte)0); // arrows - this.dataWatcher.addObject(5, 1); // max health - this.dataWatcher.addObject(6, 1); // health - this.dataWatcher.addObject(7, 0); // age + this.dataWatcher.addObject(7, Integer.valueOf(0)); + this.dataWatcher.addObject(8, Byte.valueOf((byte)0)); + this.dataWatcher.addObject(9, Byte.valueOf((byte)0)); + this.dataWatcher.addObject(6, Integer.valueOf(1)); + this.dataWatcher.addObject(12, Integer.valueOf(0)); +// this.dataWatcher.addObject(15, Byte.valueOf((byte)0)); } protected void applyEntityAttributes() { + this.getAttributeMap().registerAttribute(Attributes.MAX_HEALTH); + this.getAttributeMap().registerAttribute(Attributes.KNOCKBACK_RESISTANCE); + this.getAttributeMap().registerAttribute(Attributes.MOVEMENT_SPEED); + this.getAttributeMap().registerAttribute(Attributes.RADIATION); + this.getAttributeMap().registerAttribute(Attributes.RADIATION_RESISTANCE); + + this.getAttributeMap().registerAttribute(Attributes.FOLLOW_RANGE).setBaseValue(16.0D); } protected void updateFallState(double y, boolean onGroundIn, Block blockIn, BlockPos pos) @@ -214,7 +224,7 @@ public abstract class EntityLiving extends Entity Block block = iblockstate.getBlock(); float f = (float)ExtMath.ceilf(this.fallDistance - 3.0F); - if (block != Blocks.air) + if (block.getMaterial() != Material.air) { double d0 = (double)Math.min(0.2F + f / 15.0F, 10.0F); @@ -245,7 +255,7 @@ public abstract class EntityLiving extends Entity if (this.isEntityAlive()) { - if ((this.worldObj.client || Vars.damageWall) && this.isEntityInsideOpaqueBlock()) + if ((this.worldObj.client || Config.damageWall) && this.isEntityInsideOpaqueBlock()) { this.attackEntityFrom(DamageSource.inWall, 1); } @@ -304,7 +314,7 @@ public abstract class EntityLiving extends Entity // } // } - if (this.isEntityAlive() && this.isWet()) + if (!this.worldObj.client && this.isEntityAlive() && this.isWet()) { this.extinguish(); } @@ -357,10 +367,10 @@ public abstract class EntityLiving extends Entity } if(!this.worldObj.client) { - if(!this.firstEffectUpdate && Vars.radiation) { // && + if(!this.firstEffectUpdate && Config.radiation) { // && // (!(this.isPlayer()) || !((EntityNPCMP)this).creative)) { - float radiation = this.radiation + this.attributes.get(Attribute.RADIATION); - radiation -= 10.0f + this.attributes.get(Attribute.RADIATION_RESISTANCE); + float radiation = this.radiation + (float)this.attributes.getAttributeInstance(Attributes.RADIATION).getAttributeValue(); + radiation -= (float)this.attributes.getAttributeInstance(Attributes.RADIATION_RESISTANCE).getAttributeValue(); // if(this.isPlayer()) // Log.SERVER.info("rad:" + radiation); if(radiation >= 0.0f) { @@ -419,7 +429,7 @@ public abstract class EntityLiving extends Entity if (this.deathTime == 20) { - if (!this.worldObj.client && (this.recentlyHit > 0 || this.isPlayer()) && this.canDropLoot() && Vars.mobXP) + if (!this.worldObj.client && (this.recentlyHit > 0 || this.isPlayer()) && this.canDropLoot() && Config.mobXP) { int i = this.getExperiencePoints(this.playerAttacker); @@ -530,34 +540,50 @@ public abstract class EntityLiving extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - tagCompound.setInt("MaxHealth", this.getMaxHealth()); - tagCompound.setInt("Health", this.getHealth()); + tagCompound.setInteger("Health", this.getHealth()); // tagCompound.setShort("Health", (short)((int)Math.ceil((double)this.getHealth()))); tagCompound.setShort("HurtTime", (short)this.hurtTime); - tagCompound.setInt("HurtByTimestamp", this.lastAttacked); + tagCompound.setInteger("HurtByTimestamp", this.lastAttacked); tagCompound.setFloat("Radiation", this.radiation); tagCompound.setShort("DeathTime", (short)this.deathTime); - tagCompound.setInt("Absorption", this.getAbsorptionAmount()); - tagCompound.setFloat("SpeedBase", this.getSpeedBase()); + tagCompound.setInteger("Absorption", this.getAbsorptionAmount()); + + for (ItemStack itemstack : this.getInventory()) + { + if (itemstack != null) + { + this.attributes.removeAttributeModifiers(itemstack.getAttributeModifiers(1)); + } + } + + tagCompound.setTag("Attributes", Attributes.writeBaseAttributeMapToNBT(this.getAttributeMap())); + + for (ItemStack itemstack1 : this.getInventory()) + { + if (itemstack1 != null) + { + this.attributes.applyAttributeModifiers(itemstack1.getAttributeModifiers(1)); + } + } if (!this.effects.isEmpty()) { - List nbttaglist = Lists.newArrayList(); + NBTTagList nbttaglist = new NBTTagList(); for (PotionEffect potioneffect : this.effects.values()) { - nbttaglist.add(potioneffect.toTags()); + nbttaglist.appendTag(potioneffect.toNbt()); } - tagCompound.setList("ActiveEffects", nbttaglist); + tagCompound.setTag("ActiveEffects", nbttaglist); } - tagCompound.setBool("Leashed", this.leashed); + tagCompound.setBoolean("Leashed", this.leashed); if(this.leashedTo != null) { - TagObject nbttagcompound1 = new TagObject(); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); // if(this.leashedTo.isPlayer()) { // nbttagcompound1.setString("PlayerName", ((EntityNPC)this.leashedTo).getUser()); @@ -565,18 +591,18 @@ public abstract class EntityLiving extends Entity // else if(this.leashedTo instanceof EntityLeashKnot) { BlockPos blockpos = ((EntityLeashKnot)this.leashedTo).getHangingPosition(); - nbttagcompound1.setInt("X", blockpos.getX()); - nbttagcompound1.setInt("Y", blockpos.getY()); - nbttagcompound1.setInt("Z", blockpos.getZ()); + nbttagcompound1.setInteger("X", blockpos.getX()); + nbttagcompound1.setInteger("Y", blockpos.getY()); + nbttagcompound1.setInteger("Z", blockpos.getZ()); } - tagCompound.setObject("Leash", nbttagcompound1); + tagCompound.setTag("Leash", nbttagcompound1); } // if(this.isAIDisabled()) { // tagCompound.setBoolean("NoAI", this.isAIDisabled()); // } - tagCompound.setInt("Age", this.getGrowingAge()); + tagCompound.setInteger("Age", this.getGrowingAge()); if(this.description != null) tagCompound.setString("Description", this.description); } @@ -584,19 +610,23 @@ public abstract class EntityLiving extends Entity /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - this.setAbsorptionAmount(tagCompund.getInt("Absorption")); - this.setSpeedBase(tagCompund.getFloat("SpeedBase")); + this.setAbsorptionAmount(tagCompund.getInteger("Absorption")); - if (tagCompund.hasList("ActiveEffects")) + if (tagCompund.hasKey("Attributes", 9) && this.worldObj != null && !this.worldObj.client) { - List nbttaglist = tagCompund.getList("ActiveEffects"); + Attributes.setAttributeModifiers(this.getAttributeMap(), tagCompund.getTagList("Attributes", 10)); + } - for (int i = 0; i < nbttaglist.size(); ++i) + if (tagCompund.hasKey("ActiveEffects", 9)) + { + NBTTagList nbttaglist = tagCompund.getTagList("ActiveEffects", 10); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject nbttagcompound = nbttaglist.get(i); - PotionEffect potioneffect = PotionEffect.fromTags(nbttagcompound); + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + PotionEffect potioneffect = PotionEffect.fromNbt(nbttagcompound); if (potioneffect != null && !potioneffect.getPotion().isInstant()) { @@ -605,10 +635,9 @@ public abstract class EntityLiving extends Entity } } - this.setMaxHealth(Math.max(1, tagCompund.getInt("MaxHealth"))); - if (tagCompund.hasInt("Health")) + if (tagCompund.hasKey("Health", 3)) { - this.setHealth(tagCompund.getInt("Health")); + this.setHealth(tagCompund.getInteger("Health")); } else { @@ -630,20 +659,20 @@ public abstract class EntityLiving extends Entity this.hurtTime = tagCompund.getShort("HurtTime"); this.deathTime = tagCompund.getShort("DeathTime"); - this.lastAttacked = tagCompund.getInt("HurtByTimestamp"); + this.lastAttacked = tagCompund.getInteger("HurtByTimestamp"); this.radiation = tagCompund.getFloat("Radiation"); if(!(this.isPlayer())) { - this.leashed = tagCompund.getBool("Leashed"); + this.leashed = tagCompund.getBoolean("Leashed"); - if(this.leashed && tagCompund.hasObject("Leash")) { - this.leashTag = tagCompund.getObject("Leash"); + if(this.leashed && tagCompund.hasKey("Leash", 10)) { + this.leashTag = tagCompund.getCompoundTag("Leash"); } } // this.setNoAI(tagCompund.getBoolean("NoAI")); - this.setGrowingAge(tagCompund.getInt("Age")); - this.description = tagCompund.hasString("Description") ? tagCompund.getString("Description") : null; + this.setGrowingAge(tagCompund.getInteger("Age")); + this.description = tagCompund.hasKey("Description", 8) ? tagCompund.getString("Description") : null; if(this.description != null && this.description.isEmpty()) this.description = null; } @@ -681,8 +710,8 @@ public abstract class EntityLiving extends Entity this.effectsDirty = false; } - int i = this.dataWatcher.getWatchableObjectInt(2); - boolean flag1 = this.dataWatcher.getWatchableObjectByte(3) > 0; + int i = this.dataWatcher.getWatchableObjectInt(7); + boolean flag1 = this.dataWatcher.getWatchableObjectByte(8) > 0; if (i > 0) { @@ -726,8 +755,8 @@ public abstract class EntityLiving extends Entity else { int i = PotionHelper.calcPotionLiquidColor(this.effects.values()); - this.dataWatcher.updateObject(3, Byte.valueOf((byte)(PotionHelper.getAreAmbient(this.effects.values()) ? 1 : 0))); - this.dataWatcher.updateObject(2, Integer.valueOf(i)); + this.dataWatcher.updateObject(8, Byte.valueOf((byte)(PotionHelper.getAreAmbient(this.effects.values()) ? 1 : 0))); + this.dataWatcher.updateObject(7, Integer.valueOf(i)); // this.setInvisible(this.hasEffect(Potion.invisibility.id)); } } @@ -737,8 +766,8 @@ public abstract class EntityLiving extends Entity */ protected void resetPotionEffectMetadata() { - this.dataWatcher.updateObject(3, Byte.valueOf((byte)0)); - this.dataWatcher.updateObject(2, Integer.valueOf(0)); + this.dataWatcher.updateObject(8, Byte.valueOf((byte)0)); + this.dataWatcher.updateObject(7, Integer.valueOf(0)); } public void clearEffects(boolean negative) @@ -786,7 +815,7 @@ public abstract class EntityLiving extends Entity */ public void addEffect(PotionEffect potioneffectIn) { - if (!potioneffectIn.getPotion().isInstant() && this.isPotionApplicable(potioneffectIn.getPotion(), potioneffectIn.getAmplifier())) + if (!potioneffectIn.getPotion().isInstant() && this.isPotionApplicable(potioneffectIn.getPotion())) { if (this.effects.containsKey(potioneffectIn.getPotion())) { @@ -801,9 +830,20 @@ public abstract class EntityLiving extends Entity } } - public boolean isPotionApplicable(Potion potion, int amplifier) { - return potion == Potion.SPEED || potion == Potion.SLOWNESS || potion == Potion.HEAL || potion == Potion.DAMAGE || potion == Potion.POISON || potion == Potion.RADIATION; - } + public boolean isPotionApplicable(Potion potion) + { +// if (this.getCreatureType() == CreatureType.UNDEAD) +// { +// int i = potioneffectIn.getPotionID(); +// +// if (i == Potion.regeneration.id || i == Potion.poison.id) +// { +// return false; +// } +// } + + return true; + } public boolean arePotionsInverted() { @@ -837,7 +877,7 @@ public abstract class EntityLiving extends Entity if (!this.worldObj.client) { - id.getPotion().addModifiers(this, id.getAmplifier()); + id.getPotion().addModifiers(this, this.getAttributeMap(), id.getAmplifier()); } } @@ -847,8 +887,8 @@ public abstract class EntityLiving extends Entity if (added && !this.worldObj.client) { - id.getPotion().removeModifiers(this, id.getAmplifier()); - id.getPotion().addModifiers(this, id.getAmplifier()); + id.getPotion().removeModifiers(this, this.getAttributeMap(), id.getAmplifier()); + id.getPotion().addModifiers(this, this.getAttributeMap(), id.getAmplifier()); } } @@ -858,7 +898,7 @@ public abstract class EntityLiving extends Entity if (!this.worldObj.client) { - effect.getPotion().removeModifiers(this, effect.getAmplifier()); + effect.getPotion().removeModifiers(this, this.getAttributeMap(), effect.getAmplifier()); } } @@ -874,6 +914,11 @@ public abstract class EntityLiving extends Entity this.setHealth(f + healAmount); } } + + public void healMana(int amount) + { + this.setManaPoints(ExtMath.clampi(this.getManaPoints() + amount, 0, this.getMaxMana())); + } public final int getHealth() { @@ -940,7 +985,7 @@ public abstract class EntityLiving extends Entity else { this.lastDamage = amount; - this.hurtResistance = this.hurtCooldown = Vars.hurtDelay; + this.hurtResistance = this.hurtCooldown = Config.hurtDelay; this.damageEntity(source, amount); this.hurtTime = this.maxHurtTime = 10; } @@ -1079,7 +1124,7 @@ public abstract class EntityLiving extends Entity i = EnchantmentHelper.getLootingModifier((EntityLiving)entity); } - if (this.canDropLoot() && Vars.dropLoot) + if (this.canDropLoot() && Config.dropLoot) { this.dropFewItems(this.recentlyHit > 0, i); // this.dropEquipment(this.recentlyHit > 0, i); @@ -1110,11 +1155,11 @@ public abstract class EntityLiving extends Entity */ public void knockBack(Entity source, float damage, double xfactor, double zfactor) { - if (!this.hasEffect(Potion.STABILITY) && this.rand.doublev() >= this.getKnockBackResistance()) + if (this.rand.doublev() >= this.getEntityAttribute(Attributes.KNOCKBACK_RESISTANCE).getAttributeValue()) { this.isAirBorne = true; float div = ExtMath.sqrtd(xfactor * xfactor + zfactor * zfactor); - float mult = 0.4F * Vars.knockback; + float mult = 0.4F * Config.knockback; this.motionX /= 2.0D; this.motionY /= 2.0D; this.motionZ /= 2.0D; @@ -1193,7 +1238,7 @@ public abstract class EntityLiving extends Entity if (i > 0) { - if(Vars.damageFall) { + if(Config.damageFall) { this.playSound(i > 4 ? SoundEvent.FALL_BIG : SoundEvent.FALL_SMALL, 1.0F); this.attackEntityFrom(DamageSource.fall, i); } @@ -1202,7 +1247,7 @@ public abstract class EntityLiving extends Entity int l = ExtMath.floord(this.posZ); Block block = this.worldObj.getState(new BlockPos(j, k, l)).getBlock(); - if (block != Blocks.air) + if (block.getMaterial() != Material.air) { SoundType block$soundtype = block.sound; if(block$soundtype.getStepSound() != null) @@ -1336,12 +1381,21 @@ public abstract class EntityLiving extends Entity public final int getMaxHealth() { - return this.dataWatcher.getWatchableObjectInt(5); + return (int)this.getEntityAttribute(Attributes.MAX_HEALTH).getAttributeValue(); + } + + public final int getRawMaxHealth() + { + return (int)this.getEntityAttribute(Attributes.MAX_HEALTH).getBaseValue(); } public final void setMaxHealth(int max) { - this.dataWatcher.updateObject(5, max); + this.getEntityAttribute(Attributes.MAX_HEALTH).setBaseValue((double)max); + } + + public int getMaxMana() { + return 0; } /** @@ -1349,7 +1403,7 @@ public abstract class EntityLiving extends Entity */ public final int getArrowCountInEntity() { - return this.dataWatcher.getWatchableObjectByte(4); + return this.dataWatcher.getWatchableObjectByte(9); } /** @@ -1357,7 +1411,7 @@ public abstract class EntityLiving extends Entity */ public final void setArrowCountInEntity(int count) { - this.dataWatcher.updateObject(4, Byte.valueOf((byte)count)); + this.dataWatcher.updateObject(9, Byte.valueOf((byte)count)); } /** @@ -1430,7 +1484,7 @@ public abstract class EntityLiving extends Entity public void kill() { - if(this.worldObj.client || Vars.damageVoid) + if(this.worldObj.client || Config.damageVoid) this.attackEntityFrom(DamageSource.outOfWorld, Integer.MAX_VALUE); } @@ -1459,8 +1513,18 @@ public abstract class EntityLiving extends Entity this.swingFactor = (float)this.swingTimer / (float)i; } - public final AttributeMap getAttributeMap() + public AttributeInstance getEntityAttribute(Attribute attribute) { + return this.getAttributeMap().getAttributeInstance(attribute); + } + + public AttributeMap getAttributeMap() + { + if (this.attributes == null) + { + this.attributes = new AttributeMap(this.worldObj == null || this.worldObj.client); + } + return this.attributes; } @@ -1482,6 +1546,25 @@ public abstract class EntityLiving extends Entity } // public abstract void setItem(int slot, ItemStack stack); + /** + * Set sprinting switch for Entity. + */ + public void setSprinting(boolean sprinting) + { + super.setSprinting(sprinting); + AttributeInstance iattributeinstance = this.getEntityAttribute(Attributes.MOVEMENT_SPEED); + + if (iattributeinstance.getModifier(Attributes.SPRINT_SPEED_ID) != null) + { + iattributeinstance.removeModifier(Attributes.SPRINT_SPEED_MOD); + } + + if (sprinting) + { + iattributeinstance.applyModifier(Attributes.SPRINT_SPEED_MOD); + } + } + /** * returns the inventory of this entity (only used in EntityNPCMP it seems) */ @@ -1663,7 +1746,7 @@ public abstract class EntityLiving extends Entity this.motionY = 0.2D; } - if (this.worldObj.client && (!this.worldObj.isBlockLoaded(new BlockPos((int)this.posX, 0, (int)this.posZ)) || !this.worldObj.getChunk(new BlockPos((int)this.posX, 0, (int)this.posZ)).isLoaded()) && !this.isPlayer()) + if (this.worldObj.client && (!this.worldObj.isBlockLoaded(new BlockPos((int)this.posX, 0, (int)this.posZ)) || !this.worldObj.getChunk(new BlockPos((int)this.posX, 0, (int)this.posZ)).isLoaded())) { if (this.posY > 0.0D) { @@ -1758,27 +1841,6 @@ public abstract class EntityLiving extends Entity { return this.landMovement; } - - public float getSpeedBase() { - return this.baseSpeed; - } - - public void setSpeedBase(float value) { - this.baseSpeed = value; - } - - public final void setSpeedMod(float value) { - this.modSpeed = value; - } - - public float getMovementSpeed() { - float speed = this.getSpeedBase() * (this.isSprinting() ? 1.3f : 1.0f); - if(this.hasEffect(Potion.SPEED)) - speed *= 1.0f + (float)(this.getEffect(Potion.SPEED).getAmplifier() + 1) * 0.2f; - if(this.hasEffect(Potion.SLOWNESS)) - speed *= Math.max(1.0f - (float)(this.getEffect(Potion.SLOWNESS).getAmplifier() + 1) * 0.15f, 0.0f); - return Math.max(this.modSpeed * speed, 0.0f); - } /** * set the movespeed used for the new AI system @@ -2135,14 +2197,14 @@ public abstract class EntityLiving extends Entity this.fallDistance = 0.0F; } - public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) { this.newX = x; this.newY = y; this.newZ = z; this.newYaw = (double)yaw; this.newPitch = (double)pitch; - this.moveIncrements = 3; + this.moveIncrements = posRotationIncrements; } public void setJumping(boolean jumping) @@ -2244,17 +2306,13 @@ public abstract class EntityLiving extends Entity { return !this.dead; } - - public double getKnockBackResistance() { - return 0.0; - } /** * Sets that this entity has been attacked. */ protected void setBeenAttacked() { - this.veloChanged = !this.hasEffect(Potion.STABILITY) && this.rand.doublev() >= this.getKnockBackResistance(); + this.veloChanged = this.rand.doublev() >= this.getEntityAttribute(Attributes.KNOCKBACK_RESISTANCE).getAttributeValue(); } public float getRotationYawHead() @@ -2324,6 +2382,13 @@ public abstract class EntityLiving extends Entity return max >= 2000 ? TextColor.BLACK : (max >= 500 ? TextColor.DMAGENTA : (max >= 120 ? TextColor.MAGENTA : (max >= 40 ? TextColor.CYAN : (max >= 15 ? TextColor.NEON : (max >= 5 ? TextColor.BLUE : TextColor.LGRAY))))); } + + public int getManaPoints() { + return 0; + } + + public void setManaPoints(int pts) { + } public int getEnergy(Energy type) { return 0; @@ -2343,8 +2408,9 @@ public abstract class EntityLiving extends Entity public String formatStats() { return String.format(this.getAlignment().prefix + " " + getHealthColor(this.getHealth(), this.getMaxHealth()) + "%d" + - TextColor.GRAY + "/" + getMaxHpColor(this.getMaxHealth()) + "%d", - this.getHealth(), this.getMaxHealth()); + TextColor.GRAY + "/" + getMaxHpColor(this.getMaxHealth()) + + "%d" + (this.getManaPoints() == 0 ? "" : (TextColor.GRAY + " [" + TextColor.MIDNIGHT + "%d" + TextColor.GRAY + "]")), + this.getHealth(), this.getMaxHealth(), this.getManaPoints()); } public abstract int getColor(); @@ -2379,11 +2445,11 @@ public abstract class EntityLiving extends Entity else if(this.isInLiquid()) { this.blockType = "aus dem Wasser"; } - CombatEntry entry = new CombatEntry(source, amount, this.blockType, source == DamageSource.outOfWorld ? Float.MAX_VALUE : this.fallDistance); + CombatEntry entry = new CombatEntry(source, amount, this.blockType, this.fallDistance); this.combat.add(entry); this.lastDamaged = this.ticksExisted; this.damaged = true; - if(entry.source().getEntity() instanceof EntityLiving && !this.attacked && this.isEntityAlive()) + if(entry.getSource().getEntity() instanceof EntityLiving && !this.attacked && this.isEntityAlive()) this.attacked = true; } @@ -2410,8 +2476,8 @@ public abstract class EntityLiving extends Entity CombatEntry entry = (CombatEntry)this.combat.get(z); CombatEntry last = z > 0 ? (CombatEntry)this.combat.get(z - 1) : null; - if((entry.source() == DamageSource.fall || entry.source() == DamageSource.outOfWorld) && - entry.fallDistance() > 0.0F && (strong == null || entry.fallDistance() > max)) { + if((entry.getSource() == DamageSource.fall || entry.getSource() == DamageSource.outOfWorld) && + entry.getFallDistance() > 0.0F && (strong == null || entry.getFallDistance() > max)) { if(z > 0) { strong = last; } @@ -2419,20 +2485,20 @@ public abstract class EntityLiving extends Entity strong = entry; } - max = entry.fallDistance(); + max = entry.getFallDistance(); } - if(entry.blockType() != null && (block == null || entry.damage() > min)) { + if(entry.getBlockType() != null && (block == null || entry.getDamage() > min)) { block = entry; } } CombatEntry fall = max > 5.0F && strong != null ? strong : (min > 5 && block != null ? block : null); CombatEntry last = (CombatEntry)this.combat.get(this.combat.size() - 1); - Entity lastEnt = last.source().getEntity(); + Entity lastEnt = last.getSource().getEntity(); - if(fall != null && last.source() == DamageSource.fall) { - if(fall.source() != DamageSource.fall && fall.source() != DamageSource.outOfWorld) { - Entity fallEnt = fall.source().getEntity(); + if(fall != null && last.getSource() == DamageSource.fall) { + if(fall.getSource() != DamageSource.fall && fall.getSource() != DamageSource.outOfWorld) { + Entity fallEnt = fall.getSource().getEntity(); if(fallEnt != null && (lastEnt == null || fallEnt != lastEnt)) { ItemStack fallItem = fallEnt instanceof EntityLiving ? ((EntityLiving)fallEnt).getHeldItem() : null; receiver = fallEnt.isPlayer() ? ((EntityNPC)fallEnt).connection : null; @@ -2470,14 +2536,14 @@ public abstract class EntityLiving extends Entity } } else { - msg = kill = natural ? String.format("%s fiel " + (fall.blockType() == null ? "aus zu großer Höhe" : fall.blockType()), + msg = kill = natural ? String.format("%s fiel " + (fall.getBlockType() == null ? "aus zu großer Höhe" : fall.getBlockType()), this.getColoredName(TextColor.NEON)) : null; } } else { - receiver = last.source().getEntity() != null && last.source().getEntity().isPlayer() ? ((EntityNPC)last.source().getEntity()).connection : null; - msg = natural || (last.source() instanceof EntityDamageSource ? last.source().getEntity() != null : this.getAttackingEntity() != null) ? last.source().getDeathMessage(this) : null; - kill = msg == null ? null : last.source().getKillMessage(this); + receiver = last.getSource().getEntity() != null && last.getSource().getEntity().isPlayer() ? ((EntityNPC)last.getSource().getEntity()).connection : null; + msg = natural || (last.getSource() instanceof EntityDamageSource ? last.getSource().getEntity() != null : this.getAttackingEntity() != null) ? last.getSource().getDeathMessage(this) : null; + kill = msg == null ? null : last.getSource().getKillMessage(this); } } if(msg == null) @@ -2497,13 +2563,13 @@ public abstract class EntityLiving extends Entity int edmg = 0; int pdmg = 0; for(CombatEntry entry : this.combat) { - if(entry.source().getEntity() != null && entry.source().getEntity().isPlayer() && (player == null || entry.damage() > pdmg)) { - pdmg = entry.damage(); - player = (EntityNPC)entry.source().getEntity(); + if(entry.getSource().getEntity() != null && entry.getSource().getEntity().isPlayer() && (player == null || entry.getDamage() > pdmg)) { + pdmg = entry.getDamage(); + player = (EntityNPC)entry.getSource().getEntity(); } - if(entry.source().getEntity() instanceof EntityLiving && (entity == null || entry.damage() > edmg)) { - edmg = entry.damage(); - entity = (EntityLiving)entry.source().getEntity(); + if(entry.getSource().getEntity() instanceof EntityLiving && (entity == null || entry.getDamage() > edmg)) { + edmg = entry.getDamage(); + entity = (EntityLiving)entry.getSource().getEntity(); } } return player != null && pdmg >= edmg / 3 ? player : entity; @@ -2647,12 +2713,10 @@ public abstract class EntityLiving extends Entity // super.setAIMoveSpeed(speedIn); // this.setMoveForward(speedIn); // } - - public int getPathingRange() { - return 16; - } public Object onInitialSpawn(Object livingdata) { + this.getEntityAttribute(Attributes.FOLLOW_RANGE) + .applyModifier(new AttributeModifier("Random spawn bonus", this.rand.gaussian() * 0.05D, true)); return livingdata; } @@ -2673,7 +2737,7 @@ public abstract class EntityLiving extends Entity // } public boolean isTicked() { - return !this.worldObj.client && /* !this.isAIDisabled() && */ Vars.mobTick; + return !this.worldObj.client && /* !this.isAIDisabled() && */ Config.mobTick; } // public void setNoAI(boolean disable) { @@ -2712,13 +2776,13 @@ public abstract class EntityLiving extends Entity if(stack != null && stack.getItem() == Items.lead && this.allowLeashing()) { if(!(this instanceof EntityTameable) || !((EntityTameable)this).isTamed()) { this.setLeashedTo(player, true); - --stack.size; + --stack.stackSize; return true; } if(((EntityTameable)this).isOwner(player)) { this.setLeashedTo(player, true); - --stack.size; + --stack.stackSize; return true; } } @@ -3030,7 +3094,7 @@ public abstract class EntityLiving extends Entity } if(!this.worldObj.client && pkt && this.worldObj instanceof AWorldServer) { - ((AWorldServer)this.worldObj).sendToAllTrackingEntity(this, new SPacketEntityAttach(1, this, (Entity)null)); + ((AWorldServer)this.worldObj).sendToAllTrackingEntity(this, new S1BPacketEntityAttach(1, this, (Entity)null)); } } } @@ -3052,13 +3116,13 @@ public abstract class EntityLiving extends Entity this.leashedTo = entity; if(!this.worldObj.client && pkt && this.worldObj instanceof AWorldServer) { - ((AWorldServer)this.worldObj).sendToAllTrackingEntity(this, new SPacketEntityAttach(1, this, this.leashedTo)); + ((AWorldServer)this.worldObj).sendToAllTrackingEntity(this, new S1BPacketEntityAttach(1, this, this.leashedTo)); } } private void recreateLeash() { if(this.leashed && this.leashTag != null) { -// if(this.leashTag.hasString("PlayerName")) { +// if(this.leashTag.hasKey("PlayerName", 8)) { // String id = this.leashTag.getString("PlayerName"); // if(!id.isEmpty()) { // for(EntityNPC entitylivingbase : this.worldObj.getEntitiesWithinAABB(EntityNPC.class, @@ -3071,9 +3135,9 @@ public abstract class EntityLiving extends Entity // } // } // else - if(this.leashTag.hasInt("X") && this.leashTag.hasInt("Y") && this.leashTag.hasInt("Z")) { - BlockPos blockpos = new BlockPos(this.leashTag.getInt("X"), this.leashTag.getInt("Y"), - this.leashTag.getInt("Z")); + if(this.leashTag.hasKey("X", 99) && this.leashTag.hasKey("Y", 99) && this.leashTag.hasKey("Z", 99)) { + BlockPos blockpos = new BlockPos(this.leashTag.getInteger("X"), this.leashTag.getInteger("Y"), + this.leashTag.getInteger("Z")); EntityLeashKnot entityleashknot = EntityLeashKnot.getKnotForPosition(this.worldObj, blockpos); if(entityleashknot == null) { @@ -3159,9 +3223,9 @@ public abstract class EntityLiving extends Entity // if (!player.creative) // { - --itemstack.size; + --itemstack.stackSize; - if (itemstack.size <= 0) + if (itemstack.stackSize <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } @@ -3180,7 +3244,7 @@ public abstract class EntityLiving extends Entity public int getGrowingAge() { - return this.worldObj.client ? this.dataWatcher.getWatchableObjectInt(7) : this.growingAge; + return this.worldObj.client ? this.dataWatcher.getWatchableObjectInt(12) : this.growingAge; } public void grow(int amount) @@ -3192,7 +3256,7 @@ public abstract class EntityLiving extends Entity public void setGrowingAge(int age) { - this.dataWatcher.updateObject(7, Integer.valueOf(ExtMath.clampi(age, -24000, 1))); + this.dataWatcher.updateObject(12, Integer.valueOf(ExtMath.clampi(age, -24000, 1))); this.growingAge = age; this.setScaleForAge(); } diff --git a/common/src/main/java/common/entity/types/EntityTameable.java b/common/src/common/entity/types/EntityTameable.java similarity index 90% rename from common/src/main/java/common/entity/types/EntityTameable.java rename to common/src/common/entity/types/EntityTameable.java index eb6e0c9..877b9c9 100755 --- a/common/src/main/java/common/entity/types/EntityTameable.java +++ b/common/src/common/entity/types/EntityTameable.java @@ -2,7 +2,7 @@ package common.entity.types; import common.ai.EntityAISit; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.world.World; public abstract class EntityTameable extends EntityAnimal implements IEntityOwnable @@ -25,9 +25,9 @@ public abstract class EntityTameable extends EntityAnimal implements IEntityOwna /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntity(tagCompound); + super.writeEntityToNBT(tagCompound); // if (this.getOwnerId() == null) // { @@ -38,19 +38,19 @@ public abstract class EntityTameable extends EntityAnimal implements IEntityOwna // tagCompound.setString("Owner", this.getOwnerId()); // } - tagCompound.setBool("Tame", this.isTamed()); - tagCompound.setBool("Sitting", this.isSitting()); + tagCompound.setBoolean("Tame", this.isTamed()); + tagCompound.setBoolean("Sitting", this.isSitting()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntity(tagCompund); + super.readEntityFromNBT(tagCompund); // String s = ""; // -// if (tagCompund.hasString("Owner")) +// if (tagCompund.hasKey("Owner", 8)) // { // s = tagCompund.getString("Owner"); // } @@ -61,9 +61,9 @@ public abstract class EntityTameable extends EntityAnimal implements IEntityOwna // this.setTamed(true); // } - this.setTamed(tagCompund.getBool("Tame")); - this.aiSit.setSitting(tagCompund.getBool("Sitting")); - this.setSitting(tagCompund.getBool("Sitting")); + this.setTamed(tagCompund.getBoolean("Tame")); + this.aiSit.setSitting(tagCompund.getBoolean("Sitting")); + this.setSitting(tagCompund.getBoolean("Sitting")); } /** diff --git a/common/src/main/java/common/entity/types/EntityThrowable.java b/common/src/common/entity/types/EntityThrowable.java similarity index 94% rename from common/src/main/java/common/entity/types/EntityThrowable.java rename to common/src/common/entity/types/EntityThrowable.java index a67633e..e325a29 100755 --- a/common/src/main/java/common/entity/types/EntityThrowable.java +++ b/common/src/common/entity/types/EntityThrowable.java @@ -3,13 +3,13 @@ package common.entity.types; import java.util.List; import common.block.Block; -import common.block.artificial.BlockPortal; +import common.block.BlockPortal; import common.entity.Entity; import common.entity.EntityType; import common.init.BlockRegistry; import common.init.Blocks; import common.model.ParticleType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; @@ -303,17 +303,15 @@ public abstract class EntityThrowable extends Entity implements IProjectile /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntity(TagObject tagCompound) + public void writeEntityToNBT(NBTTagCompound tagCompound) { tagCompound.setShort("xTile", (short)this.xTile); tagCompound.setShort("yTile", (short)this.yTile); tagCompound.setShort("zTile", (short)this.zTile); - if(this.inTile != null) { - String id = BlockRegistry.getNameFromBlock(this.inTile); - tagCompound.setString("inTile", id == null ? "" : id.toString()); - } + String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(this.inTile); + tagCompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); tagCompound.setByte("shake", (byte)this.throwableShake); - tagCompound.setBool("inGround", this.inGround); + tagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0)); // if ((this.throwerName == null || this.throwerName.length() == 0) && this.thrower.isPlayer()) // { @@ -326,23 +324,23 @@ public abstract class EntityThrowable extends Entity implements IProjectile /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntity(TagObject tagCompund) + public void readEntityFromNBT(NBTTagCompound tagCompund) { this.xTile = tagCompund.getShort("xTile"); this.yTile = tagCompund.getShort("yTile"); this.zTile = tagCompund.getShort("zTile"); - if (tagCompund.hasString("inTile")) + if (tagCompund.hasKey("inTile", 8)) { - this.inTile = BlockRegistry.getRegisteredBlock(tagCompund.getString("inTile")); + this.inTile = BlockRegistry.getByIdFallback(tagCompund.getString("inTile")); } else { - this.inTile = null; + this.inTile = BlockRegistry.getBlockById(tagCompund.getByte("inTile") & 255); } this.throwableShake = tagCompund.getByte("shake") & 255; - this.inGround = tagCompund.getBool("inGround"); + this.inGround = tagCompund.getByte("inGround") == 1; // this.thrower = null; // this.throwerName = tagCompund.getString("ownerName"); // diff --git a/common/src/main/java/common/entity/types/EntityWaterMob.java b/common/src/common/entity/types/EntityWaterMob.java similarity index 94% rename from common/src/main/java/common/entity/types/EntityWaterMob.java rename to common/src/common/entity/types/EntityWaterMob.java index ae019b0..7b9e27e 100755 --- a/common/src/main/java/common/entity/types/EntityWaterMob.java +++ b/common/src/common/entity/types/EntityWaterMob.java @@ -3,7 +3,7 @@ package common.entity.types; import common.entity.DamageSource; import common.entity.EntityType; import common.entity.npc.EntityNPC; -import common.vars.Vars; +import common.init.Config; import common.world.World; public abstract class EntityWaterMob extends EntityLiving @@ -71,7 +71,7 @@ public abstract class EntityWaterMob extends EntityLiving // int i = this.getAir(); super.onEntityUpdate(); - if (this.isEntityAlive() && (this.worldObj.client || Vars.waterMobDry) && !this.isInLiquid() && this.rand.chance(30)) + if (this.isEntityAlive() && (this.worldObj.client || Config.waterMobDry) && !this.isInLiquid() && this.rand.chance(30)) { // --i; // this.setAir(i); diff --git a/common/src/main/java/common/entity/types/EntityWeatherEffect.java b/common/src/common/entity/types/EntityWeatherEffect.java similarity index 77% rename from common/src/main/java/common/entity/types/EntityWeatherEffect.java rename to common/src/common/entity/types/EntityWeatherEffect.java index 315c0a0..3604e81 100755 --- a/common/src/main/java/common/entity/types/EntityWeatherEffect.java +++ b/common/src/common/entity/types/EntityWeatherEffect.java @@ -2,7 +2,7 @@ package common.entity.types; import common.entity.Entity; import common.entity.EntityType; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.world.World; public abstract class EntityWeatherEffect extends Entity { @@ -25,10 +25,10 @@ public abstract class EntityWeatherEffect extends Entity { protected final void entityInit() { } - protected final void readEntity(TagObject tagCompund) { + protected final void readEntityFromNBT(NBTTagCompound tagCompund) { } - protected final void writeEntity(TagObject tagCompound) { + protected final void writeEntityToNBT(NBTTagCompound tagCompound) { } public final EntityType getType() { diff --git a/common/src/main/java/common/entity/types/IEntityMultiPart.java b/common/src/common/entity/types/IEntityMultiPart.java similarity index 100% rename from common/src/main/java/common/entity/types/IEntityMultiPart.java rename to common/src/common/entity/types/IEntityMultiPart.java diff --git a/common/src/main/java/common/entity/types/IEntityOwnable.java b/common/src/common/entity/types/IEntityOwnable.java similarity index 100% rename from common/src/main/java/common/entity/types/IEntityOwnable.java rename to common/src/common/entity/types/IEntityOwnable.java diff --git a/common/src/main/java/common/entity/types/IObjectData.java b/common/src/common/entity/types/IObjectData.java similarity index 100% rename from common/src/main/java/common/entity/types/IObjectData.java rename to common/src/common/entity/types/IObjectData.java diff --git a/common/src/main/java/common/entity/types/IProjectile.java b/common/src/common/entity/types/IProjectile.java similarity index 100% rename from common/src/main/java/common/entity/types/IProjectile.java rename to common/src/common/entity/types/IProjectile.java diff --git a/common/src/main/java/common/future/AbstractFuture.java b/common/src/common/future/AbstractFuture.java similarity index 100% rename from common/src/main/java/common/future/AbstractFuture.java rename to common/src/common/future/AbstractFuture.java diff --git a/common/src/main/java/common/future/ExecutionError.java b/common/src/common/future/ExecutionError.java similarity index 100% rename from common/src/main/java/common/future/ExecutionError.java rename to common/src/common/future/ExecutionError.java diff --git a/common/src/main/java/common/future/ExecutionList.java b/common/src/common/future/ExecutionList.java similarity index 100% rename from common/src/main/java/common/future/ExecutionList.java rename to common/src/common/future/ExecutionList.java diff --git a/common/src/main/java/common/future/FutureCallback.java b/common/src/common/future/FutureCallback.java similarity index 100% rename from common/src/main/java/common/future/FutureCallback.java rename to common/src/common/future/FutureCallback.java diff --git a/common/src/main/java/common/future/Futures.java b/common/src/common/future/Futures.java similarity index 100% rename from common/src/main/java/common/future/Futures.java rename to common/src/common/future/Futures.java diff --git a/common/src/main/java/common/future/ListenableFuture.java b/common/src/common/future/ListenableFuture.java similarity index 100% rename from common/src/main/java/common/future/ListenableFuture.java rename to common/src/common/future/ListenableFuture.java diff --git a/common/src/main/java/common/future/ListenableFutureTask.java b/common/src/common/future/ListenableFutureTask.java similarity index 100% rename from common/src/main/java/common/future/ListenableFutureTask.java rename to common/src/common/future/ListenableFutureTask.java diff --git a/common/src/main/java/common/future/MoreExecutors.java b/common/src/common/future/MoreExecutors.java similarity index 100% rename from common/src/main/java/common/future/MoreExecutors.java rename to common/src/common/future/MoreExecutors.java diff --git a/common/src/main/java/common/future/ThreadFactoryBuilder.java b/common/src/common/future/ThreadFactoryBuilder.java similarity index 100% rename from common/src/main/java/common/future/ThreadFactoryBuilder.java rename to common/src/common/future/ThreadFactoryBuilder.java diff --git a/common/src/main/java/common/future/UncheckedExecutionException.java b/common/src/common/future/UncheckedExecutionException.java similarity index 100% rename from common/src/main/java/common/future/UncheckedExecutionException.java rename to common/src/common/future/UncheckedExecutionException.java diff --git a/common/src/main/java/common/init/BlockRegistry.java b/common/src/common/init/BlockRegistry.java similarity index 67% rename from common/src/main/java/common/init/BlockRegistry.java rename to common/src/common/init/BlockRegistry.java index abb3594..2139cff 100755 --- a/common/src/main/java/common/init/BlockRegistry.java +++ b/common/src/common/init/BlockRegistry.java @@ -1,133 +1,10 @@ package common.init; import common.block.*; -import common.block.artificial.BlockBed; -import common.block.artificial.BlockBookshelf; -import common.block.artificial.BlockCake; -import common.block.artificial.BlockCarpet; -import common.block.artificial.BlockCompressedPowered; -import common.block.artificial.BlockDoor; -import common.block.artificial.BlockDragonEgg; -import common.block.artificial.BlockFence; -import common.block.artificial.BlockFenceGate; -import common.block.artificial.BlockFloorPortal; -import common.block.artificial.BlockFlowerPot; -import common.block.artificial.BlockGlass; -import common.block.artificial.BlockHay; -import common.block.artificial.BlockLadder; -import common.block.artificial.BlockPane; -import common.block.artificial.BlockPortal; -import common.block.artificial.BlockPortalFrame; -import common.block.artificial.BlockQuartz; -import common.block.artificial.BlockSkull; -import common.block.artificial.BlockSlab; -import common.block.artificial.BlockStainedGlass; -import common.block.artificial.BlockStainedGlassPane; -import common.block.artificial.BlockStairs; -import common.block.artificial.BlockStoneBrick; -import common.block.artificial.BlockTrapDoor; -import common.block.artificial.BlockWall; -import common.block.foliage.BlockBaseFlower; -import common.block.foliage.BlockBlackenedSoil; -import common.block.foliage.BlockBlueShroom; -import common.block.foliage.BlockCactus; -import common.block.foliage.BlockCarrot; -import common.block.foliage.BlockCocoa; -import common.block.foliage.BlockCrops; -import common.block.foliage.BlockDeadBush; -import common.block.foliage.BlockDoublePlant; -import common.block.foliage.BlockDryLeaves; -import common.block.foliage.BlockFarmland; -import common.block.foliage.BlockGrass; -import common.block.foliage.BlockHugeMushroom; -import common.block.foliage.BlockLeaves; -import common.block.foliage.BlockLilyPad; -import common.block.foliage.BlockLog; -import common.block.foliage.BlockMelon; -import common.block.foliage.BlockMushroom; -import common.block.foliage.BlockMycelium; -import common.block.foliage.BlockPotato; -import common.block.foliage.BlockPumpkin; -import common.block.foliage.BlockReed; -import common.block.foliage.BlockSapling; -import common.block.foliage.BlockStem; -import common.block.foliage.BlockTallGrass; -import common.block.foliage.BlockTianSoil; -import common.block.foliage.BlockVine; -import common.block.foliage.BlockWart; -import common.block.liquid.BlockDynamicLiquid; -import common.block.liquid.BlockStaticLiquid; -import common.block.natural.BlockBedrock; -import common.block.natural.BlockBlackenedDirt; -import common.block.natural.BlockBlackenedStone; -import common.block.natural.BlockClay; -import common.block.natural.BlockDirt; -import common.block.natural.BlockFire; -import common.block.natural.BlockGlowstone; -import common.block.natural.BlockGravel; -import common.block.natural.BlockHardenedClay; -import common.block.natural.BlockHellRock; -import common.block.natural.BlockIce; -import common.block.natural.BlockObsidian; -import common.block.natural.BlockOre; -import common.block.natural.BlockPackedIce; -import common.block.natural.BlockRedstoneOre; -import common.block.natural.BlockRock; -import common.block.natural.BlockSand; -import common.block.natural.BlockSandStone; -import common.block.natural.BlockSlime; -import common.block.natural.BlockSnow; -import common.block.natural.BlockSnowBlock; -import common.block.natural.BlockSoulFire; -import common.block.natural.BlockSoulSand; -import common.block.natural.BlockStone; -import common.block.natural.BlockTintedFire; -import common.block.natural.BlockWeb; -import common.block.tech.BlockAnvil; -import common.block.tech.BlockBeacon; -import common.block.tech.BlockBrewingStand; -import common.block.tech.BlockButton; -import common.block.tech.BlockCauldron; -import common.block.tech.BlockChest; -import common.block.tech.BlockCore; -import common.block.tech.BlockDaylightDetector; -import common.block.tech.BlockDispenser; -import common.block.tech.BlockDropper; -import common.block.tech.BlockEnchantmentTable; -import common.block.tech.BlockFurnace; -import common.block.tech.BlockHopper; -import common.block.tech.BlockJukebox; -import common.block.tech.BlockLever; -import common.block.tech.BlockMobSpawner; -import common.block.tech.BlockNote; -import common.block.tech.BlockNuke; -import common.block.tech.BlockPistonBase; -import common.block.tech.BlockPistonHead; -import common.block.tech.BlockPistonMoving; -import common.block.tech.BlockPressurePlate; -import common.block.tech.BlockPressurePlateWeighted; -import common.block.tech.BlockRail; -import common.block.tech.BlockRailDetector; -import common.block.tech.BlockRailPowered; -import common.block.tech.BlockRedstoneComparator; -import common.block.tech.BlockRedstoneLight; -import common.block.tech.BlockRedstoneRepeater; -import common.block.tech.BlockRedstoneTorch; -import common.block.tech.BlockRedstoneWire; -import common.block.tech.BlockTNT; -import common.block.tech.BlockTianReactor; -import common.block.tech.BlockTorch; -import common.block.tech.BlockTripWire; -import common.block.tech.BlockTripWireHook; -import common.block.tech.BlockWarpChest; -import common.block.tech.BlockWorkbench; -import common.block.tile.BlockBannerHanging; -import common.block.tile.BlockBannerStanding; -import common.block.tile.BlockStandingSign; -import common.block.tile.BlockWallSign; import common.color.DyeColor; import common.init.FluidRegistry.LiquidType; import common.item.CheatTab; +import common.material.Material; import common.util.ObjectIntIdentityMap; import common.util.RegistryNamespacedDefaultedByKey; import common.world.State; @@ -141,17 +18,13 @@ public abstract class BlockRegistry { return REGISTRY.getIDForObject(block); } - public static String getNameFromBlock(Block block) { - return REGISTRY.getNameForObject(block); - } - public static int getStateId(State state) { Block block = state.getBlock(); return getIdFromBlock(block) + (block.getMetaFromState(state) << 12); } public static Block getBlockById(int id) { - return REGISTRY.getObjectById(id); + return (Block)REGISTRY.getObjectById(id); } public static State getStateById(int id) { @@ -160,21 +33,65 @@ public abstract class BlockRegistry { return getBlockById(i).getStateFromMeta(j); } + public static Block getByNameOrId(String name) { + Block block = REGISTRY.getObjectExact(name); + if(block == null) { + try { + return REGISTRY.getObjectExact(Integer.parseInt(name)); + } + catch(NumberFormatException e) { + } + } + return block; + } + + public static Block getByIdFallback(String name) { +// String loc = StringUtils.trimColon(name); + if(REGISTRY.containsKey(name)) { + return REGISTRY.getObject(name); + } + else { + try { + return REGISTRY.getObjectById(Integer.parseInt(name)); + } + catch(NumberFormatException e) { + return null; + } + } + } + + public static String toIdName(State block) { + int meta = block.getBlock().getMetaFromState(block); + return REGISTRY.getNameForObject(block.getBlock()).toString() + + ((meta == block.getBlock().getMetaFromState(block.getBlock().getState())) ? "" : (":" + meta)); + } + public static State getFromIdName(String name, State def) { - if(name == null) + if(name == null) { return def; + } String[] tok = name.split(":"); - if(tok.length < 1 || tok.length > 2) + if(tok.length < 1 || tok.length > 2) { return def; - Block block = REGISTRY.getObjectExact(tok[0]); - if(block == null) + } + Block block = getByNameOrId(tok[0]); +// if(block == null) { +// try { +// block = getBlockById(Integer.parseUnsignedInt(tok[0])); +// } +// catch(NumberFormatException e) { +// } +// } + if(block == null) { return def; + } byte data; if(tok.length == 2) { try { - int i = Integer.parseUnsignedInt(tok[1]); - if(i >= 16) + int i = (byte)Integer.parseUnsignedInt(tok[1]); + if(i >= 16) { return def; + } data = (byte)i; } catch(NumberFormatException e) { @@ -197,7 +114,7 @@ public abstract class BlockRegistry { REGISTRY.validateKey(); for(Block block : REGISTRY) { - if(block != Blocks.air + if(block.getMaterial() != Material.air && ((block instanceof BlockStairs) || /* (block instanceof BlockSlab) || */ (block instanceof BlockSlab) || (block instanceof BlockFarmland) || block.isTranslucent() || block.getLightOpacity() == 0)) { block.setSumBrightness(); @@ -232,19 +149,19 @@ public abstract class BlockRegistry { Block stone = (new BlockStone()).setHardness(1.5F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Stein"); registerBlock(1, "stone", stone); registerBlock(2, "bedrock", (new BlockBedrock()).setHardness(1000.0F).setResistance(100000.0F).setStepSound(SoundType.STONE) - .setDisplay("Grundgestein").setTab(CheatTab.NATURE).setMiningLevel(6)); + .setDisplay("Grundgestein").setTab(CheatTab.tabNature).setMiningLevel(6)); registerBlock(3, "rock", (new BlockRock()).setHardness(2.0F).setResistance(15.0F).setStepSound(SoundType.STONE).setDisplay("Felsen")); registerBlock(4, "hellrock", (new BlockHellRock()).setHardness(0.4F).setStepSound(SoundType.STONE).setDisplay("Höllenstein")); - registerBlock(5, "cell_rock", (new Block(Material.LOOSE)).setHardness(1.0F).setResistance(3.0F) - .setStepSound(SoundType.SLIME).setDisplay("Zellstein").setTab(CheatTab.NATURE)); - registerBlock(6, "moon_rock", (new Block(Material.SOLID)).setHardness(2.5F).setResistance(10.0F) - .setStepSound(SoundType.STONE).setDisplay("Mondgestein").setTab(CheatTab.NATURE)); - Block cobblestone = (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Bruchstein").setTab(CheatTab.NATURE); + registerBlock(5, "cell_rock", (new Block(Material.clay)).setHardness(1.0F).setResistance(3.0F) + .setStepSound(SoundType.SLIME).setDisplay("Zellstein").setTab(CheatTab.tabNature)); + registerBlock(6, "moon_rock", (new Block(Material.rock)).setHardness(2.5F).setResistance(10.0F) + .setStepSound(SoundType.STONE).setDisplay("Mondgestein").setTab(CheatTab.tabNature)); + Block cobblestone = (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Bruchstein").setTab(CheatTab.tabNature); registerBlock(7, "cobblestone", cobblestone); - registerBlock(8, "mossy_cobblestone", (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Bemooster Bruchstein").setTab(CheatTab.NATURE)); + registerBlock(8, "mossy_cobblestone", (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Bemooster Bruchstein").setTab(CheatTab.tabNature)); Block sandstone = (new BlockSandStone()).setStepSound(SoundType.STONE).setHardness(0.8F).setDisplay("Sandstein"); registerBlock(9, "sandstone", sandstone); registerBlock(10, "obsidian", (new BlockObsidian()).setHardness(50.0F).setResistance(2000.0F).setStepSound(SoundType.STONE) @@ -253,16 +170,16 @@ public abstract class BlockRegistry { (new BlockClay()).setHardness(0.6F).setStepSound(SoundType.GRAVEL).setDisplay("Ton").setShovelHarvestable()); registerBlock(12, "hardened_clay", (new BlockHardenedClay()).setHardness(1.25F).setResistance(7.0F).setStepSound(SoundType.STONE).setDisplay("Gebrannter Ton")); - registerBlock(13, "stained_hardened_clay", (new BlockColored(Material.SOLID)).setHardness(1.25F).setResistance(7.0F) - .setStepSound(SoundType.STONE).setDisplay("gefärbter Ton").setTab(CheatTab.NATURE)); - registerBlock(14, "coal_block", (new Block(Material.SOLID)).setHardness(5.0F).setResistance(10.0F) - .setStepSound(SoundType.STONE).setDisplay("Kohleblock").setTab(CheatTab.NATURE)); + registerBlock(13, "stained_hardened_clay", (new BlockColored(Material.rock)).setHardness(1.25F).setResistance(7.0F) + .setStepSound(SoundType.STONE).setDisplay("gefärbter Ton").setTab(CheatTab.tabNature)); + registerBlock(14, "coal_block", (new Block(Material.rock)).setHardness(5.0F).setResistance(10.0F) + .setStepSound(SoundType.STONE).setDisplay("Kohleblock").setTab(CheatTab.tabNature)); registerBlock(15, "sand", (new BlockSand()).setHardness(0.5F).setStepSound(SoundType.SAND).setDisplay("Sand").setShovelHarvestable()); registerBlock(16, "gravel", (new BlockGravel()).setHardness(0.6F).setStepSound(SoundType.GRAVEL).setDisplay("Kies").setShovelHarvestable()); registerBlock(17, "ash", - (new Block(Material.LOOSE)).setHardness(0.2F).setStepSound(SoundType.SAND).setDisplay("Asche") - .setTab(CheatTab.NATURE).setShovelHarvestable()); + (new Block(Material.sand)).setHardness(0.2F).setStepSound(SoundType.SAND).setDisplay("Asche") + .setTab(CheatTab.tabNature).setShovelHarvestable()); registerBlock(18, "snow_layer", (new BlockSnow()).setHardness(0.1F).setStepSound(SoundType.SNOW).setDisplay("Schnee").setLightOpacity(0) .setShovelHarvestable()); registerBlock(19, "snow", @@ -273,11 +190,11 @@ public abstract class BlockRegistry { (new BlockPackedIce()).setHardness(0.5F).setStepSound(SoundType.GLASS).setDisplay("Packeis").setMiningLevel(0)); registerBlock(22, "soul_sand", (new BlockSoulSand()).setHardness(0.5F).setStepSound(SoundType.SAND).setDisplay("Seelensand").setShovelHarvestable()); - registerBlock(23, "glowstone", (new BlockGlowstone(Material.TRANSLUCENT)).setHardness(0.3F).setStepSound(SoundType.GLASS).setLightLevel(1.0F) + registerBlock(23, "glowstone", (new BlockGlowstone(Material.glass)).setHardness(0.3F).setStepSound(SoundType.GLASS).setLightLevel(1.0F) .setDisplay("Glowstone")); registerBlock(24, "blackened_stone", (new BlockBlackenedStone()).setHardness(1.5F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Schwarzstein")); - registerBlock(25, "blackened_cobble", (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Schwarzbruchstein").setTab(CheatTab.NATURE)); + registerBlock(25, "blackened_cobble", (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Schwarzbruchstein").setTab(CheatTab.tabNature)); registerFluid(32, 33, "water", "Wasser", true, LiquidType.WATER, false, 0, 5, 0.0f, "water", "waterflow"); @@ -290,7 +207,6 @@ public abstract class BlockRegistry { registerFluid(46, 47, "goo", "Klebrige Masse", false, LiquidType.COLD, true, 0, 60, 0.0f, 10, 5); registerFluid(48, 49, "nukage", "Radioaktive Masse", false, LiquidType.COLD, true, 10, 10, 4.0f, 2, 2); registerFluid(50, 51, "blood", "Blut", false, LiquidType.COLD, false, 0, 10, 0.0f, 2, 1); - registerFluid(52, 53, "springwater", "Klares Wasser", true, LiquidType.COLD, false, 0, 5, 0.0f, 1, 1); registerBlock(60, "coal_ore", @@ -305,7 +221,7 @@ public abstract class BlockRegistry { .setDisplay("Schwarzes Quarzerz")); registerBlock(68, "redstone_ore", (new BlockRedstoneOre(false)).setHardness(3.0F).setResistance(5.0F).setStepSound(SoundType.STONE) - .setDisplay("Redstone-Erz").setTab(CheatTab.GEMS).setMiningLevel(2)); + .setDisplay("Redstone-Erz").setTab(CheatTab.tabGems).setMiningLevel(2)); registerBlock(69, "lit_redstone_ore", (new BlockRedstoneOre(true)).setLightLevel(0.625F).setHardness(3.0F).setResistance(5.0F) .setStepSound(SoundType.STONE).setDisplay("Redstone-Erz").setMiningLevel(2)); int bid = 70; @@ -331,12 +247,12 @@ public abstract class BlockRegistry { (new BlockGrass()).setHardness(0.6F).setStepSound(SoundType.GRASS).setDisplay("Gras").setShovelHarvestable()); registerBlock(130, "mycelium", (new BlockMycelium()).setHardness(0.6F).setStepSound(SoundType.GRASS).setDisplay("Myzel").setShovelHarvestable()); - registerBlock(131, "tian", (new Block(Material.SOLID)).setHardness(2.0F).setResistance(15.0F).setStepSound(SoundType.STONE) - .setDisplay("Tian").setTab(CheatTab.NATURE)); + registerBlock(131, "tian", (new Block(Material.rock)).setHardness(2.0F).setResistance(15.0F).setStepSound(SoundType.STONE) + .setDisplay("Tian").setTab(CheatTab.tabNature)); registerBlock(132, "tian_soil", (new BlockTianSoil()).setHardness(2.0F).setResistance(15.0F).setStepSound(SoundType.STONE) - .setDisplay("Tianerde").setTab(CheatTab.NATURE)); - registerBlock(133, "moon_cheese", (new BlockTreasure(Material.SOFT)).setHardness(1.5F).setResistance(5.0F) - .setStepSound(SoundType.CLOTH).setDisplay("Mondkäse").setTab(CheatTab.NATURE)); + .setDisplay("Tianerde").setTab(CheatTab.tabNature)); + registerBlock(133, "moon_cheese", (new BlockTreasure(Material.gourd)).setHardness(1.5F).setResistance(5.0F) + .setStepSound(SoundType.CLOTH).setDisplay("Mondkäse").setTab(CheatTab.tabNature)); registerBlock(134, "slime_block", (new BlockSlime()).setDisplay("Schleimblock").setStepSound(SoundType.SLIME)); registerBlock(135, "blackened_dirt", (new BlockBlackenedDirt()).setHardness(0.5F).setStepSound(SoundType.GRAVEL).setDisplay("Schwarzerde").setShovelHarvestable()); @@ -364,12 +280,12 @@ public abstract class BlockRegistry { Block brownMushroom = (new BlockMushroom()).setHardness(0.0F).setStepSound(SoundType.GRASS).setLightLevel(0.125F) .setDisplay("Pilz"); registerBlock(160, "brown_mushroom", brownMushroom); - registerBlock(161, "brown_mushroom_block", (new BlockHugeMushroom(Material.WOOD, brownMushroom)).setHardness(0.2F) - .setStepSound(SoundType.WOOD).setDisplay("Pilzblock").setTab(CheatTab.PLANTS)); + registerBlock(161, "brown_mushroom_block", (new BlockHugeMushroom(Material.wood, brownMushroom)).setHardness(0.2F) + .setStepSound(SoundType.WOOD).setDisplay("Pilzblock").setTab(CheatTab.tabPlants)); Block redMushrooom = (new BlockMushroom()).setHardness(0.0F).setStepSound(SoundType.GRASS).setDisplay("Pilz"); registerBlock(162, "red_mushroom", redMushrooom); - registerBlock(163, "red_mushroom_block", (new BlockHugeMushroom(Material.WOOD, redMushrooom)).setHardness(0.2F) - .setStepSound(SoundType.WOOD).setDisplay("Pilzblock").setTab(CheatTab.PLANTS)); + registerBlock(163, "red_mushroom_block", (new BlockHugeMushroom(Material.wood, redMushrooom)).setHardness(0.2F) + .setStepSound(SoundType.WOOD).setDisplay("Pilzblock").setTab(CheatTab.tabPlants)); registerBlock(164, "blue_mushroom", (new BlockBlueShroom()).setHardness(0.0F).setStepSound(SoundType.GRASS).setLightLevel(0.5F) .setDisplay("Tianpilz")); @@ -390,35 +306,31 @@ public abstract class BlockRegistry { .setDisplay(wood.getDisplay() + "setzling")); } - registerBlock(252, "soul_fire", - (new BlockSoulFire()).setHardness(0.0F).setLightLevel(1.0F).setStepSound(SoundType.CLOTH).setDisplay("Feuer der Seelen")); - registerBlock(253, "black_fire", - (new BlockTintedFire(0x202020)).setHardness(0.0F).setLightLevel(1.0F).setStepSound(SoundType.CLOTH).setDisplay("Dunkles Feuer")); registerBlock(254, "web", (new BlockWeb()).setLightOpacity(1).setHardness(4.0F).setDisplay("Spinnennetz")); registerBlock(255, "fire", (new BlockFire()).setHardness(0.0F).setLightLevel(1.0F).setStepSound(SoundType.CLOTH).setDisplay("Feuer")); - registerBlock(256, "lapis_block", (new Block(Material.SOLID)).setHardness(3.0F).setResistance(5.0F) - .setStepSound(SoundType.STONE).setDisplay("Lapislazuliblock").setTab(CheatTab.GEMS).setMiningLevel(1)); - registerBlock(257, "emerald_block", (new Block(Material.SOLID)).setHardness(5.0F).setResistance(10.0F) - .setStepSound(SoundType.STONE).setDisplay("Smaragdblock").setTab(CheatTab.GEMS).setMiningLevel(2)); - registerBlock(258, "redstone_block", (new BlockCompressedPowered(Material.SOLID)).setHardness(5.0F).setResistance(10.0F) - .setStepSound(SoundType.STONE).setDisplay("Redstone-Block").setTab(CheatTab.TECHNOLOGY)); + registerBlock(256, "lapis_block", (new Block(Material.iron)).setHardness(3.0F).setResistance(5.0F) + .setStepSound(SoundType.STONE).setDisplay("Lapislazuliblock").setTab(CheatTab.tabGems).setMiningLevel(1)); + registerBlock(257, "emerald_block", (new Block(Material.iron)).setHardness(5.0F).setResistance(10.0F) + .setStepSound(SoundType.STONE).setDisplay("Smaragdblock").setTab(CheatTab.tabGems).setMiningLevel(2)); + registerBlock(258, "redstone_block", (new BlockCompressedPowered(Material.iron)).setHardness(5.0F).setResistance(10.0F) + .setStepSound(SoundType.STONE).setDisplay("Redstone-Block").setTab(CheatTab.tabTech)); registerBlock(270, "glass", - (new BlockGlass()).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("Glas")); + (new BlockGlass(Material.glass, false)).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("Glas")); registerBlock(271, "stained_glass", - (new BlockStainedGlass()).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("gefärbtes Glas")); + (new BlockStainedGlass(Material.glass)).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("gefärbtes Glas")); registerBlock(272, "glass_pane", - (new BlockPane(Material.TRANSLUCENT, false)).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("Glasscheibe")); + (new BlockPane(Material.glass, false)).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("Glasscheibe")); registerBlock(273, "stained_glass_pane", (new BlockStainedGlassPane()).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("gefärbte Glasscheibe")); - registerBlock(280, "wool", (new BlockColored(Material.BURNABLE)).setHardness(0.8F).setStepSound(SoundType.CLOTH).setDisplay("Wolle") + registerBlock(280, "wool", (new BlockColored(Material.cloth)).setHardness(0.8F).setStepSound(SoundType.CLOTH).setDisplay("Wolle") .setShearsEfficiency(1)); registerBlock(281, "carpet", (new BlockCarpet()).setHardness(0.1F).setStepSound(SoundType.CLOTH).setDisplay("Teppich").setLightOpacity(0)); @@ -431,37 +343,37 @@ public abstract class BlockRegistry { (new BlockLadder()).setHardness(0.4F).setStepSound(SoundType.LADDER).setDisplay("Leiter").setAxeHarvestable()); registerBlock(301, "torch", (new BlockTorch()).setHardness(0.0F).setLightLevel(0.9375F).setStepSound(SoundType.WOOD).setDisplay("Fackel")); - registerBlock(302, "lamp", (new Block(Material.TRANSLUCENT)).setHardness(0.3F).setStepSound(SoundType.GLASS).setLightLevel(1.0F) - .setDisplay("Lampe").setTab(CheatTab.TECHNOLOGY)); + registerBlock(302, "lamp", (new Block(Material.glass)).setHardness(0.3F).setStepSound(SoundType.GLASS).setLightLevel(1.0F) + .setDisplay("Lampe").setTab(CheatTab.tabTech)); registerBlock(304, "bookshelf", (new BlockBookshelf()).setHardness(1.5F).setStepSound(SoundType.WOOD).setDisplay("Bücherregal")); registerBlock(305, "cake", (new BlockCake()).setHardness(0.5F).setStepSound(SoundType.CLOTH).setDisplay("Kuchen")); registerBlock(306, "dragon_egg", (new BlockDragonEgg()).setHardness(3.0F).setResistance(15.0F).setStepSound(SoundType.STONE) - .setLightLevel(0.125F).setDisplay("Drachenei").setTab(CheatTab.DECORATION)); + .setLightLevel(0.125F).setDisplay("Drachenei").setTab(CheatTab.tabDeco)); registerBlock(307, "flower_pot", (new BlockFlowerPot()).setHardness(0.0F).setStepSound(SoundType.STONE).setDisplay("Blumentopf")); - registerBlock(308, "sponge", (new Block(Material.LOOSE)).setHardness(0.6F).setStepSound(SoundType.GRASS).setDisplay("Schwamm") - .setTab(CheatTab.DECORATION)); - registerBlock(309, "skull", (new BlockSkull()).setHardness(1.0F).setStepSound(SoundType.STONE).setDisplay("Schädel").setTab(CheatTab.DECORATION)); + registerBlock(308, "sponge", (new Block(Material.sponge)).setHardness(0.6F).setStepSound(SoundType.GRASS).setDisplay("Schwamm") + .setTab(CheatTab.tabDeco)); + registerBlock(309, "skull", (new BlockSkull()).setHardness(1.0F).setStepSound(SoundType.STONE).setDisplay("Kopf")); registerBlock(310, "lit_pumpkin", (new BlockPumpkin()).setHardness(1.0F).setStepSound(SoundType.WOOD).setLightLevel(1.0F).setDisplay("Kürbislaterne")); registerBlock(311, "hay_block", (new BlockHay()).setHardness(0.5F).setStepSound(SoundType.GRASS).setDisplay("Strohballen") - .setTab(CheatTab.DECORATION)); + .setTab(CheatTab.tabDeco)); registerBlock(312, "sign", (new BlockStandingSign()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Schild")); registerBlock(313, "wall_sign", (new BlockWallSign()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Schild")); registerBlock(314, "banner", - (new BlockBannerStanding()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Banner")); + (new BlockBanner.BlockBannerStanding()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Banner")); registerBlock(315, "wall_banner", - (new BlockBannerHanging()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Banner")); + (new BlockBanner.BlockBannerHanging()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Banner")); registerBlock(390, "portal", (new BlockPortal()).setHardness(0.0F).setStepSound(SoundType.GLASS).setLightLevel(0.75F).setDisplay("Portal")); - registerBlock(391, "floor_portal", (new BlockFloorPortal(Material.PORTAL)).setHardness(0.0F).setDisplay("Portal")); + registerBlock(391, "floor_portal", (new BlockFloorPortal(Material.portal)).setHardness(0.0F).setDisplay("Portal")); registerBlock(392, "portal_frame", (new BlockPortalFrame()).setStepSound(SoundType.GLASS).setLightLevel(0.125F).setHardness(5.0F) - .setDisplay("Portalrahmen").setResistance(2000.0F).setTab(CheatTab.TECHNOLOGY)); + .setDisplay("Portalrahmen").setResistance(2000.0F).setTab(CheatTab.tabTech)); registerBlock(400, "farmland", (new BlockFarmland()).setHardness(0.6F).setStepSound(SoundType.GRAVEL).setDisplay("Ackerboden") - .setShovelHarvestable().setTab(CheatTab.PLANTS)); + .setShovelHarvestable().setTab(CheatTab.tabPlants)); registerBlock(401, "wheat", (new BlockCrops()).setDisplay("Getreide")); registerBlock(402, "carrot", (new BlockCarrot()).setDisplay("Karotten")); registerBlock(403, "potato", (new BlockPotato()).setDisplay("Kartoffeln")); @@ -474,16 +386,16 @@ public abstract class BlockRegistry { for(MetalType metal : MetalType.values()) { // String loc = metal.name.substring(0, 1).toUpperCase() + metal.name.substring(1); registerBlock(bid++, metal.name + "_block", - (new Block(Material.SOLID)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay(metal.display + "block").setTab(CheatTab.GEMS).setMiningLevel(1) + (new Block(Material.iron)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay(metal.display + "block").setTab(CheatTab.tabGems).setMiningLevel(1) .setLightLevel(metal.radioactivity > 0.0F ? 0.25F : 0.0F).setRadiation(metal.radioactivity * 2.0f)); } bid = 540; for(OreType ore : OreType.values()) { // String loc = ore.name.substring(0, 1).toUpperCase() + ore.name.substring(1); registerBlock(bid++, ore.name + "_block", - (new Block(Material.SOLID)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay(ore.display + "block").setTab(CheatTab.GEMS) + (new Block(Material.iron)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay(ore.display + "block").setTab(CheatTab.tabGems) .setMiningLevel(ore.material.getHarvestLevel() - 1)); } @@ -493,18 +405,18 @@ public abstract class BlockRegistry { registerBlock(600, "stone_slab", - (new BlockSlab(Material.SOLID, "stone_slab_side", "double_stone_top", "double_stone_top")) + (new BlockSlab(Material.rock, "stone_slab_side", "double_stone_top", "double_stone_top")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Steinstufe")); registerBlock(601, "stone_stairs", (new BlockStairs(stone.getState())).setDisplay("Steintreppe")); registerBlock(610, "cobblestone_slab", - (new BlockSlab(Material.SOLID, "cobblestone")) + (new BlockSlab(Material.rock, "cobblestone")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Bruchsteinstufe")); registerBlock(611, "cobblestone_stairs", (new BlockStairs(cobblestone.getState())).setDisplay("Bruchsteintreppe")); registerBlock(612, "cobblestone_wall", (new BlockWall(cobblestone)).setDisplay("Bruchsteinmauer")); registerBlock(620, "sandstone_slab", - (new BlockSlab(Material.SOLID, "sandstone_normal", "sandstone_bottom", "sandstone_all")) + (new BlockSlab(Material.rock, "sandstone_normal", "sandstone_bottom", "sandstone_all")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Sandsteinstufe")); registerBlock(621, "sandstone_stairs", (new BlockStairs(sandstone.getState().withProperty(BlockSandStone.TYPE, BlockSandStone.EnumType.DEFAULT), @@ -514,25 +426,25 @@ public abstract class BlockRegistry { Block quartz = (new BlockQuartz("")).setStepSound(SoundType.STONE).setHardness(0.8F).setDisplay("Quarzblock"); registerBlock(630, "quartz_block", quartz); registerBlock(631, "quartz_slab", - (new BlockSlab(Material.SOLID, "quartz_block_side", "quartz_block_bottom", "quartz_top")) + (new BlockSlab(Material.rock, "quartz_block_side", "quartz_block_bottom", "quartz_top")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Quarzstufe")); registerBlock(632, "quartz_stairs", (new BlockStairs(quartz.getState().withProperty(BlockQuartz.VARIANT, BlockQuartz.EnumType.DEFAULT), "quartz_block_bottom", "quartz_top")) .setDisplay("Quarztreppe")); - registerBlock(640, "iron_bars", (new BlockPane(Material.SOLID, true)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + registerBlock(640, "iron_bars", (new BlockPane(Material.iron, true)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) .setDisplay("Eisengitter")); registerBlock(641, "iron_door", - (new BlockDoor(Material.SOLID)).setHardness(5.0F).setStepSound(SoundType.STONE).setDisplay("Eisentür")); + (new BlockDoor(Material.iron)).setHardness(5.0F).setStepSound(SoundType.STONE).setDisplay("Eisentür")); registerBlock(642, "iron_trapdoor", - (new BlockTrapDoor(Material.SOLID)).setHardness(5.0F).setStepSound(SoundType.STONE).setDisplay("Eisenfalltür")); + (new BlockTrapDoor(Material.iron)).setHardness(5.0F).setStepSound(SoundType.STONE).setDisplay("Eisenfalltür")); - Block brick = (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Ziegelsteine").setTab(CheatTab.BLOCKS); + Block brick = (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Ziegelsteine").setTab(CheatTab.tabBlocks); registerBlock(650, "brick_block", brick); registerBlock(651, "brick_slab", - (new BlockSlab(Material.SOLID, "brick_block")) + (new BlockSlab(Material.rock, "brick_block")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Ziegelstufe")); registerBlock(652, "brick_stairs", (new BlockStairs(brick.getState())).setDisplay("Ziegeltreppe")); @@ -540,38 +452,38 @@ public abstract class BlockRegistry { .setDisplay("Steinziegel"); registerBlock(660, "stonebrick", stonebrick); registerBlock(661, "stonebrick_slab", - (new BlockSlab(Material.SOLID, "stonebrick_default")) + (new BlockSlab(Material.rock, "stonebrick_default")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Steinziegelstufe")); registerBlock(662, "stonebrick_stairs", (new BlockStairs(stonebrick.getState().withProperty(BlockStoneBrick.VARIANT, BlockStoneBrick.EnumType.DEFAULT))) .setDisplay("Steinziegeltreppe")); - Block bloodBrick = (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Blutrote Ziegel").setTab(CheatTab.BLOCKS); + Block bloodBrick = (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Blutrote Ziegel").setTab(CheatTab.tabBlocks); registerBlock(670, "blood_brick", bloodBrick); registerBlock(671, "blood_brick_slab", - (new BlockSlab(Material.SOLID, "blood_brick")) + (new BlockSlab(Material.rock, "blood_brick")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Blutrote Ziegelstufe")); - registerBlock(672, "blood_brick_fence", (new BlockFence(Material.SOLID, "blood_brick")).setHardness(2.0F).setResistance(10.0F) + registerBlock(672, "blood_brick_fence", (new BlockFence(Material.rock, "blood_brick")).setHardness(2.0F).setResistance(10.0F) .setStepSound(SoundType.STONE).setDisplay("Blutroter Ziegelzaun")); registerBlock(673, "blood_brick_stairs", (new BlockStairs(bloodBrick.getState())).setDisplay("Blutrote Ziegeltreppe")); - Block blackBrick = (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Schwarze Ziegel").setTab(CheatTab.BLOCKS); + Block blackBrick = (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Schwarze Ziegel").setTab(CheatTab.tabBlocks); registerBlock(680, "black_brick", blackBrick); registerBlock(681, "black_brick_slab", - (new BlockSlab(Material.SOLID, "black_brick")) + (new BlockSlab(Material.rock, "black_brick")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Schwarze Ziegelstufe")); registerBlock(682, "black_brick_stairs", (new BlockStairs(blackBrick.getState())).setDisplay("Schwarze Ziegeltreppe")); - registerBlock(683, "black_brick_fence", (new BlockFence(Material.SOLID, "black_brick")).setHardness(2.0F).setResistance(10.0F) + registerBlock(683, "black_brick_fence", (new BlockFence(Material.rock, "black_brick")).setHardness(2.0F).setResistance(10.0F) .setStepSound(SoundType.STONE).setDisplay("Schwarzer Ziegelzaun")); Block bquartz = (new BlockQuartz("black_")).setStepSound(SoundType.STONE).setHardness(0.8F).setDisplay("Schwarzer Quarzblock"); registerBlock(690, "black_quartz_block", bquartz); registerBlock(691, "black_quartz_slab", - (new BlockSlab(Material.SOLID, "black_quartz_block_side", "black_quartz_block_bottom", "black_quartz_top")) + (new BlockSlab(Material.rock, "black_quartz_block_side", "black_quartz_block_bottom", "black_quartz_top")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Schwarze Quarzstufe")); registerBlock(692, "black_quartz_stairs", (new BlockStairs(bquartz.getState().withProperty(BlockQuartz.VARIANT, BlockQuartz.EnumType.DEFAULT), @@ -580,29 +492,29 @@ public abstract class BlockRegistry { bid = 700; for(DecoType deco : DecoType.values()) { - registerBlock(bid++, deco.name, (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F) - .setStepSound(SoundType.STONE).setDisplay(deco.display).setTab(CheatTab.BLOCKS)); + registerBlock(bid++, deco.name, (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F) + .setStepSound(SoundType.STONE).setDisplay(deco.display).setTab(CheatTab.tabBlocks)); } registerBlock(1000, "trapdoor", - (new BlockTrapDoor(Material.WOOD)).setHardness(3.0F).setStepSound(SoundType.WOOD).setDisplay("Holzfalltür")); + (new BlockTrapDoor(Material.wood)).setHardness(3.0F).setStepSound(SoundType.WOOD).setDisplay("Holzfalltür")); bid = 1100; for(WoodType wood : WoodType.values()) { - Block planks = (new Block(Material.WOOD)).setHardness(2.0F).setResistance(5.0F).setStepSound(SoundType.WOOD) - .setDisplay(wood.getDisplay() + "holzbretter").setTab(CheatTab.WOOD); + Block planks = (new Block(Material.wood)).setHardness(2.0F).setResistance(5.0F).setStepSound(SoundType.WOOD) + .setDisplay(wood.getDisplay() + "holzbretter").setTab(CheatTab.tabWood); registerBlock(bid++, wood.getName() + "_planks", planks); registerBlock(bid++, wood.getName() + "_stairs", (new BlockStairs(planks.getState())) .setDisplay(wood.getDisplay() + "holztreppe")); - registerBlock(bid++, wood.getName() + "_slab", (new BlockSlab(Material.WOOD, wood.getName() + "_planks")) + registerBlock(bid++, wood.getName() + "_slab", (new BlockSlab(Material.wood, wood.getName() + "_planks")) .setHardness(2.0F).setResistance(5.0F).setStepSound(SoundType.WOOD).setDisplay(wood.getDisplay() + "holzstufe")); - registerBlock(bid++, wood.getName() + "_fence", (new BlockFence(Material.WOOD, wood.getName() + "_planks")) + registerBlock(bid++, wood.getName() + "_fence", (new BlockFence(Material.wood, wood.getName() + "_planks")) .setHardness(2.0F).setResistance(5.0F).setStepSound(SoundType.WOOD).setDisplay(wood.getDisplay() + "holzzaun")); registerBlock(bid++, wood.getName() + "_fence_gate", (new BlockFenceGate(wood)).setHardness(2.0F).setResistance(5.0F) .setStepSound(SoundType.WOOD).setDisplay(wood.getDisplay() + "holzzauntor")); - registerBlock(bid++, wood.getName() + "_door", (new BlockDoor(Material.WOOD)).setHardness(3.0F).setStepSound(SoundType.WOOD) + registerBlock(bid++, wood.getName() + "_door", (new BlockDoor(Material.wood)).setHardness(3.0F).setStepSound(SoundType.WOOD) .setDisplay(wood.getDisplay() + "holztür")); } @@ -610,12 +522,12 @@ public abstract class BlockRegistry { registerBlock(2000, "core", new BlockCore().setHardness(1.5F).setResistance(10.0F).setStepSound(SoundType.STONE) .setDisplay("Chunk-Lade-Kern")); registerBlock(2001, "mob_spawner", - (new BlockMobSpawner()).setHardness(3.0F).setResistance(8.0F).setStepSound(SoundType.STONE).setDisplay("Mob-Spawner")); - registerBlock(2002, "workbench", (new BlockWorkbench(3)).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Werkbank")); + (new BlockMobSpawner()).setHardness(5.0F).setStepSound(SoundType.STONE).setDisplay("Monsterspawner")); + registerBlock(2002, "crafting_table", (new BlockWorkbench()).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Werkbank")); registerBlock(2003, "furnace", (new BlockFurnace(false)).setHardness(3.5F).setStepSound(SoundType.STONE).setDisplay("Ofen") - .setTab(CheatTab.TECHNOLOGY)); + .setTab(CheatTab.tabTech)); registerBlock(2004, "lit_furnace", (new BlockFurnace(true)).setHardness(3.5F).setStepSound(SoundType.STONE).setLightLevel(0.875F) - .setDisplay("Ofen (Gefeuert)").setTab(CheatTab.TECHNOLOGY)); + .setDisplay("Ofen (Gefeuert)").setTab(CheatTab.tabTech)); registerBlock(2005, "anvil", (new BlockAnvil()).setHardness(5.0F).setStepSound(SoundType.ANVIL).setResistance(2000.0F).setDisplay("Amboss")); registerBlock(2006, "enchanting_table", @@ -626,8 +538,6 @@ public abstract class BlockRegistry { registerBlock(2010, "noteblock", (new BlockNote()).setHardness(0.8F).setDisplay("Notenblock")); registerBlock(2011, "jukebox", (new BlockJukebox()).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Plattenspieler")); - registerBlock(2012, "construction_table", (new BlockWorkbench(4)).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Konstruktionstisch")); - registerBlock(2013, "assembly_unit", (new BlockWorkbench(5)).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Fertigungseinheit")); registerBlock(2100, "chest", (new BlockChest(0)).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Truhe")); registerBlock(2101, "trapped_chest", (new BlockChest(1)).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Redstonetruhe")); @@ -658,13 +568,13 @@ public abstract class BlockRegistry { registerBlock(2500, "lever", (new BlockLever()).setHardness(0.5F).setStepSound(SoundType.WOOD).setDisplay("Hebel")); - registerBlock(2510, "stone_pressure_plate", (new BlockPressurePlate(Material.SOLID, BlockPressurePlate.Sensitivity.MOBS)).setHardness(0.5F) + registerBlock(2510, "stone_pressure_plate", (new BlockPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.MOBS)).setHardness(0.5F) .setStepSound(SoundType.STONE).setDisplay("Steindruckplatte")); - registerBlock(2511, "wooden_pressure_plate", (new BlockPressurePlate(Material.WOOD, BlockPressurePlate.Sensitivity.EVERYTHING)) + registerBlock(2511, "wooden_pressure_plate", (new BlockPressurePlate(Material.wood, BlockPressurePlate.Sensitivity.EVERYTHING)) .setHardness(0.5F).setStepSound(SoundType.WOOD).setDisplay("Holzdruckplatte")); - registerBlock(2512, "light_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.SOLID, 15)).setHardness(0.5F) + registerBlock(2512, "light_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.iron, 15)).setHardness(0.5F) .setStepSound(SoundType.WOOD).setDisplay("Wägeplatte (niedrige Gewichte)")); - registerBlock(2513, "heavy_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.SOLID, 150)).setHardness(0.5F) + registerBlock(2513, "heavy_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.iron, 150)).setHardness(0.5F) .setStepSound(SoundType.WOOD).setDisplay("Wägeplatte (hohe Gewichte)")); registerBlock(2520, "stone_button", (new BlockButton(false, 20, "stone")).setHardness(0.5F).setStepSound(SoundType.STONE).setDisplay("Knopf")); @@ -676,7 +586,7 @@ public abstract class BlockRegistry { registerBlock(2601, "unlit_redstone_torch", (new BlockRedstoneTorch(false)).setHardness(0.0F).setStepSound(SoundType.WOOD).setDisplay("Redstone-Fackel")); registerBlock(2602, "redstone_torch", (new BlockRedstoneTorch(true)).setHardness(0.0F).setLightLevel(0.5F).setStepSound(SoundType.WOOD) - .setDisplay("Redstone-Fackel").setTab(CheatTab.TECHNOLOGY)); + .setDisplay("Redstone-Fackel").setTab(CheatTab.tabTech)); registerBlock(2603, "repeater", (new BlockRedstoneRepeater(false)).setHardness(0.0F).setStepSound(SoundType.WOOD).setDisplay("Redstone-Verstärker")); registerBlock(2604, "powered_repeater", @@ -686,7 +596,7 @@ public abstract class BlockRegistry { registerBlock(2606, "powered_comparator", (new BlockRedstoneComparator(true)).setHardness(0.0F).setLightLevel(0.625F) .setStepSound(SoundType.WOOD).setDisplay("Redstone-Komparator")); registerBlock(2607, "redstone_lamp", (new BlockRedstoneLight(false)).setHardness(0.3F).setStepSound(SoundType.GLASS) - .setDisplay("Redstone-Lampe").setTab(CheatTab.TECHNOLOGY)); + .setDisplay("Redstone-Lampe").setTab(CheatTab.tabTech)); registerBlock(2608, "lit_redstone_lamp", (new BlockRedstoneLight(true)).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("Redstone-Lampe")); registerBlock(2609, "daylight_detector", new BlockDaylightDetector(false).setDisplay("Tageslichtsensor")); diff --git a/common/src/common/init/Blocks.java b/common/src/common/init/Blocks.java new file mode 100755 index 0000000..eb86097 --- /dev/null +++ b/common/src/common/init/Blocks.java @@ -0,0 +1,360 @@ +package common.init; + +import common.block.Block; +import common.block.BlockBeacon; +import common.block.BlockBed; +import common.block.BlockBlackenedSoil; +import common.block.BlockBush; +import common.block.BlockCactus; +import common.block.BlockCauldron; +import common.block.BlockChest; +import common.block.BlockDaylightDetector; +import common.block.BlockDeadBush; +import common.block.BlockDoublePlant; +import common.block.BlockDryLeaves; +import common.block.BlockDynamicLiquid; +import common.block.BlockFire; +import common.block.BlockFlower; +import common.block.BlockGrass; +import common.block.BlockHopper; +import common.block.BlockLeaves; +import common.block.BlockMycelium; +import common.block.BlockOre; +import common.block.BlockPistonBase; +import common.block.BlockPistonHead; +import common.block.BlockPistonMoving; +import common.block.BlockPortal; +import common.block.BlockRedstoneComparator; +import common.block.BlockRedstoneRepeater; +import common.block.BlockRedstoneWire; +import common.block.BlockReed; +import common.block.BlockSand; +import common.block.BlockSkull; +import common.block.BlockSlab; +import common.block.BlockStainedGlass; +import common.block.BlockStainedGlassPane; +import common.block.BlockStaticLiquid; +import common.block.BlockTallGrass; +import common.block.BlockTianReactor; +import common.block.BlockTripWireHook; + + +public abstract class Blocks { + public static final Block air = get("air"); + public static final Block stone = get("stone"); + public static final Block blackened_stone = get("blackened_stone"); + public static final BlockGrass grass = (BlockGrass)get("grass"); + public static final BlockBlackenedSoil blackened_soil = (BlockBlackenedSoil)get("blackened_soil"); + public static final Block dirt = get("dirt"); + public static final Block blackened_dirt = get("blackened_dirt"); + public static final Block cobblestone = get("cobblestone"); + public static final Block blackened_cobble = get("blackened_cobble"); + public static final Block oak_planks = get("oak_planks"); + public static final Block spruce_planks = get("spruce_planks"); + public static final Block birch_planks = get("birch_planks"); + public static final Block maple_planks = get("maple_planks"); + public static final Block jungle_planks = get("jungle_planks"); + public static final Block acacia_planks = get("acacia_planks"); + public static final Block dark_oak_planks = get("dark_oak_planks"); + public static final Block cherry_planks = get("cherry_planks"); + public static final Block oak_sapling = get("oak_sapling"); + public static final Block spruce_sapling = get("spruce_sapling"); + public static final Block birch_sapling = get("birch_sapling"); + public static final Block jungle_sapling = get("jungle_sapling"); + public static final Block acacia_sapling = get("acacia_sapling"); + public static final Block dark_oak_sapling = get("dark_oak_sapling"); + public static final Block cherry_sapling = get("cherry_sapling"); + public static final Block maple_sapling = get("maple_sapling"); + public static final Block bedrock = get("bedrock"); + public static final BlockDynamicLiquid flowing_water = (BlockDynamicLiquid)get("flowing_water"); + public static final BlockStaticLiquid water = (BlockStaticLiquid)get("water"); + public static final BlockDynamicLiquid flowing_lava = (BlockDynamicLiquid)get("flowing_lava"); + public static final BlockStaticLiquid lava = (BlockStaticLiquid)get("lava"); + public static final BlockDynamicLiquid flowing_goo = (BlockDynamicLiquid)get("flowing_goo"); + public static final BlockStaticLiquid goo = (BlockStaticLiquid)get("goo"); + public static final BlockSand sand = (BlockSand)get("sand"); + public static final Block gravel = get("gravel"); + public static final BlockOre gold_ore = (BlockOre)get("gold_ore"); + public static final BlockOre iron_ore = (BlockOre)get("iron_ore"); + public static final BlockOre coal_ore = (BlockOre)get("coal_ore"); + public static final BlockOre lead_ore = (BlockOre)get("lead_ore"); + public static final BlockOre copper_ore = (BlockOre)get("copper_ore"); + public static final Block oak_log = get("oak_log"); + public static final Block spruce_log = get("spruce_log"); + public static final Block birch_log = get("birch_log"); + public static final Block jungle_log = get("jungle_log"); + public static final Block acacia_log = get("acacia_log"); + public static final Block dark_oak_log = get("dark_oak_log"); + public static final Block cherry_log = get("cherry_log"); + public static final Block maple_log = get("maple_log"); + public static final Block tian_log = get("tian_log"); + public static final Block blackwood_log = get("blackwood_log"); + public static final Block oak_slab = get("oak_slab"); + public static final Block spruce_slab = get("spruce_slab"); + public static final Block birch_slab = get("birch_slab"); + public static final Block jungle_slab = get("jungle_slab"); + public static final Block acacia_slab = get("acacia_slab"); + public static final Block dark_oak_slab = get("dark_oak_slab"); + public static final Block cherry_slab = get("cherry_slab"); + public static final Block maple_slab = get("maple_slab"); + public static final Block cobblestone_slab = get("cobblestone_slab"); + public static final Block brick_slab = get("brick_slab"); + public static final Block blood_brick_slab = get("blood_brick_slab"); + public static final Block quartz_slab = get("quartz_slab"); + public static final BlockDryLeaves dry_leaves = (BlockDryLeaves)get("dry_leaves"); + public static final Block sponge = get("sponge"); + public static final Block glass = get("glass"); + public static final BlockOre lapis_ore = (BlockOre)get("lapis_ore"); + public static final Block lapis_block = get("lapis_block"); + public static final Block dispenser = get("dispenser"); + public static final Block sandstone = get("sandstone"); + public static final Block noteblock = get("noteblock"); + public static final BlockBed red_bed = (BlockBed)get("red_bed"); + public static final Block golden_rail = get("golden_rail"); + public static final Block detector_rail = get("detector_rail"); + public static final BlockPistonBase sticky_piston = (BlockPistonBase)get("sticky_piston"); + public static final Block web = get("web"); + public static final BlockTallGrass tallgrass = (BlockTallGrass)get("tallgrass"); + public static final BlockDeadBush deadbush = (BlockDeadBush)get("deadbush"); + public static final BlockPistonBase piston = (BlockPistonBase)get("piston"); + public static final BlockPistonHead piston_head = (BlockPistonHead)get("piston_head"); + public static final Block wool = get("wool"); + public static final BlockPistonMoving piston_extension = (BlockPistonMoving)get("piston_extension"); + public static final BlockFlower flower = (BlockFlower)get("flower"); + public static final BlockBush brown_mushroom = (BlockBush)get("brown_mushroom"); + public static final BlockBush red_mushroom = (BlockBush)get("red_mushroom"); + public static final Block gold_block = get("gold_block"); + public static final Block iron_block = get("iron_block"); +// public static final BlockSlab double_stone_slab = get("double_stone_slab"); +// public static final BlockSlab stone_slab = get("stone_slab"); + public static final Block brick_block = get("brick_block"); + public static final Block tnt = get("tnt"); + public static final Block bookshelf = get("bookshelf"); + public static final Block mossy_cobblestone = get("mossy_cobblestone"); + public static final Block obsidian = get("obsidian"); + public static final Block torch = get("torch"); + public static final BlockFire fire = (BlockFire)get("fire"); + public static final Block mob_spawner = get("mob_spawner"); + public static final Block oak_stairs = get("oak_stairs"); + public static final BlockChest chest = (BlockChest)get("chest"); + public static final BlockRedstoneWire redstone = (BlockRedstoneWire)get("redstone"); + public static final BlockOre diamond_ore = (BlockOre)get("diamond_ore"); + public static final Block diamond_block = get("diamond_block"); + public static final Block crafting_table = get("crafting_table"); + public static final Block wheat = get("wheat"); + public static final Block farmland = get("farmland"); + public static final Block furnace = get("furnace"); + public static final Block lit_furnace = get("lit_furnace"); + public static final Block sign = get("sign"); + public static final Block oak_door = get("oak_door"); + public static final Block spruce_door = get("spruce_door"); + public static final Block birch_door = get("birch_door"); + public static final Block jungle_door = get("jungle_door"); + public static final Block acacia_door = get("acacia_door"); + public static final Block dark_oak_door = get("dark_oak_door"); + public static final Block ladder = get("ladder"); + public static final Block rail = get("rail"); + public static final Block cobblestone_stairs = get("cobblestone_stairs"); + public static final Block wall_sign = get("wall_sign"); + public static final Block lever = get("lever"); + public static final Block stone_pressure_plate = get("stone_pressure_plate"); + public static final Block iron_door = get("iron_door"); + public static final Block wooden_pressure_plate = get("wooden_pressure_plate"); + public static final Block redstone_ore = get("redstone_ore"); + public static final Block lit_redstone_ore = get("lit_redstone_ore"); + public static final Block unlit_redstone_torch = get("unlit_redstone_torch"); + public static final Block redstone_torch = get("redstone_torch"); + public static final Block stone_button = get("stone_button"); + public static final Block snow_layer = get("snow_layer"); + public static final Block ice = get("ice"); + public static final Block snow = get("snow"); + public static final BlockCactus cactus = (BlockCactus)get("cactus"); + public static final Block clay = get("clay"); + public static final BlockReed reeds = (BlockReed)get("reeds"); + public static final Block jukebox = get("jukebox"); + public static final Block oak_fence = get("oak_fence"); + public static final Block spruce_fence = get("spruce_fence"); + public static final Block birch_fence = get("birch_fence"); + public static final Block jungle_fence = get("jungle_fence"); + public static final Block dark_oak_fence = get("dark_oak_fence"); + public static final Block acacia_fence = get("acacia_fence"); + public static final Block pumpkin = get("pumpkin"); + public static final Block hellrock = get("hellrock"); + public static final Block soul_sand = get("soul_sand"); + public static final Block glowstone = get("glowstone"); + public static final BlockPortal portal = (BlockPortal)get("portal"); + public static final Block lit_pumpkin = get("lit_pumpkin"); + public static final Block cake = get("cake"); + public static final BlockRedstoneRepeater repeater = (BlockRedstoneRepeater)get("repeater"); + public static final BlockRedstoneRepeater powered_repeater = (BlockRedstoneRepeater)get("powered_repeater"); + public static final Block trapdoor = get("trapdoor"); + public static final Block stonebrick = get("stonebrick"); + public static final Block brown_mushroom_block = get("brown_mushroom_block"); + public static final Block red_mushroom_block = get("red_mushroom_block"); + public static final Block iron_bars = get("iron_bars"); + public static final Block glass_pane = get("glass_pane"); + public static final Block melon_block = get("melon_block"); + public static final Block pumpkin_stem = get("pumpkin_stem"); + public static final Block melon_stem = get("melon_stem"); + public static final Block vine = get("vine"); + public static final Block oak_fence_gate = get("oak_fence_gate"); + public static final Block spruce_fence_gate = get("spruce_fence_gate"); + public static final Block birch_fence_gate = get("birch_fence_gate"); + public static final Block jungle_fence_gate = get("jungle_fence_gate"); + public static final Block dark_oak_fence_gate = get("dark_oak_fence_gate"); + public static final Block acacia_fence_gate = get("acacia_fence_gate"); + public static final Block brick_stairs = get("brick_stairs"); + public static final Block stonebrick_stairs = get("stonebrick_stairs"); + public static final BlockMycelium mycelium = (BlockMycelium)get("mycelium"); + public static final Block waterlily = get("waterlily"); + public static final Block blood_brick = get("blood_brick"); + public static final Block blood_brick_fence = get("blood_brick_fence"); + public static final Block blood_brick_stairs = get("blood_brick_stairs"); + public static final Block black_brick = get("black_brick"); + public static final Block black_brick_fence = get("black_brick_fence"); + public static final Block black_brick_stairs = get("black_brick_stairs"); + public static final Block soul_wart = get("soul_wart"); + public static final Block enchanting_table = get("enchanting_table"); + public static final Block brewing_stand = get("brewing_stand"); + public static final BlockCauldron cauldron = (BlockCauldron)get("cauldron"); + public static final Block floor_portal = get("floor_portal"); + public static final Block portal_frame = get("portal_frame"); + public static final Block cell_rock = get("cell_rock"); + public static final Block dragon_egg = get("dragon_egg"); + public static final Block redstone_lamp = get("redstone_lamp"); + public static final Block lit_redstone_lamp = get("lit_redstone_lamp"); +// public static final BlockSlab double_wooden_slab = get("double_wooden_slab"); +// public static final BlockSlab wooden_slab = get("wooden_slab"); + public static final Block cocoa = get("cocoa"); + public static final Block sandstone_stairs = get("sandstone_stairs"); + public static final BlockOre emerald_ore = (BlockOre)get("emerald_ore"); + public static final Block warp_chest = get("warp_chest"); + public static final BlockTripWireHook tripwire_hook = (BlockTripWireHook)get("tripwire_hook"); + public static final Block string = get("string"); + public static final Block emerald_block = get("emerald_block"); + public static final Block spruce_stairs = get("spruce_stairs"); + public static final Block birch_stairs = get("birch_stairs"); + public static final Block jungle_stairs = get("jungle_stairs"); + public static final BlockBeacon beacon = (BlockBeacon)get("beacon"); + public static final Block cobblestone_wall = get("cobblestone_wall"); + public static final Block flower_pot = get("flower_pot"); + public static final Block carrot = get("carrot"); + public static final Block potato = get("potato"); + public static final Block wooden_button = get("wooden_button"); + public static final BlockSkull skull = (BlockSkull)get("skull"); + public static final Block anvil = get("anvil"); + public static final Block trapped_chest = get("trapped_chest"); + public static final Block light_weighted_pressure_plate = get("light_weighted_pressure_plate"); + public static final Block heavy_weighted_pressure_plate = get("heavy_weighted_pressure_plate"); + public static final BlockRedstoneComparator comparator = (BlockRedstoneComparator)get("comparator"); + public static final BlockRedstoneComparator powered_comparator = (BlockRedstoneComparator)get("powered_comparator"); + public static final BlockDaylightDetector daylight_detector = (BlockDaylightDetector)get("daylight_detector"); + public static final BlockDaylightDetector daylight_detector_inverted = (BlockDaylightDetector)get("daylight_detector_inverted"); + public static final Block redstone_block = get("redstone_block"); + public static final BlockOre quartz_ore = (BlockOre)get("quartz_ore"); + public static final BlockHopper hopper = (BlockHopper)get("hopper"); + public static final Block quartz_block = get("quartz_block"); + public static final Block black_quartz_block = get("black_quartz_block"); + public static final Block quartz_stairs = get("quartz_stairs"); + public static final Block black_quartz_stairs = get("black_quartz_stairs"); + public static final Block activator_rail = get("activator_rail"); + public static final Block dropper = get("dropper"); + public static final Block stained_hardened_clay = get("stained_hardened_clay"); + public static final Block iron_trapdoor = get("iron_trapdoor"); + public static final Block hay_block = get("hay_block"); + public static final Block carpet = get("carpet"); + public static final Block hardened_clay = get("hardened_clay"); + public static final Block coal_block = get("coal_block"); + public static final Block packed_ice = get("packed_ice"); + public static final Block acacia_stairs = get("acacia_stairs"); + public static final Block dark_oak_stairs = get("dark_oak_stairs"); + public static final Block slime_block = get("slime_block"); + public static final BlockDoublePlant double_plant = (BlockDoublePlant)get("double_plant"); + public static final BlockStainedGlass stained_glass = (BlockStainedGlass)get("stained_glass"); + public static final BlockStainedGlassPane stained_glass_pane = (BlockStainedGlassPane)get("stained_glass_pane"); + public static final Block banner = get("banner"); + public static final Block wall_banner = get("wall_banner"); + + public static final BlockLeaves oak_leaves = (BlockLeaves)get("oak_leaves"); + public static final BlockLeaves spruce_leaves = (BlockLeaves)get("spruce_leaves"); + public static final BlockLeaves birch_leaves = (BlockLeaves)get("birch_leaves"); + public static final BlockLeaves jungle_leaves = (BlockLeaves)get("jungle_leaves"); + public static final BlockLeaves acacia_leaves = (BlockLeaves)get("acacia_leaves"); + public static final BlockLeaves dark_oak_leaves = (BlockLeaves)get("dark_oak_leaves"); + public static final BlockLeaves cherry_leaves = (BlockLeaves)get("cherry_leaves"); + public static final BlockLeaves maple_leaves = (BlockLeaves)get("maple_leaves"); + public static final BlockLeaves tian_leaves = (BlockLeaves)get("tian_leaves"); + public static final BlockLeaves blackwood_leaves = (BlockLeaves)get("blackwood_leaves"); + public static final Block cherry_stairs = get("cherry_stairs"); + public static final Block maple_stairs = get("maple_stairs"); + public static final Block cherry_door = get("cherry_door"); + public static final Block maple_door = get("maple_door"); + public static final Block cherry_fence = get("cherry_fence"); + public static final Block maple_fence = get("maple_fence"); + public static final Block cherry_fence_gate = get("cherry_fence_gate"); + public static final Block maple_fence_gate = get("maple_fence_gate"); + public static final Block nuke = get("nuke"); +// public static final BlockVerticalSlab stone_vslab = get("stone_vslab"); +// public static final BlockVerticalSlab stone_vslab2 = get("stone_vslab2"); +// public static final BlockVerticalSlab wooden_vslab = get("wooden_vslab"); +// public static final BlockVerticalSlab wooden_vslab2 = get("wooden_vslab2"); + public static final BlockOre thetium_ore = (BlockOre)get("thetium_ore"); + public static final BlockOre ardite_ore = (BlockOre)get("ardite_ore"); + public static final BlockOre gyriyn_ore = (BlockOre)get("gyriyn_ore"); + public static final BlockOre nichun_ore = (BlockOre)get("nichun_ore"); + public static final BlockOre ruby_ore = (BlockOre)get("ruby_ore"); + public static final BlockOre cinnabar_ore = (BlockOre)get("cinnabar_ore"); + public static final Block lamp = get("lamp"); + + public static final Block copper_block = get("copper_block"); + public static final Block tin_block = get("tin_block"); + public static final Block aluminium_block = get("aluminium_block"); + public static final Block lead_block = get("lead_block"); + + public static final Block tian = get("tian"); + public static final Block tian_soil = get("tian_soil"); + public static final BlockBush blue_mushroom = (BlockBush)get("blue_mushroom"); + public static final BlockTianReactor tian_reactor = (BlockTianReactor)get("tian_reactor"); + public static final Block red_button = get("red_button"); + public static final Block moon_rock = get("moon_rock"); + public static final Block moon_cheese = get("moon_cheese"); + public static final Block rock = get("rock"); + public static final Block ash = get("ash"); + public static final Block core = get("core"); + + public static final BlockSlab stone_slab = (BlockSlab)get("stone_slab"); + public static final BlockSlab sandstone_slab = (BlockSlab)get("sandstone_slab"); + public static final BlockSlab stonebrick_slab = (BlockSlab)get("stonebrick_slab"); + + public static final BlockDynamicLiquid flowing_blood = (BlockDynamicLiquid)get("flowing_blood"); + public static final BlockStaticLiquid blood = (BlockStaticLiquid)get("blood"); + public static final BlockDynamicLiquid flowing_mercury = (BlockDynamicLiquid)get("flowing_mercury"); + public static final BlockStaticLiquid mercury = (BlockStaticLiquid)get("mercury"); + public static final BlockDynamicLiquid flowing_magma = (BlockDynamicLiquid)get("flowing_magma"); + public static final BlockStaticLiquid magma = (BlockStaticLiquid)get("magma"); + public static final BlockDynamicLiquid flowing_hydrogen = (BlockDynamicLiquid)get("flowing_hydrogen"); + public static final BlockStaticLiquid hydrogen = (BlockStaticLiquid)get("hydrogen"); + + private static Block get(String id) { + if(!BlockRegistry.REGISTRY.containsKey(id)) + throw new RuntimeException("Block " + id + " does not exist!"); + return BlockRegistry.REGISTRY.getObject(id); + } + +// static { +// for(Field field : Blocks.class.getDeclaredFields()) { +// if(Block.class.isAssignableFrom(field.getType())) { +// if(!BlockRegistry.REGISTRY.containsKey(field.getName())) { +// throw new RuntimeException("Block " + field.getName() + " does not exist!"); +// } +// Block block = BlockRegistry.REGISTRY.getObject(field.getName()); +// try { +// field.set(null, block); +// } +// catch(IllegalArgumentException | IllegalAccessException e) { +// throw new RuntimeException(e); +// } +// } +// } +// } +} diff --git a/common/src/main/java/common/vars/Vars.java b/common/src/common/init/Config.java similarity index 51% rename from common/src/main/java/common/vars/Vars.java rename to common/src/common/init/Config.java index a704e68..d04c4e4 100755 --- a/common/src/main/java/common/vars/Vars.java +++ b/common/src/common/init/Config.java @@ -1,18 +1,154 @@ -package common.vars; +package common.init; -import common.util.Var; +import static java.lang.annotation.ElementType.FIELD; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Map; +import java.util.TreeMap; + +import common.util.ExtMath; + +public abstract class Config { + public static enum ValueType { + STRING, BOOLEAN, INTEGER, FLOAT; + } + + @Target(FIELD) + @Retention(value = RetentionPolicy.RUNTIME) + private static @interface Var { + String name(); + float min() default (float)Integer.MIN_VALUE; + float max() default (float)Integer.MAX_VALUE; + } + + public static class Value { + public final ValueType type; + public final String def; + private final Field field; + private final float min; + private final float max; + + private Runnable callback; + + private Value(Field field, Var value) { + this.type = field.getType() == int.class ? ValueType.INTEGER : (field.getType() == boolean.class ? ValueType.BOOLEAN : + (field.getType() == String.class ? ValueType.STRING : (field.getType() == float.class ? ValueType.FLOAT : null))); + if(this.type == null) + throw new IllegalArgumentException(value.name() + ": Unbekannter Variablen-Typ - " + field.getType()); + this.field = field; + this.def = this.getValue(); +// Clamped clamp = this.field.getAnnotation(Clamped.class); + this.min = (this.type == ValueType.INTEGER || this.type == ValueType.FLOAT) + ? value.min() : 0; + this.max = (this.type == ValueType.INTEGER || this.type == ValueType.FLOAT) + ? value.max() : (this.type == ValueType.BOOLEAN ? 1 : 0); +// Update update = this.field.getAnnotation(Update.class); +// if(value.callback() == Callback.class) { +// this.callback = null; +// } +// else { +// try { +// this.callback = value.callback().getConstructor().newInstance(); +// } +// catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException +// | NoSuchMethodException e) { +// throw new RuntimeException(e); +// } +// } + this.setValue(this.def); + } + + public String getValue() { + try { + return "" + this.field.get(null); +// switch(this.type) { +// case STRING: +// default: +// return (String)this.field.get(null); +// case BOOLEAN: +// return "" + this.field.getBoolean(null); +// case INTEGER: +// return "" + this.field.getInt(null); +// case FLOAT: +// return "" + this.field.getFloat(null); +// } + } + catch(IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + private void setValue(String value) { + try { + switch(this.type) { + case STRING: + this.field.set(null, value); + break; + case BOOLEAN: + this.field.setBoolean(null, Boolean.parseBoolean(value)); + break; + case INTEGER: + int inum = 0; + try { + inum = Integer.parseInt(value); + } + catch(NumberFormatException e) { + } + this.field.setInt(null, ExtMath.clampi(inum, (int)this.min, (int)this.max)); + break; + case FLOAT: + float fnum = 0.0f; + try { + fnum = Float.parseFloat(value); + } + catch(NumberFormatException e) { + } + fnum = ExtMath.clampf(fnum, this.min, this.max); + int round = (int)(fnum * 1000.0f); + this.field.setFloat(null, (float)round / 1000.0f); + break; + } + } + catch(IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); + } + } + } + + public static final int PROTOCOL = 666; + public static final int PORT = 26666; + public static final String NAME = "TCR"; + public static final String VERSION = "v2.2.1-alpha"; + public static final String CLIENT_VERSION = NAME + " Client " + VERSION; + + public static final Map VARS = new TreeMap(); -public abstract class Vars { @Var(name = "fireTick") public static boolean fire = true; @Var(name = "mobGriefing") public static boolean mobGrief = true; @Var(name = "mobSpawning") public static boolean mobs = true; + @Var(name = "tickSpawning") + public static boolean tickSpawn = true; + @Var(name = "genSpawning") + public static boolean genSpawn = true; @Var(name = "spawners") public static boolean spawners = true; + @Var(name = "spawnVillagers") + public static boolean spawnVillager = true; + @Var(name = "spawnCagedVillagers") + public static boolean spawnCagedVillager = true; + @Var(name = "spawnHutMages") + public static boolean spawnHutMage = true; @Var(name = "spawnEggChickens") public static boolean spawnEggChicken = true; + @Var(name = "spawnMoreZombies") + public static boolean spawnMoreZombie = true; @Var(name = "spawnSplitSlimes") public static boolean spawnSplitSlime = true; @Var(name = "chargeHaunter") @@ -37,6 +173,10 @@ public abstract class Vars { public static boolean objectDrop = true; @Var(name = "naturalRegeneration") public static boolean regeneration = true; + @Var(name = "daylightCycle") + public static boolean dayCycle = true; + @Var(name = "weatherChanges") + public static boolean weather = true; @Var(name = "seasonLeafUpdate") public static boolean seasonLeaves = true; @Var(name = "leavesDecay") @@ -51,6 +191,8 @@ public abstract class Vars { public static boolean portals = true; @Var(name = "portalVoid") public static boolean voidPortal = true; + @Var(name = "dropPlayerSkulls") + public static boolean skullDrop = true; @Var(name = "dropPlayerItems") public static boolean playerDrop = true; @Var(name = "blockGravity") @@ -65,6 +207,8 @@ public abstract class Vars { public static boolean mergeInfinite = true; @Var(name = "infighting") public static boolean infight = true; +// @Var(name = "infightSameType") +// public static boolean infightSame = true; @Var(name = "damageFall") public static boolean damageFall = true; @Var(name = "damageFire") @@ -181,10 +325,14 @@ public abstract class Vars { public static boolean locking = true; @Var(name = "teleFragging") public static boolean telefrag = true; + @Var(name = "checkRespawn") + public static boolean checkBed = true; @Var(name = "chunkLoaders") public static boolean loaders = true; @Var(name = "fragileItems") public static boolean itemFallDamage = true; + @Var(name = "registration") + public static boolean register = true; @Var(name = "signEditing") public static boolean editSigns = true; @@ -198,23 +346,53 @@ public abstract class Vars { public static boolean mergeFinite = false; @Var(name = "veryHungryRabbits") public static boolean rabidRabbits = false; - @Var(name = "evilFowl") - public static boolean aggressiveChickens = false; + @Var(name = "snowStacking") + public static boolean snowStack = false; + @Var(name = "randomTickSpeed") + public static int randomTick = 3; + @Var(name = "weatherTickSpeed") + public static int weatherTick = 1; + @Var(name = "lightningChance") + public static int boltChance = 100000; + @Var(name = "igniteChance") + public static int igniteChance = 100; + @Var(name = "spawnRadius") + public static int spawnRadius = 10; + @Var(name = "originRadius", min = 0, max = 262144) + public static int originRadius = 16384; + @Var(name = "respawnTime") + public static int respawnTime = 0; @Var(name = "hurtCooldown") public static int hurtDelay = 20; @Var(name = "attackCooldown") public static int attackDelay = 0; + @Var(name = "spawnGroupCount") + public static int spawnGroups = 3; + @Var(name = "spawnGroupDistance") + public static int spawnGroupDist = 6; + @Var(name = "mobSpawnRadius") + public static int mobSpawnDist = 8; + @Var(name = "mobPlayerDistance") + public static int mobPlayerDist = 24; + @Var(name = "saveInterval") + public static int saveInterval = 900; + @Var(name = "maxPlayers") + public static int playerLimit = 0; + @Var(name = "compressAbove") + public static int compression = 256; @Var(name = "pistonPushLimit") public static int pistonLimit = 16; @Var(name = "gravelFlintChance") public static int flintChance = 10; + @Var(name = "timeFlow") + public static int timeFlow = 1; + @Var(name = "emptyTicks") + public static int unloadTicks = 1200; @Var(name = "rabbitMateChance") public static int rabbitMateChance = 10; @Var(name = "killerBunnyChance") public static int killerBunnyChance = 1000; - @Var(name = "evilChickenChance") - public static int evilChickenChance = 700; @Var(name = "fallPortalHeight") public static int portalHeight = 256; @Var(name = "damageOrb") @@ -241,6 +419,10 @@ public abstract class Vars { public static int cactusHeight = 3; @Var(name = "orbThorns") public static int orbDamageOther = 0; + @Var(name = "weatherChance") + public static int weatherChance = 48000; + @Var(name = "viewDistance", min = 2, max = 128) + public static int distance = 10; @Var(name = "healChance") public static int healChance = 5; @Var(name = "hopperCooldown", min = 0, max = 160) @@ -249,11 +431,70 @@ public abstract class Vars { public static int hopperCartDelay = 1; @Var(name = "xpCooldown", min = 0, max = 10) public static int xpDelay = 0; // 2 + @Var(name = "maxSpawns") + public static int maxMobs = 120; @Var(name = "eggLayTime") public static int eggTimer = 6000; - @Var(name = "spawnMoreZombies") - public static int spawnMoreZombie = 25; + @Var(name = "connectionTimeout", min = 10, max = 300) + public static int timeout = 30; + @Var(name = "passwordMinLength", min = 1, max = 32) + public static int minPassLength = 8; +// @Var(name = "spawnX", min = -World.MAX_SIZE + 1, max = World.MAX_SIZE - 1) +// public static int spawnX = 0; +// @Var(name = "spawnY", min = -1, max = 511) +// public static int spawnY = 64; +// @Var(name = "spawnZ", min = -World.MAX_SIZE + 1, max = World.MAX_SIZE - 1) +// public static int spawnZ = 0; +// @Var(name = "spawnDim") +// public static int spawnDim = 0; + + @Var(name = "gravity") + public static float gravity = 1.0f; @Var(name = "knockback") public static float knockback = 1.0f; + + @Var(name = "spawnYaw", min = -180.0f, max = 180.0f) + public static float spawnYaw = -90.0f; + @Var(name = "spawnPitch", min = -89.0f, max = 89.0f) + public static float spawnPitch = 0.0f; + + @Var(name = "password") + public static String password = ""; + + static { + for(Field field : Config.class.getDeclaredFields()) { + if(field.isAnnotationPresent(Var.class)) { + if(!Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) + throw new IllegalArgumentException("Feld für Variable " + field + " muss statisch und änderbar sein!"); + Var value = field.getAnnotation(Var.class); + if(value.name().isEmpty()) + throw new IllegalArgumentException("Variablenname von " + field + " kann nicht leer sein!"); + if(VARS.containsKey(value.name())) + throw new IllegalArgumentException("Variable " + value.name() + " existiert bereits!"); + VARS.put(value.name(), new Config.Value(field, value)); + } + } + } + + public static void clear() { + for(Config.Value value : VARS.values()) { + value.setValue(value.def); + } + } + + public static void setCallback(Runnable callback, String ... vars) { + for(String key : vars) { + VARS.get(key).callback = callback; + } + } + + public static void set(String key, String value, boolean update) { + Config.Value vl = VARS.get(key); + if(vl != null) { + vl.setValue(value); + if(update && vl.callback != null) + vl.callback.run(); + } + } } diff --git a/common/src/main/java/common/init/CraftingRegistry.java b/common/src/common/init/CraftingRegistry.java similarity index 82% rename from common/src/main/java/common/init/CraftingRegistry.java rename to common/src/common/init/CraftingRegistry.java index d5d491f..7e5ea06 100755 --- a/common/src/main/java/common/init/CraftingRegistry.java +++ b/common/src/common/init/CraftingRegistry.java @@ -7,15 +7,15 @@ import java.util.Map; import java.util.Set; import common.block.Block; -import common.block.artificial.BlockBed; -import common.block.artificial.BlockQuartz; -import common.block.artificial.BlockStoneBrick; -import common.block.artificial.BlockWall; -import common.block.foliage.BlockDoublePlant; -import common.block.foliage.BlockFlower; -import common.block.natural.BlockDirt; -import common.block.natural.BlockSand; -import common.block.natural.BlockSandStone; +import common.block.BlockBed; +import common.block.BlockDirt; +import common.block.BlockDoublePlant; +import common.block.BlockFlower; +import common.block.BlockQuartz; +import common.block.BlockSand; +import common.block.BlockSandStone; +import common.block.BlockStoneBrick; +import common.block.BlockWall; import common.collect.Lists; import common.collect.Maps; import common.color.DyeColor; @@ -25,7 +25,8 @@ import common.item.Item; import common.item.ItemArmor; import common.item.ItemDye; import common.item.ItemStack; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.tileentity.TileEntityBanner; import common.world.World; @@ -34,11 +35,25 @@ public abstract class CraftingRegistry private static final String[][] TOOLS = new String[][] { {"XXX", " # ", " # "}, {"X", "#", "#"}, {"XX", "X#", " #"}, {"XX", " #", " #"} }; +// private static final Object[][] toolItems = new Object[][] { +// {Blocks.planks, Blocks.cobblestone}, // Items.iron_ingot, Items.diamond, Items.gold_ingot}, +// {Items.wooden_pickaxe, Items.stone_pickaxe}, // Items.iron_pickaxe, Items.diamond_pickaxe, Items.golden_pickaxe}, +// {Items.wooden_shovel, Items.stone_shovel}, // Items.iron_shovel, Items.diamond_shovel, Items.golden_shovel}, +// {Items.wooden_axe, Items.stone_axe}, // Items.iron_axe, Items.diamond_axe, Items.golden_axe}, +// {Items.wooden_hoe, Items.stone_hoe}, // Items.iron_hoe, Items.diamond_hoe, Items.golden_hoe} +// }; private static final String[][] WEAPONS = new String[][] {{"X", "X", "#"}}; +// private static final Object[][] weaponItems = new Object[][] { +// {Blocks.planks, Blocks.cobblestone}, // Items.iron_ingot, Items.diamond, Items.gold_ingot}, +// {Items.wooden_sword, Items.stone_sword}, // Items.iron_sword, Items.diamond_sword, Items.golden_sword} +// }; private static final String[][] ARMOR = new String[][] { {"XXX", "X X"}, {"X X", "XXX", "XXX"}, {"XXX", "X X", "X X"}, {"X X", "X X"} }; private static final Object[][] COMPRESSED = new Object[][] { + /* {Blocks.gold_block, new ItemStack(Items.gold_ingot, 9)}, + {Blocks.iron_block, new ItemStack(Items.iron_ingot, 9)}, */ +// {Blocks.diamond_block, new ItemStack(Items.diamond, 9)}, {Blocks.emerald_block, new ItemStack(Items.emerald, 9)}, {Blocks.lapis_block, new ItemStack(Items.dye, 9, DyeColor.BLUE.getDyeDamage())}, {Blocks.redstone_block, new ItemStack(Items.redstone, 9)}, @@ -46,12 +61,33 @@ public abstract class CraftingRegistry {Blocks.hay_block, new ItemStack(Items.wheats, 9)}, {Blocks.slime_block, new ItemStack(Items.slime_ball, 9)} }; +// private static final Item[][] armorItems = new Item[][] { +// {Items.leather}, // /* Items.iron_ingot, */ Items.diamond /* , Items.gold_ingot */}, +// {Items.leather_helmet}, // /* Items.iron_helmet, */ Items.diamond_helmet /* , Items.golden_helmet */}, +// {Items.leather_chestplate}, // /* Items.iron_chestplate, */ Items.diamond_chestplate /* , Items.golden_chestplate */}, +// {Items.leather_leggings}, // /* Items.iron_leggings, */ Items.diamond_leggings /* , Items.golden_leggings */}, +// {Items.leather_boots}, // /* Items.iron_boots, */ Items.diamond_boots /* , Items.golden_boots */} +// }; private static final List recipes = Lists.newArrayList(); private static final List base = Lists.newArrayList(); static void register() { +// for (int i = 0; i < toolItems[0].length; ++i) +// { +// Object object = toolItems[0][i]; +// +// for (int j = 0; j < toolItems.length - 1; ++j) +// { +// Item item = (Item)toolItems[j + 1][i]; +// add(new ItemStack(item), toolPatterns[j], '#', Items.stick, 'X', object); +// } +// } + +// add(new ItemStack(Items.shears), " #", "# ", '#', Items.iron_ingot); +// add(new ItemStack(Items.diamond_shears), " #", "# ", '#', Items.diamond); + for(OreType ore : OreType.values()) { Item item = ItemRegistry.getRegisteredItem(ore.item); ore.material.addRepairItem(item); @@ -128,6 +164,17 @@ public abstract class CraftingRegistry } } +// for (int i = 0; i < weaponItems[0].length; ++i) +// { +// Object object = weaponItems[0][i]; +// +// for (int j = 0; j < weaponItems.length - 1; ++j) +// { +// Item item = (Item)weaponItems[j + 1][i]; +// add(new ItemStack(item), weaponPatterns[j], '#', Items.stick, 'X', object); +// } +// } + add(new ItemStack(Items.bow, 1), " #X", "# X", " #X", 'X', Items.string, '#', Items.stick); add(new ItemStack(Items.arrow, 4), "X", "#", "Y", 'Y', Items.feather, 'X', Items.flint, '#', Items.stick); @@ -144,6 +191,8 @@ public abstract class CraftingRegistry addShapeless(new ItemStack(Items.mushroom_stew), Blocks.brown_mushroom, Blocks.red_mushroom, Items.bowl); add(new ItemStack(Items.cookie, 8), "#X#", 'X', new ItemStack(Items.dye, 1, DyeColor.BROWN.getDyeDamage()), '#', Items.wheats); +// addRecipe(new ItemStack(Items.rabbit_stew), " R ", "CPM", " B ", 'R', new ItemStack(Items.cooked_rabbit), 'C', Items.carrot, 'P', Items.baked_potato, 'M', Blocks.brown_mushroom, 'B', Items.bowl); +// addRecipe(new ItemStack(Items.rabbit_stew), " R ", "CPD", " B ", 'R', new ItemStack(Items.cooked_rabbit), 'C', Items.carrot, 'P', Items.baked_potato, 'D', Blocks.red_mushroom, 'B', Items.bowl); add(new ItemStack(Blocks.melon_block), "MMM", "MMM", "MMM", 'M', Items.melon); add(new ItemStack(Items.melon_stem), "M", 'M', Items.melon); add(new ItemStack(Items.pumpkin_stem, 4), "M", 'M', Blocks.pumpkin); @@ -156,7 +205,10 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.warp_chest), "###", "#E#", "###", '#', Blocks.obsidian, 'E', Items.charged_orb); add(new ItemStack(Blocks.furnace), "###", "# #", "###", '#', Blocks.cobblestone); add(new ItemStack(Blocks.sandstone), "##", "##", '#', new ItemStack(Blocks.sand, 1, BlockSand.EnumType.SAND.getMetadata())); +// addRecipe(new ItemStack(Blocks.red_sandstone), "##", "##", '#', new ItemStack(Blocks.sand, 1, BlockSand.EnumType.RED_SAND.getMetadata())); add(new ItemStack(Blocks.sandstone, 4, BlockSandStone.EnumType.SMOOTH.getMetadata()), "##", "##", '#', new ItemStack(Blocks.sandstone, 1, BlockSandStone.EnumType.DEFAULT.getMetadata())); +// addRecipe(new ItemStack(Blocks.red_sandstone, 4, BlockRedSandstone.EnumType.SMOOTH.getMetadata()), "##", "##", '#', new ItemStack(Blocks.red_sandstone, 1, BlockRedSandstone.EnumType.DEFAULT.getMetadata())); +// addRecipe(new ItemStack(Blocks.red_sandstone, 1, BlockRedSandstone.EnumType.CHISELED.getMetadata()), "#", "#", '#', new ItemStack(Blocks.stone_slab2, 1, BlockStoneSlabNew.EnumType.RED_SANDSTONE.getMetadata())); add(new ItemStack(Blocks.quartz_block, 2, BlockQuartz.EnumType.LINES_Y.getMetadata()), "#", "#", '#', new ItemStack(Blocks.quartz_block, 1, BlockQuartz.EnumType.DEFAULT.getMetadata())); add(new ItemStack(Blocks.stonebrick, 4), "##", "##", '#', Blocks.stone); addShapeless(new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.MOSSY_META), Blocks.stonebrick, Blocks.vine); @@ -166,10 +218,31 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.redstone_lamp, 1), " R ", "RGR", " R ", 'R', Items.redstone, 'G', Blocks.glowstone); add(new ItemStack(Blocks.beacon, 1), "GGG", "GSG", "OOO", 'G', Blocks.glass, 'S', Items.charge_crystal, 'O', Blocks.obsidian); add(new ItemStack(Blocks.blood_brick, 1), "NN", "NN", 'N', Items.bloodbrick); +// addRecipe(new ItemStack(Blocks.stone, 2, BlockStone.EnumType.DIORITE.getMetadata()), "CQ", "QC", 'C', Blocks.cobblestone, 'Q', Items.quartz); +// addShapelessRecipe(new ItemStack(Blocks.stone, 1, BlockStone.EnumType.GRANITE.getMetadata()), new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata()), Items.quartz); +// addShapelessRecipe(new ItemStack(Blocks.stone, 2, BlockStone.EnumType.ANDESITE.getMetadata()), new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata()), Blocks.cobblestone); add(new ItemStack(Blocks.dirt, 4, BlockDirt.DirtType.COARSE_DIRT.getMetadata()), "DG", "GD", 'D', new ItemStack(Blocks.dirt, 1, BlockDirt.DirtType.DIRT.getMetadata()), 'G', Blocks.gravel); +// addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.DIORITE_SMOOTH.getMetadata()), "SS", "SS", 'S', new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata())); +// addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.GRANITE_SMOOTH.getMetadata()), "SS", "SS", 'S', new ItemStack(Blocks.stone, 1, BlockStone.EnumType.GRANITE.getMetadata())); +// addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.ANDESITE_SMOOTH.getMetadata()), "SS", "SS", 'S', new ItemStack(Blocks.stone, 1, BlockStone.EnumType.ANDESITE.getMetadata())); +// addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.ROUGH_META), "SS", "SS", 'S', Items.prismarine_shard); +// addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.BRICKS_META), "SSS", "SSS", "SSS", 'S', Items.prismarine_shard); +// addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.DARK_META), "SSS", "SIS", "SSS", 'S', Items.prismarine_shard, 'I', new ItemStack(Items.dye, 1, EnumDyeColor.BLACK.getDyeDamage())); +// addRecipe(new ItemStack(Blocks.sea_lantern, 1, 0), "SCS", "CCC", "SCS", 'S', Items.prismarine_shard, 'C', Items.prismarine_crystals); add(new ItemStack(Blocks.lamp, 1), " R ", "RGR", " R ", 'R', Blocks.glass, 'G', Blocks.glowstone); +// for (int i = 0; i < armorItems[0].length; ++i) +// { +// Item item = armorItems[0][i]; +// +// for (int j = 0; j < armorItems.length - 1; ++j) +// { +// Item item1 = armorItems[j + 1][i]; +// add(new ItemStack(item1), armorPatterns[j], 'X', item); +// } +// } + for (int i = 0; i < 16; ++i) { addShapeless(new ItemStack(Blocks.wool, 1, i), new ItemStack(Items.dye, 1, 15 - i), new ItemStack(Blocks.wool, 1, 0)); @@ -213,6 +286,9 @@ public abstract class CraftingRegistry } recipes.add(new RecipesArmorDyes()); +// this.recipes.add(new RecipeBookCloning()); +// recipes.add(new RecipesMapCloning()); +// recipes.add(new RecipesMapExtending()); recipes.add(new RecipeFireworks()); recipes.add(new RecipeRepairItem()); @@ -239,8 +315,7 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.daylight_detector), "GGG", "QQQ", "WWW", 'G', Blocks.glass, 'Q', Items.quartz, 'W', slab); add(new ItemStack(Blocks.chest), "###", "# #", "###", '#', planks); - addBasic(new ItemStack(Blocks.workbench), "##", "##", '#', planks); - add(new ItemStack(Blocks.assembly_unit), "----", "XXXX", "X##X", '#', Blocks.construction_table, '-', Items.titanium_ingot, 'X', planks); + addBasic(new ItemStack(Blocks.crafting_table), "##", "##", '#', planks); add(new ItemStack(Blocks.jukebox, 1), "###", "#X#", "###", '#', planks, 'X', Items.diamond); @@ -282,6 +357,17 @@ public abstract class CraftingRegistry addShapeless(new ItemStack(Blocks.tnt, 1, 6), new ItemStack(Blocks.tnt, 1, 5), new ItemStack(Blocks.tnt, 1, 5)); addShapeless(new ItemStack(Blocks.tnt, 1, 7), new ItemStack(Blocks.tnt, 1, 6), new ItemStack(Blocks.tnt, 1, 6)); add(new ItemStack(Blocks.nuke, 1), "###", "###", "###", '#', new ItemStack(Blocks.tnt, 1, 7)); + +// add(new ItemStack(Blocks.sandstone, 1, BlockSandStone.EnumType.CHISELED.getMetadata()), "#", "#", '#', new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.SAND.getMetadata())); +// add(new ItemStack(Blocks.quartz_block, 1, BlockQuartz.EnumType.CHISELED.getMetadata()), "#", "#", '#', new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.QUARTZ.getMetadata())); +// add(new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.CHISELED_META), "#", "#", '#', new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.SMOOTHBRICK.getMetadata())); +// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.COBBLESTONE.getMetadata()), "###", '#', Blocks.cobblestone); +// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.STONE.getMetadata()), "###", '#', Blocks.stone); +// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.SAND.getMetadata()), "###", '#', Blocks.sandstone); +// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.BRICK.getMetadata()), "###", '#', Blocks.brick_block); +// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.SMOOTHBRICK.getMetadata()), "###", '#', Blocks.stonebrick); +// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.BLOODBRICK.getMetadata()), "###", '#', Blocks.blood_brick); +// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.QUARTZ.getMetadata()), "###", '#', Blocks.quartz_block); add(new ItemStack(Blocks.ladder, 3), "# #", "###", "# #", '#', Items.stick); @@ -302,6 +388,7 @@ public abstract class CraftingRegistry add(new ItemStack(Items.brewing_stand, 1), " B ", "###", '#', Blocks.cobblestone, 'B', Items.blaze_rod); add(new ItemStack(Blocks.lit_pumpkin, 1), "A", "B", 'A', Blocks.pumpkin, 'B', Blocks.torch); add(new ItemStack(Items.chest_minecart, 1), "A", "B", 'A', Blocks.chest, 'B', Items.minecart); +// add(new ItemStack(Items.furnace_minecart, 1), "A", "B", 'A', Blocks.furnace, 'B', Items.minecart); add(new ItemStack(Items.tnt_minecart, 1), "A", "B", 'A', new ItemStack(Blocks.tnt, 1, 0), 'B', Items.minecart); add(new ItemStack(Items.hopper_minecart, 1), "A", "B", 'A', Blocks.hopper, 'B', Items.minecart); add(new ItemStack(Items.bucket, 1), "# #", " # ", '#', Items.iron_ingot); @@ -316,7 +403,10 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.stonebrick_stairs, 4), "# ", "## ", "###", '#', Blocks.stonebrick); add(new ItemStack(Blocks.blood_brick_stairs, 4), "# ", "## ", "###", '#', Blocks.blood_brick); add(new ItemStack(Blocks.sandstone_stairs, 4), "# ", "## ", "###", '#', Blocks.sandstone); +// addRecipe(new ItemStack(Blocks.red_sandstone_stairs, 4), "# ", "## ", "###", '#', Blocks.red_sandstone); add(new ItemStack(Blocks.quartz_stairs, 4), "# ", "## ", "###", '#', Blocks.quartz_block); +// add(new ItemStack(Items.painting, 1), "###", "#X#", "###", '#', Items.stick, 'X', Blocks.wool); +// add(new ItemStack(Items.item_frame, 1), "###", "#X#", "###", '#', Items.stick, 'X', Items.leather); add(new ItemStack(Items.golden_apple, 1, 0), "###", "#X#", "###", '#', Items.gold_ingot, 'X', Items.apple); add(new ItemStack(Items.golden_apple, 1, 1), "###", "#X#", "###", '#', Blocks.gold_block, 'X', Items.apple); add(new ItemStack(Items.golden_carrot, 1, 0), "###", "#X#", "###", '#', Items.gold_nugget, 'X', Items.carrot); @@ -325,7 +415,9 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.redstone_torch, 1), "X", "#", '#', Items.stick, 'X', Items.redstone); add(new ItemStack(Items.repeater, 1), "#X#", "III", '#', Blocks.redstone_torch, 'X', Items.redstone, 'I', Blocks.stone); add(new ItemStack(Items.comparator, 1), " # ", "#X#", "III", '#', Blocks.redstone_torch, 'X', Items.quartz, 'I', Blocks.stone); +// add(new ItemStack(Items.clock, 1), " # ", "#X#", " # ", '#', Items.gold_ingot, 'X', Items.redstone); add(new ItemStack(Items.navigator, 1), " # ", "#X#", " # ", '#', Items.iron_ingot, 'X', Items.redstone); +// add(new ItemStack(Items.map, 1), "###", "#X#", "###", '#', Items.paper, 'X', Items.compass); add(new ItemStack(Blocks.stone_button, 1), "#", '#', Blocks.stone); add(new ItemStack(Blocks.stone_pressure_plate, 1), "##", '#', Blocks.stone); add(new ItemStack(Blocks.heavy_weighted_pressure_plate, 1), "##", '#', Items.iron_ingot); @@ -335,10 +427,12 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.sticky_piston, 1), "S", "P", 'S', Items.slime_ball, 'P', Blocks.piston); add(new ItemStack(Blocks.enchanting_table, 1), " B ", "D#D", "###", '#', Blocks.obsidian, 'B', Items.book, 'D', Items.diamond); add(new ItemStack(Blocks.anvil, 1), "III", " i ", "iii", 'I', Blocks.iron_block, 'i', Items.iron_ingot); +// addRecipe(new ItemStack(Items.leather), "##", "##", '#', Items.rabbit_hide); addShapeless(new ItemStack(Items.charged_orb, 1), Items.orb, Items.blaze_powder); addShapeless(new ItemStack(Items.fire_charge, 3), Items.gunpowder, Items.blaze_powder, Items.coal); addShapeless(new ItemStack(Items.fire_charge, 3), Items.gunpowder, Items.blaze_powder, new ItemStack(Items.coal, 1, 1)); add(new ItemStack(Blocks.hopper), "I I", "ICI", " I ", 'I', Items.iron_ingot, 'C', Blocks.chest); +// addRecipe(new ItemStack(Items.armor_stand, 1), "///", " / ", "/_/", '/', Items.stick, '_', new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.STONE.getMetadata())); add(new ItemStack(Items.dynamite, 1), "X#X", "#X#", "X#X", 'X', Items.gunpowder, '#', Items.clay_ball); @@ -351,18 +445,27 @@ public abstract class CraftingRegistry addShapeless(new ItemStack(Items.dynamite, 1, 7), new ItemStack(Items.dynamite, 1, 6), new ItemStack(Items.dynamite, 1, 6)); add(new ItemStack(Items.portal_frame, 1), "XYX", "X#X", "XXX", 'X', Blocks.obsidian, 'Y', Items.orb, '#', Items.charged_orb); +// add(new ItemStack(Blocks.monster_egg, 1, 0), "XXX", "X#X", "XXX", 'X', new ItemStack(Blocks.stone, 1, 0), '#', new ItemStack(Items.spawn_egg, 1, 60)); +// add(new ItemStack(Blocks.monster_egg, 1, 1), "XXX", "X#X", "XXX", 'X', Blocks.cobblestone, '#', new ItemStack(Items.spawn_egg, 1, 60)); +// for(int z = 0; z < 4; z++) { +// add(new ItemStack(Blocks.monster_egg, 1, z + 2), "XXX", "X#X", "XXX", 'X', new ItemStack(Blocks.stonebrick, 1, z), '#', new ItemStack(Items.spawn_egg, 1, 60)); +// } add(new ItemStack(Items.experience_bottle, 1), "YXY", "X#X", "YXY", 'X', Blocks.glass_pane, 'Y', Blocks.glowstone, '#', Items.emerald); add(new ItemStack(Blocks.mob_spawner, 1), "###", "#X#", "###", 'X', Items.charge_crystal, '#', Blocks.iron_bars); add(new ItemStack(Blocks.dragon_egg, 1), "###", "#X#", "#D#", 'X', Items.charge_crystal, 'D', Items.diamond, '#', Blocks.obsidian); +// addRecipe(new ItemStack(Blocks.command_block, 1), "###", "#X#", "###", 'X', Items.redstone, '#', Items.quartz); +// addShapeless(new ItemStack(Items.spawn_egg, 1, 51), new ItemStack(Items.skull, 1, 0)); +// addShapeless(new ItemStack(Items.spawn_egg, 1, 51), new ItemStack(Items.skull, 1, 1)); +// addShapeless(new ItemStack(Items.spawn_egg, 1, 54), new ItemStack(Items.skull, 1, 2)); +// addShapeless(new ItemStack(Items.spawn_egg, 1, 50), new ItemStack(Items.skull, 1, 4)); +// addShapeless(new ItemStack(Items.spawn_egg, 1, 124), Items.flint, Items.egg, Blocks.cobblestone, Items.slime_ball); +// addRecipe(new ItemStack(Items.command_block_minecart, 1), "A", "B", 'A', Blocks.command_block, 'B', Items.minecart); add(new ItemStack(Blocks.red_button, 1), "#", '#', Items.redstone); add(new ItemStack(Items.chick_magnet, 1), "A A", "N N", " C ", 'A', Items.aluminium_ingot, 'N', Items.nickel_ingot, 'C', Items.cobalt_ingot); add(new ItemStack(Items.magnet, 1), "I I", "N N", " R ", 'I', Items.iron_ingot, 'N', Items.neodymium_ingot, 'R', Items.redstone); addShapeless(new ItemStack(Items.potion, 1, 16384), new ItemStack(Items.potion, 1, 0), Items.gunpowder); - - add(new ItemStack(Blocks.construction_table), "---", "-#-", "---", '#', Blocks.workbench, '-', Items.iron_ingot); - add(new ItemStack(Blocks.bedrock), "#####", "#####", "#####", "#####", "#####", '#', Blocks.obsidian); Collections.sort(recipes, new Comparator() { @@ -593,14 +696,14 @@ public abstract class CraftingRegistry if (itemstack1 != null && itemstack1.getItem() == Items.banner) { itemstack = itemstack1.copy(); - itemstack.size = 1; + itemstack.stackSize = 1; break; } } - TileEntityBanner.EnumBannerPattern type = this.getBannerPattern(inv); + TileEntityBanner.EnumBannerPattern tileentitybanner$enumbannerpattern = this.getBannerPattern(inv); - if (type != null) + if (tileentitybanner$enumbannerpattern != null) { int k = 0; @@ -615,23 +718,23 @@ public abstract class CraftingRegistry } } - TagObject tag = itemstack.getSubCompound("BlockEntityTag", true); - List list = null; + NBTTagCompound nbttagcompound1 = itemstack.getSubCompound("BlockEntityTag", true); + NBTTagList nbttaglist = null; - if (tag.hasList("Patterns")) + if (nbttagcompound1.hasKey("Patterns", 9)) { - list = tag.getList("Patterns"); + nbttaglist = nbttagcompound1.getTagList("Patterns", 10); } else { - list = Lists.newArrayList(); - tag.setList("Patterns", list); + nbttaglist = new NBTTagList(); + nbttagcompound1.setTag("Patterns", nbttaglist); } - TagObject pattern = new TagObject(); - pattern.setString("Pattern", type.getPatternID()); - pattern.setInt("Color", k); - list.add(pattern); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setString("Pattern", tileentitybanner$enumbannerpattern.getPatternID()); + nbttagcompound.setInteger("Color", k); + nbttaglist.appendTag(nbttagcompound); } return itemstack; @@ -843,7 +946,7 @@ public abstract class CraftingRegistry if (itemstack != null && TileEntityBanner.getPatterns(itemstack) > 0) { ItemStack itemstack1 = itemstack.copy(); - itemstack1.size = 1; + itemstack1.stackSize = 1; return itemstack1; } } @@ -878,7 +981,7 @@ public abstract class CraftingRegistry else if (itemstack.hasTagCompound() && TileEntityBanner.getPatterns(itemstack) > 0) { aitemstack[i] = itemstack.copy(); - aitemstack[i].size = 1; + aitemstack[i].stackSize = 1; } } } @@ -968,24 +1071,24 @@ public abstract class CraftingRegistry if (l > 0) { - TagObject tag = new TagObject(); - TagObject data = new TagObject(); - List list = Lists.newArrayList(); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + NBTTagCompound nbttagcompound3 = new NBTTagCompound(); + NBTTagList nbttaglist = new NBTTagList(); for (int k2 = 0; k2 < inv.getSizeInventory(); ++k2) { ItemStack itemstack3 = inv.getStackInSlot(k2); - if (itemstack3 != null && itemstack3.getItem() == Items.firework_charge && itemstack3.hasTagCompound() && itemstack3.getTagCompound().hasObject("Explosion")) + if (itemstack3 != null && itemstack3.getItem() == Items.firework_charge && itemstack3.hasTagCompound() && itemstack3.getTagCompound().hasKey("Explosion", 10)) { - list.add(itemstack3.getTagCompound().getObject("Explosion")); + nbttaglist.appendTag(itemstack3.getTagCompound().getCompoundTag("Explosion")); } } - data.setList("Explosions", list); - data.setByte("Flight", (byte)j); - tag.setObject("Fireworks", data); - this.field_92102_a.setTagCompound(tag); + nbttagcompound3.setTag("Explosions", nbttaglist); + nbttagcompound3.setByte("Flight", (byte)j); + nbttagcompound1.setTag("Fireworks", nbttagcompound3); + this.field_92102_a.setTagCompound(nbttagcompound1); } return true; @@ -993,8 +1096,8 @@ public abstract class CraftingRegistry else if (j == 1 && i == 0 && l == 0 && k > 0 && j1 <= 1) { this.field_92102_a = new ItemStack(Items.firework_charge); - TagObject tag = new TagObject(); - TagObject data = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagCompound nbttagcompound2 = new NBTTagCompound(); byte b0 = 0; List list = Lists.newArrayList(); @@ -1010,11 +1113,11 @@ public abstract class CraftingRegistry } else if (itemstack2.getItem() == Items.glowstone_dust) { - data.setBool("Flicker", true); + nbttagcompound2.setBoolean("Flicker", true); } else if (itemstack2.getItem() == Items.diamond) { - data.setBool("Trail", true); + nbttagcompound2.setBoolean("Trail", true); } else if (itemstack2.getItem() == Items.fire_charge) { @@ -1042,10 +1145,10 @@ public abstract class CraftingRegistry aint1[l2] = ((Integer)list.get(l2)).intValue(); } - data.setIntArray("Colors", aint1); - data.setByte("Type", b0); - tag.setObject("Explosion", data); - this.field_92102_a.setTagCompound(tag); + nbttagcompound2.setIntArray("Colors", aint1); + nbttagcompound2.setByte("Type", b0); + nbttagcompound.setTag("Explosion", nbttagcompound2); + this.field_92102_a.setTagCompound(nbttagcompound); return true; } else if (j == 0 && i == 0 && l == 1 && k > 0 && k == i1) @@ -1065,7 +1168,7 @@ public abstract class CraftingRegistry else if (itemstack1.getItem() == Items.firework_charge) { this.field_92102_a = itemstack1.copy(); - this.field_92102_a.size = 1; + this.field_92102_a.stackSize = 1; } } } @@ -1079,15 +1182,15 @@ public abstract class CraftingRegistry if (this.field_92102_a != null && this.field_92102_a.hasTagCompound()) { - TagObject tag = this.field_92102_a.getTagCompound().getObject("Explosion"); + NBTTagCompound nbttagcompound4 = this.field_92102_a.getTagCompound().getCompoundTag("Explosion"); - if (tag == null) + if (nbttagcompound4 == null) { return false; } else { - tag.setIntArray("FadeColors", aint); + nbttagcompound4.setIntArray("FadeColors", aint); return true; } } @@ -1167,7 +1270,7 @@ public abstract class CraftingRegistry { ItemStack itemstack1 = (ItemStack)list.get(0); - if (itemstack.getItem() != itemstack1.getItem() || itemstack1.size != 1 || itemstack.size != 1 || !itemstack1.getItem().isDamageable()) + if (itemstack.getItem() != itemstack1.getItem() || itemstack1.stackSize != 1 || itemstack.stackSize != 1 || !itemstack1.getItem().isDamageable()) { return false; } @@ -1197,7 +1300,7 @@ public abstract class CraftingRegistry { ItemStack itemstack1 = (ItemStack)list.get(0); - if (itemstack.getItem() != itemstack1.getItem() || itemstack1.size != 1 || itemstack.size != 1 || !itemstack1.getItem().isDamageable()) + if (itemstack.getItem() != itemstack1.getItem() || itemstack1.stackSize != 1 || itemstack.stackSize != 1 || !itemstack1.getItem().isDamageable()) { return null; } @@ -1210,7 +1313,7 @@ public abstract class CraftingRegistry ItemStack itemstack2 = (ItemStack)list.get(0); ItemStack itemstack3 = (ItemStack)list.get(1); - if (itemstack2.getItem() == itemstack3.getItem() && itemstack2.size == 1 && itemstack3.size == 1 && itemstack2.getItem().isDamageable()) + if (itemstack2.getItem() == itemstack3.getItem() && itemstack2.stackSize == 1 && itemstack3.stackSize == 1 && itemstack2.getItem().isDamageable()) { Item item = itemstack2.getItem(); int j = item.getMaxDamage() - itemstack2.getItemDamage(); @@ -1330,7 +1433,7 @@ public abstract class CraftingRegistry } itemstack = itemstack1.copy(); - itemstack.size = 1; + itemstack.stackSize = 1; if (itemarmor.hasColor(itemstack1)) { @@ -1430,7 +1533,7 @@ public abstract class CraftingRegistry /** Is the ItemStack that you get when craft the recipe. */ private final ItemStack recipeOutput; - private boolean copyIngredientTag; + private boolean copyIngredientNBT; public ShapedRecipes(int width, int height, ItemStack[] p_i1917_3_, ItemStack output) { @@ -1467,9 +1570,9 @@ public abstract class CraftingRegistry */ public boolean matches(InventoryCrafting inv, World worldIn) { - for (int i = 0; i <= inv.getWidth() - this.recipeWidth; ++i) + for (int i = 0; i <= 3 - this.recipeWidth; ++i) { - for (int j = 0; j <= inv.getHeight() - this.recipeHeight; ++j) + for (int j = 0; j <= 3 - this.recipeHeight; ++j) { if (this.checkMatch(inv, i, j, true)) { @@ -1489,43 +1592,43 @@ public abstract class CraftingRegistry /** * Checks if the region of a crafting inventory is match for the recipe. */ - private boolean checkMatch(InventoryCrafting inv, int xPos, int yPos, boolean mirror) + private boolean checkMatch(InventoryCrafting p_77573_1_, int p_77573_2_, int p_77573_3_, boolean p_77573_4_) { - for (int x = 0; x < inv.getWidth(); ++x) + for (int i = 0; i < 3; ++i) { - for (int y = 0; y < inv.getHeight(); ++y) + for (int j = 0; j < 3; ++j) { - int rx = x - xPos; - int ry = y - yPos; - ItemStack stack = null; + int k = i - p_77573_2_; + int l = j - p_77573_3_; + ItemStack itemstack = null; - if (rx >= 0 && ry >= 0 && rx < this.recipeWidth && ry < this.recipeHeight) + if (k >= 0 && l >= 0 && k < this.recipeWidth && l < this.recipeHeight) { - if (mirror) + if (p_77573_4_) { - stack = this.recipeItems[this.recipeWidth - rx - 1 + ry * this.recipeWidth]; + itemstack = this.recipeItems[this.recipeWidth - k - 1 + l * this.recipeWidth]; } else { - stack = this.recipeItems[rx + ry * this.recipeWidth]; + itemstack = this.recipeItems[k + l * this.recipeWidth]; } } - ItemStack ingredient = inv.getStackInRowAndColumn(x, y); + ItemStack itemstack1 = p_77573_1_.getStackInRowAndColumn(i, j); - if (ingredient != null || stack != null) + if (itemstack1 != null || itemstack != null) { - if (ingredient == null && stack != null || ingredient != null && stack == null) + if (itemstack1 == null && itemstack != null || itemstack1 != null && itemstack == null) { return false; } - if (stack.getItem() != ingredient.getItem()) + if (itemstack.getItem() != itemstack1.getItem()) { return false; } - if (stack.getMetadata() != 32767 && stack.getMetadata() != ingredient.getMetadata()) + if (itemstack.getMetadata() != 32767 && itemstack.getMetadata() != itemstack1.getMetadata()) { return false; } @@ -1543,7 +1646,7 @@ public abstract class CraftingRegistry { ItemStack itemstack = this.getRecipeOutput().copy(); - if (this.copyIngredientTag) + if (this.copyIngredientNBT) { for (int i = 0; i < inv.getSizeInventory(); ++i) { @@ -1551,7 +1654,7 @@ public abstract class CraftingRegistry if (itemstack1 != null && itemstack1.hasTagCompound()) { - itemstack.setTagCompound(itemstack1.getTagCompound().copy()); + itemstack.setTagCompound((NBTTagCompound)itemstack1.getTagCompound().copy()); } } } diff --git a/common/src/main/java/common/init/DecoType.java b/common/src/common/init/DecoType.java similarity index 100% rename from common/src/main/java/common/init/DecoType.java rename to common/src/common/init/DecoType.java diff --git a/common/src/main/java/common/init/DispenserRegistry.java b/common/src/common/init/DispenserRegistry.java similarity index 75% rename from common/src/main/java/common/init/DispenserRegistry.java rename to common/src/common/init/DispenserRegistry.java index db74a2a..3f161a1 100755 --- a/common/src/main/java/common/init/DispenserRegistry.java +++ b/common/src/common/init/DispenserRegistry.java @@ -1,11 +1,10 @@ package common.init; import common.block.Block; -import common.block.Material; -import common.block.liquid.BlockDynamicLiquid; -import common.block.liquid.BlockLiquid; -import common.block.tech.BlockDispenser; -import common.block.tech.BlockTNT; +import common.block.BlockDispenser; +import common.block.BlockDynamicLiquid; +import common.block.BlockLiquid; +import common.block.BlockTNT; import common.color.DyeColor; import common.dispenser.BehaviorDefaultDispenseItem; import common.dispenser.BehaviorProjectileDispense; @@ -33,6 +32,7 @@ import common.item.ItemDye; import common.item.ItemMonsterPlacer; import common.item.ItemPotion; import common.item.ItemStack; +import common.material.Material; import common.rng.Random; import common.tileentity.TileEntityDispenser; import common.util.BlockPos; @@ -138,7 +138,7 @@ public abstract class DispenserRegistry { double d1 = (double)((float)source.getBlockPos().getY() + 0.2F); double d2 = source.getZ() + (double)enumfacing.getFrontOffsetZ(); Entity entity = ItemMonsterPlacer.spawnCreature(source.getWorld(), ((ItemMonsterPlacer)stack.getItem()).getSpawnedId(), - d0, d1, d2, false); + d0, d1, d2); if (entity instanceof EntityLiving && stack.hasDisplayName()) { @@ -149,8 +149,8 @@ public abstract class DispenserRegistry { return stack; } }; - for(EntityInfo egg : EntityRegistry.SPAWN_EGGS.values()) { - REGISTRY.putObject(ItemRegistry.getRegisteredItem(egg.id().toLowerCase() + "_spawner"), + for(EntityEggInfo egg : EntityRegistry.SPAWN_EGGS.values()) { + REGISTRY.putObject(ItemRegistry.getRegisteredItem(egg.id.toLowerCase() + "_spawner"), disp); } REGISTRY.putObject(Items.fireworks, new BehaviorDefaultDispenseItem() @@ -205,16 +205,16 @@ public abstract class DispenserRegistry { double d1 = source.getY() + (double)((float)enumfacing.getFrontOffsetY() * 1.125F); double d2 = source.getZ() + (double)((float)enumfacing.getFrontOffsetZ() * 1.125F); BlockPos blockpos = source.getBlockPos().offset(enumfacing); - Block block = world.getState(blockpos).getBlock(); + Material material = world.getState(blockpos).getBlock().getMaterial(); double d3; - if (block.getMaterial().isColdLiquid()) + if (material.isColdLiquid()) { d3 = 1.0D; } else { - if (block != Blocks.air || !world.getState(blockpos.down()).getBlock().getMaterial().isColdLiquid()) + if (!Material.air.equals(material) || !world.getState(blockpos.down()).getBlock().getMaterial().isColdLiquid()) { return this.field_150842_b.dispense(source, stack); } @@ -243,7 +243,7 @@ public abstract class DispenserRegistry { if (itembucket.tryPlaceContainedLiquid(source.getWorld(), blockpos)) { stack.setItem(Items.bucket); - stack.size = 1; + stack.stackSize = 1; return stack; } else @@ -256,7 +256,7 @@ public abstract class DispenserRegistry { // REGISTRY.putObject(Items.water_bucket, ibehaviordispenseitem); // REGISTRY.putObject(Items.fluid_bucket, ibehaviordispenseitem); for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { - REGISTRY.putObject(ItemRegistry.getRegisteredItem(BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)) + + REGISTRY.putObject(ItemRegistry.getRegisteredItem(BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)) + "_bucket"), ibehaviordispenseitem); } REGISTRY.putObject(Items.bucket, new BehaviorDefaultDispenseItem() @@ -283,7 +283,7 @@ public abstract class DispenserRegistry { // else if (material.isLiquid() && block instanceof BlockLiquid && ((Integer)iblockstate.getValue(BlockLiquid.LEVEL)).intValue() == 0) { - item = ItemRegistry.getRegisteredItem(BlockRegistry.getNameFromBlock(block instanceof BlockDynamicLiquid + item = ItemRegistry.getRegisteredItem(BlockRegistry.REGISTRY.getNameForObject(block instanceof BlockDynamicLiquid ? FluidRegistry.getStaticBlock((BlockDynamicLiquid)block) : block) + "_bucket"); // Items.fluid_bucket; // meta = FluidRegistry.getFluidMeta((BlockLiquid)iblockstate.getBlock()); @@ -300,10 +300,10 @@ public abstract class DispenserRegistry { world.setBlockToAir(blockpos); - if (--stack.size == 0) + if (--stack.stackSize == 0) { stack.setItem(item); - stack.size = 1; + stack.stackSize = 1; } else if (((TileEntityDispenser)source.getBlockTileEntity()).addItemStack(new ItemStack(item)) < 0) { @@ -327,7 +327,7 @@ public abstract class DispenserRegistry { if (stack.attemptDamageItem(1, world.rand)) { - stack.size = 0; + stack.stackSize = 0; } } else if (world.getState(blockpos).getBlock() == Blocks.tnt) @@ -404,9 +404,112 @@ public abstract class DispenserRegistry { EntityTnt entitytntprimed = new EntityTnt(world, (double)blockpos.getX() + 0.5D, (double)blockpos.getY(), (double)blockpos.getZ() + 0.5D, (EntityLiving)null, stack.getMetadata()); world.spawnEntityInWorld(entitytntprimed); world.playSoundAtEntity(entitytntprimed, SoundEvent.FUSE, 1.0F); - --stack.size; + --stack.stackSize; return stack; } }); +// REGISTRY.putObject(Items.skull, new BehaviorDefaultDispenseItem() +// { +// private boolean field_179240_b = true; +// protected ItemStack dispenseStack(IBlockSource source, ItemStack stack) +// { +// World world = source.getWorld(); +// EnumFacing enumfacing = BlockDispenser.getFacing(source.getBlockMetadata()); +// BlockPos blockpos = source.getBlockPos().offset(enumfacing); +// BlockSkull blockskull = Blocks.skull; +// +// if (world.isAirBlock(blockpos) && blockskull.canDispenserPlace(world, blockpos, stack)) +// { +// if (!world.client) +// { +// world.setBlockState(blockpos, blockskull.getDefaultState().withProperty(BlockSkull.FACING, EnumFacing.UP), 3); +// TileEntity tileentity = world.getTileEntity(blockpos); +// +// if (tileentity instanceof TileEntitySkull) +// { +// if (stack.getMetadata() == 3) +// { +// String user = null; +// +// if (stack.hasTagCompound()) +// { +// NBTTagCompound nbttagcompound = stack.getTagCompound(); +// +// if (nbttagcompound.hasKey("SkullOwner", 8) && nbttagcompound.getString("SkullOwner").length() > 0) +// { +// user = nbttagcompound.getString("SkullOwner"); +// } +// } +// +// ((TileEntitySkull)tileentity).setUser(user); +// } +// else +// { +// ((TileEntitySkull)tileentity).setType(stack.getMetadata()); +// } +// +// ((TileEntitySkull)tileentity).setSkullRotation(enumfacing.getOpposite().getHorizontalIndex() * 4); +//// Blocks.skull.checkWitherSpawn(world, blockpos, (TileEntitySkull)tileentity); +// } +// +// --stack.stackSize; +// } +// } +// else +// { +// this.field_179240_b = false; +// } +// +// return stack; +// } +// protected void playDispenseSound(IBlockSource source) +// { +// if (this.field_179240_b) +// { +// source.getWorld().playAuxSFX(1000, source.getBlockPos(), 0); +// } +// else +// { +// source.getWorld().playAuxSFX(1001, source.getBlockPos(), 0); +// } +// } +// }); +// REGISTRY.putObject(ItemRegistry.getItemFromBlock(Blocks.pumpkin), new BehaviorDefaultDispenseItem() +// { +// private boolean field_179241_b = true; +// protected ItemStack dispenseStack(IBlockSource source, ItemStack stack) +// { +// World world = source.getWorld(); +// BlockPos blockpos = source.getBlockPos().offset(BlockDispenser.getFacing(source.getBlockMetadata())); +// BlockPumpkin blockpumpkin = (BlockPumpkin)Blocks.pumpkin; +// +// if (world.isAirBlock(blockpos) && blockpumpkin.canDispenserPlace(world, blockpos)) +// { +// if (!world.client) +// { +// world.setBlockState(blockpos, blockpumpkin.getDefaultState(), 3); +// } +// +// --stack.stackSize; +// } +// else +// { +// this.field_179241_b = false; +// } +// +// return stack; +// } +// protected void playDispenseSound(IBlockSource source) +// { +// if (this.field_179241_b) +// { +// source.getWorld().playAuxSFX(1000, source.getBlockPos(), 0); +// } +// else +// { +// source.getWorld().playAuxSFX(1001, source.getBlockPos(), 0); +// } +// } +// }); } } diff --git a/common/src/common/init/EntityEggInfo.java b/common/src/common/init/EntityEggInfo.java new file mode 100755 index 0000000..87351b9 --- /dev/null +++ b/common/src/common/init/EntityEggInfo.java @@ -0,0 +1,15 @@ +package common.init; + +public class EntityEggInfo { + public final String id; + public final String origin; + public final int color1; + public final int color2; + + public EntityEggInfo(String id, String origin, int color1, int color2) { + this.id = id; + this.origin = origin; + this.color1 = color1; + this.color2 = color2; + } +} diff --git a/common/src/main/java/common/init/EntityRegistry.java b/common/src/common/init/EntityRegistry.java similarity index 93% rename from common/src/main/java/common/init/EntityRegistry.java rename to common/src/common/init/EntityRegistry.java index e0c9b95..7e58afe 100755 --- a/common/src/main/java/common/init/EntityRegistry.java +++ b/common/src/common/init/EntityRegistry.java @@ -9,7 +9,6 @@ import common.entity.animal.EntityBat; import common.entity.animal.EntityChicken; import common.entity.animal.EntityCow; import common.entity.animal.EntityDragon; -import common.entity.animal.EntityFox; import common.entity.animal.EntityHorse; import common.entity.animal.EntityMooshroom; import common.entity.animal.EntityMouse; @@ -50,7 +49,7 @@ import common.entity.projectile.EntitySnowball; import common.entity.types.EntityLiving; import common.entity.types.IObjectData; import common.log.Log; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.world.World; public abstract class EntityRegistry { @@ -59,7 +58,7 @@ public abstract class EntityRegistry { private static final Map> ID_TO_CLASS = Maps.>newHashMap(); private static final Map, Integer> CLASS_TO_ID = Maps., Integer>newHashMap(); // private static final Map STRING_TO_ID = Maps.newHashMap(); - public static final Map SPAWN_EGGS = Maps.newLinkedHashMap(); + public static final Map SPAWN_EGGS = Maps.newLinkedHashMap(); private static final Map STRING_TO_NAME = Maps.newHashMap(); private static boolean register; @@ -90,7 +89,7 @@ public abstract class EntityRegistry { } else { // String name = clazz.getSimpleName().substring(6); - SPAWN_EGGS.put(name, new EntityInfo(name, origin, eggColor, spotColor)); + SPAWN_EGGS.put(name, new EntityEggInfo(name, origin, eggColor, spotColor)); } } @@ -118,14 +117,19 @@ public abstract class EntityRegistry { return entity; } - public static Entity createFromTags(TagObject tag, World world) { + public static Entity createEntityFromNBT(NBTTagCompound nbt, World worldIn) { Entity entity = null; +// if("Minecart".equals(nbt.getString("id"))) { +// nbt.setString("id", EntityMinecart.EnumMinecartType.byNetworkID(nbt.getInteger("Type")).getName()); +// nbt.removeTag("Type"); +// } + try { - Class oclass = (Class)STRING_TO_CLASS.get(tag.getString("id")); + Class oclass = (Class)STRING_TO_CLASS.get(nbt.getString("id")); if(oclass != null) { - entity = (Entity)oclass.getConstructor(World.class).newInstance(world); + entity = (Entity)oclass.getConstructor(World.class).newInstance(worldIn); } } catch(Exception exception) { @@ -133,10 +137,10 @@ public abstract class EntityRegistry { } if(entity != null) { - entity.readTags(tag); + entity.readFromNBT(nbt); } else { - Log.TICK.warn("Ignoriere Objekt mit Name " + tag.getString("id")); + Log.JNI.warn("Ignoriere Objekt mit Name " + nbt.getString("id")); } return entity; @@ -157,7 +161,7 @@ public abstract class EntityRegistry { } if(entity == null) { - Log.TICK.warn("Ignoriere Objekt mit ID " + entityID); + Log.JNI.warn("Ignoriere Objekt mit ID " + entityID); } return entity; @@ -191,7 +195,7 @@ public abstract class EntityRegistry { } if(entity == null) { - Log.TICK.warn("Ignoriere Objekt mit ID " + entityID); + Log.JNI.warn("Ignoriere Objekt mit ID " + entityID); } return entity; @@ -263,7 +267,6 @@ public abstract class EntityRegistry { registerEntity("Horse", EntityHorse.class, "terra", "Pferd", 12623485, 15656192); registerEntity("Rabbit", EntityRabbit.class, "terra", "Kaninchen", 10051392, 7555121); registerEntity("Mouse", EntityMouse.class, "terra", "Maus", 0x606060, 0xb0b0b0); - registerEntity("Fox", EntityFox.class, "terra", "Fuchs", 0xae5300, 0x622f00); for(int z = 0; z < SpeciesRegistry.SPECIMEN.size(); z++) { SpeciesInfo info = SpeciesRegistry.SPECIMEN.get(z); diff --git a/common/src/common/init/FlammabilityRegistry.java b/common/src/common/init/FlammabilityRegistry.java new file mode 100755 index 0000000..54f8f47 --- /dev/null +++ b/common/src/common/init/FlammabilityRegistry.java @@ -0,0 +1,34 @@ +package common.init; + +import common.block.Block; + +public abstract class FlammabilityRegistry { + private static void setFlammable(Block blockIn, int encouragement, int flammability) { + Blocks.fire.setFireInfo(blockIn, encouragement, flammability); + } + + static void register() { + for(WoodType wood : WoodType.values()) { + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_planks"), 5, 20); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_slab"), 5, 20); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_stairs"), 5, 20); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_fence"), 5, 20); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_fence_gate"), 5, 20); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_log"), 5, 5); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_leaves"), 30, 60); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_sapling"), 15, 100); + } + setFlammable(Blocks.bookshelf, 30, 20); + setFlammable(Blocks.tnt, 15, 100); + setFlammable(Blocks.tallgrass, 60, 100); + setFlammable(Blocks.double_plant, 60, 100); + setFlammable(Blocks.flower, 60, 100); + setFlammable(Blocks.deadbush, 60, 100); + setFlammable(Blocks.dry_leaves, 60, 100); + setFlammable(Blocks.wool, 30, 60); + setFlammable(Blocks.vine, 15, 100); + setFlammable(Blocks.coal_block, 5, 5); + setFlammable(Blocks.hay_block, 60, 20); + setFlammable(Blocks.carpet, 60, 20); + } +} diff --git a/common/src/main/java/common/init/FluidRegistry.java b/common/src/common/init/FluidRegistry.java similarity index 89% rename from common/src/main/java/common/init/FluidRegistry.java rename to common/src/common/init/FluidRegistry.java index ad5b6ac..e585f54 100755 --- a/common/src/main/java/common/init/FluidRegistry.java +++ b/common/src/common/init/FluidRegistry.java @@ -4,16 +4,16 @@ import java.util.List; import java.util.Map; import common.block.Block; -import common.block.Material; -import common.block.liquid.BlockDynamicLiquid; -import common.block.liquid.BlockLiquid; -import common.block.liquid.BlockStaticLiquid; +import common.block.BlockDynamicLiquid; +import common.block.BlockLiquid; +import common.block.BlockStaticLiquid; import common.collect.Lists; import common.collect.Maps; +import common.material.Material; public abstract class FluidRegistry { public static enum LiquidType { - COLD(Material.COLD), HOT(Material.HOT), WATER(Material.WATER), LAVA(Material.LAVA); + COLD(Material.coldFluid), HOT(Material.hotFluid), WATER(Material.water), LAVA(Material.lava); public final Material material; diff --git a/common/src/main/java/common/init/ItemRegistry.java b/common/src/common/init/ItemRegistry.java similarity index 83% rename from common/src/main/java/common/init/ItemRegistry.java rename to common/src/common/init/ItemRegistry.java index 83b991e..18a101d 100755 --- a/common/src/main/java/common/init/ItemRegistry.java +++ b/common/src/common/init/ItemRegistry.java @@ -4,23 +4,22 @@ import java.util.Map; import java.util.Set; import java.util.function.Function; -import common.attributes.UsageSlot; import common.block.Block; -import common.block.artificial.BlockBed; -import common.block.artificial.BlockDoor; -import common.block.artificial.BlockFence; -import common.block.artificial.BlockSlab; -import common.block.artificial.BlockStoneBrick; -import common.block.artificial.BlockWall; -import common.block.foliage.BlockDoublePlant; -import common.block.foliage.BlockFlower; -import common.block.foliage.BlockLeaves; -import common.block.foliage.BlockSapling; -import common.block.natural.BlockDirt; -import common.block.natural.BlockOre; -import common.block.natural.BlockSand; -import common.block.natural.BlockSandStone; -import common.block.tech.BlockButton; +import common.block.BlockBed; +import common.block.BlockButton; +import common.block.BlockDirt; +import common.block.BlockDoor; +import common.block.BlockDoublePlant; +import common.block.BlockFence; +import common.block.BlockFlower; +import common.block.BlockLeaves; +import common.block.BlockOre; +import common.block.BlockSand; +import common.block.BlockSandStone; +import common.block.BlockSapling; +import common.block.BlockSlab; +import common.block.BlockStoneBrick; +import common.block.BlockWall; import common.collect.Maps; import common.collect.Sets; import common.color.DyeColor; @@ -100,20 +99,21 @@ import common.item.ItemPotion; import common.item.ItemPressurePlate; import common.item.ItemRecord; import common.item.ItemRedstone; -import common.item.ItemSmallBlock; +import common.item.ItemReed; import common.item.ItemRod; import common.item.ItemSaddle; import common.item.ItemSeedFood; import common.item.ItemSeeds; import common.item.ItemShears; import common.item.ItemSign; +import common.item.ItemSkull; import common.item.ItemSlab; import common.item.ItemSmall; import common.item.ItemSnow; import common.item.ItemSnowball; import common.item.ItemSoup; import common.item.ItemSpaceNavigator; -import common.item.ItemShovel; +import common.item.ItemSpade; import common.item.ItemStack; import common.item.ItemStick; import common.item.ItemSword; @@ -137,10 +137,6 @@ public abstract class ItemRegistry { return item == null ? 0 : REGISTRY.getIDForObject(item); } - public static String getNameFromItem(Item item) { - return REGISTRY.getNameForObject(item); - } - public static Item getItemById(int id) { return REGISTRY.getObjectById(id); } @@ -153,30 +149,6 @@ public abstract class ItemRegistry { return REGISTRY.getObject(name); } - public static ItemStack getFromIdName(String name, ItemStack def) { - if(name == null) - return def; - String[] tok = name.split(":"); - if(tok.length < 1 || tok.length > 2) - return def; - Item item = REGISTRY.getObject(tok[0]); - if(item == null) - return def; - short data = 0; - if(tok.length == 2) { - try { - int i = Integer.parseUnsignedInt(tok[1]); - if(i >= 32768) - return def; - data = (short)i; - } - catch(NumberFormatException e) { - return def; - } - } - return new ItemStack(item, 1, data); - } - private static ItemBlock registerFlat(Block block) { ItemBlock item = new ItemBlock(block, ""); registerBlock(block, item); @@ -190,13 +162,13 @@ public abstract class ItemRegistry { } private static void registerBlock(Block block, ItemBlock item) { - REGISTRY.register(BlockRegistry.getIdFromBlock(block), BlockRegistry.getNameFromBlock(block), item); + REGISTRY.register(BlockRegistry.getIdFromBlock(block), BlockRegistry.REGISTRY.getNameForObject(block), item); BLOCKMAP.put(block, item); } private static void registerSpecial(Block block) { if(BLOCKMAP.containsKey(block) || SPECIALIZED.contains(block)) - throw new IllegalArgumentException("Block " + BlockRegistry.getNameFromBlock(block) + " ist bereits registriert"); + throw new IllegalArgumentException("Block " + BlockRegistry.REGISTRY.getNameForObject(block) + " ist bereits registriert"); SPECIALIZED.add(block); } @@ -210,13 +182,13 @@ public abstract class ItemRegistry { if(item.getBlock() == null) throw new IllegalArgumentException("Unbenanntes Item benötigt einen Block"); registerSpecial(item.getBlock()); - REGISTRY.register(BlockRegistry.getIdFromBlock(item.getBlock()), BlockRegistry.getNameFromBlock(item.getBlock()), item); + REGISTRY.register(BlockRegistry.getIdFromBlock(item.getBlock()), BlockRegistry.REGISTRY.getNameForObject(item.getBlock()), item); } private static void registerTools(ToolMaterial material, String name, String prefix) { // String loc = name.substring(0, 1).toUpperCase() + name.substring(1); if(material.hasTools()) { - registerItem(name + "_shovel", (new ItemShovel(material)).setDisplay(prefix + "schaufel")); + registerItem(name + "_shovel", (new ItemSpade(material)).setDisplay(prefix + "schaufel")); registerItem(name + "_pickaxe", (new ItemPickaxe(material)).setDisplay(prefix + "spitzhacke")); registerItem(name + "_axe", (new ItemAxe(material)).setDisplay(prefix + "axt")); registerItem(name + "_hoe", (new ItemHoe(material)).setDisplay(prefix + "hacke")); @@ -229,10 +201,10 @@ public abstract class ItemRegistry { registerItem(name + "_sword", (new ItemSword(material)).setDisplay(prefix + "schwert")); } if(material.hasArmor()) { - registerItem(name + "_helmet", (new ItemArmor(material, name, UsageSlot.HEAD)).setDisplay(prefix == null ? "Kappe" : prefix + "helm")); - registerItem(name + "_chestplate", (new ItemArmor(material, name, UsageSlot.BODY)).setDisplay(prefix == null ? "Jacke" : prefix + "brustpanzer")); - registerItem(name + "_leggings", (new ItemArmor(material, name, UsageSlot.LEGS)).setDisplay(prefix == null ? "Hose" : prefix + "beinschutz")); - registerItem(name + "_boots", (new ItemArmor(material, name, UsageSlot.FEET)).setDisplay(prefix == null ? "Stiefel" : prefix + "stiefel")); + registerItem(name + "_helmet", (new ItemArmor(material, name, 0)).setDisplay(prefix == null ? "Kappe" : prefix + "helm")); + registerItem(name + "_chestplate", (new ItemArmor(material, name, 1)).setDisplay(prefix == null ? "Jacke" : prefix + "brustpanzer")); + registerItem(name + "_leggings", (new ItemArmor(material, name, 2)).setDisplay(prefix == null ? "Hose" : prefix + "beinschutz")); + registerItem(name + "_boots", (new ItemArmor(material, name, 3)).setDisplay(prefix == null ? "Stiefel" : prefix + "stiefel")); } } @@ -361,7 +333,7 @@ public abstract class ItemRegistry { })).setDisplay("Felsen")); for(BlockLeaves leaves : BlockLeaves.LEAVES) { - registerBlock(leaves, new ItemLeaves(leaves)); // .setDisplay(BlockRegistry.getNameFromBlock(leaves))); + registerBlock(leaves, new ItemLeaves(leaves)); // .setDisplay(BlockRegistry.REGISTRY.getNameForObject(leaves))); } for(BlockSlab slab : BlockSlab.SLABS) { registerBlock(slab, new ItemSlab(slab)); @@ -380,13 +352,13 @@ public abstract class ItemRegistry { Item bucket = (new ItemBucket(null, false)).setDisplay("Eimer"); registerItem("bucket", bucket); for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { - registerItem(BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)) + + registerItem(BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)) + "_bucket", new ItemBucket(FluidRegistry.getFluidBlock(z), false).setDisplay("Eimer") .setContainerItem(bucket)); } registerItem("recursive_bucket", (new ItemBucket(null, true)).setDisplay("Unendlicher Eimer")); for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { - registerItem("recursive_" + BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)) + + registerItem("recursive_" + BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)) + "_bucket", new ItemBucket(FluidRegistry.getFluidBlock(z), true).setDisplay("Flutender Eimer")); } registerItem("milk_bucket", (new ItemBucketMilk()).setDisplay("Milch").setContainerItem(bucket)); @@ -399,8 +371,8 @@ public abstract class ItemRegistry { registerItem("hopper_minecart", (new ItemMinecart(EntityCart.EnumMinecartType.HOPPER)).setDisplay("Trichterlore")); registerItem("tnt_minecart", (new ItemMinecart(EntityCart.EnumMinecartType.TNT)).setDisplay("TNT-Lore") .setColor(TextColor.RED)); - for(EntityInfo egg : EntityRegistry.SPAWN_EGGS.values()) { - registerItem(egg.id().toLowerCase() + "_spawner", (new ItemMonsterPlacer(egg.id())) + for(EntityEggInfo egg : EntityRegistry.SPAWN_EGGS.values()) { + registerItem(egg.id.toLowerCase() + "_spawner", (new ItemMonsterPlacer(egg.id)) .setDisplay("Spawner").setMaxStackSize(ItemStack.MAX_SIZE)); } for(SpeciesInfo species : SpeciesRegistry.SPECIMEN) { @@ -414,37 +386,35 @@ public abstract class ItemRegistry { registerItem("wand", (new ItemEditWand()).setDisplay("Bearbeitungswerkzeug")); registerItem("info_wand", (new ItemInfoWand()).setDisplay("Infowerkzeug")); registerItem("lightning_wand", (new ItemLightning()).setDisplay("Geladenes Zepter")); - registerItem("banhammer", (new ItemBanHammer()).setDisplay("Hammer der Verbannung").setTab(CheatTab.TOOLS)); - registerItem("key", (new ItemKey()).setDisplay("Schlüssel").setTab(CheatTab.TOOLS).setMaxStackSize(128)); + registerItem("banhammer", (new ItemBanHammer()).setDisplay("Hammer der Verbannung").setTab(CheatTab.tabTools)); + registerItem("key", (new ItemKey()).setDisplay("Schlüssel").setTab(CheatTab.tabTools).setMaxStackSize(128)); registerItem("die", (new ItemDie()).setDisplay("Würfel").setMaxStackSize(128)); registerItem("chick_magnet", (new ItemMagnet(true)).setDisplay("Kükenmagnet")); registerItem("magnet", (new ItemMagnet(false)).setDisplay("Magnet")); - registerItem("camera", (new ItemCamera()).setDisplay("Kamera").setTab(CheatTab.TOOLS)); + registerItem("camera", (new ItemCamera()).setDisplay("Kamera").setTab(CheatTab.tabTools)); for(Weather weather : Weather.values()) { - registerItem("weather_token_" + weather.getName(), new ItemWeatherToken(weather).setDisplay("Wetterkristall").setTab(CheatTab.TOOLS)); + registerItem("weather_token_" + weather.getName(), new ItemWeatherToken(weather).setDisplay("Wetterkristall").setTab(CheatTab.tabTools)); } - - registerItem("flint_and_steel", (new ItemFlintAndSteel(Blocks.fire)).setDisplay("Feuerzeug")); - registerItem("burning_soul", (new ItemFlintAndSteel(Blocks.soul_fire)).setDisplay("Brennende Seele")); - registerItem("dark_lighter", (new ItemFlintAndSteel(Blocks.black_fire)).setDisplay("Verdunkelndes Feuerzeug")); + + registerItem("flint_and_steel", (new ItemFlintAndSteel()).setDisplay("Feuerzeug")); registerItem("apple", (new ItemFood(4, false)).setDisplay("Apfel").setMaxStackSize(128)); registerItem("bow", (new ItemBow()).setDisplay("Bogen")); registerItem("boltgun", (new ItemBoltgun()).setDisplay("Bolter")); registerItem("bolt", (new ItemAmmo(5, 1.0f, 128)).setDisplay("Bolter-Munition")); - registerItem("arrow", (new Item()).setDisplay("Pfeil").setTab(CheatTab.COMBAT).setMaxStackSize(128)); + registerItem("arrow", (new Item()).setDisplay("Pfeil").setTab(CheatTab.tabCombat).setMaxStackSize(128)); Item coal = (new ItemCoal()).setDisplay("Kohle"); registerItem("coal", coal); - registerItem("stick", (new ItemStick()).setDisplay("Stock").setTab(CheatTab.MATERIALS).setMaxStackSize(256)); - registerItem("bowl", (new ItemSmall()).setDisplay("Schüssel").setTab(CheatTab.MISC)); + registerItem("stick", (new ItemStick()).setDisplay("Stock").setTab(CheatTab.tabMaterials).setMaxStackSize(256)); + registerItem("bowl", (new ItemSmall()).setDisplay("Schüssel").setTab(CheatTab.tabMisc)); registerItem("mushroom_stew", (new ItemSoup(6)).setDisplay("Pilzsuppe")); - registerItem((new ItemSmallBlock(Blocks.string)).setDisplay("Faden").setTab(CheatTab.TECHNOLOGY).setMaxStackSize(1024)); - registerItem("feather", (new Item()).setDisplay("Feder").setTab(CheatTab.MATERIALS).setMaxStackSize(512)); - registerItem("gunpowder", (new Item()).setDisplay("Schwarzpulver").setPotionEffect(PotionHelper.gunpowderEffect).setTab(CheatTab.MATERIALS).setMaxStackSize(256)); + registerItem((new ItemReed(Blocks.string)).setDisplay("Faden").setTab(CheatTab.tabTech).setMaxStackSize(1024)); + registerItem("feather", (new Item()).setDisplay("Feder").setTab(CheatTab.tabMaterials).setMaxStackSize(512)); + registerItem("gunpowder", (new Item()).setDisplay("Schwarzpulver").setPotionEffect(PotionHelper.gunpowderEffect).setTab(CheatTab.tabMaterials).setMaxStackSize(256)); registerItem((new ItemSeeds(Blocks.wheat, Blocks.farmland)).setDisplay("Weizenkörner").setMaxStackSize(256)); - registerItem("wheats", (new Item()).setDisplay("Weizen").setTab(CheatTab.MATERIALS).setMaxStackSize(128)); + registerItem("wheats", (new Item()).setDisplay("Weizen").setTab(CheatTab.tabMaterials).setMaxStackSize(128)); registerItem("bread", (new ItemFood(5, false)).setDisplay("Brot")); - registerItem("flint", (new Item()).setDisplay("Feuerstein").setTab(CheatTab.MATERIALS).setMaxStackSize(128)); + registerItem("flint", (new Item()).setDisplay("Feuerstein").setTab(CheatTab.tabMaterials).setMaxStackSize(128)); registerItem("porkchop", (new ItemFood(3, true)).setDisplay("Rohes Schweinefleisch")); registerItem("cooked_porkchop", (new ItemFood(8, true)).setDisplay("Gebratenes Schweinefleisch")); registerItem("golden_apple", (new ItemAppleGold(4, false)).setPotionEffect(Potion.REGENERATION, 5, 1, 1.0F) @@ -457,27 +427,27 @@ public abstract class ItemRegistry { // registerItem("iron_door", (new ItemDoor(Blocks.iron_door)).setUnlocalizedName("doorIron")); registerItem((new ItemRedstone()).setDisplay("Redstone").setPotionEffect(PotionHelper.redstoneEffect).setMaxStackSize(256)); registerItem("snowball", (new ItemSnowball()).setDisplay("Schneeball").setMaxStackSize(128)); - registerItem("leather", (new Item()).setDisplay("Leder").setTab(CheatTab.MATERIALS)); - registerItem("brick", (new Item()).setDisplay("Ziegel").setTab(CheatTab.MATERIALS)); - registerItem("clay_ball", (new Item()).setDisplay("Ton").setTab(CheatTab.MATERIALS).setMaxStackSize(128)); - registerItem((new ItemSmallBlock(Blocks.reeds)).setDisplay("Zuckerrohr").setTab(CheatTab.PLANTS).setMaxStackSize(128)); - registerItem("paper", (new Item()).setDisplay("Papier").setTab(CheatTab.MATERIALS).setMaxStackSize(256)); - registerItem("book", (new ItemBook()).setDisplay("Buch").setTab(CheatTab.MISC)); - registerItem("slime_ball", (new Item()).setDisplay("Schleimball").setTab(CheatTab.MATERIALS).setMaxStackSize(128)); + registerItem("leather", (new Item()).setDisplay("Leder").setTab(CheatTab.tabMaterials)); + registerItem("brick", (new Item()).setDisplay("Ziegel").setTab(CheatTab.tabMaterials)); + registerItem("clay_ball", (new Item()).setDisplay("Ton").setTab(CheatTab.tabMaterials).setMaxStackSize(128)); + registerItem((new ItemReed(Blocks.reeds)).setDisplay("Zuckerrohr").setTab(CheatTab.tabPlants).setMaxStackSize(128)); + registerItem("paper", (new Item()).setDisplay("Papier").setTab(CheatTab.tabMaterials).setMaxStackSize(256)); + registerItem("book", (new ItemBook()).setDisplay("Buch").setTab(CheatTab.tabMisc)); + registerItem("slime_ball", (new Item()).setDisplay("Schleimball").setTab(CheatTab.tabMaterials).setMaxStackSize(128)); registerItem("egg", (new ItemEgg()).setDisplay("Ei").setMaxStackSize(128)); - registerItem("navigator", (new ItemSpaceNavigator()).setDisplay("Elektronischer Navigator").setTab(CheatTab.TOOLS)); - registerItem("exterminator", (new ItemExterminator()).setDisplay("Weltenzerstörer").setTab(CheatTab.TOOLS)); + registerItem("navigator", (new ItemSpaceNavigator()).setDisplay("Elektronischer Navigator").setTab(CheatTab.tabTools)); + registerItem("exterminator", (new ItemExterminator()).setDisplay("Weltenzerstörer").setTab(CheatTab.tabTools)); registerItem("fishing_rod", (new ItemFishingRod()).setDisplay("Angel")); registerItem("glowstone_dust", (new Item()).setDisplay("Glowstonestaub").setPotionEffect(PotionHelper.glowstoneEffect) - .setTab(CheatTab.MATERIALS).setMaxStackSize(256)); + .setTab(CheatTab.tabMaterials).setMaxStackSize(256)); registerItem("fish", (new ItemFishFood(false)).setDisplay("Fisch").setHasSubtypes(true)); registerItem("cooked_fish", (new ItemFishFood(true)).setDisplay("Fisch").setHasSubtypes(true)); Item dye = (new ItemDye()).setDisplay("Farbstoff").setMaxStackSize(512); registerItem("dye", dye); - registerItem("bone", (new ItemStick()).setDisplay("Knochen").setTab(CheatTab.MATERIALS).setMaxStackSize(128)); - registerItem("sugar", (new Item()).setDisplay("Zucker").setPotionEffect(PotionHelper.sugarEffect).setTab(CheatTab.MATERIALS).setMaxStackSize(512)); - registerItem((new ItemSmallBlock(Blocks.cake)).setMaxStackSize(1).setDisplay("Kuchen").setTab(CheatTab.DECORATION)); - registerItem((new ItemSmallBlock(Blocks.repeater)).setDisplay("Redstone-Verstärker").setTab(CheatTab.TECHNOLOGY)); + registerItem("bone", (new ItemStick()).setDisplay("Knochen").setTab(CheatTab.tabMaterials).setMaxStackSize(128)); + registerItem("sugar", (new Item()).setDisplay("Zucker").setPotionEffect(PotionHelper.sugarEffect).setTab(CheatTab.tabMaterials).setMaxStackSize(512)); + registerItem((new ItemReed(Blocks.cake)).setMaxStackSize(1).setDisplay("Kuchen").setTab(CheatTab.tabDeco)); + registerItem((new ItemReed(Blocks.repeater)).setDisplay("Redstone-Verstärker").setTab(CheatTab.tabTech)); registerItem("cookie", (new ItemFood(2, false)).setDisplay("Keks").setMaxStackSize(128)); registerItem("melon", (new ItemFood(2, false)).setDisplay("Melone")); registerItem((new ItemSeeds(Blocks.pumpkin_stem, Blocks.farmland)).setDisplay("Kürbiskerne").setMaxStackSize(256)); @@ -487,51 +457,51 @@ public abstract class ItemRegistry { registerItem("chicken", (new ItemFood(2, true)).setDisplay("Rohes Hühnchen")); registerItem("cooked_chicken", (new ItemFood(6, true)).setDisplay("Gebratenes Hühnchen")); registerItem("rotten_flesh", (new ItemFood(4, true)).setDisplay("Verrottetes Fleisch")); - registerItem("orb", (new ItemFragile()).setDisplay("Kugel").setTab(CheatTab.TOOLS)); - registerItem("blaze_rod", (new ItemRod()).setDisplay("Lohenrute").setTab(CheatTab.MATERIALS).setMaxStackSize(256)); - registerItem("ghast_tear", (new ItemTiny()).setDisplay("Ghastträne").setPotionEffect(PotionHelper.ghastTearEffect).setTab(CheatTab.MATERIALS).setMaxStackSize(256)); - registerItem("gold_nugget", (new ItemNugget()).setDisplay("Goldnugget").setTab(CheatTab.METALS).setMaxStackSize(256)); + registerItem("orb", (new ItemFragile()).setDisplay("Kugel").setTab(CheatTab.tabTools)); + registerItem("blaze_rod", (new ItemRod()).setDisplay("Lohenrute").setTab(CheatTab.tabMaterials).setMaxStackSize(256)); + registerItem("ghast_tear", (new ItemTiny()).setDisplay("Ghastträne").setPotionEffect(PotionHelper.ghastTearEffect).setTab(CheatTab.tabMaterials).setMaxStackSize(256)); + registerItem("gold_nugget", (new ItemNugget()).setDisplay("Goldnugget").setTab(CheatTab.tabMetals).setMaxStackSize(256)); registerItem((new ItemSeeds(Blocks.soul_wart, Blocks.soul_sand)).setDisplay("Seelenwarze").setPotionEffect("+4").setMaxStackSize(128)); registerItem("potion", (new ItemPotion()).setDisplay("Trank")); registerItem("glass_bottle", (new ItemGlassBottle()).setDisplay("Glasflasche")); registerItem("spider_eye", (new ItemFood(2, false)).setPotionEffect(Potion.POISON, 5, 0, 1.0F).setDisplay("Spinnenauge") .setPotionEffect(PotionHelper.spiderEyeEffect).setMaxStackSize(128)); registerItem("fermented_spider_eye", (new Item()).setDisplay("Fermentiertes Spinnenauge") - .setPotionEffect(PotionHelper.fermentedSpiderEyeEffect).setTab(CheatTab.MISC).setMaxStackSize(128)); + .setPotionEffect(PotionHelper.fermentedSpiderEyeEffect).setTab(CheatTab.tabMisc).setMaxStackSize(128)); registerItem("blaze_powder", (new Item()).setDisplay("Lohenstaub").setPotionEffect(PotionHelper.blazePowderEffect) - .setTab(CheatTab.MATERIALS).setMaxStackSize(256)); - registerItem("magma_cream", (new Item()).setDisplay("Magmacreme").setPotionEffect(PotionHelper.magmaCreamEffect).setTab(CheatTab.MATERIALS).setMaxStackSize(128)); - registerItem((new ItemSmallBlock(Blocks.brewing_stand)).setDisplay("Braustand").setTab(CheatTab.TECHNOLOGY)); - registerItem((new ItemSmallBlock(Blocks.cauldron)).setDisplay("Kessel").setTab(CheatTab.TECHNOLOGY)); + .setTab(CheatTab.tabMaterials).setMaxStackSize(256)); + registerItem("magma_cream", (new Item()).setDisplay("Magmacreme").setPotionEffect(PotionHelper.magmaCreamEffect).setTab(CheatTab.tabMaterials).setMaxStackSize(128)); + registerItem((new ItemReed(Blocks.brewing_stand)).setDisplay("Braustand").setTab(CheatTab.tabTech)); + registerItem((new ItemReed(Blocks.cauldron)).setDisplay("Kessel").setTab(CheatTab.tabTech)); registerItem("charged_orb", (new ItemChargedOrb()).setDisplay("Geladene Kugel")); registerItem("speckled_melon", (new Item()).setDisplay("Glitzernde Melone").setPotionEffect(PotionHelper.speckledMelonEffect) - .setTab(CheatTab.MISC)); + .setTab(CheatTab.tabMisc)); registerItem("experience_bottle", (new ItemExpBottle()).setDisplay("Erfahrungsfläschchen")); registerItem("fire_charge", (new ItemFireball()).setDisplay("Feuerkugel")); - registerItem("writable_book", (new Item()).setDisplay("Buch und Feder").setTab(CheatTab.TOOLS)); - registerItem("written_book", (new Item()).setDisplay("Beschriebenes Buch").setTab(CheatTab.MISC)); - Item emerald = (new Item()).setDisplay("Smaragd").setTab(CheatTab.METALS); + registerItem("writable_book", (new Item()).setDisplay("Buch und Feder").setTab(CheatTab.tabTools)); + registerItem("written_book", (new Item()).setDisplay("Beschriebenes Buch").setTab(CheatTab.tabMisc)); + Item emerald = (new Item()).setDisplay("Smaragd").setTab(CheatTab.tabMetals); registerItem("emerald", emerald); - registerItem((new ItemSmallBlock(Blocks.flower_pot)).setDisplay("Blumentopf").setTab(CheatTab.DECORATION)); + registerItem((new ItemReed(Blocks.flower_pot)).setDisplay("Blumentopf").setTab(CheatTab.tabDeco)); registerItem((new ItemSeedFood(3, Blocks.carrot, Blocks.farmland)).setDisplay("Karotte").setMaxStackSize(128)); registerItem((new ItemSeedFood(1, Blocks.potato, Blocks.farmland)).setDisplay("Kartoffel").setMaxStackSize(128)); registerItem("baked_potato", (new ItemFood(5, false)).setDisplay("Ofenkartoffel").setMaxStackSize(128)); registerItem("poisonous_potato", (new ItemFood(2, false)).setPotionEffect(Potion.POISON, 5, 0, 0.6F).setDisplay("Giftige Kartoffel").setMaxStackSize(128)); registerItem("golden_carrot", (new ItemFood(6, false)).setDisplay("Goldene Karotte") - .setPotionEffect(PotionHelper.goldenCarrotEffect).setTab(CheatTab.MISC)); - registerItem((new ItemSmallBlock(Blocks.skull)).setDisplay("Schädel").setTab(CheatTab.DECORATION)); + .setPotionEffect(PotionHelper.goldenCarrotEffect).setTab(CheatTab.tabMisc)); + registerItem((new ItemSkull()).setDisplay("Kopf")); registerItem("carrot_on_a_stick", (new ItemCarrotOnAStick()).setDisplay("Karottenrute")); - registerItem("charge_crystal", (new ItemEffect()).setDisplay("Energiekristall").setTab(CheatTab.MISC).setColor(TextColor.DMAGENTA)); - registerItem("pumpkin_pie", (new ItemFood(8, false)).setDisplay("Kürbiskuchen").setTab(CheatTab.MISC)); + registerItem("charge_crystal", (new ItemEffect()).setDisplay("Energiekristall").setTab(CheatTab.tabMisc).setColor(TextColor.DMAGENTA)); + registerItem("pumpkin_pie", (new ItemFood(8, false)).setDisplay("Kürbiskuchen").setTab(CheatTab.tabMisc)); registerItem("fireworks", (new ItemFirework()).setDisplay("Feuerwerksrakete")); - registerItem("firework_charge", (new ItemFireworkCharge()).setDisplay("Feuerwerksstern").setTab(CheatTab.MATERIALS)); - registerItem("enchanted_book", (new ItemEnchantedBook()).setMaxStackSize(1).setDisplay("Verzaubertes Buch").setTab(CheatTab.MAGIC)); - registerItem((new ItemSmallBlock(Blocks.comparator)).setDisplay("Redstone-Komparator").setTab(CheatTab.TECHNOLOGY)); - registerItem("bloodbrick", (new Item()).setDisplay("Blutroter Ziegel").setTab(CheatTab.MATERIALS)); - registerItem("blackbrick", (new Item()).setDisplay("Schwarzer Ziegel").setTab(CheatTab.MATERIALS)); - Item quartz = (new Item()).setDisplay("Quarz").setTab(CheatTab.METALS); + registerItem("firework_charge", (new ItemFireworkCharge()).setDisplay("Feuerwerksstern").setTab(CheatTab.tabMaterials)); + registerItem("enchanted_book", (new ItemEnchantedBook()).setMaxStackSize(1).setDisplay("Verzaubertes Buch").setTab(CheatTab.tabMagic)); + registerItem((new ItemReed(Blocks.comparator)).setDisplay("Redstone-Komparator").setTab(CheatTab.tabTech)); + registerItem("bloodbrick", (new Item()).setDisplay("Blutroter Ziegel").setTab(CheatTab.tabMaterials)); + registerItem("blackbrick", (new Item()).setDisplay("Schwarzer Ziegel").setTab(CheatTab.tabMaterials)); + Item quartz = (new Item()).setDisplay("Quarz").setTab(CheatTab.tabMetals); registerItem("quartz", quartz); - Item bquartz = (new Item()).setDisplay("Schwarzes Quarz").setTab(CheatTab.METALS); + Item bquartz = (new Item()).setDisplay("Schwarzes Quarz").setTab(CheatTab.tabMetals); registerItem("black_quartz", bquartz); registerItem("lead", (new ItemLead()).setDisplay("Leine").setMaxStackSize(128)); registerItem("name_tag", (new ItemNameTag()).setDisplay("Namensschild")); @@ -544,14 +514,14 @@ public abstract class ItemRegistry { registerItem("dynamite", (new ItemDynamite()).setDisplay("Dynamit").setColor(TextColor.RED)); // registerItem("cherry_door", (new ItemDoor(Blocks.cherry_door)).setUnlocalizedName("doorCherry")); // registerItem("maple_door", (new ItemDoor(Blocks.maple_door)).setUnlocalizedName("doorMaple")); - registerItem("chain", (new ItemMagnetic()).setDisplay("Kette").setTab(CheatTab.MATERIALS)); + registerItem("chain", (new ItemMagnetic()).setDisplay("Kette").setTab(CheatTab.tabMaterials)); for(OreType ore : OreType.values()) { // String loc = ore.name.substring(0, 1).toUpperCase() + ore.name.substring(1); // registerItemBlock(BlockRegistry.getRegisteredBlock(ore.name + "_ore")); // registerItemBlock(BlockRegistry.getRegisteredBlock(ore.name + "_block")); // if(ore.gem != null) { - Item itm = (new Item()).setDisplay(ore.itemDisplay).setTab(CheatTab.METALS); + Item itm = (new Item()).setDisplay(ore.itemDisplay).setTab(CheatTab.tabMetals); registerItem(ore.item, itm); ((BlockOre)BlockRegistry.getRegisteredBlock(ore.name + "_ore")).setDropItem(new ItemStack(itm, ore.dropQuantity), ore.bonusChance, ore.experience); @@ -572,12 +542,12 @@ public abstract class ItemRegistry { ItemBlock block = new ItemMetalBlock(fullBlock, metal, false); registerBlock(fullBlock, block); if(metal.isPowder) { - Item itm = (new ItemMetal(metal)).setDisplay(metal.display + "pulver").setTab(CheatTab.METALS); + Item itm = (new ItemMetal(metal)).setDisplay(metal.display + "pulver").setTab(CheatTab.tabMetals); registerItem(metal.name + "_powder", itm); ((BlockOre)BlockRegistry.getRegisteredBlock(metal.name + "_ore")).setDropItem(new ItemStack(itm), 0, 2); } else { - Item itm = (new ItemMetal(metal)).setDisplay(metal.display + "barren").setTab(CheatTab.METALS); + Item itm = (new ItemMetal(metal)).setDisplay(metal.display + "barren").setTab(CheatTab.tabMetals); registerItem(metal.name + "_ingot", itm); ((BlockOre)BlockRegistry.getRegisteredBlock(metal.name + "_ore")).setSmeltItem(new ItemStack(itm)); } @@ -644,8 +614,6 @@ public abstract class ItemRegistry { // registerSpecial(Blocks.reeds); registerSpecial(Blocks.fire); - registerSpecial(Blocks.soul_fire); - registerSpecial(Blocks.black_fire); registerSpecial(Blocks.portal); registerSpecial(Blocks.floor_portal); // registerSpecial(Blocks.standing_sign); @@ -674,7 +642,7 @@ public abstract class ItemRegistry { for(Block block : BlockRegistry.REGISTRY) { if(!BLOCKMAP.containsKey(block) && !SPECIALIZED.contains(block)) registerBlock(block, new ItemBlock(block)); -// Log.info("Block " + BlockRegistry.getNameFromBlock(block) + " hat kein Item"); +// Log.info("Block " + BlockRegistry.REGISTRY.getNameForObject(block) + " hat kein Item"); } } } diff --git a/common/src/common/init/Items.java b/common/src/common/init/Items.java new file mode 100755 index 0000000..4f9779b --- /dev/null +++ b/common/src/common/init/Items.java @@ -0,0 +1,218 @@ +package common.init; + +import common.item.Item; +import common.item.ItemAmmo; +import common.item.ItemArmor; +import common.item.ItemBow; +import common.item.ItemEnchantedBook; +import common.item.ItemFishingRod; +import common.item.ItemPotion; +import common.item.ItemShears; + + +public abstract class Items { + public static final Item acacia_door = get("acacia_door"); + public static final Item ahrd_fragment = get("ahrd_fragment"); + public static final Item aluminium_ingot = get("aluminium_ingot"); + public static final Item apple = get("apple"); + public static final Item arrow = get("arrow"); + public static final Item baked_potato = get("baked_potato"); + public static final Item banner = get("banner"); + public static final Item beef = get("beef"); + public static final Item birch_door = get("birch_door"); + public static final Item blaze_powder = get("blaze_powder"); + public static final Item blaze_rod = get("blaze_rod"); + public static final Item bloodbrick = get("bloodbrick"); + public static final Item boat = get("boat"); + public static final ItemAmmo bolt = (ItemAmmo)get("bolt"); + public static final Item boltgun = get("boltgun"); + public static final Item bone = get("bone"); + public static final Item book = get("book"); + public static final ItemBow bow = (ItemBow)get("bow"); + public static final Item bowl = get("bowl"); + public static final Item bread = get("bread"); + public static final Item brewing_stand = get("brewing_stand"); + public static final Item brick = get("brick"); + public static final Item bucket = get("bucket"); + public static final Item cake = get("cake"); + public static final Item camera = get("camera"); + public static final Item carrot = get("carrot"); + public static final Item carrot_on_a_stick = get("carrot_on_a_stick"); + public static final Item cauldron = get("cauldron"); + public static final Item chain = get("chain"); + public static final ItemArmor chain_boots = (ItemArmor)get("chain_boots"); + public static final ItemArmor chain_chestplate = (ItemArmor)get("chain_chestplate"); + public static final ItemArmor chain_helmet = (ItemArmor)get("chain_helmet"); + public static final ItemArmor chain_leggings = (ItemArmor)get("chain_leggings"); + public static final Item charge_crystal = get("charge_crystal"); + public static final Item charged_orb = get("charged_orb"); + public static final Item cherry_door = get("cherry_door"); + public static final Item chest_minecart = get("chest_minecart"); + public static final Item chick_magnet = get("chick_magnet"); + public static final Item chicken = get("chicken"); + public static final Item cinnabar = get("cinnabar"); + public static final Item clay_ball = get("clay_ball"); + public static final Item coal = get("coal"); + public static final Item cobalt_ingot = get("cobalt_ingot"); + public static final Item comparator = get("comparator"); + public static final Item cooked_beef = get("cooked_beef"); + public static final Item cooked_chicken = get("cooked_chicken"); + public static final Item cooked_fish = get("cooked_fish"); + public static final Item cooked_porkchop = get("cooked_porkchop"); + public static final Item cookie = get("cookie"); + public static final Item copper_ingot = get("copper_ingot"); + public static final Item dark_oak_door = get("dark_oak_door"); + public static final Item diamond = get("diamond"); + public static final Item diamond_axe = get("diamond_axe"); + public static final ItemArmor diamond_boots = (ItemArmor)get("diamond_boots"); + public static final ItemArmor diamond_chestplate = (ItemArmor)get("diamond_chestplate"); + public static final ItemArmor diamond_helmet = (ItemArmor)get("diamond_helmet"); + public static final Item diamond_hoe = get("diamond_hoe"); + public static final Item diamond_horse_armor = get("diamond_horse_armor"); + public static final ItemArmor diamond_leggings = (ItemArmor)get("diamond_leggings"); + public static final Item diamond_pickaxe = get("diamond_pickaxe"); + public static final ItemShears diamond_shears = (ItemShears)get("diamond_shears"); + public static final Item diamond_shovel = get("diamond_shovel"); + public static final Item diamond_sword = get("diamond_sword"); + public static final Item die = get("die"); + public static final Item dye = get("dye"); + public static final Item dynamite = get("dynamite"); + public static final Item egg = get("egg"); + public static final Item emerald = get("emerald"); + public static final ItemEnchantedBook enchanted_book = (ItemEnchantedBook)get("enchanted_book"); + public static final Item experience_bottle = get("experience_bottle"); + public static final Item feather = get("feather"); + public static final Item fermented_spider_eye = get("fermented_spider_eye"); + public static final Item fire_charge = get("fire_charge"); + public static final Item firework_charge = get("firework_charge"); + public static final Item fireworks = get("fireworks"); + public static final Item fish = get("fish"); + public static final ItemFishingRod fishing_rod = (ItemFishingRod)get("fishing_rod"); + public static final Item flint = get("flint"); + public static final Item flint_and_steel = get("flint_and_steel"); + public static final Item flower_pot = get("flower_pot"); + public static final Item ghast_tear = get("ghast_tear"); + public static final Item ghi_fragment = get("ghi_fragment"); + public static final Item glass_bottle = get("glass_bottle"); + public static final Item glowstone_dust = get("glowstone_dust"); + public static final Item gold_axe = get("gold_axe"); + public static final ItemArmor gold_boots = (ItemArmor)get("gold_boots"); + public static final ItemArmor gold_chestplate = (ItemArmor)get("gold_chestplate"); + public static final ItemArmor gold_helmet = (ItemArmor)get("gold_helmet"); + public static final Item gold_hoe = get("gold_hoe"); + public static final Item gold_horse_armor = get("gold_horse_armor"); + public static final Item gold_ingot = get("gold_ingot"); + public static final ItemArmor gold_leggings = (ItemArmor)get("gold_leggings"); + public static final Item gold_nugget = get("gold_nugget"); + public static final Item gold_pickaxe = get("gold_pickaxe"); + public static final Item gold_shovel = get("gold_shovel"); + public static final Item gold_sword = get("gold_sword"); + public static final Item golden_apple = get("golden_apple"); + public static final Item golden_carrot = get("golden_carrot"); + public static final Item gunpowder = get("gunpowder"); + public static final Item hopper_minecart = get("hopper_minecart"); + public static final Item info_wand = get("info_wand"); + public static final Item iron_axe = get("iron_axe"); + public static final ItemArmor iron_boots = (ItemArmor)get("iron_boots"); + public static final ItemArmor iron_chestplate = (ItemArmor)get("iron_chestplate"); + public static final Item iron_door = get("iron_door"); + public static final ItemArmor iron_helmet = (ItemArmor)get("iron_helmet"); + public static final Item iron_hoe = get("iron_hoe"); + public static final Item iron_horse_armor = get("iron_horse_armor"); + public static final Item iron_ingot = get("iron_ingot"); + public static final ItemArmor iron_leggings = (ItemArmor)get("iron_leggings"); + public static final Item iron_pickaxe = get("iron_pickaxe"); + public static final ItemShears iron_shears = (ItemShears)get("iron_shears"); + public static final Item iron_shovel = get("iron_shovel"); + public static final Item iron_sword = get("iron_sword"); + public static final Item jungle_door = get("jungle_door"); + public static final Item key = get("key"); + public static final Item lead = get("lead"); + public static final Item lead_ingot = get("lead_ingot"); + public static final Item leather = get("leather"); + public static final ItemArmor leather_boots = (ItemArmor)get("leather_boots"); + public static final ItemArmor leather_chestplate = (ItemArmor)get("leather_chestplate"); + public static final ItemArmor leather_helmet = (ItemArmor)get("leather_helmet"); + public static final ItemArmor leather_leggings = (ItemArmor)get("leather_leggings"); + public static final Item lightning_wand = get("lightning_wand"); + public static final Item magma_cream = get("magma_cream"); + public static final Item magnet = get("magnet"); + public static final Item maple_door = get("maple_door"); + public static final Item melon = get("melon"); + public static final Item melon_stem = get("melon_stem"); + public static final Item milk_bucket = get("milk_bucket"); + public static final Item minecart = get("minecart"); + public static final Item mushroom_stew = get("mushroom_stew"); + public static final Item name_tag = get("name_tag"); + public static final Item navigator = get("navigator"); + public static final Item neodymium_ingot = get("neodymium_ingot"); + public static final Item nickel_ingot = get("nickel_ingot"); + public static final Item nieh_fragment = get("nieh_fragment"); + public static final Item oak_door = get("oak_door"); + public static final Item orb = get("orb"); + public static final Item paper = get("paper"); + public static final Item poisonous_potato = get("poisonous_potato"); + public static final Item porkchop = get("porkchop"); + public static final Item portal_frame = get("portal_frame"); + public static final Item potato = get("potato"); + public static final ItemPotion potion = (ItemPotion)get("potion"); + public static final Item pumpkin_pie = get("pumpkin_pie"); + public static final Item pumpkin_stem = get("pumpkin_stem"); + public static final Item quartz = get("quartz"); + public static final Item record_11 = get("record_11"); + public static final Item record_13 = get("record_13"); + public static final Item record_blocks = get("record_blocks"); + public static final Item record_cat = get("record_cat"); + public static final Item record_chirp = get("record_chirp"); + public static final Item record_delay = get("record_delay"); + public static final Item record_extend = get("record_extend"); + public static final Item record_far = get("record_far"); + public static final Item record_mall = get("record_mall"); + public static final Item record_mellohi = get("record_mellohi"); + public static final Item record_stal = get("record_stal"); + public static final Item record_strad = get("record_strad"); + public static final Item record_wait = get("record_wait"); + public static final Item record_ward = get("record_ward"); + public static final Item redstone = get("redstone"); + public static final Item reeds = get("reeds"); + public static final Item repeater = get("repeater"); + public static final Item rotten_flesh = get("rotten_flesh"); + public static final Item ruby = get("ruby"); + public static final Item saddle = get("saddle"); + public static final Item sign = get("sign"); + public static final Item skull = get("skull"); + public static final Item slime_ball = get("slime_ball"); + public static final Item snowball = get("snowball"); + public static final Item soul_wart = get("soul_wart"); + public static final Item speckled_melon = get("speckled_melon"); + public static final Item spider_eye = get("spider_eye"); + public static final Item spruce_door = get("spruce_door"); + public static final Item stick = get("stick"); + public static final Item stone_axe = get("stone_axe"); + public static final Item stone_hoe = get("stone_hoe"); + public static final Item stone_pickaxe = get("stone_pickaxe"); + public static final Item stone_shovel = get("stone_shovel"); + public static final Item stone_sword = get("stone_sword"); + public static final Item string = get("string"); + public static final Item sugar = get("sugar"); + public static final Item thi_fragment = get("thi_fragment"); + public static final Item tin_ingot = get("tin_ingot"); + public static final Item tnt_minecart = get("tnt_minecart"); + public static final Item wand = get("wand"); + public static final Item water_bucket = get("water_bucket"); + public static final Item wheat = get("wheat"); + public static final Item wheats = get("wheats"); + public static final Item wood_axe = get("wood_axe"); + public static final Item wood_hoe = get("wood_hoe"); + public static final Item wood_pickaxe = get("wood_pickaxe"); + public static final Item wood_shovel = get("wood_shovel"); + public static final Item wood_sword = get("wood_sword"); + public static final Item writable_book = get("writable_book"); + public static final Item written_book = get("written_book"); + + private static Item get(String id) { + if(!ItemRegistry.REGISTRY.containsKey(id)) + throw new RuntimeException("Item " + id + " does not exist!"); + return ItemRegistry.REGISTRY.getObject(id); + } +} diff --git a/common/src/main/java/common/init/MetalType.java b/common/src/common/init/MetalType.java similarity index 100% rename from common/src/main/java/common/init/MetalType.java rename to common/src/common/init/MetalType.java diff --git a/common/src/main/java/common/init/NameRegistry.java b/common/src/common/init/NameRegistry.java similarity index 100% rename from common/src/main/java/common/init/NameRegistry.java rename to common/src/common/init/NameRegistry.java diff --git a/common/src/main/java/common/init/OreType.java b/common/src/common/init/OreType.java similarity index 100% rename from common/src/main/java/common/init/OreType.java rename to common/src/common/init/OreType.java diff --git a/common/src/common/init/Registry.java b/common/src/common/init/Registry.java new file mode 100755 index 0000000..4880af1 --- /dev/null +++ b/common/src/common/init/Registry.java @@ -0,0 +1,137 @@ +package common.init; + +import java.awt.Desktop; +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintStream; +import java.lang.Thread.UncaughtExceptionHandler; +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.lang.management.ThreadMXBean; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +import javax.imageio.ImageIO; + +import common.log.NettyLogger; + +public abstract class Registry { + private static boolean crashed; + + private static void register() { + NameRegistry.register(); + BlockRegistry.register(); + FlammabilityRegistry.register(); + SpeciesRegistry.register(); + EntityRegistry.registerEggs(); + ItemRegistry.register(); + TileRegistry.register(); + CraftingRegistry.register(); + SmeltingRegistry.register(); + EntityRegistry.register(); + DispenserRegistry.register(); + } + + public static void setup(String thread) { + Thread.currentThread().setName(thread); + Locale.setDefault(Locale.ROOT); + Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { + public void uncaughtException(Thread thread, Throwable e) { + System.err.println("Fehler in Thread '" + thread.getName() + "'"); + e.printStackTrace(System.err); + if(crashed) + System.exit(1); + if(e instanceof OutOfMemoryError) { + System.gc(); + System.gc(); + } + if(!thread.getName().startsWith("Thread-") || e instanceof OutOfMemoryError) { + System.err.println("Beende!"); + crashed = true; + if(System.getProperty("crash.nodump") == null) { + PrintStream ps = null; + File report = null; + try { + Date date = new Date(); + File file = new File("crash-" + new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(date) + ".txt"); + FileOutputStream out = new FileOutputStream(file); + ps = new PrintStream(out); + ThreadMXBean bean = ManagementFactory.getThreadMXBean(); + ThreadInfo[] info = bean.dumpAllThreads(true, true); + StringBuilder sb = new StringBuilder(); + Error error = new Error(); + for(ThreadInfo threadinfo : info) { + if(threadinfo.getThreadId() == thread.getId()) + error.setStackTrace(threadinfo.getStackTrace()); + sb.append(threadinfo); + } + ps.println("************************************************ " + new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date) + " ************************************************"); + ps.println(); + ps.println("\"Wie haste das denn nu wieder geschafft, Bursche?\""); + ps.println("Unerwarteter Fehler in Thread '" + thread.getName() + "':"); + e.printStackTrace(ps); + ps.println(); + ps.println("---------------------------------------------- Thread-Dump (" + info.length + " Threads) ---------------------------------------------"); + ps.println(); + ps.print(sb.toString()); + ps.println("*********************************************************************************************************************"); + report = file; + } + catch(Throwable t) { + System.err.println("Konnte Absturzbericht nicht speichern:"); + t.printStackTrace(System.err); + } + finally { + if(ps != null) + ps.close(); + } + if(report != null) { + System.err.println("Absturzbericht gespeichert unter " + report.getPath()); + try { + Desktop.getDesktop().browse(report.toURI()); + } + catch(Throwable e1) { + System.err.println("Konnte " + report + " nicht öffnen: " + e1); + } + } + } + System.exit(1); + } + } + }); + ImageIO.setUseCache(false); + Thread timer = new Thread("Timer Hack Thread") { + public void run() { + while(true) { + try { + Thread.sleep(2147483647L); + } + catch(InterruptedException e) { + ; + } + } + } + }; + timer.setDaemon(true); + timer.start(); + System.setProperty("java.net.preferIPv4Stack", "true"); + NettyLogger.init(); + register(); + } + + public static void addShutdownHook(final Runnable hook) { + Runtime.getRuntime().addShutdownHook(new Thread("Game Shutdown Thread") { + public void run() { + if(!crashed) { + try { + hook.run(); + } + catch(Throwable e) { + e.printStackTrace(); + } + } + } + }); + } +} diff --git a/common/src/main/java/common/init/SmeltingRegistry.java b/common/src/common/init/SmeltingRegistry.java similarity index 99% rename from common/src/main/java/common/init/SmeltingRegistry.java rename to common/src/common/init/SmeltingRegistry.java index 4a316bc..f47f6b2 100755 --- a/common/src/main/java/common/init/SmeltingRegistry.java +++ b/common/src/common/init/SmeltingRegistry.java @@ -4,7 +4,7 @@ import java.util.Map; import java.util.Map.Entry; import common.block.Block; -import common.block.artificial.BlockStoneBrick; +import common.block.BlockStoneBrick; import common.collect.Maps; import common.color.DyeColor; import common.item.Item; diff --git a/common/src/main/java/common/init/SoundEvent.java b/common/src/common/init/SoundEvent.java similarity index 98% rename from common/src/main/java/common/init/SoundEvent.java rename to common/src/common/init/SoundEvent.java index 4ab1d86..b5cb1b9 100755 --- a/common/src/main/java/common/init/SoundEvent.java +++ b/common/src/common/init/SoundEvent.java @@ -109,9 +109,6 @@ public enum SoundEvent { WOLF_PANTING("wolf_panting"), WOLF_SHAKE("wolf_shake"), WOLF_WHINE("wolf_whine"), - - FOX_DEATH("fox_death"), - FOX_HURT("fox_hurt1", "fox_hurt2"), SLIME_ATTACK("slime_attack1", "slime_attack2"), SLIME_BIG("slime_big1", "slime_big2", "slime_big3", "slime_big4"), diff --git a/common/src/main/java/common/init/SpeciesRegistry.java b/common/src/common/init/SpeciesRegistry.java similarity index 100% rename from common/src/main/java/common/init/SpeciesRegistry.java rename to common/src/common/init/SpeciesRegistry.java diff --git a/common/src/main/java/common/init/TileRegistry.java b/common/src/common/init/TileRegistry.java similarity index 93% rename from common/src/main/java/common/init/TileRegistry.java rename to common/src/common/init/TileRegistry.java index 4ebcac4..ab2b3ea 100755 --- a/common/src/main/java/common/init/TileRegistry.java +++ b/common/src/common/init/TileRegistry.java @@ -16,8 +16,10 @@ import common.tileentity.TileEntityEnchantmentTable; import common.tileentity.TileEntityFurnace; import common.tileentity.TileEntityHopper; import common.tileentity.TileEntityMobSpawner; +import common.tileentity.TileEntityNote; import common.tileentity.TileEntityPiston; import common.tileentity.TileEntitySign; +import common.tileentity.TileEntitySkull; import common.tileentity.TileEntityTianReactor; public abstract class TileRegistry { @@ -41,15 +43,17 @@ public abstract class TileRegistry { addMapping(TileEntityDispenser.class, "Trap"); addMapping(TileEntityDropper.class, "Dropper"); addMapping(TileEntitySign.class, "Sign"); + addMapping(TileEntityMobSpawner.class, "MobSpawner"); + addMapping(TileEntityNote.class, "Music"); addMapping(TileEntityPiston.class, "Piston"); addMapping(TileEntityBrewingStand.class, "Cauldron"); addMapping(TileEntityEnchantmentTable.class, "EnchantTable"); addMapping(TileEntityBeacon.class, "Beacon"); + addMapping(TileEntitySkull.class, "Skull"); addMapping(TileEntityDaylightDetector.class, "DLDetector"); addMapping(TileEntityHopper.class, "Hopper"); addMapping(TileEntityComparator.class, "Comparator"); addMapping(TileEntityBanner.class, "Banner"); addMapping(TileEntityTianReactor.class, "TianReactor"); - addMapping(TileEntityMobSpawner.class, "MobSpawner"); } } diff --git a/common/src/main/java/common/init/ToolMaterial.java b/common/src/common/init/ToolMaterial.java similarity index 84% rename from common/src/main/java/common/init/ToolMaterial.java rename to common/src/common/init/ToolMaterial.java index 5cf8dd3..5923f9a 100755 --- a/common/src/main/java/common/init/ToolMaterial.java +++ b/common/src/common/init/ToolMaterial.java @@ -2,7 +2,6 @@ package common.init; import java.util.Set; -import common.attributes.UsageSlot; import common.collect.Sets; import common.item.Item; @@ -121,20 +120,20 @@ public class ToolMaterial { return this.repair.contains(item); } - public int getDurability(UsageSlot armorType) { - return armorType.getArmorSlot() < 0 ? 0 : MAX_DAMAGE[armorType.getArmorSlot()] * this.maxDamageFactor; + public int getDurability(int armorType) { + return MAX_DAMAGE[armorType] * this.maxDamageFactor; } - public float getRadiationReduction(UsageSlot armorType) { - return armorType.getArmorSlot() < 0 ? 0.0f : RAD_REDUCE[armorType.getArmorSlot()] * this.radiationResistance; + public float getRadiationReduction(int armorType) { + return RAD_REDUCE[armorType] * this.radiationResistance; } - public float getMagicReduction(UsageSlot armorType) { - return armorType.getArmorSlot() < 0 ? 0.0f : MAG_REDUCE[armorType.getArmorSlot()] * this.magicResistance; + public float getMagicReduction(int armorType) { + return MAG_REDUCE[armorType] * this.magicResistance; } - public int getDamageReduction(UsageSlot armorType) { - return armorType.getArmorSlot() < 0 ? 0 : this.damageReduction[armorType.getArmorSlot()]; + public int getDamageReduction(int armorType) { + return this.damageReduction[armorType]; } public int getArmorEnchantability() { diff --git a/common/src/main/java/common/init/ToolType.java b/common/src/common/init/ToolType.java similarity index 100% rename from common/src/main/java/common/init/ToolType.java rename to common/src/common/init/ToolType.java diff --git a/common/src/main/java/common/init/TradeRegistry.java b/common/src/common/init/TradeRegistry.java similarity index 99% rename from common/src/main/java/common/init/TradeRegistry.java rename to common/src/common/init/TradeRegistry.java index c9d1356..9d20098 100755 --- a/common/src/main/java/common/init/TradeRegistry.java +++ b/common/src/common/init/TradeRegistry.java @@ -179,7 +179,7 @@ public abstract class TradeRegistry { static class BookForGem implements ITradeList { public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { - Enchantment enchantment = random.pick(Enchantment.values()); + Enchantment enchantment = random.pick(Enchantment.enchantmentsBookList); int i = random.range(enchantment.getMinLevel(), enchantment.getMaxLevel()); ItemStack itemstack = Items.enchanted_book.getEnchantedItemStack(new RngEnchantment(enchantment, i)); int j = 2 + random.zrange(5 + i * 10) + 3 * i; diff --git a/common/src/main/java/common/init/UniverseRegistry.java b/common/src/common/init/UniverseRegistry.java similarity index 85% rename from common/src/main/java/common/init/UniverseRegistry.java rename to common/src/common/init/UniverseRegistry.java index 3c894be..e8e2d4c 100755 --- a/common/src/main/java/common/init/UniverseRegistry.java +++ b/common/src/common/init/UniverseRegistry.java @@ -6,14 +6,13 @@ import java.util.Map.Entry; import common.biome.Biome; import common.block.BlockColored; -import common.block.foliage.LeavesType; -import common.block.natural.BlockSand; +import common.block.BlockSand; +import common.block.LeavesType; import common.collect.Lists; import common.collect.Maps; import common.collect.Sets; import common.color.DyeColor; import common.dimension.Area; -import common.dimension.CloudType; import common.dimension.DimType; import common.dimension.Dimension; import common.dimension.Domain; @@ -27,8 +26,11 @@ import common.dimension.Star; import common.dimension.Dimension.GeneratorType; import common.dimension.Dimension.ReplacerType; import common.log.Log; +import common.nbt.NBTException; +import common.nbt.NBTParser; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.rng.Random; -import common.tags.TagObject; import common.util.PortalType; import common.world.State; import common.world.Weather; @@ -89,167 +91,167 @@ public abstract class UniverseRegistry { } } - public static void fromTags(TagObject tag) { - List list = tag.getList("Dimensions"); - for(int z = 0; z < list.size(); z++) { - Dimension dim = Dimension.getByTag(list.get(z)); + public static void loadNbt(NBTTagCompound tag) { + NBTTagList list = tag.getTagList("Dimensions", 10); + for(int z = 0; z < list.tagCount(); z++) { + Dimension dim = Dimension.getByNbt(list.getCompoundTagAt(z)); if(!REGISTRY.containsKey(dim.getDimensionId()) && !ALIASES.containsKey(dim.getDimensionName())) register(dim); } - list = tag.getList("Names"); - for(int z = 0; z < list.size(); z++) { - TagObject data = list.get(z); + list = tag.getTagList("Names", 10); + for(int z = 0; z < list.tagCount(); z++) { + NBTTagCompound data = list.getCompoundTagAt(z); String id = data.getString("ID"); // if(BASE_ALIASES.containsKey(id)) { Dimension dim = ALIASES.get(id); if(dim != null && dim != Space.INSTANCE) - dim.readTags(data); + dim.readNbt(data); // } } - list = tag.getList("Sectors"); - for(int z = 0; z < list.size(); z++) { - TagObject data = list.get(z); + list = tag.getTagList("Sectors", 10); + for(int z = 0; z < list.tagCount(); z++) { + NBTTagCompound data = list.getCompoundTagAt(z); String id = data.getString("ID"); Sector sector = SECTORS.get(id); if(sector == null) SECTORS.put(id, sector = new Sector(id)); - sector.readTags(data); + sector.readNbt(data); } - list = tag.getList("Galaxies"); - for(int z = 0; z < list.size(); z++) { - TagObject data = list.get(z); + list = tag.getTagList("Galaxies", 10); + for(int z = 0; z < list.tagCount(); z++) { + NBTTagCompound data = list.getCompoundTagAt(z); String id = data.getString("ID"); Galaxy galaxy = GALAXIES.get(id); if(galaxy == null) GALAXIES.put(id, galaxy = new Galaxy(id)); - galaxy.readTags(data); + galaxy.readNbt(data); } - list = tag.getList("Domains"); - for(int z = 0; z < list.size(); z++) { - TagObject data = list.get(z); + list = tag.getTagList("Domains", 10); + for(int z = 0; z < list.tagCount(); z++) { + NBTTagCompound data = list.getCompoundTagAt(z); String id = data.getString("ID"); Domain domain = DOMAINS.get(id); if(domain == null) DOMAINS.put(id, domain = new Domain(id)); - domain.readTags(data); + domain.readNbt(data); } - list = tag.getList("Barycenters"); - for(int z = 0; z < list.size(); z++) { - TagObject link = list.get(z); + list = tag.getTagList("Barycenters", 10); + for(int z = 0; z < list.tagCount(); z++) { + NBTTagCompound link = list.getCompoundTagAt(z); if(!assign(link.getString("Celestial"), link.getString("Center"))) - Log.TICK.warn("Konnte '" + link.getString("Celestial") + "' nicht zu '" + link.getString("Center") + "' zuweisen"); + Log.JNI.warn("Konnte '" + link.getString("Celestial") + "' nicht zu '" + link.getString("Center") + "' zuweisen"); } } - public static TagObject toTags() { - TagObject tag = new TagObject(); + public static NBTTagCompound saveNbt() { + NBTTagCompound tag = new NBTTagCompound(); - List list = Lists.newArrayList(); + NBTTagList list = new NBTTagList(); for(Dimension dim : DIMENSIONS) { if(!BASE_REGISTRY.containsKey(dim.getDimensionId()) && dim != Space.INSTANCE) - list.add(dim.toTags()); + list.appendTag(dim.toNbt()); } - if(!list.isEmpty()) - tag.setList("Dimensions", list); + if(!list.hasNoTags()) + tag.setTag("Dimensions", list); - list = Lists.newArrayList(); + list = new NBTTagList(); for(Dimension dim : DIMENSIONS) { if(/* BASE_REGISTRY.containsKey(dim.getDimensionId()) */ dim != Space.INSTANCE) { - TagObject data = new TagObject(); - dim.writeTags(data); - if(!data.isEmpty()) { + NBTTagCompound data = new NBTTagCompound(); + dim.writeNbt(data); + if(!data.hasNoTags()) { data.setString("ID", dim.getDimensionName()); - list.add(data); + list.appendTag(data); } } } - if(!list.isEmpty()) - tag.setList("Names", list); + if(!list.hasNoTags()) + tag.setTag("Names", list); - list = Lists.newArrayList(); + list = new NBTTagList(); for(Sector sector : SECTORS.values()) { - TagObject data = new TagObject(); - sector.writeTags(data); - if(!data.isEmpty()) { + NBTTagCompound data = new NBTTagCompound(); + sector.writeNbt(data); + if(!data.hasNoTags()) { data.setString("ID", sector.id); - list.add(data); + list.appendTag(data); } } - if(!list.isEmpty()) - tag.setList("Sectors", list); + if(!list.hasNoTags()) + tag.setTag("Sectors", list); - list = Lists.newArrayList(); + list = new NBTTagList(); for(Galaxy galaxy : GALAXIES.values()) { - TagObject data = new TagObject(); - galaxy.writeTags(data); - if(!data.isEmpty()) { + NBTTagCompound data = new NBTTagCompound(); + galaxy.writeNbt(data); + if(!data.hasNoTags()) { data.setString("ID", galaxy.id); - list.add(data); + list.appendTag(data); } } - if(!list.isEmpty()) - tag.setList("Galaxies", list); + if(!list.hasNoTags()) + tag.setTag("Galaxies", list); - list = Lists.newArrayList(); + list = new NBTTagList(); for(Domain domain : DOMAINS.values()) { - TagObject data = new TagObject(); - domain.writeTags(data); - if(!data.isEmpty()) { + NBTTagCompound data = new NBTTagCompound(); + domain.writeNbt(data); + if(!data.hasNoTags()) { data.setString("ID", domain.id); - list.add(data); + list.appendTag(data); } } - if(!list.isEmpty()) - tag.setList("Domains", list); + if(!list.hasNoTags()) + tag.setTag("Domains", list); - list = Lists.newArrayList(); + list = new NBTTagList(); for(Entry entry : MOON_MAP.entrySet()) { if(BASE_REGISTRY.containsKey(entry.getKey().getDimensionId())) continue; - TagObject link = new TagObject(); + NBTTagCompound link = new NBTTagCompound(); link.setString("Celestial", entry.getKey().getDimensionName()); link.setString("Center", entry.getValue().getDimensionName()); - list.add(link); + list.appendTag(link); } for(Entry entry : PLANET_MAP.entrySet()) { if(BASE_REGISTRY.containsKey(entry.getKey().getDimensionId())) continue; - TagObject link = new TagObject(); + NBTTagCompound link = new NBTTagCompound(); link.setString("Celestial", entry.getKey().getDimensionName()); link.setString("Center", entry.getValue().getDimensionName()); - list.add(link); + list.appendTag(link); } for(Entry entry : STAR_MAP.entrySet()) { if(BASE_REGISTRY.containsKey(entry.getKey().getDimensionId())) continue; - TagObject link = new TagObject(); + NBTTagCompound link = new NBTTagCompound(); link.setString("Celestial", entry.getKey().getDimensionName()); link.setString("Center", entry.getValue().id); - list.add(link); + list.appendTag(link); } for(Entry entry : SECTOR_MAP.entrySet()) { if(BASE_MAP.containsKey(entry.getKey().id)) continue; - TagObject link = new TagObject(); + NBTTagCompound link = new NBTTagCompound(); link.setString("Celestial", entry.getKey().id); link.setString("Center", entry.getValue().id); - list.add(link); + list.appendTag(link); } for(Entry entry : AREA_MAP.entrySet()) { if(BASE_REGISTRY.containsKey(entry.getKey().getDimensionId())) continue; - TagObject link = new TagObject(); + NBTTagCompound link = new NBTTagCompound(); link.setString("Celestial", entry.getKey().getDimensionName()); link.setString("Center", entry.getValue().id); - list.add(link); + list.appendTag(link); } - if(!list.isEmpty()) - tag.setList("Barycenters", list); + if(!list.hasNoTags()) + tag.setTag("Barycenters", list); return tag; } @@ -526,11 +528,11 @@ public abstract class UniverseRegistry { .setBiomeReplacer(Blocks.gravel.getState()) .setBiomeGen(Biome.FOREST, false, 4, 4, 6, 50, 50, Biome.MUSHROOMPLAINS).enableMobs().enableSnow() .setFrostBiomes(Biome.ICEPLAINS, Biome.ICEPLAINS, Biome.ICEPLAINS, Biome.COLDTAIGA, Biome.MEGATAIGA) - .setColdBiomes(Biome.FOREST, Biome.EXTREMEHILLS, Biome.TAIGA, Biome.PLAINS) + .setColdBiomes(Biome.FOREST, Biome.EXTREMEHILLS, Biome.TAIGA, Biome.PLAINS, Biome.BLACKENED) .setMediumBiomes(Biome.FOREST, Biome.ROOFEDFOREST, Biome.EXTREMEHILLS, Biome.PLAINS, Biome.BIRCHFOREST, - Biome.SWAMPLAND, Biome.JUNGLE) + Biome.SWAMPLAND, Biome.JUNGLE, Biome.BLACKENED) .setHotBiomes(Biome.DESERT, Biome.DESERT, Biome.DESERT, Biome.SAVANNA, Biome.SAVANNA, Biome.PLAINS) - .enableCavesRavines(Blocks.lava.getState()).setDungeons(8) + .enableCavesRavines(Blocks.lava.getState()).setDungeons(8).setWorldFloor(Blocks.bedrock.getState()) .addLake(Blocks.water.getState(), null, Blocks.grass.getState(), 4, 0, 255, false) .addLake(Blocks.lava.getState(), Blocks.stone.getState(), null, 8, 8, 255, true) .addLiquid(Blocks.flowing_water.getState(), 50, 8, 255, false) @@ -592,6 +594,7 @@ public abstract class UniverseRegistry { .setTimeQualifier(2).setSimpleGen(Blocks.dirt.getState(), Blocks.water.getState(), 64) .setSimpleReplacer(Blocks.gravel.getState(), Blocks.sand.getState()).setBiome(Biome.ELVENFOREST) .enableCaves(Blocks.air.getState()).setDungeons(4).enableMobs().enableSnow() + .setWorldFloor(Blocks.bedrock.getState()) .addLake(Blocks.water.getState(), null, Blocks.grass.getState(), 4, 0, 255, false) .addLake(Blocks.lava.getState(), null, null, 8, 8, 255, true) .addLiquid(Blocks.flowing_water.getState(), 50, 8, 255, false) @@ -602,6 +605,7 @@ public abstract class UniverseRegistry { .setTimeQualifier(5).setPerlinGen(Blocks.rock.getState(), Blocks.water.getState(), 63) .setBiomeReplacer(Blocks.gravel.getState()).setBiomeGen(Biome.FOREST, true, 5, 3, 3, 30) .enableCavesRavines(Blocks.lava.getState()).setDungeons(10).enableMobs().enableSnow() + .setWorldFloor(Blocks.bedrock.getState()) .addLake(Blocks.water.getState(), null, Blocks.grass.getState(), 4, 0, 255, false) .addLake(Blocks.lava.getState(), null, null, 8, 8, 255, true) .addLiquid(Blocks.flowing_water.getState(), 50, 8, 255, false) @@ -612,12 +616,13 @@ public abstract class UniverseRegistry { .addOre(Blocks.nichun_ore.getState(), 0, 10, 1, 0, 10, false), "girok"); registerDimension("'Eismond Yrdinath'", new Moon(103, "yrdinath", 0xccccff, 0xccccff, 46743637L, 17460L, 2.5f, 239.15f, 8).setTimeQualifier(4) .setPerlinGen(Blocks.snow.getState(), Blocks.ice.getState(), 63).setBiome(Biome.SNOWLAND) - .enableMobs().enableSnow().setWeather(Weather.SNOW), "transylvania"); + .setWorldFloor(Blocks.air.getState()).enableMobs().enableSnow().setWeather(Weather.SNOW), "transylvania"); registerDimension("'Wüstenplanet Me'sar'", new Planet(104, "mesar", 0xff7f3f, 0xff6022, 0xff6f00, 56643366L, 87340L, 11.0f, 333.15f) .setTimeQualifier(5).setPerlinGen(Blocks.rock.getState(), Blocks.air.getState(), 63) .setBiomeReplacer(Blocks.sand.getState().withProperty(BlockSand.VARIANT, BlockSand.EnumType.RED_SAND)) .setBiomeGen(Biome.MESA, true, 3, 1000, 100000, 100000) .enableCavesRavines(Blocks.lava.getState()).enableMobs() + .setWorldFloor(Blocks.bedrock.getState()) .addLake(Blocks.lava.getState(), null, null, 8, 8, 255, true) .addLiquid(Blocks.flowing_lava.getState(), 20, 8, 255, true) .addOre(Blocks.iron_ore.getState(), 6, 2, 24, 0, 64, false) @@ -634,11 +639,12 @@ public abstract class UniverseRegistry { .setPerlinGen(Blocks.blackened_stone.getState(), Blocks.goo.getState(), 63) .setBiomeReplacer(Blocks.blackened_cobble.getState()).setBiome(Biome.BLACKENED) .enableCaves(Blocks.air.getState()).setDungeons(4).enableMobs() + .setWorldFloor(Blocks.bedrock.getState()) .addLake(Blocks.goo.getState(), null, null, 8, 8, 255, true) // .addOre(Blocks.PLACEHOLDER_ore.getState(), 0, 2, 3, 0, 12, false) , "ovrol"); - registerDimension("Der Warp", new Semi(-1, "warp", 0x0c001f, 0x0c001f, 0x190033, 285.0f, 3).setCloudTexture(CloudType.DENSE).setCloudHeight(238.0f) + registerDimension("Der Warp", new Semi(-1, "warp", 0x0c001f, 0x0c001f, 0x190033, 285.0f, 3).setCloudTexture("clouds_dense").setCloudHeight(238.0f) .setPerlinGen(Blocks.obsidian.getState(), Blocks.lava.getState(), 63) .setBiome(Biome.CHAOS).enableCavesRavines(Blocks.air.getState()).enableLongCaves().enableMobs().enableSnow() .addLake(Blocks.water.getState(), null, Blocks.obsidian.getState(), 8, 0, 255, false) @@ -650,10 +656,10 @@ public abstract class UniverseRegistry { registerDomain("Tian'Xin", "tianxin"); registerDimension("Ni'enrath", new Area(-2, "nienrath", 0x7f00ff, 0x7f00ff, 276.15f, 1) - .setPerlinGen(Blocks.tian.getState(), Blocks.springwater.getState(), 63).setBiome(Biome.TIAN) + .setPerlinGen(Blocks.tian.getState(), Blocks.water.getState(), 63).setBiome(Biome.TIAN) .setBiomeReplacer(Blocks.tian.getState()).enableLongCaves().enableMobs().enableSnow() - .addLake(Blocks.springwater.getState(), Blocks.tian.getState(), Blocks.tian.getState(), 4, 0, 255, false) - .addLiquid(Blocks.flowing_springwater.getState(), 50, 8, 255, false), "tianxin"); + .addLake(Blocks.water.getState(), Blocks.tian.getState(), Blocks.tian.getState(), 4, 0, 255, false) + .addLiquid(Blocks.flowing_water.getState(), 50, 8, 255, false), "tianxin"); registerDimension("Cyberspace", new Area(-3, "cyberspace", 0x000000, 0x000000, 293.15f, 15) .setFlatGen(Blocks.stained_hardened_clay.getState().withProperty(BlockColored.COLOR, DyeColor.GREEN), 2) @@ -661,28 +667,33 @@ public abstract class UniverseRegistry { registerDomain("Hölle", "hell"); registerDimension("Kreis Thedric", new Area(-1001, "thedric", 0x330707, 0x330707, 347.15f, 2).enableLongCaves().enableMobs().enableFortresses() - .enableWorldCeiling().enableDenseFog() + .setWorldFloor(Blocks.air.getState()).setWorldCeiling(Blocks.bedrock.getState()).enableDenseFog() .setCavernGen(Blocks.hellrock.getState(), Blocks.lava.getState(), 63) .setSurfaceReplacer(Blocks.gravel.getState(), Blocks.soul_sand.getState()) .setBiome(Biome.UPPERHELL), "hell"); registerDimension("Kreis Kyroth", new Area(-1002, "kyroth", 0x990000, 0x990000, 387.15f, 3).enableLongCaves().enableMobs() + .setWorldFloor(Blocks.air.getState()) .setSimpleGen(Blocks.hellrock.getState(), Blocks.lava.getState(), 64) .setSimpleReplacer(Blocks.obsidian.getState(), Blocks.soul_sand.getState()) .setBiome(Biome.LOWERHELL) .addLake(Blocks.lava.getState(), null, null, 4, 8, 255, false) .addLiquid(Blocks.flowing_lava.getState(), 40, 8, 255, true), "hell"); registerDimension("Kreis Ahrd", new Area(-1003, "ahrd", 0xcc0000, 0xcc0000, 467.15f, 15).enableLongCaves().enableMobs() + .setWorldFloor(Blocks.air.getState()) .setPerlinGen(Blocks.hellrock.getState(), Blocks.lava.getState(), 63) .setBiomeReplacer(Blocks.soul_sand.getState()).setBiome(Biome.HELLHILLS) .addLake(Blocks.lava.getState(), Blocks.soul_sand.getState(), Blocks.soul_sand.getState(), 2, 8, 255, false).addLiquid(Blocks.flowing_lava.getState(), 80, 8, 255, true), "hell"); registerDimension("Kreis Mizorath", new Area(-1004, "mizorath", 0xff0000, 0xff0000, 1067.15f, 15).enableMobs() + .setWorldFloor(Blocks.air.getState()) .setPerlinGen(Blocks.hellrock.getState(), Blocks.blood.getState(), 63) .setBiomeReplacer(Blocks.soul_sand.getState()).setBiome(Biome.SOULPLAINS), "hell"); registerDimension("Kreis Dargoth", new Area(-1005, "dargoth", 0xff3f0c, 0xff3f0c, 1707.15f, 15).enableMobs() + .setWorldFloor(Blocks.air.getState()) .setPerlinGen(Blocks.hellrock.getState(), Blocks.magma.getState(), 63) .setBiomeReplacer(Blocks.soul_sand.getState()).setBiome(Biome.SOULPLAINS), "hell"); registerDimension("Kreis Aasirith", new Area(-1006, "aasirith", 0x191919, 0x191919, 2482.0f, 1).enableLongCaves().enableMobs() + .setWorldFloor(Blocks.air.getState()) .setPerlinGen(Blocks.rock.getState(), Blocks.magma.getState(), 63) .setBiomeReplacer(Blocks.ash.getState()).setBiome(Biome.ASHLAND) .addLake(Blocks.lava.getState(), Blocks.rock.getState(), Blocks.rock.getState(), @@ -698,60 +709,60 @@ public abstract class UniverseRegistry { private static Dimension addPreset(String name, String base, String data) { Dimension dim = BASE_ALIASES.get(base).copy(UniverseRegistry.MORE_DIM_ID, "preset"); - TagObject ptag; + NBTTagCompound ptag; try { - ptag = TagObject.parse("{" + data + "}"); + ptag = NBTParser.parseTag("{" + data + "}"); } - catch(IllegalArgumentException e) { + catch(NBTException e) { throw new RuntimeException(e); } - TagObject dtag = dim.toTags(true); - if(ptag.getBool("ClearGenerator")) { - ptag.remove("ClearGenerator"); - dtag.remove("FloorBlock"); - dtag.remove("CeilingBlock"); - dtag.remove("Layers"); - dtag.remove("AddBiomes"); - dtag.remove("FrostBiomes"); - dtag.remove("ColdBiomes"); - dtag.remove("MediumBiomes"); - dtag.remove("HotBiomes"); - dtag.remove("Ores"); - dtag.remove("Lakes"); - dtag.remove("Liquids"); + NBTTagCompound dtag = dim.toNbt(true); + if(ptag.getBoolean("ClearGenerator")) { + ptag.removeTag("ClearGenerator"); + dtag.removeTag("FloorBlock"); + dtag.removeTag("CeilingBlock"); + dtag.removeTag("Layers"); + dtag.removeTag("AddBiomes"); + dtag.removeTag("FrostBiomes"); + dtag.removeTag("ColdBiomes"); + dtag.removeTag("MediumBiomes"); + dtag.removeTag("HotBiomes"); + dtag.removeTag("Ores"); + dtag.removeTag("Lakes"); + dtag.removeTag("Liquids"); dtag.setString("Generator", GeneratorType.FLAT.getName()); dtag.setString("Replacer", ReplacerType.NONE.getName()); // dtag.setBoolean("MobGen", false); // dtag.setBoolean("SnowGen", false); - dtag.setBool("Caves", false); - dtag.setBool("Ravines", false); - dtag.setBool("AltCaves", false); - dtag.setBool("Strongholds", false); - dtag.setBool("Villages", false); - dtag.setBool("Mineshafts", false); - dtag.setBool("Scattered", false); - dtag.setBool("Fortresses", false); - dtag.setInt("Dungeons", 0); - dtag.setInt("BiomeSize", 0); - dtag.setInt("RiverSize", 4); - dtag.setInt("SnowRarity", 6); - dtag.setInt("SeaRarity", 50); - dtag.setInt("AddRarity", 50); - dtag.setInt("SeaLevel", 0); + dtag.setBoolean("Caves", false); + dtag.setBoolean("Ravines", false); + dtag.setBoolean("AltCaves", false); + dtag.setBoolean("Strongholds", false); + dtag.setBoolean("Villages", false); + dtag.setBoolean("Mineshafts", false); + dtag.setBoolean("Scattered", false); + dtag.setBoolean("Fortresses", false); + dtag.setInteger("Dungeons", 0); + dtag.setInteger("BiomeSize", 0); + dtag.setInteger("RiverSize", 4); + dtag.setInteger("SnowRarity", 6); + dtag.setInteger("SeaRarity", 50); + dtag.setInteger("AddRarity", 50); + dtag.setInteger("SeaLevel", 0); dtag.setString("DefaultBiome", Biome.NONE.name.toLowerCase()); - dtag.setBool("SemiFixed", false); + dtag.setBoolean("SemiFixed", false); // dtag.setString("DefaultWeather", Weather.CLEAR.getName()); dtag.setString("DefaultLeaves", LeavesType.SPRING.getName()); - Dimension.writeState(dtag, "FillerBlock", Blocks.air.getState()); - Dimension.writeState(dtag, "TopBlock", Blocks.air.getState()); - Dimension.writeState(dtag, "SurfaceBlock", Blocks.air.getState()); - Dimension.writeState(dtag, "AltBlock1", Blocks.air.getState()); - Dimension.writeState(dtag, "AltBlock2", Blocks.air.getState()); - Dimension.writeState(dtag, "LiquidBlock", Blocks.air.getState()); - Dimension.writeState(dtag, "CaveFillBlock", Blocks.air.getState()); + dtag.setString("FillerBlock", BlockRegistry.toIdName(Blocks.air.getState())); + dtag.setString("TopBlock", BlockRegistry.toIdName(Blocks.air.getState())); + dtag.setString("SurfaceBlock", BlockRegistry.toIdName(Blocks.air.getState())); + dtag.setString("AltBlock1", BlockRegistry.toIdName(Blocks.air.getState())); + dtag.setString("AltBlock2", BlockRegistry.toIdName(Blocks.air.getState())); + dtag.setString("LiquidBlock", BlockRegistry.toIdName(Blocks.air.getState())); + dtag.setString("CaveFillBlock", BlockRegistry.toIdName(Blocks.air.getState())); } dtag.merge(ptag); - dim.fromTags(dtag); + dim.fromNbt(dtag); dim.setCustomName(name); // BASE_DIMS.add(dim); return dim; diff --git a/common/src/main/java/common/init/WoodType.java b/common/src/common/init/WoodType.java similarity index 100% rename from common/src/main/java/common/init/WoodType.java rename to common/src/common/init/WoodType.java diff --git a/common/src/main/java/common/inventory/AnimalChest.java b/common/src/common/inventory/AnimalChest.java similarity index 100% rename from common/src/main/java/common/inventory/AnimalChest.java rename to common/src/common/inventory/AnimalChest.java diff --git a/common/src/main/java/common/inventory/Container.java b/common/src/common/inventory/Container.java similarity index 86% rename from common/src/main/java/common/inventory/Container.java rename to common/src/common/inventory/Container.java index 59197f1..80ae090 100755 --- a/common/src/main/java/common/inventory/Container.java +++ b/common/src/common/inventory/Container.java @@ -97,6 +97,14 @@ public abstract class Container } } + /** + * Handles the given Button-click on the server, currently only used by enchanting. Name is for legacy. + */ + public boolean enchantItem(EntityNPC playerIn, int id) + { + return false; + } + public Slot getSlotFromInventory(IInventory inv, int slotIn) { for (int i = 0; i < this.inventorySlots.size(); ++i) @@ -165,7 +173,7 @@ public abstract class Container { Slot slot = (Slot)this.inventorySlots.get(slotId); - if (slot != null && canAddItemToSlot(slot, inventoryplayer.getItemStack(), true) && slot.isItemValid(inventoryplayer.getItemStack()) && inventoryplayer.getItemStack().size > this.dragSlots.size() && this.canDragIntoSlot(slot)) + if (slot != null && canAddItemToSlot(slot, inventoryplayer.getItemStack(), true) && slot.isItemValid(inventoryplayer.getItemStack()) && inventoryplayer.getItemStack().stackSize > this.dragSlots.size() && this.canDragIntoSlot(slot)) { this.dragSlots.add(slot); } @@ -175,34 +183,34 @@ public abstract class Container if (!this.dragSlots.isEmpty()) { ItemStack itemstack3 = inventoryplayer.getItemStack().copy(); - int j = inventoryplayer.getItemStack().size; + int j = inventoryplayer.getItemStack().stackSize; for (Slot slot1 : this.dragSlots) { - if (slot1 != null && canAddItemToSlot(slot1, inventoryplayer.getItemStack(), true) && slot1.isItemValid(inventoryplayer.getItemStack()) && inventoryplayer.getItemStack().size >= this.dragSlots.size() && this.canDragIntoSlot(slot1)) + if (slot1 != null && canAddItemToSlot(slot1, inventoryplayer.getItemStack(), true) && slot1.isItemValid(inventoryplayer.getItemStack()) && inventoryplayer.getItemStack().stackSize >= this.dragSlots.size() && this.canDragIntoSlot(slot1)) { ItemStack itemstack1 = itemstack3.copy(); - int k = slot1.getHasStack() ? slot1.getStack().size : 0; + int k = slot1.getHasStack() ? slot1.getStack().stackSize : 0; computeStackSize(this.dragSlots, this.dragMode, itemstack1, k); - if (itemstack1.size > itemstack1.getMaxStackSize()) + if (itemstack1.stackSize > itemstack1.getMaxStackSize()) { - itemstack1.size = itemstack1.getMaxStackSize(); + itemstack1.stackSize = itemstack1.getMaxStackSize(); } - if (itemstack1.size > slot1.getItemStackLimit(itemstack1)) + if (itemstack1.stackSize > slot1.getItemStackLimit(itemstack1)) { - itemstack1.size = slot1.getItemStackLimit(itemstack1); + itemstack1.stackSize = slot1.getItemStackLimit(itemstack1); } - j -= itemstack1.size - k; + j -= itemstack1.stackSize - k; slot1.putStack(itemstack1); } } - itemstack3.size = j; + itemstack3.stackSize = j; - if (itemstack3.size <= 0) + if (itemstack3.stackSize <= 0) { itemstack3 = null; } @@ -237,7 +245,7 @@ public abstract class Container { playerIn.dropPlayerItemWithRandomChoice(inventoryplayer.getItemStack().splitStack(1), true); - if (inventoryplayer.getItemStack().size == 0) + if (inventoryplayer.getItemStack().stackSize == 0) { inventoryplayer.setItemStack((ItemStack)null); } @@ -292,19 +300,19 @@ public abstract class Container { if (itemstack10 != null && slot7.isItemValid(itemstack10)) { - int k2 = clickedButton == 0 ? itemstack10.size : 1; + int k2 = clickedButton == 0 ? itemstack10.stackSize : 1; if (k2 > slot7.getItemStackLimit(itemstack10)) { k2 = slot7.getItemStackLimit(itemstack10); } - if (itemstack10.size >= k2) + if (itemstack10.stackSize >= k2) { slot7.putStack(itemstack10.splitStack(k2)); } - if (itemstack10.size == 0) + if (itemstack10.stackSize == 0) { inventoryplayer.setItemStack((ItemStack)null); } @@ -314,11 +322,11 @@ public abstract class Container { if (itemstack10 == null) { - int j2 = clickedButton == 0 ? itemstack9.size : (itemstack9.size + 1) / 2; + int j2 = clickedButton == 0 ? itemstack9.stackSize : (itemstack9.stackSize + 1) / 2; ItemStack itemstack12 = slot7.decrStackSize(j2); inventoryplayer.setItemStack(itemstack12); - if (itemstack9.size == 0) + if (itemstack9.stackSize == 0) { slot7.putStack((ItemStack)null); } @@ -329,28 +337,28 @@ public abstract class Container { if (itemstack9.getItem() == itemstack10.getItem() && itemstack9.getMetadata() == itemstack10.getMetadata() && ItemStack.areItemStackTagsEqual(itemstack9, itemstack10)) { - int i2 = clickedButton == 0 ? itemstack10.size : 1; + int i2 = clickedButton == 0 ? itemstack10.stackSize : 1; - if (i2 > slot7.getItemStackLimit(itemstack10) - itemstack9.size) + if (i2 > slot7.getItemStackLimit(itemstack10) - itemstack9.stackSize) { - i2 = slot7.getItemStackLimit(itemstack10) - itemstack9.size; + i2 = slot7.getItemStackLimit(itemstack10) - itemstack9.stackSize; } - if (i2 > itemstack10.getMaxStackSize() - itemstack9.size) + if (i2 > itemstack10.getMaxStackSize() - itemstack9.stackSize) { - i2 = itemstack10.getMaxStackSize() - itemstack9.size; + i2 = itemstack10.getMaxStackSize() - itemstack9.stackSize; } itemstack10.splitStack(i2); - if (itemstack10.size == 0) + if (itemstack10.stackSize == 0) { inventoryplayer.setItemStack((ItemStack)null); } - itemstack9.size += i2; + itemstack9.stackSize += i2; } - else if (itemstack10.size <= slot7.getItemStackLimit(itemstack10)) + else if (itemstack10.stackSize <= slot7.getItemStackLimit(itemstack10)) { slot7.putStack(itemstack10); inventoryplayer.setItemStack(itemstack9); @@ -358,14 +366,14 @@ public abstract class Container } else if (itemstack9.getItem() == itemstack10.getItem() && itemstack10.getMaxStackSize() > 1 && (!itemstack9.getHasSubtypes() || itemstack9.getMetadata() == itemstack10.getMetadata()) && ItemStack.areItemStackTagsEqual(itemstack9, itemstack10)) { - int l1 = itemstack9.size; + int l1 = itemstack9.stackSize; - if (l1 > 0 && l1 + itemstack10.size <= itemstack10.getMaxStackSize()) + if (l1 > 0 && l1 + itemstack10.stackSize <= itemstack10.getMaxStackSize()) { - itemstack10.size += l1; + itemstack10.stackSize += l1; itemstack9 = slot7.decrStackSize(l1); - if (itemstack9.size == 0) + if (itemstack9.stackSize == 0) { slot7.putStack((ItemStack)null); } @@ -405,14 +413,14 @@ public abstract class Container if (k1 > -1) { inventoryplayer.addItemStackToInventory(itemstack7); - slot5.decrStackSize(itemstack11.size); + slot5.decrStackSize(itemstack11.stackSize); slot5.putStack((ItemStack)null); slot5.onPickupFromSlot(playerIn, itemstack11); } } else { - slot5.decrStackSize(itemstack11.size); + slot5.decrStackSize(itemstack11.stackSize); slot5.putStack(itemstack7); slot5.onPickupFromSlot(playerIn, itemstack11); } @@ -441,7 +449,7 @@ public abstract class Container if (slot3 != null && slot3.getHasStack() && slot3.canTakeStack(playerIn)) { - ItemStack itemstack5 = slot3.decrStackSize(clickedButton == 0 ? 1 : slot3.getStack().size); + ItemStack itemstack5 = slot3.decrStackSize(clickedButton == 0 ? 1 : slot3.getStack().stackSize); slot3.onPickupFromSlot(playerIn, itemstack5); playerIn.dropPlayerItemWithRandomChoice(itemstack5, true); } @@ -458,17 +466,17 @@ public abstract class Container for (int l2 = 0; l2 < 2; ++l2) { - for (int i3 = i1; i3 >= 0 && i3 < this.inventorySlots.size() && itemstack4.size < itemstack4.getMaxStackSize(); i3 += j1) + for (int i3 = i1; i3 >= 0 && i3 < this.inventorySlots.size() && itemstack4.stackSize < itemstack4.getMaxStackSize(); i3 += j1) { Slot slot8 = (Slot)this.inventorySlots.get(i3); - if (slot8.getHasStack() && canAddItemToSlot(slot8, itemstack4, true) && slot8.canTakeStack(playerIn) && this.canMergeSlot(itemstack4, slot8) && (l2 != 0 || slot8.getStack().size != slot8.getStack().getMaxStackSize())) + if (slot8.getHasStack() && canAddItemToSlot(slot8, itemstack4, true) && slot8.canTakeStack(playerIn) && this.canMergeSlot(itemstack4, slot8) && (l2 != 0 || slot8.getStack().stackSize != slot8.getStack().getMaxStackSize())) { - int l = Math.min(itemstack4.getMaxStackSize() - itemstack4.size, slot8.getStack().size); + int l = Math.min(itemstack4.getMaxStackSize() - itemstack4.stackSize, slot8.getStack().stackSize); ItemStack itemstack2 = slot8.decrStackSize(l); - itemstack4.size += l; + itemstack4.stackSize += l; - if (itemstack2.size <= 0) + if (itemstack2.stackSize <= 0) { slot8.putStack((ItemStack)null); } @@ -598,26 +606,26 @@ public abstract class Container if (stack.isStackable()) { - while (stack.size > 0 && (!reverseDirection && i < endIndex || reverseDirection && i >= startIndex)) + while (stack.stackSize > 0 && (!reverseDirection && i < endIndex || reverseDirection && i >= startIndex)) { Slot slot = (Slot)this.inventorySlots.get(i); ItemStack itemstack = slot.getStack(); if (itemstack != null && itemstack.getItem() == stack.getItem() && (!stack.getHasSubtypes() || stack.getMetadata() == itemstack.getMetadata()) && ItemStack.areItemStackTagsEqual(stack, itemstack)) { - int j = itemstack.size + stack.size; + int j = itemstack.stackSize + stack.stackSize; if (j <= stack.getMaxStackSize()) { - stack.size = 0; - itemstack.size = j; + stack.stackSize = 0; + itemstack.stackSize = j; slot.onSlotChanged(); flag = true; } - else if (itemstack.size < stack.getMaxStackSize()) + else if (itemstack.stackSize < stack.getMaxStackSize()) { - stack.size -= stack.getMaxStackSize() - itemstack.size; - itemstack.size = stack.getMaxStackSize(); + stack.stackSize -= stack.getMaxStackSize() - itemstack.stackSize; + itemstack.stackSize = stack.getMaxStackSize(); slot.onSlotChanged(); flag = true; } @@ -634,7 +642,7 @@ public abstract class Container } } - if (stack.size > 0) + if (stack.stackSize > 0) { if (reverseDirection) { @@ -654,7 +662,7 @@ public abstract class Container { slot1.putStack(stack.copy()); slot1.onSlotChanged(); - stack.size = 0; + stack.stackSize = 0; flag = true; break; } @@ -721,7 +729,7 @@ public abstract class Container if (slotIn != null && slotIn.getHasStack() && stack != null && stack.isItemEqual(slotIn.getStack()) && ItemStack.areItemStackTagsEqual(slotIn.getStack(), stack)) { - flag |= slotIn.getStack().size + (stackSizeMatters ? 0 : stack.size) <= stack.getMaxStackSize(); + flag |= slotIn.getStack().stackSize + (stackSizeMatters ? 0 : stack.stackSize) <= stack.getMaxStackSize(); } return flag; @@ -736,18 +744,18 @@ public abstract class Container switch (p_94525_1_) { case 0: - p_94525_2_.size = ExtMath.floorf((float)p_94525_2_.size / (float)p_94525_0_.size()); + p_94525_2_.stackSize = ExtMath.floorf((float)p_94525_2_.stackSize / (float)p_94525_0_.size()); break; case 1: - p_94525_2_.size = 1; + p_94525_2_.stackSize = 1; break; case 2: - p_94525_2_.size = p_94525_2_.getItem().getItemStackLimit(); + p_94525_2_.stackSize = p_94525_2_.getItem().getItemStackLimit(); } - p_94525_2_.size += p_94525_3_; + p_94525_2_.stackSize += p_94525_3_; } /** @@ -784,7 +792,7 @@ public abstract class Container if (itemstack != null) { - f += (float)itemstack.size / (float)Math.min(inv.getInventoryStackLimit(), itemstack.getMaxStackSize()); + f += (float)itemstack.stackSize / (float)Math.min(inv.getInventoryStackLimit(), itemstack.getMaxStackSize()); ++i; } } diff --git a/common/src/main/java/common/inventory/ContainerBrewingStand.java b/common/src/common/inventory/ContainerBrewingStand.java similarity index 98% rename from common/src/main/java/common/inventory/ContainerBrewingStand.java rename to common/src/common/inventory/ContainerBrewingStand.java index cd28bb7..d4c461a 100755 --- a/common/src/main/java/common/inventory/ContainerBrewingStand.java +++ b/common/src/common/inventory/ContainerBrewingStand.java @@ -128,7 +128,7 @@ public class ContainerBrewingStand extends Container slot.onSlotChange(itemstack1, itemstack); } - if (itemstack1.size == 0) + if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } @@ -137,7 +137,7 @@ public class ContainerBrewingStand extends Container slot.onSlotChanged(); } - if (itemstack1.size == itemstack.size) + if (itemstack1.stackSize == itemstack.stackSize) { return null; } diff --git a/common/src/main/java/common/inventory/ContainerChest.java b/common/src/common/inventory/ContainerChest.java similarity index 98% rename from common/src/main/java/common/inventory/ContainerChest.java rename to common/src/common/inventory/ContainerChest.java index c20fb4d..f53fe5e 100755 --- a/common/src/main/java/common/inventory/ContainerChest.java +++ b/common/src/common/inventory/ContainerChest.java @@ -67,7 +67,7 @@ public class ContainerChest extends Container return null; } - if (itemstack1.size == 0) + if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } diff --git a/common/src/main/java/common/inventory/ContainerDispenser.java b/common/src/common/inventory/ContainerDispenser.java similarity index 95% rename from common/src/main/java/common/inventory/ContainerDispenser.java rename to common/src/common/inventory/ContainerDispenser.java index 5ed17e5..6caa6dc 100755 --- a/common/src/main/java/common/inventory/ContainerDispenser.java +++ b/common/src/common/inventory/ContainerDispenser.java @@ -63,7 +63,7 @@ public class ContainerDispenser extends Container return null; } - if (itemstack1.size == 0) + if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } @@ -72,7 +72,7 @@ public class ContainerDispenser extends Container slot.onSlotChanged(); } - if (itemstack1.size == itemstack.size) + if (itemstack1.stackSize == itemstack.stackSize) { return null; } diff --git a/common/src/common/inventory/ContainerEnchantment.java b/common/src/common/inventory/ContainerEnchantment.java new file mode 100755 index 0000000..f630bbe --- /dev/null +++ b/common/src/common/inventory/ContainerEnchantment.java @@ -0,0 +1,424 @@ +package common.inventory; + +import java.util.List; + +import common.enchantment.EnchantmentHelper; +import common.enchantment.RngEnchantment; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.item.ItemStack; +import common.rng.Random; +import common.util.BlockPos; +import common.world.World; + +public class ContainerEnchantment extends Container +{ + /** SlotEnchantmentTable object with ItemStack to be enchanted */ + public IInventory tableInventory; + + /** current world (for bookshelf counting) */ + private World worldPointer; + private BlockPos position; + private Random rand; + public int xpSeed; + + /** 3-member array storing the enchantment levels of each slot */ + public int[] enchantLevels; + public int[] enchantmentIds; + + public ContainerEnchantment(InventoryPlayer playerInv, World worldIn) + { + this(playerInv, worldIn, BlockPos.ORIGIN); + } + + public ContainerEnchantment(InventoryPlayer playerInv, World worldIn, BlockPos pos) + { + this.tableInventory = new InventoryBasic("Enchant", true, 1) + { + public int getInventoryStackLimit() + { + return ItemStack.MAX_SIZE; + } + public void markDirty() + { + super.markDirty(); + ContainerEnchantment.this.onCraftMatrixChanged(this); + } + }; + this.rand = new Random(); + this.enchantLevels = new int[3]; + this.enchantmentIds = new int[] { -1, -1, -1}; + this.worldPointer = worldIn; + this.position = pos; + this.xpSeed = playerInv.player.getXPSeed(); + this.addSlotToContainer(new Slot(this.tableInventory, 0, 25, 47) + { + public boolean isItemValid(ItemStack stack) + { + return true; + } + public int getSlotStackLimit() + { + return 1; + } + }); +// this.addSlotToContainer(new Slot(this.tableInventory, 1, 35, 47) +// { +// public boolean isItemValid(ItemStack stack) +// { +// return stack.getItem() == Items.dye && EnumDyeColor.byDyeDamage(stack.getMetadata()) == EnumDyeColor.BLUE; +// } +// }); + + for (int i = 0; i < 3; ++i) + { + for (int j = 0; j < 9; ++j) + { + this.addSlotToContainer(new Slot(playerInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (int k = 0; k < 9; ++k) + { + this.addSlotToContainer(new Slot(playerInv, k, 8 + k * 18, 142)); + } + } + + public void onCraftGuiOpened(ICrafting listener) + { + super.onCraftGuiOpened(listener); + listener.sendProgressBarUpdate(this, 0, this.enchantLevels[0]); + listener.sendProgressBarUpdate(this, 1, this.enchantLevels[1]); + listener.sendProgressBarUpdate(this, 2, this.enchantLevels[2]); + listener.sendProgressBarUpdate(this, 3, this.xpSeed & -16); + listener.sendProgressBarUpdate(this, 4, this.enchantmentIds[0]); + listener.sendProgressBarUpdate(this, 5, this.enchantmentIds[1]); + listener.sendProgressBarUpdate(this, 6, this.enchantmentIds[2]); + } + + /** + * Looks for changes made in the container, sends them to every listener. + */ + public void detectAndSendChanges() + { + super.detectAndSendChanges(); + + for (int i = 0; i < this.crafters.size(); ++i) + { + ICrafting icrafting = (ICrafting)this.crafters.get(i); + icrafting.sendProgressBarUpdate(this, 0, this.enchantLevels[0]); + icrafting.sendProgressBarUpdate(this, 1, this.enchantLevels[1]); + icrafting.sendProgressBarUpdate(this, 2, this.enchantLevels[2]); + icrafting.sendProgressBarUpdate(this, 3, this.xpSeed & -16); + icrafting.sendProgressBarUpdate(this, 4, this.enchantmentIds[0]); + icrafting.sendProgressBarUpdate(this, 5, this.enchantmentIds[1]); + icrafting.sendProgressBarUpdate(this, 6, this.enchantmentIds[2]); + } + } + + public void updateProgressBar(int id, int data) + { + if (id >= 0 && id <= 2) + { + this.enchantLevels[id] = data; + } + else if (id == 3) + { + this.xpSeed = data; + } + else if (id >= 4 && id <= 6) + { + this.enchantmentIds[id - 4] = data; + } + else + { + super.updateProgressBar(id, data); + } + } + + /** + * Callback for when the crafting matrix is changed. + */ + public void onCraftMatrixChanged(IInventory inventoryIn) + { + if (inventoryIn == this.tableInventory) + { + ItemStack itemstack = inventoryIn.getStackInSlot(0); + + if (itemstack != null && itemstack.isItemEnchantable()) + { + if (!this.worldPointer.client) + { + int l = 0; + + for (int j = -1; j <= 1; ++j) + { + for (int k = -1; k <= 1; ++k) + { + if ((j != 0 || k != 0) && this.worldPointer.isAirBlock(this.position.add(k, 0, j)) && this.worldPointer.isAirBlock(this.position.add(k, 1, j))) + { + if (this.worldPointer.getState(this.position.add(k * 2, 0, j * 2)).getBlock() == Blocks.bookshelf) + { + ++l; + } + + if (this.worldPointer.getState(this.position.add(k * 2, 1, j * 2)).getBlock() == Blocks.bookshelf) + { + ++l; + } + + if (k != 0 && j != 0) + { + if (this.worldPointer.getState(this.position.add(k * 2, 0, j)).getBlock() == Blocks.bookshelf) + { + ++l; + } + + if (this.worldPointer.getState(this.position.add(k * 2, 1, j)).getBlock() == Blocks.bookshelf) + { + ++l; + } + + if (this.worldPointer.getState(this.position.add(k, 0, j * 2)).getBlock() == Blocks.bookshelf) + { + ++l; + } + + if (this.worldPointer.getState(this.position.add(k, 1, j * 2)).getBlock() == Blocks.bookshelf) + { + ++l; + } + } + } + } + } + + this.rand.setSeed((long)this.xpSeed); + + for (int i1 = 0; i1 < 3; ++i1) + { + this.enchantLevels[i1] = EnchantmentHelper.calcItemStackEnchantability(this.rand, i1, l, itemstack); + this.enchantmentIds[i1] = -1; + + if (this.enchantLevels[i1] < i1 + 1) + { + this.enchantLevels[i1] = 0; + } + } + + for (int j1 = 0; j1 < 3; ++j1) + { + if (this.enchantLevels[j1] > 0) + { + List list = this.getRandomEnchantments(itemstack, j1, this.enchantLevels[j1]); + + if (list != null && !list.isEmpty()) + { + RngEnchantment enchantmentdata = (RngEnchantment)list.get(this.rand.zrange(list.size())); + this.enchantmentIds[j1] = enchantmentdata.enchantmentobj.effectId | enchantmentdata.enchantmentLevel << 8; + } + } + } + + this.detectAndSendChanges(); + } + } + else + { + for (int i = 0; i < 3; ++i) + { + this.enchantLevels[i] = 0; + this.enchantmentIds[i] = -1; + } + } + } + } + + /** + * Handles the given Button-click on the server, currently only used by enchanting. Name is for legacy. + */ + public boolean enchantItem(EntityNPC playerIn, int id) + { + ItemStack itemstack = this.tableInventory.getStackInSlot(0); +// ItemStack itemstack1 = this.tableInventory.getStackInSlot(1); + int i = id + 1; + +// if ((itemstack1 == null || itemstack1.stackSize < i) && !playerIn.capabilities.isCreativeMode) +// { +// return false; +// } +// else + if (this.enchantLevels[id] > 0 && itemstack != null && /* ( */ playerIn.experienceLevel >= i && playerIn.experienceLevel >= this.enchantLevels[id]) // || playerIn.creative)) + { + if (!this.worldPointer.client) + { + List list = this.getRandomEnchantments(itemstack, id, this.enchantLevels[id]); + boolean flag = itemstack.getItem() == Items.book; + + if (list != null) + { + playerIn.removeExperienceLevel(i); + + if (flag) + { + itemstack.setItem(Items.enchanted_book); + } + + for (int j = 0; j < list.size(); ++j) + { + RngEnchantment enchantmentdata = (RngEnchantment)list.get(j); + + if (flag) + { + Items.enchanted_book.addEnchantment(itemstack, enchantmentdata); + } + else + { + itemstack.addEnchantment(enchantmentdata.enchantmentobj, enchantmentdata.enchantmentLevel); + } + } + +// if (!playerIn.capabilities.isCreativeMode) +// { +// itemstack1.stackSize -= i; +// +// if (itemstack1.stackSize <= 0) +// { +// this.tableInventory.setInventorySlotContents(1, (ItemStack)null); +// } +// } + +// playerIn.triggerAchievement(StatRegistry.enchantedStat); + this.tableInventory.markDirty(); + this.xpSeed = playerIn.getXPSeed(); + this.onCraftMatrixChanged(this.tableInventory); + } + } + + return true; + } + else + { + return false; + } + } + + private List getRandomEnchantments(ItemStack stack, int id, int level) + { + this.rand.setSeed((long)(this.xpSeed + id)); + List list = EnchantmentHelper.buildEnchantmentList(this.rand, stack, level); + + if (stack.getItem() == Items.book && list != null && list.size() > 1) + { + list.remove(this.rand.zrange(list.size())); + } + + return list; + } + +// public int getLapisAmount() +// { +// ItemStack itemstack = this.tableInventory.getStackInSlot(1); +// return itemstack == null ? 0 : itemstack.stackSize; +// } + + /** + * Called when the container is closed. + */ + public void onContainerClosed(EntityNPC playerIn) + { + super.onContainerClosed(playerIn); + + if (!this.worldPointer.client) + { + for (int i = 0; i < this.tableInventory.getSizeInventory(); ++i) + { + ItemStack itemstack = this.tableInventory.removeStackFromSlot(i); + + if (itemstack != null) + { + playerIn.dropPlayerItemWithRandomChoice(itemstack, false); + } + } + } + } + + public boolean canInteractWith(EntityNPC playerIn) + { + return this.worldPointer.getState(this.position).getBlock() != Blocks.enchanting_table ? false : playerIn.getDistanceSq((double)this.position.getX() + 0.5D, (double)this.position.getY() + 0.5D, (double)this.position.getZ() + 0.5D) <= 64.0D; + } + + /** + * Take a stack from the specified inventory slot. + */ + public ItemStack transferStackInSlot(EntityNPC playerIn, int index) + { + ItemStack itemstack = null; + Slot slot = (Slot)this.inventorySlots.get(index); + + if (slot != null && slot.getHasStack()) + { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + + if (index == 0) + { + if (!this.mergeItemStack(itemstack1, 1, 37, true)) + { + return null; + } + } +// else if (index == 1) +// { +// if (!this.mergeItemStack(itemstack1, 2, 38, true)) +// { +// return null; +// } +// } +// else if (itemstack1.getItem() == Items.dye && EnumDyeColor.byDyeDamage(itemstack1.getMetadata()) == EnumDyeColor.BLUE) +// { +// if (!this.mergeItemStack(itemstack1, 1, 2, true)) +// { +// return null; +// } +// } + else + { + if (((Slot)this.inventorySlots.get(0)).getHasStack() || !((Slot)this.inventorySlots.get(0)).isItemValid(itemstack1)) + { + return null; + } + + if (itemstack1.hasTagCompound() && itemstack1.stackSize == 1) + { + ((Slot)this.inventorySlots.get(0)).putStack(itemstack1.copy()); + itemstack1.stackSize = 0; + } + else if (itemstack1.stackSize >= 1) + { + ((Slot)this.inventorySlots.get(0)).putStack(new ItemStack(itemstack1.getItem(), 1, itemstack1.getMetadata())); + --itemstack1.stackSize; + } + } + + if (itemstack1.stackSize == 0) + { + slot.putStack((ItemStack)null); + } + else + { + slot.onSlotChanged(); + } + + if (itemstack1.stackSize == itemstack.stackSize) + { + return null; + } + + slot.onPickupFromSlot(playerIn, itemstack1); + } + + return itemstack; + } +} diff --git a/common/src/main/java/common/inventory/ContainerFurnace.java b/common/src/common/inventory/ContainerFurnace.java similarity index 97% rename from common/src/main/java/common/inventory/ContainerFurnace.java rename to common/src/common/inventory/ContainerFurnace.java index a4c67ff..ae7cc2d 100755 --- a/common/src/main/java/common/inventory/ContainerFurnace.java +++ b/common/src/common/inventory/ContainerFurnace.java @@ -143,7 +143,7 @@ public class ContainerFurnace extends Container return null; } - if (itemstack1.size == 0) + if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } @@ -152,7 +152,7 @@ public class ContainerFurnace extends Container slot.onSlotChanged(); } - if (itemstack1.size == itemstack.size) + if (itemstack1.stackSize == itemstack.stackSize) { return null; } diff --git a/common/src/main/java/common/inventory/ContainerHopper.java b/common/src/common/inventory/ContainerHopper.java similarity index 98% rename from common/src/main/java/common/inventory/ContainerHopper.java rename to common/src/common/inventory/ContainerHopper.java index 9b8326b..99d9283 100755 --- a/common/src/main/java/common/inventory/ContainerHopper.java +++ b/common/src/common/inventory/ContainerHopper.java @@ -62,7 +62,7 @@ public class ContainerHopper extends Container return null; } - if (itemstack1.size == 0) + if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } diff --git a/common/src/common/inventory/ContainerHorseInventory.java b/common/src/common/inventory/ContainerHorseInventory.java new file mode 100755 index 0000000..928b183 --- /dev/null +++ b/common/src/common/inventory/ContainerHorseInventory.java @@ -0,0 +1,129 @@ +package common.inventory; + +import common.entity.animal.EntityHorse; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.item.ItemStack; + +public class ContainerHorseInventory extends Container +{ + private IInventory horseInventory; + private EntityHorse theHorse; + + public ContainerHorseInventory(IInventory playerInventory, final IInventory horseInventoryIn, final EntityHorse horse, EntityNPC player) + { + this.horseInventory = horseInventoryIn; + this.theHorse = horse; + int i = 3; + horseInventoryIn.openInventory(player); + int j = (i - 4) * 18; + this.addSlotToContainer(new Slot(horseInventoryIn, 0, 8, 18) + { + public boolean isItemValid(ItemStack stack) + { + return super.isItemValid(stack) && stack.getItem() == Items.saddle && !this.getHasStack(); + } + }); + this.addSlotToContainer(new Slot(horseInventoryIn, 1, 8, 36) + { + public boolean isItemValid(ItemStack stack) + { + return super.isItemValid(stack) && horse.canWearArmor() && EntityHorse.isArmorItem(stack.getItem()); + } + public boolean canBeHovered() + { + return horse.canWearArmor(); + } + }); + + if (horse.isChested()) + { + for (int k = 0; k < i; ++k) + { + for (int l = 0; l < 5; ++l) + { + this.addSlotToContainer(new Slot(horseInventoryIn, 2 + l + k * 5, 80 + l * 18, 18 + k * 18)); + } + } + } + + for (int i1 = 0; i1 < 3; ++i1) + { + for (int k1 = 0; k1 < 9; ++k1) + { + this.addSlotToContainer(new Slot(playerInventory, k1 + i1 * 9 + 9, 8 + k1 * 18, 102 + i1 * 18 + j)); + } + } + + for (int j1 = 0; j1 < 9; ++j1) + { + this.addSlotToContainer(new Slot(playerInventory, j1, 8 + j1 * 18, 160 + j)); + } + } + + public boolean canInteractWith(EntityNPC playerIn) + { + return this.horseInventory.isUseableByPlayer(playerIn) && this.theHorse.isEntityAlive() && this.theHorse.getDistanceToEntity(playerIn) < 8.0F; + } + + /** + * Take a stack from the specified inventory slot. + */ + public ItemStack transferStackInSlot(EntityNPC playerIn, int index) + { + ItemStack itemstack = null; + Slot slot = (Slot)this.inventorySlots.get(index); + + if (slot != null && slot.getHasStack()) + { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + + if (index < this.horseInventory.getSizeInventory()) + { + if (!this.mergeItemStack(itemstack1, this.horseInventory.getSizeInventory(), this.inventorySlots.size(), true)) + { + return null; + } + } + else if (this.getSlot(1).isItemValid(itemstack1) && !this.getSlot(1).getHasStack()) + { + if (!this.mergeItemStack(itemstack1, 1, 2, false)) + { + return null; + } + } + else if (this.getSlot(0).isItemValid(itemstack1)) + { + if (!this.mergeItemStack(itemstack1, 0, 1, false)) + { + return null; + } + } + else if (this.horseInventory.getSizeInventory() <= 2 || !this.mergeItemStack(itemstack1, 2, this.horseInventory.getSizeInventory(), false)) + { + return null; + } + + if (itemstack1.stackSize == 0) + { + slot.putStack((ItemStack)null); + } + else + { + slot.onSlotChanged(); + } + } + + return itemstack; + } + + /** + * Called when the container is closed. + */ + public void onContainerClosed(EntityNPC playerIn) + { + super.onContainerClosed(playerIn); + this.horseInventory.closeInventory(playerIn); + } +} diff --git a/common/src/common/inventory/ContainerLocalMenu.java b/common/src/common/inventory/ContainerLocalMenu.java new file mode 100755 index 0000000..c8f636e --- /dev/null +++ b/common/src/common/inventory/ContainerLocalMenu.java @@ -0,0 +1,59 @@ +package common.inventory; + +import java.util.Map; + +import common.collect.Maps; +import common.entity.npc.EntityNPC; +import common.tileentity.ILockableContainer; +import common.tileentity.LockCode; + +public class ContainerLocalMenu extends InventoryBasic implements ILockableContainer +{ + private String guiID; + private Map field_174895_b = Maps.newHashMap(); + + public ContainerLocalMenu(String id, String title, int slotCount) + { + super(title, slotCount); + this.guiID = id; + } + + public int getField(int id) + { + return this.field_174895_b.containsKey(Integer.valueOf(id)) ? ((Integer)this.field_174895_b.get(Integer.valueOf(id))).intValue() : 0; + } + + public void setField(int id, int value) + { + this.field_174895_b.put(Integer.valueOf(id), Integer.valueOf(value)); + } + + public int getFieldCount() + { + return this.field_174895_b.size(); + } + + public boolean isLocked() + { + return false; + } + + public void setLockCode(LockCode code) + { + } + + public LockCode getLockCode() + { + return LockCode.EMPTY_CODE; + } + + public String getGuiID() + { + return this.guiID; + } + + public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) + { + throw new UnsupportedOperationException(); + } +} diff --git a/common/src/main/java/common/inventory/ContainerTile.java b/common/src/common/inventory/ContainerMachine.java similarity index 62% rename from common/src/main/java/common/inventory/ContainerTile.java rename to common/src/common/inventory/ContainerMachine.java index e697fff..0a71f19 100755 --- a/common/src/main/java/common/inventory/ContainerTile.java +++ b/common/src/common/inventory/ContainerMachine.java @@ -2,32 +2,32 @@ package common.inventory; import common.entity.npc.EntityNPC; import common.item.ItemStack; -import common.tileentity.TileEntityDevice; -import common.tileentity.TileEntityDevice.Status; +import common.tileentity.TileEntityMachine; +import common.tileentity.TileEntityMachine.Status; -public class ContainerTile extends Container +public class ContainerMachine extends Container { - private final IInventory tileInv; - private final TileEntityDevice tile; + private final IInventory machine; + private final TileEntityMachine tile; private int temperature; private Status status = Status.OFF; private final int[] resources; - public ContainerTile(InventoryPlayer playerInv, TileEntityDevice tile, IInventory tileInv, EntityNPC player) + public ContainerMachine(InventoryPlayer playerInv, TileEntityMachine tile, IInventory machine, EntityNPC player) { - this.tileInv = tileInv; + this.machine = machine; this.tile = tile; this.resources = new int[tile.getNumResources()]; - tileInv.openInventory(player); + machine.openInventory(player); int i = 71; - for (int j = 0; j < tileInv.getSizeInventory(); ++j) + for (int j = 0; j < machine.getSizeInventory(); ++j) { final int index = j; - this.addSlotToContainer(new Slot(tileInv, j, 8 + j * 18, 40) { + this.addSlotToContainer(new Slot(machine, j, 8 + j * 18, 40) { public boolean isItemValid(ItemStack stack) { - return ContainerTile.this.tile.isItemValidForSlot(index, stack); + return ContainerMachine.this.tile.isItemValidForSlot(index, stack); } }); } @@ -48,7 +48,7 @@ public class ContainerTile extends Container public boolean canInteractWith(EntityNPC playerIn) { - return this.tileInv.isUseableByPlayer(playerIn); + return this.machine.isUseableByPlayer(playerIn); } protected boolean canTransfer(Slot slot, ItemStack stack) { @@ -65,19 +65,19 @@ public class ContainerTile extends Container ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); - if (index < this.tileInv.getSizeInventory()) + if (index < this.machine.getSizeInventory()) { - if (!this.mergeItemStack(itemstack1, this.tileInv.getSizeInventory(), this.inventorySlots.size(), true)) + if (!this.mergeItemStack(itemstack1, this.machine.getSizeInventory(), this.inventorySlots.size(), true)) { return null; } } - else if (!this.mergeItemStack(itemstack1, 0, this.tileInv.getSizeInventory(), false)) + else if (!this.mergeItemStack(itemstack1, 0, this.machine.getSizeInventory(), false)) { return null; } - if (itemstack1.size == 0) + if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } @@ -93,17 +93,13 @@ public class ContainerTile extends Container public void onContainerClosed(EntityNPC playerIn) { super.onContainerClosed(playerIn); - this.tileInv.closeInventory(playerIn); + this.machine.closeInventory(playerIn); } public void onCraftGuiOpened(ICrafting listener) { super.onCraftGuiOpened(listener); - listener.sendProgressBarUpdate(this, this.resources.length, this.tile.getTemperature()); - listener.sendProgressBarUpdate(this, this.resources.length + 1, this.tile.getStatus().ordinal()); - for(int z = 0; z < this.resources.length; z++) { - listener.sendProgressBarUpdate(this, z, this.tile.getResource(z).getValue()); - } +// listener.sendAllWindowProperties(this, this.machine); } public void updateProgressBar(int id, int data) @@ -122,14 +118,14 @@ public class ContainerTile extends Container for (int i = 0; i < this.crafters.size(); ++i) { - ICrafting listener = this.crafters.get(i); + ICrafting icrafting = (ICrafting)this.crafters.get(i); if(this.temperature != this.tile.getTemperature()) - listener.sendProgressBarUpdate(this, this.resources.length, this.tile.getTemperature()); + icrafting.sendProgressBarUpdate(this, this.resources.length, this.tile.getTemperature()); if(this.status != this.tile.getStatus()) - listener.sendProgressBarUpdate(this, this.resources.length + 1, this.tile.getStatus().ordinal()); + icrafting.sendProgressBarUpdate(this, this.resources.length + 1, this.tile.getStatus().ordinal()); for(int z = 0; z < this.resources.length; z++) { if(this.resources[z] != this.tile.getResource(z).getValue()) - listener.sendProgressBarUpdate(this, z, this.tile.getResource(z).getValue()); + icrafting.sendProgressBarUpdate(this, z, this.tile.getResource(z).getValue()); } } diff --git a/common/src/main/java/common/inventory/ContainerMerchant.java b/common/src/common/inventory/ContainerMerchant.java similarity index 97% rename from common/src/main/java/common/inventory/ContainerMerchant.java rename to common/src/common/inventory/ContainerMerchant.java index 96c4a4b..dd43752 100755 --- a/common/src/main/java/common/inventory/ContainerMerchant.java +++ b/common/src/common/inventory/ContainerMerchant.java @@ -115,7 +115,7 @@ public class ContainerMerchant extends Container return null; } - if (itemstack1.size == 0) + if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } @@ -124,7 +124,7 @@ public class ContainerMerchant extends Container slot.onSlotChanged(); } - if (itemstack1.size == itemstack.size) + if (itemstack1.stackSize == itemstack.stackSize) { return null; } diff --git a/common/src/main/java/common/inventory/ContainerPlayer.java b/common/src/common/inventory/ContainerPlayer.java similarity index 91% rename from common/src/main/java/common/inventory/ContainerPlayer.java rename to common/src/common/inventory/ContainerPlayer.java index 7db091b..1512068 100755 --- a/common/src/main/java/common/inventory/ContainerPlayer.java +++ b/common/src/common/inventory/ContainerPlayer.java @@ -3,7 +3,6 @@ package common.inventory; import java.util.List; import common.attributes.AttributeMap; -import common.attributes.UsageSlot; import common.collect.Lists; import common.entity.npc.EntityNPC; import common.init.CraftingRegistry; @@ -45,7 +44,7 @@ public class ContainerPlayer extends Container } public boolean isItemValid(ItemStack stack) { - return stack != null && stack.getItem() instanceof ItemArmor && ((ItemArmor)stack.getItem()).armorType.getArmorSlot() == k_f; // : (stack.getItem() != ItemRegistry.getItemFromBlock(Blocks.pumpkin) && stack.getItem() != Items.skull ? false : k_f == 0)); + return stack != null && stack.getItem() instanceof ItemArmor && ((ItemArmor)stack.getItem()).armorType == k_f; // : (stack.getItem() != ItemRegistry.getItemFromBlock(Blocks.pumpkin) && stack.getItem() != Items.skull ? false : k_f == 0)); } // public String getSlotTexture() // { @@ -91,12 +90,12 @@ public class ContainerPlayer extends Container { if (last != null) { - this.attributes.remove(last.getAttributeModifiers(UsageSlot.INVENTORY), slot.getIndex()); + this.attributes.removeAttributeModifiers(last.getAttributeModifiers(2), slot.getIndex(), last.stackSize); } if (current != null) { - this.attributes.add(current.getAttributeModifiers(UsageSlot.INVENTORY), slot.getIndex(), current.size); + this.attributes.applyAttributeModifiers(current.getAttributeModifiers(2), slot.getIndex(), current.stackSize); } last = current == null ? null : current.copy(); @@ -175,9 +174,9 @@ public class ContainerPlayer extends Container return null; } } - else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType.getArmorSlot())).getHasStack()) + else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType)).getHasStack()) { - int i = 5 + ((ItemArmor)itemstack.getItem()).armorType.getArmorSlot(); + int i = 5 + ((ItemArmor)itemstack.getItem()).armorType; if (!this.mergeItemStack(itemstack1, i, i + 1, false)) { @@ -203,7 +202,7 @@ public class ContainerPlayer extends Container return null; } - if (itemstack1.size == 0) + if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } @@ -212,7 +211,7 @@ public class ContainerPlayer extends Container slot.onSlotChanged(); } - if (itemstack1.size == itemstack.size) + if (itemstack1.stackSize == itemstack.stackSize) { return null; } diff --git a/common/src/main/java/common/inventory/ContainerRepair.java b/common/src/common/inventory/ContainerRepair.java similarity index 89% rename from common/src/main/java/common/inventory/ContainerRepair.java rename to common/src/common/inventory/ContainerRepair.java index 522df45..82da6ed 100755 --- a/common/src/main/java/common/inventory/ContainerRepair.java +++ b/common/src/common/inventory/ContainerRepair.java @@ -3,15 +3,15 @@ package common.inventory; import java.util.Iterator; import java.util.Map; -import common.block.tech.BlockAnvil; +import common.block.BlockAnvil; import common.enchantment.Enchantment; import common.enchantment.EnchantmentHelper; import common.entity.npc.EntityNPC; import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.item.ItemStack; import common.util.BlockPos; -import common.vars.Vars; import common.world.State; import common.world.World; @@ -66,14 +66,13 @@ public class ContainerRepair extends Container } public boolean canTakeStack(EntityNPC playerIn) { - return /* (playerIn.creative || */ playerIn.getManaPoints() >= ContainerRepair.this.maximumCost /* ) */ && ContainerRepair.this.maximumCost > 0 && this.getHasStack(); + return /* (playerIn.creative || */ playerIn.experienceLevel >= ContainerRepair.this.maximumCost /* ) */ && ContainerRepair.this.maximumCost > 0 && this.getHasStack(); } public void onPickupFromSlot(EntityNPC playerIn, ItemStack stack) { // if (!playerIn.creative) // { - if(!playerIn.worldObj.client) - playerIn.useMana(ContainerRepair.this.maximumCost); + playerIn.addExperienceLevel(-ContainerRepair.this.maximumCost); // } ContainerRepair.this.inputSlots.setInventorySlotContents(0, (ItemStack)null); @@ -82,9 +81,9 @@ public class ContainerRepair extends Container { ItemStack itemstack = ContainerRepair.this.inputSlots.getStackInSlot(1); - if (itemstack != null && itemstack.size > ContainerRepair.this.materialCost) + if (itemstack != null && itemstack.stackSize > ContainerRepair.this.materialCost) { - itemstack.size -= ContainerRepair.this.materialCost; + itemstack.stackSize -= ContainerRepair.this.materialCost; ContainerRepair.this.inputSlots.setInventorySlotContents(1, itemstack); } else @@ -100,7 +99,7 @@ public class ContainerRepair extends Container ContainerRepair.this.maximumCost = 0; State iblockstate = worldIn.getState(blockPosIn); - if (/* !playerIn.creative && */ !worldIn.client && Vars.anvilRepairDecay && iblockstate.getBlock() == Blocks.anvil && playerIn.getRNG().floatv() < 0.12F) + if (/* !playerIn.creative && */ !worldIn.client && Config.anvilRepairDecay && iblockstate.getBlock() == Blocks.anvil && playerIn.getRNG().floatv() < 0.12F) { int l = ((Integer)iblockstate.getValue(BlockAnvil.DAMAGE)).intValue(); ++l; @@ -177,14 +176,14 @@ public class ContainerRepair extends Container { ItemStack newStack = stack.copy(); ItemStack repStack = this.inputSlots.getStackInSlot(1); - Map newEnch = EnchantmentHelper.getEnchantments(newStack); + Map newEnch = EnchantmentHelper.getEnchantments(newStack); boolean isBook = false; repairCost = repairCost + stack.getRepairCost() + (repStack == null ? 0 : repStack.getRepairCost()); this.materialCost = 0; if (repStack != null) { - isBook = repStack.getItem() == Items.enchanted_book && Items.enchanted_book.getEnchantments(repStack).size() > 0; + isBook = repStack.getItem() == Items.enchanted_book && Items.enchanted_book.getEnchantments(repStack).tagCount() > 0; if (newStack.isItemStackDamageable() && newStack.getItem().getIsRepairable(stack, repStack)) { @@ -199,7 +198,7 @@ public class ContainerRepair extends Container int cost; - for (cost = 0; damage > 0 && cost < repStack.size; ++cost) + for (cost = 0; damage > 0 && cost < repStack.stackSize; ++cost) { int j5 = newStack.getItemDamage() - damage; newStack.setItemDamage(j5); @@ -238,17 +237,18 @@ public class ContainerRepair extends Container } } - Map ench = EnchantmentHelper.getEnchantments(repStack); - Iterator enchs = ench.keySet().iterator(); + Map ench = EnchantmentHelper.getEnchantments(repStack); + Iterator enchs = ench.keySet().iterator(); while (enchs.hasNext()) { - Enchantment enchantment = enchs.next(); + int eid = ((Integer)enchs.next()).intValue(); + Enchantment enchantment = Enchantment.getEnchantmentById(eid); if (enchantment != null) { - int newLevel = newEnch.containsKey(enchantment) ? newEnch.get(enchantment) : 0; - int level = ench.get(enchantment); + int newLevel = newEnch.containsKey(Integer.valueOf(eid)) ? ((Integer)newEnch.get(Integer.valueOf(eid))).intValue() : 0; + int level = ((Integer)ench.get(Integer.valueOf(eid))).intValue(); int diff; if (newLevel == level) @@ -269,13 +269,13 @@ public class ContainerRepair extends Container applies = true; } - Iterator newEnchs = newEnch.keySet().iterator(); + Iterator newEnchs = newEnch.keySet().iterator(); while (newEnchs.hasNext()) { - Enchantment nEid = newEnchs.next(); + int nEid = ((Integer)newEnchs.next()).intValue(); - if (nEid != enchantment && !enchantment.canApplyTogether(nEid)) + if (nEid != eid && !enchantment.canApplyTogether(Enchantment.getEnchantmentById(nEid))) { applies = false; ++totalCost; @@ -289,7 +289,7 @@ public class ContainerRepair extends Container level = enchantment.getMaxLevel(); } - newEnch.put(enchantment, level); + newEnch.put(Integer.valueOf(eid), Integer.valueOf(level)); int cost = 0; switch (enchantment.getWeight()) @@ -365,7 +365,7 @@ public class ContainerRepair extends Container if (newStack != null) { - if(!this.theWorld.client && Vars.repairXP) { + if(!this.theWorld.client && Config.repairXP) { int cost = newStack.getRepairCost(); if (repStack != null && cost < repStack.getRepairCost()) @@ -458,7 +458,7 @@ public class ContainerRepair extends Container return null; } - if (itemstack1.size == 0) + if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } @@ -467,7 +467,7 @@ public class ContainerRepair extends Container slot.onSlotChanged(); } - if (itemstack1.size == itemstack.size) + if (itemstack1.stackSize == itemstack.stackSize) { return null; } diff --git a/common/src/main/java/common/inventory/ContainerWorkbench.java b/common/src/common/inventory/ContainerWorkbench.java similarity index 63% rename from common/src/main/java/common/inventory/ContainerWorkbench.java rename to common/src/common/inventory/ContainerWorkbench.java index c0dbf6f..2dce2fc 100755 --- a/common/src/main/java/common/inventory/ContainerWorkbench.java +++ b/common/src/common/inventory/ContainerWorkbench.java @@ -1,7 +1,7 @@ package common.inventory; -import common.block.tech.BlockWorkbench; import common.entity.npc.EntityNPC; +import common.init.Blocks; import common.init.CraftingRegistry; import common.item.ItemStack; import common.util.BlockPos; @@ -9,28 +9,25 @@ import common.world.World; public class ContainerWorkbench extends Container { - private final int craftSlots; - public final InventoryCrafting craftMatrix; - public final IInventory craftResult = new InventoryCraftResult(); - private final World worldObj; - private final BlockPos pos; - private final BlockWorkbench block; + /** The crafting matrix inventory (3x3). */ + public InventoryCrafting craftMatrix = new InventoryCrafting(this, 3, 3); + public IInventory craftResult = new InventoryCraftResult(); + private World worldObj; - public ContainerWorkbench(InventoryPlayer playerInventory, World worldIn, BlockPos posIn, BlockWorkbench block) + /** Position of the workbench */ + private BlockPos pos; + + public ContainerWorkbench(InventoryPlayer playerInventory, World worldIn, BlockPos posIn) { - int size = block.getSize(); - this.block = block; this.worldObj = worldIn; this.pos = posIn; - this.craftSlots = size * size; - this.craftMatrix = new InventoryCrafting(this, size, size); - this.addSlotToContainer(new SlotCrafting(playerInventory.player, this.craftMatrix, this.craftResult, 0, 134, 17 + ((size - 1) * 18) / 2)); + this.addSlotToContainer(new SlotCrafting(playerInventory.player, this.craftMatrix, this.craftResult, 0, 124, 35)); - for (int i = 0; i < size; ++i) + for (int i = 0; i < 3; ++i) { - for (int j = 0; j < size; ++j) + for (int j = 0; j < 3; ++j) { - this.addSlotToContainer(new Slot(this.craftMatrix, j + i * size, 26 + j * 18, 17 + i * 18)); + this.addSlotToContainer(new Slot(this.craftMatrix, j + i * 3, 30 + j * 18, 17 + i * 18)); } } @@ -38,13 +35,13 @@ public class ContainerWorkbench extends Container { for (int i1 = 0; i1 < 9; ++i1) { - this.addSlotToContainer(new Slot(playerInventory, i1 + k * 9 + 9, 8 + i1 * 18, 30 + size * 18 + k * 18)); + this.addSlotToContainer(new Slot(playerInventory, i1 + k * 9 + 9, 8 + i1 * 18, 84 + k * 18)); } } for (int l = 0; l < 9; ++l) { - this.addSlotToContainer(new Slot(playerInventory, l, 8 + l * 18, 88 + size * 18)); + this.addSlotToContainer(new Slot(playerInventory, l, 8 + l * 18, 142)); } this.onCraftMatrixChanged(this.craftMatrix); @@ -67,7 +64,7 @@ public class ContainerWorkbench extends Container if (!this.worldObj.client) { - for (int i = 0; i < this.craftSlots; ++i) + for (int i = 0; i < 9; ++i) { ItemStack itemstack = this.craftMatrix.removeStackFromSlot(i); @@ -81,7 +78,7 @@ public class ContainerWorkbench extends Container public boolean canInteractWith(EntityNPC playerIn) { - return this.worldObj.getState(this.pos).getBlock() != this.block ? false : playerIn.getDistanceSq((double)this.pos.getX() + 0.5D, (double)this.pos.getY() + 0.5D, (double)this.pos.getZ() + 0.5D) <= 64.0D; + return this.worldObj.getState(this.pos).getBlock() != Blocks.crafting_table ? false : playerIn.getDistanceSq((double)this.pos.getX() + 0.5D, (double)this.pos.getY() + 0.5D, (double)this.pos.getZ() + 0.5D) <= 64.0D; } /** @@ -90,7 +87,7 @@ public class ContainerWorkbench extends Container public ItemStack transferStackInSlot(EntityNPC playerIn, int index) { ItemStack itemstack = null; - Slot slot = this.inventorySlots.get(index); + Slot slot = (Slot)this.inventorySlots.get(index); if (slot != null && slot.getHasStack()) { @@ -99,33 +96,33 @@ public class ContainerWorkbench extends Container if (index == 0) { - if (!this.mergeItemStack(itemstack1, this.craftSlots + 1, this.craftSlots + 37, true)) + if (!this.mergeItemStack(itemstack1, 10, 46, true)) { return null; } slot.onSlotChange(itemstack1, itemstack); } - else if (index >= this.craftSlots + 1 && index < this.craftSlots + 28) + else if (index >= 10 && index < 37) { - if (!this.mergeItemStack(itemstack1, this.craftSlots + 28, this.craftSlots + 37, false)) + if (!this.mergeItemStack(itemstack1, 37, 46, false)) { return null; } } - else if (index >= this.craftSlots + 28 && index < this.craftSlots + 37) + else if (index >= 37 && index < 46) { - if (!this.mergeItemStack(itemstack1, this.craftSlots + 1, this.craftSlots + 28, false)) + if (!this.mergeItemStack(itemstack1, 10, 37, false)) { return null; } } - else if (!this.mergeItemStack(itemstack1, this.craftSlots + 1, this.craftSlots + 37, false)) + else if (!this.mergeItemStack(itemstack1, 10, 46, false)) { return null; } - if (itemstack1.size == 0) + if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } @@ -134,7 +131,7 @@ public class ContainerWorkbench extends Container slot.onSlotChanged(); } - if (itemstack1.size == itemstack.size) + if (itemstack1.stackSize == itemstack.stackSize) { return null; } diff --git a/common/src/main/java/common/inventory/ICrafting.java b/common/src/common/inventory/ICrafting.java similarity index 100% rename from common/src/main/java/common/inventory/ICrafting.java rename to common/src/common/inventory/ICrafting.java diff --git a/common/src/main/java/common/inventory/IInvBasic.java b/common/src/common/inventory/IInvBasic.java similarity index 100% rename from common/src/main/java/common/inventory/IInvBasic.java rename to common/src/common/inventory/IInvBasic.java diff --git a/common/src/main/java/common/inventory/IInventory.java b/common/src/common/inventory/IInventory.java similarity index 100% rename from common/src/main/java/common/inventory/IInventory.java rename to common/src/common/inventory/IInventory.java diff --git a/common/src/main/java/common/inventory/ISidedInventory.java b/common/src/common/inventory/ISidedInventory.java similarity index 100% rename from common/src/main/java/common/inventory/ISidedInventory.java rename to common/src/common/inventory/ISidedInventory.java diff --git a/common/src/main/java/common/inventory/InventoryBasic.java b/common/src/common/inventory/InventoryBasic.java similarity index 92% rename from common/src/main/java/common/inventory/InventoryBasic.java rename to common/src/common/inventory/InventoryBasic.java index 1e7086d..15853bd 100755 --- a/common/src/main/java/common/inventory/InventoryBasic.java +++ b/common/src/common/inventory/InventoryBasic.java @@ -68,7 +68,7 @@ public class InventoryBasic implements IInventory { if (this.inventoryContents[index] != null) { - if (this.inventoryContents[index].size <= count) + if (this.inventoryContents[index].stackSize <= count) { ItemStack itemstack1 = this.inventoryContents[index]; this.inventoryContents[index] = null; @@ -79,7 +79,7 @@ public class InventoryBasic implements IInventory { ItemStack itemstack = this.inventoryContents[index].splitStack(count); - if (this.inventoryContents[index].size == 0) + if (this.inventoryContents[index].stackSize == 0) { this.inventoryContents[index] = null; } @@ -112,14 +112,14 @@ public class InventoryBasic implements IInventory if (ItemStack.areItemsEqual(itemstack1, itemstack)) { int j = Math.min(this.getInventoryStackLimit(), itemstack1.getMaxStackSize()); - int k = Math.min(itemstack.size, j - itemstack1.size); + int k = Math.min(itemstack.stackSize, j - itemstack1.stackSize); if (k > 0) { - itemstack1.size += k; - itemstack.size -= k; + itemstack1.stackSize += k; + itemstack.stackSize -= k; - if (itemstack.size <= 0) + if (itemstack.stackSize <= 0) { this.markDirty(); return null; @@ -128,7 +128,7 @@ public class InventoryBasic implements IInventory } } - if (itemstack.size != stack.size) + if (itemstack.stackSize != stack.stackSize) { this.markDirty(); } @@ -160,9 +160,9 @@ public class InventoryBasic implements IInventory { this.inventoryContents[index] = stack; - if (stack != null && stack.size > this.getInventoryStackLimit()) + if (stack != null && stack.stackSize > this.getInventoryStackLimit()) { - stack.size = this.getInventoryStackLimit(); + stack.stackSize = this.getInventoryStackLimit(); } this.markDirty(); diff --git a/common/src/main/java/common/inventory/InventoryCraftResult.java b/common/src/common/inventory/InventoryCraftResult.java similarity index 100% rename from common/src/main/java/common/inventory/InventoryCraftResult.java rename to common/src/common/inventory/InventoryCraftResult.java diff --git a/common/src/main/java/common/inventory/InventoryCrafting.java b/common/src/common/inventory/InventoryCrafting.java similarity index 97% rename from common/src/main/java/common/inventory/InventoryCrafting.java rename to common/src/common/inventory/InventoryCrafting.java index e026d87..e1b6d39 100755 --- a/common/src/main/java/common/inventory/InventoryCrafting.java +++ b/common/src/common/inventory/InventoryCrafting.java @@ -98,7 +98,7 @@ public class InventoryCrafting implements IInventory { if (this.stackList[index] != null) { - if (this.stackList[index].size <= count) + if (this.stackList[index].stackSize <= count) { ItemStack itemstack1 = this.stackList[index]; this.stackList[index] = null; @@ -109,7 +109,7 @@ public class InventoryCrafting implements IInventory { ItemStack itemstack = this.stackList[index].splitStack(count); - if (this.stackList[index].size == 0) + if (this.stackList[index].stackSize == 0) { this.stackList[index] = null; } diff --git a/common/src/main/java/common/inventory/InventoryHelper.java b/common/src/common/inventory/InventoryHelper.java similarity index 84% rename from common/src/main/java/common/inventory/InventoryHelper.java rename to common/src/common/inventory/InventoryHelper.java index 97dbb15..43d6151 100755 --- a/common/src/main/java/common/inventory/InventoryHelper.java +++ b/common/src/common/inventory/InventoryHelper.java @@ -3,6 +3,7 @@ package common.inventory; import common.entity.Entity; import common.entity.item.EntityItem; import common.item.ItemStack; +import common.nbt.NBTTagCompound; import common.rng.Random; import common.util.BlockPos; import common.world.World; @@ -40,21 +41,21 @@ public class InventoryHelper float f1 = RANDOM.floatv() * 0.8F + 0.1F; float f2 = RANDOM.floatv() * 0.8F + 0.1F; - while (stack.size > 0) + while (stack.stackSize > 0) { - int i = stack.size > 64 ? stack.size : (RANDOM.zrange(21) + 10); + int i = stack.stackSize > 64 ? stack.stackSize : (RANDOM.zrange(21) + 10); - if (i > stack.size) + if (i > stack.stackSize) { - i = stack.size; + i = stack.stackSize; } - stack.size -= i; + stack.stackSize -= i; EntityItem entityitem = new EntityItem(worldIn, x + (double)f, y + (double)f1, z + (double)f2, new ItemStack(stack.getItem(), i, stack.getMetadata())); if (stack.hasTagCompound()) { - entityitem.getEntityItem().setTagCompound(stack.getTagCompound().copy()); + entityitem.getEntityItem().setTagCompound((NBTTagCompound)stack.getTagCompound().copy()); } float f3 = 0.05F; diff --git a/common/src/main/java/common/inventory/InventoryLargeChest.java b/common/src/common/inventory/InventoryLargeChest.java similarity index 98% rename from common/src/main/java/common/inventory/InventoryLargeChest.java rename to common/src/common/inventory/InventoryLargeChest.java index 7021e91..85d9844 100755 --- a/common/src/main/java/common/inventory/InventoryLargeChest.java +++ b/common/src/common/inventory/InventoryLargeChest.java @@ -3,7 +3,7 @@ package common.inventory; import common.entity.npc.EntityNPC; import common.item.ItemStack; import common.tileentity.ILockableContainer; -import common.tileentity.Passcode; +import common.tileentity.LockCode; import common.tileentity.TileEntityChest; public class InventoryLargeChest implements ILockableContainer @@ -188,13 +188,13 @@ public class InventoryLargeChest implements ILockableContainer return this.upperChest.isLocked() || this.lowerChest.isLocked(); } - public void setLockCode(Passcode code) + public void setLockCode(LockCode code) { this.upperChest.setLockCode(code); this.lowerChest.setLockCode(code); } - public Passcode getLockCode() + public LockCode getLockCode() { return this.upperChest.getLockCode(); } diff --git a/common/src/main/java/common/inventory/InventoryMerchant.java b/common/src/common/inventory/InventoryMerchant.java similarity index 93% rename from common/src/main/java/common/inventory/InventoryMerchant.java rename to common/src/common/inventory/InventoryMerchant.java index b6f4baf..223bf4d 100755 --- a/common/src/main/java/common/inventory/InventoryMerchant.java +++ b/common/src/common/inventory/InventoryMerchant.java @@ -59,7 +59,7 @@ public class InventoryMerchant implements IInventory this.theInventory[index] = null; return itemstack2; } - else if (this.theInventory[index].size <= count) + else if (this.theInventory[index].stackSize <= count) { ItemStack itemstack1 = this.theInventory[index]; this.theInventory[index] = null; @@ -75,7 +75,7 @@ public class InventoryMerchant implements IInventory { ItemStack itemstack = this.theInventory[index].splitStack(count); - if (this.theInventory[index].size == 0) + if (this.theInventory[index].stackSize == 0) { this.theInventory[index] = null; } @@ -126,9 +126,9 @@ public class InventoryMerchant implements IInventory { this.theInventory[index] = stack; - if (stack != null && stack.size > this.getInventoryStackLimit()) + if (stack != null && stack.stackSize > this.getInventoryStackLimit()) { - stack.size = this.getInventoryStackLimit(); + stack.stackSize = this.getInventoryStackLimit(); } if (this.inventoryResetNeededOnSlotChange(index)) @@ -224,21 +224,21 @@ public class InventoryMerchant implements IInventory if (merchantrecipelist != null) { - MerchantRecipe merchantrecipe = merchantrecipelist.canUse(itemstack, itemstack1, this.currentRecipeIndex); + MerchantRecipe merchantrecipe = merchantrecipelist.canRecipeBeUsed(itemstack, itemstack1, this.currentRecipeIndex); if (merchantrecipe != null) // && !merchantrecipe.isRecipeDisabled()) { this.currentRecipe = merchantrecipe; - this.setInventorySlotContents(2, merchantrecipe.result().copy()); + this.setInventorySlotContents(2, merchantrecipe.getItemToSell().copy()); } else if (itemstack1 != null) { - merchantrecipe = merchantrecipelist.canUse(itemstack1, itemstack, this.currentRecipeIndex); + merchantrecipe = merchantrecipelist.canRecipeBeUsed(itemstack1, itemstack, this.currentRecipeIndex); if (merchantrecipe != null) // && !merchantrecipe.isRecipeDisabled()) { this.currentRecipe = merchantrecipe; - this.setInventorySlotContents(2, merchantrecipe.result().copy()); + this.setInventorySlotContents(2, merchantrecipe.getItemToSell().copy()); } else { diff --git a/common/src/main/java/common/inventory/InventoryPlayer.java b/common/src/common/inventory/InventoryPlayer.java similarity index 88% rename from common/src/main/java/common/inventory/InventoryPlayer.java rename to common/src/common/inventory/InventoryPlayer.java index 8802577..7b651c8 100755 --- a/common/src/main/java/common/inventory/InventoryPlayer.java +++ b/common/src/common/inventory/InventoryPlayer.java @@ -5,8 +5,8 @@ import common.entity.npc.EntityNPC; import common.item.Item; import common.item.ItemArmor; import common.item.ItemStack; -import common.tags.TagObject; -import java.util.List; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; public class InventoryPlayer implements IInventory { @@ -85,7 +85,7 @@ public class InventoryPlayer implements IInventory { for (int i = 0; i < this.mainInventory.length; ++i) { - if (this.mainInventory[i] != null && this.mainInventory[i].getItem() == itemStackIn.getItem() && this.mainInventory[i].isStackable() && this.mainInventory[i].size < this.mainInventory[i].getMaxStackSize() && this.mainInventory[i].size < this.getInventoryStackLimit() && (!this.mainInventory[i].getHasSubtypes() || this.mainInventory[i].getMetadata() == itemStackIn.getMetadata()) && ItemStack.areItemStackTagsEqual(this.mainInventory[i], itemStackIn)) + if (this.mainInventory[i] != null && this.mainInventory[i].getItem() == itemStackIn.getItem() && this.mainInventory[i].isStackable() && this.mainInventory[i].stackSize < this.mainInventory[i].getMaxStackSize() && this.mainInventory[i].stackSize < this.getInventoryStackLimit() && (!this.mainInventory[i].getHasSubtypes() || this.mainInventory[i].getMetadata() == itemStackIn.getMetadata()) && ItemStack.areItemStackTagsEqual(this.mainInventory[i], itemStackIn)) { return i; } @@ -196,7 +196,7 @@ public class InventoryPlayer implements IInventory private int storePartialItemStack(ItemStack itemStackIn) { Item item = itemStackIn.getItem(); - int i = itemStackIn.size; + int i = itemStackIn.stackSize; int j = this.storeItemStack(itemStackIn); if (j < 0) @@ -216,20 +216,20 @@ public class InventoryPlayer implements IInventory if (itemStackIn.hasTagCompound()) { - this.mainInventory[j].setTagCompound(itemStackIn.getTagCompound().copy()); + this.mainInventory[j].setTagCompound((NBTTagCompound)itemStackIn.getTagCompound().copy()); } } int k = i; - if (i > this.mainInventory[j].getMaxStackSize() - this.mainInventory[j].size) + if (i > this.mainInventory[j].getMaxStackSize() - this.mainInventory[j].stackSize) { - k = this.mainInventory[j].getMaxStackSize() - this.mainInventory[j].size; + k = this.mainInventory[j].getMaxStackSize() - this.mainInventory[j].stackSize; } - if (k > this.getInventoryStackLimit() - this.mainInventory[j].size) + if (k > this.getInventoryStackLimit() - this.mainInventory[j].stackSize) { - k = this.getInventoryStackLimit() - this.mainInventory[j].size; + k = this.getInventoryStackLimit() - this.mainInventory[j].stackSize; } if (k == 0) @@ -239,7 +239,7 @@ public class InventoryPlayer implements IInventory else { i = i - k; - this.mainInventory[j].size += k; + this.mainInventory[j].stackSize += k; // this.mainInventory[j].animationsToGo = 5; return i; } @@ -274,7 +274,7 @@ public class InventoryPlayer implements IInventory } else { - if (--this.mainInventory[i].size <= 0) + if (--this.mainInventory[i].stackSize <= 0) { this.mainInventory[i] = null; } @@ -297,7 +297,7 @@ public class InventoryPlayer implements IInventory */ public boolean addItemStackToInventory(final ItemStack itemStackIn) { - if (itemStackIn != null && itemStackIn.size != 0 && itemStackIn.getItem() != null) + if (itemStackIn != null && itemStackIn.stackSize != 0 && itemStackIn.getItem() != null) { if (itemStackIn.isItemDamaged()) { @@ -307,7 +307,7 @@ public class InventoryPlayer implements IInventory { this.mainInventory[j] = ItemStack.copyItemStack(itemStackIn); // this.mainInventory[j].animationsToGo = 5; - itemStackIn.size = 0; + itemStackIn.stackSize = 0; return true; } // else if (this.player.creative) @@ -326,10 +326,10 @@ public class InventoryPlayer implements IInventory while (true) { - i = itemStackIn.size; - itemStackIn.size = this.storePartialItemStack(itemStackIn); + i = itemStackIn.stackSize; + itemStackIn.stackSize = this.storePartialItemStack(itemStackIn); - if (itemStackIn.size <= 0 || itemStackIn.size >= i) + if (itemStackIn.stackSize <= 0 || itemStackIn.stackSize >= i) { break; } @@ -342,7 +342,7 @@ public class InventoryPlayer implements IInventory // } // else // { - return itemStackIn.size < i; + return itemStackIn.stackSize < i; // } } } @@ -367,7 +367,7 @@ public class InventoryPlayer implements IInventory if (aitemstack[index] != null) { - if (aitemstack[index].size <= count) + if (aitemstack[index].stackSize <= count) { ItemStack itemstack1 = aitemstack[index]; aitemstack[index] = null; @@ -377,7 +377,7 @@ public class InventoryPlayer implements IInventory { ItemStack itemstack = aitemstack[index].splitStack(count); - if (aitemstack[index].size == 0) + if (aitemstack[index].stackSize == 0) { aitemstack[index] = null; } @@ -450,16 +450,16 @@ public class InventoryPlayer implements IInventory * * @param nbtTagListIn List to append tags to */ - public List writeToNBT(List nbtTagListIn) + public NBTTagList writeToNBT(NBTTagList nbtTagListIn) { for (int i = 0; i < this.mainInventory.length; ++i) { if (this.mainInventory[i] != null) { - TagObject nbttagcompound = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setByte("Slot", (byte)i); - this.mainInventory[i].writeTags(nbttagcompound); - nbtTagListIn.add(nbttagcompound); + this.mainInventory[i].writeToNBT(nbttagcompound); + nbtTagListIn.appendTag(nbttagcompound); } } @@ -467,10 +467,10 @@ public class InventoryPlayer implements IInventory { if (this.armorInventory[j] != null) { - TagObject nbttagcompound1 = new TagObject(); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound1.setByte("Slot", (byte)(j + 100)); - this.armorInventory[j].writeTags(nbttagcompound1); - nbtTagListIn.add(nbttagcompound1); + this.armorInventory[j].writeToNBT(nbttagcompound1); + nbtTagListIn.appendTag(nbttagcompound1); } } @@ -482,16 +482,16 @@ public class InventoryPlayer implements IInventory * * @param nbtTagListIn tagList to read from */ - public void readFromNBT(List nbtTagListIn) + public void readFromNBT(NBTTagList nbtTagListIn) { this.mainInventory = new ItemStack[36]; this.armorInventory = new ItemStack[4]; - for (int i = 0; i < nbtTagListIn.size(); ++i) + for (int i = 0; i < nbtTagListIn.tagCount(); ++i) { - TagObject nbttagcompound = nbtTagListIn.get(i); + NBTTagCompound nbttagcompound = nbtTagListIn.getCompoundTagAt(i); int j = nbttagcompound.getByte("Slot") & 255; - ItemStack itemstack = ItemStack.readFromTag(nbttagcompound); + ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttagcompound); if (itemstack != null) { @@ -564,11 +564,17 @@ public class InventoryPlayer implements IInventory return ItemStack.MAX_SIZE; } - public boolean canHeldItemHarvest(Block block) { - if(!block.getMaterial().isToolRequired()) + public boolean canHeldItemHarvest(Block blockIn) + { + if (blockIn.getMaterial().isToolNotRequired()) + { return true; - ItemStack stack = this.getStackInSlot(this.currentItem); - return stack != null && stack.canHarvestBlock(block); + } + else + { + ItemStack itemstack = this.getStackInSlot(this.currentItem); + return itemstack != null ? itemstack.canHarvestBlock(blockIn) : false; + } } /** @@ -618,7 +624,7 @@ public class InventoryPlayer implements IInventory { this.armorInventory[i].damageItem(damage, this.player); - if (this.armorInventory[i].size == 0) + if (this.armorInventory[i].stackSize == 0) { this.armorInventory[i] = null; } diff --git a/common/src/main/java/common/inventory/InventoryWarpChest.java b/common/src/common/inventory/InventoryWarpChest.java similarity index 70% rename from common/src/main/java/common/inventory/InventoryWarpChest.java rename to common/src/common/inventory/InventoryWarpChest.java index af5b384..4d83f60 100755 --- a/common/src/main/java/common/inventory/InventoryWarpChest.java +++ b/common/src/common/inventory/InventoryWarpChest.java @@ -1,11 +1,10 @@ package common.inventory; -import common.collect.Lists; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.item.ItemStack; -import common.tags.TagObject; -import java.util.List; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.util.BlockPos; public class InventoryWarpChest extends InventoryBasic @@ -22,28 +21,28 @@ public class InventoryWarpChest extends InventoryBasic this.associatedChest = chestTileEntity; } - public void readTags(List list) + public void loadInventoryFromNBT(NBTTagList p_70486_1_) { for (int i = 0; i < this.getSizeInventory(); ++i) { this.setInventorySlotContents(i, (ItemStack)null); } - for (int k = 0; k < list.size(); ++k) + for (int k = 0; k < p_70486_1_.tagCount(); ++k) { - TagObject tag = list.get(k); - int j = tag.getByte("Slot") & 255; + NBTTagCompound nbttagcompound = p_70486_1_.getCompoundTagAt(k); + int j = nbttagcompound.getByte("Slot") & 255; if (j >= 0 && j < this.getSizeInventory()) { - this.setInventorySlotContents(j, ItemStack.readFromTag(tag)); + this.setInventorySlotContents(j, ItemStack.loadItemStackFromNBT(nbttagcompound)); } } } - public List writeTags() + public NBTTagList saveInventoryToNBT() { - List list = Lists.newArrayList(); + NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < this.getSizeInventory(); ++i) { @@ -51,14 +50,14 @@ public class InventoryWarpChest extends InventoryBasic if (itemstack != null) { - TagObject tag = new TagObject(); - tag.setByte("Slot", (byte)i); - itemstack.writeTags(tag); - list.add(tag); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setByte("Slot", (byte)i); + itemstack.writeToNBT(nbttagcompound); + nbttaglist.appendTag(nbttagcompound); } } - return list; + return nbttaglist; } public boolean isUseableByPlayer(EntityNPC player) diff --git a/common/src/main/java/common/inventory/Slot.java b/common/src/common/inventory/Slot.java similarity index 98% rename from common/src/main/java/common/inventory/Slot.java rename to common/src/common/inventory/Slot.java index d386abc..9176b08 100755 --- a/common/src/main/java/common/inventory/Slot.java +++ b/common/src/common/inventory/Slot.java @@ -37,7 +37,7 @@ public class Slot { if (p_75220_1_.getItem() == p_75220_2_.getItem()) { - int i = p_75220_2_.size - p_75220_1_.size; + int i = p_75220_2_.stackSize - p_75220_1_.stackSize; if (i > 0) { diff --git a/common/src/main/java/common/inventory/SlotCrafting.java b/common/src/common/inventory/SlotCrafting.java similarity index 99% rename from common/src/main/java/common/inventory/SlotCrafting.java rename to common/src/common/inventory/SlotCrafting.java index 363b5e9..a598f45 100755 --- a/common/src/main/java/common/inventory/SlotCrafting.java +++ b/common/src/common/inventory/SlotCrafting.java @@ -40,7 +40,7 @@ public class SlotCrafting extends Slot { if (this.getHasStack()) { - this.amountCrafted += Math.min(amount, this.getStack().size); + this.amountCrafted += Math.min(amount, this.getStack().stackSize); } return super.decrStackSize(amount); diff --git a/common/src/main/java/common/inventory/SlotFurnaceFuel.java b/common/src/common/inventory/SlotFurnaceFuel.java similarity index 100% rename from common/src/main/java/common/inventory/SlotFurnaceFuel.java rename to common/src/common/inventory/SlotFurnaceFuel.java diff --git a/common/src/main/java/common/inventory/SlotFurnaceOutput.java b/common/src/common/inventory/SlotFurnaceOutput.java similarity index 94% rename from common/src/main/java/common/inventory/SlotFurnaceOutput.java rename to common/src/common/inventory/SlotFurnaceOutput.java index 877db02..930318a 100755 --- a/common/src/main/java/common/inventory/SlotFurnaceOutput.java +++ b/common/src/common/inventory/SlotFurnaceOutput.java @@ -2,10 +2,10 @@ package common.inventory; import common.entity.item.EntityXp; import common.entity.npc.EntityNPC; +import common.init.Config; import common.init.SmeltingRegistry; import common.item.ItemStack; import common.util.ExtMath; -import common.vars.Vars; public class SlotFurnaceOutput extends Slot { @@ -35,7 +35,7 @@ public class SlotFurnaceOutput extends Slot { if (this.getHasStack()) { - this.smelted += Math.min(amount, this.getStack().size); + this.smelted += Math.min(amount, this.getStack().stackSize); } return super.decrStackSize(amount); @@ -64,7 +64,7 @@ public class SlotFurnaceOutput extends Slot { // stack.onCrafting(this.thePlayer.worldObj, this.thePlayer, this.smelted); - if (!this.thePlayer.worldObj.client && Vars.smeltingXP) + if (!this.thePlayer.worldObj.client && Config.smeltingXP) { int xp = this.smelted; float smeltXp = SmeltingRegistry.getExperience(stack); diff --git a/common/src/main/java/common/inventory/SlotMerchantResult.java b/common/src/common/inventory/SlotMerchantResult.java similarity index 87% rename from common/src/main/java/common/inventory/SlotMerchantResult.java rename to common/src/common/inventory/SlotMerchantResult.java index 05172d5..01998ee 100755 --- a/common/src/main/java/common/inventory/SlotMerchantResult.java +++ b/common/src/common/inventory/SlotMerchantResult.java @@ -35,7 +35,7 @@ public class SlotMerchantResult extends Slot { if (this.getHasStack()) { - this.traded += Math.min(amount, this.getStack().size); + this.traded += Math.min(amount, this.getStack().stackSize); } return super.decrStackSize(amount); @@ -76,12 +76,12 @@ public class SlotMerchantResult extends Slot // this.theMerchant.useRecipe(merchantrecipe); // playerIn.triggerAchievement(StatRegistry.timesTradedWithNpcStat); - if (itemstack != null && itemstack.size <= 0) + if (itemstack != null && itemstack.stackSize <= 0) { itemstack = null; } - if (itemstack1 != null && itemstack1.size <= 0) + if (itemstack1 != null && itemstack1.stackSize <= 0) { itemstack1 = null; } @@ -94,21 +94,21 @@ public class SlotMerchantResult extends Slot private boolean doTrade(MerchantRecipe trade, ItemStack firstItem, ItemStack secondItem) { - ItemStack itemstack = trade.first(); - ItemStack itemstack1 = trade.second(); + ItemStack itemstack = trade.getItemToBuy(); + ItemStack itemstack1 = trade.getSecondItemToBuy(); if (firstItem != null && firstItem.getItem() == itemstack.getItem()) { if (itemstack1 != null && secondItem != null && itemstack1.getItem() == secondItem.getItem()) { - firstItem.size -= itemstack.size; - secondItem.size -= itemstack1.size; + firstItem.stackSize -= itemstack.stackSize; + secondItem.stackSize -= itemstack1.stackSize; return true; } if (itemstack1 == null && secondItem == null) { - firstItem.size -= itemstack.size; + firstItem.stackSize -= itemstack.stackSize; return true; } } diff --git a/common/src/common/item/CheatTab.java b/common/src/common/item/CheatTab.java new file mode 100755 index 0000000..83729d0 --- /dev/null +++ b/common/src/common/item/CheatTab.java @@ -0,0 +1,171 @@ +package common.item; + +import java.util.List; + +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; + +public enum CheatTab +{ + tabBlocks("Baumaterial") + { + protected Item getTabIconItem() + { + return ItemRegistry.getItemFromBlock(Blocks.glass); + } + }, + tabNature("Gestein und Natur") + { + protected Item getTabIconItem() + { + return ItemRegistry.getItemFromBlock(Blocks.grass); + } + }, + tabWood("Holz") + { + protected Item getTabIconItem() + { + return ItemRegistry.getItemFromBlock(Blocks.maple_planks); + } + }, + tabPlants("Pflanzen") + { + protected Item getTabIconItem() + { + return ItemRegistry.getItemFromBlock(Blocks.oak_leaves); + } + }, + tabDeco("Dekoration") + { + protected Item getTabIconItem() + { + return ItemRegistry.getItemFromBlock(Blocks.hay_block); + } + }, + tabTech("Redstone & Technik") + { + protected Item getTabIconItem() + { + return ItemRegistry.getItemFromBlock(Blocks.tnt); + } + }, + tabGems("Erze & Teure Blöcke") + { + protected Item getTabIconItem() + { + return ItemRegistry.getItemFromBlock(Blocks.diamond_block); + } + }, + tabSpawners("Mob & Itemspawner") + { + protected Item getTabIconItem() + { + return Items.minecart; + } + }, + tabTools("Werkzeug") + { + protected Item getTabIconItem() + { + return Items.flint_and_steel; + } + }, + tabLiquids("Flüssigkeiten") + { + protected Item getTabIconItem() + { + return Items.water_bucket; + } + }, + tabCombat("Kampf") + { + protected Item getTabIconItem() + { + return Items.bow; + } + }, + tabMagic("Tränke & Verzauberungen") + { + protected Item getTabIconItem() + { + return Items.potion; + } + protected int getIconItemDamage() + { + return 8261; + } + }, + tabMaterials("Werkstoffe") + { + protected Item getTabIconItem() + { + return Items.leather; + } + }, + tabMetals("Metalle und Juwelen") + { + protected Item getTabIconItem() + { + return Items.iron_ingot; + } + }, + tabMisc("Verschiedenes & Nahrung") + { + protected Item getTabIconItem() + { + return Items.charge_crystal; + } + }; + + private final String name; + private ItemStack iconItemStack; + + private CheatTab(String name) + { + this.name = name; + } + + public int getHorizontal() + { + return this.ordinal() % 12; + } + + public int getVertical() + { + return this.ordinal() / 12; + } + + public String getName() + { + return this.name; + } + + public ItemStack getIconItemStack() + { + if (this.iconItemStack == null) + { + this.iconItemStack = new ItemStack(this.getTabIconItem(), 1, this.getIconItemDamage()); + } + + return this.iconItemStack; + } + + protected abstract Item getTabIconItem(); + + protected int getIconItemDamage() + { + return 0; + } + + public void displayAllReleventItems(List list) + { + for (Item item : ItemRegistry.REGISTRY) + { + if (item != null && item.getTab() == this) + { + item.getSubItems(item, this, list); + } + } + } +} diff --git a/common/src/main/java/common/item/Item.java b/common/src/common/item/Item.java similarity index 93% rename from common/src/main/java/common/item/Item.java rename to common/src/common/item/Item.java index daa6b61..f968ee9 100755 --- a/common/src/main/java/common/item/Item.java +++ b/common/src/common/item/Item.java @@ -5,8 +5,9 @@ import java.util.Map; import java.util.Set; import common.attributes.Attribute; -import common.attributes.UsageSlot; +import common.attributes.AttributeModifier; import common.block.Block; +import common.collect.Maps; import common.collect.Sets; import common.color.TextColor; import common.entity.npc.EntityNPC; @@ -15,8 +16,8 @@ import common.model.ItemMeshDefinition; import common.model.Model; import common.model.ModelProvider; import common.model.Transforms; +import common.nbt.NBTTagCompound; import common.rng.Random; -import common.tags.TagObject; import common.util.BlockPos; import common.util.ExtMath; import common.util.Facing; @@ -104,7 +105,7 @@ public class Item /** * Called when an ItemStack with NBT data is read to potentially that ItemStack's NBT data */ - public boolean updateItemStackNBT(TagObject nbt) + public boolean updateItemStackNBT(NBTTagCompound nbt) { return false; } @@ -230,6 +231,14 @@ public class Item return this.display; } + /** + * If this function returns true (or the item is damageable), the ItemStack's NBT tag will be sent to the client. + */ + public boolean getShareTag() + { + return true; + } + public Item getContainerItem() { return this.containerItem; @@ -386,13 +395,15 @@ public class Item { return false; } - - public int getAttackDamageBonus() { - return 0; + + public Map> getItemAttributeModifiers() + { + return Maps.newHashMap(); } - public void getModifiers(Map map, UsageSlot slot) + public Map> getItemInventoryModifiers() { + return Maps.newHashMap(); } // public boolean canBeDyed() { @@ -417,7 +428,7 @@ public class Item // private static final Set VALID_TAGS = Sets.newHashSet("Name", "ench", "RepairCost"); - protected final boolean validateNbt(TagObject tag) { + protected final boolean validateNbt(NBTTagCompound tag) { return true; } @@ -467,14 +478,14 @@ public class Item // return false; // } //// if(tag.hasKey("display")) { -//// if(!tag.hasTag("display")) { +//// if(!tag.hasKey("display", 10)) { //// return false; //// } //// NBTTagCompound display = tag.getCompoundTag("display"); //// keys = display.getKeySet(); //// z = keys.size(); // if(tag.hasKey("Name")) { -// if(!tag.hasString("Name")) { +// if(!tag.hasKey("Name", 8)) { // return false; // } // if(tag.getString("Name").length() > 64) { @@ -494,7 +505,7 @@ public class Item //// } //// } //// else { -//// if(!display.hasList("Lore")) { +//// if(!display.hasKey("Lore", 9)) { //// return false; //// } //// NBTTagList lore = display.getTagList("Lore", 8); @@ -505,7 +516,7 @@ public class Item //// z--; //// } //// if(display.hasKey("color")) { -//// if(!display.hasInt("color")) { +//// if(!display.hasKey("color", 3)) { //// return false; //// } //// if(!this.canBeDyed()) { @@ -518,7 +529,7 @@ public class Item //// } //// } // if(tag.hasKey("RepairCost")) { -// if(!tag.hasInt("RepairCost")) { +// if(!tag.hasKey("RepairCost", 3)) { // return false; // } // if(tag.getInteger("RepairCost") < 1) { @@ -526,7 +537,7 @@ public class Item // } // } // if(tag.hasKey("ench")) { -// if(!tag.hasList("ench")) { +// if(!tag.hasKey("ench", 9)) { // return false; // } // NBTTagList ench = tag.getTagList("ench", 10); @@ -539,7 +550,7 @@ public class Item // Enchantment[] ecn = new Enchantment[ench.tagCount()]; // for(int e = 0; e < ench.tagCount(); e++) { // NBTTagCompound ec = ench.getCompoundTagAt(e); -// if(ec.getKeySet().size() != 2 || !ec.hasShort("id") || !ec.hasShort("lvl")) { +// if(ec.getKeySet().size() != 2 || !ec.hasKey("id", 2) || !ec.hasKey("lvl", 2)) { // return false; // } // int id = ec.getShort("id"); @@ -566,12 +577,12 @@ public class Item // } //// if(adv) { //// if(tag.hasKey("Unbreakable")) { -//// if(!tag.hasBoolean("Unbreakable")) { +//// if(!tag.hasKey("Unbreakable", 1)) { //// return false; //// } //// } //// if(tag.hasKey("HideFlags")) { -//// if(!tag.hasInt("HideFlags")) { +//// if(!tag.hasKey("HideFlags", 3)) { //// return false; //// } //// } diff --git a/common/src/main/java/common/item/ItemAction.java b/common/src/common/item/ItemAction.java similarity index 100% rename from common/src/main/java/common/item/ItemAction.java rename to common/src/common/item/ItemAction.java diff --git a/common/src/main/java/common/item/ItemAmmo.java b/common/src/common/item/ItemAmmo.java similarity index 90% rename from common/src/main/java/common/item/ItemAmmo.java rename to common/src/common/item/ItemAmmo.java index e76602a..9f1b64b 100755 --- a/common/src/main/java/common/item/ItemAmmo.java +++ b/common/src/common/item/ItemAmmo.java @@ -6,7 +6,7 @@ public class ItemAmmo extends ItemMagnetic { public ItemAmmo(int damage, float explosion, int stack) { this.maxStackSize = stack; - this.setTab(CheatTab.COMBAT); + this.setTab(CheatTab.tabCombat); this.damage = damage; this.explosion = explosion; } diff --git a/common/src/main/java/common/item/ItemAnvilBlock.java b/common/src/common/item/ItemAnvilBlock.java similarity index 100% rename from common/src/main/java/common/item/ItemAnvilBlock.java rename to common/src/common/item/ItemAnvilBlock.java diff --git a/common/src/main/java/common/item/ItemAppleGold.java b/common/src/common/item/ItemAppleGold.java similarity index 100% rename from common/src/main/java/common/item/ItemAppleGold.java rename to common/src/common/item/ItemAppleGold.java diff --git a/common/src/main/java/common/item/ItemArmor.java b/common/src/common/item/ItemArmor.java similarity index 78% rename from common/src/main/java/common/item/ItemArmor.java rename to common/src/common/item/ItemArmor.java index 3c5722c..09e371e 100755 --- a/common/src/main/java/common/item/ItemArmor.java +++ b/common/src/common/item/ItemArmor.java @@ -2,11 +2,14 @@ package common.item; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Predicate; import common.attributes.Attribute; -import common.attributes.UsageSlot; -import common.block.tech.BlockDispenser; +import common.attributes.AttributeModifier; +import common.attributes.Attributes; +import common.block.BlockDispenser; +import common.collect.Sets; import common.dispenser.BehaviorDefaultDispenseItem; import common.dispenser.IBehaviorDispenseItem; import common.dispenser.IBlockSource; @@ -17,7 +20,7 @@ import common.init.ToolMaterial; import common.model.Model; import common.model.ModelProvider; import common.model.Transforms; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BlockPos; import common.util.BoundingBox; import common.world.World; @@ -47,7 +50,7 @@ public class ItemArmor extends Item int l = entitylivingbase.isPlayer() ? 1 : 0; int i1 = ItemArmor.getArmorPosition(stack); ItemStack itemstack = stack.copy(); - itemstack.size = 1; + itemstack.stackSize = 1; entitylivingbase.setItem(i1 - l, itemstack); // if (entitylivingbase instanceof EntityLiving) @@ -55,7 +58,7 @@ public class ItemArmor extends Item // ((EntityLiving)entitylivingbase).setDropChance(i1, 2.0F); // } - --stack.size; + --stack.stackSize; return stack; } else @@ -68,7 +71,7 @@ public class ItemArmor extends Item /** * Stores the armor type: 0 is helmet, 1 is plate, 2 is legs and 3 is boots */ - public final UsageSlot armorType; + public final int armorType; /** Holds the amount of damage that the armor reduces at full durability. */ public final int damageReduceAmount; @@ -83,7 +86,7 @@ public class ItemArmor extends Item private final ToolMaterial material; private final String texture; - public ItemArmor(ToolMaterial material, String texture, UsageSlot armorType) + public ItemArmor(ToolMaterial material, String texture, int armorType) { this.material = material; this.texture = texture; @@ -92,7 +95,7 @@ public class ItemArmor extends Item this.damageReduceAmount = material.getDamageReduction(armorType); this.setMaxDamage(material.getDurability(armorType)); this.maxStackSize = 1; - this.setTab(CheatTab.COMBAT); + this.setTab(CheatTab.tabCombat); DispenserRegistry.REGISTRY.putObject(this, dispenserBehavior); } @@ -141,7 +144,7 @@ public class ItemArmor extends Item */ public boolean hasColor(ItemStack stack) { - return this.material.canBeDyed() && stack.hasTagCompound() && stack.getTagCompound().hasInt("color"); + return this.material.canBeDyed() && stack.hasTagCompound() && stack.getTagCompound().hasKey("color", 3); } /** @@ -155,15 +158,15 @@ public class ItemArmor extends Item } else { - TagObject nbttagcompound = stack.getTagCompound(); + NBTTagCompound nbttagcompound = stack.getTagCompound(); - if (nbttagcompound != null && nbttagcompound.hasInt("color")) + if (nbttagcompound != null && nbttagcompound.hasKey("color", 3)) { // NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); // -// if (nbttagcompound1 != null && nbttagcompound1.hasInt("color")) +// if (nbttagcompound1 != null && nbttagcompound1.hasKey("color", 3)) // { - return nbttagcompound.getInt("color"); + return nbttagcompound.getInteger("color"); // } } @@ -178,16 +181,16 @@ public class ItemArmor extends Item { if (this.material.canBeDyed()) { - TagObject nbttagcompound = stack.getTagCompound(); + NBTTagCompound nbttagcompound = stack.getTagCompound(); if (nbttagcompound != null) { // NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); - if (nbttagcompound.hasInt("color")) + if (nbttagcompound.hasKey("color")) { - nbttagcompound.remove("color"); - if(nbttagcompound.isEmpty()) + nbttagcompound.removeTag("color"); + if(nbttagcompound.hasNoTags()) stack.setTagCompound(null); } } @@ -205,22 +208,22 @@ public class ItemArmor extends Item } else { - TagObject nbttagcompound = stack.getTagCompound(); + NBTTagCompound nbttagcompound = stack.getTagCompound(); if (nbttagcompound == null) { - nbttagcompound = new TagObject(); + nbttagcompound = new NBTTagCompound(); stack.setTagCompound(nbttagcompound); } // NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); // -// if (!nbttagcompound.hasTag("display")) +// if (!nbttagcompound.hasKey("display", 10)) // { // nbttagcompound.setTag("display", nbttagcompound1); // } - nbttagcompound.setInt("color", color); + nbttagcompound.setInteger("color", color); } } @@ -243,7 +246,7 @@ public class ItemArmor extends Item if (itemstack == null) { playerIn.setItem(i, itemStackIn.copy()); - itemStackIn.size = 0; + itemStackIn.stackSize = 0; } return itemStackIn; @@ -253,14 +256,18 @@ public class ItemArmor extends Item // return this.material.canBeDyed(); // } - public void getModifiers(Map map, UsageSlot slot) + public Map> getItemAttributeModifiers() { - if(slot != null && slot != this.armorType) - return; + Map> multimap = super.getItemAttributeModifiers(); if(this.material.getRadiationReduction(this.armorType) > 0.0f) - map.put(Attribute.RADIATION_RESISTANCE, this.material.getRadiationReduction(this.armorType)); + multimap.put(Attributes.RADIATION_RESISTANCE, + Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID + (long)this.armorType + 1L, "Armor modifier " + (this.armorType + 1), + (double)this.material.getRadiationReduction(this.armorType), false))); if(this.material.getMagicReduction(this.armorType) > 0.0f) - map.put(Attribute.MAGIC_RESISTANCE, this.material.getMagicReduction(this.armorType)); + multimap.put(Attributes.MAGIC_RESISTANCE, + Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID + (long)this.armorType + 1L, "Armor modifier " + (this.armorType + 1), + (double)this.material.getMagicReduction(this.armorType), false))); + return multimap; } public boolean isMagnetic() { @@ -268,7 +275,7 @@ public class ItemArmor extends Item } public Transforms getTransform() { - return this.armorType == UsageSlot.HEAD ? Transforms.OFFSET2 : (this.armorType == UsageSlot.FEET ? Transforms.OFFSET1 : + return this.armorType == 0 ? Transforms.OFFSET2 : (this.armorType == 3 ? Transforms.OFFSET1 : super.getTransform()); } @@ -282,8 +289,8 @@ public class ItemArmor extends Item public void addInformation(ItemStack stack, EntityNPC playerIn, List tooltip) { if(this.material.canBeDyed()) { int color = this.material.getDefaultColor(); - if(stack.hasTagCompound() && stack.getTagCompound().hasInt("color")) - color = stack.getTagCompound().getInt("color"); + if(stack.hasTagCompound() && stack.getTagCompound().hasKey("color", 3)) + color = stack.getTagCompound().getInteger("color"); tooltip.add("Farbe: #" + Integer.toHexString(color).toUpperCase()); } } @@ -296,16 +303,16 @@ public class ItemArmor extends Item // if(stack.getItem() != ItemRegistry.getItemFromBlock(Blocks.pumpkin) && stack.getItem() != Items.skull) { if(stack.getItem() instanceof ItemArmor) { switch(((ItemArmor)stack.getItem()).armorType) { - case HEAD: + case 0: return 4; - case BODY: + case 1: return 3; - case LEGS: + case 2: return 2; - case FEET: + case 3: return 1; } } diff --git a/common/src/common/item/ItemAxe.java b/common/src/common/item/ItemAxe.java new file mode 100755 index 0000000..2a2ccc6 --- /dev/null +++ b/common/src/common/item/ItemAxe.java @@ -0,0 +1,22 @@ +package common.item; + +import common.block.Block; +import common.init.ToolMaterial; + +public class ItemAxe extends ItemTool +{ +// private static final Set EFFECTIVE_ON = Sets.newHashSet(new Block[] { +// Blocks.planks, Blocks.bookshelf, Blocks.log, Blocks.log2, Blocks.chest, Blocks.pumpkin, Blocks.lit_pumpkin, Blocks.melon_block, Blocks.ladder +// }); + + public ItemAxe(ToolMaterial material) + { + super(3, material); + } + + public boolean canUseOn(ItemStack stack, Block state) + { + return state.canAxeHarvest() /* state.getMaterial() != Material.wood && state.getMaterial() != Material.plants && state.getMaterial() != Material.vine ? + super.getStrVsBlock(stack, state) */; + } +} diff --git a/common/src/main/java/common/item/ItemBanHammer.java b/common/src/common/item/ItemBanHammer.java similarity index 100% rename from common/src/main/java/common/item/ItemBanHammer.java rename to common/src/common/item/ItemBanHammer.java diff --git a/common/src/main/java/common/item/ItemBanner.java b/common/src/common/item/ItemBanner.java similarity index 82% rename from common/src/main/java/common/item/ItemBanner.java rename to common/src/common/item/ItemBanner.java index c5c76f6..dc04e64 100755 --- a/common/src/main/java/common/item/ItemBanner.java +++ b/common/src/common/item/ItemBanner.java @@ -2,15 +2,16 @@ package common.item; import java.util.List; -import common.block.tile.BlockStandingSign; -import common.block.tile.BlockWallSign; +import common.block.BlockStandingSign; +import common.block.BlockWallSign; import common.color.DyeColor; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.model.ItemMeshDefinition; import common.model.Model; import common.model.ModelProvider; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.tileentity.TileEntity; import common.tileentity.TileEntityBanner; import common.util.BlockPos; @@ -23,7 +24,7 @@ public class ItemBanner extends ItemBlock public ItemBanner() { super(Blocks.banner); - this.setTab(CheatTab.DECORATION); + this.setTab(CheatTab.tabDeco); this.setHasSubtypes(true); this.setMaxDamage(0); } @@ -69,7 +70,7 @@ public class ItemBanner extends ItemBlock worldIn.setState(pos, Blocks.wall_banner.getState().withProperty(BlockWallSign.FACING, side), 3); } - --stack.size; + --stack.stackSize; TileEntity tileentity = worldIn.getTileEntity(pos); if (tileentity instanceof TileEntityBanner) @@ -95,16 +96,16 @@ public class ItemBanner extends ItemBlock */ public void addInformation(ItemStack stack, EntityNPC playerIn, List tooltip) { - TagObject nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - if (nbttagcompound != null && nbttagcompound.hasList("Patterns")) + if (nbttagcompound != null && nbttagcompound.hasKey("Patterns")) { - List nbttaglist = nbttagcompound.getList("Patterns"); + NBTTagList nbttaglist = nbttagcompound.getTagList("Patterns", 10); - for (int i = 0; i < nbttaglist.size() && i < 6; ++i) + for (int i = 0; i < nbttaglist.tagCount() && i < 6; ++i) { - TagObject nbttagcompound1 = nbttaglist.get(i); - DyeColor enumdyecolor = DyeColor.byDyeDamage(nbttagcompound1.getInt("Color")); + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + DyeColor enumdyecolor = DyeColor.byDyeDamage(nbttagcompound1.getInteger("Color")); TileEntityBanner.EnumBannerPattern pattern = TileEntityBanner.EnumBannerPattern.getPatternByID(nbttagcompound1.getString("Pattern")); if (pattern != null) @@ -136,10 +137,10 @@ public class ItemBanner extends ItemBlock { for (DyeColor enumdyecolor : DyeColor.values()) { - TagObject nbttagcompound = new TagObject(); - TileEntityBanner.setBaseColorAndPatterns(nbttagcompound, enumdyecolor.getDyeDamage(), null); - TagObject nbttagcompound1 = new TagObject(); - nbttagcompound1.setObject("BlockEntityTag", nbttagcompound); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + TileEntityBanner.setBaseColorAndPatterns(nbttagcompound, enumdyecolor.getDyeDamage(), (NBTTagList)null); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setTag("BlockEntityTag", nbttagcompound); ItemStack itemstack = new ItemStack(itemIn, 1, enumdyecolor.getDyeDamage()); itemstack.setTagCompound(nbttagcompound1); subItems.add(itemstack); @@ -151,17 +152,17 @@ public class ItemBanner extends ItemBlock */ public CheatTab getTab() { - return CheatTab.DECORATION; + return CheatTab.tabDeco; } private DyeColor getBaseColor(ItemStack stack) { - TagObject nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); DyeColor enumdyecolor = null; - if (nbttagcompound != null && nbttagcompound.hasInt("Base")) + if (nbttagcompound != null && nbttagcompound.hasKey("Base")) { - enumdyecolor = DyeColor.byDyeDamage(nbttagcompound.getInt("Base")); + enumdyecolor = DyeColor.byDyeDamage(nbttagcompound.getInteger("Base")); } else { @@ -173,12 +174,12 @@ public class ItemBanner extends ItemBlock // protected boolean validateNbt(NBTTagCompound tag) { // if(tag.hasKey("BlockEntityTag")) { -// if(!tag.hasTag("BlockEntityTag")) { +// if(!tag.hasKey("BlockEntityTag", 10)) { // return false; // } // NBTTagCompound etag = tag.getCompoundTag("BlockEntityTag"); // if(etag.hasKey("Patterns")) { -// if(!etag.hasList("Patterns")) { +// if(!etag.hasKey("Patterns", 9)) { // return false; // } // NBTTagList patterns = etag.getTagList("Patterns", 10); @@ -191,7 +192,7 @@ public class ItemBanner extends ItemBlock // } // } // if(etag.hasKey("Base")) { -// if(!etag.hasInt("Base")) { +// if(!etag.hasKey("Base", 3)) { // return false; // } // } diff --git a/common/src/main/java/common/item/ItemBed.java b/common/src/common/item/ItemBed.java similarity index 95% rename from common/src/main/java/common/item/ItemBed.java rename to common/src/common/item/ItemBed.java index 0f17218..f2c927e 100755 --- a/common/src/main/java/common/item/ItemBed.java +++ b/common/src/common/item/ItemBed.java @@ -1,7 +1,7 @@ package common.item; import common.block.Block; -import common.block.artificial.BlockBed; +import common.block.BlockBed; import common.entity.npc.EntityNPC; import common.util.BlockPos; import common.util.ExtMath; @@ -16,7 +16,7 @@ public class ItemBed extends Item public ItemBed(BlockBed bedBlock) { this.bedBlock = bedBlock; - this.setTab(CheatTab.DECORATION); + this.setTab(CheatTab.tabDeco); } public Block getBlock() @@ -68,7 +68,7 @@ public class ItemBed extends Item worldIn.setState(blockpos, iblockstate2, 3); } - --stack.size; + --stack.stackSize; return true; } else diff --git a/common/src/main/java/common/item/ItemBlock.java b/common/src/common/item/ItemBlock.java similarity index 84% rename from common/src/main/java/common/item/ItemBlock.java rename to common/src/common/item/ItemBlock.java index 8cdc501..b6f4928 100755 --- a/common/src/main/java/common/item/ItemBlock.java +++ b/common/src/common/item/ItemBlock.java @@ -11,7 +11,7 @@ import common.init.Blocks; import common.model.Model; import common.model.ModelProvider; import common.model.Transforms; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.tileentity.TileEntity; import common.util.BlockPos; import common.util.Facing; @@ -62,7 +62,7 @@ public class ItemBlock extends Item pos = pos.offset(side); } - if (stack.size == 0) + if (stack.stackSize == 0) { return false; } @@ -86,7 +86,7 @@ public class ItemBlock extends Item } worldIn.playSound(this.block.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), 1.0F); - --stack.size; + --stack.stackSize; } return true; @@ -107,7 +107,7 @@ public class ItemBlock extends Item // } // else // { - if (p_179224_3_.hasTagCompound() && p_179224_3_.getTagCompound().hasObject("BlockEntityTag")) + if (p_179224_3_.hasTagCompound() && p_179224_3_.getTagCompound().hasKey("BlockEntityTag", 10)) { TileEntity tileentity = worldIn.getTileEntity(stack); @@ -118,18 +118,18 @@ public class ItemBlock extends Item return false; } - TagObject nbttagcompound = new TagObject(); - TagObject nbttagcompound1 = nbttagcompound.copy(); - tileentity.writeTags(nbttagcompound); - TagObject nbttagcompound2 = p_179224_3_.getTagCompound().getObject("BlockEntityTag"); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttagcompound.copy(); + tileentity.writeToNBT(nbttagcompound); + NBTTagCompound nbttagcompound2 = (NBTTagCompound)p_179224_3_.getTagCompound().getTag("BlockEntityTag"); nbttagcompound.merge(nbttagcompound2); - nbttagcompound.setInt("x", stack.getX()); - nbttagcompound.setInt("y", stack.getY()); - nbttagcompound.setInt("z", stack.getZ()); + nbttagcompound.setInteger("x", stack.getX()); + nbttagcompound.setInteger("y", stack.getY()); + nbttagcompound.setInteger("z", stack.getZ()); if (!nbttagcompound.equals(nbttagcompound1)) { - tileentity.readTags(nbttagcompound); + tileentity.readFromNBT(nbttagcompound); tileentity.markDirty(); return true; } @@ -200,7 +200,7 @@ public class ItemBlock extends Item // // protected boolean validateNbt(NBTTagCompound tag) { // if(tag.hasKey("BlockEntityTag")) { -// if(!tag.hasTag("BlockEntityTag")) { +// if(!tag.hasKey("BlockEntityTag", 10)) { // return false; // } // } @@ -218,8 +218,8 @@ public class ItemBlock extends Item public Model getModel(ModelProvider provider, String name, int meta) { return this.flatTexture != null ? provider.getModel(this.getTransform(), !this.flatTexture.isEmpty() ? this.flatTexture : this.block.getModel(provider, - BlockRegistry.getNameFromBlock(this.block).toString(), this.block.getStateFromMeta(this.getMetadata(meta))).getPrimary() /* "blocks/" + name */) : + BlockRegistry.REGISTRY.getNameForObject(this.block).toString(), this.block.getStateFromMeta(this.getMetadata(meta))).getPrimary() /* "blocks/" + name */) : provider.getModel(this.block.getModel(provider, - BlockRegistry.getNameFromBlock(this.block).toString(), this.block.getStateFromMeta(this.getMetadata(meta))), this.getTransform()); + BlockRegistry.REGISTRY.getNameForObject(this.block).toString(), this.block.getStateFromMeta(this.getMetadata(meta))), this.getTransform()); } } diff --git a/common/src/main/java/common/item/ItemBoat.java b/common/src/common/item/ItemBoat.java similarity index 97% rename from common/src/main/java/common/item/ItemBoat.java rename to common/src/common/item/ItemBoat.java index 2d78fcf..1aa2ae3 100755 --- a/common/src/main/java/common/item/ItemBoat.java +++ b/common/src/common/item/ItemBoat.java @@ -18,7 +18,7 @@ public class ItemBoat extends Item public ItemBoat() { this.maxStackSize = 1; - this.setTab(CheatTab.SPAWNERS); + this.setTab(CheatTab.tabSpawners); } /** @@ -100,7 +100,7 @@ public class ItemBoat extends Item // if (!playerIn.creative) // { - --itemStackIn.size; + --itemStackIn.stackSize; // } // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); diff --git a/common/src/main/java/common/item/ItemBoltgun.java b/common/src/common/item/ItemBoltgun.java similarity index 100% rename from common/src/main/java/common/item/ItemBoltgun.java rename to common/src/common/item/ItemBoltgun.java diff --git a/common/src/main/java/common/item/ItemBook.java b/common/src/common/item/ItemBook.java similarity index 90% rename from common/src/main/java/common/item/ItemBook.java rename to common/src/common/item/ItemBook.java index 16c714e..f1d7b20 100755 --- a/common/src/main/java/common/item/ItemBook.java +++ b/common/src/common/item/ItemBook.java @@ -7,7 +7,7 @@ public class ItemBook extends Item */ public boolean isItemTool(ItemStack stack) { - return stack.size == 1; + return stack.stackSize == 1; } /** diff --git a/common/src/main/java/common/item/ItemBow.java b/common/src/common/item/ItemBow.java similarity index 95% rename from common/src/main/java/common/item/ItemBow.java rename to common/src/common/item/ItemBow.java index 4ee6e40..ddd477d 100755 --- a/common/src/main/java/common/item/ItemBow.java +++ b/common/src/common/item/ItemBow.java @@ -19,7 +19,7 @@ public class ItemBow extends Item { this.maxStackSize = 1; this.setMaxDamage(384); - this.setTab(CheatTab.COMBAT); + this.setTab(CheatTab.tabCombat); } /** @@ -27,7 +27,7 @@ public class ItemBow extends Item */ public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityNPC playerIn, int timeLeft) { - boolean flag = /* playerIn.creative || */ EnchantmentHelper.getEnchantmentLevel(Enchantment.INFINITY, stack) > 0; + boolean flag = /* playerIn.creative || */ EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0; if (flag || playerIn.inventory.hasItem(Items.arrow)) { @@ -52,21 +52,21 @@ public class ItemBow extends Item entityarrow.setIsCritical(true); } - int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.POWER, stack); + int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, stack); if (j > 0) { entityarrow.setDamage(entityarrow.getDamage() + (double)j * 0.5D + 0.5D); } - int k = EnchantmentHelper.getEnchantmentLevel(Enchantment.PUNCH, stack); + int k = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, stack); if (k > 0) { entityarrow.setKnockbackStrength(k); } - if (EnchantmentHelper.getEnchantmentLevel(Enchantment.FLAME, stack) > 0) + if (EnchantmentHelper.getEnchantmentLevel(Enchantment.flame.effectId, stack) > 0) { entityarrow.setFire(100); } diff --git a/common/src/main/java/common/item/ItemBucket.java b/common/src/common/item/ItemBucket.java similarity index 90% rename from common/src/main/java/common/item/ItemBucket.java rename to common/src/common/item/ItemBucket.java index ad0b2dd..464a389 100755 --- a/common/src/main/java/common/item/ItemBucket.java +++ b/common/src/common/item/ItemBucket.java @@ -8,10 +8,9 @@ import java.util.Queue; import java.util.Set; import common.block.Block; -import common.block.Material; -import common.block.liquid.BlockDynamicLiquid; -import common.block.liquid.BlockLiquid; -import common.block.liquid.BlockStaticLiquid; +import common.block.BlockDynamicLiquid; +import common.block.BlockLiquid; +import common.block.BlockStaticLiquid; import common.collect.Sets; import common.entity.npc.EntityNPC; import common.init.BlockRegistry; @@ -20,6 +19,7 @@ import common.init.FluidRegistry; import common.init.ItemRegistry; import common.init.Items; import common.init.SoundEvent; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ParticleType; @@ -36,7 +36,7 @@ public class ItemBucket extends Item private final BlockDynamicLiquid liquid; private static boolean test(AWorldServer world, BlockPos pos, Set blocks, int max, BlockPos origin, int radius) { - if(pos.getY() < -World.MAX_SIZE_Y || pos.getY() > max) + if(pos.getY() < 0 || pos.getY() > max) return false; if(pos.getX() < origin.getX() - radius || pos.getX() > origin.getX() + radius) return false; @@ -54,7 +54,7 @@ public class ItemBucket extends Item List dirs = new ArrayList(); Set blocks = liquid == null ? null : Sets.newHashSet(FluidRegistry.getDynamicBlock(liquid), liquid, Blocks.air); State state = (liquid == null ? Blocks.air : liquid).getState(); - int max = World.MAX_SIZE_Y - 1; + int max = 511; if(liquid != null) { dirs.add(new Vec3i(1, 0, 0)); @@ -104,7 +104,7 @@ public class ItemBucket extends Item this.maxStackSize = liquid == null ? 16 : 1; this.liquid = liquid; this.recursive = recursive; - this.setTab(liquid == null ? CheatTab.TOOLS : CheatTab.LIQUIDS); + this.setTab(liquid == null ? CheatTab.tabTools : CheatTab.tabLiquids); // if(!empty) // this.setHasSubtypes(true); } @@ -165,7 +165,7 @@ public class ItemBucket extends Item setRecursive((AWorldServer)worldIn, blockpos, 4, null); // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); // if(!playerIn.creative) - --itemStackIn.size; + --itemStackIn.stackSize; return itemStackIn; } } @@ -176,7 +176,7 @@ public class ItemBucket extends Item // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); Block block = iblockstate.getBlock(); return this.fillBucket(itemStackIn, playerIn, new ItemStack( - ItemRegistry.getRegisteredItem(BlockRegistry.getNameFromBlock(block instanceof BlockDynamicLiquid + ItemRegistry.getRegisteredItem(BlockRegistry.REGISTRY.getNameForObject(block instanceof BlockDynamicLiquid ? FluidRegistry.getStaticBlock((BlockDynamicLiquid)block) : block) + "_bucket"), 1, 0)); } @@ -200,7 +200,7 @@ public class ItemBucket extends Item { // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); if(this.recursive) { - --itemStackIn.size; + --itemStackIn.stackSize; return itemStackIn; } return new ItemStack(Items.bucket); @@ -219,7 +219,7 @@ public class ItemBucket extends Item // return emptyBuckets; // } // else - if (--emptyBuckets.size <= 0) + if (--emptyBuckets.stackSize <= 0) { return fullBucket; } @@ -249,38 +249,32 @@ public class ItemBucket extends Item { return false; } - else + else if(!worldIn.client) { - if (worldIn.doesWaterVaporize(pos) && this.liquid.getMaterial() == Material.WATER) + if (((AWorldServer)worldIn).doesWaterVaporize(pos) && this.liquid.getMaterial() == Material.water) { int i = pos.getX(); int j = pos.getY(); int k = pos.getZ(); worldIn.playSound(SoundEvent.FIZZ, (double)((float)i + 0.5F), (double)((float)j + 0.5F), (double)((float)k + 0.5F), 0.5F); - - for (int l = 0; l < 8; ++l) - { - worldIn.spawnParticle(ParticleType.SMOKE_LARGE, (double)i + Math.random(), (double)j + Math.random(), (double)k + Math.random(), 0.0D, 0.0D, 0.0D); - } + ((AWorldServer)worldIn).spawnParticle(ParticleType.SMOKE_LARGE, (double)i, (double)j, (double)k, 8, 1.0D, 1.0D, 1.0D, 0.0f); } else { - if (!worldIn.client && flag && !material.isLiquid()) + if (flag && !material.isLiquid()) { worldIn.destroyBlock(pos, true); } if(this.recursive) { - if(!worldIn.client) - setRecursive((AWorldServer)worldIn, pos, 4, FluidRegistry.getStaticBlock(this.liquid)); + setRecursive((AWorldServer)worldIn, pos, 4, FluidRegistry.getStaticBlock(this.liquid)); } else { worldIn.setState(pos, this.liquid.getState(), 3); } } - - return true; } + return true; } } @@ -342,6 +336,6 @@ public class ItemBucket extends Item // return super.getModel(name, meta); // else // return provider.getModel(this.getTransform(), meta < 0 || meta >= FluidRegistry.getNumFluids() ? "bucket" : -// (BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(meta)) + "_bucket")); +// (BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(meta)) + "_bucket")); // } } diff --git a/common/src/main/java/common/item/ItemBucketMilk.java b/common/src/common/item/ItemBucketMilk.java similarity index 72% rename from common/src/main/java/common/item/ItemBucketMilk.java rename to common/src/common/item/ItemBucketMilk.java index 90f2e49..7eaecfa 100755 --- a/common/src/main/java/common/item/ItemBucketMilk.java +++ b/common/src/common/item/ItemBucketMilk.java @@ -1,8 +1,12 @@ package common.item; import java.util.Map; +import java.util.Set; + import common.attributes.Attribute; -import common.attributes.UsageSlot; +import common.attributes.AttributeModifier; +import common.attributes.Attributes; +import common.collect.Sets; import common.entity.npc.EntityNPC; import common.init.Items; import common.world.World; @@ -12,7 +16,7 @@ public class ItemBucketMilk extends Item public ItemBucketMilk() { this.setMaxStackSize(1); - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } /** @@ -23,7 +27,7 @@ public class ItemBucketMilk extends Item { // if (!playerIn.creative) // { - --stack.size; + --stack.stackSize; // } if (!worldIn.client) @@ -32,7 +36,7 @@ public class ItemBucketMilk extends Item } // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); - return stack.size <= 0 ? new ItemStack(Items.bucket) : stack; + return stack.stackSize <= 0 ? new ItemStack(Items.bucket) : stack; } /** @@ -60,10 +64,11 @@ public class ItemBucketMilk extends Item return itemStackIn; } - public void getModifiers(Map map, UsageSlot slot) + public Map> getItemInventoryModifiers() { - if(slot == null || slot == UsageSlot.INVENTORY) - map.put(Attribute.RADIATION, -5.0f); + Map> multimap = super.getItemInventoryModifiers(); + multimap.put(Attributes.RADIATION, Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID, "Milk modifier", -5.0, false, true, true))); + return multimap; } public boolean isMagnetic() { diff --git a/common/src/main/java/common/item/ItemButton.java b/common/src/common/item/ItemButton.java similarity index 93% rename from common/src/main/java/common/item/ItemButton.java rename to common/src/common/item/ItemButton.java index 95b923b..34c50ce 100755 --- a/common/src/main/java/common/item/ItemButton.java +++ b/common/src/common/item/ItemButton.java @@ -1,6 +1,6 @@ package common.item; -import common.block.tech.BlockButton; +import common.block.BlockButton; import common.model.Model; import common.model.ModelProvider; diff --git a/common/src/main/java/common/item/ItemCamera.java b/common/src/common/item/ItemCamera.java similarity index 100% rename from common/src/main/java/common/item/ItemCamera.java rename to common/src/common/item/ItemCamera.java diff --git a/common/src/main/java/common/item/ItemCarrotOnAStick.java b/common/src/common/item/ItemCarrotOnAStick.java similarity index 95% rename from common/src/main/java/common/item/ItemCarrotOnAStick.java rename to common/src/common/item/ItemCarrotOnAStick.java index 83d923c..1a7983e 100755 --- a/common/src/main/java/common/item/ItemCarrotOnAStick.java +++ b/common/src/common/item/ItemCarrotOnAStick.java @@ -10,7 +10,7 @@ public class ItemCarrotOnAStick extends Item { public ItemCarrotOnAStick() { - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); this.setMaxStackSize(1); this.setMaxDamage(25); } @@ -46,7 +46,7 @@ public class ItemCarrotOnAStick extends Item entitypig.getAIControlledByPlayer().boostSpeed(); itemStackIn.damageItem(7, playerIn); - if (itemStackIn.size == 0) + if (itemStackIn.stackSize == 0) { ItemStack itemstack = new ItemStack(Items.fishing_rod); itemstack.setTagCompound(itemStackIn.getTagCompound()); diff --git a/common/src/main/java/common/item/ItemChargedOrb.java b/common/src/common/item/ItemChargedOrb.java similarity index 98% rename from common/src/main/java/common/item/ItemChargedOrb.java rename to common/src/common/item/ItemChargedOrb.java index 0b29515..8e93c20 100755 --- a/common/src/main/java/common/item/ItemChargedOrb.java +++ b/common/src/common/item/ItemChargedOrb.java @@ -1,6 +1,6 @@ package common.item; -import common.block.artificial.BlockPortalFrame; +import common.block.BlockPortalFrame; import common.color.TextColor; import common.entity.item.EntityOrb; import common.entity.npc.EntityNPC; @@ -18,7 +18,7 @@ public class ItemChargedOrb extends ItemFragile public ItemChargedOrb() { this.maxStackSize = 1; - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); this.setMaxDamage(16); this.setColor(TextColor.DMAGENTA); } @@ -57,7 +57,7 @@ public class ItemChargedOrb extends ItemFragile { worldIn.setState(pos, iblockstate.withProperty(BlockPortalFrame.ORB, Boolean.valueOf(true)), 2); worldIn.updateComparatorOutputLevel(pos, Blocks.portal_frame); - --stack.size; + --stack.stackSize; for (int i = 0; i < 16; ++i) { diff --git a/common/src/main/java/common/item/ItemChest.java b/common/src/common/item/ItemChest.java similarity index 100% rename from common/src/main/java/common/item/ItemChest.java rename to common/src/common/item/ItemChest.java diff --git a/common/src/main/java/common/item/ItemCloth.java b/common/src/common/item/ItemCloth.java similarity index 100% rename from common/src/main/java/common/item/ItemCloth.java rename to common/src/common/item/ItemCloth.java diff --git a/common/src/main/java/common/item/ItemCoal.java b/common/src/common/item/ItemCoal.java similarity index 96% rename from common/src/main/java/common/item/ItemCoal.java rename to common/src/common/item/ItemCoal.java index aa192ae..bef0689 100755 --- a/common/src/main/java/common/item/ItemCoal.java +++ b/common/src/common/item/ItemCoal.java @@ -11,7 +11,7 @@ public class ItemCoal extends Item { this.setHasSubtypes(true); this.setMaxDamage(0); - this.setTab(CheatTab.METALS); + this.setTab(CheatTab.tabMetals); } /** diff --git a/common/src/main/java/common/item/ItemColored.java b/common/src/common/item/ItemColored.java similarity index 100% rename from common/src/main/java/common/item/ItemColored.java rename to common/src/common/item/ItemColored.java diff --git a/common/src/main/java/common/item/ItemControl.java b/common/src/common/item/ItemControl.java similarity index 100% rename from common/src/main/java/common/item/ItemControl.java rename to common/src/common/item/ItemControl.java diff --git a/common/src/main/java/common/item/ItemDie.java b/common/src/common/item/ItemDie.java similarity index 96% rename from common/src/main/java/common/item/ItemDie.java rename to common/src/common/item/ItemDie.java index 1afefd9..5565fb4 100755 --- a/common/src/main/java/common/item/ItemDie.java +++ b/common/src/common/item/ItemDie.java @@ -20,7 +20,7 @@ public class ItemDie extends Item public ItemDie() { - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); this.setMaxDamage(0); this.setHasSubtypes(true); } @@ -29,7 +29,7 @@ public class ItemDie extends Item { // if (!playerIn.creative) // { - --itemStackIn.size; + --itemStackIn.stackSize; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); diff --git a/common/src/main/java/common/item/ItemDispenser.java b/common/src/common/item/ItemDispenser.java similarity index 100% rename from common/src/main/java/common/item/ItemDispenser.java rename to common/src/common/item/ItemDispenser.java diff --git a/common/src/main/java/common/item/ItemDoor.java b/common/src/common/item/ItemDoor.java similarity index 93% rename from common/src/main/java/common/item/ItemDoor.java rename to common/src/common/item/ItemDoor.java index 6a050be..ed84de0 100755 --- a/common/src/main/java/common/item/ItemDoor.java +++ b/common/src/common/item/ItemDoor.java @@ -1,10 +1,10 @@ package common.item; import common.block.Block; -import common.block.Material; -import common.block.artificial.BlockDoor; +import common.block.BlockDoor; import common.entity.npc.EntityNPC; import common.init.Blocks; +import common.material.Material; import common.util.BlockPos; import common.util.Facing; import common.world.State; @@ -17,7 +17,7 @@ public class ItemDoor extends Item public ItemDoor(Block block) { this.block = block; - this.setTab(block.getMaterial() == Material.WOOD ? CheatTab.WOOD : CheatTab.TECHNOLOGY); + this.setTab(block.getMaterial() == Material.wood ? CheatTab.tabWood : CheatTab.tabTech); } public Block getBlock() @@ -55,7 +55,7 @@ public class ItemDoor extends Item else { placeDoor(worldIn, pos, Facing.fromAngle((double)playerIn.rotYaw), this.block, true); - --stack.size; + --stack.stackSize; return true; } } diff --git a/common/src/main/java/common/item/ItemDoublePlant.java b/common/src/common/item/ItemDoublePlant.java similarity index 91% rename from common/src/main/java/common/item/ItemDoublePlant.java rename to common/src/common/item/ItemDoublePlant.java index 2e1875e..fe2b963 100755 --- a/common/src/main/java/common/item/ItemDoublePlant.java +++ b/common/src/common/item/ItemDoublePlant.java @@ -3,8 +3,8 @@ package common.item; import java.util.function.Function; import common.block.Block; -import common.block.foliage.BlockDoublePlant; -import common.block.foliage.BlockDoublePlant.EnumPlantType; +import common.block.BlockDoublePlant; +import common.block.BlockDoublePlant.EnumPlantType; import common.color.Colorizer; import common.model.Model; import common.model.ModelProvider; diff --git a/common/src/main/java/common/item/ItemDye.java b/common/src/common/item/ItemDye.java similarity index 93% rename from common/src/main/java/common/item/ItemDye.java rename to common/src/common/item/ItemDye.java index af0b10b..c42120e 100755 --- a/common/src/main/java/common/item/ItemDye.java +++ b/common/src/common/item/ItemDye.java @@ -3,14 +3,15 @@ package common.item; import java.util.List; import common.block.Block; -import common.block.artificial.BlockBed; -import common.block.foliage.IGrowable; +import common.block.BlockBed; +import common.block.IGrowable; import common.color.DyeColor; import common.entity.animal.EntitySheep; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.BlockRegistry; import common.init.Blocks; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.model.ParticleType; @@ -30,7 +31,7 @@ public class ItemDye extends Item { this.setHasSubtypes(true); this.setMaxDamage(0); - this.setTab(CheatTab.MATERIALS); + this.setTab(CheatTab.tabMaterials); } /** @@ -94,7 +95,7 @@ public class ItemDye extends Item // if (!playerIn.creative) // { - --stack.size; + --stack.stackSize; // } } @@ -103,8 +104,8 @@ public class ItemDye extends Item } State iblockstate = worldIn.getState(pos); if(iblockstate.getBlock() instanceof BlockBed) { - Block bedBlock = BlockRegistry.getRegisteredBlock(enumdyecolor.getName() + "_bed"); - if(bedBlock != Blocks.air) { + Block bedBlock = BlockRegistry.getByNameOrId(enumdyecolor.getName() + "_bed"); + if(bedBlock != null) { if (iblockstate.getValue(BlockBed.PART) == BlockBed.EnumPartType.FOOT) { pos = pos.offset(iblockstate.getValue(BlockBed.FACING)); @@ -127,7 +128,7 @@ public class ItemDye extends Item worldIn.setState(pos, iblockstate1, 2); } // if(!playerIn.creative) - --stack.size; + --stack.stackSize; return true; } } @@ -136,7 +137,7 @@ public class ItemDye extends Item if(te instanceof TileEntityBeacon) { ((TileEntityBeacon)te).setBeamColor(enumdyecolor); // if(!playerIn.creative) - --stack.size; + --stack.stackSize; } } @@ -161,7 +162,7 @@ public class ItemDye extends Item igrowable.grow((AWorldServer)worldIn, worldIn.rand, target, iblockstate); } - --stack.size; + --stack.stackSize; } return true; @@ -180,7 +181,7 @@ public class ItemDye extends Item Block block = worldIn.getState(pos).getBlock(); - if (block != Blocks.air) + if (block.getMaterial() != Material.air) { block.setBlockBoundsBasedOnState(worldIn, pos); @@ -207,7 +208,7 @@ public class ItemDye extends Item if (!entitysheep.getSheared() && entitysheep.getFleeceColor() != enumdyecolor) { entitysheep.setFleeceColor(enumdyecolor); - --stack.size; + --stack.stackSize; } return true; diff --git a/common/src/main/java/common/item/ItemDynamite.java b/common/src/common/item/ItemDynamite.java similarity index 95% rename from common/src/main/java/common/item/ItemDynamite.java rename to common/src/common/item/ItemDynamite.java index d343350..56a3d46 100755 --- a/common/src/main/java/common/item/ItemDynamite.java +++ b/common/src/common/item/ItemDynamite.java @@ -16,7 +16,7 @@ public class ItemDynamite extends Item public ItemDynamite() { this.maxStackSize = 32; - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); this.setMaxDamage(0); this.setHasSubtypes(true); } @@ -28,7 +28,7 @@ public class ItemDynamite extends Item { // if (!playerIn.creative) // { - --itemStackIn.size; + --itemStackIn.stackSize; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); diff --git a/common/src/main/java/common/item/ItemEditWand.java b/common/src/common/item/ItemEditWand.java similarity index 96% rename from common/src/main/java/common/item/ItemEditWand.java rename to common/src/common/item/ItemEditWand.java index 6d1baa9..ca542f9 100755 --- a/common/src/main/java/common/item/ItemEditWand.java +++ b/common/src/common/item/ItemEditWand.java @@ -8,7 +8,7 @@ import common.world.World; public class ItemEditWand extends Item { public ItemEditWand() { this.maxStackSize = 1; - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } // public boolean canBreakBlocks() { diff --git a/common/src/main/java/common/item/ItemEffect.java b/common/src/common/item/ItemEffect.java similarity index 100% rename from common/src/main/java/common/item/ItemEffect.java rename to common/src/common/item/ItemEffect.java diff --git a/common/src/main/java/common/item/ItemEgg.java b/common/src/common/item/ItemEgg.java similarity index 92% rename from common/src/main/java/common/item/ItemEgg.java rename to common/src/common/item/ItemEgg.java index 10a8f70..ec3c8ff 100755 --- a/common/src/main/java/common/item/ItemEgg.java +++ b/common/src/common/item/ItemEgg.java @@ -9,7 +9,7 @@ public class ItemEgg extends Item { public ItemEgg() { - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } /** @@ -19,7 +19,7 @@ public class ItemEgg extends Item { // if (!playerIn.creative) // { - --itemStackIn.size; + --itemStackIn.stackSize; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); diff --git a/common/src/main/java/common/item/ItemEnchantedBook.java b/common/src/common/item/ItemEnchantedBook.java similarity index 72% rename from common/src/main/java/common/item/ItemEnchantedBook.java rename to common/src/common/item/ItemEnchantedBook.java index 37a1079..c923726 100755 --- a/common/src/main/java/common/item/ItemEnchantedBook.java +++ b/common/src/common/item/ItemEnchantedBook.java @@ -2,7 +2,6 @@ package common.item; import java.util.List; -import common.collect.Lists; import common.color.TextColor; import common.enchantment.Enchantment; import common.enchantment.EnchantmentHelper; @@ -10,8 +9,9 @@ import common.enchantment.RngEnchantment; import common.entity.npc.EntityNPC; import common.init.Items; import common.model.ItemMeshDefinition; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.rng.Random; -import common.tags.TagObject; public class ItemEnchantedBook extends Item { @@ -34,8 +34,8 @@ public class ItemEnchantedBook extends Item public void getSubItems(Item itemIn, CheatTab tab, List subItems) { - for (Enchantment enchantment : Enchantment.values()) { - if(enchantment != null && enchantment.getType() != null) + for (Enchantment enchantment : Enchantment.enchantmentsBookList) { + if(enchantment != null && enchantment.type != null) subItems.add(Items.enchanted_book.getEnchantedItemStack(new RngEnchantment(enchantment, enchantment.getMaxLevel()))); } } @@ -48,10 +48,10 @@ public class ItemEnchantedBook extends Item // return this.getEnchantments(stack).tagCount() > 0 ? ChatFormat.YELLOW : super.getColor(stack); // } - public List getEnchantments(ItemStack stack) + public NBTTagList getEnchantments(ItemStack stack) { - TagObject nbttagcompound = stack.getTagCompound(); - return nbttagcompound != null && nbttagcompound.hasList("StoredEnchantments") ? nbttagcompound.getList("StoredEnchantments") : Lists.newArrayList(); + NBTTagCompound nbttagcompound = stack.getTagCompound(); + return nbttagcompound != null && nbttagcompound.hasKey("StoredEnchantments", 9) ? (NBTTagList)nbttagcompound.getTag("StoredEnchantments") : new NBTTagList(); } /** @@ -60,18 +60,18 @@ public class ItemEnchantedBook extends Item public void addInformation(ItemStack stack, EntityNPC playerIn, List tooltip) { super.addInformation(stack, playerIn, tooltip); - List nbttaglist = this.getEnchantments(stack); + NBTTagList nbttaglist = this.getEnchantments(stack); if (nbttaglist != null) { - for (int i = 0; i < nbttaglist.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - Enchantment j = Enchantment.getEnchantment(nbttaglist.get(i).getString("id")); + int j = nbttaglist.getCompoundTagAt(i).getShort("id"); + int k = nbttaglist.getCompoundTagAt(i).getShort("lvl"); - if (j != null) + if (Enchantment.getEnchantmentById(j) != null) { - int k = nbttaglist.get(i).getShort("lvl"); - tooltip.add(j.getFormattedName(k)); + tooltip.add(Enchantment.getEnchantmentById(j).getFormattedName(k)); } } } @@ -82,18 +82,18 @@ public class ItemEnchantedBook extends Item */ public void addEnchantment(ItemStack stack, RngEnchantment enchantment) { - List nbttaglist = this.getEnchantments(stack); + NBTTagList nbttaglist = this.getEnchantments(stack); boolean flag = true; - for (int i = 0; i < nbttaglist.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject nbttagcompound = nbttaglist.get(i); + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); - if (Enchantment.getEnchantment(nbttagcompound.getString("id")) == enchantment.enchantment) + if (nbttagcompound.getShort("id") == enchantment.enchantmentobj.effectId) { - if (nbttagcompound.getShort("lvl") < enchantment.level) + if (nbttagcompound.getShort("lvl") < enchantment.enchantmentLevel) { - nbttagcompound.setShort("lvl", (short)enchantment.level); + nbttagcompound.setShort("lvl", (short)enchantment.enchantmentLevel); } flag = false; @@ -103,18 +103,18 @@ public class ItemEnchantedBook extends Item if (flag) { - TagObject nbttagcompound1 = new TagObject(); - nbttagcompound1.setString("id", enchantment.enchantment.getName()); - nbttagcompound1.setShort("lvl", (short)enchantment.level); - nbttaglist.add(nbttagcompound1); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setShort("id", (short)enchantment.enchantmentobj.effectId); + nbttagcompound1.setShort("lvl", (short)enchantment.enchantmentLevel); + nbttaglist.appendTag(nbttagcompound1); } if (!stack.hasTagCompound()) { - stack.setTagCompound(new TagObject()); + stack.setTagCompound(new NBTTagCompound()); } - stack.getTagCompound().setList("StoredEnchantments", nbttaglist); + stack.getTagCompound().setTag("StoredEnchantments", nbttaglist); } /** @@ -153,7 +153,7 @@ public class ItemEnchantedBook extends Item // // protected boolean validateNbt(NBTTagCompound tag) { // if(tag.hasKey("StoredEnchantments")) { -// if(!tag.hasList("StoredEnchantments")) { +// if(!tag.hasKey("StoredEnchantments", 9)) { // return false; // } // NBTTagList ench = tag.getTagList("StoredEnchantments", 10); @@ -166,7 +166,7 @@ public class ItemEnchantedBook extends Item // Enchantment[] ecn = new Enchantment[ench.tagCount()]; // for(int e = 0; e < ench.tagCount(); e++) { // NBTTagCompound ec = ench.getCompoundTagAt(e); -// if(ec.getKeySet().size() != 2 || !ec.hasShort("id") || !ec.hasShort("lvl")) { +// if(ec.getKeySet().size() != 2 || !ec.hasKey("id", 2) || !ec.hasKey("lvl", 2)) { // return false; // } // int id = ec.getShort("id"); diff --git a/common/src/main/java/common/item/ItemExpBottle.java b/common/src/common/item/ItemExpBottle.java similarity index 92% rename from common/src/main/java/common/item/ItemExpBottle.java rename to common/src/common/item/ItemExpBottle.java index 754f347..ce0b567 100755 --- a/common/src/main/java/common/item/ItemExpBottle.java +++ b/common/src/common/item/ItemExpBottle.java @@ -9,7 +9,7 @@ public class ItemExpBottle extends Item { public ItemExpBottle() { - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } public boolean hasEffect(ItemStack stack) @@ -24,7 +24,7 @@ public class ItemExpBottle extends Item { // if (!playerIn.creative) // { - --itemStackIn.size; + --itemStackIn.stackSize; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); diff --git a/common/src/main/java/common/item/ItemExterminator.java b/common/src/common/item/ItemExterminator.java similarity index 100% rename from common/src/main/java/common/item/ItemExterminator.java rename to common/src/common/item/ItemExterminator.java diff --git a/common/src/main/java/common/item/ItemFence.java b/common/src/common/item/ItemFence.java similarity index 95% rename from common/src/main/java/common/item/ItemFence.java rename to common/src/common/item/ItemFence.java index cd6c5c0..38089d5 100755 --- a/common/src/main/java/common/item/ItemFence.java +++ b/common/src/common/item/ItemFence.java @@ -1,7 +1,7 @@ package common.item; import common.block.Block; -import common.block.artificial.BlockFence; +import common.block.BlockFence; import common.model.Model; import common.model.ModelProvider; @@ -11,7 +11,7 @@ public class ItemFence extends ItemBlock { } public Model getModel(ModelProvider provider, String name, int meta) { - return provider.getModel(provider.getModel(((BlockFence)this.block).getTexture()) + return provider.getModel(provider.getModel(((BlockFence)this.block).getTexture()).noOcclude() .add(6, 0, 0, 10, 16, 4) .d().uv(6, 0, 10, 4) .u().uv(6, 0, 10, 4).noCull() diff --git a/common/src/main/java/common/item/ItemFireball.java b/common/src/common/item/ItemFireball.java similarity index 86% rename from common/src/main/java/common/item/ItemFireball.java rename to common/src/common/item/ItemFireball.java index 4cacb31..5870b25 100755 --- a/common/src/main/java/common/item/ItemFireball.java +++ b/common/src/common/item/ItemFireball.java @@ -3,6 +3,7 @@ package common.item; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.init.SoundEvent; +import common.material.Material; import common.util.BlockPos; import common.util.Facing; import common.world.World; @@ -11,7 +12,7 @@ public class ItemFireball extends Item { public ItemFireball() { - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } /** @@ -33,7 +34,7 @@ public class ItemFireball extends Item } else { - if (worldIn.getState(pos).getBlock() == Blocks.air) + if (worldIn.getState(pos).getBlock().getMaterial() == Material.air) { worldIn.playSound(SoundEvent.FIREBALL, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, 1.0F); worldIn.setState(pos, Blocks.fire.getState()); @@ -41,7 +42,7 @@ public class ItemFireball extends Item // if (!playerIn.creative) // { - --stack.size; + --stack.stackSize; // } return true; diff --git a/common/src/main/java/common/item/ItemFirework.java b/common/src/common/item/ItemFirework.java similarity index 79% rename from common/src/main/java/common/item/ItemFirework.java rename to common/src/common/item/ItemFirework.java index 4f207b2..24450e4 100755 --- a/common/src/main/java/common/item/ItemFirework.java +++ b/common/src/common/item/ItemFirework.java @@ -5,7 +5,8 @@ import java.util.List; import common.collect.Lists; import common.entity.item.EntityFireworks; import common.entity.npc.EntityNPC; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.util.BlockPos; import common.util.Facing; import common.world.World; @@ -24,7 +25,7 @@ public class ItemFirework extends Item // if (!playerIn.creative) // { - --stack.size; + --stack.stackSize; // } return true; @@ -42,22 +43,22 @@ public class ItemFirework extends Item { if (stack.hasTagCompound()) { - TagObject nbttagcompound = stack.getTagCompound().getObject("Fireworks"); + NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("Fireworks"); if (nbttagcompound != null) { - if (nbttagcompound.hasByte("Flight")) + if (nbttagcompound.hasKey("Flight", 99)) { tooltip.add("Flugdauer: " + nbttagcompound.getByte("Flight")); } - List nbttaglist = nbttagcompound.getList("Explosions"); + NBTTagList nbttaglist = nbttagcompound.getTagList("Explosions", 10); - if (nbttaglist != null && nbttaglist.size() > 0) + if (nbttaglist != null && nbttaglist.tagCount() > 0) { - for (int i = 0; i < nbttaglist.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject nbttagcompound1 = nbttaglist.get(i); + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); List list = Lists.newArrayList(); ItemFireworkCharge.addExplosionInfo(nbttagcompound1, list); diff --git a/common/src/main/java/common/item/ItemFireworkCharge.java b/common/src/common/item/ItemFireworkCharge.java similarity index 66% rename from common/src/main/java/common/item/ItemFireworkCharge.java rename to common/src/common/item/ItemFireworkCharge.java index 14e9ba1..9d0a7f8 100755 --- a/common/src/main/java/common/item/ItemFireworkCharge.java +++ b/common/src/common/item/ItemFireworkCharge.java @@ -6,7 +6,9 @@ import common.color.DyeColor; import common.entity.npc.EntityNPC; import common.model.Model; import common.model.ModelProvider; -import common.tags.TagObject; +import common.nbt.NBTBase; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagIntArray; public class ItemFireworkCharge extends Item { @@ -20,44 +22,58 @@ public class ItemFireworkCharge extends Item } else { - if (stack.hasTagCompound()) + NBTBase nbtbase = getExplosionTag(stack, "Colors"); + + if (!(nbtbase instanceof NBTTagIntArray)) { - TagObject nbttagcompound = stack.getTagCompound().getObject("Explosion"); + return 9079434; + } + else + { + NBTTagIntArray nbttagintarray = (NBTTagIntArray)nbtbase; + int[] aint = nbttagintarray.getIntArray(); - if (nbttagcompound != null) + if (aint.length == 1) { - if(nbttagcompound.hasIntArray("Colors")) { - int[] aint = nbttagcompound.getIntArray("Colors"); + return aint[0]; + } + else + { + int i = 0; + int j = 0; + int k = 0; - if (aint.length == 1) - { - return aint[0]; - } - else - { - int i = 0; - int j = 0; - int k = 0; + for (int l : aint) + { + i += (l & 16711680) >> 16; + j += (l & 65280) >> 8; + k += (l & 255) >> 0; + } - for (int l : aint) - { - i += (l & 16711680) >> 16; - j += (l & 65280) >> 8; - k += (l & 255) >> 0; - } - - i = i / aint.length; - j = j / aint.length; - k = k / aint.length; - return i << 16 | j << 8 | k; - } - } + i = i / aint.length; + j = j / aint.length; + k = k / aint.length; + return i << 16 | j << 8 | k; } } - return 9079434; } } + public static NBTBase getExplosionTag(ItemStack stack, String key) + { + if (stack.hasTagCompound()) + { + NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("Explosion"); + + if (nbttagcompound != null) + { + return nbttagcompound.getTag(key); + } + } + + return null; + } + /** * allows items to add custom lines of information to the mouseover description */ @@ -65,7 +81,7 @@ public class ItemFireworkCharge extends Item { if (stack.hasTagCompound()) { - TagObject nbttagcompound = stack.getTagCompound().getObject("Explosion"); + NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("Explosion"); if (nbttagcompound != null) { @@ -74,7 +90,7 @@ public class ItemFireworkCharge extends Item } } - public static void addExplosionInfo(TagObject nbt, List tooltip) + public static void addExplosionInfo(NBTTagCompound nbt, List tooltip) { byte b0 = nbt.getByte("Type"); @@ -159,14 +175,14 @@ public class ItemFireworkCharge extends Item tooltip.add(s1); } - boolean flag3 = nbt.getBool("Trail"); + boolean flag3 = nbt.getBoolean("Trail"); if (flag3) { tooltip.add("Schweif"); } - boolean flag4 = nbt.getBool("Flicker"); + boolean flag4 = nbt.getBoolean("Flicker"); if (flag4) { diff --git a/common/src/main/java/common/item/ItemFishFood.java b/common/src/common/item/ItemFishFood.java similarity index 100% rename from common/src/main/java/common/item/ItemFishFood.java rename to common/src/common/item/ItemFishFood.java diff --git a/common/src/main/java/common/item/ItemFishingRod.java b/common/src/common/item/ItemFishingRod.java similarity index 98% rename from common/src/main/java/common/item/ItemFishingRod.java rename to common/src/common/item/ItemFishingRod.java index f7278f8..91f0c75 100755 --- a/common/src/main/java/common/item/ItemFishingRod.java +++ b/common/src/common/item/ItemFishingRod.java @@ -16,7 +16,7 @@ public class ItemFishingRod extends Item { this.setMaxDamage(64); this.setMaxStackSize(1); - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } // /** diff --git a/common/src/main/java/common/item/ItemFlintAndSteel.java b/common/src/common/item/ItemFlintAndSteel.java similarity index 75% rename from common/src/main/java/common/item/ItemFlintAndSteel.java rename to common/src/common/item/ItemFlintAndSteel.java index 55ff3be..52ba772 100755 --- a/common/src/main/java/common/item/ItemFlintAndSteel.java +++ b/common/src/common/item/ItemFlintAndSteel.java @@ -1,23 +1,20 @@ package common.item; -import common.block.natural.BlockFire; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.init.SoundEvent; +import common.material.Material; import common.util.BlockPos; import common.util.Facing; import common.world.World; public class ItemFlintAndSteel extends Item { - private final BlockFire fireBlock; - - public ItemFlintAndSteel(BlockFire fireBlock) + public ItemFlintAndSteel() { - this.fireBlock = fireBlock; this.maxStackSize = 1; this.setMaxDamage(64); - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } /** @@ -33,10 +30,10 @@ public class ItemFlintAndSteel extends Item } else { - if (worldIn.getState(pos).getBlock() == Blocks.air) + if (worldIn.getState(pos).getBlock().getMaterial() == Material.air) { worldIn.playSound(SoundEvent.IGNITE, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, 1.0F); - worldIn.setState(pos, this.fireBlock.getState()); + worldIn.setState(pos, Blocks.fire.getState()); } stack.damageItem(1, playerIn); diff --git a/common/src/main/java/common/item/ItemFood.java b/common/src/common/item/ItemFood.java similarity index 97% rename from common/src/main/java/common/item/ItemFood.java rename to common/src/common/item/ItemFood.java index 9052904..cf71fa5 100755 --- a/common/src/main/java/common/item/ItemFood.java +++ b/common/src/common/item/ItemFood.java @@ -21,7 +21,7 @@ public class ItemFood extends Item this.itemUseDuration = 32; this.healAmount = amount; this.isWolfsFavoriteMeat = isWolfFood; - this.setTab(CheatTab.MISC); + this.setTab(CheatTab.tabMisc); } /** @@ -31,7 +31,7 @@ public class ItemFood extends Item public ItemStack onItemUseFinish(ItemStack stack, World worldIn, EntityNPC playerIn) { // if(!playerIn.creative) - --stack.size; + --stack.stackSize; worldIn.playSoundAtEntity(playerIn, SoundEvent.EAT, 0.5F); playerIn.heal((int)((float)this.getHealAmount(stack) * 0.5f * (1.0f + worldIn.rand.floatv()))); this.onFoodEaten(stack, worldIn, playerIn); diff --git a/common/src/main/java/common/item/ItemFragile.java b/common/src/common/item/ItemFragile.java similarity index 100% rename from common/src/main/java/common/item/ItemFragile.java rename to common/src/common/item/ItemFragile.java diff --git a/common/src/main/java/common/item/ItemGlassBottle.java b/common/src/common/item/ItemGlassBottle.java similarity index 91% rename from common/src/main/java/common/item/ItemGlassBottle.java rename to common/src/common/item/ItemGlassBottle.java index d4b046a..aabb0ed 100755 --- a/common/src/main/java/common/item/ItemGlassBottle.java +++ b/common/src/common/item/ItemGlassBottle.java @@ -1,8 +1,8 @@ package common.item; -import common.block.Material; import common.entity.npc.EntityNPC; import common.init.Items; +import common.material.Material; import common.model.Model; import common.model.ModelProvider; import common.util.BlockPos; @@ -13,7 +13,7 @@ public class ItemGlassBottle extends Item { public ItemGlassBottle() { - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } /** @@ -43,12 +43,12 @@ public class ItemGlassBottle extends Item return itemStackIn; } - if (worldIn.getState(blockpos).getBlock().getMaterial() == Material.WATER) + if (worldIn.getState(blockpos).getBlock().getMaterial() == Material.water) { - --itemStackIn.size; + --itemStackIn.stackSize; // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); - if (itemStackIn.size <= 0) + if (itemStackIn.stackSize <= 0) { return new ItemStack(Items.potion); } diff --git a/common/src/main/java/common/item/ItemGunBase.java b/common/src/common/item/ItemGunBase.java similarity index 93% rename from common/src/main/java/common/item/ItemGunBase.java rename to common/src/common/item/ItemGunBase.java index 73f56ab..26fbc81 100755 --- a/common/src/main/java/common/item/ItemGunBase.java +++ b/common/src/common/item/ItemGunBase.java @@ -17,7 +17,7 @@ public abstract class ItemGunBase extends Item { this.maxStackSize = 1; this.setMaxDamage(durability); - this.setTab(CheatTab.COMBAT); + this.setTab(CheatTab.tabCombat); } public ItemAction getItemPosition(ItemStack stack) @@ -30,13 +30,13 @@ public abstract class ItemGunBase extends Item if(stack.getItemDamage() >= this.getMaxDamage()) return stack; boolean flag = // playerIn.creative || - EnchantmentHelper.getEnchantmentLevel(Enchantment.INFINITY, stack) > 0; + EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0; if (flag || playerIn.inventory.hasItem(this.getAmmo())) { EntityBullet bullet = new EntityBullet(worldIn, playerIn, this.getVelocity()); bullet.setDamage(this.getAmmo().getDamage(stack)); - int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.POWER, stack); + int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, stack); if (j > 0) { diff --git a/common/src/main/java/common/item/ItemHoe.java b/common/src/common/item/ItemHoe.java similarity index 95% rename from common/src/main/java/common/item/ItemHoe.java rename to common/src/common/item/ItemHoe.java index 9e7b7b7..1d5294c 100755 --- a/common/src/main/java/common/item/ItemHoe.java +++ b/common/src/common/item/ItemHoe.java @@ -1,10 +1,11 @@ package common.item; import common.block.Block; -import common.block.natural.BlockDirt; +import common.block.BlockDirt; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.init.ToolMaterial; +import common.material.Material; import common.model.Transforms; import common.util.BlockPos; import common.util.Facing; @@ -20,7 +21,7 @@ public class ItemHoe extends Item this.theToolMaterial = material; this.maxStackSize = 1; this.setMaxDamage(material.getDurability()); - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } @@ -39,7 +40,7 @@ public class ItemHoe extends Item State iblockstate = worldIn.getState(pos); Block block = iblockstate.getBlock(); - if (side != Facing.DOWN && worldIn.getState(pos.up()).getBlock() == Blocks.air) + if (side != Facing.DOWN && worldIn.getState(pos.up()).getBlock().getMaterial() == Material.air) { if (block == Blocks.grass) { diff --git a/common/src/main/java/common/item/ItemHorseArmor.java b/common/src/common/item/ItemHorseArmor.java similarity index 91% rename from common/src/main/java/common/item/ItemHorseArmor.java rename to common/src/common/item/ItemHorseArmor.java index 3b60d1f..a976e1a 100755 --- a/common/src/main/java/common/item/ItemHorseArmor.java +++ b/common/src/common/item/ItemHorseArmor.java @@ -10,7 +10,7 @@ public class ItemHorseArmor extends Item { this.material = material; this.texture = texture; this.setMaxStackSize(1); - this.setTab(CheatTab.COMBAT); + this.setTab(CheatTab.tabCombat); } public boolean isMagnetic() { diff --git a/common/src/main/java/common/item/ItemHugeMushroom.java b/common/src/common/item/ItemHugeMushroom.java similarity index 100% rename from common/src/main/java/common/item/ItemHugeMushroom.java rename to common/src/common/item/ItemHugeMushroom.java diff --git a/common/src/main/java/common/item/ItemInfoWand.java b/common/src/common/item/ItemInfoWand.java similarity index 100% rename from common/src/main/java/common/item/ItemInfoWand.java rename to common/src/common/item/ItemInfoWand.java diff --git a/common/src/main/java/common/item/ItemKey.java b/common/src/common/item/ItemKey.java similarity index 100% rename from common/src/main/java/common/item/ItemKey.java rename to common/src/common/item/ItemKey.java diff --git a/common/src/main/java/common/item/ItemLead.java b/common/src/common/item/ItemLead.java similarity index 96% rename from common/src/main/java/common/item/ItemLead.java rename to common/src/common/item/ItemLead.java index fc914a4..263e5f3 100755 --- a/common/src/main/java/common/item/ItemLead.java +++ b/common/src/common/item/ItemLead.java @@ -1,7 +1,7 @@ package common.item; import common.block.Block; -import common.block.artificial.BlockFence; +import common.block.BlockFence; import common.entity.item.EntityLeashKnot; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; @@ -14,7 +14,7 @@ public class ItemLead extends Item { public ItemLead() { - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } /** diff --git a/common/src/main/java/common/item/ItemLeaves.java b/common/src/common/item/ItemLeaves.java similarity index 93% rename from common/src/main/java/common/item/ItemLeaves.java rename to common/src/common/item/ItemLeaves.java index efe717c..16e91d0 100755 --- a/common/src/main/java/common/item/ItemLeaves.java +++ b/common/src/common/item/ItemLeaves.java @@ -1,7 +1,7 @@ package common.item; -import common.block.foliage.BlockLeaves; -import common.block.foliage.LeavesType; +import common.block.BlockLeaves; +import common.block.LeavesType; public class ItemLeaves extends ItemBlock { diff --git a/common/src/main/java/common/item/ItemLightning.java b/common/src/common/item/ItemLightning.java similarity index 100% rename from common/src/main/java/common/item/ItemLightning.java rename to common/src/common/item/ItemLightning.java diff --git a/common/src/main/java/common/item/ItemLilyPad.java b/common/src/common/item/ItemLilyPad.java similarity index 96% rename from common/src/main/java/common/item/ItemLilyPad.java rename to common/src/common/item/ItemLilyPad.java index efe834d..6a69dc2 100755 --- a/common/src/main/java/common/item/ItemLilyPad.java +++ b/common/src/common/item/ItemLilyPad.java @@ -2,7 +2,7 @@ package common.item; import common.block.Block; import common.block.BlockDirectional; -import common.block.liquid.BlockLiquid; +import common.block.BlockLiquid; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.util.BlockPos; @@ -50,7 +50,7 @@ public class ItemLilyPad extends ItemColored // if (!playerIn.creative) // { - --itemStackIn.size; + --itemStackIn.stackSize; // } // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); diff --git a/common/src/main/java/common/item/ItemMagnet.java b/common/src/common/item/ItemMagnet.java similarity index 98% rename from common/src/main/java/common/item/ItemMagnet.java rename to common/src/common/item/ItemMagnet.java index f2b8527..c7dfa31 100755 --- a/common/src/main/java/common/item/ItemMagnet.java +++ b/common/src/common/item/ItemMagnet.java @@ -15,7 +15,7 @@ public class ItemMagnet extends Item { private final boolean chicken; public ItemMagnet(boolean chicken) { - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); this.setMaxStackSize(1); this.chicken = chicken; } diff --git a/common/src/main/java/common/item/ItemMagnetic.java b/common/src/common/item/ItemMagnetic.java similarity index 100% rename from common/src/main/java/common/item/ItemMagnetic.java rename to common/src/common/item/ItemMagnetic.java diff --git a/common/src/main/java/common/item/ItemMetal.java b/common/src/common/item/ItemMetal.java similarity index 61% rename from common/src/main/java/common/item/ItemMetal.java rename to common/src/common/item/ItemMetal.java index 58656dc..9962259 100755 --- a/common/src/main/java/common/item/ItemMetal.java +++ b/common/src/common/item/ItemMetal.java @@ -2,8 +2,12 @@ package common.item; import java.util.List; import java.util.Map; +import java.util.Set; + import common.attributes.Attribute; -import common.attributes.UsageSlot; +import common.attributes.AttributeModifier; +import common.attributes.Attributes; +import common.collect.Sets; import common.color.TextColor; import common.entity.npc.EntityNPC; import common.init.MetalType; @@ -31,14 +35,16 @@ public class ItemMetal extends Item { // return this.metal.radioactivity > 0.0f ? ChatFormat.GREEN : super.getColor(stack); // } - public void getModifiers(Map map, UsageSlot slot) + public Map> getItemInventoryModifiers() { - if((slot == null || slot == UsageSlot.INVENTORY) && this.metal.radioactivity > 0.0f) - map.put(Attribute.RADIATION, this.metal.radioactivity * 4.0f); + Map> multimap = super.getItemInventoryModifiers(); + if(this.metal.radioactivity > 0.0f) + multimap.put(Attributes.RADIATION, Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID, "Metal modifier", (double)this.metal.radioactivity * 4.0, false, true, true))); + return multimap; } public float getRadiation(ItemStack stack) { - return this.metal.radioactivity * 0.25f * (float)stack.size; + return this.metal.radioactivity * 0.25f * (float)stack.stackSize; } public boolean isMagnetic() { diff --git a/common/src/main/java/common/item/ItemMetalBlock.java b/common/src/common/item/ItemMetalBlock.java similarity index 66% rename from common/src/main/java/common/item/ItemMetalBlock.java rename to common/src/common/item/ItemMetalBlock.java index a6531b2..c43e4f2 100755 --- a/common/src/main/java/common/item/ItemMetalBlock.java +++ b/common/src/common/item/ItemMetalBlock.java @@ -2,9 +2,13 @@ package common.item; import java.util.List; import java.util.Map; +import java.util.Set; + import common.attributes.Attribute; -import common.attributes.UsageSlot; +import common.attributes.AttributeModifier; +import common.attributes.Attributes; import common.block.Block; +import common.collect.Sets; import common.color.TextColor; import common.entity.npc.EntityNPC; import common.init.MetalType; @@ -35,14 +39,16 @@ public class ItemMetalBlock extends ItemBlock { // return this.metal.radioactivity > 0.0f ? ChatFormat.GREEN : super.getColor(stack); // } - public void getModifiers(Map map, UsageSlot slot) + public Map> getItemInventoryModifiers() { - if((slot == null || slot == UsageSlot.INVENTORY) && this.metal.radioactivity > 0.0f) - map.put(Attribute.RADIATION, this.metal.radioactivity * 4.0f * (this.ore ? 2.0f : 9.0f)); + Map> multimap = super.getItemInventoryModifiers(); + if(this.metal.radioactivity > 0.0f) + multimap.put(Attributes.RADIATION, Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID, "Metal modifier", (double)this.metal.radioactivity * 4.0 * (this.ore ? 2.0 : 9.0), false, true, true))); + return multimap; } public float getRadiation(ItemStack stack) { - return this.metal.radioactivity * (this.ore ? 0.5f : 2.0f) * (float)stack.size; + return this.metal.radioactivity * (this.ore ? 0.5f : 2.0f) * (float)stack.stackSize; } public boolean isMagnetic() { diff --git a/common/src/main/java/common/item/ItemMinecart.java b/common/src/common/item/ItemMinecart.java similarity index 94% rename from common/src/main/java/common/item/ItemMinecart.java rename to common/src/common/item/ItemMinecart.java index ccc8a41..73ab5b6 100755 --- a/common/src/main/java/common/item/ItemMinecart.java +++ b/common/src/common/item/ItemMinecart.java @@ -1,14 +1,14 @@ package common.item; -import common.block.tech.BlockDispenser; -import common.block.tech.BlockRailBase; +import common.block.BlockDispenser; +import common.block.BlockRailBase; import common.dispenser.BehaviorDefaultDispenseItem; import common.dispenser.IBehaviorDispenseItem; import common.dispenser.IBlockSource; import common.entity.item.EntityCart; import common.entity.npc.EntityNPC; -import common.init.Blocks; import common.init.DispenserRegistry; +import common.material.Material; import common.util.BlockPos; import common.util.Facing; import common.world.State; @@ -44,7 +44,7 @@ public class ItemMinecart extends Item } else { - if (iblockstate.getBlock() != Blocks.air || !BlockRailBase.isRailBlock(world.getState(blockpos.down()))) + if (iblockstate.getBlock().getMaterial() != Material.air || !BlockRailBase.isRailBlock(world.getState(blockpos.down()))) { return this.behaviourDefaultDispenseItem.dispense(source, stack); } @@ -84,7 +84,7 @@ public class ItemMinecart extends Item { this.maxStackSize = 1; this.minecartType = type; - this.setTab(CheatTab.SPAWNERS); + this.setTab(CheatTab.tabSpawners); // if(type != EntityMinecart.EnumMinecartType.COMMAND_BLOCK) DispenserRegistry.REGISTRY.putObject(this, dispenserMinecartBehavior); } @@ -129,7 +129,7 @@ public class ItemMinecart extends Item // ((EntityMinecartCommandBlock)entityminecart).getCommandBlockLogic().setEnabled(((EntityNPCMP)playerIn).canUse(Permissions.CMDBLOCK)); } - --stack.size; + --stack.stackSize; return true; } else diff --git a/common/src/main/java/common/item/ItemMonsterPlacer.java b/common/src/common/item/ItemMonsterPlacer.java similarity index 71% rename from common/src/main/java/common/item/ItemMonsterPlacer.java rename to common/src/common/item/ItemMonsterPlacer.java index c7faf25..b5e0d4d 100755 --- a/common/src/main/java/common/item/ItemMonsterPlacer.java +++ b/common/src/common/item/ItemMonsterPlacer.java @@ -2,18 +2,21 @@ package common.item; import java.util.List; -import common.block.artificial.BlockFence; -import common.block.liquid.BlockLiquid; +import common.block.BlockFence; +import common.block.BlockLiquid; import common.color.TextColor; import common.dimension.Dimension; import common.entity.Entity; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; -import common.init.EntityInfo; +import common.init.Blocks; +import common.init.EntityEggInfo; import common.init.EntityRegistry; import common.init.UniverseRegistry; import common.model.Model; import common.model.ModelProvider; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityMobSpawner; import common.util.BlockPos; import common.util.ExtMath; import common.util.Facing; @@ -28,7 +31,7 @@ public class ItemMonsterPlacer extends Item public ItemMonsterPlacer(String entityId) { // this.setHasSubtypes(true); - this.setTab(CheatTab.SPAWNERS); + this.setTab(CheatTab.tabSpawners); this.entityId = entityId; } @@ -51,14 +54,14 @@ public class ItemMonsterPlacer extends Item public int getColorFromItemStack(ItemStack stack, int renderPass) { - EntityInfo egg = EntityRegistry.SPAWN_EGGS.get(this.entityId); - return egg != null ? (renderPass == 0 ? egg.color1() : egg.color2()) : 16777215; + EntityEggInfo egg = EntityRegistry.SPAWN_EGGS.get(this.entityId); + return egg != null ? (renderPass == 0 ? egg.color1 : egg.color2) : 16777215; } public void addInformation(ItemStack stack, EntityNPC player, List tooltip) { - EntityInfo egg = EntityRegistry.SPAWN_EGGS.get(this.entityId); + EntityEggInfo egg = EntityRegistry.SPAWN_EGGS.get(this.entityId); if(egg != null) { - Dimension dim = egg.origin() == null ? null : UniverseRegistry.getDimension(egg.origin()); + Dimension dim = egg.origin == null ? null : UniverseRegistry.getDimension(egg.origin); tooltip.add(TextColor.ORANGE + "Herkunft: " + (dim == null ? "???" : dim.getFormattedName(false))); } } @@ -80,6 +83,26 @@ public class ItemMonsterPlacer extends Item { State iblockstate = worldIn.getState(pos); + if (iblockstate.getBlock() == Blocks.mob_spawner) + { + TileEntity tileentity = worldIn.getTileEntity(pos); + + if (tileentity instanceof TileEntityMobSpawner) + { +// MobSpawnerBaseLogic mobspawnerbaselogic = ((TileEntityMobSpawner)tileentity).getSpawnerBaseLogic(); + ((TileEntityMobSpawner)tileentity).setEntityName(this.entityId); + tileentity.markDirty(); + worldIn.markBlockForUpdate(pos); + +// if (!playerIn.creative) +// { + --stack.stackSize; +// } + + return true; + } + } + pos = pos.offset(side); double d0 = 0.0D; @@ -91,7 +114,7 @@ public class ItemMonsterPlacer extends Item // int amount = Math.min(stack.stackSize, 128); // for(int z = 0; z < amount; z++) { - Entity entity = spawnCreature(worldIn, this.entityId, (double)pos.getX() + 0.5D, (double)pos.getY() + d0, (double)pos.getZ() + 0.5D, false); + Entity entity = spawnCreature(worldIn, this.entityId, (double)pos.getX() + 0.5D, (double)pos.getY() + d0, (double)pos.getZ() + 0.5D); if (entity != null) { @@ -107,7 +130,7 @@ public class ItemMonsterPlacer extends Item // if (!playerIn.creative) // { - --stack.size; + --stack.stackSize; // } } // } @@ -153,7 +176,7 @@ public class ItemMonsterPlacer extends Item { // int amount = Math.min(itemStackIn.stackSize, 128); // for(int z = 0; z < amount; z++) { - Entity entity = spawnCreature(worldIn, this.entityId, (double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D, false); + Entity entity = spawnCreature(worldIn, this.entityId, (double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D); if (entity != null) { @@ -169,7 +192,7 @@ public class ItemMonsterPlacer extends Item // if (!playerIn.creative) // { - --itemStackIn.size; + --itemStackIn.stackSize; // } // if(z == 0) @@ -184,21 +207,38 @@ public class ItemMonsterPlacer extends Item } } - public static EntityLiving spawnCreature(World worldIn, String entityID, double x, double y, double z, boolean check) { + /** + * Spawns the creature specified by the egg's type in the location specified by the last three parameters. + * Parameters: world, entityID, x, y, z. + */ + public static Entity spawnCreature(World worldIn, String entityID, double x, double y, double z) + { if (!EntityRegistry.SPAWN_EGGS.containsKey(entityID)) + { return null; - Entity entity = EntityRegistry.createEntityByName(entityID, worldIn); - if(!(entity instanceof EntityLiving living)) - return null; - living.setLocationAndAngles(x, y, z, ExtMath.wrapf(worldIn.rand.floatv() * 360.0F), 0.0F); - if(check && !living.isNotColliding()) - return null; - living.headYaw = living.rotYaw; - living.yawOffset = living.rotYaw; - living.onInitialSpawn(null); - worldIn.spawnEntityInWorld(living); - living.playLivingSound(); - return living; + } + else + { + Entity entity = null; + + for (int i = 0; i < 1; ++i) + { + entity = EntityRegistry.createEntityByName(entityID, worldIn); + + if (entity instanceof EntityLiving) + { + EntityLiving entityliving = (EntityLiving)entity; + entity.setLocationAndAngles(x, y, z, ExtMath.wrapf(worldIn.rand.floatv() * 360.0F), 0.0F); + entityliving.headYaw = entityliving.rotYaw; + entityliving.yawOffset = entityliving.rotYaw; + entityliving.onInitialSpawn(null); + worldIn.spawnEntityInWorld(entity); + entityliving.playLivingSound(); + } + } + + return entity; + } } // /** diff --git a/common/src/main/java/common/item/ItemMultiTexture.java b/common/src/common/item/ItemMultiTexture.java similarity index 100% rename from common/src/main/java/common/item/ItemMultiTexture.java rename to common/src/common/item/ItemMultiTexture.java diff --git a/common/src/main/java/common/item/ItemNameTag.java b/common/src/common/item/ItemNameTag.java similarity index 92% rename from common/src/main/java/common/item/ItemNameTag.java rename to common/src/common/item/ItemNameTag.java index 109c2e0..8b6d2dd 100755 --- a/common/src/main/java/common/item/ItemNameTag.java +++ b/common/src/common/item/ItemNameTag.java @@ -7,7 +7,7 @@ public class ItemNameTag extends Item { public ItemNameTag() { - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } /** @@ -24,7 +24,7 @@ public class ItemNameTag extends Item EntityLiving entityliving = (EntityLiving)target; entityliving.setCustomNameTag(stack.getDisplayName()); // entityliving.disableDespawn(); - --stack.size; + --stack.stackSize; return true; } else diff --git a/common/src/main/java/common/item/ItemNpcSpawner.java b/common/src/common/item/ItemNpcSpawner.java similarity index 88% rename from common/src/main/java/common/item/ItemNpcSpawner.java rename to common/src/common/item/ItemNpcSpawner.java index edc04b2..1f81811 100755 --- a/common/src/main/java/common/item/ItemNpcSpawner.java +++ b/common/src/common/item/ItemNpcSpawner.java @@ -3,8 +3,8 @@ package common.item; import java.lang.reflect.InvocationTargetException; import java.util.List; -import common.block.artificial.BlockFence; -import common.block.liquid.BlockLiquid; +import common.block.BlockFence; +import common.block.BlockLiquid; import common.color.TextColor; import common.dimension.Dimension; import common.entity.Entity; @@ -30,28 +30,19 @@ public class ItemNpcSpawner extends Item public ItemNpcSpawner(CharacterInfo spawned) { // this.setHasSubtypes(true); - this.setTab(CheatTab.SPAWNERS); + this.setTab(CheatTab.tabSpawners); this.spawned = spawned; } - - public CharacterInfo getSpawnedChar() { - return this.spawned; - } - - public String getCharName() { - CharacterInfo info = this.spawned; // SpeciesRegistry.CHARACTERS.get(stack.getMetadata() % SpeciesRegistry.CHARACTERS.size()); - String species = EntityRegistry.getEntityName(info.species.id); - if(info.species.prefix && info.type != null && !info.type.toString().isEmpty()) - species = info.type.toString(); - String character = info.name; - return species + (character.isEmpty() ? "" : (" " + character)); - } public String getDisplay(ItemStack stack) { String item = "Erschaffe"; - - item = item + " " + this.getCharName(); + CharacterInfo info = this.spawned; // SpeciesRegistry.CHARACTERS.get(stack.getMetadata() % SpeciesRegistry.CHARACTERS.size()); + String species = EntityRegistry.getEntityName(info.species.id); + if(info.species.prefix && info.type != null && !info.type.toString().isEmpty()) + species = info.type.toString(); + String character = info.name; + item = item + " " + species + (character.isEmpty() ? "" : (" " + character)); return item; } @@ -90,7 +81,7 @@ public class ItemNpcSpawner extends Item // int amount = Math.min(stack.stackSize, 128); // for(int z = 0; z < amount; z++) { - Entity entity = spawnNpc(worldIn, this.spawned, (double)pos.getX() + 0.5D, (double)pos.getY() + d0, (double)pos.getZ() + 0.5D, false); + Entity entity = spawnNpc(worldIn, this.spawned, (double)pos.getX() + 0.5D, (double)pos.getY() + d0, (double)pos.getZ() + 0.5D); if (entity != null) { @@ -101,7 +92,7 @@ public class ItemNpcSpawner extends Item // if (!playerIn.creative) // { - --stack.size; + --stack.stackSize; // } } // } @@ -144,7 +135,7 @@ public class ItemNpcSpawner extends Item { // int amount = Math.min(itemStackIn.stackSize, 128); // for(int z = 0; z < amount; z++) { - Entity entity = spawnNpc(worldIn, this.spawned, (double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D, false); + Entity entity = spawnNpc(worldIn, this.spawned, (double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D); if (entity != null) { @@ -155,7 +146,7 @@ public class ItemNpcSpawner extends Item // if (!playerIn.creative) // { - --itemStackIn.size; + --itemStackIn.stackSize; // } // if(z == 0) @@ -170,8 +161,9 @@ public class ItemNpcSpawner extends Item } } - public static EntityNPC spawnNpc(World worldIn, CharacterInfo character, double x, double y, double z, boolean check) + public static Entity spawnNpc(World worldIn, CharacterInfo character, double x, double y, double z) { +// CharacterInfo character = SpeciesRegistry.CHARACTERS.get(entityID % SpeciesRegistry.CHARACTERS.size()); EntityNPC entity; try { entity = character.species.clazz.getConstructor(World.class).newInstance(worldIn); @@ -180,11 +172,10 @@ public class ItemNpcSpawner extends Item throw new RuntimeException(e); } entity.setLocationAndAngles(x, y, z, ExtMath.wrapf(worldIn.rand.floatv() * 360.0F), 0.0F); - if(check && !entity.isNotColliding()) - return null; entity.headYaw = entity.rotYaw; entity.yawOffset = entity.rotYaw; entity.onInitialSpawn(new CharacterTypeData(character)); +// entity.setFromInfo(character); worldIn.spawnEntityInWorld(entity); return entity; } diff --git a/common/src/main/java/common/item/ItemNugget.java b/common/src/common/item/ItemNugget.java similarity index 100% rename from common/src/main/java/common/item/ItemNugget.java rename to common/src/common/item/ItemNugget.java diff --git a/common/src/common/item/ItemPickaxe.java b/common/src/common/item/ItemPickaxe.java new file mode 100755 index 0000000..1abbc61 --- /dev/null +++ b/common/src/common/item/ItemPickaxe.java @@ -0,0 +1,46 @@ +package common.item; + +import common.block.Block; +import common.init.ToolMaterial; + +public class ItemPickaxe extends ItemTool +{ +// private static final Set EFFECTIVE_ON = Sets.newHashSet(new Block[] { +// Blocks.activator_rail, Blocks.coal_ore, Blocks.cobblestone, Blocks.detector_rail, Blocks.diamond_block, Blocks.diamond_ore, Blocks.double_stone_slab, +// Blocks.golden_rail, Blocks.gold_block, Blocks.gold_ore, Blocks.ice, Blocks.iron_block, Blocks.iron_ore, Blocks.lapis_block, Blocks.lapis_ore, +// Blocks.lit_redstone_ore, Blocks.mossy_cobblestone, Blocks.netherrack, Blocks.packed_ice, Blocks.rail, Blocks.redstone_ore, Blocks.sandstone, +// Blocks.red_sandstone, Blocks.stone, Blocks.stone_slab +// }); + + public ItemPickaxe(ToolMaterial material) + { + super(2, material); + } + + public boolean canHarvestBlock(Block blockIn) + { + return blockIn.getMiningLevel() >= 0 && this.toolMaterial.getHarvestLevel() >= blockIn.getMiningLevel(); +// blockIn == Blocks.obsidian ? this.toolMaterial.getHarvestLevel() == 3 : +// (blockIn != Blocks.diamond_block && blockIn != Blocks.diamond_ore ? +// (blockIn != Blocks.emerald_ore && blockIn != Blocks.emerald_block ? +// (blockIn != Blocks.gold_block && blockIn != Blocks.gold_ore ? +// (blockIn != Blocks.iron_block && blockIn != Blocks.iron_ore ? +// (blockIn != Blocks.lapis_block && blockIn != Blocks.lapis_ore ? +// (blockIn != Blocks.redstone_ore && blockIn != Blocks.lit_redstone_ore ? +// (blockIn.getMaterial() == Material.rock ? true : +// (blockIn.getMaterial() == Material.iron ? true : +// blockIn.getMaterial() == Material.anvil)) : +// this.toolMaterial.getHarvestLevel() >= 2) : +// this.toolMaterial.getHarvestLevel() >= 1) : +// this.toolMaterial.getHarvestLevel() >= 1) : +// this.toolMaterial.getHarvestLevel() >= 2) : +// this.toolMaterial.getHarvestLevel() >= 2) : +// this.toolMaterial.getHarvestLevel() >= 2); + } + + public boolean canUseOn(ItemStack stack, Block state) + { + return state.getMiningLevel() >= 0 /* state.getMaterial() != Material.iron && state.getMaterial() != Material.anvil && state.getMaterial() != Material.rock + ? super.getStrVsBlock(stack, state) */; + } +} diff --git a/common/src/main/java/common/item/ItemPiston.java b/common/src/common/item/ItemPiston.java similarity index 100% rename from common/src/main/java/common/item/ItemPiston.java rename to common/src/common/item/ItemPiston.java diff --git a/common/src/main/java/common/item/ItemPotion.java b/common/src/common/item/ItemPotion.java similarity index 76% rename from common/src/main/java/common/item/ItemPotion.java rename to common/src/common/item/ItemPotion.java index 29a9c7b..a254127 100755 --- a/common/src/main/java/common/item/ItemPotion.java +++ b/common/src/common/item/ItemPotion.java @@ -3,8 +3,12 @@ package common.item; import java.util.Iterator; import java.util.List; import java.util.Map; -import common.collect.Lists; +import java.util.Map.Entry; + +import common.attributes.Attribute; +import common.attributes.AttributeModifier; import common.collect.Maps; +import common.collect.Sets; import common.color.TextColor; import common.entity.npc.EntityNPC; import common.entity.projectile.EntityPotion; @@ -18,6 +22,8 @@ import common.potion.PotionEffect; import common.potion.PotionHelper; import common.world.World; +import java.util.Set; + public class ItemPotion extends Item { private Map> effectCache = Maps.>newHashMap(); @@ -28,13 +34,13 @@ public class ItemPotion extends Item this.setMaxStackSize(1); this.setHasSubtypes(true); this.setMaxDamage(0); - this.setTab(CheatTab.MAGIC); + this.setTab(CheatTab.tabMagic); this.setColor(TextColor.ORK); } public List getEffects(ItemStack stack) { -// if (stack.hasTagCompound() && stack.getTagCompound().hasList("CustomPotionEffects")) +// if (stack.hasTagCompound() && stack.getTagCompound().hasKey("CustomPotionEffects", 9)) // { // List list1 = Lists.newArrayList(); // NBTTagList nbttaglist = stack.getTagCompound().getTagList("CustomPotionEffects", 10); @@ -87,7 +93,7 @@ public class ItemPotion extends Item { // if (!playerIn.creative) // { - --stack.size; + --stack.stackSize; // } if (!worldIn.client) @@ -98,10 +104,7 @@ public class ItemPotion extends Item { for (PotionEffect potioneffect : list) { - if(potioneffect.getPotion().isInstant()) - potioneffect.getPotion().onImpact(null, null, playerIn, potioneffect.getAmplifier(), 1.0); - else - playerIn.addEffect(new PotionEffect(potioneffect)); + playerIn.addEffect(new PotionEffect(potioneffect)); } } } @@ -110,7 +113,7 @@ public class ItemPotion extends Item // if (!playerIn.creative) // { - if (stack.size <= 0) + if (stack.stackSize <= 0) { return new ItemStack(Items.glass_bottle); } @@ -146,7 +149,7 @@ public class ItemPotion extends Item { // if (!playerIn.creative) // { - --itemStackIn.size; + --itemStackIn.stackSize; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); @@ -225,7 +228,7 @@ public class ItemPotion extends Item if (list != null && !list.isEmpty()) { - String s2 = list.get(0).getPotionName(); + String s2 = ((PotionEffect)list.get(0)).getPotionName(); // s2 = s2 + ".postfix"; return s + s2.trim(); } @@ -245,7 +248,7 @@ public class ItemPotion extends Item if ((stack.getMetadata() & 16383) != 0) { List list = Items.potion.getEffects(stack); - List implications = Lists.newArrayList(); + Map> multimap = Maps.newHashMap(); if (list != null && !list.isEmpty()) { @@ -253,6 +256,31 @@ public class ItemPotion extends Item { String s1 = potioneffect.getEffectName().trim(); Potion potion = potioneffect.getPotion(); + Map map = potion.getModifiers(); + + if (map != null && map.size() > 0) + { + for (Entry entry : map.entrySet()) + { + AttributeModifier attributemodifier = (AttributeModifier)entry.getValue(); + AttributeModifier attributemodifier1 = new AttributeModifier(attributemodifier.getName(), potion.getAmount(potioneffect.getAmplifier(), attributemodifier), attributemodifier.isMultiplied()); + Set set = multimap.get(entry.getKey()); + if(set == null) + multimap.put(entry.getKey(), set = Sets.newHashSet()); + set.add(attributemodifier1); +// multimap.put((Attribute)entry.getKey(), set); + } + } + + s1 = s1 + PotionHelper.getPotionPotency(potioneffect.getAmplifier()); +// if (potioneffect.getAmplifier() >= 1 && potioneffect.getAmplifier() <= 9) +// { +// s1 = s1 + " " + Strs.get("potion.potency." + potioneffect.getAmplifier()).trim(); +// } +// else if (potioneffect.getAmplifier() != 0) +// { +// s1 = s1 + " " + (potioneffect.getAmplifier() + 1); +// } if (potioneffect.getDuration() > 20) { @@ -267,9 +295,6 @@ public class ItemPotion extends Item { tooltip.add(TextColor.LGRAY + s1); } - String effectTip = potioneffect.getPotion().getTooltip(potioneffect.getAmplifier()); - if(effectTip != null) - implications.add(effectTip); } } else @@ -278,11 +303,37 @@ public class ItemPotion extends Item tooltip.add(TextColor.LGRAY + s); } - if (!implications.isEmpty()) + if (!multimap.isEmpty()) { tooltip.add(""); tooltip.add(TextColor.DMAGENTA + "Auswirkungen:"); - tooltip.addAll(implications); + + for (Entry> entry1 : multimap.entrySet()) + { + for(AttributeModifier attributemodifier2 : entry1.getValue()) { + double d0 = attributemodifier2.getAmount(); + double d1; + + if (!attributemodifier2.isMultiplied()) + { + d1 = attributemodifier2.getAmount(); + } + else + { + d1 = attributemodifier2.getAmount() * 100.0D; + } + + if (d0 > 0.0D) + { + tooltip.add(TextColor.BLUE + String.format("+%s" + (attributemodifier2.isMultiplied() ? "%%" : "") + " %s", ItemStack.DECIMALFORMAT.format(d1), entry1.getKey().getDisplayName())); + } + else if (d0 < 0.0D) + { + d1 = d1 * -1.0D; + tooltip.add(TextColor.RED + String.format("-%s" + (attributemodifier2.isMultiplied() ? "%%" : "") + " %s", ItemStack.DECIMALFORMAT.format(d1), entry1.getKey().getDisplayName())); + } + } + } } } } @@ -363,7 +414,7 @@ public class ItemPotion extends Item // if(!adv) { // return false; // } -// if(!tag.hasList("CustomPotionEffects")) { +// if(!tag.hasKey("CustomPotionEffects", 9)) { // return false; // } // NBTTagList effects = tag.getTagList("CustomPotionEffects", 10); diff --git a/common/src/main/java/common/item/ItemPressurePlate.java b/common/src/common/item/ItemPressurePlate.java similarity index 93% rename from common/src/main/java/common/item/ItemPressurePlate.java rename to common/src/common/item/ItemPressurePlate.java index e644b4b..5a246b2 100755 --- a/common/src/main/java/common/item/ItemPressurePlate.java +++ b/common/src/common/item/ItemPressurePlate.java @@ -1,7 +1,7 @@ package common.item; import common.block.Block; -import common.block.tech.BlockBasePressurePlate; +import common.block.BlockBasePressurePlate; import common.model.Model; import common.model.ModelProvider; diff --git a/common/src/main/java/common/item/ItemRecord.java b/common/src/common/item/ItemRecord.java similarity index 90% rename from common/src/main/java/common/item/ItemRecord.java rename to common/src/common/item/ItemRecord.java index d43a90e..ae209bc 100755 --- a/common/src/main/java/common/item/ItemRecord.java +++ b/common/src/common/item/ItemRecord.java @@ -5,7 +5,7 @@ import common.model.ModelProvider; public class ItemRecord extends Item { public ItemRecord() { - this.setTab(CheatTab.MISC); + this.setTab(CheatTab.tabMisc); } public Model getModel(ModelProvider provider, String name, int meta) { diff --git a/common/src/main/java/common/item/ItemRedstone.java b/common/src/common/item/ItemRedstone.java similarity index 95% rename from common/src/main/java/common/item/ItemRedstone.java rename to common/src/common/item/ItemRedstone.java index 27a1662..fa090d4 100755 --- a/common/src/main/java/common/item/ItemRedstone.java +++ b/common/src/common/item/ItemRedstone.java @@ -12,7 +12,7 @@ public class ItemRedstone extends Item { public ItemRedstone() { - this.setTab(CheatTab.TECHNOLOGY); + this.setTab(CheatTab.tabTech); } public Block getBlock() @@ -42,7 +42,7 @@ public class ItemRedstone extends Item } else if (Blocks.redstone.canPlaceBlockAt(worldIn, blockpos)) { - --stack.size; + --stack.stackSize; worldIn.setState(blockpos, Blocks.redstone.getState()); return true; } diff --git a/common/src/common/item/ItemReed.java b/common/src/common/item/ItemReed.java new file mode 100755 index 0000000..263df61 --- /dev/null +++ b/common/src/common/item/ItemReed.java @@ -0,0 +1,81 @@ +package common.item; + +import common.block.Block; +import common.block.BlockSnow; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; + +public class ItemReed extends Item +{ + private Block block; + + public ItemReed(Block block) + { + this.block = block; + } + + public Block getBlock() + { + return this.block; + } + + /** + * Called when a Block is right-clicked with this Item + */ + public boolean onItemUse(ItemStack stack, EntityNPC playerIn, World worldIn, BlockPos pos, Facing side, float hitX, float hitY, float hitZ) + { + State iblockstate = worldIn.getState(pos); + Block block = iblockstate.getBlock(); + + if (block == Blocks.snow_layer && ((Integer)iblockstate.getValue(BlockSnow.LAYERS)).intValue() < 1) + { + side = Facing.UP; + } + else if (!block.isReplaceable(worldIn, pos)) + { + pos = pos.offset(side); + } + + if (!playerIn.canPlayerEdit(pos, side, stack)) + { + return false; + } + else if (stack.stackSize == 0) + { + return false; + } + else + { + if (worldIn.canBlockBePlaced(this.block, pos, false, side, (Entity)null, stack)) + { + State iblockstate1 = this.block.onBlockPlaced(worldIn, pos, side, hitX, hitY, hitZ, 0, playerIn); + + if (worldIn.setState(pos, iblockstate1, 3)) + { + iblockstate1 = worldIn.getState(pos); + + if (iblockstate1.getBlock() == this.block) + { + ItemBlock.setTileEntityNBT(worldIn, playerIn, pos, stack); + iblockstate1.getBlock().onBlockPlacedBy(worldIn, pos, iblockstate1, playerIn, stack); + } + + worldIn.playSound(this.block.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), 1.0F); + --stack.stackSize; + return true; + } + } + + return false; + } + } + + public boolean isMagnetic() { + return this.block.isMagnetic(); + } +} diff --git a/common/src/main/java/common/item/ItemRod.java b/common/src/common/item/ItemRod.java similarity index 100% rename from common/src/main/java/common/item/ItemRod.java rename to common/src/common/item/ItemRod.java diff --git a/common/src/main/java/common/item/ItemSaddle.java b/common/src/common/item/ItemSaddle.java similarity index 94% rename from common/src/main/java/common/item/ItemSaddle.java rename to common/src/common/item/ItemSaddle.java index be30a91..f872541 100755 --- a/common/src/main/java/common/item/ItemSaddle.java +++ b/common/src/common/item/ItemSaddle.java @@ -9,7 +9,7 @@ public class ItemSaddle extends Item public ItemSaddle() { this.maxStackSize = 1; - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } /** @@ -25,7 +25,7 @@ public class ItemSaddle extends Item { entitypig.setSaddled(true); // entitypig.worldObj.playSoundAtEntity(entitypig, "mob.horse.leather", 0.5F, 1.0F); - --stack.size; + --stack.stackSize; } return true; diff --git a/common/src/main/java/common/item/ItemSeedFood.java b/common/src/common/item/ItemSeedFood.java similarity index 94% rename from common/src/main/java/common/item/ItemSeedFood.java rename to common/src/common/item/ItemSeedFood.java index e7f7fb1..7347a5c 100755 --- a/common/src/main/java/common/item/ItemSeedFood.java +++ b/common/src/common/item/ItemSeedFood.java @@ -18,7 +18,7 @@ public class ItemSeedFood extends ItemFood super(healAmount, false); this.crops = crops; this.soilId = soil; - this.setTab(CheatTab.PLANTS); + this.setTab(CheatTab.tabPlants); } public Block getBlock() @@ -42,7 +42,7 @@ public class ItemSeedFood extends ItemFood else if (worldIn.getState(pos).getBlock() == this.soilId && worldIn.isAirBlock(pos.up())) { worldIn.setState(pos.up(), this.crops.getState()); - --stack.size; + --stack.stackSize; return true; } else diff --git a/common/src/main/java/common/item/ItemSeeds.java b/common/src/common/item/ItemSeeds.java similarity index 94% rename from common/src/main/java/common/item/ItemSeeds.java rename to common/src/common/item/ItemSeeds.java index 6604c20..2bf6656 100755 --- a/common/src/main/java/common/item/ItemSeeds.java +++ b/common/src/common/item/ItemSeeds.java @@ -18,7 +18,7 @@ public class ItemSeeds extends Item { this.crops = crops; this.soilBlockID = soil; - this.setTab(CheatTab.PLANTS); + this.setTab(CheatTab.tabPlants); } public Block getBlock() @@ -42,7 +42,7 @@ public class ItemSeeds extends Item else if (worldIn.getState(pos).getBlock() == this.soilBlockID && worldIn.isAirBlock(pos.up())) { worldIn.setState(pos.up(), this.crops.getState()); - --stack.size; + --stack.stackSize; return true; } else diff --git a/common/src/main/java/common/item/ItemShears.java b/common/src/common/item/ItemShears.java similarity index 90% rename from common/src/main/java/common/item/ItemShears.java rename to common/src/common/item/ItemShears.java index b3e3556..81c0b0a 100755 --- a/common/src/main/java/common/item/ItemShears.java +++ b/common/src/common/item/ItemShears.java @@ -1,10 +1,10 @@ package common.item; import common.block.Block; -import common.block.Material; import common.entity.types.EntityLiving; import common.init.Blocks; import common.init.ToolMaterial; +import common.material.Material; import common.util.BlockPos; import common.world.World; @@ -16,7 +16,7 @@ public class ItemShears extends Item { this.setMaxStackSize(1); this.setMaxDamage(material.getDurability() - 12); - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); this.material = material; } @@ -35,7 +35,7 @@ public class ItemShears extends Item public boolean canHarvestBlock(Block blockIn) { - return blockIn.getMaterial() == Material.FLUFF || blockIn == Blocks.redstone || blockIn == Blocks.string; + return blockIn.getMaterial() == Material.web || blockIn == Blocks.redstone || blockIn == Blocks.string; } public float getStrVsBlock(ItemStack stack, Block state) diff --git a/common/src/main/java/common/item/ItemSign.java b/common/src/common/item/ItemSign.java similarity index 92% rename from common/src/main/java/common/item/ItemSign.java rename to common/src/common/item/ItemSign.java index d96831a..81719ad 100755 --- a/common/src/main/java/common/item/ItemSign.java +++ b/common/src/common/item/ItemSign.java @@ -1,8 +1,8 @@ package common.item; import common.block.Block; -import common.block.tile.BlockStandingSign; -import common.block.tile.BlockWallSign; +import common.block.BlockStandingSign; +import common.block.BlockWallSign; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.tileentity.TileEntity; @@ -16,7 +16,7 @@ public class ItemSign extends Item { public ItemSign() { - this.setTab(CheatTab.DECORATION); + this.setTab(CheatTab.tabDeco); } public Block getBlock() @@ -65,7 +65,7 @@ public class ItemSign extends Item worldIn.setState(pos, Blocks.wall_sign.getState().withProperty(BlockWallSign.FACING, side), 3); } - --stack.size; + --stack.stackSize; TileEntity tileentity = worldIn.getTileEntity(pos); if (tileentity instanceof TileEntitySign && !ItemBlock.setTileEntityNBT(worldIn, playerIn, pos, stack)) @@ -84,7 +84,7 @@ public class ItemSign extends Item // // protected boolean validateNbt(NBTTagCompound tag) { // if(tag.hasKey("BlockEntityTag")) { -// if(!tag.hasTag("BlockEntityTag")) { +// if(!tag.hasKey("BlockEntityTag", 10)) { // return false; // } // } diff --git a/common/src/common/item/ItemSkull.java b/common/src/common/item/ItemSkull.java new file mode 100755 index 0000000..ce5443e --- /dev/null +++ b/common/src/common/item/ItemSkull.java @@ -0,0 +1,188 @@ +package common.item; + +import common.block.Block; +import common.block.BlockSkull; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.tileentity.TileEntity; +import common.tileentity.TileEntitySkull; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.world.State; +import common.world.World; + +public class ItemSkull extends Item +{ + public ItemSkull() + { + this.setTab(CheatTab.tabDeco); +// this.setMaxDamage(0); +// this.setHasSubtypes(true); + } + + public Block getBlock() + { + return Blocks.skull; + } + + /** + * Called when a Block is right-clicked with this Item + */ + public boolean onItemUse(ItemStack stack, EntityNPC playerIn, World worldIn, BlockPos pos, Facing side, float hitX, float hitY, float hitZ) + { + if (side == Facing.DOWN) + { + return false; + } + else + { + State iblockstate = worldIn.getState(pos); + Block block = iblockstate.getBlock(); + boolean flag = block.isReplaceable(worldIn, pos); + + if (!flag) + { + if (!worldIn.getState(pos).getBlock().getMaterial().isSolid()) + { + return false; + } + + pos = pos.offset(side); + } + + if (!playerIn.canPlayerEdit(pos, side, stack)) + { + return false; + } + else if (!Blocks.skull.canPlaceBlockAt(worldIn, pos)) + { + return false; + } + else + { + if (!worldIn.client) + { + worldIn.setState(pos, Blocks.skull.getState().withProperty(BlockSkull.FACING, side), 3); + int i = 0; + + if (side == Facing.UP) + { + i = ExtMath.floord((double)(playerIn.rotYaw * 16.0F / 360.0F) + 0.5D) & 15; + } + + TileEntity tileentity = worldIn.getTileEntity(pos); + + if (tileentity instanceof TileEntitySkull) + { + TileEntitySkull tileentityskull = (TileEntitySkull)tileentity; + +// if (stack.getMetadata() == 3) +// { +// String user = null; +// +// if (stack.hasTagCompound()) +// { +// NBTTagCompound nbttagcompound = stack.getTagCompound(); +// +// if (nbttagcompound.hasKey("SkullOwner", 8) && nbttagcompound.getString("SkullOwner").length() > 0) +// { +// user = nbttagcompound.getString("SkullOwner"); +// } +// } +// +// tileentityskull.setUser(user); +// } +// else +// { +// tileentityskull.setType(stack.getMetadata()); +// } + + tileentityskull.setSkullRotation(i); +// Blocks.skull.checkWitherSpawn(worldIn, pos, tileentityskull); + } + + --stack.stackSize; + } + + return true; + } + } + } + +// /** +// * returns a list of items with the same ID, but different meta (eg: dye returns 16 items) +// */ +// public void getSubItems(Item itemIn, CreativeTabs tab, List subItems) +// { +// for (int i = 0; i < skullTypes.length; ++i) +// { +// subItems.add(new ItemStack(itemIn, 1, i)); +// } +// } + +// /** +// * Converts the given ItemStack damage value into a metadata value to be placed in the world when this Item is +// * placed as a Block (mostly used with ItemBlocks). +// */ +// public int getMetadata(int damage) +// { +// return damage; +// } + +// /** +// * Returns the unlocalized name of this item. This version accepts an ItemStack so different stacks can have +// * different names based on their damage or NBT. +// */ +// public String getUnlocalizedName(ItemStack stack) +// { +// int i = stack.getMetadata(); +// +// if (i < 0 || i >= skullTypes.length) +// { +// i = 0; +// } +// +// return super.getUnlocalizedName() + "." + skullTypes[i]; +// } + +// public String getDisplay(ItemStack stack) +// { +// if (stack.hasTagCompound()) +// { +// if (stack.getTagCompound().hasKey("SkullOwner", 8)) +// { +// return super.getDisplay(stack) + " von " + stack.getTagCompound().getString("SkullOwner"); +// } +// } +// +// return super.getDisplay(stack); +// } + +// public Set getValidTags() { +// return Sets.newHashSet("SkullOwner"); +// } +// +// protected boolean validateNbt(NBTTagCompound tag) { +// if(tag.hasKey("SkullOwner")) { +//// if(!adv) { +//// return false; +//// } +// if(!tag.hasKey("SkullOwner", 8)) { +// return false; +// } +// } +// return true; +// } + + public Transforms getTransform() { + return Transforms.SKULL; + } + + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(provider.getEntityModel(), this.getTransform()); + } +} diff --git a/common/src/main/java/common/item/ItemSlab.java b/common/src/common/item/ItemSlab.java similarity index 97% rename from common/src/main/java/common/item/ItemSlab.java rename to common/src/common/item/ItemSlab.java index e30370b..4b171ba 100755 --- a/common/src/main/java/common/item/ItemSlab.java +++ b/common/src/common/item/ItemSlab.java @@ -1,7 +1,7 @@ package common.item; import common.block.Block; -import common.block.artificial.BlockSlab; +import common.block.BlockSlab; import common.entity.npc.EntityNPC; import common.util.BlockPos; import common.util.Facing; @@ -43,7 +43,7 @@ public class ItemSlab extends ItemBlock */ public boolean onItemUse(ItemStack stack, EntityNPC playerIn, World worldIn, BlockPos pos, Facing side, float hitX, float hitY, float hitZ) { - if (stack.size == 0) + if (stack.stackSize == 0) { return false; } @@ -69,7 +69,7 @@ public class ItemSlab extends ItemBlock if (worldIn.checkNoEntityCollision(this.slab.getCollisionBoundingBox(worldIn, pos, iblockstate1)) && worldIn.setState(pos, iblockstate1, 3)) { worldIn.playSound(this.slab.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), 1.0F); - --stack.size; + --stack.stackSize; } return true; @@ -143,7 +143,7 @@ public class ItemSlab extends ItemBlock if (worldIn.checkNoEntityCollision(this.slab.getCollisionBoundingBox(worldIn, pos, iblockstate1)) && worldIn.setState(pos, iblockstate1, 3)) { worldIn.playSound(this.slab.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), 1.0F); - --stack.size; + --stack.stackSize; } return true; @@ -173,7 +173,7 @@ public class ItemSlab extends ItemBlock if (worldIn.setState(pos, iblockstate1, 3)) { worldIn.playSound(this.slab.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), 1.0F); - --stack.size; + --stack.stackSize; } return true; diff --git a/common/src/main/java/common/item/ItemSmall.java b/common/src/common/item/ItemSmall.java similarity index 100% rename from common/src/main/java/common/item/ItemSmall.java rename to common/src/common/item/ItemSmall.java diff --git a/common/src/main/java/common/item/ItemSnow.java b/common/src/common/item/ItemSnow.java similarity index 95% rename from common/src/main/java/common/item/ItemSnow.java rename to common/src/common/item/ItemSnow.java index f19ba09..d98bc65 100755 --- a/common/src/main/java/common/item/ItemSnow.java +++ b/common/src/common/item/ItemSnow.java @@ -1,7 +1,7 @@ package common.item; import common.block.Block; -import common.block.natural.BlockSnow; +import common.block.BlockSnow; import common.entity.npc.EntityNPC; import common.util.BlockPos; import common.util.BoundingBox; @@ -23,7 +23,7 @@ public class ItemSnow extends ItemBlock */ public boolean onItemUse(ItemStack stack, EntityNPC playerIn, World worldIn, BlockPos pos, Facing side, float hitX, float hitY, float hitZ) { - if (stack.size == 0) + if (stack.stackSize == 0) { return false; } @@ -56,7 +56,7 @@ public class ItemSnow extends ItemBlock if (axisalignedbb != null && worldIn.checkNoEntityCollision(axisalignedbb) && worldIn.setState(blockpos, iblockstate1, 2)) { worldIn.playSound(this.block.sound.getPlaceSound(), (double)((float)blockpos.getX() + 0.5F), (double)((float)blockpos.getY() + 0.5F), (double)((float)blockpos.getZ() + 0.5F), 1.0F); - --stack.size; + --stack.stackSize; return true; } } diff --git a/common/src/main/java/common/item/ItemSnowball.java b/common/src/common/item/ItemSnowball.java similarity index 92% rename from common/src/main/java/common/item/ItemSnowball.java rename to common/src/common/item/ItemSnowball.java index 08177e5..efdf480 100755 --- a/common/src/main/java/common/item/ItemSnowball.java +++ b/common/src/common/item/ItemSnowball.java @@ -9,7 +9,7 @@ public class ItemSnowball extends Item { public ItemSnowball() { - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } /** @@ -19,7 +19,7 @@ public class ItemSnowball extends Item { // if (!playerIn.creative) // { - --itemStackIn.size; + --itemStackIn.stackSize; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); diff --git a/common/src/main/java/common/item/ItemSoup.java b/common/src/common/item/ItemSoup.java similarity index 100% rename from common/src/main/java/common/item/ItemSoup.java rename to common/src/common/item/ItemSoup.java diff --git a/common/src/main/java/common/item/ItemSpaceNavigator.java b/common/src/common/item/ItemSpaceNavigator.java similarity index 96% rename from common/src/main/java/common/item/ItemSpaceNavigator.java rename to common/src/common/item/ItemSpaceNavigator.java index eb3841f..5c256ad 100755 --- a/common/src/main/java/common/item/ItemSpaceNavigator.java +++ b/common/src/common/item/ItemSpaceNavigator.java @@ -15,12 +15,12 @@ public class ItemSpaceNavigator extends ItemMagnetic { long frac = (time * 1000L / UniverseRegistry.EARTH_YEAR) % 1000L; if(!world.dimension.getType().time) { return String.format("%d.%03d.%03d.M%d" + (days ? " T???.??? D???.???.G?" : ""), world.dimension.getTimeQualifier(), - frac, year % 1000L, year / 1000L + 1L); + frac, year % 1000L, year / 1000L); } long day = time / world.dimension.getRotationalPeriod(); time = time % world.dimension.getRotationalPeriod(); return String.format("%d.%03d.%03d.M%d" + (days ? " T%03d.%03d D%03d.%03d.G%d" : ""), world.dimension.getTimeQualifier(), - frac, year % 1000L, year / 1000L + 1L, + frac, year % 1000L, year / 1000L, time / 1000L, time % 1000L, (day / 1000L) % 1000L, day % 1000L, day / 1000000L); } diff --git a/common/src/common/item/ItemSpade.java b/common/src/common/item/ItemSpade.java new file mode 100755 index 0000000..f2633c7 --- /dev/null +++ b/common/src/common/item/ItemSpade.java @@ -0,0 +1,28 @@ +package common.item; + +import common.block.Block; +import common.init.ToolMaterial; +import common.material.Material; + +public class ItemSpade extends ItemTool +{ +// private static final Set EFFECTIVE_ON = Sets.newHashSet(new Block[] { +// Blocks.clay, Blocks.dirt, Blocks.farmland, Blocks.grass, Blocks.gravel, Blocks.mycelium, Blocks.sand, Blocks.snow, Blocks.snow_layer, Blocks.soul_sand +// }); + + public ItemSpade(ToolMaterial material) + { + super(1, material); + } + + public boolean canUseOn(ItemStack stack, Block state) + { + return state.canShovelHarvest(); + } + + public boolean canHarvestBlock(Block blockIn) + { +// return blockIn == Blocks.snow_layer ? true : blockIn == Blocks.snow; + return blockIn.getMaterial() == Material.snow ? true : blockIn.getMaterial() == Material.craftedSnow; + } +} diff --git a/common/src/main/java/common/item/ItemStack.java b/common/src/common/item/ItemStack.java similarity index 67% rename from common/src/main/java/common/item/ItemStack.java rename to common/src/common/item/ItemStack.java index 82a92c2..0088c3c 100755 --- a/common/src/main/java/common/item/ItemStack.java +++ b/common/src/common/item/ItemStack.java @@ -6,71 +6,94 @@ import java.util.Map; import java.util.Map.Entry; import common.attributes.Attribute; -import common.attributes.UsageSlot; +import common.attributes.AttributeModifier; +import common.attributes.Attributes; import common.block.Block; import common.collect.Lists; import common.collect.Maps; import common.color.TextColor; import common.enchantment.Enchantment; +import common.enchantment.EnchantmentDurability; import common.enchantment.EnchantmentHelper; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.BlockRegistry; import common.init.ItemRegistry; +import common.nbt.NBTBase; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.rng.Random; -import common.tags.TagObject; import common.util.BlockPos; import common.util.Facing; import common.world.World; +import java.util.Set; + public final class ItemStack { public static final int MAX_SIZE = 67108864; public static final DecimalFormat DECIMALFORMAT = new DecimalFormat("#.###"); - public int size; + /** Size of the stack. */ + public int stackSize; + + /** + * Number of animation frames to go when receiving an item (by walking into it, for example). + */ +// public int animationsToGo; private Item item; - private TagObject tag; - private int meta; - public ItemStack(Block block) + /** + * A NBTTagMap containing data about an ItemStack. Can only be used for non stackable items + */ + private NBTTagCompound stackTagCompound; + private int itemDamage; + + /** Item frame this stack is on, or null if not on an item frame. */ +// private EntityFrame itemFrame; +// private Block canDestroyCacheBlock; +// private boolean canDestroyCacheResult; +// private Block canPlaceOnCacheBlock; +// private boolean canPlaceOnCacheResult; + + public ItemStack(Block blockIn) { - this(block, 1); + this((Block)blockIn, 1); } - public ItemStack(Block block, int amount) + public ItemStack(Block blockIn, int amount) { - this(block, amount, 0); + this((Block)blockIn, amount, 0); } - public ItemStack(Block block, int amount, int meta) + public ItemStack(Block blockIn, int amount, int meta) { - this(ItemRegistry.getItemFromBlock(block), amount, meta); + this(ItemRegistry.getItemFromBlock(blockIn), amount, meta); } - public ItemStack(Item item) + public ItemStack(Item itemIn) { - this(item, 1); + this((Item)itemIn, 1); } - public ItemStack(Item item, int amount) + public ItemStack(Item itemIn, int amount) { - this(item, amount, 0); + this((Item)itemIn, amount, 0); } - public ItemStack(Item item, int amount, int meta) + public ItemStack(Item itemIn, int amount, int meta) { // this.canDestroyCacheBlock = null; // this.canDestroyCacheResult = false; // this.canPlaceOnCacheBlock = null; // this.canPlaceOnCacheResult = false; - this.item = item; - this.size = amount; - this.meta = meta; + this.item = itemIn; + this.stackSize = amount; + this.itemDamage = meta; - if (this.meta < 0) + if (this.itemDamage < 0) { - this.meta = 0; + this.itemDamage = 0; } } @@ -91,10 +114,10 @@ public final class ItemStack return (amount / 1000000000) + "B+"; } - public static ItemStack readFromTag(TagObject tag) + public static ItemStack loadItemStackFromNBT(NBTTagCompound nbt) { ItemStack itemstack = new ItemStack(); - itemstack.readTags(tag); + itemstack.readFromNBT(nbt); return itemstack.getItem() != null ? itemstack : null; } @@ -111,14 +134,14 @@ public final class ItemStack */ public ItemStack splitStack(int amount) { - ItemStack itemstack = new ItemStack(this.item, amount, this.meta); + ItemStack itemstack = new ItemStack(this.item, amount, this.itemDamage); - if (this.tag != null) + if (this.stackTagCompound != null) { - itemstack.tag = this.tag.copy(); + itemstack.stackTagCompound = (NBTTagCompound)this.stackTagCompound.copy(); } - this.size -= amount; + this.stackSize -= amount; return itemstack; } @@ -169,52 +192,52 @@ public final class ItemStack } /** - * Write the stack fields to a object. Return the new object. + * Write the stack fields to a NBT object. Return the new NBT object. */ - public TagObject writeTags(TagObject tag) + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { - String resourcelocation = ItemRegistry.getNameFromItem(this.item); - tag.setString("id", resourcelocation == null ? "air" : resourcelocation.toString()); - tag.setInt("Count", this.size); - tag.setShort("Damage", (short)this.meta); + String resourcelocation = ItemRegistry.REGISTRY.getNameForObject(this.item); + nbt.setString("id", resourcelocation == null ? "air" : resourcelocation.toString()); + nbt.setInteger("Count", this.stackSize); + nbt.setShort("Damage", (short)this.itemDamage); - if (this.tag != null) + if (this.stackTagCompound != null) { - tag.setObject("tag", this.tag); + nbt.setTag("tag", this.stackTagCompound); } - return tag; + return nbt; } /** - * Read the stack fields from a object. + * Read the stack fields from a NBT object. */ - public void readTags(TagObject tag) + public void readFromNBT(NBTTagCompound nbt) { - if (tag.hasString("id")) + if (nbt.hasKey("id", 8)) { - this.item = ItemRegistry.getRegisteredItem(tag.getString("id")); + this.item = ItemRegistry.getRegisteredItem(nbt.getString("id")); } else { - this.item = ItemRegistry.getItemById(tag.getShort("id")); + this.item = ItemRegistry.getItemById(nbt.getShort("id")); } - this.size = tag.getInt("Count"); - this.meta = tag.getShort("Damage"); + this.stackSize = nbt.getInteger("Count"); + this.itemDamage = nbt.getShort("Damage"); - if (this.meta < 0) + if (this.itemDamage < 0) { - this.meta = 0; + this.itemDamage = 0; } - if (tag.hasObject("tag")) + if (nbt.hasKey("tag", 10)) { - this.tag = tag.getObject("tag"); + this.stackTagCompound = nbt.getCompoundTag("tag"); if (this.item != null) { - this.item.updateItemStackNBT(this.tag); + this.item.updateItemStackNBT(this.stackTagCompound); } } } @@ -247,7 +270,7 @@ public final class ItemStack // { // if(!breakable) { // if(this.stackTagCompound == null) { -// this.setTagCompound(new TagObject()); +// this.setTagCompound(new NBTTagCompound()); // } // this.stackTagCompound.setBoolean("Unbreakable", true); // this.setItemDamage(0); @@ -272,26 +295,26 @@ public final class ItemStack */ public boolean isItemDamaged() { - return this.isItemStackDamageable() && this.meta > 0; + return this.isItemStackDamageable() && this.itemDamage > 0; } public int getItemDamage() { - return this.meta; + return this.itemDamage; } public int getMetadata() { - return this.meta; + return this.itemDamage; } public void setItemDamage(int meta) { - this.meta = meta; + this.itemDamage = meta; - if (this.meta < 0) + if (this.itemDamage < 0) { - this.meta = 0; + this.itemDamage = 0; } } @@ -319,12 +342,12 @@ public final class ItemStack { if (amount > 0) { - int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.UNBREAKING, this); + int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.unbreaking.effectId, this); int j = 0; for (int k = 0; i > 0 && k < amount; ++k) { - if (Enchantment.negateDamage(this, i, rand)) + if (EnchantmentDurability.negateDamage(this, i, rand)) { ++j; } @@ -338,8 +361,8 @@ public final class ItemStack } } - this.meta += amount; - return this.meta > this.getMaxDamage(); + this.itemDamage += amount; + return this.itemDamage > this.getMaxDamage(); } } @@ -355,25 +378,25 @@ public final class ItemStack if (this.attemptDamageItem(amount, entityIn.getRNG())) { entityIn.renderBrokenItemStack(this); - --this.size; + --this.stackSize; if (entityIn.isPlayer()) { EntityNPC entityplayer = (EntityNPC)entityIn; // entityplayer.triggerAchievement(StatRegistry.objectBreakStats[ItemRegistry.getIdFromItem(this.item)]); - if (this.size == 0 && this.getItem() instanceof ItemBow) + if (this.stackSize == 0 && this.getItem() instanceof ItemBow) { entityplayer.destroyCurrentEquippedItem(); } } - if (this.size < 0) + if (this.stackSize < 0) { - this.size = 0; + this.stackSize = 0; } - this.meta = 0; + this.itemDamage = 0; } } // } @@ -423,11 +446,11 @@ public final class ItemStack */ public ItemStack copy() { - ItemStack itemstack = new ItemStack(this.item, this.size, this.meta); + ItemStack itemstack = new ItemStack(this.item, this.stackSize, this.itemDamage); - if (this.tag != null) + if (this.stackTagCompound != null) { - itemstack.tag = this.tag.copy(); + itemstack.stackTagCompound = (NBTTagCompound)this.stackTagCompound.copy(); } return itemstack; @@ -435,7 +458,7 @@ public final class ItemStack public static boolean areItemStackTagsEqual(ItemStack stackA, ItemStack stackB) { - return stackA == null && stackB == null ? true : (stackA != null && stackB != null ? (stackA.tag == null && stackB.tag != null ? false : stackA.tag == null || stackA.tag.equals(stackB.tag)) : false); + return stackA == null && stackB == null ? true : (stackA != null && stackB != null ? (stackA.stackTagCompound == null && stackB.stackTagCompound != null ? false : stackA.stackTagCompound == null || stackA.stackTagCompound.equals(stackB.stackTagCompound)) : false); } /** @@ -451,7 +474,7 @@ public final class ItemStack */ private boolean isItemStackEqual(ItemStack other) { - return this.size != other.size ? false : (this.item != other.item ? false : (this.meta != other.meta ? false : (this.tag == null && other.tag != null ? false : this.tag == null || this.tag.equals(other.tag)))); + return this.stackSize != other.stackSize ? false : (this.item != other.item ? false : (this.itemDamage != other.itemDamage ? false : (this.stackTagCompound == null && other.stackTagCompound != null ? false : this.stackTagCompound == null || this.stackTagCompound.equals(other.stackTagCompound)))); } /** @@ -468,7 +491,7 @@ public final class ItemStack */ public boolean isItemEqual(ItemStack other) { - return other != null && this.item == other.item && this.meta == other.meta; + return other != null && this.item == other.item && this.itemDamage == other.itemDamage; } // public String getUnlocalizedName() @@ -542,29 +565,29 @@ public final class ItemStack */ public boolean hasTagCompound() { - return this.tag != null; + return this.stackTagCompound != null; } /** * Returns the NBTTagCompound of the ItemStack. */ - public TagObject getTagCompound() + public NBTTagCompound getTagCompound() { - return this.tag; + return this.stackTagCompound; } /** * Get an NBTTagCompound from this stack's NBT data. */ - public TagObject getSubCompound(String key, boolean create) + public NBTTagCompound getSubCompound(String key, boolean create) { - if (this.tag != null && this.tag.hasObject(key)) + if (this.stackTagCompound != null && this.stackTagCompound.hasKey(key, 10)) { - return this.tag.getObject(key); + return this.stackTagCompound.getCompoundTag(key); } else if (create) { - TagObject nbttagcompound = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); this.setTagInfo(key, nbttagcompound); return nbttagcompound; } @@ -574,17 +597,17 @@ public final class ItemStack } } - public List getEnchantmentTagList() + public NBTTagList getEnchantmentTagList() { - return this.tag == null ? null : this.tag.getList("ench"); + return this.stackTagCompound == null ? null : this.stackTagCompound.getTagList("ench", 10); } /** * Assigns a NBTTagCompound to the ItemStack, does not validate that only non-stackable items can have it. */ - public void setTagCompound(TagObject nbt) + public void setTagCompound(NBTTagCompound nbt) { - this.tag = nbt; + this.stackTagCompound = nbt; } /** @@ -594,13 +617,13 @@ public final class ItemStack { String s = this.getItem().getDisplay(this); - if (this.tag != null && this.tag.hasString("Name")) + if (this.stackTagCompound != null && this.stackTagCompound.hasKey("Name", 8)) { // NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag("display"); // -// if (nbttagcompound.hasString("Name")) +// if (nbttagcompound.hasKey("Name", 8)) // { - s = this.tag.getString("Name"); + s = this.stackTagCompound.getString("Name"); // } } @@ -617,17 +640,17 @@ public final class ItemStack public ItemStack setStackDisplayName(String displayName) { - if (this.tag == null) + if (this.stackTagCompound == null) { - this.tag = new TagObject(); + this.stackTagCompound = new NBTTagCompound(); } -// if (!this.stackTagCompound.hasTag("display")) +// if (!this.stackTagCompound.hasKey("display", 10)) // { // this.stackTagCompound.setTag("display", new NBTTagCompound()); // } - this.tag.setString("Name", displayName); + this.stackTagCompound.setString("Name", displayName); return this; } @@ -638,7 +661,7 @@ public final class ItemStack // this.stackTagCompound = new NBTTagCompound(); // } // -// if (!this.stackTagCompound.hasTag("display")) +// if (!this.stackTagCompound.hasKey("display", 10)) // { // this.stackTagCompound.setTag("display", new NBTTagCompound()); // } @@ -658,7 +681,7 @@ public final class ItemStack // return null; // } // -// if (!this.stackTagCompound.hasTag("display")) +// if (!this.stackTagCompound.hasKey("display", 10)) // { // return null; // } @@ -702,14 +725,14 @@ public final class ItemStack */ public void clearCustomName() { - if (this.tag != null) + if (this.stackTagCompound != null) { - if (this.tag.hasString("Name")) + if (this.stackTagCompound.hasKey("Name", 8)) { // NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag("display"); - this.tag.remove("Name"); + this.stackTagCompound.removeTag("Name"); - if (this.tag.isEmpty()) + if (this.stackTagCompound.hasNoTags()) { // this.stackTagCompound.removeTag("display"); // @@ -726,7 +749,7 @@ public final class ItemStack // { // if (this.stackTagCompound != null) // { -// if (this.stackTagCompound.hasTag("display")) +// if (this.stackTagCompound.hasKey("display", 10)) // { // NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag("display"); // nbttagcompound.removeTag("Lore"); @@ -749,7 +772,7 @@ public final class ItemStack */ public boolean hasDisplayName() { - return this.tag != null && this.tag.hasString("Name"); + return this.stackTagCompound != null && this.stackTagCompound.hasKey("Name", 8); } public List getTooltip(EntityNPC playerIn) @@ -762,8 +785,8 @@ public final class ItemStack // s = ChatFormat.ITALIC + s; // } - if(this.size != 1) - s = TextColor.YELLOW + "" + this.size + " " + TextColor.RESET + s; + if(this.stackSize != 1) + s = TextColor.YELLOW + "" + this.stackSize + " " + TextColor.RESET + s; s = s + TextColor.RESET; @@ -783,7 +806,7 @@ public final class ItemStack if (this.getHasSubtypes()) { - s1 = s1 + String.format("%d", this.meta); + s1 = s1 + String.format("%d", this.itemDamage); } // else // { @@ -819,28 +842,28 @@ public final class ItemStack { // if ((i1 & 1) == 0) // { - List nbttaglist = this.getEnchantmentTagList(); + NBTTagList nbttaglist = this.getEnchantmentTagList(); if (nbttaglist != null) { - for (int j = 0; j < nbttaglist.size(); ++j) + for (int j = 0; j < nbttaglist.tagCount(); ++j) { - Enchantment k = Enchantment.getEnchantment(nbttaglist.get(j).getString("id")); + int k = nbttaglist.getCompoundTagAt(j).getShort("id"); + int l = nbttaglist.getCompoundTagAt(j).getShort("lvl"); - if (k != null) + if (Enchantment.getEnchantmentById(k) != null) { - int l = nbttaglist.get(j).getShort("lvl"); - list.add(k.getFormattedName(l)); + list.add(Enchantment.getEnchantmentById(k).getFormattedName(l)); } } } // } -// if (this.stackTagCompound.hasTag("display")) +// if (this.stackTagCompound.hasKey("display", 10)) // { // NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag("display"); // -// if (nbttagcompound.hasInt("color")) +// if (nbttagcompound.hasKey("color", 3)) // { // if (advanced) // { @@ -866,41 +889,57 @@ public final class ItemStack //// } // } } - - int damage = this.item.getAttackDamageBonus(); - damage += EnchantmentHelper.getDamageModifier(this); - if(damage != 0) { - if(damage > 0) - list.add(TextColor.BLUE + String.format("+%d Angriffsschaden", damage)); - else - list.add(TextColor.RED + String.format("-%d Angriffsschaden", damage)); - } - Map mods = this.getAttributeModifiers(null); + Map> multimap = this.getAttributeModifiers(3); - if (!mods.isEmpty()) + if (!multimap.isEmpty()) // && (i1 & 2) == 0) { list.add(""); - for (Entry entry : mods.entrySet()) + + for (Entry> entry : multimap.entrySet()) { - float amt = entry.getValue(); - if(this.size != 1) { - double total = amt * (double)this.size; - if (amt > 0.0D) - list.add(TextColor.BLUE + String.format("+%s %s [%dx +%s]", DECIMALFORMAT.format(total), entry.getKey(), this.size, DECIMALFORMAT.format(amt))); - else if (amt < 0.0D) - list.add(TextColor.RED + String.format("-%s %s [%dx -%s]", DECIMALFORMAT.format(total * -1.0), entry.getKey(), this.size, DECIMALFORMAT.format(amt * -1.0))); - } - else { - if (amt > 0.0D) - list.add(TextColor.BLUE + String.format("+%s %s", DECIMALFORMAT.format(amt), entry.getKey())); - else if (amt < 0.0D) - list.add(TextColor.RED + String.format("-%s %s", DECIMALFORMAT.format(amt * -1.0), entry.getKey())); + for(AttributeModifier mod : entry.getValue()) { + double amt = mod.getAmount(); + + if (mod.getID() == Attributes.ITEM_VAL_ID) + { + amt += (double)EnchantmentHelper.getDamageModifier(this); + } + + double num; + + if (!mod.isMultiplied()) + { + num = amt; + } + else + { + num = amt * 100.0D; + } + + if(mod.isInventory() && this.stackSize != 1) { + double total = num * (double)this.stackSize; + if (amt > 0.0D) + list.add(TextColor.BLUE + String.format("+%s" + (mod.isMultiplied() ? "%%" : "") + " %s [%dx +%s" + (mod.isMultiplied() ? "%%" : "") + "]", DECIMALFORMAT.format(total), entry.getKey().getDisplayName(), this.stackSize, DECIMALFORMAT.format(num))); + else if (amt < 0.0D) + list.add(TextColor.RED + String.format("-%s" + (mod.isMultiplied() ? "%%" : "") + " %s [%dx -%s" + (mod.isMultiplied() ? "%%" : "") + "]", DECIMALFORMAT.format(total * -1.0), entry.getKey().getDisplayName(), this.stackSize, DECIMALFORMAT.format(num * -1.0))); + } + else { + if (amt > 0.0D) + list.add(TextColor.BLUE + String.format("+%s" + (mod.isMultiplied() ? "%%" : "") + " %s", DECIMALFORMAT.format(num), entry.getKey().getDisplayName())); + else if (amt < 0.0D) + list.add(TextColor.RED + String.format("-%s" + (mod.isMultiplied() ? "%%" : "") + " %s", DECIMALFORMAT.format(num * -1.0), entry.getKey().getDisplayName())); + } } } } -// if (this.hasTagCompound() && this.stackTagCompound.hasList("CanDestroy") && (i1 & 8) == 0) + if (this.hasTagCompound() && this.getTagCompound().getBoolean("Unbreakable")) // && (i1 & 4) == 0) + { + list.add(TextColor.BLUE + "Unzerstörbar"); + } + +// if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanDestroy", 9) && (i1 & 8) == 0) // { // NBTTagList nbttaglist2 = this.stackTagCompound.getTagList("CanDestroy", 8); // @@ -925,7 +964,7 @@ public final class ItemStack // } // } // -// if (this.hasTagCompound() && this.stackTagCompound.hasList("CanPlaceOn") && (i1 & 16) == 0) +// if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanPlaceOn", 9) && (i1 & 16) == 0) // { // NBTTagList nbttaglist3 = this.stackTagCompound.getTagList("CanPlaceOn", 8); // @@ -957,15 +996,12 @@ public final class ItemStack list.add(String.format("Haltbarkeit: %d" + (this.isItemDamaged() ? " / %d" : ""), this.isItemDamaged() ? (this.getMaxDamage() - this.getItemDamage()) : this.getMaxDamage(), this.getMaxDamage())); } - - if(this.getRepairCost() > 0) - list.add("Reparaturkosten: " + this.getRepairCost() + " Mana"); - list.add(TextColor.GRAY + ItemRegistry.getNameFromItem(this.item)); + list.add(TextColor.GRAY + ItemRegistry.REGISTRY.getNameForObject(this.item)); if (this.hasTagCompound()) { - list.add(TextColor.GRAY + String.format("NBT-Tags: %d", this.getTagCompound().keySet().size())); + list.add(TextColor.GRAY + String.format("NBT-Tags: %d", this.getTagCompound().getKeySet().size())); } // } @@ -995,41 +1031,41 @@ public final class ItemStack */ public void addEnchantment(Enchantment ench, int level) { - if (this.tag == null) + if (this.stackTagCompound == null) { - this.setTagCompound(new TagObject()); + this.setTagCompound(new NBTTagCompound()); } - if (!this.tag.hasList("ench")) + if (!this.stackTagCompound.hasKey("ench", 9)) { - this.tag.setList("ench", Lists.newArrayList()); + this.stackTagCompound.setTag("ench", new NBTTagList()); } - List nbttaglist = this.tag.getList("ench"); - TagObject nbttagcompound = new TagObject(); - nbttagcompound.setString("id", ench.getName()); + NBTTagList nbttaglist = this.stackTagCompound.getTagList("ench", 10); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setShort("id", (short)ench.effectId); nbttagcompound.setShort("lvl", (short)(/* (byte) */ level)); - nbttaglist.add(nbttagcompound); + nbttaglist.appendTag(nbttagcompound); } /** * Removes an enchantment from the ItemStack. */ public boolean removeEnchantment(Enchantment ench) { - if(this.tag == null) { + if(this.stackTagCompound == null) { return false; } - if(!this.tag.hasList("ench")) { + if(!this.stackTagCompound.hasKey("ench", 9)) { return false; } - List oldEnch = this.tag.getList("ench"); - List newEnch = Lists.newArrayList(); + NBTTagList oldEnch = this.stackTagCompound.getTagList("ench", 10); + NBTTagList newEnch = new NBTTagList(); boolean changed = false; - TagObject tag; - for(int z = 0; z < oldEnch.size(); z++) { - tag = oldEnch.get(z); - if(Enchantment.getEnchantment(tag.getString("id")) != ench) { - newEnch.add(tag); + NBTTagCompound tag; + for(int z = 0; z < oldEnch.tagCount(); z++) { + tag = oldEnch.getCompoundTagAt(z); + if(tag.getShort("id") != ench.effectId) { + newEnch.appendTag(tag); } else { changed = true; @@ -1038,14 +1074,14 @@ public final class ItemStack if(!changed) { return false; } - if(newEnch.size() == 0) { - this.tag.remove("ench"); - if(this.tag.isEmpty()) { - this.tag = null; + if(newEnch.tagCount() == 0) { + this.stackTagCompound.removeTag("ench"); + if(this.stackTagCompound.hasNoTags()) { + this.stackTagCompound = null; } } else { - this.tag.setList("ench", newEnch); + this.stackTagCompound.setTag("ench", newEnch); } return true; } @@ -1054,15 +1090,15 @@ public final class ItemStack * Removes all enchantments from the ItemStack. */ public boolean clearEnchantments() { - if(this.tag == null) { + if(this.stackTagCompound == null) { return false; } - if(!this.tag.hasList("ench")) { + if(!this.stackTagCompound.hasKey("ench", 9)) { return false; } - this.tag.remove("ench"); - if(this.tag.isEmpty()) { - this.tag = null; + this.stackTagCompound.removeTag("ench"); + if(this.stackTagCompound.hasNoTags()) { + this.stackTagCompound = null; } return true; } @@ -1072,27 +1108,17 @@ public final class ItemStack */ public boolean isItemEnchanted() { - return this.tag != null && this.tag.hasList("ench"); + return this.stackTagCompound != null && this.stackTagCompound.hasKey("ench", 9); } - public void setTagInfo(String key, TagObject value) + public void setTagInfo(String key, NBTBase value) { - if (this.tag == null) + if (this.stackTagCompound == null) { - this.setTagCompound(new TagObject()); + this.setTagCompound(new NBTTagCompound()); } - this.tag.setObject(key, value); - } - - public void setTagInfo(String key, List value) - { - if (this.tag == null) - { - this.setTagCompound(new TagObject()); - } - - this.tag.setList(key, value); + this.stackTagCompound.setTag(key, value); } // public boolean canEditBlocks() @@ -1129,7 +1155,7 @@ public final class ItemStack */ public int getRepairCost() { - return this.hasTagCompound() && this.tag.hasInt("RepairCost") ? this.tag.getInt("RepairCost") : 0; + return this.hasTagCompound() && this.stackTagCompound.hasKey("RepairCost", 3) ? this.stackTagCompound.getInteger("RepairCost") : 0; } /** @@ -1138,32 +1164,62 @@ public final class ItemStack public void setRepairCost(int cost) { if(cost == 0) { - if(this.tag == null) { + if(this.stackTagCompound == null) { return; } - if(!this.tag.hasInt("RepairCost")) { + if(!this.stackTagCompound.hasKey("RepairCost", 3)) { return; } - this.tag.remove("RepairCost"); - if(this.tag.isEmpty()) { - this.tag = null; + this.stackTagCompound.removeTag("RepairCost"); + if(this.stackTagCompound.hasNoTags()) { + this.stackTagCompound = null; } return; } if (!this.hasTagCompound()) { - this.tag = new TagObject(); + this.stackTagCompound = new NBTTagCompound(); } - this.tag.setInt("RepairCost", cost); + this.stackTagCompound.setInteger("RepairCost", cost); } - public Map getAttributeModifiers(UsageSlot slot) { - Map map = Maps.newEnumMap(Attribute.class); - this.getItem().getModifiers(map, slot); - return map; - } + public Map> getAttributeModifiers(int type) + { + Map> multimap; + +// if ((type & 1) == 1 && this.hasTagCompound() && this.stackTagCompound.hasKey("AttributeModifiers", 9)) +// { +// multimap = HashMultimap.create(); +// NBTTagList nbttaglist = this.stackTagCompound.getTagList("AttributeModifiers", 10); +// +// for (int i = 0; i < nbttaglist.tagCount(); ++i) +// { +// NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); +// AttributeModifier attributemodifier = Attributes.readAttributeModifierFromNBT(nbttagcompound); +// +// if (attributemodifier != null && attributemodifier.getID() != 0L) +// { +// multimap.put(nbttagcompound.getString("AttributeName"), attributemodifier); +// } +// } +// } +// else + if((type & 1) == 1) + { + multimap = this.getItem().getItemAttributeModifiers(); + } + else { + multimap = Maps.newHashMap(); + } + + if((type & 2) == 2) { + multimap.putAll(this.getItem().getItemInventoryModifiers()); + } + + return multimap; + } public void setItem(Item newItem) { @@ -1180,7 +1236,7 @@ public final class ItemStack // { // this.canDestroyCacheBlock = blockIn; // -// if (this.hasTagCompound() && this.stackTagCompound.hasList("CanDestroy")) +// if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanDestroy", 9)) // { // NBTTagList nbttaglist = this.stackTagCompound.getTagList("CanDestroy", 8); // @@ -1211,7 +1267,7 @@ public final class ItemStack // { // this.canPlaceOnCacheBlock = blockIn; // -// if (this.hasTagCompound() && this.stackTagCompound.hasList("CanPlaceOn")) +// if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanPlaceOn", 9)) // { // NBTTagList nbttaglist = this.stackTagCompound.getTagList("CanPlaceOn", 8); // diff --git a/common/src/main/java/common/item/ItemStick.java b/common/src/common/item/ItemStick.java similarity index 100% rename from common/src/main/java/common/item/ItemStick.java rename to common/src/common/item/ItemStick.java diff --git a/common/src/main/java/common/item/ItemSword.java b/common/src/common/item/ItemSword.java similarity index 82% rename from common/src/main/java/common/item/ItemSword.java rename to common/src/common/item/ItemSword.java index 2a741fa..67840f0 100755 --- a/common/src/main/java/common/item/ItemSword.java +++ b/common/src/common/item/ItemSword.java @@ -1,11 +1,18 @@ package common.item; +import java.util.Map; +import java.util.Set; + +import common.attributes.Attribute; +import common.attributes.AttributeModifier; +import common.attributes.Attributes; import common.block.Block; -import common.block.Material; +import common.collect.Sets; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; import common.init.ToolMaterial; +import common.material.Material; import common.model.Transforms; import common.util.BlockPos; import common.world.World; @@ -20,7 +27,7 @@ public class ItemSword extends Item this.material = material; this.maxStackSize = 1; this.setMaxDamage(material.getDurability()); - this.setTab(CheatTab.COMBAT); + this.setTab(CheatTab.tabCombat); this.attackDamage = 4 + material.getDamage(); } @@ -46,7 +53,7 @@ public class ItemSword extends Item else { Material material = state.getMaterial(); - return material != Material.PLANT && material != Material.BUSH && material != Material.LEAVES && material != Material.SOFT ? 1.0F : 1.5F; + return material != Material.plants && material != Material.vine && material != Material.coral && material != Material.leaves && material != Material.gourd ? 1.0F : 1.5F; } } @@ -137,9 +144,12 @@ public class ItemSword extends Item { return this.material.isRepairItem(repair.getItem()) ? true : super.getIsRepairable(toRepair, repair); } - - public int getAttackDamageBonus() { - return this.attackDamage; + + public Map> getItemAttributeModifiers() + { + Map> multimap = super.getItemAttributeModifiers(); + multimap.put(Attributes.ATTACK_DAMAGE, Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID, "Weapon modifier", this.attackDamage, false))); + return multimap; } // public boolean canBreakBlocks() { diff --git a/common/src/main/java/common/item/ItemTNT.java b/common/src/common/item/ItemTNT.java similarity index 100% rename from common/src/main/java/common/item/ItemTNT.java rename to common/src/common/item/ItemTNT.java diff --git a/common/src/main/java/common/item/ItemTiny.java b/common/src/common/item/ItemTiny.java similarity index 100% rename from common/src/main/java/common/item/ItemTiny.java rename to common/src/common/item/ItemTiny.java diff --git a/common/src/common/item/ItemTool.java b/common/src/common/item/ItemTool.java new file mode 100755 index 0000000..2e2f8b6 --- /dev/null +++ b/common/src/common/item/ItemTool.java @@ -0,0 +1,126 @@ +package common.item; + +import java.util.Map; +import java.util.Set; + +import common.attributes.Attribute; +import common.attributes.AttributeModifier; +import common.attributes.Attributes; +import common.block.Block; +import common.collect.Sets; +import common.entity.types.EntityLiving; +import common.init.ToolMaterial; +import common.model.Transforms; +import common.util.BlockPos; +import common.world.World; + +public abstract class ItemTool extends Item +{ +// private Set effectiveBlocks; + protected float efficiencyOnProperMaterial = 4.0F; + + /** Damage versus entities. */ + private int damageVsEntity; + + /** The material this tool is made from. */ + protected ToolMaterial toolMaterial; + + public ItemTool(int attackDamage, ToolMaterial material) + { + this.toolMaterial = material; +// this.effectiveBlocks = effectiveBlocks; + this.maxStackSize = 1; + this.setMaxDamage(material.getDurability()); + this.efficiencyOnProperMaterial = material.getEfficiency(); + this.damageVsEntity = attackDamage + material.getDamage(); + this.setTab(CheatTab.tabTools); + } + + public abstract boolean canUseOn(ItemStack stack, Block state); + + public float getStrVsBlock(ItemStack stack, Block state) { + return !this.canUseOn(stack, state) ? 1.0F : this.efficiencyOnProperMaterial; + } +// { +// return this.effectiveBlocks.contains(state) ? this.efficiencyOnProperMaterial : 1.0F; +// } + + /** + * Current implementations of this method in child classes do not use the entry argument beside ev. They just raise + * the damage on the stack. + */ + public boolean hitEntity(ItemStack stack, EntityLiving target, EntityLiving attacker) + { + stack.damageItem(2, attacker); + return true; + } + + /** + * Called when a Block is destroyed using this Item. Return true to trigger the "Use Item" statistic. + */ + public boolean onBlockDestroyed(ItemStack stack, World worldIn, Block blockIn, BlockPos pos, EntityLiving playerIn) + { + if ((double)blockIn.getBlockHardness(worldIn, pos) != 0.0D) + { + stack.damageItem(1, playerIn); + } + + return true; + } + +// /** +// * Returns True is the item is renderer in full 3D when hold. +// */ +// public boolean isFull3D() +// { +// return true; +// } + + public ToolMaterial getToolMaterial() + { + return this.toolMaterial; + } + + /** + * Return the enchantability factor of the item, most of the time is based on material. + */ + public int getItemEnchantability() + { + return this.toolMaterial.getEnchantability(); + } + +// /** +// * Return the name for this tool's material. +// */ +// public String getToolMaterialName() +// { +// return this.toolMaterial.toString(); +// } + + /** + * Return whether this item is repairable in an anvil. + */ + public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) + { + return this.toolMaterial.isRepairItem(repair.getItem()) ? true : super.getIsRepairable(toRepair, repair); + } + + public Map> getItemAttributeModifiers() + { + Map> multimap = super.getItemAttributeModifiers(); + multimap.put(Attributes.ATTACK_DAMAGE, Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID, "Tool modifier", this.damageVsEntity, false))); + return multimap; + } + + public boolean isMagnetic() { + return this.toolMaterial.isMagnetic(); + } + + public Transforms getTransform() { + return Transforms.TOOL; + } + + public boolean canBeWielded() { + return true; + } +} diff --git a/common/src/main/java/common/item/ItemWall.java b/common/src/common/item/ItemWall.java similarity index 91% rename from common/src/main/java/common/item/ItemWall.java rename to common/src/common/item/ItemWall.java index 9e138fd..0579baa 100755 --- a/common/src/main/java/common/item/ItemWall.java +++ b/common/src/common/item/ItemWall.java @@ -3,7 +3,7 @@ package common.item; import java.util.function.Function; import common.block.Block; -import common.block.artificial.BlockWall; +import common.block.BlockWall; import common.model.Model; import common.model.ModelProvider; @@ -14,7 +14,7 @@ public class ItemWall extends ItemMultiTexture { public Model getModel(ModelProvider provider, String name, int meta) { return provider.getModel( - provider.getModel(this.block.getStateFromMeta(this.getMetadata(meta)).getValue(BlockWall.VARIANT).getName()) + provider.getModel(this.block.getStateFromMeta(this.getMetadata(meta)).getValue(BlockWall.VARIANT).getName()).noOcclude() .add(4, 0, 4, 12, 16, 12) .d().uv(4, 4, 12, 12) .u().uv(4, 4, 12, 12).noCull() diff --git a/common/src/main/java/common/item/ItemWand.java b/common/src/common/item/ItemWand.java similarity index 98% rename from common/src/main/java/common/item/ItemWand.java rename to common/src/common/item/ItemWand.java index f0a494d..8b69b69 100755 --- a/common/src/main/java/common/item/ItemWand.java +++ b/common/src/common/item/ItemWand.java @@ -15,7 +15,7 @@ import common.world.AWorldServer; public abstract class ItemWand extends Item { public ItemWand() { this.maxStackSize = 1; - this.setTab(CheatTab.TOOLS); + this.setTab(CheatTab.tabTools); } // public boolean canBreakBlocks() { diff --git a/common/src/main/java/common/item/ItemWeatherToken.java b/common/src/common/item/ItemWeatherToken.java similarity index 97% rename from common/src/main/java/common/item/ItemWeatherToken.java rename to common/src/common/item/ItemWeatherToken.java index bff9568..ccb48e4 100755 --- a/common/src/main/java/common/item/ItemWeatherToken.java +++ b/common/src/common/item/ItemWeatherToken.java @@ -20,7 +20,7 @@ public class ItemWeatherToken extends ItemMagnetic { { if(worldIn.dimension.getType().weather) { // if (!playerIn.creative) - --itemStackIn.size; + --itemStackIn.stackSize; worldIn.playSoundAtEntity(playerIn, SoundEvent.SPELL, 0.5F); if (!worldIn.client) { diff --git a/common/src/main/java/common/item/RngLoot.java b/common/src/common/item/RngLoot.java similarity index 91% rename from common/src/main/java/common/item/RngLoot.java rename to common/src/common/item/RngLoot.java index b8c9c4e..8c59985 100755 --- a/common/src/main/java/common/item/RngLoot.java +++ b/common/src/common/item/RngLoot.java @@ -34,7 +34,7 @@ public class RngLoot extends RngItem if(this.item == null) return null; ItemStack stack = this.item.copy(); - stack.size = this.minStackSize + rand.zrange(this.maxStackSize - this.minStackSize + 1); + stack.stackSize = this.minStackSize + rand.zrange(this.maxStackSize - this.minStackSize + 1); return stack; } @@ -48,7 +48,7 @@ public class RngLoot extends RngItem if (loot.item.getMaxStackSize() >= j) { ItemStack itemstack1 = loot.item.copy(); - itemstack1.size = j; + itemstack1.stackSize = j; inv.setInventorySlotContents(random.zrange(inv.getSizeInventory()), itemstack1); } else @@ -56,7 +56,7 @@ public class RngLoot extends RngItem for (int k = 0; k < j; ++k) { ItemStack itemstack = loot.item.copy(); - itemstack.size = 1; + itemstack.stackSize = 1; inv.setInventorySlotContents(random.zrange(inv.getSizeInventory()), itemstack); } } @@ -73,7 +73,7 @@ public class RngLoot extends RngItem if (loot.item.getMaxStackSize() >= j) { ItemStack itemstack1 = loot.item.copy(); - itemstack1.size = j; + itemstack1.stackSize = j; dispenser.setInventorySlotContents(random.zrange(dispenser.getSizeInventory()), itemstack1); } else @@ -81,7 +81,7 @@ public class RngLoot extends RngItem for (int k = 0; k < j; ++k) { ItemStack itemstack = loot.item.copy(); - itemstack.size = 1; + itemstack.stackSize = 1; dispenser.setInventorySlotContents(random.zrange(dispenser.getSizeInventory()), itemstack); } } diff --git a/common/src/main/java/common/log/Log.java b/common/src/common/log/Log.java similarity index 97% rename from common/src/main/java/common/log/Log.java rename to common/src/common/log/Log.java index ea68b87..04aa56c 100644 --- a/common/src/main/java/common/log/Log.java +++ b/common/src/common/log/Log.java @@ -17,7 +17,8 @@ public enum Log { CONSOLE("Console"), TICK("Tick"), SOUND("Sound"), - NETWORK("Network"); + JNI("JNI"), + NETTY("Netty"); private static class LogMessage { private final LogLevel level; @@ -112,13 +113,9 @@ public enum Log { return time > 0 ? String.format("%dD+%02d:%02d:%02d", time, hrs, mins, secs) : String.format("%02d:%02d:%02d", hrs, mins, secs); } - public static void init() { - Log.colors = System.getProperty("log.nocolor") == null && !Util.WINDOWS; - Log.level = LogLevel.parse(System.getProperty("log.level", LogLevel.INFO.id)); - } - - public static void setSync(IThreadListener sync) { + public static void init(IThreadListener sync) { Log.sync = sync; + Log.colors = System.getProperty("log.nocolor") == null && !Util.WINDOWS; } public static void flushLog() { diff --git a/common/src/main/java/common/log/LogLevel.java b/common/src/common/log/LogLevel.java similarity index 74% rename from common/src/main/java/common/log/LogLevel.java rename to common/src/common/log/LogLevel.java index e436d04..c16ba5a 100644 --- a/common/src/main/java/common/log/LogLevel.java +++ b/common/src/common/log/LogLevel.java @@ -2,7 +2,6 @@ package common.log; import common.color.TextColor; import common.util.Displayable; -import common.util.ExtMath; import common.util.Identifyable; public enum LogLevel implements Displayable, Identifyable { @@ -20,19 +19,6 @@ public enum LogLevel implements Displayable, Identifyable { public final String log; public final TextColor color; - public static LogLevel parse(String str) { - for(LogLevel level : values()) { - if(level.id.equalsIgnoreCase(str)) - return level; - } - try { - return values()[ExtMath.clampi(Integer.parseUnsignedInt(str), 0, values().length - 1)]; - } - catch(NumberFormatException e) { - return INFO; - } - } - private LogLevel(String id, String name, String log, TextColor color) { this.id = id; this.name = name; diff --git a/common/src/common/log/Message.java b/common/src/common/log/Message.java new file mode 100644 index 0000000..939962d --- /dev/null +++ b/common/src/common/log/Message.java @@ -0,0 +1,11 @@ +package common.log; + +public class Message { + public final String message; + public final long time; + + public Message(String message, long time) { + this.message = message; + this.time = time; + } +} diff --git a/common/src/common/log/NettyLogger.java b/common/src/common/log/NettyLogger.java new file mode 100644 index 0000000..8371653 --- /dev/null +++ b/common/src/common/log/NettyLogger.java @@ -0,0 +1,170 @@ +package common.log; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import io.netty.util.internal.logging.AbstractInternalLogger; +import io.netty.util.internal.logging.FormattingTuple; +import io.netty.util.internal.logging.InternalLogger; +import io.netty.util.internal.logging.InternalLoggerFactory; +import io.netty.util.internal.logging.MessageFormatter; + +public class NettyLogger extends AbstractInternalLogger { + public static void init() { + InternalLoggerFactory.setDefaultFactory(new InternalLoggerFactory() { + protected InternalLogger newInstance(String name) { + return new NettyLogger(name); + } + }); + } + + private NettyLogger(String name) { + super(name); + } + + public boolean isTraceEnabled() { + return Log.getLevel().ordinal() >= LogLevel.TRACE.ordinal(); + } + + public void trace(String msg) { + this.log(LogLevel.TRACE, msg, null); + } + + public void trace(String format, Object arg) { + FormattingTuple ft = MessageFormatter.format(format, arg); + this.log(LogLevel.TRACE, ft.getMessage(), ft.getThrowable()); + } + + public void trace(String format, Object argA, Object argB) { + FormattingTuple ft = MessageFormatter.format(format, argA, argB); + this.log(LogLevel.TRACE, ft.getMessage(), ft.getThrowable()); + } + + public void trace(String format, Object... argArray) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + this.log(LogLevel.TRACE, ft.getMessage(), ft.getThrowable()); + } + + public void trace(String msg, Throwable t) { + this.log(LogLevel.TRACE, msg, t); + } + + public boolean isDebugEnabled() { + return Log.getLevel().ordinal() >= LogLevel.DEBUG.ordinal(); + } + + public void debug(String msg) { + this.log(LogLevel.DEBUG, msg, null); + } + + public void debug(String format, Object arg) { + FormattingTuple ft = MessageFormatter.format(format, arg); + this.log(LogLevel.DEBUG, ft.getMessage(), ft.getThrowable()); + } + + public void debug(String format, Object argA, Object argB) { + FormattingTuple ft = MessageFormatter.format(format, argA, argB); + this.log(LogLevel.DEBUG, ft.getMessage(), ft.getThrowable()); + } + + public void debug(String format, Object... argArray) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + this.log(LogLevel.DEBUG, ft.getMessage(), ft.getThrowable()); + } + + public void debug(String msg, Throwable t) { + this.log(LogLevel.DEBUG, msg, t); + } + + public boolean isInfoEnabled() { + return Log.getLevel().ordinal() >= LogLevel.INFO.ordinal(); + } + + public void info(String msg) { + this.log(LogLevel.INFO, msg, null); + } + + public void info(String format, Object arg) { + FormattingTuple ft = MessageFormatter.format(format, arg); + this.log(LogLevel.INFO, ft.getMessage(), ft.getThrowable()); + } + + public void info(String format, Object argA, Object argB) { + FormattingTuple ft = MessageFormatter.format(format, argA, argB); + this.log(LogLevel.INFO, ft.getMessage(), ft.getThrowable()); + } + + public void info(String format, Object... argArray) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + this.log(LogLevel.INFO, ft.getMessage(), ft.getThrowable()); + } + + public void info(String msg, Throwable t) { + this.log(LogLevel.INFO, msg, t); + } + + public boolean isWarnEnabled() { + return Log.getLevel().ordinal() >= LogLevel.WARN.ordinal(); + } + + public void warn(String msg) { + this.log(LogLevel.WARN, msg, null); + } + + public void warn(String format, Object arg) { + FormattingTuple ft = MessageFormatter.format(format, arg); + this.log(LogLevel.WARN, ft.getMessage(), ft.getThrowable()); + } + + public void warn(String format, Object argA, Object argB) { + FormattingTuple ft = MessageFormatter.format(format, argA, argB); + this.log(LogLevel.WARN, ft.getMessage(), ft.getThrowable()); + } + + public void warn(String format, Object... argArray) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + this.log(LogLevel.WARN, ft.getMessage(), ft.getThrowable()); + } + + public void warn(String msg, Throwable t) { + this.log(LogLevel.WARN, msg, t); + } + + public boolean isErrorEnabled() { + return Log.getLevel().ordinal() >= LogLevel.ERROR.ordinal(); + } + + public void error(String msg) { + this.log(LogLevel.ERROR, msg, null); + } + + public void error(String format, Object arg) { + FormattingTuple ft = MessageFormatter.format(format, arg); + this.log(LogLevel.ERROR, ft.getMessage(), ft.getThrowable()); + } + + public void error(String format, Object argA, Object argB) { + FormattingTuple ft = MessageFormatter.format(format, argA, argB); + this.log(LogLevel.ERROR, ft.getMessage(), ft.getThrowable()); + } + + public void error(String format, Object... arguments) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); + this.log(LogLevel.ERROR, ft.getMessage(), ft.getThrowable()); + } + + public void error(String msg, Throwable t) { + this.log(LogLevel.ERROR, msg, t); + } + + private void log(LogLevel level, String msg, Throwable t) { + Log.NETTY.log(level, msg); + if(t != null) { + StringWriter sw = new StringWriter(); + PrintWriter st = new PrintWriter(sw); + t.printStackTrace(st); + sw.flush(); + Log.NETTY.log(level, sw.toString().trim().replace('\t', ' ')); + } + } +} diff --git a/common/src/common/material/Material.java b/common/src/common/material/Material.java new file mode 100755 index 0000000..c71b80c --- /dev/null +++ b/common/src/common/material/Material.java @@ -0,0 +1,235 @@ +package common.material; + +public class Material +{ + public static final Material air = new MaterialTransparent(); + public static final Material grass = new Material(); + public static final Material ground = new Material(); + public static final Material wood = (new Material()).setBurning(); + public static final Material rock = (new Material()).setRequiresTool(); + public static final Material iron = (new Material()).setRequiresTool(); + public static final Material anvil = (new Material()).setRequiresTool().setImmovableMobility(); + public static final Material water = (new MaterialColdFluid()).setNoPushMobility(); + public static final Material coldFluid = (new MaterialColdFluid()).setNoPushMobility(); + public static final Material lava = (new MaterialHotFluid()).setNoPushMobility(); + public static final Material hotFluid = (new MaterialHotFluid()).setNoPushMobility(); + public static final Material leaves = (new Material()).setBurning().setTranslucent().setNoPushMobility(); + public static final Material plants = (new MaterialLogic()).setNoPushMobility(); + public static final Material vine = (new MaterialLogic()).setBurning().setNoPushMobility().setReplaceable(); + public static final Material sponge = new Material(); + public static final Material cloth = (new Material()).setBurning(); + public static final Material fire = (new MaterialTransparent()).setNoPushMobility(); + public static final Material sand = new Material(); + public static final Material circuits = (new MaterialLogic()).setNoPushMobility(); + public static final Material carpet = (new MaterialLogic()).setBurning(); + public static final Material glass = (new Material()).setTranslucent(); // .setAdventureModeExempt(); + public static final Material redstoneLight = (new Material()); // .setAdventureModeExempt(); + public static final Material tnt = (new Material()).setBurning().setTranslucent(); + public static final Material coral = (new Material()).setNoPushMobility(); + public static final Material ice = (new Material()).setTranslucent(); // .setAdventureModeExempt(); + public static final Material packedIce = (new Material()); // .setAdventureModeExempt(); + public static final Material snow = (new MaterialLogic()).setReplaceable().setTranslucent().setRequiresTool().setNoPushMobility(); + + /** The material for crafted snow. */ + public static final Material craftedSnow = (new Material()).setRequiresTool(); + public static final Material cactus = (new Material()).setTranslucent().setNoPushMobility(); + public static final Material clay = new Material(); + public static final Material gourd = (new Material()).setNoPushMobility(); + public static final Material dragonEgg = (new Material()).setNoPushMobility(); + public static final Material portal = (new MaterialPortal()).setImmovableMobility(); + public static final Material cake = (new Material()).setNoPushMobility(); + public static final Material web = (new Material() + { + public boolean blocksMovement() + { + return false; + } + }).setRequiresTool().setNoPushMobility(); + + /** Pistons' material. */ + public static final Material piston = (new Material()).setImmovableMobility(); +// public static final Material barrier = (new Material()).setRequiresTool().setImmovableMobility(); + + /** Bool defining if the block can burn or not. */ + private boolean canBurn; + + /** + * Determines whether blocks with this material can be "overwritten" by other blocks when placed - eg snow, vines + * and tall grass. + */ + private boolean replaceable; + + /** Indicates if the material is translucent */ + private boolean isTranslucent; + +// /** The color index used to draw the blocks of this material on maps. */ +// private final MapColor materialMapColor; + + /** + * Determines if the material can be harvested without a tool (or with the wrong tool) + */ + private boolean requiresNoTool = true; + + /** + * Mobility information flag. 0 indicates that this block is normal, 1 indicates that it can't push other blocks, 2 + * indicates that it can't be pushed. + */ + private int mobilityFlag; +// private boolean isAdventureModeExempt; + +// public Material(MapColor color) +// { +//// this.materialMapColor = color; +// } + + /** + * Returns if blocks of these materials are liquids. + */ + public boolean isLiquid() + { + return false; + } + + public boolean isColdLiquid() + { + return false; + } + + public boolean isHotLiquid() + { + return false; + } + + /** + * Returns true if the block is a considered solid. This is true by default. + */ + public boolean isSolid() + { + return true; + } + + /** + * Will prevent grass from growing on dirt underneath and kill any grass below it if it returns true + */ + public boolean blocksLight() + { + return true; + } + + /** + * Returns if this material is considered solid or not + */ + public boolean blocksMovement() + { + return true; + } + + /** + * Marks the material as translucent + */ + private Material setTranslucent() + { + this.isTranslucent = true; + return this; + } + + /** + * Makes blocks with this material require the correct tool to be harvested. + */ + protected Material setRequiresTool() + { + this.requiresNoTool = false; + return this; + } + + /** + * Set the canBurn bool to True and return the current object. + */ + protected Material setBurning() + { + this.canBurn = true; + return this; + } + + /** + * Returns if the block can burn or not. + */ + public boolean getCanBurn() + { + return this.canBurn; + } + + /** + * Sets {@link #replaceable} to true. + */ + public Material setReplaceable() + { + this.replaceable = true; + return this; + } + + /** + * Returns whether the material can be replaced by other blocks when placed - eg snow, vines and tall grass. + */ + public boolean isReplaceable() + { + return this.replaceable; + } + + /** + * Indicate if the material is opaque + */ + public boolean isOpaque() + { + return this.isTranslucent ? false : this.blocksMovement(); + } + + /** + * Returns true if the material can be harvested without a tool (or with the wrong tool) + */ + public boolean isToolNotRequired() + { + return this.requiresNoTool; + } + + /** + * Returns the mobility information of the material, 0 = free, 1 = can't push but can move over, 2 = total + * immobility and stop pistons. + */ + public int getMaterialMobility() + { + return this.mobilityFlag; + } + + /** + * This type of material can't be pushed, but pistons can move over it. + */ + protected Material setNoPushMobility() + { + this.mobilityFlag = 1; + return this; + } + + /** + * This type of material can't be pushed, and pistons are blocked to move. + */ + protected Material setImmovableMobility() + { + this.mobilityFlag = 2; + return this; + } + +// protected Material setAdventureModeExempt() +// { +// this.isAdventureModeExempt = true; +// return this; +// } + +// /** +// * Retrieves the color index of the block. This is is the same color used by vanilla maps to represent this block. +// */ +// public MapColor getMaterialMapColor() +// { +// return this.materialMapColor; +// } +} diff --git a/common/src/common/material/MaterialColdFluid.java b/common/src/common/material/MaterialColdFluid.java new file mode 100755 index 0000000..9187ad2 --- /dev/null +++ b/common/src/common/material/MaterialColdFluid.java @@ -0,0 +1,24 @@ +package common.material; + +public class MaterialColdFluid extends Material { + public MaterialColdFluid() { + this.setReplaceable(); + this.setNoPushMobility(); + } + + public boolean isLiquid() { + return true; + } + + public boolean isColdLiquid() { + return true; + } + + public boolean blocksMovement() { + return false; + } + + public boolean isSolid() { + return false; + } +} diff --git a/common/src/common/material/MaterialHotFluid.java b/common/src/common/material/MaterialHotFluid.java new file mode 100755 index 0000000..03b6ca1 --- /dev/null +++ b/common/src/common/material/MaterialHotFluid.java @@ -0,0 +1,24 @@ +package common.material; + +public class MaterialHotFluid extends Material { + public MaterialHotFluid() { + this.setReplaceable(); + this.setNoPushMobility(); + } + + public boolean isLiquid() { + return true; + } + + public boolean isHotLiquid() { + return true; + } + + public boolean blocksMovement() { + return false; + } + + public boolean isSolid() { + return false; + } +} diff --git a/common/src/common/material/MaterialLogic.java b/common/src/common/material/MaterialLogic.java new file mode 100755 index 0000000..137eb9a --- /dev/null +++ b/common/src/common/material/MaterialLogic.java @@ -0,0 +1,28 @@ +package common.material; + +public class MaterialLogic extends Material +{ + /** + * Returns true if the block is a considered solid. This is true by default. + */ + public boolean isSolid() + { + return false; + } + + /** + * Will prevent grass from growing on dirt underneath and kill any grass below it if it returns true + */ + public boolean blocksLight() + { + return false; + } + + /** + * Returns if this material is considered solid or not + */ + public boolean blocksMovement() + { + return false; + } +} diff --git a/common/src/common/material/MaterialPortal.java b/common/src/common/material/MaterialPortal.java new file mode 100755 index 0000000..778d739 --- /dev/null +++ b/common/src/common/material/MaterialPortal.java @@ -0,0 +1,28 @@ +package common.material; + +public class MaterialPortal extends Material +{ + /** + * Returns true if the block is a considered solid. This is true by default. + */ + public boolean isSolid() + { + return false; + } + + /** + * Will prevent grass from growing on dirt underneath and kill any grass below it if it returns true + */ + public boolean blocksLight() + { + return false; + } + + /** + * Returns if this material is considered solid or not + */ + public boolean blocksMovement() + { + return false; + } +} diff --git a/common/src/common/material/MaterialTransparent.java b/common/src/common/material/MaterialTransparent.java new file mode 100755 index 0000000..82af6d1 --- /dev/null +++ b/common/src/common/material/MaterialTransparent.java @@ -0,0 +1,33 @@ +package common.material; + +public class MaterialTransparent extends Material +{ + public MaterialTransparent() + { + this.setReplaceable(); + } + + /** + * Returns true if the block is a considered solid. This is true by default. + */ + public boolean isSolid() + { + return false; + } + + /** + * Will prevent grass from growing on dirt underneath and kill any grass below it if it returns true + */ + public boolean blocksLight() + { + return false; + } + + /** + * Returns if this material is considered solid or not + */ + public boolean blocksMovement() + { + return false; + } +} diff --git a/common/src/common/model/BlockLayer.java b/common/src/common/model/BlockLayer.java new file mode 100755 index 0000000..ec9f03a --- /dev/null +++ b/common/src/common/model/BlockLayer.java @@ -0,0 +1,21 @@ +package common.model; + +public enum BlockLayer +{ + SOLID("Solid"), + CUTOUT_MIPPED("Mipped Cutout"), + CUTOUT("Cutout"), + TRANSLUCENT("Translucent"); + + private final String layerName; + + private BlockLayer(String layerNameIn) + { + this.layerName = layerNameIn; + } + + public String toString() + { + return this.layerName; + } +} diff --git a/common/src/main/java/common/model/ItemMeshDefinition.java b/common/src/common/model/ItemMeshDefinition.java similarity index 72% rename from common/src/main/java/common/model/ItemMeshDefinition.java rename to common/src/common/model/ItemMeshDefinition.java index 354f27f..cd7942e 100755 --- a/common/src/main/java/common/model/ItemMeshDefinition.java +++ b/common/src/common/model/ItemMeshDefinition.java @@ -2,6 +2,7 @@ package common.model; import common.item.ItemStack; -public interface ItemMeshDefinition { +public interface ItemMeshDefinition +{ String getModelLocation(ItemStack stack); } diff --git a/common/src/main/java/common/model/Model.java b/common/src/common/model/Model.java similarity index 98% rename from common/src/main/java/common/model/Model.java rename to common/src/common/model/Model.java index ba446c8..8affcad 100644 --- a/common/src/main/java/common/model/Model.java +++ b/common/src/common/model/Model.java @@ -3,6 +3,7 @@ package common.model; import common.util.Facing; public abstract class Model { + public abstract Model noOcclude(); public abstract Model uvLock(); public abstract Model rotate(ModelRotation rot); public abstract Model add(float x1, float y1, float z1, float x2, float y2, float z2); @@ -41,7 +42,7 @@ public abstract class Model { } public Model cross() { - return this + return this.noOcclude() .add(0.8f, 0f, 8f, 15.2f, 16f, 8f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) .ns().uv(0, 0, 16, 16).noCull() .add(8f, 0f, 0.8f, 8f, 16f, 15.2f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) @@ -49,7 +50,7 @@ public abstract class Model { } public Model crossTint() { - return this + return this.noOcclude() .add(0.8f, 0f, 8f, 15.2f, 16f, 8f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) .ns().uv(0, 0, 16, 16).noCull().tint() .add(8f, 0f, 0.8f, 8f, 16f, 15.2f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) diff --git a/common/src/main/java/common/model/ModelProvider.java b/common/src/common/model/ModelProvider.java similarity index 97% rename from common/src/main/java/common/model/ModelProvider.java rename to common/src/common/model/ModelProvider.java index 4cf3877..f4cb0bf 100644 --- a/common/src/main/java/common/model/ModelProvider.java +++ b/common/src/common/model/ModelProvider.java @@ -10,6 +10,10 @@ public interface ModelProvider { Model getEntityModel(); public static class DummyModel extends Model { + public Model noOcclude() { + return this; + } + public Model uvLock() { return this; } diff --git a/common/src/main/java/common/model/ModelRotation.java b/common/src/common/model/ModelRotation.java similarity index 100% rename from common/src/main/java/common/model/ModelRotation.java rename to common/src/common/model/ModelRotation.java diff --git a/common/src/main/java/common/model/ParticleType.java b/common/src/common/model/ParticleType.java similarity index 100% rename from common/src/main/java/common/model/ParticleType.java rename to common/src/common/model/ParticleType.java diff --git a/common/src/common/model/Transform.java b/common/src/common/model/Transform.java new file mode 100755 index 0000000..4bb0994 --- /dev/null +++ b/common/src/common/model/Transform.java @@ -0,0 +1,37 @@ +package common.model; + +import common.util.Vector3f; + +public class Transform { + public static final Transform IDENTITY = new Transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); + + public final Vector3f rotation; + public final Vector3f translation; + public final Vector3f scale; + + public Transform(float rx, float ry, float rz, float tx, float ty, float tz, float sx, float sy, float sz) { + this.rotation = new Vector3f(rx, ry, rz); + this.translation = (Vector3f)new Vector3f(tx, ty, tz).scale(0.0625F); + this.scale = new Vector3f(sx, sy, sz); + } + + public boolean equals(Object obj) { + if(this == obj) { + return true; + } + else if(this.getClass() != obj.getClass()) { + return false; + } + else { + Transform other = (Transform)obj; + return this.rotation.equals(other.rotation) && this.scale.equals(other.scale) && this.translation.equals(other.translation); + } + } + + public int hashCode() { + int i = this.rotation.hashCode(); + i = 31 * i + this.translation.hashCode(); + i = 31 * i + this.scale.hashCode(); + return i; + } +} diff --git a/common/src/common/model/Transforms.java b/common/src/common/model/Transforms.java new file mode 100755 index 0000000..6333c89 --- /dev/null +++ b/common/src/common/model/Transforms.java @@ -0,0 +1,165 @@ +package common.model; + +public enum Transforms { + DEFAULT( + Transform.IDENTITY, + Transform.IDENTITY, + Transform.IDENTITY, + Transform.IDENTITY + ), + ANVIL( + new Transform(10.0f, -45.0f, 170.0f, 0.25f, 1.5f, -2.5f, 0.375f, 0.375f, 0.375f), + Transform.IDENTITY, + Transform.IDENTITY, + Transform.IDENTITY + ), + BLOCK( + new Transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f, 0.375f, 0.375f), + Transform.IDENTITY, + Transform.IDENTITY, + Transform.IDENTITY + ), + ITEM( + new Transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -3.0f, 0.55f, 0.55f, 0.55f), + new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + TOOL_FLIP( + new Transform(180.0f, 90.0f, -35.0f, 0.0f, 0.0f, -3.5f, 0.85f, 0.85f, 0.85f), + new Transform(0.0f, 45.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + TOOL( + new Transform(0.0f, 90.0f, -35.0f, 0.0f, 1.25f, -3.5f, 0.85f, 0.85f, 0.85f), + new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + OFFSET2( + new Transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.25f, 0.55f, 0.55f, 0.55f), + new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + LAYER( + new Transform(10.0f, -45.0f, 170.0f, 0.0f, 0.25f, -2.75f, 0.375f, 0.375f, 0.375f), + new Transform(0.0f, 0.0f, 0.0f, 0.0f, 5.25f, 0.0f, 1.0f, 1.0f, 1.0f), + Transform.IDENTITY, + Transform.IDENTITY + ), + DICE( + new Transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -1.75f, 0.15f, 0.15f, 0.15f), + new Transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.4f, 0.4f, 0.4f), + new Transform(135.0f, -55.0f, 180.0f, 0.0f, 0.0f, 0.0f, 1.1f, 1.1f, 1.1f), + new Transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.4f, 0.4f, 0.4f) + ), + STAIRS( + new Transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f, 0.375f, 0.375f), + Transform.IDENTITY, + new Transform(0.0f, 180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f), + Transform.IDENTITY + ), + OFFSET1( + new Transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.5f, 0.55f, 0.55f, 0.55f), + new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + GATE( + new Transform(0.0f, -90.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f, 0.375f, 0.375f), + new Transform(0.0f, 90.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f), + Transform.IDENTITY, + Transform.IDENTITY + ), + NUGGET( + new Transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.0f, 0.55f, 0.55f, 0.55f), + new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + SKULL( + new Transform(180.0f, -45.0f, 0.0f, 0.0f, 1.0f, -2.5f, 0.25f, 0.25f, 0.25f), + new Transform(0.0f, -180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.55f, 0.55f, 0.55f), + new Transform(0.0f, 180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.7f, 0.7f, 0.7f), + Transform.IDENTITY + ), + BUTTON( + new Transform(10.0f, -45.0f, 170.0f, 0.0f, 1.0f, -1.75f, 0.375f, 0.375f, 0.375f), + Transform.IDENTITY, + Transform.IDENTITY, + Transform.IDENTITY + ), + RANGED( + new Transform(5.0f, 80.0f, -45.0f, 0.75f, 0.0f, 0.25f, 1.0f, 1.0f, 1.0f), + new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + BANNER( + new Transform(0.0f, 90.0f, -90.0f, 0.0f, 0.0f, -4.0f, 0.5f, 0.5f, 0.5f), + new Transform(0.0f, 225.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f), + new Transform(0.0f, -65.0f, 0.0f, 0.0f, -3.0f, 0.0f, 0.85f, 0.85f, 0.85f), + Transform.IDENTITY + ), + FENCE( + new Transform(0.0f, 0.0f, 180.0f, 0.0f, 1.5f, -2.75f, 0.375f, 0.375f, 0.375f), + Transform.IDENTITY, + new Transform(0.0f, 90.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f), + Transform.IDENTITY + ), + FLAT( + new Transform(10.0f, -45.0f, 170.0f, 0.0f, 0.25f, -2.75f, 0.375f, 0.375f, 0.375f), + new Transform(0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 0.0f, 1.0f, 1.0f, 1.0f), + Transform.IDENTITY, + Transform.IDENTITY + ), + ROD( + new Transform(0.0f, 90.0f, -35.0f, 0.0f, 0.75f, -3.5f, 0.85f, 0.85f, 0.85f), + new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + KEY( + new Transform(0.0f, 270.0f, -35.0f, 0.0f, 1.25f, -3.5f, 0.85f, 0.85f, 0.85f), + new Transform(180.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ); + + public static enum Camera { + NONE, + THIRD_PERSON, + FIRST_PERSON, + GUI, + GROUND; + } + + public final Transform third; + public final Transform first; + public final Transform gui; + public final Transform ground; + + private Transforms(Transform third, Transform first, Transform gui, Transform ground) { + this.third = third; + this.first = first; + this.gui = gui; + this.ground = ground; + } + + public Transform get(Camera type) { + switch(type) { + case THIRD_PERSON: + return this.third; + case FIRST_PERSON: + return this.first; + case GUI: + return this.gui; + case GROUND: + return this.ground; + default: + return Transform.IDENTITY; + } + } +} diff --git a/common/src/common/nbt/NBTBase.java b/common/src/common/nbt/NBTBase.java new file mode 100755 index 0000000..4fe8be1 --- /dev/null +++ b/common/src/common/nbt/NBTBase.java @@ -0,0 +1,123 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public abstract class NBTBase +{ + public static final String[] NBT_TYPES = new String[] {"END", "BYTE", "SHORT", "INT", "LONG", "FLOAT", "DOUBLE", "BYTE[]", "STRING", "LIST", "COMPOUND", "INT[]"}; + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + abstract void write(DataOutput output) throws IOException; + + abstract void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException; + + public abstract String toString(); + + /** + * Gets the type byte for the tag. + */ + public abstract byte getId(); + + /** + * Creates a new NBTBase object that corresponds with the passed in id. + */ + protected static NBTBase createNewByType(byte id) + { + switch (id) + { + case 0: + return new NBTTagEnd(); + + case 1: + return new NBTTagByte(); + + case 2: + return new NBTTagShort(); + + case 3: + return new NBTTagInt(); + + case 4: + return new NBTTagLong(); + + case 5: + return new NBTTagFloat(); + + case 6: + return new NBTTagDouble(); + + case 7: + return new NBTTagByteArray(); + + case 8: + return new NBTTagString(); + + case 9: + return new NBTTagList(); + + case 10: + return new NBTTagCompound(); + + case 11: + return new NBTTagIntArray(); + + default: + return null; + } + } + + /** + * Creates a clone of the tag. + */ + public abstract NBTBase copy(); + + /** + * Return whether this compound has no tags. + */ + public boolean hasNoTags() + { + return false; + } + + public boolean equals(Object p_equals_1_) + { + if (!(p_equals_1_ instanceof NBTBase)) + { + return false; + } + else + { + NBTBase nbtbase = (NBTBase)p_equals_1_; + return this.getId() == nbtbase.getId(); + } + } + + public int hashCode() + { + return this.getId(); + } + + protected String getString() + { + return this.toString(); + } + + public abstract static class NBTPrimitive extends NBTBase + { + public abstract long getLong(); + + public abstract int getInt(); + + public abstract short getShort(); + + public abstract byte getByte(); + + public abstract double getDouble(); + + public abstract float getFloat(); + } +} diff --git a/common/src/common/nbt/NBTException.java b/common/src/common/nbt/NBTException.java new file mode 100755 index 0000000..0290c39 --- /dev/null +++ b/common/src/common/nbt/NBTException.java @@ -0,0 +1,9 @@ +package common.nbt; + +public class NBTException extends Exception +{ + public NBTException(String p_i45136_1_) + { + super(p_i45136_1_); + } +} diff --git a/common/src/common/nbt/NBTLoader.java b/common/src/common/nbt/NBTLoader.java new file mode 100755 index 0000000..a1d0073 --- /dev/null +++ b/common/src/common/nbt/NBTLoader.java @@ -0,0 +1,148 @@ +package common.nbt; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInput; +import java.io.DataInputStream; +import java.io.DataOutput; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +public class NBTLoader { + public static NBTTagCompound readGZip(File file) throws IOException { + DataInputStream in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)))); + NBTTagCompound tag; + + try { + tag = read(in, NBTSizeTracker.INFINITE); + } + finally { + in.close(); + } + + return tag; + } + + public static void writeGZip(NBTTagCompound tag, File file) throws IOException { + DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(file)))); + + try { + write(tag, out); + } + finally { + out.close(); + } + } + +// public static void safeWrite(NBTTagCompound p_74793_0_, File p_74793_1_) throws IOException +// { +// File file1 = new File(p_74793_1_.getAbsolutePath() + "_tmp"); +// +// if (file1.exists()) +// { +// file1.delete(); +// } +// +// write(p_74793_0_, file1); +// +// if (p_74793_1_.exists()) +// { +// p_74793_1_.delete(); +// } +// +// if (p_74793_1_.exists()) +// { +// throw new IOException("Failed to delete " + p_74793_1_); +// } +// else +// { +// file1.renameTo(p_74793_1_); +// } +// } + +// public static void write(NBTTagCompound p_74795_0_, File p_74795_1_) throws IOException +// { +// DataOutputStream dataoutputstream = new DataOutputStream(new FileOutputStream(p_74795_1_)); +// +// try +// { +// write(p_74795_0_, dataoutputstream); +// } +// finally +// { +// dataoutputstream.close(); +// } +// } + +// public static NBTTagCompound read(File p_74797_0_) throws IOException +// { +// if (!p_74797_0_.exists()) +// { +// return null; +// } +// else +// { +// DataInputStream datainputstream = new DataInputStream(new FileInputStream(p_74797_0_)); +// NBTTagCompound nbttagcompound; +// +// try +// { +// nbttagcompound = read(datainputstream, NBTSizeTracker.INFINITE); +// } +// finally +// { +// datainputstream.close(); +// } +// +// return nbttagcompound; +// } +// } + + public static NBTTagCompound read(DataInputStream in) throws IOException { + return read(in, NBTSizeTracker.INFINITE); + } + + public static NBTTagCompound read(DataInput in, NBTSizeTracker tracker) throws IOException { + NBTBase tag = readType(in, 0, tracker); + + if(tag instanceof NBTTagCompound) { + return (NBTTagCompound)tag; + } + else { + throw new IOException("Root tag must be a named compound tag"); + } + } + + public static void write(NBTTagCompound tag, DataOutput out) throws IOException { + writeTag(tag, out); + } + + private static void writeTag(NBTBase tag, DataOutput out) throws IOException { + out.writeByte(tag.getId()); + + if(tag.getId() != 0) { + out.writeUTF(""); + tag.write(out); + } + } + + private static NBTBase readType(DataInput in, int depth, NBTSizeTracker tracker) throws IOException { + byte type = in.readByte(); + + if(type == 0) { + return new NBTTagEnd(); + } + else { + in.readUTF(); + NBTBase tag = NBTBase.createNewByType(type); + + tag.read(in, depth, tracker); + return tag; + } + } +} diff --git a/common/src/common/nbt/NBTParser.java b/common/src/common/nbt/NBTParser.java new file mode 100755 index 0000000..8bb650f --- /dev/null +++ b/common/src/common/nbt/NBTParser.java @@ -0,0 +1,549 @@ +package common.nbt; + +import java.util.Stack; +import java.util.regex.Pattern; + +import common.collect.Lists; + +public class NBTParser +{ + private static final Pattern PATTERN = Pattern.compile("\\[[-+\\d|,\\s]+\\]"); + + public static NBTTagCompound parseTag(String jsonString) throws NBTException + { + jsonString = jsonString.trim(); + + if (!jsonString.startsWith("{")) + { + throw new NBTException("Invalid tag encountered, expected \'{\' as first char."); + } + else if (func_150310_b(jsonString) != 1) + { + throw new NBTException("Encountered multiple top tags, only one expected"); + } + else + { + return (NBTTagCompound)func_150316_a("tag", jsonString).parse(); + } + } + + static int func_150310_b(String p_150310_0_) throws NBTException + { + int i = 0; + boolean flag = false; + Stack stack = new Stack(); + + for (int j = 0; j < p_150310_0_.length(); ++j) + { + char c0 = p_150310_0_.charAt(j); + + if (c0 == 34) + { + if (func_179271_b(p_150310_0_, j)) + { + if (!flag) + { + throw new NBTException("Illegal use of \\\": " + p_150310_0_); + } + } + else + { + flag = !flag; + } + } + else if (!flag) + { + if (c0 != 123 && c0 != 91) + { + if (c0 == 125 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 123)) + { + throw new NBTException("Unbalanced curly brackets {}: " + p_150310_0_); + } + + if (c0 == 93 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 91)) + { + throw new NBTException("Unbalanced square brackets []: " + p_150310_0_); + } + } + else + { + if (stack.isEmpty()) + { + ++i; + } + + stack.push(Character.valueOf(c0)); + } + } + } + + if (flag) + { + throw new NBTException("Unbalanced quotation: " + p_150310_0_); + } + else if (!stack.isEmpty()) + { + throw new NBTException("Unbalanced brackets: " + p_150310_0_); + } + else + { + if (i == 0 && !p_150310_0_.isEmpty()) + { + i = 1; + } + + return i; + } + } + +// static JsonToNBT.Any func_179272_a(String s1, String s2) throws NBTException +// { +// return func_150316_a(s1, s2); +// } + + static NBTParser.Any func_150316_a(String p_150316_0_, String p_150316_1_) throws NBTException + { + p_150316_1_ = p_150316_1_.trim(); + + if (p_150316_1_.startsWith("{")) + { + p_150316_1_ = p_150316_1_.substring(1, p_150316_1_.length() - 1); + NBTParser.Compound jsontonbt$compound; + String s1; + + for (jsontonbt$compound = new NBTParser.Compound(p_150316_0_); p_150316_1_.length() > 0; p_150316_1_ = p_150316_1_.substring(s1.length() + 1)) + { + s1 = func_150314_a(p_150316_1_, true); + + if (s1.length() > 0) + { + boolean flag1 = false; + jsontonbt$compound.field_150491_b.add(func_179270_a(s1, flag1)); + } + + if (p_150316_1_.length() < s1.length() + 1) + { + break; + } + + char c1 = p_150316_1_.charAt(s1.length()); + + if (c1 != 44 && c1 != 123 && c1 != 125 && c1 != 91 && c1 != 93) + { + throw new NBTException("Unexpected token \'" + c1 + "\' at: " + p_150316_1_.substring(s1.length())); + } + } + + return jsontonbt$compound; + } + else if (p_150316_1_.startsWith("[") && !PATTERN.matcher(p_150316_1_).matches()) + { + p_150316_1_ = p_150316_1_.substring(1, p_150316_1_.length() - 1); + NBTParser.List jsontonbt$list; + String s; + + for (jsontonbt$list = new NBTParser.List(p_150316_0_); p_150316_1_.length() > 0; p_150316_1_ = p_150316_1_.substring(s.length() + 1)) + { + s = func_150314_a(p_150316_1_, false); + + if (s.length() > 0) + { + boolean flag = true; + jsontonbt$list.field_150492_b.add(func_179270_a(s, flag)); + } + + if (p_150316_1_.length() < s.length() + 1) + { + break; + } + + char c0 = p_150316_1_.charAt(s.length()); + + if (c0 != 44 && c0 != 123 && c0 != 125 && c0 != 91 && c0 != 93) + { + throw new NBTException("Unexpected token \'" + c0 + "\' at: " + p_150316_1_.substring(s.length())); + } + } + + return jsontonbt$list; + } + else + { + return new NBTParser.Primitive(p_150316_0_, p_150316_1_); + } + } + + private static NBTParser.Any func_179270_a(String p_179270_0_, boolean p_179270_1_) throws NBTException + { + String s = func_150313_b(p_179270_0_, p_179270_1_); + String s1 = func_150311_c(p_179270_0_, p_179270_1_); + return func_150316_a(s, s1); + } + + private static String func_150314_a(String p_150314_0_, boolean p_150314_1_) throws NBTException + { + int i = func_150312_a(p_150314_0_, ':'); + int j = func_150312_a(p_150314_0_, ','); + + if (p_150314_1_) + { + if (i == -1) + { + throw new NBTException("Unable to locate name/value separator for string: " + p_150314_0_); + } + + if (j != -1 && j < i) + { + throw new NBTException("Name error at: " + p_150314_0_); + } + } + else if (i == -1 || i > j) + { + i = -1; + } + + return func_179269_a(p_150314_0_, i); + } + + private static String func_179269_a(String p_179269_0_, int p_179269_1_) throws NBTException + { + Stack stack = new Stack(); + int i = p_179269_1_ + 1; + boolean flag = false; + boolean flag1 = false; + boolean flag2 = false; + + for (int j = 0; i < p_179269_0_.length(); ++i) + { + char c0 = p_179269_0_.charAt(i); + + if (c0 == 34) + { + if (func_179271_b(p_179269_0_, i)) + { + if (!flag) + { + throw new NBTException("Illegal use of \\\": " + p_179269_0_); + } + } + else + { + flag = !flag; + + if (flag && !flag2) + { + flag1 = true; + } + + if (!flag) + { + j = i; + } + } + } + else if (!flag) + { + if (c0 != 123 && c0 != 91) + { + if (c0 == 125 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 123)) + { + throw new NBTException("Unbalanced curly brackets {}: " + p_179269_0_); + } + + if (c0 == 93 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 91)) + { + throw new NBTException("Unbalanced square brackets []: " + p_179269_0_); + } + + if (c0 == 44 && stack.isEmpty()) + { + return p_179269_0_.substring(0, i); + } + } + else + { + stack.push(Character.valueOf(c0)); + } + } + + if (!Character.isWhitespace(c0)) + { + if (!flag && flag1 && j != i) + { + return p_179269_0_.substring(0, j + 1); + } + + flag2 = true; + } + } + + return p_179269_0_.substring(0, i); + } + + private static String func_150313_b(String p_150313_0_, boolean p_150313_1_) throws NBTException + { + if (p_150313_1_) + { + p_150313_0_ = p_150313_0_.trim(); + + if (p_150313_0_.startsWith("{") || p_150313_0_.startsWith("[")) + { + return ""; + } + } + + int i = func_150312_a(p_150313_0_, ':'); + + if (i == -1) + { + if (p_150313_1_) + { + return ""; + } + else + { + throw new NBTException("Unable to locate name/value separator for string: " + p_150313_0_); + } + } + else + { + return p_150313_0_.substring(0, i).trim(); + } + } + + private static String func_150311_c(String p_150311_0_, boolean p_150311_1_) throws NBTException + { + if (p_150311_1_) + { + p_150311_0_ = p_150311_0_.trim(); + + if (p_150311_0_.startsWith("{") || p_150311_0_.startsWith("[")) + { + return p_150311_0_; + } + } + + int i = func_150312_a(p_150311_0_, ':'); + + if (i == -1) + { + if (p_150311_1_) + { + return p_150311_0_; + } + else + { + throw new NBTException("Unable to locate name/value separator for string: " + p_150311_0_); + } + } + else + { + return p_150311_0_.substring(i + 1).trim(); + } + } + + private static int func_150312_a(String p_150312_0_, char p_150312_1_) + { + int i = 0; + + for (boolean flag = true; i < p_150312_0_.length(); ++i) + { + char c0 = p_150312_0_.charAt(i); + + if (c0 == 34) + { + if (!func_179271_b(p_150312_0_, i)) + { + flag = !flag; + } + } + else if (flag) + { + if (c0 == p_150312_1_) + { + return i; + } + + if (c0 == 123 || c0 == 91) + { + return -1; + } + } + } + + return -1; + } + + private static boolean func_179271_b(String p_179271_0_, int p_179271_1_) + { + return p_179271_1_ > 0 && p_179271_0_.charAt(p_179271_1_ - 1) == 92 && !func_179271_b(p_179271_0_, p_179271_1_ - 1); + } + + abstract static class Any + { + protected String json; + + public abstract NBTBase parse() throws NBTException; + } + + static class Compound extends NBTParser.Any + { + protected java.util.List field_150491_b = Lists.newArrayList(); + + public Compound(String p_i45137_1_) + { + this.json = p_i45137_1_; + } + + public NBTBase parse() throws NBTException + { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + for (NBTParser.Any jsontonbt$any : this.field_150491_b) + { + nbttagcompound.setTag(jsontonbt$any.json, jsontonbt$any.parse()); + } + + return nbttagcompound; + } + } + + static class List extends NBTParser.Any + { + protected java.util.List field_150492_b = Lists.newArrayList(); + + public List(String json) + { + this.json = json; + } + + public NBTBase parse() throws NBTException + { + NBTTagList nbttaglist = new NBTTagList(); + + for (NBTParser.Any jsontonbt$any : this.field_150492_b) + { + nbttaglist.appendTag(jsontonbt$any.parse()); + } + + return nbttaglist; + } + } + + static class Primitive extends NBTParser.Any + { + private static final Pattern DOUBLE = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[d|D]"); + private static final Pattern FLOAT = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[f|F]"); + private static final Pattern BYTE = Pattern.compile("[-+]?[0-9]+[b|B]"); + private static final Pattern LONG = Pattern.compile("[-+]?[0-9]+[l|L]"); + private static final Pattern SHORT = Pattern.compile("[-+]?[0-9]+[s|S]"); + private static final Pattern INTEGER = Pattern.compile("[-+]?[0-9]+"); + private static final Pattern DOUBLE_UNTYPED = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+"); +// private static final Splitter SPLITTER = Splitter.on(',').omitEmptyStrings(); + protected String jsonValue; + + public Primitive(String p_i45139_1_, String p_i45139_2_) + { + this.json = p_i45139_1_; + this.jsonValue = p_i45139_2_; + } + + public NBTBase parse() throws NBTException + { + try + { + if (DOUBLE.matcher(this.jsonValue).matches()) + { + return new NBTTagDouble(Double.parseDouble(this.jsonValue.substring(0, this.jsonValue.length() - 1))); + } + + if (FLOAT.matcher(this.jsonValue).matches()) + { + return new NBTTagFloat(Float.parseFloat(this.jsonValue.substring(0, this.jsonValue.length() - 1))); + } + + if (BYTE.matcher(this.jsonValue).matches()) + { + return new NBTTagByte(Byte.parseByte(this.jsonValue.substring(0, this.jsonValue.length() - 1))); + } + + if (LONG.matcher(this.jsonValue).matches()) + { + return new NBTTagLong(Long.parseLong(this.jsonValue.substring(0, this.jsonValue.length() - 1))); + } + + if (SHORT.matcher(this.jsonValue).matches()) + { + return new NBTTagShort(Short.parseShort(this.jsonValue.substring(0, this.jsonValue.length() - 1))); + } + + if (INTEGER.matcher(this.jsonValue).matches()) + { + return new NBTTagInt(Integer.parseInt(this.jsonValue)); + } + + if (DOUBLE_UNTYPED.matcher(this.jsonValue).matches()) + { + return new NBTTagDouble(Double.parseDouble(this.jsonValue)); + } + + if (this.jsonValue.equalsIgnoreCase("true") || this.jsonValue.equalsIgnoreCase("false")) + { + return new NBTTagByte((byte)(Boolean.parseBoolean(this.jsonValue) ? 1 : 0)); + } + } + catch (NumberFormatException var6) + { + this.jsonValue = this.jsonValue.replaceAll("\\\\\"", "\""); + return new NBTTagString(this.jsonValue); + } + + if (this.jsonValue.startsWith("[") && this.jsonValue.endsWith("]")) + { + String s = this.jsonValue.substring(1, this.jsonValue.length() - 1); + String[] astring = s.split(","); + + try + { + int[] aint = new int[astring.length]; + + for (int j = 0; j < astring.length; ++j) + { + aint[j] = Integer.parseInt(astring[j].trim()); + } + + return new NBTTagIntArray(aint); + } + catch (NumberFormatException var5) + { + return new NBTTagString(this.jsonValue); + } + } + else + { + if (this.jsonValue.startsWith("\"") && this.jsonValue.endsWith("\"")) + { + this.jsonValue = this.jsonValue.substring(1, this.jsonValue.length() - 1); + } + + this.jsonValue = this.jsonValue.replaceAll("\\\\\"", "\""); + StringBuilder stringbuilder = new StringBuilder(); + + for (int i = 0; i < this.jsonValue.length(); ++i) + { + if (i < this.jsonValue.length() - 1 && this.jsonValue.charAt(i) == 92 && this.jsonValue.charAt(i + 1) == 92) + { + stringbuilder.append('\\'); + ++i; + } + else + { + stringbuilder.append(this.jsonValue.charAt(i)); + } + } + + return new NBTTagString(stringbuilder.toString()); + } + } + } +} diff --git a/common/src/common/nbt/NBTSizeTracker.java b/common/src/common/nbt/NBTSizeTracker.java new file mode 100755 index 0000000..140df95 --- /dev/null +++ b/common/src/common/nbt/NBTSizeTracker.java @@ -0,0 +1,31 @@ +package common.nbt; + +public class NBTSizeTracker +{ + public static final NBTSizeTracker INFINITE = new NBTSizeTracker(0L) + { + public void read(long bits) + { + } + }; + private final long max; + private long read; + + public NBTSizeTracker(long max) + { + this.max = max; + } + + /** + * Tracks the reading of the given amount of bits(!) + */ + public void read(long bits) + { + this.read += bits / 8L; + + if (this.read > this.max) + { + throw new RuntimeException("Tried to read NBT tag that was too big; tried to allocate: " + this.read + "bytes where max allowed: " + this.max); + } + } +} diff --git a/common/src/common/nbt/NBTTagByte.java b/common/src/common/nbt/NBTTagByte.java new file mode 100755 index 0000000..b5a0644 --- /dev/null +++ b/common/src/common/nbt/NBTTagByte.java @@ -0,0 +1,103 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagByte extends NBTBase.NBTPrimitive +{ + /** The byte value for the tag. */ + private byte data; + + NBTTagByte() + { + } + + public NBTTagByte(byte data) + { + this.data = data; + } + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + output.writeByte(this.data); + } + + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(72L); + this.data = input.readByte(); + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)1; + } + + public String toString() + { + return "" + this.data + "b"; + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + return new NBTTagByte(this.data); + } + + public boolean equals(Object p_equals_1_) + { + if (super.equals(p_equals_1_)) + { + NBTTagByte nbttagbyte = (NBTTagByte)p_equals_1_; + return this.data == nbttagbyte.data; + } + else + { + return false; + } + } + + public int hashCode() + { + return super.hashCode() ^ this.data; + } + + public long getLong() + { + return (long)this.data; + } + + public int getInt() + { + return this.data; + } + + public short getShort() + { + return (short)this.data; + } + + public byte getByte() + { + return this.data; + } + + public double getDouble() + { + return (double)this.data; + } + + public float getFloat() + { + return (float)this.data; + } +} diff --git a/common/src/common/nbt/NBTTagByteArray.java b/common/src/common/nbt/NBTTagByteArray.java new file mode 100755 index 0000000..c5c0417 --- /dev/null +++ b/common/src/common/nbt/NBTTagByteArray.java @@ -0,0 +1,77 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Arrays; + +public class NBTTagByteArray extends NBTBase +{ + /** The byte array stored in the tag. */ + private byte[] data; + + NBTTagByteArray() + { + } + + public NBTTagByteArray(byte[] data) + { + this.data = data; + } + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + output.writeInt(this.data.length); + output.write(this.data); + } + + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(192L); + int i = input.readInt(); + sizeTracker.read((long)(8 * i)); + this.data = new byte[i]; + input.readFully(this.data); + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)7; + } + + public String toString() + { + return "[" + this.data.length + " bytes]"; + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + byte[] abyte = new byte[this.data.length]; + System.arraycopy(this.data, 0, abyte, 0, this.data.length); + return new NBTTagByteArray(abyte); + } + + public boolean equals(Object p_equals_1_) + { + return super.equals(p_equals_1_) ? Arrays.equals(this.data, ((NBTTagByteArray)p_equals_1_).data) : false; + } + + public int hashCode() + { + return super.hashCode() ^ Arrays.hashCode(this.data); + } + + public byte[] getByteArray() + { + return this.data; + } +} diff --git a/common/src/common/nbt/NBTTagCompound.java b/common/src/common/nbt/NBTTagCompound.java new file mode 100755 index 0000000..b64ce1c --- /dev/null +++ b/common/src/common/nbt/NBTTagCompound.java @@ -0,0 +1,485 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +import common.collect.Maps; + +import java.util.Set; + +public class NBTTagCompound extends NBTBase +{ + private Map tagMap = Maps.newHashMap(); + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + for (String s : this.tagMap.keySet()) + { + NBTBase nbtbase = (NBTBase)this.tagMap.get(s); + writeEntry(s, nbtbase, output); + } + + output.writeByte(0); + } + + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(384L); + + if (depth > 512) + { + throw new RuntimeException("Tried to read NBT tag with too high complexity, depth > 512"); + } + else + { + this.tagMap.clear(); + byte b0; + + while ((b0 = readType(input, sizeTracker)) != 0) + { + String s = readKey(input, sizeTracker); + sizeTracker.read((long)(224 + 16 * s.length())); + NBTBase nbtbase = readNBT(b0, s, input, depth + 1, sizeTracker); + + if (this.tagMap.put(s, nbtbase) != null) + { + sizeTracker.read(288L); + } + } + } + } + + public Set getKeySet() + { + return this.tagMap.keySet(); + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)10; + } + + /** + * Stores the given tag into the map with the given string key. This is mostly used to store tag lists. + */ + public void setTag(String key, NBTBase value) + { + this.tagMap.put(key, value); + } + + /** + * Stores a new NBTTagByte with the given byte value into the map with the given string key. + */ + public void setByte(String key, byte value) + { + this.tagMap.put(key, new NBTTagByte(value)); + } + + /** + * Stores a new NBTTagShort with the given short value into the map with the given string key. + */ + public void setShort(String key, short value) + { + this.tagMap.put(key, new NBTTagShort(value)); + } + + /** + * Stores a new NBTTagInt with the given integer value into the map with the given string key. + */ + public void setInteger(String key, int value) + { + this.tagMap.put(key, new NBTTagInt(value)); + } + + /** + * Stores a new NBTTagLong with the given long value into the map with the given string key. + */ + public void setLong(String key, long value) + { + this.tagMap.put(key, new NBTTagLong(value)); + } + + /** + * Stores a new NBTTagFloat with the given float value into the map with the given string key. + */ + public void setFloat(String key, float value) + { + this.tagMap.put(key, new NBTTagFloat(value)); + } + + /** + * Stores a new NBTTagDouble with the given double value into the map with the given string key. + */ + public void setDouble(String key, double value) + { + this.tagMap.put(key, new NBTTagDouble(value)); + } + + /** + * Stores a new NBTTagString with the given string value into the map with the given string key. + */ + public void setString(String key, String value) + { + this.tagMap.put(key, new NBTTagString(value)); + } + + /** + * Stores a new NBTTagByteArray with the given array as data into the map with the given string key. + */ + public void setByteArray(String key, byte[] value) + { + this.tagMap.put(key, new NBTTagByteArray(value)); + } + + /** + * Stores a new NBTTagIntArray with the given array as data into the map with the given string key. + */ + public void setIntArray(String key, int[] value) + { + this.tagMap.put(key, new NBTTagIntArray(value)); + } + + /** + * Stores the given boolean value as a NBTTagByte, storing 1 for true and 0 for false, using the given string key. + */ + public void setBoolean(String key, boolean value) + { + this.setByte(key, (byte)(value ? 1 : 0)); + } + + /** + * gets a generic tag with the specified name + */ + public NBTBase getTag(String key) + { + return (NBTBase)this.tagMap.get(key); + } + + /** + * Gets the ID byte for the given tag key + */ + public byte getTagId(String key) + { + NBTBase nbtbase = (NBTBase)this.tagMap.get(key); + return nbtbase != null ? nbtbase.getId() : 0; + } + + /** + * Returns whether the given string has been previously stored as a key in the map. + */ + public boolean hasKey(String key) + { + return this.tagMap.containsKey(key); + } + + public boolean hasKey(String key, int type) + { + int i = this.getTagId(key); + + if (i == type) + { + return true; + } + else if (type != 99) + { + if (i > 0) + { + ; + } + + return false; + } + else + { + return i == 1 || i == 2 || i == 3 || i == 4 || i == 5 || i == 6; + } + } + + /** + * Retrieves a byte value using the specified key, or 0 if no such key was stored. + */ + public byte getByte(String key) + { + try + { + return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getByte(); + } + catch (ClassCastException var3) + { + return (byte)0; + } + } + + /** + * Retrieves a short value using the specified key, or 0 if no such key was stored. + */ + public short getShort(String key) + { + try + { + return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getShort(); + } + catch (ClassCastException var3) + { + return (short)0; + } + } + + /** + * Retrieves an integer value using the specified key, or 0 if no such key was stored. + */ + public int getInteger(String key) + { + try + { + return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getInt(); + } + catch (ClassCastException var3) + { + return 0; + } + } + + /** + * Retrieves a long value using the specified key, or 0 if no such key was stored. + */ + public long getLong(String key) + { + try + { + return !this.hasKey(key, 99) ? 0L : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getLong(); + } + catch (ClassCastException var3) + { + return 0L; + } + } + + /** + * Retrieves a float value using the specified key, or 0 if no such key was stored. + */ + public float getFloat(String key) + { + try + { + return !this.hasKey(key, 99) ? 0.0F : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getFloat(); + } + catch (ClassCastException var3) + { + return 0.0F; + } + } + + /** + * Retrieves a double value using the specified key, or 0 if no such key was stored. + */ + public double getDouble(String key) + { + try + { + return !this.hasKey(key, 99) ? 0.0D : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getDouble(); + } + catch (ClassCastException var3) + { + return 0.0D; + } + } + + /** + * Retrieves a string value using the specified key, or an empty string if no such key was stored. + */ + public String getString(String key) + { + try + { + return !this.hasKey(key, 8) ? "" : ((NBTBase)this.tagMap.get(key)).getString(); + } + catch (ClassCastException var3) + { + return ""; + } + } + + /** + * Retrieves a byte array using the specified key, or a zero-length array if no such key was stored. + */ + public byte[] getByteArray(String key) + { + return !this.hasKey(key, 7) ? new byte[0] : ((NBTTagByteArray)this.tagMap.get(key)).getByteArray(); + } + + /** + * Retrieves an int array using the specified key, or a zero-length array if no such key was stored. + */ + public int[] getIntArray(String key) + { + return !this.hasKey(key, 11) ? new int[0] : ((NBTTagIntArray)this.tagMap.get(key)).getIntArray(); + } + + /** + * Retrieves a NBTTagCompound subtag matching the specified key, or a new empty NBTTagCompound if no such key was + * stored. + */ + public NBTTagCompound getCompoundTag(String key) + { + return !this.hasKey(key, 10) ? new NBTTagCompound() : (NBTTagCompound)this.tagMap.get(key); + } + + /** + * Gets the NBTTagList object with the given name. Args: name, NBTBase type + */ + public NBTTagList getTagList(String key, int type) + { + if (this.getTagId(key) != 9) + { + return new NBTTagList(); + } + else + { + NBTTagList nbttaglist = (NBTTagList)this.tagMap.get(key); + return nbttaglist.tagCount() > 0 && nbttaglist.getTagType() != type ? new NBTTagList() : nbttaglist; + } + } + + /** + * Retrieves a boolean value using the specified key, or false if no such key was stored. This uses the getByte + * method. + */ + public boolean getBoolean(String key) + { + return this.getByte(key) != 0; + } + + /** + * Remove the specified tag. + */ + public void removeTag(String key) + { + this.tagMap.remove(key); + } + + public String toString() + { + StringBuilder stringbuilder = new StringBuilder("{"); + + for (Entry entry : this.tagMap.entrySet()) + { + if (stringbuilder.length() != 1) + { + stringbuilder.append(','); + } + + stringbuilder.append((String)entry.getKey()).append(':').append(entry.getValue()); + } + + return stringbuilder.append('}').toString(); + } + + /** + * Return whether this compound has no tags. + */ + public boolean hasNoTags() + { + return this.tagMap.isEmpty(); + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + for (String s : this.tagMap.keySet()) + { + nbttagcompound.setTag(s, ((NBTBase)this.tagMap.get(s)).copy()); + } + + return nbttagcompound; + } + + public boolean equals(Object p_equals_1_) + { + if (super.equals(p_equals_1_)) + { + NBTTagCompound nbttagcompound = (NBTTagCompound)p_equals_1_; + return this.tagMap.entrySet().equals(nbttagcompound.tagMap.entrySet()); + } + else + { + return false; + } + } + + public int hashCode() + { + return super.hashCode() ^ this.tagMap.hashCode(); + } + + private static void writeEntry(String name, NBTBase data, DataOutput output) throws IOException + { + output.writeByte(data.getId()); + + if (data.getId() != 0) + { + output.writeUTF(name); + data.write(output); + } + } + + private static byte readType(DataInput input, NBTSizeTracker sizeTracker) throws IOException + { + return input.readByte(); + } + + private static String readKey(DataInput input, NBTSizeTracker sizeTracker) throws IOException + { + return input.readUTF(); + } + + static NBTBase readNBT(byte id, String key, DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + NBTBase nbtbase = NBTBase.createNewByType(id); + + nbtbase.read(input, depth, sizeTracker); + return nbtbase; + } + + /** + * Merges this NBTTagCompound with the given compound. Any sub-compounds are merged using the same methods, other + * types of tags are overwritten from the given compound. + */ + public void merge(NBTTagCompound other) + { + for (String s : other.tagMap.keySet()) + { + NBTBase nbtbase = (NBTBase)other.tagMap.get(s); + + if (nbtbase.getId() == 10) + { + if (this.hasKey(s, 10)) + { + NBTTagCompound nbttagcompound = this.getCompoundTag(s); + nbttagcompound.merge((NBTTagCompound)nbtbase); + } + else + { + this.setTag(s, nbtbase.copy()); + } + } + else + { + this.setTag(s, nbtbase.copy()); + } + } + } +} diff --git a/common/src/common/nbt/NBTTagDouble.java b/common/src/common/nbt/NBTTagDouble.java new file mode 100755 index 0000000..2a711b3 --- /dev/null +++ b/common/src/common/nbt/NBTTagDouble.java @@ -0,0 +1,106 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +import common.util.ExtMath; + +public class NBTTagDouble extends NBTBase.NBTPrimitive +{ + /** The double value for the tag. */ + private double data; + + NBTTagDouble() + { + } + + public NBTTagDouble(double data) + { + this.data = data; + } + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + output.writeDouble(this.data); + } + + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(128L); + this.data = input.readDouble(); + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)6; + } + + public String toString() + { + return "" + this.data + "d"; + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + return new NBTTagDouble(this.data); + } + + public boolean equals(Object p_equals_1_) + { + if (super.equals(p_equals_1_)) + { + NBTTagDouble nbttagdouble = (NBTTagDouble)p_equals_1_; + return this.data == nbttagdouble.data; + } + else + { + return false; + } + } + + public int hashCode() + { + long i = Double.doubleToLongBits(this.data); + return super.hashCode() ^ (int)(i ^ i >>> 32); + } + + public long getLong() + { + return (long)Math.floor(this.data); + } + + public int getInt() + { + return ExtMath.floord(this.data); + } + + public short getShort() + { + return (short)(ExtMath.floord(this.data) & 65535); + } + + public byte getByte() + { + return (byte)(ExtMath.floord(this.data) & 255); + } + + public double getDouble() + { + return this.data; + } + + public float getFloat() + { + return (float)this.data; + } +} diff --git a/common/src/common/nbt/NBTTagEnd.java b/common/src/common/nbt/NBTTagEnd.java new file mode 100755 index 0000000..69fc4a7 --- /dev/null +++ b/common/src/common/nbt/NBTTagEnd.java @@ -0,0 +1,41 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagEnd extends NBTBase +{ + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(64L); + } + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)0; + } + + public String toString() + { + return "END"; + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + return new NBTTagEnd(); + } +} diff --git a/common/src/common/nbt/NBTTagFloat.java b/common/src/common/nbt/NBTTagFloat.java new file mode 100755 index 0000000..a51869e --- /dev/null +++ b/common/src/common/nbt/NBTTagFloat.java @@ -0,0 +1,105 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +import common.util.ExtMath; + +public class NBTTagFloat extends NBTBase.NBTPrimitive +{ + /** The float value for the tag. */ + private float data; + + NBTTagFloat() + { + } + + public NBTTagFloat(float data) + { + this.data = data; + } + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + output.writeFloat(this.data); + } + + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(96L); + this.data = input.readFloat(); + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)5; + } + + public String toString() + { + return "" + this.data + "f"; + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + return new NBTTagFloat(this.data); + } + + public boolean equals(Object p_equals_1_) + { + if (super.equals(p_equals_1_)) + { + NBTTagFloat nbttagfloat = (NBTTagFloat)p_equals_1_; + return this.data == nbttagfloat.data; + } + else + { + return false; + } + } + + public int hashCode() + { + return super.hashCode() ^ Float.floatToIntBits(this.data); + } + + public long getLong() + { + return (long)this.data; + } + + public int getInt() + { + return ExtMath.floorf(this.data); + } + + public short getShort() + { + return (short)(ExtMath.floorf(this.data) & 65535); + } + + public byte getByte() + { + return (byte)(ExtMath.floorf(this.data) & 255); + } + + public double getDouble() + { + return (double)this.data; + } + + public float getFloat() + { + return this.data; + } +} diff --git a/common/src/common/nbt/NBTTagInt.java b/common/src/common/nbt/NBTTagInt.java new file mode 100755 index 0000000..50dc226 --- /dev/null +++ b/common/src/common/nbt/NBTTagInt.java @@ -0,0 +1,103 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagInt extends NBTBase.NBTPrimitive +{ + /** The integer value for the tag. */ + private int data; + + NBTTagInt() + { + } + + public NBTTagInt(int data) + { + this.data = data; + } + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + output.writeInt(this.data); + } + + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(96L); + this.data = input.readInt(); + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)3; + } + + public String toString() + { + return "" + this.data; + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + return new NBTTagInt(this.data); + } + + public boolean equals(Object p_equals_1_) + { + if (super.equals(p_equals_1_)) + { + NBTTagInt nbttagint = (NBTTagInt)p_equals_1_; + return this.data == nbttagint.data; + } + else + { + return false; + } + } + + public int hashCode() + { + return super.hashCode() ^ this.data; + } + + public long getLong() + { + return (long)this.data; + } + + public int getInt() + { + return this.data; + } + + public short getShort() + { + return (short)(this.data & 65535); + } + + public byte getByte() + { + return (byte)(this.data & 255); + } + + public double getDouble() + { + return (double)this.data; + } + + public float getFloat() + { + return (float)this.data; + } +} diff --git a/common/src/common/nbt/NBTTagIntArray.java b/common/src/common/nbt/NBTTagIntArray.java new file mode 100755 index 0000000..657abbe --- /dev/null +++ b/common/src/common/nbt/NBTTagIntArray.java @@ -0,0 +1,92 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Arrays; + +public class NBTTagIntArray extends NBTBase +{ + /** The array of saved integers */ + private int[] intArray; + + NBTTagIntArray() + { + } + + public NBTTagIntArray(int[] p_i45132_1_) + { + this.intArray = p_i45132_1_; + } + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + output.writeInt(this.intArray.length); + + for (int i = 0; i < this.intArray.length; ++i) + { + output.writeInt(this.intArray[i]); + } + } + + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(192L); + int i = input.readInt(); + sizeTracker.read((long)(32 * i)); + this.intArray = new int[i]; + + for (int j = 0; j < i; ++j) + { + this.intArray[j] = input.readInt(); + } + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)11; + } + + public String toString() + { + String s = "["; + + for (int i : this.intArray) + { + s = s + i + ","; + } + + return s + "]"; + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + int[] aint = new int[this.intArray.length]; + System.arraycopy(this.intArray, 0, aint, 0, this.intArray.length); + return new NBTTagIntArray(aint); + } + + public boolean equals(Object p_equals_1_) + { + return super.equals(p_equals_1_) ? Arrays.equals(this.intArray, ((NBTTagIntArray)p_equals_1_).intArray) : false; + } + + public int hashCode() + { + return super.hashCode() ^ Arrays.hashCode(this.intArray); + } + + public int[] getIntArray() + { + return this.intArray; + } +} diff --git a/common/src/common/nbt/NBTTagList.java b/common/src/common/nbt/NBTTagList.java new file mode 100755 index 0000000..c20a725 --- /dev/null +++ b/common/src/common/nbt/NBTTagList.java @@ -0,0 +1,300 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import common.collect.Lists; +import common.log.Log; + +public class NBTTagList extends NBTBase +{ + private List tagList = Lists.newArrayList(); + + /** + * The type byte for the tags in the list - they must all be of the same type. + */ + private byte tagType = 0; + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + if (!this.tagList.isEmpty()) + { + this.tagType = ((NBTBase)this.tagList.get(0)).getId(); + } + else + { + this.tagType = 0; + } + + output.writeByte(this.tagType); + output.writeInt(this.tagList.size()); + + for (int i = 0; i < this.tagList.size(); ++i) + { + ((NBTBase)this.tagList.get(i)).write(output); + } + } + + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(296L); + + if (depth > 512) + { + throw new RuntimeException("Tried to read NBT tag with too high complexity, depth > 512"); + } + else + { + this.tagType = input.readByte(); + int i = input.readInt(); + + if (this.tagType == 0 && i > 0) + { + throw new RuntimeException("Missing type on ListTag"); + } + else + { + sizeTracker.read(32L * (long)i); + this.tagList = new ArrayList(i); + + for (int j = 0; j < i; ++j) + { + NBTBase nbtbase = NBTBase.createNewByType(this.tagType); + nbtbase.read(input, depth + 1, sizeTracker); + this.tagList.add(nbtbase); + } + } + } + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)9; + } + + public String toString() + { + StringBuilder stringbuilder = new StringBuilder("["); + + for (int i = 0; i < this.tagList.size(); ++i) + { + if (i != 0) + { + stringbuilder.append(','); + } + + stringbuilder.append(i).append(':').append(this.tagList.get(i)); + } + + return stringbuilder.append(']').toString(); + } + + /** + * Adds the provided tag to the end of the list. There is no check to verify this tag is of the same type as any + * previous tag. + */ + public void appendTag(NBTBase nbt) + { + if (nbt.getId() == 0) + { + Log.JNI.warn("Ungültiger End-Tag zu Tag-Liste hinzugefügt"); + } + else + { + if (this.tagType == 0) + { + this.tagType = nbt.getId(); + } + else if (this.tagType != nbt.getId()) + { + Log.JNI.warn("Füge ungleiche Tag-Typen zu Tag-Liste hinzu"); + return; + } + + this.tagList.add(nbt); + } + } + + /** + * Set the given index to the given tag + */ + public void set(int idx, NBTBase nbt) + { + if (nbt.getId() == 0) + { + Log.JNI.warn("Ungültiger End-Tag zu Tag-Liste hinzugefügt"); + } + else if (idx >= 0 && idx < this.tagList.size()) + { + if (this.tagType == 0) + { + this.tagType = nbt.getId(); + } + else if (this.tagType != nbt.getId()) + { + Log.JNI.warn("Füge ungleiche Tag-Typen zu Tag-Liste hinzu"); + return; + } + + this.tagList.set(idx, nbt); + } + else + { + Log.JNI.warn("Index außerhalb des Bereiches um Tag in Tag-Liste zu setzen"); + } + } + + /** + * Removes a tag at the given index. + */ + public NBTBase removeTag(int i) + { + return (NBTBase)this.tagList.remove(i); + } + + /** + * Return whether this compound has no tags. + */ + public boolean hasNoTags() + { + return this.tagList.isEmpty(); + } + + /** + * Retrieves the NBTTagCompound at the specified index in the list + */ + public NBTTagCompound getCompoundTagAt(int i) + { + if (i >= 0 && i < this.tagList.size()) + { + NBTBase nbtbase = (NBTBase)this.tagList.get(i); + return nbtbase.getId() == 10 ? (NBTTagCompound)nbtbase : new NBTTagCompound(); + } + else + { + return new NBTTagCompound(); + } + } + + public int[] getIntArrayAt(int i) + { + if (i >= 0 && i < this.tagList.size()) + { + NBTBase nbtbase = (NBTBase)this.tagList.get(i); + return nbtbase.getId() == 11 ? ((NBTTagIntArray)nbtbase).getIntArray() : new int[0]; + } + else + { + return new int[0]; + } + } + + public double getDoubleAt(int i) + { + if (i >= 0 && i < this.tagList.size()) + { + NBTBase nbtbase = (NBTBase)this.tagList.get(i); + return nbtbase.getId() == 6 ? ((NBTTagDouble)nbtbase).getDouble() : 0.0D; + } + else + { + return 0.0D; + } + } + + public float getFloatAt(int i) + { + if (i >= 0 && i < this.tagList.size()) + { + NBTBase nbtbase = (NBTBase)this.tagList.get(i); + return nbtbase.getId() == 5 ? ((NBTTagFloat)nbtbase).getFloat() : 0.0F; + } + else + { + return 0.0F; + } + } + + /** + * Retrieves the tag String value at the specified index in the list + */ + public String getStringTagAt(int i) + { + if (i >= 0 && i < this.tagList.size()) + { + NBTBase nbtbase = (NBTBase)this.tagList.get(i); + return nbtbase.getId() == 8 ? nbtbase.getString() : nbtbase.toString(); + } + else + { + return ""; + } + } + + /** + * Get the tag at the given position + */ + public NBTBase get(int idx) + { + return (NBTBase)(idx >= 0 && idx < this.tagList.size() ? (NBTBase)this.tagList.get(idx) : new NBTTagEnd()); + } + + /** + * Returns the number of tags in the list. + */ + public int tagCount() + { + return this.tagList.size(); + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + NBTTagList nbttaglist = new NBTTagList(); + nbttaglist.tagType = this.tagType; + + for (NBTBase nbtbase : this.tagList) + { + NBTBase nbtbase1 = nbtbase.copy(); + nbttaglist.tagList.add(nbtbase1); + } + + return nbttaglist; + } + + public boolean equals(Object p_equals_1_) + { + if (super.equals(p_equals_1_)) + { + NBTTagList nbttaglist = (NBTTagList)p_equals_1_; + + if (this.tagType == nbttaglist.tagType) + { + return this.tagList.equals(nbttaglist.tagList); + } + } + + return false; + } + + public int hashCode() + { + return super.hashCode() ^ this.tagList.hashCode(); + } + + public int getTagType() + { + return this.tagType; + } +} diff --git a/common/src/common/nbt/NBTTagLong.java b/common/src/common/nbt/NBTTagLong.java new file mode 100755 index 0000000..aa9313a --- /dev/null +++ b/common/src/common/nbt/NBTTagLong.java @@ -0,0 +1,103 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagLong extends NBTBase.NBTPrimitive +{ + /** The long value for the tag. */ + private long data; + + NBTTagLong() + { + } + + public NBTTagLong(long data) + { + this.data = data; + } + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + output.writeLong(this.data); + } + + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(128L); + this.data = input.readLong(); + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)4; + } + + public String toString() + { + return "" + this.data + "L"; + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + return new NBTTagLong(this.data); + } + + public boolean equals(Object p_equals_1_) + { + if (super.equals(p_equals_1_)) + { + NBTTagLong nbttaglong = (NBTTagLong)p_equals_1_; + return this.data == nbttaglong.data; + } + else + { + return false; + } + } + + public int hashCode() + { + return super.hashCode() ^ (int)(this.data ^ this.data >>> 32); + } + + public long getLong() + { + return this.data; + } + + public int getInt() + { + return (int)(this.data & -1L); + } + + public short getShort() + { + return (short)((int)(this.data & 65535L)); + } + + public byte getByte() + { + return (byte)((int)(this.data & 255L)); + } + + public double getDouble() + { + return (double)this.data; + } + + public float getFloat() + { + return (float)this.data; + } +} diff --git a/common/src/common/nbt/NBTTagShort.java b/common/src/common/nbt/NBTTagShort.java new file mode 100755 index 0000000..684aa95 --- /dev/null +++ b/common/src/common/nbt/NBTTagShort.java @@ -0,0 +1,103 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagShort extends NBTBase.NBTPrimitive +{ + /** The short value for the tag. */ + private short data; + + public NBTTagShort() + { + } + + public NBTTagShort(short data) + { + this.data = data; + } + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + output.writeShort(this.data); + } + + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(80L); + this.data = input.readShort(); + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)2; + } + + public String toString() + { + return "" + this.data + "s"; + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + return new NBTTagShort(this.data); + } + + public boolean equals(Object p_equals_1_) + { + if (super.equals(p_equals_1_)) + { + NBTTagShort nbttagshort = (NBTTagShort)p_equals_1_; + return this.data == nbttagshort.data; + } + else + { + return false; + } + } + + public int hashCode() + { + return super.hashCode() ^ this.data; + } + + public long getLong() + { + return (long)this.data; + } + + public int getInt() + { + return this.data; + } + + public short getShort() + { + return this.data; + } + + public byte getByte() + { + return (byte)(this.data & 255); + } + + public double getDouble() + { + return (double)this.data; + } + + public float getFloat() + { + return (float)this.data; + } +} diff --git a/common/src/common/nbt/NBTTagString.java b/common/src/common/nbt/NBTTagString.java new file mode 100755 index 0000000..5968697 --- /dev/null +++ b/common/src/common/nbt/NBTTagString.java @@ -0,0 +1,93 @@ +package common.nbt; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagString extends NBTBase +{ + /** The string value for the tag (cannot be empty). */ + private String data; + + public NBTTagString() + { + this.data = ""; + } + + public NBTTagString(String data) + { + this.data = data; + + if (data == null) + { + throw new IllegalArgumentException("Empty string not allowed"); + } + } + + /** + * Write the actual data contents of the tag, implemented in NBT extension classes + */ + void write(DataOutput output) throws IOException + { + output.writeUTF(this.data); + } + + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException + { + sizeTracker.read(288L); + this.data = input.readUTF(); + sizeTracker.read((long)(16 * this.data.length())); + } + + /** + * Gets the type byte for the tag. + */ + public byte getId() + { + return (byte)8; + } + + public String toString() + { + return "\"" + this.data.replace("\"", "\\\"") + "\""; + } + + /** + * Creates a clone of the tag. + */ + public NBTBase copy() + { + return new NBTTagString(this.data); + } + + /** + * Return whether this compound has no tags. + */ + public boolean hasNoTags() + { + return this.data.isEmpty(); + } + + public boolean equals(Object p_equals_1_) + { + if (!super.equals(p_equals_1_)) + { + return false; + } + else + { + NBTTagString nbttagstring = (NBTTagString)p_equals_1_; + return this.data == null && nbttagstring.data == null || this.data != null && this.data.equals(nbttagstring.data); + } + } + + public int hashCode() + { + return super.hashCode() ^ this.data.hashCode(); + } + + public String getString() + { + return this.data; + } +} diff --git a/common/src/common/nbt/NBTUtil.java b/common/src/common/nbt/NBTUtil.java new file mode 100755 index 0000000..8d3eaf8 --- /dev/null +++ b/common/src/common/nbt/NBTUtil.java @@ -0,0 +1,79 @@ +package common.nbt; + +public final class NBTUtil +{ + public static boolean compareTags(NBTBase tag1, NBTBase tag2, boolean lists) + { + if (tag1 == tag2) + { + return true; + } + else if (tag1 == null) + { + return true; + } + else if (tag2 == null) + { + return false; + } + else if (!tag1.getClass().equals(tag2.getClass())) + { + return false; + } + else if (tag1 instanceof NBTTagCompound) + { + NBTTagCompound nbttagcompound = (NBTTagCompound)tag1; + NBTTagCompound nbttagcompound1 = (NBTTagCompound)tag2; + + for (String s : nbttagcompound.getKeySet()) + { + NBTBase nbtbase1 = nbttagcompound.getTag(s); + + if (!compareTags(nbtbase1, nbttagcompound1.getTag(s), lists)) + { + return false; + } + } + + return true; + } + else if (tag1 instanceof NBTTagList && lists) + { + NBTTagList nbttaglist = (NBTTagList)tag1; + NBTTagList nbttaglist1 = (NBTTagList)tag2; + + if (nbttaglist.tagCount() == 0) + { + return nbttaglist1.tagCount() == 0; + } + else + { + for (int i = 0; i < nbttaglist.tagCount(); ++i) + { + NBTBase nbtbase = nbttaglist.get(i); + boolean flag = false; + + for (int j = 0; j < nbttaglist1.tagCount(); ++j) + { + if (compareTags(nbtbase, nbttaglist1.get(j), lists)) + { + flag = true; + break; + } + } + + if (!flag) + { + return false; + } + } + + return true; + } + } + else + { + return tag1.equals(tag2); + } + } +} diff --git a/common/src/main/java/common/network/EncryptionCodec.java b/common/src/common/network/EncryptionCodec.java similarity index 93% rename from common/src/main/java/common/network/EncryptionCodec.java rename to common/src/common/network/EncryptionCodec.java index 4a6d981..2598ecc 100644 --- a/common/src/main/java/common/network/EncryptionCodec.java +++ b/common/src/common/network/EncryptionCodec.java @@ -1,11 +1,10 @@ package common.network; +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; import javax.crypto.Cipher; import javax.crypto.ShortBufferException; -import common.net.buffer.ByteBuf; -import common.net.channel.ChannelHandlerContext; - public class EncryptionCodec { private final Cipher cipher; private byte[] receiveBuf = new byte[0]; diff --git a/common/src/common/network/IClientLoginHandler.java b/common/src/common/network/IClientLoginHandler.java new file mode 100644 index 0000000..b2606e1 --- /dev/null +++ b/common/src/common/network/IClientLoginHandler.java @@ -0,0 +1,18 @@ +package common.network; + +import common.packet.RPacketDisconnect; +import common.packet.RPacketEnableCompression; +import common.packet.RPacketLoginSuccess; +import common.packet.RPacketRequestEncrypt; + +public interface IClientLoginHandler { + + void handleDisconnect(RPacketDisconnect packetIn); + + void handleLoginSuccess(RPacketLoginSuccess packetIn); + + void handleEnableCompression(RPacketEnableCompression packetIn); + + void handleEncrypt(RPacketRequestEncrypt packet); + +} \ No newline at end of file diff --git a/common/src/common/network/IClientPlayer.java b/common/src/common/network/IClientPlayer.java new file mode 100644 index 0000000..a1c0704 --- /dev/null +++ b/common/src/common/network/IClientPlayer.java @@ -0,0 +1,156 @@ +package common.network; + +import common.entity.Entity; +import common.entity.animal.EntityHorse; +import common.inventory.IInventory; +import common.inventory.InventoryPlayer; +import common.model.ParticleType; +import common.packet.S14PacketEntity; +import common.packet.S18PacketEntityTeleport; +import common.packet.S19PacketEntityHeadLook; +import common.packet.S1APacketEntityStatus; +import common.packet.S1BPacketEntityAttach; +import common.packet.S1CPacketEntityMetadata; +import common.packet.S1DPacketEntityEffect; +import common.packet.S1EPacketRemoveEntityEffect; +import common.packet.S20PacketEntityProperties; +import common.packet.S27PacketExplosion; +import common.packet.S28PacketEffect; +import common.packet.S29PacketSoundEffect; +import common.packet.S2APacketParticles; +import common.packet.S2BPacketChangeGameState; +import common.packet.S2CPacketSpawnGlobalEntity; +import common.packet.S2DPacketOpenWindow; +import common.packet.S2EPacketCloseWindow; +import common.packet.S2FPacketSetSlot; +import common.packet.S30PacketWindowItems; +import common.packet.S31PacketWindowProperty; +import common.packet.S32PacketConfirmTransaction; +import common.packet.S33PacketUpdateSign; +import common.packet.S35PacketUpdateTileEntity; +import common.packet.S36PacketSignEditorOpen; +import common.packet.S38PacketPlayerListItem; +import common.packet.S39PacketPlayerAbilities; +import common.packet.S3APacketTabComplete; +import common.packet.S43PacketUpdateEntityNBT; +import common.packet.SPacketAnimation; +import common.packet.SPacketBlockAction; +import common.packet.SPacketBlockBreakAnim; +import common.packet.SPacketBlockChange; +import common.packet.SPacketCamera; +import common.packet.SPacketCharacterList; +import common.packet.SPacketChunkData; +import common.packet.SPacketCollectItem; +import common.packet.SPacketDestroyEntities; +import common.packet.SPacketDimensionName; +import common.packet.SPacketDisconnect; +import common.packet.SPacketDisplayForm; +import common.packet.SPacketEntityEquipment; +import common.packet.SPacketEntityVelocity; +import common.packet.SPacketHeldItemChange; +import common.packet.SPacketJoinGame; +import common.packet.SPacketKeepAlive; +import common.packet.SPacketLoading; +import common.packet.SPacketMapChunkBulk; +import common.packet.SPacketMessage; +import common.packet.SPacketMultiBlockChange; +import common.packet.SPacketPlayerPosLook; +import common.packet.SPacketRespawn; +import common.packet.SPacketServerTick; +import common.packet.SPacketSetExperience; +import common.packet.SPacketSkin; +import common.packet.SPacketSpawnMob; +import common.packet.SPacketSpawnObject; +import common.packet.SPacketSpawnPlayer; +import common.packet.SPacketTimeUpdate; +import common.packet.SPacketTrades; +import common.packet.SPacketUpdateHealth; +import common.packet.SPacketWorld; +import common.sound.Sound; +import common.tileentity.IInteractionObject; +import common.util.BlockPos; +import common.world.World; + +public interface IClientPlayer { + void playSound(Sound sound); + boolean isRenderViewEntity(Entity entity); + void updatePlayerMoveState(); + void emitParticleAtEntity(Entity entityIn, ParticleType particleTypes); + boolean isJumping(); + boolean isSprinting(); + boolean isSneaking(); + float getMoveForward(); + float getMoveStrafe(); + void setMoveForward(float value); + void setMoveStrafe(float value); + void addToSendQueue(Packet packet); + + void handleJoinGame(SPacketJoinGame packetIn); + void handleSpawnObject(SPacketSpawnObject packetIn); + void handleSpawnGlobalEntity(S2CPacketSpawnGlobalEntity packetIn); + void handleEntityVelocity(SPacketEntityVelocity packetIn); + void handleEntityMetadata(S1CPacketEntityMetadata packetIn); + void handleSpawnPlayer(SPacketSpawnPlayer packetIn); + void handleEntityTeleport(S18PacketEntityTeleport packetIn); + void handleHeldItemChange(SPacketHeldItemChange packetIn); + void handleEntityMovement(S14PacketEntity packetIn); + void handleEntityHeadLook(S19PacketEntityHeadLook packetIn); + void handleDestroyEntities(SPacketDestroyEntities packetIn); + void handlePlayerPosLook(SPacketPlayerPosLook packetIn); + void handleMultiBlockChange(SPacketMultiBlockChange packetIn); + void handleChunkData(SPacketChunkData packetIn); + void handleBlockChange(SPacketBlockChange packetIn); + void handleDisconnect(SPacketDisconnect packetIn); + void handleCollectItem(SPacketCollectItem packetIn); + void handleMessage(SPacketMessage packetIn); + void handleLoading(SPacketLoading packet); + void handleAnimation(SPacketAnimation packetIn); + void handleSpawnMob(SPacketSpawnMob packetIn); + void handleTimeUpdate(SPacketTimeUpdate packetIn); + void handleServerTick(SPacketServerTick packet); + void handleEntityAttach(S1BPacketEntityAttach packetIn); + void handleEntityStatus(S1APacketEntityStatus packetIn); + void handleUpdateHealth(SPacketUpdateHealth packetIn); + void handleSetExperience(SPacketSetExperience packetIn); + void handleRespawn(SPacketRespawn packetIn); + void handleExplosion(S27PacketExplosion packetIn); + void handleOpenWindow(S2DPacketOpenWindow packetIn); + void handleSetSlot(S2FPacketSetSlot packetIn); + void handleConfirmTransaction(S32PacketConfirmTransaction packetIn); + void handleWindowItems(S30PacketWindowItems packetIn); + void handleSignEditorOpen(S36PacketSignEditorOpen packetIn); + void handleUpdateSign(S33PacketUpdateSign packetIn); + void handleUpdateTileEntity(S35PacketUpdateTileEntity packetIn); + void handleWindowProperty(S31PacketWindowProperty packetIn); + void handleEntityEquipment(SPacketEntityEquipment packetIn); + void handleCloseWindow(S2EPacketCloseWindow packetIn); + void handleBlockAction(SPacketBlockAction packetIn); + void handleBlockBreakAnim(SPacketBlockBreakAnim packetIn); + void handleMapChunkBulk(SPacketMapChunkBulk packetIn); + void handleChangeGameState(S2BPacketChangeGameState packetIn); + void handleEffect(S28PacketEffect packetIn); + void handleEntityEffect(S1DPacketEntityEffect packetIn); + void handleCamera(SPacketCamera packetIn); + void handleRemoveEntityEffect(S1EPacketRemoveEntityEffect packetIn); + void handlePlayerListItem(S38PacketPlayerListItem packetIn); + void handleCharacterList(SPacketCharacterList packet); + void handleKeepAlive(SPacketKeepAlive packetIn); + void handlePlayerAbilities(S39PacketPlayerAbilities packetIn); + void handleTabComplete(S3APacketTabComplete packetIn); + void handleSoundEffect(S29PacketSoundEffect packetIn); + void handleEntityNBT(S43PacketUpdateEntityNBT packetIn); + void handleParticles(S2APacketParticles packetIn); + void handleEntityProperties(S20PacketEntityProperties packetIn); + void handleSkin(SPacketSkin packetIn); + void handleTrades(SPacketTrades packetIn); + void handleWorld(SPacketWorld packetIn); + void handleDimName(SPacketDimensionName packetIn); + void handleForm(SPacketDisplayForm packet); + + void displayGUIChest(IInventory chestInventory, InventoryPlayer inventory); + void displayGui(IInteractionObject guiOwner, InventoryPlayer inventory, World worldObj); + void displayGuiHorse(EntityHorse horse, InventoryPlayer inventory, IInventory horseInventory); + void displayGuiMerchant(String title, InventoryPlayer inventory, World worldObj); + void displayGuiSign(BlockPos pos, String[] text); + void closeGui(); +} \ No newline at end of file diff --git a/common/src/common/network/IHandshakeHandler.java b/common/src/common/network/IHandshakeHandler.java new file mode 100644 index 0000000..b6815e8 --- /dev/null +++ b/common/src/common/network/IHandshakeHandler.java @@ -0,0 +1,9 @@ +package common.network; + +import common.packet.HPacketHandshake; + +public interface IHandshakeHandler { + + void processHandshake(HPacketHandshake packetIn); + +} \ No newline at end of file diff --git a/common/src/common/network/ILoginHandler.java b/common/src/common/network/ILoginHandler.java new file mode 100644 index 0000000..479e986 --- /dev/null +++ b/common/src/common/network/ILoginHandler.java @@ -0,0 +1,15 @@ +package common.network; + +import common.packet.LPacketLogin; +import common.packet.LPacketPasswordResponse; +import common.packet.LPacketStartEncrypt; + +public interface ILoginHandler { + + void processPasswordResponse(LPacketPasswordResponse packetIn); + + void processEncryption(LPacketStartEncrypt packet); + + void processLogin(LPacketLogin packet); + +} \ No newline at end of file diff --git a/common/src/main/java/common/network/IPlayer.java b/common/src/common/network/IPlayer.java similarity index 75% rename from common/src/main/java/common/network/IPlayer.java rename to common/src/common/network/IPlayer.java index 41d069e..42d3fb6 100644 --- a/common/src/main/java/common/network/IPlayer.java +++ b/common/src/common/network/IPlayer.java @@ -3,6 +3,7 @@ package common.network; import java.util.List; import common.entity.Entity; +import common.entity.animal.EntityHorse; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.SoundEvent; @@ -10,6 +11,7 @@ import common.inventory.Container; import common.inventory.IInventory; import common.item.ItemStack; import common.packet.CPacketAction; +import common.packet.CPacketBook; import common.packet.CPacketBreak; import common.packet.CPacketCheat; import common.packet.CPacketClick; @@ -30,7 +32,7 @@ import common.util.CharValidator; import common.util.ChunkPos; import common.util.PortalType; -public interface IPlayer extends NetHandler { +public interface IPlayer { public static class UserValidator implements CharValidator { public boolean valid(char ch) { return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-'; @@ -61,61 +63,115 @@ public interface IPlayer extends NetHandler { } void onEntityDeath(); + boolean isInEditor(); + EntityNPC getPresentEntity(); + String getUser(); + int getLatency(); + boolean isAdmin(); + void addToPlayerScore(EntityLiving entity); - void displayTradeGui(EntityNPC entity); + + void displayTradeGui(EntityNPC npc); + void setPlayerHealthUpdated(); - void removeEntity(Entity entity); + + void removeEntity(Entity p_152339_1_); + void sendPlayerAbilities(); + void addFeed(String msg); + void addHotbar(String msg); + void addHotbar(String format, Object... args); + void sendThrowMessage(ItemStack stack); + void resetLastExperience(); - void travelToDimension(int dimension, BlockPos pos, float yaw, float pitch, PortalType portal); + + void travelToDimension(int dimensionId, BlockPos pos, float yaw, float pitch, PortalType portal); + void teleport(double x, double y, double z, float yaw, float pitch, int dimension); + void onItemPickup(Entity entity, int amount); - void mountEntity(Entity entity); + + void mountEntity(Entity entityIn); + void openEditSign(TileEntitySign signTile); + void displayGui(IInteractionObject guiOwner); + void displayGUIChest(IInventory chestInventory); - void displayEntityGui(Entity entity, IInventory inventory); + + void displayGUIHorse(EntityHorse horse, IInventory horseInventory); + void closeScreen(); + void onItemUseFinish(); + void onNewEffect(PotionEffect id); + void onChangedEffect(PotionEffect id, boolean added); + void onFinishedEffect(PotionEffect effect); + void setPositionAndUpdate(double x, double y, double z); - void onCriticalHit(Entity entity); - void onEnchantmentCritical(Entity entity); + + void onCriticalHit(Entity entityHit); + + void onEnchantmentCritical(Entity entityHit); + void updateEffectMeta(); + void playSound(SoundEvent name, float volume); + void sendContainerToPlayer(Container container); + void updateEntity(); + void setSelection(boolean primary, BlockPos pos); + void setSelectMode(); + void sendPacket(Packet packet); + void setPlayerLocation(double x, double y, double z, float yaw, float pitch); + + void processKeepAlive(CPacketKeepAlive packetIn); + + void processMessage(CPacketMessage packetIn); + + void processComplete(CPacketComplete packetIn); + + void processPlayer(CPacketPlayer packetIn); + + void processBreak(CPacketBreak packetIn); + + void processPlace(CPacketPlace packetIn); + + void processAction(CPacketAction packetIn); + + void processInput(CPacketInput packetIn); + + void processClick(CPacketClick packetIn); + + void processCheat(CPacketCheat packetIn); + + void processSign(CPacketSign packetIn); + + void processSkin(CPacketSkin packetIn); + + void processBook(CPacketBook packetIn); + + void processForm(CPacketForm packet); + List getLoadedChunkList(); double getManagedX(); double getManagedZ(); void setManagedPos(double x, double z); - - void processKeepAlive(CPacketKeepAlive packet); - void processMessage(CPacketMessage packet); - void processComplete(CPacketComplete packet); - void processPlayer(CPacketPlayer packet); - void processBreak(CPacketBreak packet); - void processPlace(CPacketPlace packet); - void processAction(CPacketAction packet); - void processInput(CPacketInput packet); - void processClick(CPacketClick packet); - void processCheat(CPacketCheat packet); - void processSign(CPacketSign packet); - void processSkin(CPacketSkin packet); - void processForm(CPacketForm packet); -} +} \ No newline at end of file diff --git a/common/src/main/java/common/network/IThreadListener.java b/common/src/common/network/IThreadListener.java similarity index 85% rename from common/src/main/java/common/network/IThreadListener.java rename to common/src/common/network/IThreadListener.java index 646777a..e6f14d4 100755 --- a/common/src/main/java/common/network/IThreadListener.java +++ b/common/src/common/network/IThreadListener.java @@ -2,7 +2,8 @@ package common.network; import common.future.ListenableFuture; -public interface IThreadListener { +public interface IThreadListener +{ ListenableFuture schedule(Runnable run); boolean isMainThread(); default void log(String prefixed, String line) { diff --git a/common/src/common/network/NetConnection.java b/common/src/common/network/NetConnection.java new file mode 100755 index 0000000..a359d83 --- /dev/null +++ b/common/src/common/network/NetConnection.java @@ -0,0 +1,382 @@ +package common.network; + +import java.net.SocketAddress; +import java.nio.channels.ClosedChannelException; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.regex.Pattern; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; + +import common.log.Log; +import common.network.NetHandler.ThreadQuickExitException; +import common.util.EncryptUtil; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.timeout.TimeoutException; +import io.netty.util.AttributeKey; +import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.GenericFutureListener; + +public class NetConnection extends SimpleChannelInboundHandler +{ + private static final Pattern IP_REPLACER = Pattern.compile("([0-9]*)\\.([0-9]*)\\.[0-9]*\\.[0-9]*"); + public static final AttributeKey ATTR_STATE = AttributeKey.valueOf("protocol"); + private final Queue outboundPacketsQueue = new ConcurrentLinkedQueue(); + private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); + + private Channel channel; + private SocketAddress socketAddress; + private NetHandler packetListener; + private String terminationReason; + private boolean disconnected; + + public void channelActive(ChannelHandlerContext p_channelActive_1_) throws Exception + { + super.channelActive(p_channelActive_1_); + this.channel = p_channelActive_1_.channel(); + this.socketAddress = this.channel.remoteAddress(); + + try + { + this.setConnectionState(PacketRegistry.HANDSHAKE); + } + catch (Throwable throwable) + { + Log.JNI.error(throwable, "Fehler beim Aufbauen der Verbindung für Handshake"); + } + } + + /** + * Sets the new connection state and registers which packets this channel may send and receive + */ + public void setConnectionState(PacketRegistry newState) + { + this.channel.attr(ATTR_STATE).set(newState); + this.channel.config().setAutoRead(true); +// Log.debug("Automatisches Lesen eingeschaltet"); + } + + public void channelInactive(ChannelHandlerContext p_channelInactive_1_) throws Exception + { + this.closeChannel("Ende der Datenübertragung"); + } + + public void exceptionCaught(ChannelHandlerContext p_exceptionCaught_1_, Throwable p_exceptionCaught_2_) throws Exception + { + String comp; + + if (p_exceptionCaught_2_ instanceof TimeoutException) + { + comp = "Zeitüberschreitung"; + } + else + { + comp = "Interner Fehler: " + p_exceptionCaught_2_; + if(!(p_exceptionCaught_2_ instanceof ClosedChannelException)) + Log.SYSTEM.error(p_exceptionCaught_2_, "Fehler in der Verbindung mit %s", this.getCutAddress()); + } + + this.closeChannel(comp); + } + + protected void channelRead0(ChannelHandlerContext p_channelRead0_1_, Packet p_channelRead0_2_) throws Exception + { + if (this.channel.isOpen()) + { + try + { + p_channelRead0_2_.processPacket(this.packetListener); + } + catch (ThreadQuickExitException e) + { + ; + } + } + } + + /** + * Sets the NetHandler for this NetworkManager, no checks are made if this handler is suitable for the particular + * connection state (protocol) + */ + public void setNetHandler(NetHandler handler) + { + if (handler == null) { + throw new NullPointerException("Handler ist Null"); + } +// Log.debug("Setze Handler von " + this + " auf " + handler); + this.packetListener = handler; + } + + public void sendPacket(Packet packetIn) + { + if (this.isChannelOpen()) + { + this.flushOutboundQueue(); + this.dispatchPacket(packetIn, null); + } + else + { + this.readWriteLock.writeLock().lock(); + + try + { + this.outboundPacketsQueue.add(new NetConnection.InboundHandlerTuplePacketListener(packetIn, null)); + } + finally + { + this.readWriteLock.writeLock().unlock(); + } + } + } + + public void sendPacket(Packet packetIn, GenericFutureListener > listener) + { + if (this.isChannelOpen()) + { + this.flushOutboundQueue(); + this.dispatchPacket(packetIn, new GenericFutureListener[] {listener}); + } + else + { + this.readWriteLock.writeLock().lock(); + + try + { + this.outboundPacketsQueue.add(new NetConnection.InboundHandlerTuplePacketListener(packetIn, listener)); + } + finally + { + this.readWriteLock.writeLock().unlock(); + } + } + } + + /** + * Will commit the packet to the channel. If the current thread 'owns' the channel it will write and flush the + * packet, otherwise it will add a task for the channel eventloop thread to do that. + */ + private void dispatchPacket(final Packet inPacket, final GenericFutureListener > [] futureListeners) + { + final PacketRegistry enumconnectionstate = PacketRegistry.getType(inPacket); + final PacketRegistry enumconnectionstate1 = (PacketRegistry)this.channel.attr(ATTR_STATE).get(); + + if (enumconnectionstate1 != enumconnectionstate) + { +// Log.debug("Automatisches Lesen ausgeschaltet"); + this.channel.config().setAutoRead(false); + } + + if (this.channel.eventLoop().inEventLoop()) + { + if (enumconnectionstate != enumconnectionstate1) + { + this.setConnectionState(enumconnectionstate); + } + + ChannelFuture channelfuture = this.channel.writeAndFlush(inPacket); + + if (futureListeners != null) + { + channelfuture.addListeners(futureListeners); + } + + channelfuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + } + else + { + this.channel.eventLoop().execute(new Runnable() + { + public void run() + { + if (enumconnectionstate != enumconnectionstate1) + { + NetConnection.this.setConnectionState(enumconnectionstate); + } + + ChannelFuture channelfuture1 = NetConnection.this.channel.writeAndFlush(inPacket); + + if (futureListeners != null) + { + channelfuture1.addListeners(futureListeners); + } + + channelfuture1.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + } + }); + } + } + + /** + * Will iterate through the outboundPacketQueue and dispatch all Packets + */ + private void flushOutboundQueue() + { + if (this.channel != null && this.channel.isOpen()) + { + this.readWriteLock.readLock().lock(); + + try + { + while (!this.outboundPacketsQueue.isEmpty()) + { + NetConnection.InboundHandlerTuplePacketListener networkmanager$inboundhandlertuplepacketlistener = (NetConnection.InboundHandlerTuplePacketListener)this.outboundPacketsQueue.poll(); + if(networkmanager$inboundhandlertuplepacketlistener != null) { // NPE Fix + this.dispatchPacket(networkmanager$inboundhandlertuplepacketlistener.packet, networkmanager$inboundhandlertuplepacketlistener.futureListeners); + } + } + } + finally + { + this.readWriteLock.readLock().unlock(); + } + } + } + + /** + * Checks timeouts and processes all packets received + */ + public void processReceivedPackets() + { + this.flushOutboundQueue(); + this.packetListener.update(); +// if (this.packetListener instanceof ITickable) +// { +// ((ITickable)this.packetListener).update(); +// } + if(this.channel != null) + this.channel.flush(); + } + +// /** +// * Returns the socket address of the remote side. Server-only. +// */ +// public SocketAddress getRemoteAddress() +// { +// return this.socketAddress; +// } + + public String getCutAddress() { + return this.socketAddress == null ? "?.?.*.*" : IP_REPLACER.matcher(this.socketAddress.toString()).replaceAll("$1.$2.*.*"); + } + + /** + * Closes the channel, the parameter can be used for an exit message (not certain how it gets sent) + */ + public void closeChannel(String message) + { + if (this.channel.isOpen()) + { + this.channel.close().awaitUninterruptibly(); + this.terminationReason = message; + } + } + + public boolean isChannelOpen() + { + return this.channel != null && this.channel.isOpen(); + } + + public boolean hasNoChannel() + { + return this.channel == null; + } + + /** + * Gets the current handler for processing packets + */ + public NetHandler getNetHandler() + { + return this.packetListener; + } + + /** + * Switches the channel to manual reading modus + */ + public void disableAutoRead() + { + this.channel.config().setAutoRead(false); + } + + public void setCompressionTreshold(int treshold) + { + if (treshold >= 0) + { + if (this.channel.pipeline().get("decompress") instanceof NettyCompressionDecoder) + { + ((NettyCompressionDecoder)this.channel.pipeline().get("decompress")).setCompressionTreshold(treshold); + } + else + { + this.channel.pipeline().addBefore("decoder", "decompress", new NettyCompressionDecoder(treshold)); + } + + if (this.channel.pipeline().get("compress") instanceof NettyCompressionEncoder) + { + ((NettyCompressionEncoder)this.channel.pipeline().get("compress")).setCompressionTreshold(treshold); + } + else + { + this.channel.pipeline().addBefore("encoder", "compress", new NettyCompressionEncoder(treshold)); + } + } + else + { + if (this.channel.pipeline().get("decompress") instanceof NettyCompressionDecoder) + { + this.channel.pipeline().remove("decompress"); + } + + if (this.channel.pipeline().get("compress") instanceof NettyCompressionEncoder) + { + this.channel.pipeline().remove("compress"); + } + } + } + + public void checkDisconnected() + { + if (this.channel != null && !this.channel.isOpen()) + { + if (!this.disconnected) + { + this.disconnected = true; + + if (this.terminationReason != null) + { + this.getNetHandler().onDisconnect(this.terminationReason); + } + else if (this.getNetHandler() != null) + { + this.getNetHandler().onDisconnect("Verbindung getrennt"); + } + } + else + { + Log.JNI.warn("handleDisconnection() zweifach aufgerufen"); + } + } + } + + public void startEncryption(SecretKey key) { + this.channel.pipeline().addBefore("splitter", "decrypt", new NettyEncryptionDecoder(EncryptUtil.createCipher(Cipher.DECRYPT_MODE, key))); + this.channel.pipeline().addBefore("prepender", "encrypt", new NettyEncryptionEncoder(EncryptUtil.createCipher(Cipher.ENCRYPT_MODE, key))); + } + + static class InboundHandlerTuplePacketListener + { + private final Packet packet; + private final GenericFutureListener > [] futureListeners; + + public InboundHandlerTuplePacketListener(Packet inPacket, GenericFutureListener > inFutureListener) + { + this.packet = inPacket; + this.futureListeners = inFutureListener == null ? null : new GenericFutureListener[] {inFutureListener}; + } + } +} diff --git a/common/src/main/java/common/network/NetHandler.java b/common/src/common/network/NetHandler.java similarity index 58% rename from common/src/main/java/common/network/NetHandler.java rename to common/src/common/network/NetHandler.java index 2d8808b..1454ec5 100755 --- a/common/src/main/java/common/network/NetHandler.java +++ b/common/src/common/network/NetHandler.java @@ -1,9 +1,9 @@ package common.network; -public interface NetHandler { +public abstract class NetHandler { + private static final ThreadQuickExitException EXIT = new ThreadQuickExitException(); + public static final class ThreadQuickExitException extends RuntimeException { - private static final ThreadQuickExitException EXIT = new ThreadQuickExitException(); - private ThreadQuickExitException() { this.setStackTrace(new StackTraceElement[0]); } @@ -14,25 +14,28 @@ public interface NetHandler { } } - void onDisconnect(String reason); + public abstract void onDisconnect(String reason); - default void update() { + public void update() { } - public static void checkThread(final Packet packet, final T handler, IThreadListener listener) throws ThreadQuickExitException { + public static void checkThread(final Packet packet, final T handler, IThreadListener listener) + throws ThreadQuickExitException { if(!listener.isMainThread()) { listener.schedule(new Runnable() { public void run() { packet.processPacket(handler); } }); - throw ThreadQuickExitException.EXIT; + throw EXIT; } } - public static void checkThread(final Packet packet, final T handler, IThreadListener listener, Object check) throws ThreadQuickExitException { - if(check == null && listener.isMainThread()) - throw ThreadQuickExitException.EXIT; + public static void checkThread(final Packet packet, final T handler, IThreadListener listener, Object check) + throws ThreadQuickExitException { + if(check == null && listener.isMainThread()) { + throw EXIT; + } checkThread(packet, handler, listener); } } diff --git a/common/src/common/network/NettyCompressionDecoder.java b/common/src/common/network/NettyCompressionDecoder.java new file mode 100755 index 0000000..d77de45 --- /dev/null +++ b/common/src/common/network/NettyCompressionDecoder.java @@ -0,0 +1,62 @@ +package common.network; + +import java.util.List; +import java.util.zip.DataFormatException; +import java.util.zip.Inflater; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; +import io.netty.handler.codec.DecoderException; + +public class NettyCompressionDecoder extends ByteToMessageDecoder +{ + private final Inflater inflater; + private int treshold; + + public NettyCompressionDecoder(int treshold) + { + this.treshold = treshold; + this.inflater = new Inflater(); + } + + protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List p_decode_3_) throws DataFormatException, Exception + { + if (p_decode_2_.readableBytes() != 0) + { + PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_); + int i = packetbuffer.readVarIntFromBuffer(); + + if (i == 0) + { + p_decode_3_.add(packetbuffer.readBytes(packetbuffer.readableBytes())); + } + else + { + if (i < this.treshold) + { + throw new DecoderException("Badly compressed packet - size of " + i + " is below server threshold of " + this.treshold); + } + + if (i > 2097152) + { + throw new DecoderException("Badly compressed packet - size of " + i + " is larger than protocol maximum of " + 2097152); + } + + byte[] abyte = new byte[packetbuffer.readableBytes()]; + packetbuffer.readBytes(abyte); + this.inflater.setInput(abyte); + byte[] abyte1 = new byte[i]; + this.inflater.inflate(abyte1); + p_decode_3_.add(Unpooled.wrappedBuffer(abyte1)); + this.inflater.reset(); + } + } + } + + public void setCompressionTreshold(int treshold) + { + this.treshold = treshold; + } +} diff --git a/common/src/common/network/NettyCompressionEncoder.java b/common/src/common/network/NettyCompressionEncoder.java new file mode 100755 index 0000000..9719f99 --- /dev/null +++ b/common/src/common/network/NettyCompressionEncoder.java @@ -0,0 +1,53 @@ +package common.network; + +import java.util.zip.Deflater; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToByteEncoder; + +public class NettyCompressionEncoder extends MessageToByteEncoder +{ + private final byte[] buffer = new byte[8192]; + private final Deflater deflater; + private int treshold; + + public NettyCompressionEncoder(int treshold) + { + this.treshold = treshold; + this.deflater = new Deflater(); + } + + protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception + { + int i = p_encode_2_.readableBytes(); + PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_); + + if (i < this.treshold) + { + packetbuffer.writeVarIntToBuffer(0); + packetbuffer.writeBytes(p_encode_2_); + } + else + { + byte[] abyte = new byte[i]; + p_encode_2_.readBytes(abyte); + packetbuffer.writeVarIntToBuffer(abyte.length); + this.deflater.setInput(abyte, 0, i); + this.deflater.finish(); + + while (!this.deflater.finished()) + { + int j = this.deflater.deflate(this.buffer); + packetbuffer.writeBytes((byte[])this.buffer, 0, j); + } + + this.deflater.reset(); + } + } + + public void setCompressionTreshold(int treshold) + { + this.treshold = treshold; + } +} diff --git a/common/src/common/network/NettyEncryptionDecoder.java b/common/src/common/network/NettyEncryptionDecoder.java new file mode 100644 index 0000000..dac5156 --- /dev/null +++ b/common/src/common/network/NettyEncryptionDecoder.java @@ -0,0 +1,20 @@ +package common.network; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToMessageDecoder; +import java.util.List; +import javax.crypto.Cipher; +import javax.crypto.ShortBufferException; + +public class NettyEncryptionDecoder extends MessageToMessageDecoder { + private final EncryptionCodec codec; + + public NettyEncryptionDecoder(Cipher cipher) { + this.codec = new EncryptionCodec(cipher); + } + + protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List p_decode_3_) throws ShortBufferException, Exception { + p_decode_3_.add(this.codec.decipher(p_decode_1_, p_decode_2_)); + } +} diff --git a/common/src/common/network/NettyEncryptionEncoder.java b/common/src/common/network/NettyEncryptionEncoder.java new file mode 100644 index 0000000..0ec56f2 --- /dev/null +++ b/common/src/common/network/NettyEncryptionEncoder.java @@ -0,0 +1,19 @@ +package common.network; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToByteEncoder; +import javax.crypto.Cipher; +import javax.crypto.ShortBufferException; + +public class NettyEncryptionEncoder extends MessageToByteEncoder { + private final EncryptionCodec codec; + + public NettyEncryptionEncoder(Cipher cipher) { + this.codec = new EncryptionCodec(cipher); + } + + protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws ShortBufferException, Exception { + this.codec.cipher(p_encode_2_, p_encode_3_); + } +} diff --git a/common/src/main/java/common/network/Packet.java b/common/src/common/network/Packet.java similarity index 88% rename from common/src/main/java/common/network/Packet.java rename to common/src/common/network/Packet.java index bc9c9d9..4ba381f 100755 --- a/common/src/main/java/common/network/Packet.java +++ b/common/src/common/network/Packet.java @@ -2,7 +2,8 @@ package common.network; import java.io.IOException; -public interface Packet { +public interface Packet +{ void readPacketData(PacketBuffer buf) throws IOException; void writePacketData(PacketBuffer buf) throws IOException; void processPacket(T handler); diff --git a/common/src/common/network/PacketBuffer.java b/common/src/common/network/PacketBuffer.java new file mode 100755 index 0000000..390c141 --- /dev/null +++ b/common/src/common/network/PacketBuffer.java @@ -0,0 +1,463 @@ +package common.network; + +import java.io.IOException; +import java.nio.charset.Charset; + +import common.init.ItemRegistry; +import common.item.ItemStack; +import common.nbt.NBTLoader; +import common.nbt.NBTSizeTracker; +import common.nbt.NBTTagCompound; +import common.util.BlockPos; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufInputStream; +import io.netty.buffer.ByteBufOutputStream; +import io.netty.handler.codec.DecoderException; +import io.netty.handler.codec.EncoderException; + +public class PacketBuffer +{ + private static final Charset UTF_8 = Charset.forName("UTF-8"); + + private final ByteBuf buf; + + public PacketBuffer(ByteBuf wrapped) + { + this.buf = wrapped; + } + + /** + * Calculates the number of bytes required to fit the supplied int (0-5) if it were to be read/written using + * readVarIntFromBuffer or writeVarIntToBuffer + */ + public static int getVarIntSize(int input) + { + for (int i = 1; i < 5; ++i) + { + if ((input & -1 << i * 7) == 0) + { + return i; + } + } + + return 5; + } + + public void writeByteArray(byte[] array) + { + this.writeVarIntToBuffer(array.length); + this.writeBytes(array); + } + + public byte[] readByteArray() + { + byte[] abyte = new byte[this.readVarIntFromBuffer()]; + this.readBytes(abyte); + return abyte; + } + + public BlockPos readBlockPos() + { + return new BlockPos(this.readInt(), this.readInt(), this.readInt()); + } + + public void writeBlockPos(BlockPos pos) + { + this.writeInt(pos.getX()); + this.writeInt(pos.getY()); + this.writeInt(pos.getZ()); + } + +// public Text readChatComponent() throws IOException +// { +// return Text.toComponent(this.readNBTTagCompoundFromBuffer()); +// } +// +// public void writeChatComponent(Text component) throws IOException +// { +// this.writeNBTTagCompoundToBuffer(Text.toNbt(component)); +//// String s = ; +//// if(s.length() > 32767) { +//// s = component.getFormattedText(); +//// s = s.length() > 32720 ? s.substring(0, 32720) : s; +//// s = TextSerializer.toNbt(new TextComponent(s + ChatFormat.GRAY + ChatFormat.ITALIC + " [...]")); +//// } +//// this.writeString(s); +// } + + public > T readEnumValue(Class enumClass) + { + return (T)((Enum[])enumClass.getEnumConstants())[this.readVarIntFromBuffer()]; + } + + public > T readEnumOrNull(Class enumClass) + { + int n = this.readVarIntFromBuffer(); + return n < 0 ? null : (T)((Enum[])enumClass.getEnumConstants())[n]; + } + + public void writeEnumValue(Enum value) + { + this.writeVarIntToBuffer(value.ordinal()); + } + + public void writeEnumOrNull(Enum value) + { + this.writeVarIntToBuffer(value == null ? -1 : value.ordinal()); + } + + /** + * Reads a compressed int from the buffer. To do so it maximally reads 5 byte-sized chunks whose most significant + * bit dictates whether another byte should be read. + */ + public int readVarIntFromBuffer() + { + int i = 0; + int j = 0; + + while (true) + { + byte b0 = this.readByte(); + i |= (b0 & 127) << j++ * 7; + + if (j > 5) + { + throw new RuntimeException("VarInt too big"); + } + + if ((b0 & 128) != 128) + { + break; + } + } + + return i; + } + + public long readVarLong() + { + long i = 0L; + int j = 0; + + while (true) + { + byte b0 = this.readByte(); + i |= (long)(b0 & 127) << j++ * 7; + + if (j > 10) + { + throw new RuntimeException("VarLong too big"); + } + + if ((b0 & 128) != 128) + { + break; + } + } + + return i; + } + +// public void writeUuid(UUID uuid) +// { +// this.writeLong(uuid.getMostSignificantBits()); +// this.writeLong(uuid.getLeastSignificantBits()); +// } +// +// public UUID readUuid() +// { +// return new UUID(this.readLong(), this.readLong()); +// } + + /** + * Writes a compressed int to the buffer. The smallest number of bytes to fit the passed int will be written. Of + * each such byte only 7 bits will be used to describe the actual value since its most significant bit dictates + * whether the next byte is part of that same int. Micro-optimization for int values that are expected to have + * values below 128. + */ + public void writeVarIntToBuffer(int input) + { + while ((input & -128) != 0) + { + this.writeByte(input & 127 | 128); + input >>>= 7; + } + + this.writeByte(input); + } + + public void writeVarLong(long value) + { + while ((value & -128L) != 0L) + { + this.writeByte((int)(value & 127L) | 128); + value >>>= 7; + } + + this.writeByte((int)value); + } + + /** + * Writes a compressed NBTTagCompound to this buffer + */ + public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt) + { + if (nbt == null) + { + this.writeByte(0); + } + else + { + try + { + NBTLoader.write(nbt, new ByteBufOutputStream(this.buf)); + } + catch (IOException ioexception) + { + throw new EncoderException(ioexception); + } + } + } + + /** + * Reads a compressed NBTTagCompound from this buffer + */ + public NBTTagCompound readNBTTagCompoundFromBuffer() throws IOException + { + int i = this.buf.readerIndex(); + byte b0 = this.readByte(); + + if (b0 == 0) + { + return null; + } + else + { + this.buf.readerIndex(i); + return NBTLoader.read(new ByteBufInputStream(this.buf), new NBTSizeTracker(2097152L)); + } + } + + /** + * Writes the ItemStack's ID (short), then size (byte), then damage. (short) + */ + public void writeItemStackToBuffer(ItemStack stack) + { + if (stack == null) + { + this.writeShort(-1); + } + else + { + this.writeShort(ItemRegistry.getIdFromItem(stack.getItem())); + this.writeVarIntToBuffer(stack.stackSize); + this.writeShort(stack.getMetadata()); + NBTTagCompound nbttagcompound = null; + + if (stack.getItem().isDamageable() || stack.getItem().getShareTag()) + { + nbttagcompound = stack.getTagCompound(); + } + + this.writeNBTTagCompoundToBuffer(nbttagcompound); + } + } + + /** + * Reads an ItemStack from this buffer + */ + public ItemStack readItemStackFromBuffer() throws IOException + { + ItemStack itemstack = null; + int i = this.readShort(); + + if (i >= 0) + { + int j = this.readVarIntFromBuffer(); + int k = this.readShort(); + itemstack = new ItemStack(ItemRegistry.getItemById(i), j, k); + itemstack.setTagCompound(this.readNBTTagCompoundFromBuffer()); + } + + return itemstack; + } + + /** + * Reads a string from this buffer. Expected parameter is maximum allowed string length. Will throw IOException if + * string length exceeds this value! + */ + public String readStringFromBuffer(int maxLength) + { + int i = this.readVarIntFromBuffer(); + + if (i > maxLength * 4) + { + throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + i + " > " + maxLength * 4 + ")"); + } + else if (i < 0) + { + throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!"); + } + else + { + byte[] abyte = new byte[i]; + this.readBytes(abyte); + String s = new String(abyte, UTF_8); // this.readBytes(i).array() + + if (s.length() > maxLength) + { + throw new DecoderException("The received string length is longer than maximum allowed (" + i + " > " + maxLength + ")"); + } + else + { + return s; + } + } + } + + public PacketBuffer writeString(String string) + { + byte[] abyte = string.getBytes(UTF_8); + + if (abyte.length > 32767) + { + throw new EncoderException("String too big (was " + string.length() + " bytes encoded, max " + 32767 + ")"); + } + else + { + this.writeVarIntToBuffer(abyte.length); + this.writeBytes(abyte); + return this; + } + } + + public int readableBytes() + { + return this.buf.readableBytes(); + } + + public ByteBuf ensureWritable(int p_ensureWritable_1_) + { + return this.buf.ensureWritable(p_ensureWritable_1_); + } + + public boolean readBoolean() + { + return this.buf.readBoolean(); + } + + public byte readByte() + { + return this.buf.readByte(); + } + + public short readUnsignedByte() + { + return this.buf.readUnsignedByte(); + } + + public short readShort() + { + return this.buf.readShort(); + } + + public int readUnsignedShort() + { + return this.buf.readUnsignedShort(); + } + + public int readInt() + { + return this.buf.readInt(); + } + + public long readUnsignedInt() + { + return this.buf.readUnsignedInt(); + } + + public long readLong() + { + return this.buf.readLong(); + } + + public float readFloat() + { + return this.buf.readFloat(); + } + + public double readDouble() + { + return this.buf.readDouble(); + } + + public ByteBuf readBytes(int p_readBytes_1_) + { + return this.buf.readBytes(p_readBytes_1_); + } + + public ByteBuf readBytes(byte[] p_readBytes_1_) + { + return this.buf.readBytes(p_readBytes_1_); + } + + public ByteBuf writeBoolean(boolean p_writeBoolean_1_) + { + return this.buf.writeBoolean(p_writeBoolean_1_); + } + + public ByteBuf writeByte(int p_writeByte_1_) + { + return this.buf.writeByte(p_writeByte_1_); + } + + public ByteBuf writeShort(int p_writeShort_1_) + { + return this.buf.writeShort(p_writeShort_1_); + } + + public ByteBuf writeInt(int p_writeInt_1_) + { + return this.buf.writeInt(p_writeInt_1_); + } + + public ByteBuf writeLong(long p_writeLong_1_) + { + return this.buf.writeLong(p_writeLong_1_); + } + + public ByteBuf writeFloat(float p_writeFloat_1_) + { + return this.buf.writeFloat(p_writeFloat_1_); + } + + public ByteBuf writeDouble(double p_writeDouble_1_) + { + return this.buf.writeDouble(p_writeDouble_1_); + } + + public ByteBuf writeBytes(ByteBuf p_writeBytes_1_) + { + return this.buf.writeBytes(p_writeBytes_1_); + } + + public ByteBuf writeBytes(ByteBuf p_writeBytes_1_, int p_writeBytes_2_, int p_writeBytes_3_) + { + return this.buf.writeBytes(p_writeBytes_1_, p_writeBytes_2_, p_writeBytes_3_); + } + + public ByteBuf writeBytes(byte[] p_writeBytes_1_) + { + return this.buf.writeBytes(p_writeBytes_1_); + } + + public ByteBuf writeBytes(byte[] p_writeBytes_1_, int p_writeBytes_2_, int p_writeBytes_3_) + { + return this.buf.writeBytes(p_writeBytes_1_, p_writeBytes_2_, p_writeBytes_3_); + } + + public boolean release() + { + return this.buf.release(); + } +} diff --git a/common/src/common/network/PacketDecoder.java b/common/src/common/network/PacketDecoder.java new file mode 100755 index 0000000..e00089d --- /dev/null +++ b/common/src/common/network/PacketDecoder.java @@ -0,0 +1,51 @@ +package common.network; + +import java.io.IOException; +import java.util.List; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; + +public class PacketDecoder extends ByteToMessageDecoder +{ + private final boolean client; + + public PacketDecoder(boolean client) + { + this.client = client; + } + + protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List p_decode_3_) throws IOException, InstantiationException, IllegalAccessException, Exception + { + if (p_decode_2_.readableBytes() != 0) + { + PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_); + int i = packetbuffer.readVarIntFromBuffer(); + Packet packet = ((PacketRegistry)p_decode_1_.channel().attr(NetConnection.ATTR_STATE).get()).getPacket(this.client, i); + + if (packet == null) + { + throw new IOException("Ungültige Paket-ID " + i); + } + else + { + packet.readPacketData(packetbuffer); + + if (packetbuffer.readableBytes() > 0) + { + throw new IOException("Paket " + ((PacketRegistry)p_decode_1_.channel().attr(NetConnection.ATTR_STATE).get()).ordinal() + "/" + i + " (" + packet.getClass() + ") war größer als erwartet, " + packetbuffer.readableBytes() + " weitere Bytes wurden beim Lesen von Paket " + i + " gefunden"); + } + else + { + p_decode_3_.add(packet); + +// if (Log.isTraceEnabled()) +// { +// Log.SYSTEM.info("EIN: [" + p_decode_1_.channel().attr(NetConnection.ATTR_STATE).get() + ":" + i + "] " + packet.getClass().getName()); +// } + } + } + } + } +} diff --git a/common/src/common/network/PacketEncoder.java b/common/src/common/network/PacketEncoder.java new file mode 100755 index 0000000..ff7cdbf --- /dev/null +++ b/common/src/common/network/PacketEncoder.java @@ -0,0 +1,47 @@ +package common.network; + +import java.io.IOException; + +import common.log.Log; +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToByteEncoder; + +public class PacketEncoder extends MessageToByteEncoder +{ + private final boolean client; + + public PacketEncoder(boolean client) + { + this.client = client; + } + + protected void encode(ChannelHandlerContext p_encode_1_, Packet p_encode_2_, ByteBuf p_encode_3_) throws IOException, Exception + { + Integer integer = ((PacketRegistry)p_encode_1_.channel().attr(NetConnection.ATTR_STATE).get()).getId(this.client, p_encode_2_); + +// if (Log.isTraceEnabled()) +// { +// Log.debug("AUS: [" + p_encode_1_.channel().attr(NetConnection.ATTR_STATE).get() + ":" + integer + "] " + p_encode_2_.getClass().getName()); +// } + + if (integer == null) + { + throw new IOException("Kann nicht registriertes Paket nicht serialisieren"); + } + else + { + PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_); + packetbuffer.writeVarIntToBuffer(integer.intValue()); + + try + { + p_encode_2_.writePacketData(packetbuffer); + } + catch (Throwable throwable) + { + Log.JNI.error(throwable, "Fehler beim Schreiben der Paketdaten"); + } + } + } +} diff --git a/common/src/common/network/PacketPrepender.java b/common/src/common/network/PacketPrepender.java new file mode 100755 index 0000000..670f337 --- /dev/null +++ b/common/src/common/network/PacketPrepender.java @@ -0,0 +1,26 @@ +package common.network; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToByteEncoder; + +public class PacketPrepender extends MessageToByteEncoder +{ + protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception + { + int i = p_encode_2_.readableBytes(); + int j = PacketBuffer.getVarIntSize(i); + + if (j > 3) + { + throw new IllegalArgumentException("unable to fit " + i + " into " + 3); + } + else + { + PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_); + packetbuffer.ensureWritable(j + i); + packetbuffer.writeVarIntToBuffer(i); + packetbuffer.writeBytes(p_encode_2_, p_encode_2_.readerIndex(), i); + } + } +} diff --git a/common/src/common/network/PacketRegistry.java b/common/src/common/network/PacketRegistry.java new file mode 100755 index 0000000..d905ace --- /dev/null +++ b/common/src/common/network/PacketRegistry.java @@ -0,0 +1,263 @@ +package common.network; + +import java.util.Map; + +import common.collect.BiMap; +import common.collect.HashBiMap; +import common.collect.Maps; +import common.packet.CPacketAction; +import common.packet.CPacketBook; +import common.packet.CPacketBreak; +import common.packet.CPacketCheat; +import common.packet.CPacketClick; +import common.packet.CPacketComplete; +import common.packet.CPacketForm; +import common.packet.CPacketInput; +import common.packet.CPacketKeepAlive; +import common.packet.CPacketMessage; +import common.packet.CPacketPlace; +import common.packet.CPacketPlayer; +import common.packet.CPacketSign; +import common.packet.CPacketSkin; +import common.packet.HPacketHandshake; +import common.packet.LPacketLogin; +import common.packet.LPacketPasswordResponse; +import common.packet.LPacketStartEncrypt; +import common.packet.RPacketDisconnect; +import common.packet.RPacketEnableCompression; +import common.packet.RPacketLoginSuccess; +import common.packet.RPacketRequestEncrypt; +import common.packet.S14PacketEntity; +import common.packet.S18PacketEntityTeleport; +import common.packet.S19PacketEntityHeadLook; +import common.packet.S1APacketEntityStatus; +import common.packet.S1BPacketEntityAttach; +import common.packet.S1CPacketEntityMetadata; +import common.packet.S1DPacketEntityEffect; +import common.packet.S1EPacketRemoveEntityEffect; +import common.packet.S20PacketEntityProperties; +import common.packet.S27PacketExplosion; +import common.packet.S28PacketEffect; +import common.packet.S29PacketSoundEffect; +import common.packet.S2APacketParticles; +import common.packet.S2BPacketChangeGameState; +import common.packet.S2CPacketSpawnGlobalEntity; +import common.packet.S2DPacketOpenWindow; +import common.packet.S2EPacketCloseWindow; +import common.packet.S2FPacketSetSlot; +import common.packet.S30PacketWindowItems; +import common.packet.S31PacketWindowProperty; +import common.packet.S32PacketConfirmTransaction; +import common.packet.S33PacketUpdateSign; +import common.packet.S35PacketUpdateTileEntity; +import common.packet.S36PacketSignEditorOpen; +import common.packet.S38PacketPlayerListItem; +import common.packet.S39PacketPlayerAbilities; +import common.packet.S3APacketTabComplete; +import common.packet.S43PacketUpdateEntityNBT; +import common.packet.SPacketAnimation; +import common.packet.SPacketBlockAction; +import common.packet.SPacketBlockBreakAnim; +import common.packet.SPacketBlockChange; +import common.packet.SPacketCamera; +import common.packet.SPacketCharacterList; +import common.packet.SPacketChunkData; +import common.packet.SPacketCollectItem; +import common.packet.SPacketDestroyEntities; +import common.packet.SPacketDimensionName; +import common.packet.SPacketDisconnect; +import common.packet.SPacketDisplayForm; +import common.packet.SPacketEntityEquipment; +import common.packet.SPacketEntityVelocity; +import common.packet.SPacketHeldItemChange; +import common.packet.SPacketJoinGame; +import common.packet.SPacketKeepAlive; +import common.packet.SPacketLoading; +import common.packet.SPacketMapChunkBulk; +import common.packet.SPacketMessage; +import common.packet.SPacketMultiBlockChange; +import common.packet.SPacketPlayerPosLook; +import common.packet.SPacketRespawn; +import common.packet.SPacketServerTick; +import common.packet.SPacketSetExperience; +import common.packet.SPacketSkin; +import common.packet.SPacketSpawnMob; +import common.packet.SPacketSpawnObject; +import common.packet.SPacketSpawnPlayer; +import common.packet.SPacketTimeUpdate; +import common.packet.SPacketTrades; +import common.packet.SPacketUpdateHealth; +import common.packet.SPacketWorld; + +public enum PacketRegistry +{ + HANDSHAKE + { + { + this.client(HPacketHandshake.class); + } + }, + LOGIN + { + { + this.server(RPacketDisconnect.class); + this.server(RPacketRequestEncrypt.class); + this.server(RPacketLoginSuccess.class); + this.server(RPacketEnableCompression.class); + this.client(LPacketLogin.class); + this.client(LPacketStartEncrypt.class); + this.client(LPacketPasswordResponse.class); + } + }, + PLAY + { + { + this.server(SPacketKeepAlive.class); + this.server(SPacketJoinGame.class); + this.server(SPacketMessage.class); +// this.server(SPacketMessage.class); + this.server(SPacketTimeUpdate.class); + this.server(SPacketEntityEquipment.class); + this.server(SPacketUpdateHealth.class); + this.server(SPacketRespawn.class); + this.server(SPacketPlayerPosLook.class); + this.server(SPacketHeldItemChange.class); + this.server(SPacketAnimation.class); + this.server(SPacketSpawnPlayer.class); + this.server(SPacketCollectItem.class); + this.server(SPacketSpawnObject.class); + this.server(SPacketSpawnMob.class); +// this.server(SPacketSpawnPainting.class); +// this.server(SPacketSpawnExperienceOrb.class); + this.server(SPacketEntityVelocity.class); + this.server(SPacketDestroyEntities.class); + this.server(S14PacketEntity.class); + this.server(S14PacketEntity.S15PacketEntityRelMove.class); + this.server(S14PacketEntity.S16PacketEntityLook.class); + this.server(S14PacketEntity.S17PacketEntityLookMove.class); + this.server(S18PacketEntityTeleport.class); + this.server(S19PacketEntityHeadLook.class); + this.server(S1APacketEntityStatus.class); + this.server(S1BPacketEntityAttach.class); + this.server(S1CPacketEntityMetadata.class); + this.server(S1DPacketEntityEffect.class); + this.server(S1EPacketRemoveEntityEffect.class); + this.server(SPacketSetExperience.class); + this.server(S20PacketEntityProperties.class); + this.server(SPacketChunkData.class); + this.server(SPacketMultiBlockChange.class); + this.server(SPacketBlockChange.class); + this.server(SPacketBlockAction.class); + this.server(SPacketBlockBreakAnim.class); + this.server(SPacketMapChunkBulk.class); + this.server(S27PacketExplosion.class); + this.server(S28PacketEffect.class); + this.server(S29PacketSoundEffect.class); + this.server(S2APacketParticles.class); + this.server(S2BPacketChangeGameState.class); + this.server(S2CPacketSpawnGlobalEntity.class); + this.server(S2DPacketOpenWindow.class); + this.server(S2EPacketCloseWindow.class); + this.server(S2FPacketSetSlot.class); + this.server(S30PacketWindowItems.class); + this.server(S31PacketWindowProperty.class); + this.server(S32PacketConfirmTransaction.class); + this.server(S33PacketUpdateSign.class); +// this.server(S34PacketMaps.class); + this.server(S35PacketUpdateTileEntity.class); + this.server(S36PacketSignEditorOpen.class); +// this.server(S37PacketStatistics.class); + this.server(S38PacketPlayerListItem.class); + this.server(S39PacketPlayerAbilities.class); + this.server(S3APacketTabComplete.class); +// this.server(SPacketDisplay.class); + this.server(SPacketSkin.class); + this.server(SPacketDisconnect.class); + this.server(SPacketWorld.class); +// this.server(SPacketCapes.class); + this.server(SPacketCamera.class); +// this.server(S42PacketTitle.class); + this.server(S43PacketUpdateEntityNBT.class); +// this.server(SPacketBook.class); + this.server(SPacketTrades.class); +// this.server(SPacketNotify.class); + this.server(SPacketDimensionName.class); + this.server(SPacketCharacterList.class); + this.server(SPacketServerTick.class); + this.server(SPacketLoading.class); + this.server(SPacketDisplayForm.class); + + this.client(CPacketKeepAlive.class); + this.client(CPacketMessage.class); + this.client(CPacketAction.class); + this.client(CPacketPlayer.class); + this.client(CPacketPlayer.C04PacketPlayerPosition.class); + this.client(CPacketPlayer.C05PacketPlayerLook.class); + this.client(CPacketPlayer.C06PacketPlayerPosLook.class); + this.client(CPacketBreak.class); + this.client(CPacketPlace.class); + this.client(CPacketInput.class); + this.client(CPacketClick.class); + this.client(CPacketCheat.class); + this.client(CPacketComplete.class); + this.client(CPacketSkin.class); + this.client(CPacketSign.class); + this.client(CPacketBook.class); + this.client(CPacketForm.class); + } + }; + + private static final Map, PacketRegistry> STATES = Maps., PacketRegistry>newHashMap(); + + private final BiMap> server = HashBiMap.>create(); + private final BiMap> client = HashBiMap.>create(); + + protected void server(Class clazz) + { + if(this.server.containsValue(clazz)) + throw new IllegalArgumentException("S-Paket " + clazz + " ist bereits bekannt unter ID " + this.server.inverse().get(clazz)); + this.server.put(Integer.valueOf(this.server.size()), clazz); + } + + protected void client(Class clazz) + { + if(this.client.containsValue(clazz)) + throw new IllegalArgumentException("C-Paket " + clazz + " ist bereits bekannt unter ID " + this.client.inverse().get(clazz)); + this.client.put(Integer.valueOf(this.client.size()), clazz); + } + + public Integer getId(boolean client, Packet packet) + { + return (client ? this.client : this.server).inverse().get(packet.getClass()); + } + + public Packet getPacket(boolean client, int id) throws InstantiationException, IllegalAccessException { + Class oclass = (client ? this.client : this.server).get(id); + return oclass == null ? null : oclass.newInstance(); + } + + public static PacketRegistry getType(Packet packetIn) + { + return STATES.get(packetIn.getClass()); + } + + static { + for(PacketRegistry reg : values()) { + for(BiMap> map : new BiMap[] {reg.server, reg.client}) { + for(Class clazz : map.values()) { + if(STATES.containsKey(clazz) && STATES.get(clazz) != reg) { + throw new Error("Paket " + clazz + " ist bereits zu ID " + STATES.get(clazz) + + " zugewiesen - kann nicht auf " + reg + " neu zuweisen"); + } + try { + clazz.newInstance(); + } + catch(Throwable e) { + throw new Error("Paket " + clazz + " kann nicht instanziert werden!"); + } + STATES.put(clazz, reg); + } + } + } + } +} diff --git a/common/src/common/network/PacketSplitter.java b/common/src/common/network/PacketSplitter.java new file mode 100755 index 0000000..7540257 --- /dev/null +++ b/common/src/common/network/PacketSplitter.java @@ -0,0 +1,55 @@ +package common.network; + +import java.util.List; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; +import io.netty.handler.codec.CorruptedFrameException; + +public class PacketSplitter extends ByteToMessageDecoder +{ + protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List p_decode_3_) throws Exception + { + p_decode_2_.markReaderIndex(); + byte[] abyte = new byte[3]; + + for (int i = 0; i < abyte.length; ++i) + { + if (!p_decode_2_.isReadable()) + { + p_decode_2_.resetReaderIndex(); + return; + } + + abyte[i] = p_decode_2_.readByte(); + + if (abyte[i] >= 0) + { + PacketBuffer packetbuffer = new PacketBuffer(Unpooled.wrappedBuffer(abyte)); + + try + { + int j = packetbuffer.readVarIntFromBuffer(); + + if (p_decode_2_.readableBytes() >= j) + { + p_decode_3_.add(p_decode_2_.readBytes(j)); + return; + } + + p_decode_2_.resetReaderIndex(); + } + finally + { + packetbuffer.release(); + } + + return; + } + } + + throw new CorruptedFrameException("length wider than 21-bit"); + } +} diff --git a/common/src/main/java/common/packet/APacketVarInt.java b/common/src/common/packet/APacketVarInt.java similarity index 86% rename from common/src/main/java/common/packet/APacketVarInt.java rename to common/src/common/packet/APacketVarInt.java index f68d407..e3196af 100755 --- a/common/src/main/java/common/packet/APacketVarInt.java +++ b/common/src/common/packet/APacketVarInt.java @@ -16,11 +16,11 @@ public abstract class APacketVarInt implements Packet { } public final void readPacketData(PacketBuffer buf) throws IOException { - this.value = buf.readVarInt(); + this.value = buf.readVarIntFromBuffer(); } public final void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.value); + buf.writeVarIntToBuffer(this.value); } public final int getValue() { diff --git a/common/src/main/java/common/packet/CPacketAction.java b/common/src/common/packet/CPacketAction.java similarity index 95% rename from common/src/main/java/common/packet/CPacketAction.java rename to common/src/common/packet/CPacketAction.java index 9aceb60..1df60fb 100755 --- a/common/src/main/java/common/packet/CPacketAction.java +++ b/common/src/common/packet/CPacketAction.java @@ -29,13 +29,13 @@ public class CPacketAction implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.action = buf.readEnumValue(Action.class); - this.auxData = buf.readVarInt(); + this.auxData = buf.readVarIntFromBuffer(); } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeEnumValue(this.action); - buf.writeVarInt(this.auxData); + buf.writeVarIntToBuffer(this.auxData); } public void processPacket(IPlayer handler) @@ -57,7 +57,6 @@ public class CPacketAction implements Packet { OPEN_EDITOR, CLOSE_EDITOR, - CANCEL_EDITOR, SELECT_CHARACTER, DELETE_CHARACTER, SWING_ARM, diff --git a/common/src/common/packet/CPacketBook.java b/common/src/common/packet/CPacketBook.java new file mode 100755 index 0000000..771fa06 --- /dev/null +++ b/common/src/common/packet/CPacketBook.java @@ -0,0 +1,52 @@ +package common.packet; + +import java.io.IOException; + +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; + +public class CPacketBook implements Packet +{ + private String[] pages; + + public CPacketBook() + { + } + + public CPacketBook(String[] pages) + { + this.pages = pages; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + int pages = (int)buf.readByte(); + if(pages > 50) { + this.pages = new String[0]; + return; + } + this.pages = new String[pages]; + for(int z = 0; z < pages; z++) { + this.pages[z] = buf.readStringFromBuffer(1024); + } + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeByte(this.pages.length); + for(int z = 0; z < this.pages.length; z++) { + buf.writeString(this.pages[z]); + } + } + + public void processPacket(IPlayer handler) + { + handler.processBook(this); + } + + public String[] getPages() + { + return this.pages; + } +} diff --git a/common/src/main/java/common/packet/CPacketBreak.java b/common/src/common/packet/CPacketBreak.java similarity index 100% rename from common/src/main/java/common/packet/CPacketBreak.java rename to common/src/common/packet/CPacketBreak.java diff --git a/common/src/main/java/common/packet/CPacketCheat.java b/common/src/common/packet/CPacketCheat.java similarity index 84% rename from common/src/main/java/common/packet/CPacketCheat.java rename to common/src/common/packet/CPacketCheat.java index eb02559..f2b0715 100755 --- a/common/src/main/java/common/packet/CPacketCheat.java +++ b/common/src/common/packet/CPacketCheat.java @@ -20,7 +20,7 @@ public class CPacketCheat implements Packet { this.stack = stackIn.copy(); this.slot = slot; - this.stack.size = full ? this.stack.getMaxStackSize() : 1; + this.stack.stackSize = full ? this.stack.getMaxStackSize() : 1; } public void processPacket(IPlayer handler) @@ -30,13 +30,13 @@ public class CPacketCheat implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.stack = buf.readItemStack(); + this.stack = buf.readItemStackFromBuffer(); this.slot = buf.readByte(); } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeItemStack(this.stack); + buf.writeItemStackToBuffer(this.stack); buf.writeByte(this.slot); } diff --git a/common/src/main/java/common/packet/CPacketClick.java b/common/src/common/packet/CPacketClick.java similarity index 95% rename from common/src/main/java/common/packet/CPacketClick.java rename to common/src/common/packet/CPacketClick.java index efdf80f..cb4e282 100755 --- a/common/src/main/java/common/packet/CPacketClick.java +++ b/common/src/common/packet/CPacketClick.java @@ -53,7 +53,7 @@ public class CPacketClick implements Packet this.usedButton = buf.readByte(); this.actionNumber = buf.readShort(); this.mode = buf.readByte(); - this.clickedItem = buf.readItemStack(); + this.clickedItem = buf.readItemStackFromBuffer(); } public void writePacketData(PacketBuffer buf) throws IOException @@ -63,7 +63,7 @@ public class CPacketClick implements Packet buf.writeByte(this.usedButton); buf.writeShort(this.actionNumber); buf.writeByte(this.mode); - buf.writeItemStack(this.clickedItem); + buf.writeItemStackToBuffer(this.clickedItem); } public int getWindowId() diff --git a/common/src/main/java/common/packet/CPacketComplete.java b/common/src/common/packet/CPacketComplete.java similarity index 89% rename from common/src/main/java/common/packet/CPacketComplete.java rename to common/src/common/packet/CPacketComplete.java index 83fd0f0..31b0cc6 100755 --- a/common/src/main/java/common/packet/CPacketComplete.java +++ b/common/src/common/packet/CPacketComplete.java @@ -26,8 +26,8 @@ public class CPacketComplete implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.message = buf.readString(32767); - this.entityId = buf.readVarInt(); + this.message = buf.readStringFromBuffer(32767); + this.entityId = buf.readVarIntFromBuffer(); if(buf.readBoolean()) this.position = buf.readBlockPos(); } @@ -35,7 +35,7 @@ public class CPacketComplete implements Packet public void writePacketData(PacketBuffer buf) throws IOException { buf.writeString(this.message.length() > 32767 ? this.message.substring(0, 32767) : this.message); - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); buf.writeBoolean(this.position != null); if(this.position != null) buf.writeBlockPos(this.position); diff --git a/common/src/main/java/common/packet/CPacketForm.java b/common/src/common/packet/CPacketForm.java similarity index 83% rename from common/src/main/java/common/packet/CPacketForm.java rename to common/src/common/packet/CPacketForm.java index 5c9e5bf..136fccc 100644 --- a/common/src/main/java/common/packet/CPacketForm.java +++ b/common/src/common/packet/CPacketForm.java @@ -23,12 +23,12 @@ public class CPacketForm implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.id = buf.readVarInt(); + this.id = buf.readVarIntFromBuffer(); if(!buf.readBoolean()) { this.data = null; return; } - this.data = new Object[buf.readVarInt()]; + this.data = new Object[buf.readVarIntFromBuffer()]; for(int z = 0; z < this.data.length; z++) { Object obj; switch(buf.readByte()) { @@ -36,10 +36,10 @@ public class CPacketForm implements Packet obj = buf.readBoolean(); break; case 1: - obj = buf.readVarInt(); + obj = buf.readVarIntFromBuffer(); break; default: - obj = buf.readString(1024); + obj = buf.readStringFromBuffer(256); break; } this.data[z] = obj; @@ -48,11 +48,11 @@ public class CPacketForm implements Packet public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.id); + buf.writeVarIntToBuffer(this.id); buf.writeBoolean(this.data != null); if(this.data == null) return; - buf.writeVarInt(this.data.length); + buf.writeVarIntToBuffer(this.data.length); for(int z = 0; z < this.data.length; z++) { Object obj = this.data[z]; if(obj instanceof Boolean) { @@ -61,7 +61,7 @@ public class CPacketForm implements Packet } else if(obj instanceof Integer) { buf.writeByte(1); - buf.writeVarInt((Integer)obj); + buf.writeVarIntToBuffer((Integer)obj); } else { buf.writeByte(2); diff --git a/common/src/main/java/common/packet/CPacketInput.java b/common/src/common/packet/CPacketInput.java similarity index 100% rename from common/src/main/java/common/packet/CPacketInput.java rename to common/src/common/packet/CPacketInput.java diff --git a/common/src/main/java/common/packet/CPacketKeepAlive.java b/common/src/common/packet/CPacketKeepAlive.java similarity index 100% rename from common/src/main/java/common/packet/CPacketKeepAlive.java rename to common/src/common/packet/CPacketKeepAlive.java diff --git a/common/src/main/java/common/packet/CPacketMessage.java b/common/src/common/packet/CPacketMessage.java similarity index 95% rename from common/src/main/java/common/packet/CPacketMessage.java rename to common/src/common/packet/CPacketMessage.java index 3b34e2d..c7141ea 100755 --- a/common/src/main/java/common/packet/CPacketMessage.java +++ b/common/src/common/packet/CPacketMessage.java @@ -24,7 +24,7 @@ public class CPacketMessage implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.type = buf.readEnumValue(Type.class); - this.message = buf.readString(this.type.length); + this.message = buf.readStringFromBuffer(this.type.length); } public void writePacketData(PacketBuffer buf) throws IOException diff --git a/common/src/main/java/common/packet/CPacketPlace.java b/common/src/common/packet/CPacketPlace.java similarity index 96% rename from common/src/main/java/common/packet/CPacketPlace.java rename to common/src/common/packet/CPacketPlace.java index a2b8964..c082f6e 100755 --- a/common/src/main/java/common/packet/CPacketPlace.java +++ b/common/src/common/packet/CPacketPlace.java @@ -42,7 +42,7 @@ public class CPacketPlace implements Packet { this.position = buf.readBlockPos(); this.placedBlockDirection = buf.readUnsignedByte(); - this.stack = buf.readItemStack(); + this.stack = buf.readItemStackFromBuffer(); this.facingX = (float)buf.readUnsignedByte() / 16.0F; this.facingY = (float)buf.readUnsignedByte() / 16.0F; this.facingZ = (float)buf.readUnsignedByte() / 16.0F; @@ -52,7 +52,7 @@ public class CPacketPlace implements Packet { buf.writeBlockPos(this.position); buf.writeByte(this.placedBlockDirection); - buf.writeItemStack(this.stack); + buf.writeItemStackToBuffer(this.stack); buf.writeByte((int)(this.facingX * 16.0F)); buf.writeByte((int)(this.facingY * 16.0F)); buf.writeByte((int)(this.facingZ * 16.0F)); diff --git a/common/src/common/packet/CPacketPlayer.java b/common/src/common/packet/CPacketPlayer.java new file mode 100755 index 0000000..58c70e7 --- /dev/null +++ b/common/src/common/packet/CPacketPlayer.java @@ -0,0 +1,192 @@ +package common.packet; + +import java.io.IOException; + +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; + +public class CPacketPlayer implements Packet +{ + protected double x; + protected double y; + protected double z; + protected float yaw; + protected float pitch; + protected boolean onGround; + protected boolean moving; + protected boolean rotating; + + public CPacketPlayer() + { + } + + public CPacketPlayer(boolean isOnGround) + { + this.onGround = isOnGround; + } + + public void processPacket(IPlayer handler) + { + handler.processPlayer(this); + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + this.onGround = buf.readUnsignedByte() != 0; + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeByte(this.onGround ? 1 : 0); + } + + public double getPositionX() + { + return this.x; + } + + public double getPositionY() + { + return this.y; + } + + public double getPositionZ() + { + return this.z; + } + + public float getYaw() + { + return this.yaw; + } + + public float getPitch() + { + return this.pitch; + } + + public boolean isOnGround() + { + return this.onGround; + } + + public boolean isMoving() + { + return this.moving; + } + + public boolean getRotating() + { + return this.rotating; + } + + public void setMoving(boolean isMoving) + { + this.moving = isMoving; + } + + public static class C04PacketPlayerPosition extends CPacketPlayer + { + public C04PacketPlayerPosition() + { + this.moving = true; + } + + public C04PacketPlayerPosition(double posX, double posY, double posZ, boolean isOnGround) + { + this.x = posX; + this.y = posY; + this.z = posZ; + this.onGround = isOnGround; + this.moving = true; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + this.x = buf.readDouble(); + this.y = buf.readDouble(); + this.z = buf.readDouble(); + super.readPacketData(buf); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeDouble(this.x); + buf.writeDouble(this.y); + buf.writeDouble(this.z); + super.writePacketData(buf); + } + } + + public static class C05PacketPlayerLook extends CPacketPlayer + { + public C05PacketPlayerLook() + { + this.rotating = true; + } + + public C05PacketPlayerLook(float playerYaw, float playerPitch, boolean isOnGround) + { + this.yaw = playerYaw; + this.pitch = playerPitch; + this.onGround = isOnGround; + this.rotating = true; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + this.yaw = buf.readFloat(); + this.pitch = buf.readFloat(); + super.readPacketData(buf); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeFloat(this.yaw); + buf.writeFloat(this.pitch); + super.writePacketData(buf); + } + } + + public static class C06PacketPlayerPosLook extends CPacketPlayer + { + public C06PacketPlayerPosLook() + { + this.moving = true; + this.rotating = true; + } + + public C06PacketPlayerPosLook(double playerX, double playerY, double playerZ, float playerYaw, float playerPitch, boolean playerIsOnGround) + { + this.x = playerX; + this.y = playerY; + this.z = playerZ; + this.yaw = playerYaw; + this.pitch = playerPitch; + this.onGround = playerIsOnGround; + this.rotating = true; + this.moving = true; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + this.x = buf.readDouble(); + this.y = buf.readDouble(); + this.z = buf.readDouble(); + this.yaw = buf.readFloat(); + this.pitch = buf.readFloat(); + super.readPacketData(buf); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeDouble(this.x); + buf.writeDouble(this.y); + buf.writeDouble(this.z); + buf.writeFloat(this.yaw); + buf.writeFloat(this.pitch); + super.writePacketData(buf); + } + } +} diff --git a/common/src/main/java/common/packet/CPacketSign.java b/common/src/common/packet/CPacketSign.java similarity index 96% rename from common/src/main/java/common/packet/CPacketSign.java rename to common/src/common/packet/CPacketSign.java index 9e01415..3653f78 100755 --- a/common/src/main/java/common/packet/CPacketSign.java +++ b/common/src/common/packet/CPacketSign.java @@ -34,7 +34,7 @@ public class CPacketSign implements Packet for (int i = 0; i < 4; ++i) { - this.lines[i] = buf.readString(50); + this.lines[i] = buf.readStringFromBuffer(50); } } diff --git a/common/src/main/java/common/packet/CPacketSkin.java b/common/src/common/packet/CPacketSkin.java similarity index 95% rename from common/src/main/java/common/packet/CPacketSkin.java rename to common/src/common/packet/CPacketSkin.java index d587918..30e476c 100755 --- a/common/src/main/java/common/packet/CPacketSkin.java +++ b/common/src/common/packet/CPacketSkin.java @@ -29,7 +29,7 @@ public class CPacketSkin implements Packet { public void readPacketData(PacketBuffer buf) throws IOException { if(buf.readBoolean()) { this.texture = null; - this.character = buf.readString(64); + this.character = buf.readStringFromBuffer(64); } else { this.texture = buf.readByteArray(); diff --git a/common/src/main/java/common/packet/HPacketHandshake.java b/common/src/common/packet/HPacketHandshake.java similarity index 89% rename from common/src/main/java/common/packet/HPacketHandshake.java rename to common/src/common/packet/HPacketHandshake.java index f94e44e..e2a0018 100755 --- a/common/src/main/java/common/packet/HPacketHandshake.java +++ b/common/src/common/packet/HPacketHandshake.java @@ -17,7 +17,7 @@ public class HPacketHandshake implements Packet { } public void readPacketData(PacketBuffer buf) throws IOException { - this.protocol = buf.readVarInt(); + this.protocol = buf.readVarIntFromBuffer(); int r = buf.readableBytes(); if(r > 0) { this.protocol = 0; @@ -27,7 +27,7 @@ public class HPacketHandshake implements Packet { } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.protocol); + buf.writeVarIntToBuffer(this.protocol); } public void processPacket(IHandshakeHandler handler) { diff --git a/common/src/common/packet/LPacketLogin.java b/common/src/common/packet/LPacketLogin.java new file mode 100644 index 0000000..671fca7 --- /dev/null +++ b/common/src/common/packet/LPacketLogin.java @@ -0,0 +1,21 @@ +package common.packet; + +import java.io.IOException; +import common.network.ILoginHandler; +import common.network.Packet; +import common.network.PacketBuffer; + +public class LPacketLogin implements Packet { + public LPacketLogin() { + } + + public void readPacketData(PacketBuffer buf) throws IOException { + } + + public void writePacketData(PacketBuffer buf) throws IOException { + } + + public void processPacket(ILoginHandler handler) { + handler.processLogin(this); + } +} diff --git a/common/src/main/java/common/packet/LPacketPassword.java b/common/src/common/packet/LPacketPasswordResponse.java similarity index 68% rename from common/src/main/java/common/packet/LPacketPassword.java rename to common/src/common/packet/LPacketPasswordResponse.java index 5436f32..073009c 100755 --- a/common/src/main/java/common/packet/LPacketPassword.java +++ b/common/src/common/packet/LPacketPasswordResponse.java @@ -7,20 +7,20 @@ import common.network.IPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class LPacketPassword implements Packet +public class LPacketPasswordResponse implements Packet { private String user; private String access; private String password; - public LPacketPassword() + public LPacketPasswordResponse() { } - public LPacketPassword(String user, String access, String passwordIn) + public LPacketPasswordResponse(String userIn, String accessIn, String passwordIn) { - this.user = user; - this.access = access; + this.user = userIn; + this.access = accessIn; this.password = passwordIn; } @@ -29,9 +29,9 @@ public class LPacketPassword implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.user = buf.readString(IPlayer.MAX_USER_LENGTH); - this.access = buf.readString(IPlayer.MAX_PASS_LENGTH); - this.password = buf.readString(IPlayer.MAX_PASS_LENGTH); + this.user = buf.readStringFromBuffer(IPlayer.MAX_USER_LENGTH); + this.access = buf.readStringFromBuffer(IPlayer.MAX_PASS_LENGTH); + this.password = buf.readStringFromBuffer(IPlayer.MAX_PASS_LENGTH); } /** @@ -49,7 +49,7 @@ public class LPacketPassword implements Packet */ public void processPacket(ILoginHandler handler) { - handler.processPassword(this); + handler.processPasswordResponse(this); } public String getUser() diff --git a/common/src/common/packet/LPacketStartEncrypt.java b/common/src/common/packet/LPacketStartEncrypt.java new file mode 100644 index 0000000..3408450 --- /dev/null +++ b/common/src/common/packet/LPacketStartEncrypt.java @@ -0,0 +1,47 @@ +package common.packet; + +import java.io.IOException; +import java.security.PrivateKey; +import java.security.PublicKey; + +import javax.crypto.SecretKey; + +import common.network.ILoginHandler; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.EncryptUtil; + +public class LPacketStartEncrypt implements Packet { + private byte[] key = new byte[0]; + private byte[] token = new byte[0]; + + public LPacketStartEncrypt() { + } + + public LPacketStartEncrypt(SecretKey secret, PublicKey pubkey, byte[] token) { + this.key = EncryptUtil.encryptData(pubkey, secret.getEncoded()); + this.token = EncryptUtil.encryptData(pubkey, token); + } + + public void readPacketData(PacketBuffer buf) throws IOException { + this.key = buf.readByteArray(); + this.token = buf.readByteArray(); + } + + public void writePacketData(PacketBuffer buf) throws IOException { + buf.writeByteArray(this.key); + buf.writeByteArray(this.token); + } + + public void processPacket(ILoginHandler handler) { + handler.processEncryption(this); + } + + public SecretKey getKey(PrivateKey key) { + return EncryptUtil.decryptSharedKey(key, this.key); + } + + public byte[] getToken(PrivateKey key) { + return key == null ? this.token : EncryptUtil.decryptData(key, this.token); + } +} diff --git a/common/src/main/java/common/packet/RPacketDisconnect.java b/common/src/common/packet/RPacketDisconnect.java similarity index 94% rename from common/src/main/java/common/packet/RPacketDisconnect.java rename to common/src/common/packet/RPacketDisconnect.java index 36f8aad..3e1c8cb 100755 --- a/common/src/main/java/common/packet/RPacketDisconnect.java +++ b/common/src/common/packet/RPacketDisconnect.java @@ -24,7 +24,7 @@ public class RPacketDisconnect implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.reason = buf.readString(8192); + this.reason = buf.readStringFromBuffer(8192); } /** diff --git a/common/src/main/java/common/packet/RPacketEnableCompression.java b/common/src/common/packet/RPacketEnableCompression.java similarity index 100% rename from common/src/main/java/common/packet/RPacketEnableCompression.java rename to common/src/common/packet/RPacketEnableCompression.java diff --git a/common/src/main/java/common/packet/RPacketLoginSuccess.java b/common/src/common/packet/RPacketLoginSuccess.java similarity index 71% rename from common/src/main/java/common/packet/RPacketLoginSuccess.java rename to common/src/common/packet/RPacketLoginSuccess.java index 0869607..a8b7837 100755 --- a/common/src/main/java/common/packet/RPacketLoginSuccess.java +++ b/common/src/common/packet/RPacketLoginSuccess.java @@ -7,16 +7,28 @@ import common.network.Packet; import common.network.PacketBuffer; public class RPacketLoginSuccess implements Packet { + private boolean debug; + public RPacketLoginSuccess() { } + public RPacketLoginSuccess(boolean debug) { + this.debug = debug; + } + public final void readPacketData(PacketBuffer buf) throws IOException { + this.debug = buf.readBoolean(); } public final void writePacketData(PacketBuffer buf) throws IOException { + buf.writeBoolean(this.debug); } public void processPacket(IClientLoginHandler handler) { handler.handleLoginSuccess(this); } + + public boolean isDebug() { + return this.debug; + } } diff --git a/common/src/main/java/common/packet/RPacketRequestEncrypt.java b/common/src/common/packet/RPacketRequestEncrypt.java similarity index 73% rename from common/src/main/java/common/packet/RPacketRequestEncrypt.java rename to common/src/common/packet/RPacketRequestEncrypt.java index 4492a17..2b45964 100644 --- a/common/src/main/java/common/packet/RPacketRequestEncrypt.java +++ b/common/src/common/packet/RPacketRequestEncrypt.java @@ -10,24 +10,24 @@ import common.util.EncryptUtil; public class RPacketRequestEncrypt implements Packet { private PublicKey key; - private PublicKey tempKey; + private byte[] token; public RPacketRequestEncrypt() { } - public RPacketRequestEncrypt(PublicKey key, PublicKey tempKey) { + public RPacketRequestEncrypt(PublicKey key, byte[] token) { this.key = key; - this.tempKey = tempKey; + this.token = token; } public final void readPacketData(PacketBuffer buf) throws IOException { this.key = EncryptUtil.decodePublicKey(buf.readByteArray()); - this.tempKey = EncryptUtil.decodeDHPublicKey(buf.readByteArray()); + this.token = buf.readByteArray(); } public final void writePacketData(PacketBuffer buf) throws IOException { buf.writeByteArray(this.key.getEncoded()); - buf.writeByteArray(this.tempKey.getEncoded()); + buf.writeByteArray(this.token); } public void processPacket(IClientLoginHandler handler) { @@ -38,7 +38,7 @@ public class RPacketRequestEncrypt implements Packet { return this.key; } - public PublicKey getTempKey() { - return this.tempKey; + public byte[] getToken() { + return this.token; } } diff --git a/common/src/common/packet/S14PacketEntity.java b/common/src/common/packet/S14PacketEntity.java new file mode 100755 index 0000000..68507af --- /dev/null +++ b/common/src/common/packet/S14PacketEntity.java @@ -0,0 +1,208 @@ +package common.packet; + +import java.io.IOException; + +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.world.World; + +public class S14PacketEntity implements Packet +{ + protected int entityId; + protected byte posX; + protected byte posY; + protected byte posZ; + protected byte yaw; + protected byte pitch; + protected boolean onGround; + protected boolean rotation; + + public S14PacketEntity() + { + } + + public S14PacketEntity(int entityIdIn) + { + this.entityId = entityIdIn; + } + + /** + * Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer buf) throws IOException + { + this.entityId = buf.readVarIntFromBuffer(); + } + + /** + * Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeVarIntToBuffer(this.entityId); + } + + /** + * Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(IClientPlayer handler) + { + handler.handleEntityMovement(this); + } + + public String toString() + { + return "Entity_" + super.toString(); + } + + public Entity getEntity(World worldIn) + { + return worldIn.getEntityByID(this.entityId); + } + + public byte getPosX() + { + return this.posX; + } + + public byte getPosY() + { + return this.posY; + } + + public byte getPosZ() + { + return this.posZ; + } + + public byte getYaw() + { + return this.yaw; + } + + public byte getPitch() + { + return this.pitch; + } + + public boolean hasRotations() + { + return this.rotation; + } + + public boolean getOnGround() + { + return this.onGround; + } + + public static class S15PacketEntityRelMove extends S14PacketEntity + { + public S15PacketEntityRelMove() + { + } + + public S15PacketEntityRelMove(int entityIdIn, byte x, byte y, byte z, boolean onGroundIn) + { + super(entityIdIn); + this.posX = x; + this.posY = y; + this.posZ = z; + this.onGround = onGroundIn; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + super.readPacketData(buf); + this.posX = buf.readByte(); + this.posY = buf.readByte(); + this.posZ = buf.readByte(); + this.onGround = buf.readBoolean(); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + super.writePacketData(buf); + buf.writeByte(this.posX); + buf.writeByte(this.posY); + buf.writeByte(this.posZ); + buf.writeBoolean(this.onGround); + } + } + + public static class S16PacketEntityLook extends S14PacketEntity + { + public S16PacketEntityLook() + { + this.rotation = true; + } + + public S16PacketEntityLook(int entityIdIn, byte yawIn, byte pitchIn, boolean onGroundIn) + { + super(entityIdIn); + this.yaw = yawIn; + this.pitch = pitchIn; + this.rotation = true; + this.onGround = onGroundIn; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + super.readPacketData(buf); + this.yaw = buf.readByte(); + this.pitch = buf.readByte(); + this.onGround = buf.readBoolean(); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + super.writePacketData(buf); + buf.writeByte(this.yaw); + buf.writeByte(this.pitch); + buf.writeBoolean(this.onGround); + } + } + + public static class S17PacketEntityLookMove extends S14PacketEntity + { + public S17PacketEntityLookMove() + { + this.rotation = true; + } + + public S17PacketEntityLookMove(int p_i45973_1_, byte p_i45973_2_, byte p_i45973_3_, byte p_i45973_4_, byte p_i45973_5_, byte p_i45973_6_, boolean p_i45973_7_) + { + super(p_i45973_1_); + this.posX = p_i45973_2_; + this.posY = p_i45973_3_; + this.posZ = p_i45973_4_; + this.yaw = p_i45973_5_; + this.pitch = p_i45973_6_; + this.onGround = p_i45973_7_; + this.rotation = true; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + super.readPacketData(buf); + this.posX = buf.readByte(); + this.posY = buf.readByte(); + this.posZ = buf.readByte(); + this.yaw = buf.readByte(); + this.pitch = buf.readByte(); + this.onGround = buf.readBoolean(); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + super.writePacketData(buf); + buf.writeByte(this.posX); + buf.writeByte(this.posY); + buf.writeByte(this.posZ); + buf.writeByte(this.yaw); + buf.writeByte(this.pitch); + buf.writeBoolean(this.onGround); + } + } +} diff --git a/common/src/main/java/common/packet/SPacketEntityTeleport.java b/common/src/common/packet/S18PacketEntityTeleport.java similarity index 86% rename from common/src/main/java/common/packet/SPacketEntityTeleport.java rename to common/src/common/packet/S18PacketEntityTeleport.java index 204fa21..67f4118 100755 --- a/common/src/main/java/common/packet/SPacketEntityTeleport.java +++ b/common/src/common/packet/S18PacketEntityTeleport.java @@ -8,7 +8,7 @@ import common.network.Packet; import common.network.PacketBuffer; import common.util.ExtMath; -public class SPacketEntityTeleport implements Packet +public class S18PacketEntityTeleport implements Packet { private int entityId; private int posX; @@ -18,11 +18,11 @@ public class SPacketEntityTeleport implements Packet private byte pitch; private boolean onGround; - public SPacketEntityTeleport() + public S18PacketEntityTeleport() { } - public SPacketEntityTeleport(Entity entityIn) + public S18PacketEntityTeleport(Entity entityIn) { this.entityId = entityIn.getId(); this.posX = ExtMath.floord(entityIn.posX * 32.0D); @@ -33,7 +33,7 @@ public class SPacketEntityTeleport implements Packet this.onGround = entityIn.onGround; } - public SPacketEntityTeleport(int entityIdIn, int posXIn, int posYIn, int posZIn, byte yawIn, byte pitchIn, boolean onGroundIn) + public S18PacketEntityTeleport(int entityIdIn, int posXIn, int posYIn, int posZIn, byte yawIn, byte pitchIn, boolean onGroundIn) { this.entityId = entityIdIn; this.posX = posXIn; @@ -49,7 +49,7 @@ public class SPacketEntityTeleport implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); + this.entityId = buf.readVarIntFromBuffer(); this.posX = buf.readInt(); this.posY = buf.readInt(); this.posZ = buf.readInt(); @@ -63,7 +63,7 @@ public class SPacketEntityTeleport implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); buf.writeInt(this.posX); buf.writeInt(this.posY); buf.writeInt(this.posZ); diff --git a/common/src/main/java/common/packet/SPacketEntityHeadLook.java b/common/src/common/packet/S19PacketEntityHeadLook.java similarity index 79% rename from common/src/main/java/common/packet/SPacketEntityHeadLook.java rename to common/src/common/packet/S19PacketEntityHeadLook.java index 76f5ddf..885659e 100755 --- a/common/src/main/java/common/packet/SPacketEntityHeadLook.java +++ b/common/src/common/packet/S19PacketEntityHeadLook.java @@ -8,16 +8,16 @@ import common.network.Packet; import common.network.PacketBuffer; import common.world.World; -public class SPacketEntityHeadLook implements Packet +public class S19PacketEntityHeadLook implements Packet { private int entityId; private byte yaw; - public SPacketEntityHeadLook() + public S19PacketEntityHeadLook() { } - public SPacketEntityHeadLook(Entity entityIn, byte p_i45214_2_) + public S19PacketEntityHeadLook(Entity entityIn, byte p_i45214_2_) { this.entityId = entityIn.getId(); this.yaw = p_i45214_2_; @@ -28,7 +28,7 @@ public class SPacketEntityHeadLook implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); + this.entityId = buf.readVarIntFromBuffer(); this.yaw = buf.readByte(); } @@ -37,7 +37,7 @@ public class SPacketEntityHeadLook implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); buf.writeByte(this.yaw); } diff --git a/common/src/main/java/common/packet/SPacketEntityStatus.java b/common/src/common/packet/S1APacketEntityStatus.java similarity index 87% rename from common/src/main/java/common/packet/SPacketEntityStatus.java rename to common/src/common/packet/S1APacketEntityStatus.java index 6c201c1..1775cec 100755 --- a/common/src/main/java/common/packet/SPacketEntityStatus.java +++ b/common/src/common/packet/S1APacketEntityStatus.java @@ -8,16 +8,16 @@ import common.network.Packet; import common.network.PacketBuffer; import common.world.World; -public class SPacketEntityStatus implements Packet +public class S1APacketEntityStatus implements Packet { private int entityId; private byte logicOpcode; - public SPacketEntityStatus() + public S1APacketEntityStatus() { } - public SPacketEntityStatus(Entity entityIn, byte opCodeIn) + public S1APacketEntityStatus(Entity entityIn, byte opCodeIn) { this.entityId = entityIn.getId(); this.logicOpcode = opCodeIn; diff --git a/common/src/main/java/common/packet/SPacketEntityAttach.java b/common/src/common/packet/S1BPacketEntityAttach.java similarity index 88% rename from common/src/main/java/common/packet/SPacketEntityAttach.java rename to common/src/common/packet/S1BPacketEntityAttach.java index 618311a..24c0807 100755 --- a/common/src/main/java/common/packet/SPacketEntityAttach.java +++ b/common/src/common/packet/S1BPacketEntityAttach.java @@ -7,17 +7,17 @@ import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketEntityAttach implements Packet +public class S1BPacketEntityAttach implements Packet { private int leash; private int entityId; private int vehicleEntityId; - public SPacketEntityAttach() + public S1BPacketEntityAttach() { } - public SPacketEntityAttach(int leashIn, Entity entityIn, Entity vehicle) + public S1BPacketEntityAttach(int leashIn, Entity entityIn, Entity vehicle) { this.leash = leashIn; this.entityId = entityIn.getId(); diff --git a/common/src/main/java/common/packet/SPacketEntityMetadata.java b/common/src/common/packet/S1CPacketEntityMetadata.java similarity index 82% rename from common/src/main/java/common/packet/SPacketEntityMetadata.java rename to common/src/common/packet/S1CPacketEntityMetadata.java index fc748e1..645e1a2 100755 --- a/common/src/main/java/common/packet/SPacketEntityMetadata.java +++ b/common/src/common/packet/S1CPacketEntityMetadata.java @@ -8,16 +8,16 @@ import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketEntityMetadata implements Packet +public class S1CPacketEntityMetadata implements Packet { private int entityId; private List field_149378_b; - public SPacketEntityMetadata() + public S1CPacketEntityMetadata() { } - public SPacketEntityMetadata(int entityIdIn, DataWatcher p_i45217_2_, boolean p_i45217_3_) + public S1CPacketEntityMetadata(int entityIdIn, DataWatcher p_i45217_2_, boolean p_i45217_3_) { this.entityId = entityIdIn; @@ -36,7 +36,7 @@ public class SPacketEntityMetadata implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); + this.entityId = buf.readVarIntFromBuffer(); this.field_149378_b = DataWatcher.readWatchedListFromPacketBuffer(buf); } @@ -45,7 +45,7 @@ public class SPacketEntityMetadata implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); DataWatcher.writeWatchedListToPacketBuffer(this.field_149378_b, buf); } diff --git a/common/src/main/java/common/packet/SPacketEntityEffect.java b/common/src/common/packet/S1DPacketEntityEffect.java similarity index 77% rename from common/src/main/java/common/packet/SPacketEntityEffect.java rename to common/src/common/packet/S1DPacketEntityEffect.java index ce38939..faf5dc6 100755 --- a/common/src/main/java/common/packet/SPacketEntityEffect.java +++ b/common/src/common/packet/S1DPacketEntityEffect.java @@ -8,7 +8,7 @@ import common.network.PacketBuffer; import common.potion.Potion; import common.potion.PotionEffect; -public class SPacketEntityEffect implements Packet +public class S1DPacketEntityEffect implements Packet { private int entityId; private Potion effectId; @@ -17,11 +17,11 @@ public class SPacketEntityEffect implements Packet private int remaining; private boolean particles; - public SPacketEntityEffect() + public S1DPacketEntityEffect() { } - public SPacketEntityEffect(int entityIdIn, PotionEffect effect) + public S1DPacketEntityEffect(int entityIdIn, PotionEffect effect) { this.entityId = entityIdIn; this.effectId = effect.getPotion(); @@ -45,11 +45,11 @@ public class SPacketEntityEffect implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); + this.entityId = buf.readVarIntFromBuffer(); this.effectId = buf.readEnumValue(Potion.class); - this.amplifier = buf.readVarInt(); - this.duration = buf.readVarInt(); - this.remaining = buf.readVarInt(); + this.amplifier = buf.readVarIntFromBuffer(); + this.duration = buf.readVarIntFromBuffer(); + this.remaining = buf.readVarIntFromBuffer(); this.particles = buf.readBoolean(); } @@ -58,11 +58,11 @@ public class SPacketEntityEffect implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); buf.writeEnumValue(this.effectId); - buf.writeVarInt(this.amplifier); - buf.writeVarInt(this.duration); - buf.writeVarInt(this.remaining); + buf.writeVarIntToBuffer(this.amplifier); + buf.writeVarIntToBuffer(this.duration); + buf.writeVarIntToBuffer(this.remaining); buf.writeBoolean(this.particles); } diff --git a/common/src/main/java/common/packet/SPacketRemoveEntityEffect.java b/common/src/common/packet/S1EPacketRemoveEntityEffect.java similarity index 79% rename from common/src/main/java/common/packet/SPacketRemoveEntityEffect.java rename to common/src/common/packet/S1EPacketRemoveEntityEffect.java index 7a27c9d..9cd091e 100755 --- a/common/src/main/java/common/packet/SPacketRemoveEntityEffect.java +++ b/common/src/common/packet/S1EPacketRemoveEntityEffect.java @@ -8,16 +8,16 @@ import common.network.PacketBuffer; import common.potion.Potion; import common.potion.PotionEffect; -public class SPacketRemoveEntityEffect implements Packet +public class S1EPacketRemoveEntityEffect implements Packet { private int entityId; private Potion effectId; - public SPacketRemoveEntityEffect() + public S1EPacketRemoveEntityEffect() { } - public SPacketRemoveEntityEffect(int entityIdIn, PotionEffect effect) + public S1EPacketRemoveEntityEffect(int entityIdIn, PotionEffect effect) { this.entityId = entityIdIn; this.effectId = effect.getPotion(); @@ -28,7 +28,7 @@ public class SPacketRemoveEntityEffect implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); + this.entityId = buf.readVarIntFromBuffer(); this.effectId = buf.readEnumValue(Potion.class); } @@ -37,7 +37,7 @@ public class SPacketRemoveEntityEffect implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); buf.writeEnumValue(this.effectId); } diff --git a/common/src/common/packet/S20PacketEntityProperties.java b/common/src/common/packet/S20PacketEntityProperties.java new file mode 100755 index 0000000..f3ca49a --- /dev/null +++ b/common/src/common/packet/S20PacketEntityProperties.java @@ -0,0 +1,127 @@ +package common.packet; + +import java.io.IOException; +import java.util.Collection; +import java.util.List; + +import common.attributes.AttributeInstance; +import common.attributes.AttributeModifier; +import common.collect.Lists; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; + +public class S20PacketEntityProperties implements Packet +{ + private int entityId; + private final List field_149444_b = Lists.newArrayList(); + + public S20PacketEntityProperties() + { + } + + public S20PacketEntityProperties(int entityIdIn, Collection p_i45236_2_) + { + this.entityId = entityIdIn; + + for (AttributeInstance iattributeinstance : p_i45236_2_) + { + this.field_149444_b.add(new S20PacketEntityProperties.Snapshot(iattributeinstance.getAttribute().getUnlocalizedName(), iattributeinstance.getBaseValue(), iattributeinstance.getModifiers())); + } + } + + /** + * Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer buf) throws IOException + { + this.entityId = buf.readVarIntFromBuffer(); + int i = buf.readInt(); + + for (int j = 0; j < i; ++j) + { + String s = buf.readStringFromBuffer(64); + double d0 = buf.readDouble(); + List list = Lists.newArrayList(); + int k = buf.readVarIntFromBuffer(); + + for (int l = 0; l < k; ++l) + { + long id = buf.readLong(); + list.add(new AttributeModifier(id, "Unknown synced attribute modifier", buf.readDouble(), buf.readBoolean())); + } + + this.field_149444_b.add(new S20PacketEntityProperties.Snapshot(s, d0, list)); + } + } + + /** + * Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeVarIntToBuffer(this.entityId); + buf.writeInt(this.field_149444_b.size()); + + for (S20PacketEntityProperties.Snapshot s20packetentityproperties$snapshot : this.field_149444_b) + { + buf.writeString(s20packetentityproperties$snapshot.func_151409_a()); + buf.writeDouble(s20packetentityproperties$snapshot.func_151410_b()); + buf.writeVarIntToBuffer(s20packetentityproperties$snapshot.func_151408_c().size()); + + for (AttributeModifier attributemodifier : s20packetentityproperties$snapshot.func_151408_c()) + { + buf.writeLong(attributemodifier.getID()); + buf.writeDouble(attributemodifier.getAmount()); + buf.writeBoolean(attributemodifier.isMultiplied()); + } + } + } + + /** + * Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(IClientPlayer handler) + { + handler.handleEntityProperties(this); + } + + public int getEntityId() + { + return this.entityId; + } + + public List func_149441_d() + { + return this.field_149444_b; + } + + public class Snapshot + { + private final String field_151412_b; + private final double field_151413_c; + private final Collection field_151411_d; + + public Snapshot(String p_i45235_2_, double p_i45235_3_, Collection p_i45235_5_) + { + this.field_151412_b = p_i45235_2_; + this.field_151413_c = p_i45235_3_; + this.field_151411_d = p_i45235_5_; + } + + public String func_151409_a() + { + return this.field_151412_b; + } + + public double func_151410_b() + { + return this.field_151413_c; + } + + public Collection func_151408_c() + { + return this.field_151411_d; + } + } +} diff --git a/common/src/main/java/common/packet/SPacketExplosion.java b/common/src/common/packet/S27PacketExplosion.java similarity index 93% rename from common/src/main/java/common/packet/SPacketExplosion.java rename to common/src/common/packet/S27PacketExplosion.java index d9fa7cf..85f90ee 100755 --- a/common/src/main/java/common/packet/SPacketExplosion.java +++ b/common/src/common/packet/S27PacketExplosion.java @@ -11,7 +11,7 @@ import common.network.PacketBuffer; import common.util.BlockPos; import common.util.Vec3; -public class SPacketExplosion implements Packet +public class S27PacketExplosion implements Packet { private double posX; private double posY; @@ -23,11 +23,11 @@ public class SPacketExplosion implements Packet private float field_149159_h; private boolean altSound; - public SPacketExplosion() + public S27PacketExplosion() { } - public SPacketExplosion(double p_i45193_1_, double y, double z, float strengthIn, List affectedBlocksIn, Vec3 p_i45193_9_, boolean altSound) + public S27PacketExplosion(double p_i45193_1_, double y, double z, float strengthIn, List affectedBlocksIn, Vec3 p_i45193_9_, boolean altSound) { this.posX = p_i45193_1_; this.posY = y; diff --git a/common/src/main/java/common/packet/SPacketEffect.java b/common/src/common/packet/S28PacketEffect.java similarity index 84% rename from common/src/main/java/common/packet/SPacketEffect.java rename to common/src/common/packet/S28PacketEffect.java index 9c81fb1..cd826e2 100755 --- a/common/src/main/java/common/packet/SPacketEffect.java +++ b/common/src/common/packet/S28PacketEffect.java @@ -7,15 +7,15 @@ import common.network.Packet; import common.network.PacketBuffer; import common.util.BlockPos; -public class SPacketEffect implements Packet { +public class S28PacketEffect implements Packet { private int soundType; private BlockPos soundPos; private int soundData; - public SPacketEffect() { + public S28PacketEffect() { } - public SPacketEffect(int soundTypeIn, BlockPos soundPosIn, int soundDataIn) { + public S28PacketEffect(int soundTypeIn, BlockPos soundPosIn, int soundDataIn) { this.soundType = soundTypeIn; this.soundPos = soundPosIn; this.soundData = soundDataIn; diff --git a/common/src/main/java/common/packet/SPacketSoundEffect.java b/common/src/common/packet/S29PacketSoundEffect.java similarity index 90% rename from common/src/main/java/common/packet/SPacketSoundEffect.java rename to common/src/common/packet/S29PacketSoundEffect.java index d6ecedf..c39ca1a 100755 --- a/common/src/main/java/common/packet/SPacketSoundEffect.java +++ b/common/src/common/packet/S29PacketSoundEffect.java @@ -7,7 +7,7 @@ import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketSoundEffect implements Packet +public class S29PacketSoundEffect implements Packet { private SoundEvent sound; private int posX; @@ -15,12 +15,12 @@ public class SPacketSoundEffect implements Packet private int posZ; private float soundVolume; - public SPacketSoundEffect() + public S29PacketSoundEffect() { this.sound = null; } - public SPacketSoundEffect(SoundEvent sound, double soundX, double soundY, double soundZ, float volume) + public S29PacketSoundEffect(SoundEvent sound, double soundX, double soundY, double soundZ, float volume) { this.sound = sound; if(this.sound == null) { diff --git a/common/src/main/java/common/packet/SPacketParticles.java b/common/src/common/packet/S2APacketParticles.java similarity index 90% rename from common/src/main/java/common/packet/SPacketParticles.java rename to common/src/common/packet/S2APacketParticles.java index f2fd4ba..0d6329c 100755 --- a/common/src/main/java/common/packet/SPacketParticles.java +++ b/common/src/common/packet/S2APacketParticles.java @@ -7,7 +7,7 @@ import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketParticles implements Packet +public class S2APacketParticles implements Packet { private ParticleType particleType; private float xCoord; @@ -25,11 +25,11 @@ public class SPacketParticles implements Packet */ private int[] particleArguments; - public SPacketParticles() + public S2APacketParticles() { } - public SPacketParticles(ParticleType particleTypeIn, boolean longDistanceIn, float x, float y, float z, float xOffsetIn, float yOffset, float zOffset, float particleSpeedIn, int particleCountIn, int[] particleArgumentsIn) + public S2APacketParticles(ParticleType particleTypeIn, boolean longDistanceIn, float x, float y, float z, float xOffsetIn, float yOffset, float zOffset, float particleSpeedIn, int particleCountIn, int[] particleArgumentsIn) { this.particleType = particleTypeIn; this.longDistance = longDistanceIn; @@ -70,7 +70,7 @@ public class SPacketParticles implements Packet for (int j = 0; j < i; ++j) { - this.particleArguments[j] = buf.readVarInt(); + this.particleArguments[j] = buf.readVarIntFromBuffer(); } } @@ -93,7 +93,7 @@ public class SPacketParticles implements Packet for (int j = 0; j < i; ++j) { - buf.writeVarInt(this.particleArguments[j]); + buf.writeVarIntToBuffer(this.particleArguments[j]); } } diff --git a/common/src/main/java/common/packet/SPacketChangeGameState.java b/common/src/common/packet/S2BPacketChangeGameState.java similarity index 72% rename from common/src/main/java/common/packet/SPacketChangeGameState.java rename to common/src/common/packet/S2BPacketChangeGameState.java index 2485d8a..ba4ca54 100755 --- a/common/src/main/java/common/packet/SPacketChangeGameState.java +++ b/common/src/common/packet/S2BPacketChangeGameState.java @@ -7,26 +7,26 @@ import common.network.Packet; import common.network.PacketBuffer; import common.util.ExtMath; -public class SPacketChangeGameState implements Packet +public class S2BPacketChangeGameState implements Packet { private Action action; private int param; - public SPacketChangeGameState() + public S2BPacketChangeGameState() { } - public SPacketChangeGameState(Action action) + public S2BPacketChangeGameState(Action action) { this(action, 0); } - public SPacketChangeGameState(Action action, float param) + public S2BPacketChangeGameState(Action action, float param) { this(action, (int)(param * 1000.0f)); } - public SPacketChangeGameState(Action action, int param) + public S2BPacketChangeGameState(Action action, int param) { this.action = action; this.param = param; @@ -35,13 +35,13 @@ public class SPacketChangeGameState implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.action = buf.readEnumValue(Action.class); - this.param = buf.readVarInt(); + this.param = buf.readVarIntFromBuffer(); } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeEnumValue(this.action); - buf.writeVarInt(this.param); + buf.writeVarIntToBuffer(this.param); } public void processPacket(IClientPlayer handler) @@ -65,6 +65,6 @@ public class SPacketChangeGameState implements Packet } public static enum Action { - SET_WEATHER, RAIN_STRENGTH, DARKNESS, FOG_STRENGTH, TEMPERATURE; + SET_WEATHER, RAIN_STRENGTH, DARKNESS, FOG_STRENGTH; } } diff --git a/common/src/main/java/common/packet/SPacketSpawnGlobalEntity.java b/common/src/common/packet/S2CPacketSpawnGlobalEntity.java similarity index 82% rename from common/src/main/java/common/packet/SPacketSpawnGlobalEntity.java rename to common/src/common/packet/S2CPacketSpawnGlobalEntity.java index baf214a..4741c44 100755 --- a/common/src/main/java/common/packet/SPacketSpawnGlobalEntity.java +++ b/common/src/common/packet/S2CPacketSpawnGlobalEntity.java @@ -8,7 +8,7 @@ import common.network.Packet; import common.network.PacketBuffer; import common.util.ExtMath; -public class SPacketSpawnGlobalEntity implements Packet +public class S2CPacketSpawnGlobalEntity implements Packet { private int entityId; private int x; @@ -17,11 +17,11 @@ public class SPacketSpawnGlobalEntity implements Packet private int type; private int data; - public SPacketSpawnGlobalEntity() + public S2CPacketSpawnGlobalEntity() { } - public SPacketSpawnGlobalEntity(Entity entityIn, int type, int data) + public S2CPacketSpawnGlobalEntity(Entity entityIn, int type, int data) { this.entityId = entityIn.getId(); this.x = ExtMath.floord(entityIn.posX * 32.0D); @@ -36,12 +36,12 @@ public class SPacketSpawnGlobalEntity implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); + this.entityId = buf.readVarIntFromBuffer(); this.type = buf.readByte(); this.x = buf.readInt(); this.y = buf.readInt(); this.z = buf.readInt(); - this.data = buf.readVarInt(); + this.data = buf.readVarIntFromBuffer(); } /** @@ -49,12 +49,12 @@ public class SPacketSpawnGlobalEntity implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); buf.writeByte(this.type); buf.writeInt(this.x); buf.writeInt(this.y); buf.writeInt(this.z); - buf.writeVarInt(this.data); + buf.writeVarIntToBuffer(this.data); } /** diff --git a/common/src/main/java/common/packet/SPacketOpenWindow.java b/common/src/common/packet/S2DPacketOpenWindow.java similarity index 69% rename from common/src/main/java/common/packet/SPacketOpenWindow.java rename to common/src/common/packet/S2DPacketOpenWindow.java index 1ec413e..6fb2370 100755 --- a/common/src/main/java/common/packet/SPacketOpenWindow.java +++ b/common/src/common/packet/S2DPacketOpenWindow.java @@ -7,7 +7,7 @@ import common.network.Packet; import common.network.PacketBuffer; import common.util.BlockPos; -public class SPacketOpenWindow implements Packet +public class S2DPacketOpenWindow implements Packet { private int windowId; private String inventoryType; @@ -16,16 +16,16 @@ public class SPacketOpenWindow implements Packet private int entityId; private BlockPos tilePos; - public SPacketOpenWindow() + public S2DPacketOpenWindow() { } - public SPacketOpenWindow(int incomingWindowId, String incomingWindowTitle, String windowTitleIn) + public S2DPacketOpenWindow(int incomingWindowId, String incomingWindowTitle, String windowTitleIn) { this(incomingWindowId, incomingWindowTitle, windowTitleIn, 0); } - public SPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn) + public S2DPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn) { this.windowId = windowIdIn; this.inventoryType = guiId; @@ -33,13 +33,13 @@ public class SPacketOpenWindow implements Packet this.slotCount = slotCountIn; } - public SPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn, int incomingEntityId) + public S2DPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn, int incomingEntityId) { this(windowIdIn, guiId, windowTitleIn, slotCountIn); this.entityId = incomingEntityId; } - public SPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn, BlockPos incomingTilePos) + public S2DPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn, BlockPos incomingTilePos) { this(windowIdIn, guiId, windowTitleIn, slotCountIn); this.tilePos = incomingTilePos; @@ -59,15 +59,15 @@ public class SPacketOpenWindow implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.windowId = buf.readUnsignedByte(); - this.inventoryType = buf.readString(32); - this.windowTitle = buf.readString(256); + this.inventoryType = buf.readStringFromBuffer(32); + this.windowTitle = buf.readStringFromBuffer(256); this.slotCount = buf.readUnsignedByte(); - if (this.inventoryType.equals("entity")) + if (this.inventoryType.equals("EntityHorse")) { this.entityId = buf.readInt(); } - else if(this.inventoryType.equals("tile")) { + else if(this.inventoryType.startsWith("machine_")) { this.tilePos = buf.readBlockPos(); } } @@ -82,11 +82,11 @@ public class SPacketOpenWindow implements Packet buf.writeString(this.windowTitle); buf.writeByte(this.slotCount); - if (this.inventoryType.equals("entity")) + if (this.inventoryType.equals("EntityHorse")) { buf.writeInt(this.entityId); } - else if(this.inventoryType.equals("tile")) { + else if(this.inventoryType.startsWith("machine_")) { buf.writeBlockPos(this.tilePos); } } @@ -120,4 +120,9 @@ public class SPacketOpenWindow implements Packet { return this.tilePos; } + + public boolean hasSlots() + { + return this.slotCount > 0 || this.inventoryType.startsWith("machine_"); + } } diff --git a/common/src/main/java/common/packet/SPacketCloseWindow.java b/common/src/common/packet/S2EPacketCloseWindow.java similarity index 84% rename from common/src/main/java/common/packet/SPacketCloseWindow.java rename to common/src/common/packet/S2EPacketCloseWindow.java index 28b01f9..7629715 100755 --- a/common/src/main/java/common/packet/SPacketCloseWindow.java +++ b/common/src/common/packet/S2EPacketCloseWindow.java @@ -6,15 +6,15 @@ import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketCloseWindow implements Packet +public class S2EPacketCloseWindow implements Packet { private int windowId; - public SPacketCloseWindow() + public S2EPacketCloseWindow() { } - public SPacketCloseWindow(int windowIdIn) + public S2EPacketCloseWindow(int windowIdIn) { this.windowId = windowIdIn; } diff --git a/common/src/main/java/common/packet/SPacketSetSlot.java b/common/src/common/packet/S2FPacketSetSlot.java similarity index 82% rename from common/src/main/java/common/packet/SPacketSetSlot.java rename to common/src/common/packet/S2FPacketSetSlot.java index 0eaf219..def36be 100755 --- a/common/src/main/java/common/packet/SPacketSetSlot.java +++ b/common/src/common/packet/S2FPacketSetSlot.java @@ -7,17 +7,17 @@ import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketSetSlot implements Packet +public class S2FPacketSetSlot implements Packet { private int windowId; private int slot; private ItemStack item; - public SPacketSetSlot() + public S2FPacketSetSlot() { } - public SPacketSetSlot(int windowIdIn, int slotIn, ItemStack itemIn) + public S2FPacketSetSlot(int windowIdIn, int slotIn, ItemStack itemIn) { this.windowId = windowIdIn; this.slot = slotIn; @@ -39,7 +39,7 @@ public class SPacketSetSlot implements Packet { this.windowId = buf.readByte(); this.slot = buf.readShort(); - this.item = buf.readItemStack(); + this.item = buf.readItemStackFromBuffer(); } /** @@ -49,7 +49,7 @@ public class SPacketSetSlot implements Packet { buf.writeByte(this.windowId); buf.writeShort(this.slot); - buf.writeItemStack(this.item); + buf.writeItemStackToBuffer(this.item); } public int getWindowId() diff --git a/common/src/main/java/common/packet/SPacketWindowItems.java b/common/src/common/packet/S30PacketWindowItems.java similarity index 84% rename from common/src/main/java/common/packet/SPacketWindowItems.java rename to common/src/common/packet/S30PacketWindowItems.java index ad38bca..c3e37f3 100755 --- a/common/src/main/java/common/packet/SPacketWindowItems.java +++ b/common/src/common/packet/S30PacketWindowItems.java @@ -8,16 +8,16 @@ import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketWindowItems implements Packet +public class S30PacketWindowItems implements Packet { private int windowId; private ItemStack[] itemStacks; - public SPacketWindowItems() + public S30PacketWindowItems() { } - public SPacketWindowItems(int windowIdIn, List p_i45186_2_) + public S30PacketWindowItems(int windowIdIn, List p_i45186_2_) { this.windowId = windowIdIn; this.itemStacks = new ItemStack[p_i45186_2_.size()]; @@ -40,7 +40,7 @@ public class SPacketWindowItems implements Packet for (int j = 0; j < i; ++j) { - this.itemStacks[j] = buf.readItemStack(); + this.itemStacks[j] = buf.readItemStackFromBuffer(); } } @@ -54,7 +54,7 @@ public class SPacketWindowItems implements Packet for (ItemStack itemstack : this.itemStacks) { - buf.writeItemStack(itemstack); + buf.writeItemStackToBuffer(itemstack); } } diff --git a/common/src/main/java/common/packet/SPacketWindowProperty.java b/common/src/common/packet/S31PacketWindowProperty.java similarity index 87% rename from common/src/main/java/common/packet/SPacketWindowProperty.java rename to common/src/common/packet/S31PacketWindowProperty.java index ef546c5..e8b02ff 100755 --- a/common/src/main/java/common/packet/SPacketWindowProperty.java +++ b/common/src/common/packet/S31PacketWindowProperty.java @@ -6,17 +6,17 @@ import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketWindowProperty implements Packet +public class S31PacketWindowProperty implements Packet { private int windowId; private int varIndex; private int varValue; - public SPacketWindowProperty() + public S31PacketWindowProperty() { } - public SPacketWindowProperty(int windowIdIn, int varIndexIn, int varValueIn) + public S31PacketWindowProperty(int windowIdIn, int varIndexIn, int varValueIn) { this.windowId = windowIdIn; this.varIndex = varIndexIn; diff --git a/common/src/main/java/common/packet/SPacketConfirmTransaction.java b/common/src/common/packet/S32PacketConfirmTransaction.java similarity index 86% rename from common/src/main/java/common/packet/SPacketConfirmTransaction.java rename to common/src/common/packet/S32PacketConfirmTransaction.java index e09cd3e..2bf7c0f 100755 --- a/common/src/main/java/common/packet/SPacketConfirmTransaction.java +++ b/common/src/common/packet/S32PacketConfirmTransaction.java @@ -6,17 +6,17 @@ import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketConfirmTransaction implements Packet +public class S32PacketConfirmTransaction implements Packet { private int windowId; private short actionNumber; private boolean matching; - public SPacketConfirmTransaction() + public S32PacketConfirmTransaction() { } - public SPacketConfirmTransaction(int windowIdIn, short actionNumberIn, boolean matching) + public S32PacketConfirmTransaction(int windowIdIn, short actionNumberIn, boolean matching) { this.windowId = windowIdIn; this.actionNumber = actionNumberIn; diff --git a/common/src/main/java/common/packet/SPacketUpdateSign.java b/common/src/common/packet/S33PacketUpdateSign.java similarity index 88% rename from common/src/main/java/common/packet/SPacketUpdateSign.java rename to common/src/common/packet/S33PacketUpdateSign.java index 25a586b..8c75e28 100755 --- a/common/src/main/java/common/packet/SPacketUpdateSign.java +++ b/common/src/common/packet/S33PacketUpdateSign.java @@ -8,18 +8,18 @@ import common.network.PacketBuffer; import common.util.BlockPos; import common.world.World; -public class SPacketUpdateSign implements Packet +public class S33PacketUpdateSign implements Packet { private World world; private BlockPos blockPos; private String[] lines; // private String command; - public SPacketUpdateSign() + public S33PacketUpdateSign() { } - public SPacketUpdateSign(World worldIn, BlockPos blockPosIn, String[] linesIn) + public S33PacketUpdateSign(World worldIn, BlockPos blockPosIn, String[] linesIn) { this.world = worldIn; this.blockPos = blockPosIn; @@ -37,7 +37,7 @@ public class SPacketUpdateSign implements Packet for (int i = 0; i < 4; ++i) { - this.lines[i] = buf.readString(64); + this.lines[i] = buf.readStringFromBuffer(64); } // this.command = buf.readStringFromBuffer(1024); diff --git a/common/src/main/java/common/packet/SPacketUpdateTileEntity.java b/common/src/common/packet/S35PacketUpdateTileEntity.java similarity index 74% rename from common/src/main/java/common/packet/SPacketUpdateTileEntity.java rename to common/src/common/packet/S35PacketUpdateTileEntity.java index f1420cf..dc1f0c3 100755 --- a/common/src/main/java/common/packet/SPacketUpdateTileEntity.java +++ b/common/src/common/packet/S35PacketUpdateTileEntity.java @@ -3,28 +3,28 @@ package common.packet; import java.io.IOException; import common.init.TileRegistry; +import common.nbt.NBTTagCompound; import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -import common.tags.TagObject; import common.tileentity.TileEntity; import common.util.BlockPos; -public class SPacketUpdateTileEntity implements Packet +public class S35PacketUpdateTileEntity implements Packet { private BlockPos blockPos; private int type; - private TagObject tag; + private NBTTagCompound nbt; - public SPacketUpdateTileEntity() + public S35PacketUpdateTileEntity() { } - public SPacketUpdateTileEntity(TileEntity tile) + public S35PacketUpdateTileEntity(TileEntity tile) { this.blockPos = tile.getPos(); this.type = TileRegistry.CLASS_TO_ID.get(tile.getClass()); - tile.writeTags(this.tag = new TagObject()); + tile.writeToNBT(this.nbt = new NBTTagCompound()); } /** @@ -34,7 +34,7 @@ public class SPacketUpdateTileEntity implements Packet { this.blockPos = buf.readBlockPos(); this.type = buf.readUnsignedByte(); - this.tag = buf.readTag(); + this.nbt = buf.readNBTTagCompoundFromBuffer(); } /** @@ -44,7 +44,7 @@ public class SPacketUpdateTileEntity implements Packet { buf.writeBlockPos(this.blockPos); buf.writeByte((byte)this.type); - buf.writeTag(this.tag); + buf.writeNBTTagCompoundToBuffer(this.nbt); } /** @@ -65,8 +65,8 @@ public class SPacketUpdateTileEntity implements Packet return this.type == TileRegistry.CLASS_TO_ID.get(tile.getClass()); } - public TagObject getTags() + public NBTTagCompound getNbtCompound() { - return this.tag; + return this.nbt; } } diff --git a/common/src/main/java/common/packet/SPacketSignEditorOpen.java b/common/src/common/packet/S36PacketSignEditorOpen.java similarity index 85% rename from common/src/main/java/common/packet/SPacketSignEditorOpen.java rename to common/src/common/packet/S36PacketSignEditorOpen.java index b7b09e9..1059d0c 100755 --- a/common/src/main/java/common/packet/SPacketSignEditorOpen.java +++ b/common/src/common/packet/S36PacketSignEditorOpen.java @@ -7,15 +7,15 @@ import common.network.Packet; import common.network.PacketBuffer; import common.util.BlockPos; -public class SPacketSignEditorOpen implements Packet +public class S36PacketSignEditorOpen implements Packet { private BlockPos signPosition; - public SPacketSignEditorOpen() + public S36PacketSignEditorOpen() { } - public SPacketSignEditorOpen(BlockPos signPositionIn) + public S36PacketSignEditorOpen(BlockPos signPositionIn) { this.signPosition = signPositionIn; } diff --git a/common/src/main/java/common/packet/SPacketPlayerListItem.java b/common/src/common/packet/S38PacketPlayerListItem.java similarity index 70% rename from common/src/main/java/common/packet/SPacketPlayerListItem.java rename to common/src/common/packet/S38PacketPlayerListItem.java index 2bc0601..f83caa5 100755 --- a/common/src/main/java/common/packet/SPacketPlayerListItem.java +++ b/common/src/common/packet/S38PacketPlayerListItem.java @@ -11,36 +11,36 @@ import common.network.IPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketPlayerListItem implements Packet { +public class S38PacketPlayerListItem implements Packet { private final Map players = Maps.newHashMap(); - public SPacketPlayerListItem() { + public S38PacketPlayerListItem() { } - public SPacketPlayerListItem(boolean remove, IPlayer... conns) { + public S38PacketPlayerListItem(boolean remove, IPlayer... conns) { for(IPlayer conn : conns) { this.players.put(conn.getUser(), remove ? -1 : conn.getLatency()); } } - public SPacketPlayerListItem(Iterable conns) { + public S38PacketPlayerListItem(Iterable conns) { for(IPlayer conn : conns) { this.players.put(((IPlayer)conn).getUser(), ((IPlayer)conn).getLatency()); } } public void readPacketData(PacketBuffer buf) throws IOException { - int n = buf.readVarInt(); + int n = buf.readVarIntFromBuffer(); for(int z = 0; z < n; z++) { - this.players.put(buf.readString(16), buf.readVarInt()); + this.players.put(buf.readStringFromBuffer(16), buf.readVarIntFromBuffer()); } } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.players.size()); + buf.writeVarIntToBuffer(this.players.size()); for(Entry data : this.players.entrySet()) { buf.writeString(data.getKey()); - buf.writeVarInt(data.getValue()); + buf.writeVarIntToBuffer(data.getValue()); } } diff --git a/common/src/main/java/common/packet/SPacketPlayerAbilities.java b/common/src/common/packet/S39PacketPlayerAbilities.java similarity index 84% rename from common/src/main/java/common/packet/SPacketPlayerAbilities.java rename to common/src/common/packet/S39PacketPlayerAbilities.java index d7b7d34..24f0537 100755 --- a/common/src/main/java/common/packet/SPacketPlayerAbilities.java +++ b/common/src/common/packet/S39PacketPlayerAbilities.java @@ -7,14 +7,14 @@ import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketPlayerAbilities implements Packet { +public class S39PacketPlayerAbilities implements Packet { private boolean flying; private boolean noClip; - public SPacketPlayerAbilities() { + public S39PacketPlayerAbilities() { } - public SPacketPlayerAbilities(EntityNPC capabilities) { + public S39PacketPlayerAbilities(EntityNPC capabilities) { this.flying = capabilities.flying; this.noClip = capabilities.noclip; } diff --git a/common/src/main/java/common/packet/SPacketTabComplete.java b/common/src/common/packet/S3APacketTabComplete.java similarity index 74% rename from common/src/main/java/common/packet/SPacketTabComplete.java rename to common/src/common/packet/S3APacketTabComplete.java index 88ef0e2..76beea3 100755 --- a/common/src/main/java/common/packet/SPacketTabComplete.java +++ b/common/src/common/packet/S3APacketTabComplete.java @@ -6,15 +6,15 @@ import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -public class SPacketTabComplete implements Packet +public class S3APacketTabComplete implements Packet { private String[] matches; - public SPacketTabComplete() + public S3APacketTabComplete() { } - public SPacketTabComplete(String[] matchesIn) + public S3APacketTabComplete(String[] matchesIn) { this.matches = matchesIn; } @@ -24,11 +24,11 @@ public class SPacketTabComplete implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.matches = new String[buf.readVarInt()]; + this.matches = new String[buf.readVarIntFromBuffer()]; for (int i = 0; i < this.matches.length; ++i) { - this.matches[i] = buf.readString(32767); + this.matches[i] = buf.readStringFromBuffer(32767); } } @@ -37,7 +37,7 @@ public class SPacketTabComplete implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.matches.length); + buf.writeVarIntToBuffer(this.matches.length); for (String s : this.matches) { diff --git a/common/src/main/java/common/packet/SPacketUpdateEntityTags.java b/common/src/common/packet/S43PacketUpdateEntityNBT.java similarity index 62% rename from common/src/main/java/common/packet/SPacketUpdateEntityTags.java rename to common/src/common/packet/S43PacketUpdateEntityNBT.java index 0a3f15a..ad56eac 100755 --- a/common/src/main/java/common/packet/SPacketUpdateEntityTags.java +++ b/common/src/common/packet/S43PacketUpdateEntityNBT.java @@ -3,22 +3,22 @@ package common.packet; import java.io.IOException; import common.entity.Entity; +import common.nbt.NBTTagCompound; import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -import common.tags.TagObject; import common.world.World; -public class SPacketUpdateEntityTags implements Packet +public class S43PacketUpdateEntityNBT implements Packet { private int entityId; - private TagObject tagCompound; + private NBTTagCompound tagCompound; - public SPacketUpdateEntityTags() + public S43PacketUpdateEntityNBT() { } - public SPacketUpdateEntityTags(int entityIdIn, TagObject tagCompoundIn) + public S43PacketUpdateEntityNBT(int entityIdIn, NBTTagCompound tagCompoundIn) { this.entityId = entityIdIn; this.tagCompound = tagCompoundIn; @@ -29,8 +29,8 @@ public class SPacketUpdateEntityTags implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); - this.tagCompound = buf.readTag(); + this.entityId = buf.readVarIntFromBuffer(); + this.tagCompound = buf.readNBTTagCompoundFromBuffer(); } /** @@ -38,8 +38,8 @@ public class SPacketUpdateEntityTags implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); - buf.writeTag(this.tagCompound); + buf.writeVarIntToBuffer(this.entityId); + buf.writeNBTTagCompoundToBuffer(this.tagCompound); } /** @@ -47,10 +47,10 @@ public class SPacketUpdateEntityTags implements Packet */ public void processPacket(IClientPlayer handler) { - handler.handleEntityTags(this); + handler.handleEntityNBT(this); } - public TagObject getTagCompound() + public NBTTagCompound getTagCompound() { return this.tagCompound; } diff --git a/common/src/main/java/common/packet/SPacketAnimation.java b/common/src/common/packet/SPacketAnimation.java similarity index 93% rename from common/src/main/java/common/packet/SPacketAnimation.java rename to common/src/common/packet/SPacketAnimation.java index de8b50d..ad62a60 100755 --- a/common/src/main/java/common/packet/SPacketAnimation.java +++ b/common/src/common/packet/SPacketAnimation.java @@ -33,14 +33,14 @@ public class SPacketAnimation implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); + this.entityId = buf.readVarIntFromBuffer(); this.type = buf.readUnsignedByte(); // this.par = buf.readVarIntFromBuffer(); } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); buf.writeByte(this.type); // buf.writeVarIntToBuffer(this.par); } diff --git a/common/src/main/java/common/packet/SPacketBlockAction.java b/common/src/common/packet/SPacketBlockAction.java similarity index 91% rename from common/src/main/java/common/packet/SPacketBlockAction.java rename to common/src/common/packet/SPacketBlockAction.java index 083cf7f..239d6eb 100755 --- a/common/src/main/java/common/packet/SPacketBlockAction.java +++ b/common/src/common/packet/SPacketBlockAction.java @@ -36,7 +36,7 @@ public class SPacketBlockAction implements Packet this.blockPosition = buf.readBlockPos(); this.instrument = buf.readUnsignedByte(); this.pitch = buf.readUnsignedByte(); - this.block = BlockRegistry.getBlockById(buf.readVarInt() & 4095); + this.block = BlockRegistry.getBlockById(buf.readVarIntFromBuffer() & 4095); } /** @@ -47,7 +47,7 @@ public class SPacketBlockAction implements Packet buf.writeBlockPos(this.blockPosition); buf.writeByte(this.instrument); buf.writeByte(this.pitch); - buf.writeVarInt(BlockRegistry.getIdFromBlock(this.block) & 4095); + buf.writeVarIntToBuffer(BlockRegistry.getIdFromBlock(this.block) & 4095); } /** diff --git a/common/src/main/java/common/packet/SPacketBlockBreakAnim.java b/common/src/common/packet/SPacketBlockBreakAnim.java similarity index 93% rename from common/src/main/java/common/packet/SPacketBlockBreakAnim.java rename to common/src/common/packet/SPacketBlockBreakAnim.java index 1b1acec..ccebc7e 100755 --- a/common/src/main/java/common/packet/SPacketBlockBreakAnim.java +++ b/common/src/common/packet/SPacketBlockBreakAnim.java @@ -29,7 +29,7 @@ public class SPacketBlockBreakAnim implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.breakerId = buf.readVarInt(); + this.breakerId = buf.readVarIntFromBuffer(); this.position = buf.readBlockPos(); this.progress = buf.readUnsignedByte(); } @@ -39,7 +39,7 @@ public class SPacketBlockBreakAnim implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.breakerId); + buf.writeVarIntToBuffer(this.breakerId); buf.writeBlockPos(this.position); buf.writeByte(this.progress); } diff --git a/common/src/main/java/common/packet/SPacketBlockChange.java b/common/src/common/packet/SPacketBlockChange.java similarity index 92% rename from common/src/main/java/common/packet/SPacketBlockChange.java rename to common/src/common/packet/SPacketBlockChange.java index ca79376..9ab2a01 100755 --- a/common/src/main/java/common/packet/SPacketBlockChange.java +++ b/common/src/common/packet/SPacketBlockChange.java @@ -31,7 +31,7 @@ public class SPacketBlockChange implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.blockPosition = buf.readBlockPos(); - this.blockState = (State)BlockRegistry.STATEMAP.getByValue(buf.readVarInt()); + this.blockState = (State)BlockRegistry.STATEMAP.getByValue(buf.readVarIntFromBuffer()); } /** @@ -40,7 +40,7 @@ public class SPacketBlockChange implements Packet public void writePacketData(PacketBuffer buf) throws IOException { buf.writeBlockPos(this.blockPosition); - buf.writeVarInt(BlockRegistry.STATEMAP.get(this.blockState)); + buf.writeVarIntToBuffer(BlockRegistry.STATEMAP.get(this.blockState)); } /** diff --git a/common/src/main/java/common/packet/SPacketCamera.java b/common/src/common/packet/SPacketCamera.java similarity index 89% rename from common/src/main/java/common/packet/SPacketCamera.java rename to common/src/common/packet/SPacketCamera.java index d72765c..40edc45 100755 --- a/common/src/main/java/common/packet/SPacketCamera.java +++ b/common/src/common/packet/SPacketCamera.java @@ -23,12 +23,12 @@ public class SPacketCamera implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); + this.entityId = buf.readVarIntFromBuffer(); } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); } public void processPacket(IClientPlayer handler) diff --git a/common/src/main/java/common/packet/SPacketCharacterList.java b/common/src/common/packet/SPacketCharacterList.java similarity index 71% rename from common/src/main/java/common/packet/SPacketCharacterList.java rename to common/src/common/packet/SPacketCharacterList.java index 88777b8..8978d9d 100644 --- a/common/src/main/java/common/packet/SPacketCharacterList.java +++ b/common/src/common/packet/SPacketCharacterList.java @@ -40,44 +40,44 @@ public class SPacketCharacterList implements Packet { } public void readPacketData(PacketBuffer buf) throws IOException { - int n = buf.readVarInt(); + int n = buf.readVarIntFromBuffer(); for(int z = 0; z < n; z++) { - int id = buf.readVarInt(); - String name = buf.readString(IPlayer.MAX_NICK_LENGTH); + int id = buf.readVarIntFromBuffer(); + String name = buf.readStringFromBuffer(IPlayer.MAX_NICK_LENGTH); if(name.isEmpty()) { this.players.put(id, null); continue; } - String info = buf.readString(IPlayer.MAX_INFO_LENGTH); + String info = buf.readStringFromBuffer(IPlayer.MAX_INFO_LENGTH); info = info.isEmpty() ? null : info; Alignment align = buf.readEnumValue(Alignment.class); - String dim = buf.readString(256); + String dim = buf.readStringFromBuffer(256); BlockPos pos = buf.readBlockPos(); - String type = buf.readString(256); - int level = buf.readVarInt(); + String type = buf.readStringFromBuffer(256); + int level = buf.readVarIntFromBuffer(); this.players.put(id, new PlayerCharacter(name, info, align, dim, pos, type, level)); } - this.selected = buf.readVarInt(); + this.selected = buf.readVarIntFromBuffer(); } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.players.size()); + buf.writeVarIntToBuffer(this.players.size()); for(Entry data : this.players.entrySet()) { PlayerCharacter chr = data.getValue(); - buf.writeVarInt(data.getKey()); + buf.writeVarIntToBuffer(data.getKey()); if(chr == null) { buf.writeString(""); continue; } - buf.writeString(chr.name()); - buf.writeString(chr.info() == null ? "" : chr.info()); - buf.writeEnumValue(chr.align()); - buf.writeString(chr.dim()); - buf.writeBlockPos(chr.pos()); - buf.writeString(chr.type()); - buf.writeVarInt(chr.level()); + buf.writeString(chr.name); + buf.writeString(chr.info == null ? "" : chr.info); + buf.writeEnumValue(chr.align); + buf.writeString(chr.dim); + buf.writeBlockPos(chr.pos); + buf.writeString(chr.type); + buf.writeVarIntToBuffer(chr.level); } - buf.writeVarInt(this.selected); + buf.writeVarIntToBuffer(this.selected); } public void processPacket(IClientPlayer handler) { diff --git a/common/src/common/packet/SPacketChunkData.java b/common/src/common/packet/SPacketChunkData.java new file mode 100755 index 0000000..0878dda --- /dev/null +++ b/common/src/common/packet/SPacketChunkData.java @@ -0,0 +1,147 @@ +package common.packet; + +import java.io.IOException; +import java.util.List; + +import common.collect.Lists; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.world.BlockArray; +import common.world.Chunk; + +public class SPacketChunkData implements Packet +{ + private int chunkX; + private int chunkZ; + private SPacketChunkData.Extracted extractedData; + private boolean resend; + + public SPacketChunkData() + { + } + + public SPacketChunkData(Chunk chunkIn, boolean resend, int segUpdate) + { + this.chunkX = chunkIn.xPos; + this.chunkZ = chunkIn.zPos; + this.resend = resend; + this.extractedData = getExtractedData(chunkIn, resend, segUpdate); + } + + /** + * Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer buf) throws IOException + { + this.chunkX = buf.readInt(); + this.chunkZ = buf.readInt(); + this.resend = buf.readBoolean(); + this.extractedData = new SPacketChunkData.Extracted(); + this.extractedData.dataSize = buf.readInt(); + this.extractedData.data = buf.readByteArray(); + } + + /** + * Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeInt(this.chunkX); + buf.writeInt(this.chunkZ); + buf.writeBoolean(this.resend); + buf.writeInt(this.extractedData.dataSize); + buf.writeByteArray(this.extractedData.data); + } + + /** + * Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(IClientPlayer handler) + { + handler.handleChunkData(this); + } + + public byte[] getExtractedDataBytes() + { + return this.extractedData.data; + } + + protected static int getSize(int segments) + { + int i = segments * 2 * 16 * 16 * 16; + int j = segments * 16 * 16 * 16 / 2; + return i + j; + } + + public static SPacketChunkData.Extracted getExtractedData(Chunk chunk, boolean biomes, int segUpdate) + { + BlockArray[] aextendedblockstorage = chunk.getStorage(); + SPacketChunkData.Extracted s21packetchunkdata$extracted = new SPacketChunkData.Extracted(); + List list = Lists.newArrayList(); + + for (int i = 0; i < aextendedblockstorage.length; ++i) + { + BlockArray extendedblockstorage = aextendedblockstorage[i]; + + if (extendedblockstorage != null && (!biomes || !extendedblockstorage.isEmpty()) && (segUpdate & 1 << i) != 0) + { + s21packetchunkdata$extracted.dataSize |= 1 << i; + list.add(extendedblockstorage); + } + } + + s21packetchunkdata$extracted.data = new byte[getSize(Integer.bitCount(s21packetchunkdata$extracted.dataSize))]; + int j = 0; + + for (BlockArray extendedblockstorage1 : list) + { + char[] achar = extendedblockstorage1.getData(); + + for (char c0 : achar) + { + s21packetchunkdata$extracted.data[j++] = (byte)(c0 & 255); + s21packetchunkdata$extracted.data[j++] = (byte)(c0 >> 8 & 255); + } + } + + for (BlockArray extendedblockstorage2 : list) + { + j = copyTo(extendedblockstorage2.getBlocklight().getData(), s21packetchunkdata$extracted.data, j); + } + + return s21packetchunkdata$extracted; + } + + private static int copyTo(byte[] src, byte[] dest, int offset) + { + System.arraycopy(src, 0, dest, offset, src.length); + return offset + src.length; + } + + public int getChunkX() + { + return this.chunkX; + } + + public int getChunkZ() + { + return this.chunkZ; + } + + public int getExtractedSize() + { + return this.extractedData.dataSize; + } + + public boolean isResend() + { + return this.resend; + } + + public static class Extracted + { + public byte[] data; + public int dataSize; + } +} diff --git a/common/src/main/java/common/packet/SPacketCollectItem.java b/common/src/common/packet/SPacketCollectItem.java similarity index 83% rename from common/src/main/java/common/packet/SPacketCollectItem.java rename to common/src/common/packet/SPacketCollectItem.java index ea5d18f..4c0deb7 100755 --- a/common/src/main/java/common/packet/SPacketCollectItem.java +++ b/common/src/common/packet/SPacketCollectItem.java @@ -26,8 +26,8 @@ public class SPacketCollectItem implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.collectedItemEntityId = buf.readVarInt(); - this.entityId = buf.readVarInt(); + this.collectedItemEntityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarIntFromBuffer(); } /** @@ -35,8 +35,8 @@ public class SPacketCollectItem implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.collectedItemEntityId); - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.collectedItemEntityId); + buf.writeVarIntToBuffer(this.entityId); } /** diff --git a/common/src/main/java/common/packet/SPacketDestroyEntities.java b/common/src/common/packet/SPacketDestroyEntities.java similarity index 82% rename from common/src/main/java/common/packet/SPacketDestroyEntities.java rename to common/src/common/packet/SPacketDestroyEntities.java index aafef94..9927461 100755 --- a/common/src/main/java/common/packet/SPacketDestroyEntities.java +++ b/common/src/common/packet/SPacketDestroyEntities.java @@ -24,11 +24,11 @@ public class SPacketDestroyEntities implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityIDs = new int[buf.readVarInt()]; + this.entityIDs = new int[buf.readVarIntFromBuffer()]; for (int i = 0; i < this.entityIDs.length; ++i) { - this.entityIDs[i] = buf.readVarInt(); + this.entityIDs[i] = buf.readVarIntFromBuffer(); } } @@ -37,11 +37,11 @@ public class SPacketDestroyEntities implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityIDs.length); + buf.writeVarIntToBuffer(this.entityIDs.length); for (int i = 0; i < this.entityIDs.length; ++i) { - buf.writeVarInt(this.entityIDs[i]); + buf.writeVarIntToBuffer(this.entityIDs[i]); } } diff --git a/common/src/main/java/common/packet/SPacketDimensionName.java b/common/src/common/packet/SPacketDimensionName.java similarity index 91% rename from common/src/main/java/common/packet/SPacketDimensionName.java rename to common/src/common/packet/SPacketDimensionName.java index 2523147..feb1c80 100755 --- a/common/src/main/java/common/packet/SPacketDimensionName.java +++ b/common/src/common/packet/SPacketDimensionName.java @@ -25,8 +25,8 @@ public class SPacketDimensionName implements Packet { } public void readPacketData(PacketBuffer buf) throws IOException { - this.fullName = buf.readString(64); - this.customName = buf.readString(64); + this.fullName = buf.readStringFromBuffer(64); + this.customName = buf.readStringFromBuffer(64); this.customName = this.customName.isEmpty() ? null : this.customName; } diff --git a/common/src/main/java/common/packet/SPacketDisconnect.java b/common/src/common/packet/SPacketDisconnect.java similarity index 93% rename from common/src/main/java/common/packet/SPacketDisconnect.java rename to common/src/common/packet/SPacketDisconnect.java index f558fc0..133acdc 100755 --- a/common/src/main/java/common/packet/SPacketDisconnect.java +++ b/common/src/common/packet/SPacketDisconnect.java @@ -17,7 +17,7 @@ public class SPacketDisconnect implements Packet { } public void readPacketData(PacketBuffer buf) throws IOException { - this.message = buf.readString(2048); + this.message = buf.readStringFromBuffer(2048); } public void writePacketData(PacketBuffer buf) throws IOException { diff --git a/common/src/main/java/common/packet/SPacketDisplayForm.java b/common/src/common/packet/SPacketDisplayForm.java similarity index 74% rename from common/src/main/java/common/packet/SPacketDisplayForm.java rename to common/src/common/packet/SPacketDisplayForm.java index 7532ab5..372e8af 100644 --- a/common/src/main/java/common/packet/SPacketDisplayForm.java +++ b/common/src/common/packet/SPacketDisplayForm.java @@ -31,39 +31,39 @@ public class SPacketDisplayForm implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.id = buf.readVarInt(); - this.title = buf.readString(256); - this.data = new Triplet[buf.readVarInt()]; + this.id = buf.readVarIntFromBuffer(); + this.title = buf.readStringFromBuffer(256); + this.data = new Triplet[buf.readVarIntFromBuffer()]; for(int z = 0; z < this.data.length; z++) { - String name = buf.readString(64); + String name = buf.readStringFromBuffer(64); Object obj; switch(buf.readByte()) { case 0: obj = buf.readBoolean(); break; case 1: - String[] strs = new String[buf.readVarInt()]; + String[] strs = new String[buf.readVarIntFromBuffer()]; obj = strs; for(int n = 0; n < strs.length; n++) { - strs[n] = buf.readString(128); + strs[n] = buf.readStringFromBuffer(128); } break; default: - obj = buf.readString(256); + obj = buf.readStringFromBuffer(256); break; } - this.data[z] = new Triplet(name, obj, buf.readVarInt()); + this.data[z] = new Triplet(name, obj, buf.readVarIntFromBuffer()); } } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.id); + buf.writeVarIntToBuffer(this.id); buf.writeString(this.title); - buf.writeVarInt(this.data.length); + buf.writeVarIntToBuffer(this.data.length); for(int z = 0; z < this.data.length; z++) { - buf.writeString(this.data[z].first()); - Object obj = this.data[z].second(); + buf.writeString(this.data[z].first); + Object obj = this.data[z].second; if(obj instanceof Boolean) { buf.writeByte(0); buf.writeBoolean((Boolean)obj); @@ -71,7 +71,7 @@ public class SPacketDisplayForm implements Packet else if(obj instanceof String[]) { buf.writeByte(1); String[] strs = (String[])obj; - buf.writeVarInt(strs.length); + buf.writeVarIntToBuffer(strs.length); for(int n = 0; n < strs.length; n++) { buf.writeString(strs[n]); } @@ -80,7 +80,7 @@ public class SPacketDisplayForm implements Packet buf.writeByte(2); buf.writeString((String)obj); } - buf.writeVarInt(this.data[z].third()); + buf.writeVarIntToBuffer(this.data[z].third); } } diff --git a/common/src/main/java/common/packet/SPacketEntityEquipment.java b/common/src/common/packet/SPacketEntityEquipment.java similarity index 87% rename from common/src/main/java/common/packet/SPacketEntityEquipment.java rename to common/src/common/packet/SPacketEntityEquipment.java index 8497508..0ee5fd8 100755 --- a/common/src/main/java/common/packet/SPacketEntityEquipment.java +++ b/common/src/common/packet/SPacketEntityEquipment.java @@ -29,9 +29,9 @@ public class SPacketEntityEquipment implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityID = buf.readVarInt(); + this.entityID = buf.readVarIntFromBuffer(); this.equipmentSlot = buf.readShort(); - this.itemStack = buf.readItemStack(); + this.itemStack = buf.readItemStackFromBuffer(); } /** @@ -39,9 +39,9 @@ public class SPacketEntityEquipment implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityID); + buf.writeVarIntToBuffer(this.entityID); buf.writeShort(this.equipmentSlot); - buf.writeItemStack(this.itemStack); + buf.writeItemStackToBuffer(this.itemStack); } /** diff --git a/common/src/main/java/common/packet/SPacketEntityVelocity.java b/common/src/common/packet/SPacketEntityVelocity.java similarity index 95% rename from common/src/main/java/common/packet/SPacketEntityVelocity.java rename to common/src/common/packet/SPacketEntityVelocity.java index 60818b0..8b6520c 100755 --- a/common/src/main/java/common/packet/SPacketEntityVelocity.java +++ b/common/src/common/packet/SPacketEntityVelocity.java @@ -68,7 +68,7 @@ public class SPacketEntityVelocity implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityID = buf.readVarInt(); + this.entityID = buf.readVarIntFromBuffer(); this.motionX = buf.readShort(); this.motionY = buf.readShort(); this.motionZ = buf.readShort(); @@ -79,7 +79,7 @@ public class SPacketEntityVelocity implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityID); + buf.writeVarIntToBuffer(this.entityID); buf.writeShort(this.motionX); buf.writeShort(this.motionY); buf.writeShort(this.motionZ); diff --git a/common/src/main/java/common/packet/SPacketHeldItemChange.java b/common/src/common/packet/SPacketHeldItemChange.java similarity index 100% rename from common/src/main/java/common/packet/SPacketHeldItemChange.java rename to common/src/common/packet/SPacketHeldItemChange.java diff --git a/common/src/main/java/common/packet/SPacketJoinGame.java b/common/src/common/packet/SPacketJoinGame.java similarity index 81% rename from common/src/main/java/common/packet/SPacketJoinGame.java rename to common/src/common/packet/SPacketJoinGame.java index 2d6606d..1f452fd 100755 --- a/common/src/main/java/common/packet/SPacketJoinGame.java +++ b/common/src/common/packet/SPacketJoinGame.java @@ -3,14 +3,14 @@ package common.packet; import java.io.IOException; import common.dimension.Dimension; +import common.nbt.NBTTagCompound; import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -import common.tags.TagObject; public class SPacketJoinGame implements Packet { private int entityId; - private TagObject dimension; + private NBTTagCompound dimension; private int type; private boolean editor; @@ -19,21 +19,21 @@ public class SPacketJoinGame implements Packet { public SPacketJoinGame(int entityIdIn, Dimension dimensionIn, int type, boolean editor) { this.entityId = entityIdIn; - this.dimension = dimensionIn.toTags(false); + this.dimension = dimensionIn.toNbt(false); this.type = type; this.editor = editor; } public void readPacketData(PacketBuffer buf) throws IOException { this.entityId = buf.readInt(); - this.dimension = buf.readTag(); + this.dimension = buf.readNBTTagCompoundFromBuffer(); this.type = buf.readUnsignedShort(); this.editor = buf.readBoolean(); } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeInt(this.entityId); - buf.writeTag(this.dimension); + buf.writeNBTTagCompoundToBuffer(this.dimension); buf.writeShort(this.type & 65535); buf.writeBoolean(this.editor); } @@ -47,7 +47,7 @@ public class SPacketJoinGame implements Packet { } public Dimension getDimension() { - return Dimension.getByTag(this.dimension, false); + return Dimension.getByNbt(this.dimension, false); } public int getEntityType() { diff --git a/common/src/main/java/common/packet/SPacketKeepAlive.java b/common/src/common/packet/SPacketKeepAlive.java similarity index 100% rename from common/src/main/java/common/packet/SPacketKeepAlive.java rename to common/src/common/packet/SPacketKeepAlive.java diff --git a/common/src/main/java/common/packet/SPacketLoading.java b/common/src/common/packet/SPacketLoading.java similarity index 94% rename from common/src/main/java/common/packet/SPacketLoading.java rename to common/src/common/packet/SPacketLoading.java index 2a090f9..4daa761 100644 --- a/common/src/main/java/common/packet/SPacketLoading.java +++ b/common/src/common/packet/SPacketLoading.java @@ -29,10 +29,10 @@ public class SPacketLoading implements Packet { } public void readPacketData(PacketBuffer buf) throws IOException { - this.message = buf.readString(128); + this.message = buf.readStringFromBuffer(128); this.message = this.message != null && this.message.isEmpty() ? null : this.message; if(this.message == null) { - this.task = buf.readString(128); + this.task = buf.readStringFromBuffer(128); this.task = this.task != null && this.task.isEmpty() ? null : this.task; this.total = buf.readInt(); this.progress = buf.readInt(); diff --git a/common/src/main/java/common/packet/SPacketMapChunkBulk.java b/common/src/common/packet/SPacketMapChunkBulk.java similarity index 67% rename from common/src/main/java/common/packet/SPacketMapChunkBulk.java rename to common/src/common/packet/SPacketMapChunkBulk.java index 8adceef..653352e 100755 --- a/common/src/main/java/common/packet/SPacketMapChunkBulk.java +++ b/common/src/common/packet/SPacketMapChunkBulk.java @@ -1,36 +1,46 @@ package common.packet; import java.io.IOException; +import java.util.List; + import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; +import common.world.Chunk; public class SPacketMapChunkBulk implements Packet { private int[] xPositions; private int[] zPositions; private SPacketChunkData.Extracted[] chunksData; - private boolean sky; public SPacketMapChunkBulk() { } - public SPacketMapChunkBulk(int[] x, int[] z, SPacketChunkData.Extracted[] chunks, boolean sky) + public SPacketMapChunkBulk(List chunks) { - this.xPositions = x; - this.zPositions = z; - this.chunksData = chunks; - this.sky = sky; + int i = chunks.size(); + this.xPositions = new int[i]; + this.zPositions = new int[i]; + this.chunksData = new SPacketChunkData.Extracted[i]; + + for (int j = 0; j < i; ++j) + { + Chunk chunk = (Chunk)chunks.get(j); + SPacketChunkData.Extracted s21packetchunkdata$extracted = SPacketChunkData.getExtractedData(chunk, true, 0xffffffff); + this.xPositions[j] = chunk.xPos; + this.zPositions[j] = chunk.zPos; + this.chunksData[j] = s21packetchunkdata$extracted; + } } - + /** * Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer buf) throws IOException { - this.sky = buf.readBoolean(); - int i = buf.readVarInt(); + int i = buf.readVarIntFromBuffer(); this.xPositions = new int[i]; this.zPositions = new int[i]; this.chunksData = new SPacketChunkData.Extracted[i]; @@ -40,11 +50,8 @@ public class SPacketMapChunkBulk implements Packet this.xPositions[j] = buf.readInt(); this.zPositions[j] = buf.readInt(); this.chunksData[j] = new SPacketChunkData.Extracted(); - this.chunksData[j].extend = new int[buf.readVarInt()]; - for(int z = 0; z < this.chunksData[j].extend.length; z++) { - this.chunksData[j].extend[z] = buf.readVarInt(); - } - this.chunksData[j].data = new byte[SPacketChunkData.getSize(this.chunksData[j].extend.length, this.sky, true)]; + this.chunksData[j].dataSize = buf.readInt(); + this.chunksData[j].data = new byte[SPacketChunkData.getSize(Integer.bitCount(this.chunksData[j].dataSize))]; } for (int k = 0; k < i; ++k) @@ -58,17 +65,13 @@ public class SPacketMapChunkBulk implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeBoolean(this.sky); - buf.writeVarInt(this.chunksData.length); + buf.writeVarIntToBuffer(this.chunksData.length); for (int i = 0; i < this.xPositions.length; ++i) { buf.writeInt(this.xPositions[i]); buf.writeInt(this.zPositions[i]); - buf.writeVarInt(this.chunksData[i].extend.length); - for(int z = 0; z < this.chunksData[i].extend.length; z++) { - buf.writeVarInt(this.chunksData[i].extend[z]); - } + buf.writeInt(this.chunksData[i].dataSize); } for (int j = 0; j < this.xPositions.length; ++j) @@ -104,9 +107,9 @@ public class SPacketMapChunkBulk implements Packet { return this.chunksData[p_149256_1_].data; } - - public int[] getChunkExtend(int index) + + public int getChunkSize(int p_179754_1_) { - return this.chunksData[index].extend; + return this.chunksData[p_179754_1_].dataSize; } } diff --git a/common/src/main/java/common/packet/SPacketMessage.java b/common/src/common/packet/SPacketMessage.java similarity index 94% rename from common/src/main/java/common/packet/SPacketMessage.java rename to common/src/common/packet/SPacketMessage.java index 4b72178..3832c29 100755 --- a/common/src/main/java/common/packet/SPacketMessage.java +++ b/common/src/common/packet/SPacketMessage.java @@ -23,7 +23,7 @@ public class SPacketMessage implements Packet { } public void readPacketData(PacketBuffer buf) throws IOException { - this.message = buf.readString(32767); + this.message = buf.readStringFromBuffer(32767); this.type = buf.readEnumValue(Type.class); } diff --git a/common/src/main/java/common/packet/SPacketMultiBlockChange.java b/common/src/common/packet/SPacketMultiBlockChange.java similarity index 56% rename from common/src/main/java/common/packet/SPacketMultiBlockChange.java rename to common/src/common/packet/SPacketMultiBlockChange.java index df86ebb..97d5e60 100755 --- a/common/src/main/java/common/packet/SPacketMultiBlockChange.java +++ b/common/src/common/packet/SPacketMultiBlockChange.java @@ -8,6 +8,7 @@ import common.network.Packet; import common.network.PacketBuffer; import common.util.BlockPos; import common.util.ChunkPos; +import common.world.Chunk; import common.world.State; public class SPacketMultiBlockChange implements Packet @@ -15,18 +16,19 @@ public class SPacketMultiBlockChange implements Packet private ChunkPos chunkPosCoord; private SPacketMultiBlockChange.BlockUpdateData[] changedBlocks; - public static BlockPos getPos(ChunkPos pos, long position) - { - return new BlockPos(new BlockPos((pos.x << 4) + (int)(position >> 36 & 15L), (int)(position & 4294967295L), (pos.z << 4) + (int)(position >> 32 & 15L))); - } - public SPacketMultiBlockChange() { } - - public SPacketMultiBlockChange(ChunkPos pos, SPacketMultiBlockChange.BlockUpdateData[] changes) { - this.chunkPosCoord = pos; - this.changedBlocks = changes; + + public SPacketMultiBlockChange(int p_i45181_1_, int[] crammedPositionsIn, Chunk chunkIn) + { + this.chunkPosCoord = new ChunkPos(chunkIn.xPos, chunkIn.zPos); + this.changedBlocks = new SPacketMultiBlockChange.BlockUpdateData[p_i45181_1_]; + + for (int i = 0; i < this.changedBlocks.length; ++i) + { + this.changedBlocks[i] = new SPacketMultiBlockChange.BlockUpdateData(crammedPositionsIn[i], chunkIn); + } } /** @@ -35,11 +37,11 @@ public class SPacketMultiBlockChange implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.chunkPosCoord = new ChunkPos(buf.readInt(), buf.readInt()); - this.changedBlocks = new SPacketMultiBlockChange.BlockUpdateData[buf.readVarInt()]; + this.changedBlocks = new SPacketMultiBlockChange.BlockUpdateData[buf.readVarIntFromBuffer()]; for (int i = 0; i < this.changedBlocks.length; ++i) { - this.changedBlocks[i] = new SPacketMultiBlockChange.BlockUpdateData(buf.readLong(), (State)BlockRegistry.STATEMAP.getByValue(buf.readVarInt())); + this.changedBlocks[i] = new SPacketMultiBlockChange.BlockUpdateData(buf.readInt(), (State)BlockRegistry.STATEMAP.getByValue(buf.readVarIntFromBuffer())); } } @@ -50,12 +52,12 @@ public class SPacketMultiBlockChange implements Packet { buf.writeInt(this.chunkPosCoord.x); buf.writeInt(this.chunkPosCoord.z); - buf.writeVarInt(this.changedBlocks.length); + buf.writeVarIntToBuffer(this.changedBlocks.length); for (SPacketMultiBlockChange.BlockUpdateData s22packetmultiblockchange$blockupdatedata : this.changedBlocks) { - buf.writeLong(s22packetmultiblockchange$blockupdatedata.getRawPos()); - buf.writeVarInt(BlockRegistry.STATEMAP.get(s22packetmultiblockchange$blockupdatedata.getBlockState())); + buf.writeInt(s22packetmultiblockchange$blockupdatedata.getRawPos()); + buf.writeVarIntToBuffer(BlockRegistry.STATEMAP.get(s22packetmultiblockchange$blockupdatedata.getBlockState())); } } @@ -72,23 +74,30 @@ public class SPacketMultiBlockChange implements Packet return this.changedBlocks; } - public ChunkPos getChunkPos() + public class BlockUpdateData { - return this.chunkPosCoord; - } - - public static class BlockUpdateData - { - private final long position; + private final int position; private final State blockState; - public BlockUpdateData(long raw, State state) + public BlockUpdateData(int raw, State state) { this.position = raw; this.blockState = state; } - - public long getRawPos() + + public BlockUpdateData(int raw, Chunk chunkIn) + { + this.position = raw; + this.blockState = chunkIn.getState(this.getPos()); + } + + public BlockPos getPos() + { + ChunkPos r = SPacketMultiBlockChange.this.chunkPosCoord; + return new BlockPos(new BlockPos((r.x << 4) + (this.position >> 13 & 15), this.position & 511, (r.z << 4) + (this.position >> 9 & 15))); + } + + public int getRawPos() { return this.position; } diff --git a/common/src/main/java/common/packet/SPacketPlayerPosLook.java b/common/src/common/packet/SPacketPlayerPosLook.java similarity index 100% rename from common/src/main/java/common/packet/SPacketPlayerPosLook.java rename to common/src/common/packet/SPacketPlayerPosLook.java diff --git a/common/src/main/java/common/packet/SPacketRespawn.java b/common/src/common/packet/SPacketRespawn.java similarity index 78% rename from common/src/main/java/common/packet/SPacketRespawn.java rename to common/src/common/packet/SPacketRespawn.java index fba7d5a..3e8d3fd 100755 --- a/common/src/main/java/common/packet/SPacketRespawn.java +++ b/common/src/common/packet/SPacketRespawn.java @@ -3,14 +3,14 @@ package common.packet; import java.io.IOException; import common.dimension.Dimension; +import common.nbt.NBTTagCompound; import common.network.IClientPlayer; import common.network.Packet; import common.network.PacketBuffer; -import common.tags.TagObject; public class SPacketRespawn implements Packet { - private TagObject dimension; + private NBTTagCompound dimension; private int type; private boolean editor; @@ -20,7 +20,7 @@ public class SPacketRespawn implements Packet public SPacketRespawn(Dimension dimensionIn, int type, boolean editor) { - this.dimension = dimensionIn.toTags(false); + this.dimension = dimensionIn.toNbt(false); this.type = type; this.editor = editor; } @@ -32,21 +32,21 @@ public class SPacketRespawn implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.dimension = buf.readTag(); + this.dimension = buf.readNBTTagCompoundFromBuffer(); this.type = buf.readUnsignedShort(); this.editor = buf.readBoolean(); } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeTag(this.dimension); + buf.writeNBTTagCompoundToBuffer(this.dimension); buf.writeShort(this.type & 65535); buf.writeBoolean(this.editor); } public Dimension getDimension() { - return Dimension.getByTag(this.dimension, false); + return Dimension.getByNbt(this.dimension, false); } public int getEntityType() diff --git a/common/src/main/java/common/packet/SPacketServerTick.java b/common/src/common/packet/SPacketServerTick.java similarity index 71% rename from common/src/main/java/common/packet/SPacketServerTick.java rename to common/src/common/packet/SPacketServerTick.java index 0a9eac1..4cac35c 100644 --- a/common/src/main/java/common/packet/SPacketServerTick.java +++ b/common/src/common/packet/SPacketServerTick.java @@ -8,20 +8,24 @@ import common.network.PacketBuffer; public class SPacketServerTick implements Packet { private int time; + private String serverInfo; public SPacketServerTick() { } - public SPacketServerTick(int time) { + public SPacketServerTick(int time, String info) { this.time = time; + this.serverInfo = info; } public void readPacketData(PacketBuffer buf) throws IOException { this.time = buf.readInt(); + this.serverInfo = buf.readStringFromBuffer(64); } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeInt(this.time); + buf.writeString(this.serverInfo); } public void processPacket(IClientPlayer handler) { @@ -31,4 +35,8 @@ public class SPacketServerTick implements Packet { public int getTime() { return this.time; } + + public String getServerinfo() { + return this.serverInfo; + } } diff --git a/common/src/main/java/common/packet/SPacketSetExperience.java b/common/src/common/packet/SPacketSetExperience.java similarity index 86% rename from common/src/main/java/common/packet/SPacketSetExperience.java rename to common/src/common/packet/SPacketSetExperience.java index b2f2b06..1b60ca9 100755 --- a/common/src/main/java/common/packet/SPacketSetExperience.java +++ b/common/src/common/packet/SPacketSetExperience.java @@ -29,8 +29,8 @@ public class SPacketSetExperience implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.progress = buf.readFloat(); - this.level = buf.readVarInt(); - this.totalExperience = buf.readVarInt(); + this.level = buf.readVarIntFromBuffer(); + this.totalExperience = buf.readVarIntFromBuffer(); } /** @@ -39,8 +39,8 @@ public class SPacketSetExperience implements Packet public void writePacketData(PacketBuffer buf) throws IOException { buf.writeFloat(this.progress); - buf.writeVarInt(this.level); - buf.writeVarInt(this.totalExperience); + buf.writeVarIntToBuffer(this.level); + buf.writeVarIntToBuffer(this.totalExperience); } /** diff --git a/common/src/main/java/common/packet/SPacketSkin.java b/common/src/common/packet/SPacketSkin.java similarity index 94% rename from common/src/main/java/common/packet/SPacketSkin.java rename to common/src/common/packet/SPacketSkin.java index 4cf14f1..2efdcc9 100755 --- a/common/src/main/java/common/packet/SPacketSkin.java +++ b/common/src/common/packet/SPacketSkin.java @@ -40,7 +40,7 @@ public class SPacketSkin implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.id = buf.readVarInt(); + this.id = buf.readVarIntFromBuffer(); // this.model = buf.readEnumValue(ModelType.class); this.texture = buf.readByteArray(); if(this.texture.length == 0) { @@ -53,7 +53,7 @@ public class SPacketSkin implements Packet public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.id); + buf.writeVarIntToBuffer(this.id); // buf.writeEnumValue(this.model); buf.writeByteArray(this.texture == null ? new byte[0] : this.texture); } diff --git a/common/src/main/java/common/packet/SPacketSpawnMob.java b/common/src/common/packet/SPacketSpawnMob.java similarity index 97% rename from common/src/main/java/common/packet/SPacketSpawnMob.java rename to common/src/common/packet/SPacketSpawnMob.java index 5542cb0..b26ba57 100755 --- a/common/src/main/java/common/packet/SPacketSpawnMob.java +++ b/common/src/common/packet/SPacketSpawnMob.java @@ -84,7 +84,7 @@ public class SPacketSpawnMob implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); + this.entityId = buf.readVarIntFromBuffer(); this.type = buf.readUnsignedShort(); this.x = buf.readInt(); this.y = buf.readInt(); @@ -100,7 +100,7 @@ public class SPacketSpawnMob implements Packet public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); buf.writeShort(this.type & 65535); buf.writeInt(this.x); buf.writeInt(this.y); diff --git a/common/src/main/java/common/packet/SPacketSpawnObject.java b/common/src/common/packet/SPacketSpawnObject.java similarity index 97% rename from common/src/main/java/common/packet/SPacketSpawnObject.java rename to common/src/common/packet/SPacketSpawnObject.java index 6ae2456..6af450a 100755 --- a/common/src/main/java/common/packet/SPacketSpawnObject.java +++ b/common/src/common/packet/SPacketSpawnObject.java @@ -106,7 +106,7 @@ public class SPacketSpawnObject implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); + this.entityId = buf.readVarIntFromBuffer(); this.type = buf.readUnsignedShort(); this.x = buf.readInt(); this.y = buf.readInt(); @@ -123,7 +123,7 @@ public class SPacketSpawnObject implements Packet public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); buf.writeShort(this.type & 65535); buf.writeInt(this.x); buf.writeInt(this.y); diff --git a/common/src/main/java/common/packet/SPacketSpawnPlayer.java b/common/src/common/packet/SPacketSpawnPlayer.java similarity index 97% rename from common/src/main/java/common/packet/SPacketSpawnPlayer.java rename to common/src/common/packet/SPacketSpawnPlayer.java index a12ede6..7c1ab02 100755 --- a/common/src/main/java/common/packet/SPacketSpawnPlayer.java +++ b/common/src/common/packet/SPacketSpawnPlayer.java @@ -52,7 +52,7 @@ public class SPacketSpawnPlayer implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarInt(); + this.entityId = buf.readVarIntFromBuffer(); this.type = buf.readUnsignedShort(); this.x = buf.readInt(); this.y = buf.readInt(); @@ -75,7 +75,7 @@ public class SPacketSpawnPlayer implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarInt(this.entityId); + buf.writeVarIntToBuffer(this.entityId); buf.writeShort(this.type & 65535); buf.writeInt(this.x); buf.writeInt(this.y); diff --git a/common/src/main/java/common/packet/SPacketTimeUpdate.java b/common/src/common/packet/SPacketTimeUpdate.java similarity index 94% rename from common/src/main/java/common/packet/SPacketTimeUpdate.java rename to common/src/common/packet/SPacketTimeUpdate.java index 4ed2a98..3885c3a 100755 --- a/common/src/main/java/common/packet/SPacketTimeUpdate.java +++ b/common/src/common/packet/SPacketTimeUpdate.java @@ -20,7 +20,7 @@ public class SPacketTimeUpdate implements Packet { public void readPacketData(PacketBuffer buf) throws IOException { this.worldTime = buf.readLong(); - this.serverInfo = buf.readString(512); + this.serverInfo = buf.readStringFromBuffer(512); } public void writePacketData(PacketBuffer buf) throws IOException { diff --git a/common/src/main/java/common/packet/SPacketTrades.java b/common/src/common/packet/SPacketTrades.java similarity index 84% rename from common/src/main/java/common/packet/SPacketTrades.java rename to common/src/common/packet/SPacketTrades.java index 1ef9a4c..94a5e65 100755 --- a/common/src/main/java/common/packet/SPacketTrades.java +++ b/common/src/common/packet/SPacketTrades.java @@ -35,13 +35,13 @@ public class SPacketTrades implements Packet for (int j = 0; j < i; ++j) { - ItemStack itemstack = buf.readItemStack(); - ItemStack itemstack1 = buf.readItemStack(); + ItemStack itemstack = buf.readItemStackFromBuffer(); + ItemStack itemstack1 = buf.readItemStackFromBuffer(); ItemStack itemstack2 = null; if (buf.readBoolean()) { - itemstack2 = buf.readItemStack(); + itemstack2 = buf.readItemStackFromBuffer(); } // boolean flag = buf.readBoolean(); @@ -69,14 +69,14 @@ public class SPacketTrades implements Packet for (int i = 0; i < this.recipes.size(); ++i) { MerchantRecipe merchantrecipe = (MerchantRecipe)this.recipes.get(i); - buf.writeItemStack(merchantrecipe.first()); - buf.writeItemStack(merchantrecipe.result()); - ItemStack itemstack = merchantrecipe.second(); + buf.writeItemStackToBuffer(merchantrecipe.getItemToBuy()); + buf.writeItemStackToBuffer(merchantrecipe.getItemToSell()); + ItemStack itemstack = merchantrecipe.getSecondItemToBuy(); buf.writeBoolean(itemstack != null); if (itemstack != null) { - buf.writeItemStack(itemstack); + buf.writeItemStackToBuffer(itemstack); } // buf.writeBoolean(merchantrecipe.isRecipeDisabled()); diff --git a/common/src/main/java/common/packet/SPacketUpdateHealth.java b/common/src/common/packet/SPacketUpdateHealth.java similarity index 100% rename from common/src/main/java/common/packet/SPacketUpdateHealth.java rename to common/src/common/packet/SPacketUpdateHealth.java diff --git a/common/src/main/java/common/packet/SPacketWorld.java b/common/src/common/packet/SPacketWorld.java similarity index 92% rename from common/src/main/java/common/packet/SPacketWorld.java rename to common/src/common/packet/SPacketWorld.java index 6b79517..17ff613 100755 --- a/common/src/main/java/common/packet/SPacketWorld.java +++ b/common/src/common/packet/SPacketWorld.java @@ -26,14 +26,14 @@ public class SPacketWorld implements Packet { public void readPacketData(PacketBuffer buf) throws IOException { this.gravity = buf.readFloat(); - this.timeFactor = buf.readVarInt(); + this.timeFactor = buf.readVarIntFromBuffer(); int flags = buf.readUnsignedByte(); this.dayCycle = (flags & 1) > 0; } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeFloat(this.gravity); - buf.writeVarInt(this.timeFactor); + buf.writeVarIntToBuffer(this.timeFactor); buf.writeByte(this.dayCycle ? 1 : 0); } diff --git a/common/src/main/java/common/pathfinding/NodeProcessor.java b/common/src/common/pathfinding/NodeProcessor.java similarity index 100% rename from common/src/main/java/common/pathfinding/NodeProcessor.java rename to common/src/common/pathfinding/NodeProcessor.java diff --git a/common/src/main/java/common/pathfinding/Path.java b/common/src/common/pathfinding/Path.java similarity index 100% rename from common/src/main/java/common/pathfinding/Path.java rename to common/src/common/pathfinding/Path.java diff --git a/common/src/common/pathfinding/PathCache.java b/common/src/common/pathfinding/PathCache.java new file mode 100755 index 0000000..3af36a8 --- /dev/null +++ b/common/src/common/pathfinding/PathCache.java @@ -0,0 +1,38 @@ +package common.pathfinding; + +import common.init.Blocks; +import common.util.BlockPos; +import common.world.Chunk; +import common.world.ChunkCache; +import common.world.IBlockAccess; +import common.world.State; +import common.world.World; + +public class PathCache extends ChunkCache implements IBlockAccess +{ + public PathCache(World worldIn, BlockPos posFromIn, BlockPos posToIn) + { + super(worldIn, posFromIn, posToIn, 0); + } + + public State getState(BlockPos pos) + { + if (pos.getY() >= 0 && pos.getY() < 512) + { + int i = (pos.getX() >> 4) - this.chunkX; + int j = (pos.getZ() >> 4) - this.chunkZ; + + if (i >= 0 && i < this.chunkArray.length && j >= 0 && j < this.chunkArray[i].length) + { + Chunk chunk = this.chunkArray[i][j]; + + if (chunk != null) + { + return chunk.getState(pos); + } + } + } + + return Blocks.air.getState(); + } +} diff --git a/common/src/main/java/common/pathfinding/PathEntity.java b/common/src/common/pathfinding/PathEntity.java similarity index 100% rename from common/src/main/java/common/pathfinding/PathEntity.java rename to common/src/common/pathfinding/PathEntity.java diff --git a/common/src/main/java/common/pathfinding/PathFinder.java b/common/src/common/pathfinding/PathFinder.java similarity index 100% rename from common/src/main/java/common/pathfinding/PathFinder.java rename to common/src/common/pathfinding/PathFinder.java diff --git a/common/src/main/java/common/pathfinding/PathNavigate.java b/common/src/common/pathfinding/PathNavigate.java similarity index 96% rename from common/src/main/java/common/pathfinding/PathNavigate.java rename to common/src/common/pathfinding/PathNavigate.java index 605a176..8044438 100755 --- a/common/src/main/java/common/pathfinding/PathNavigate.java +++ b/common/src/common/pathfinding/PathNavigate.java @@ -2,6 +2,8 @@ package common.pathfinding; import java.util.List; +import common.attributes.AttributeInstance; +import common.attributes.Attributes; import common.entity.Entity; import common.entity.types.EntityLiving; import common.util.BlockPos; @@ -19,6 +21,11 @@ public abstract class PathNavigate protected PathEntity currentPath; protected double speed; + /** + * The number of blocks (extra) +/- in each axis that get pulled out as cache for the pathfinder's search space + */ + private final AttributeInstance pathSearchRange; + /** Time, in number of ticks, following the current path */ private int totalTicks; @@ -38,6 +45,7 @@ public abstract class PathNavigate { this.theEntity = entitylivingIn; this.worldObj = worldIn; + this.pathSearchRange = entitylivingIn.getEntityAttribute(Attributes.FOLLOW_RANGE); this.pathFinder = this.getPathFinder(); } @@ -56,7 +64,7 @@ public abstract class PathNavigate */ public float getPathSearchRange() { - return (float)this.theEntity.getPathingRange(); + return (float)this.pathSearchRange.getAttributeValue(); } /** @@ -155,8 +163,6 @@ public abstract class PathNavigate this.currentPath = pathentityIn; } - this.removeSunnyPath(); - if (this.currentPath.getCurrentPathLength() == 0) { return false; @@ -314,13 +320,6 @@ public abstract class PathNavigate return this.theEntity.isInLiquid() || this.theEntity.isInMolten(); } - /** - * Trims path data from the end to the first sun covered block - */ - protected void removeSunnyPath() - { - } - /** * Returns true when an entity of specified size could safely walk in a straight line between the two points. Args: * pos1, pos2, entityXSize, entityYSize, entityZSize diff --git a/common/src/main/java/common/pathfinding/PathNavigateClimber.java b/common/src/common/pathfinding/PathNavigateClimber.java similarity index 100% rename from common/src/main/java/common/pathfinding/PathNavigateClimber.java rename to common/src/common/pathfinding/PathNavigateClimber.java diff --git a/common/src/main/java/common/pathfinding/PathNavigateGround.java b/common/src/common/pathfinding/PathNavigateGround.java similarity index 87% rename from common/src/main/java/common/pathfinding/PathNavigateGround.java rename to common/src/common/pathfinding/PathNavigateGround.java index 7a6c5de..afef617 100755 --- a/common/src/main/java/common/pathfinding/PathNavigateGround.java +++ b/common/src/common/pathfinding/PathNavigateGround.java @@ -1,11 +1,10 @@ package common.pathfinding; import common.block.Block; -import common.block.Material; import common.entity.animal.EntityChicken; import common.entity.npc.EntityZombie; import common.entity.types.EntityLiving; -import common.init.Blocks; +import common.material.Material; import common.util.BlockPos; import common.util.ExtMath; import common.util.Vec3; @@ -14,7 +13,6 @@ import common.world.World; public class PathNavigateGround extends PathNavigate { protected WalkNodeProcessor nodeProcessor; - private boolean shouldAvoidSun; public PathNavigateGround(EntityLiving entitylivingIn, World worldIn) { @@ -72,33 +70,6 @@ public class PathNavigateGround extends PathNavigate } } - /** - * Trims path data from the end to the first sun covered block - */ - protected void removeSunnyPath() - { - super.removeSunnyPath(); - - if (this.shouldAvoidSun) - { - if (this.worldObj.canSeeSky(new BlockPos(ExtMath.floord(this.theEntity.posX), (int)(this.theEntity.getEntityBoundingBox().minY + 0.5D), ExtMath.floord(this.theEntity.posZ)))) - { - return; - } - - for (int i = 0; i < this.currentPath.getCurrentPathLength(); ++i) - { - PathPoint pathpoint = this.currentPath.getPathPointFromIndex(i); - - if (this.worldObj.canSeeSky(new BlockPos(pathpoint.xCoord, pathpoint.yCoord, pathpoint.zCoord))) - { - this.currentPath.setCurrentPathLength(i - 1); - return; - } - } - } - } - /** * Returns true when an entity of specified size could safely walk in a straight line between the two points. Args: * pos1, pos2, entityXSize, entityYSize, entityZSize @@ -207,7 +178,7 @@ public class PathNavigateGround extends PathNavigate Block block = this.worldObj.getState(new BlockPos(k, y - 1, l)).getBlock(); Material material = block.getMaterial(); - if (block == Blocks.air) + if (material == Material.air) { return false; } @@ -287,9 +258,4 @@ public class PathNavigateGround extends PathNavigate { return this.nodeProcessor.getCanSwim(); } - - public void setAvoidSun(boolean par1) - { - this.shouldAvoidSun = par1; - } } diff --git a/common/src/main/java/common/pathfinding/PathPoint.java b/common/src/common/pathfinding/PathPoint.java similarity index 100% rename from common/src/main/java/common/pathfinding/PathPoint.java rename to common/src/common/pathfinding/PathPoint.java diff --git a/common/src/main/java/common/pathfinding/SwimNodeProcessor.java b/common/src/common/pathfinding/SwimNodeProcessor.java similarity index 100% rename from common/src/main/java/common/pathfinding/SwimNodeProcessor.java rename to common/src/common/pathfinding/SwimNodeProcessor.java diff --git a/common/src/main/java/common/pathfinding/WalkNodeProcessor.java b/common/src/common/pathfinding/WalkNodeProcessor.java similarity index 96% rename from common/src/main/java/common/pathfinding/WalkNodeProcessor.java rename to common/src/common/pathfinding/WalkNodeProcessor.java index cfe84a6..1233bcd 100755 --- a/common/src/main/java/common/pathfinding/WalkNodeProcessor.java +++ b/common/src/common/pathfinding/WalkNodeProcessor.java @@ -1,14 +1,14 @@ package common.pathfinding; import common.block.Block; -import common.block.Material; -import common.block.artificial.BlockDoor; -import common.block.artificial.BlockFence; -import common.block.artificial.BlockFenceGate; -import common.block.artificial.BlockWall; -import common.block.tech.BlockRailBase; +import common.block.BlockDoor; +import common.block.BlockFence; +import common.block.BlockFenceGate; +import common.block.BlockRailBase; +import common.block.BlockWall; import common.entity.Entity; import common.init.Blocks; +import common.material.Material; import common.util.BlockPos; import common.util.ExtMath; import common.world.IBlockAccess; @@ -205,13 +205,13 @@ public class WalkNodeProcessor extends NodeProcessor mpos.set(i, j, k); Block block = world.getState(mpos).getBlock(); - if (block != Blocks.air) + if (block.getMaterial() != Material.air) { if (block != Blocks.trapdoor && block != Blocks.iron_trapdoor) { if (!block.getMaterial().isColdLiquid()) { - if (!enterDoors && block instanceof BlockDoor && block.getMaterial() == Material.WOOD) + if (!enterDoors && block instanceof BlockDoor && block.getMaterial() == Material.wood) { return 0; } @@ -238,7 +238,7 @@ public class WalkNodeProcessor extends NodeProcessor return -3; } } - else if (!block.isPassable(world, mpos) && (!breakDoors || !(block instanceof BlockDoor) || block.getMaterial() != Material.WOOD)) + else if (!block.isPassable(world, mpos) && (!breakDoors || !(block instanceof BlockDoor) || block.getMaterial() != Material.wood)) { if (block instanceof BlockFence || block instanceof BlockFenceGate || block instanceof BlockWall) { diff --git a/common/src/common/pattern/BlockStateHelper.java b/common/src/common/pattern/BlockStateHelper.java new file mode 100755 index 0000000..df47558 --- /dev/null +++ b/common/src/common/pattern/BlockStateHelper.java @@ -0,0 +1,61 @@ +package common.pattern; + +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Predicate; + +import common.block.Block; +import common.collect.Maps; +import common.properties.IProperty; +import common.world.State; + +public class BlockStateHelper implements Predicate +{ + private final Block block; + private final Map predicates = Maps.newHashMap(); + + private BlockStateHelper(Block blockStateIn) + { + this.block = blockStateIn; + } + + public static BlockStateHelper forBlock(Block blockIn) + { + return new BlockStateHelper(blockIn); + } + + public boolean test(State p_apply_1_) + { + if (p_apply_1_ != null && p_apply_1_.getBlock().equals(this.block)) + { + for (Entry entry : this.predicates.entrySet()) + { + Object object = p_apply_1_.getValue((IProperty)entry.getKey()); + + if (!((Predicate)entry.getValue()).test(object)) + { + return false; + } + } + + return true; + } + else + { + return false; + } + } + + public > BlockStateHelper where(IProperty property, Predicate is) + { + if (!this.block.getPropertyMap().contains(property)) + { + throw new IllegalArgumentException(this.block + " cannot support property " + property); + } + else + { + this.predicates.put(property, is); + return this; + } + } +} diff --git a/common/src/main/java/common/potion/Potion.java b/common/src/common/potion/Potion.java similarity index 56% rename from common/src/main/java/common/potion/Potion.java rename to common/src/common/potion/Potion.java index f711c42..c2eab2f 100755 --- a/common/src/main/java/common/potion/Potion.java +++ b/common/src/common/potion/Potion.java @@ -1,44 +1,41 @@ package common.potion; import java.util.Map; +import java.util.Map.Entry; + +import common.attributes.Attribute; +import common.attributes.AttributeInstance; +import common.attributes.AttributeMap; +import common.attributes.AttributeModifier; +import common.attributes.Attributes; import common.collect.Maps; -import common.color.TextColor; import common.entity.DamageSource; -import common.entity.npc.EntityNPC; import common.entity.projectile.EntityPotion; import common.entity.types.EntityLiving; -import common.vars.Vars; +import common.init.Config; public enum Potion { - SPEED("speed", "Schnelligkeit", "Trank der Schnelligkeit", false, 8171462) { - public String getTooltip(int amp) { - return String.format(TextColor.BLUE + "+%d%% Geschwindigkeit", 20 * (amp + 1)); - } - }, - SLOWNESS("slowness", "Langsamkeit", "Trank der Langsamkeit", true, 5926017) { - public String getTooltip(int amp) { - return String.format(TextColor.RED + "-%d%% Geschwindigkeit", 15 * (amp + 1)); - } - }, + SPEED("speed", "Schnelligkeit", "Trank der Schnelligkeit", false, 8171462, new PotionModifier(Attributes.MOVEMENT_SPEED, "PotSpd", 0.2, true)), + SLOWNESS("slowness", "Langsamkeit", "Trank der Langsamkeit", true, 5926017, new PotionModifier(Attributes.MOVEMENT_SPEED, "PotSlow", -0.15, true)), HASTE("haste", "Eile", "Trank der Eile", false, 14270531) { public double getEffectiveness() { return 1.5; } }, FATIGUE("mining_fatigue", "Abbaulähmung", "Trank der Trägheit", true, 4866583), - STRENGTH("strength", "Stärke", "Trank der Stärke", false, 9643043) { - public String getTooltip(int amp) { - return String.format(TextColor.BLUE + "+%d%% Angriffsschaden", 50 * (amp + 1)); - } + STRENGTH("strength", "Stärke", "Trank der Stärke", false, 9643043, new PotionModifier(Attributes.ATTACK_DAMAGE, "PotDmg", 2.5, true)) { + public double getAmount(int amp, AttributeModifier modifier) { + return 1.3D * (double)(amp + 1); + } }, - HEAL("health", "Direktheilung", "Trank der Heilung", false, 16262179) { + HEAL("instant_health", "Direktheilung", "Trank der Heilung", false, 16262179) { public boolean isInstant() { return true; } public void onImpact(EntityPotion potion, EntityLiving thrower, EntityLiving entity, int amp, double effect) { if(entity.arePotionsInverted()) { - if(Vars.damagePotion) { + if(Config.damagePotion) { int dmg = (int)(effect * (double)(6 << amp) + 0.5D); if(potion == null) entity.attackEntityFrom(DamageSource.magic, dmg); @@ -51,14 +48,14 @@ public enum Potion { } } }, - DAMAGE("damage", "Direktschaden", "Trank des Schadens", true, 4393481) { + DAMAGE("instant_damage", "Direktschaden", "Trank des Schadens", true, 4393481) { public boolean isInstant() { return true; } public void onImpact(EntityPotion potion, EntityLiving thrower, EntityLiving entity, int amp, double effect) { if(!entity.arePotionsInverted()) { - if(Vars.damagePotion) { + if(Config.damagePotion) { int dmg = (int)(effect * (double)(6 << amp) + 0.5D); if(potion == null) entity.attackEntityFrom(DamageSource.magic, dmg); @@ -90,40 +87,30 @@ public enum Potion { }, RESISTANCE("resistance", "Resistenz", "Trank des Widerstandes", false, 10044730), FIRE_RESISTANCE("fire_resistance", "Feuerschutz", "Trank der Feuerresistenz", false, 14981690), - MANA_GENERATION("mana_generation", "Manaschub", "Trank des Manaschubes", false, 3035801) { + MANA("mana_boost", "Manaschub", "Trank des Manaschubes", false, 3035801) { public void onUpdate(EntityLiving entity, int duration, int amp) { - if(!(entity instanceof EntityNPC npc)) - return; int k = 40 >> amp; - if((k <= 0 || duration % k == 0) && npc.getManaPoints() < npc.getMaxMana()) - npc.healMana(1); + if((k <= 0 || duration % k == 0) && entity.getManaPoints() < entity.getMaxMana()) + entity.healMana(1); } }, - FLYING("flying", null, null, false, 8356754) { - public String getDisplay(int amplifier) { - return amplifier <= 0 ? "Schweben" : "Flugkraft"; - } - - public String getPotionDisplay(int amplifier) { - return amplifier <= 0 ? "Trank des Schwebens" : "Trank der Flugkraft"; - } - }, + FLYING("flying", "Schweben", "Trank des Schwebens", false, 8356754), BLINDNESS("blindness", "Blindheit", "Trank der Blindheit", true, 2039587) { public double getEffectiveness() { return 0.25; } }, NIGHT_VISION("night_vision", "Nachtsicht", "Trank der Nachtsicht", false, 2039713), - STABILITY("stability", "Stabilität", "Trank der Standfestigkeit", false, 5797459), - WEAKNESS("weakness", "Schwäche", "Trank der Schwäche", true, 4738376) { - public String getTooltip(int amp) { - return String.format(TextColor.RED + "-%d%% Angriffsschaden", 20 * (amp + 1)); - } + STABILITY("stability", "Stabilität", "Trank der Standfestigkeit", false, 5797459, new PotionModifier(Attributes.KNOCKBACK_RESISTANCE, "PotStbl", 1.0, false)), + WEAKNESS("weakness", "Schwäche", "Trank der Schwäche", true, 4738376, new PotionModifier(Attributes.ATTACK_DAMAGE, "PotWeak", 2.0, false)) { + public double getAmount(int amp, AttributeModifier modifier) { + return (double)(-0.5F * (float)(amp + 1)); + } }, POISON("poison", "Vergiftung", "Trank der Vergiftung", true, 5149489) { public void onUpdate(EntityLiving entity, int duration, int amp) { int j = 25 >> amp; - if((j <= 0 || duration % j == 0) && (entity.worldObj.client || Vars.damagePoison) && entity.getHealth() > 1) + if((j <= 0 || duration % j == 0) && (entity.worldObj.client || Config.damagePoison) && entity.getHealth() > 1) entity.attackEntityFrom(DamageSource.magic, 1); } @@ -131,34 +118,48 @@ public enum Potion { return 0.25; } }, + HEALTH("health_boost", "Extraenergie", "Trank der Extraenergie", false, 16284963, new PotionModifier(Attributes.MAX_HEALTH, "PotHp", 4.0, false)) { + public void removeModifiers(EntityLiving entity, AttributeMap map, int amp) { + super.removeModifiers(entity, map, amp); + if(entity.getHealth() > entity.getMaxHealth()) + entity.setHealth(entity.getMaxHealth()); + } + }, ABSORPTION("absorption", "Absorption", "Trank der Absorption", false, 2445989) { - public void removeModifiers(EntityLiving entity, int amp) { + public void removeModifiers(EntityLiving entity, AttributeMap map, int amp) { entity.setAbsorptionAmount(entity.getAbsorptionAmount() - (4 * (amp + 1))); + super.removeModifiers(entity, map, amp); } - public void addModifiers(EntityLiving entity, int amp) { + public void addModifiers(EntityLiving entity, AttributeMap map, int amp) { entity.setAbsorptionAmount(entity.getAbsorptionAmount() + (4 * (amp + 1))); + super.addModifiers(entity, map, amp); } }, RADIATION("radiation", "Strahlung", "Radioaktiver Trank", true, 0x00ff00) { public void onUpdate(EntityLiving entity, int duration, int amp) { - if(entity.ticksExisted % 20 == 0 && (entity.worldObj.client || Vars.damageRadiation)) // && entityLivingBaseIn.getHealth() > 1.0F) + if(entity.ticksExisted % 20 == 0 && (entity.worldObj.client || Config.damageRadiation)) // && entityLivingBaseIn.getHealth() > 1.0F) entity.attackEntityFrom(DamageSource.radiation, 1 + amp); } - }, - MANA("mana", "Mana", "Manatrank", false, 0x0000ff) { - public boolean isInstant() { - return true; - } - - public void onImpact(EntityPotion potion, EntityLiving thrower, EntityLiving entity, int amp, double effect) { - if(entity instanceof EntityNPC npc) - npc.healMana(Math.max((int)(effect * (double)(4 << amp) + 0.5D), 0)); - } }; + + private static class PotionModifier { + private final Attribute attribute; + private final String id; + private final double value; + private final boolean multiply; + + public PotionModifier(Attribute attr, String id, double value, boolean multiply) { + this.attribute = attr; + this.id = id; + this.value = value; + this.multiply = multiply; + } + } private static final Map LOOKUP = Maps.newHashMap(); + private final Map modifiers = Maps.newHashMap(); private final String name; private final String effectDisplay; private final String potionDisplay; @@ -175,12 +176,15 @@ public enum Potion { return LOOKUP.get(name); } - private Potion(String name, String effectDisplay, String potionDisplay, boolean bad, int color) { + private Potion(String name, String effectDisplay, String potionDisplay, boolean bad, int color, PotionModifier ... modifiers) { this.name = name; this.bad = bad; this.color = color; this.effectDisplay = effectDisplay; this.potionDisplay = potionDisplay; + for(PotionModifier modifier : modifiers) { + this.modifiers.put(modifier.attribute, new AttributeModifier(AttributeModifier.getModifierId(modifier.id), "potion." + name, modifier.value, modifier.multiply)); + } } public String getName() { @@ -191,11 +195,11 @@ public enum Potion { return this.name; } - public String getDisplay(int amplifier) { - return this.effectDisplay + PotionHelper.getPotionPotency(amplifier); + public String getDisplay() { + return this.effectDisplay; } - public String getPotionDisplay(int amplifier) { + public String getPotionDisplay() { return this.potionDisplay; } @@ -207,6 +211,10 @@ public enum Potion { return this.color; } + public Map getModifiers() { + return this.modifiers; + } + public void onUpdate(EntityLiving entity, int duration, int amp) { } @@ -216,18 +224,31 @@ public enum Potion { public boolean isInstant() { return false; } - - public String getTooltip(int amp) { - return null; + + public double getAmount(int amp, AttributeModifier modifier) { + return modifier.getAmount() * (double)(amp + 1); } public double getEffectiveness() { return this.bad ? 0.5 : 1.0; } - public void removeModifiers(EntityLiving entity, int amp) { + public void removeModifiers(EntityLiving entity, AttributeMap map, int amp) { + for(Entry entry : this.modifiers.entrySet()) { + AttributeInstance attr = map.getAttributeInstance(entry.getKey()); + if(attr != null) + attr.removeModifier(entry.getValue()); + } } - public void addModifiers(EntityLiving entity, int amp) { + public void addModifiers(EntityLiving entity, AttributeMap map, int amp) { + for(Entry entry : this.modifiers.entrySet()) { + AttributeInstance attr = map.getAttributeInstance(entry.getKey()); + if(attr != null) { + AttributeModifier mod = entry.getValue(); + attr.removeModifier(mod); + attr.applyModifier(new AttributeModifier(mod.getID(), "potion." + this.name + " " + amp, this.getAmount(amp, mod), mod.isMultiplied())); + } + } } } diff --git a/common/src/main/java/common/potion/PotionEffect.java b/common/src/common/potion/PotionEffect.java similarity index 78% rename from common/src/main/java/common/potion/PotionEffect.java rename to common/src/common/potion/PotionEffect.java index 861e034..ccbfae5 100755 --- a/common/src/main/java/common/potion/PotionEffect.java +++ b/common/src/common/potion/PotionEffect.java @@ -2,7 +2,7 @@ package common.potion; import common.entity.types.EntityLiving; import common.log.Log; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; public class PotionEffect { private final Potion potion; @@ -36,7 +36,7 @@ public class PotionEffect { public PotionEffect combine(PotionEffect other) { if(this.potion != other.potion) - Log.TICK.warn("PotionEffect.combine(): Diese Methode sollte nur für gleiche Effekte aufgerufen werden!"); + Log.JNI.warn("PotionEffect.combine(): Diese Methode sollte nur für gleiche Effekte aufgerufen werden!"); int duration = this.duration; int amplifier = this.amplifier; int remaining = this.remaining; @@ -105,11 +105,11 @@ public class PotionEffect { } public String getEffectName() { - return this.potion.getDisplay(this.amplifier); + return this.potion.getDisplay(); } public String getPotionName() { - return this.potion.getPotionDisplay(this.amplifier); + return this.potion.getPotionDisplay(); } public String getDurationString() { @@ -135,20 +135,20 @@ public class PotionEffect { && this.thrown == other.thrown && this.remaining == other.remaining && this.ambient == other.ambient; } - public TagObject toTags() { - TagObject tag = new TagObject(); - tag.setString("Type", this.potion.getName()); - tag.setByte("Amplifier", (byte)this.amplifier); - tag.setInt("Duration", this.duration); - tag.setInt("Remaining", this.remaining); - tag.setBool("Ambient", this.ambient); - tag.setBool("Particles", this.particles); - return tag; + public NBTTagCompound toNbt() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setString("Type", this.potion.getName()); + nbt.setByte("Amplifier", (byte)this.amplifier); + nbt.setInteger("Duration", this.duration); + nbt.setInteger("Remaining", this.remaining); + nbt.setBoolean("Ambient", this.ambient); + nbt.setBoolean("Particles", this.particles); + return nbt; } - public static PotionEffect fromTags(TagObject tag) { - Potion potion = Potion.getByName(tag.getString("Type")); - return potion == null ? null : new PotionEffect(potion, tag.getInt("Duration"), (int)(tag.getByte("Amplifier") & 255), tag.getBool("Ambient"), tag.getBool("Particles")) - .setRemaining(tag.getInt("Remaining")); + public static PotionEffect fromNbt(NBTTagCompound nbt) { + Potion potion = Potion.getByName(nbt.getString("Type")); + return potion == null ? null : new PotionEffect(potion, nbt.getInteger("Duration"), (int)(nbt.getByte("Amplifier") & 255), nbt.getBoolean("Ambient"), nbt.getBoolean("Particles")) + .setRemaining(nbt.getInteger("Remaining")); } } diff --git a/common/src/main/java/common/potion/PotionHelper.java b/common/src/common/potion/PotionHelper.java similarity index 100% rename from common/src/main/java/common/potion/PotionHelper.java rename to common/src/common/potion/PotionHelper.java diff --git a/common/src/main/java/common/properties/IProperty.java b/common/src/common/properties/IProperty.java similarity index 100% rename from common/src/main/java/common/properties/IProperty.java rename to common/src/common/properties/IProperty.java diff --git a/common/src/main/java/common/properties/PropertyBool.java b/common/src/common/properties/PropertyBool.java similarity index 100% rename from common/src/main/java/common/properties/PropertyBool.java rename to common/src/common/properties/PropertyBool.java diff --git a/common/src/main/java/common/properties/PropertyDirection.java b/common/src/common/properties/PropertyDirection.java similarity index 100% rename from common/src/main/java/common/properties/PropertyDirection.java rename to common/src/common/properties/PropertyDirection.java diff --git a/common/src/main/java/common/properties/PropertyEnum.java b/common/src/common/properties/PropertyEnum.java similarity index 100% rename from common/src/main/java/common/properties/PropertyEnum.java rename to common/src/common/properties/PropertyEnum.java diff --git a/common/src/main/java/common/properties/PropertyHelper.java b/common/src/common/properties/PropertyHelper.java similarity index 100% rename from common/src/main/java/common/properties/PropertyHelper.java rename to common/src/common/properties/PropertyHelper.java diff --git a/common/src/main/java/common/properties/PropertyInteger.java b/common/src/common/properties/PropertyInteger.java similarity index 100% rename from common/src/main/java/common/properties/PropertyInteger.java rename to common/src/common/properties/PropertyInteger.java diff --git a/common/src/main/java/common/rng/ImprovedGen.java b/common/src/common/rng/ImprovedGen.java similarity index 100% rename from common/src/main/java/common/rng/ImprovedGen.java rename to common/src/common/rng/ImprovedGen.java diff --git a/common/src/main/java/common/rng/ImprovedGenOld.java b/common/src/common/rng/ImprovedGenOld.java similarity index 100% rename from common/src/main/java/common/rng/ImprovedGenOld.java rename to common/src/common/rng/ImprovedGenOld.java diff --git a/common/src/main/java/common/rng/NoiseGen.java b/common/src/common/rng/NoiseGen.java similarity index 100% rename from common/src/main/java/common/rng/NoiseGen.java rename to common/src/common/rng/NoiseGen.java diff --git a/common/src/main/java/common/rng/OctaveGen.java b/common/src/common/rng/OctaveGen.java similarity index 100% rename from common/src/main/java/common/rng/OctaveGen.java rename to common/src/common/rng/OctaveGen.java diff --git a/common/src/main/java/common/rng/OctaveGenOld.java b/common/src/common/rng/OctaveGenOld.java similarity index 100% rename from common/src/main/java/common/rng/OctaveGenOld.java rename to common/src/common/rng/OctaveGenOld.java diff --git a/common/src/main/java/common/rng/PerlinGen.java b/common/src/common/rng/PerlinGen.java similarity index 100% rename from common/src/main/java/common/rng/PerlinGen.java rename to common/src/common/rng/PerlinGen.java diff --git a/common/src/main/java/common/rng/PerlinGenOld.java b/common/src/common/rng/PerlinGenOld.java similarity index 100% rename from common/src/main/java/common/rng/PerlinGenOld.java rename to common/src/common/rng/PerlinGenOld.java diff --git a/common/src/main/java/common/rng/Random.java b/common/src/common/rng/Random.java similarity index 100% rename from common/src/main/java/common/rng/Random.java rename to common/src/common/rng/Random.java diff --git a/common/src/main/java/common/rng/RngItem.java b/common/src/common/rng/RngItem.java similarity index 100% rename from common/src/main/java/common/rng/RngItem.java rename to common/src/common/rng/RngItem.java diff --git a/common/src/main/java/common/rng/SimplexGen.java b/common/src/common/rng/SimplexGen.java similarity index 100% rename from common/src/main/java/common/rng/SimplexGen.java rename to common/src/common/rng/SimplexGen.java diff --git a/common/src/main/java/common/rng/SimplexGenOld.java b/common/src/common/rng/SimplexGenOld.java similarity index 100% rename from common/src/main/java/common/rng/SimplexGenOld.java rename to common/src/common/rng/SimplexGenOld.java diff --git a/common/src/main/java/common/rng/WeightedList.java b/common/src/common/rng/WeightedList.java similarity index 100% rename from common/src/main/java/common/rng/WeightedList.java rename to common/src/common/rng/WeightedList.java diff --git a/common/src/main/java/common/sound/EventType.java b/common/src/common/sound/EventType.java similarity index 100% rename from common/src/main/java/common/sound/EventType.java rename to common/src/common/sound/EventType.java diff --git a/common/src/main/java/common/sound/MovingSound.java b/common/src/common/sound/MovingSound.java similarity index 100% rename from common/src/main/java/common/sound/MovingSound.java rename to common/src/common/sound/MovingSound.java diff --git a/common/src/main/java/common/sound/MovingSoundMinecart.java b/common/src/common/sound/MovingSoundMinecart.java similarity index 100% rename from common/src/main/java/common/sound/MovingSoundMinecart.java rename to common/src/common/sound/MovingSoundMinecart.java diff --git a/common/src/main/java/common/sound/MovingSoundMinecartRiding.java b/common/src/common/sound/MovingSoundMinecartRiding.java similarity index 100% rename from common/src/main/java/common/sound/MovingSoundMinecartRiding.java rename to common/src/common/sound/MovingSoundMinecartRiding.java diff --git a/common/src/main/java/common/sound/PositionedSound.java b/common/src/common/sound/PositionedSound.java similarity index 100% rename from common/src/main/java/common/sound/PositionedSound.java rename to common/src/common/sound/PositionedSound.java diff --git a/common/src/main/java/common/sound/Sound.java b/common/src/common/sound/Sound.java similarity index 100% rename from common/src/main/java/common/sound/Sound.java rename to common/src/common/sound/Sound.java diff --git a/common/src/main/java/common/tileentity/IHopper.java b/common/src/common/tileentity/IHopper.java similarity index 100% rename from common/src/main/java/common/tileentity/IHopper.java rename to common/src/common/tileentity/IHopper.java diff --git a/common/src/main/java/common/tileentity/IInteractionObject.java b/common/src/common/tileentity/IInteractionObject.java similarity index 100% rename from common/src/main/java/common/tileentity/IInteractionObject.java rename to common/src/common/tileentity/IInteractionObject.java diff --git a/common/src/main/java/common/tileentity/ILockableContainer.java b/common/src/common/tileentity/ILockableContainer.java similarity index 72% rename from common/src/main/java/common/tileentity/ILockableContainer.java rename to common/src/common/tileentity/ILockableContainer.java index f534a92..df4cbca 100755 --- a/common/src/main/java/common/tileentity/ILockableContainer.java +++ b/common/src/common/tileentity/ILockableContainer.java @@ -6,7 +6,7 @@ public interface ILockableContainer extends IInventory, IInteractionObject { boolean isLocked(); - void setLockCode(Passcode code); + void setLockCode(LockCode code); - Passcode getLockCode(); + LockCode getLockCode(); } diff --git a/common/src/main/java/common/tileentity/ITickable.java b/common/src/common/tileentity/ITickable.java similarity index 100% rename from common/src/main/java/common/tileentity/ITickable.java rename to common/src/common/tileentity/ITickable.java diff --git a/common/src/main/java/common/tileentity/IWorldNameable.java b/common/src/common/tileentity/IWorldNameable.java similarity index 100% rename from common/src/main/java/common/tileentity/IWorldNameable.java rename to common/src/common/tileentity/IWorldNameable.java diff --git a/common/src/common/tileentity/LocalBlockIntercommunication.java b/common/src/common/tileentity/LocalBlockIntercommunication.java new file mode 100755 index 0000000..caa5a25 --- /dev/null +++ b/common/src/common/tileentity/LocalBlockIntercommunication.java @@ -0,0 +1,51 @@ +package common.tileentity; + +import common.entity.npc.EntityNPC; +import common.inventory.Container; +import common.inventory.InventoryPlayer; + +public class LocalBlockIntercommunication implements IInteractionObject +{ + private String guiID; + private String displayName; + + public LocalBlockIntercommunication(String guiIdIn, String displayNameIn) + { + this.guiID = guiIdIn; + this.displayName = displayNameIn; + } + + public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) + { + throw new UnsupportedOperationException(); + } + + /** + * Get the name of this object. For players this returns their username + */ + public String getName() + { + return this.displayName; + } + + /** + * Returns true if this thing is named + */ + public boolean hasCustomName() + { + return true; + } + + public String getGuiID() + { + return this.guiID; + } + + /** + * Get the formatted ChatComponent that will be used for the sender's username in chat + */ + public String getCommandName() + { + return this.displayName; + } +} diff --git a/common/src/common/tileentity/LockCode.java b/common/src/common/tileentity/LockCode.java new file mode 100755 index 0000000..cc8da4e --- /dev/null +++ b/common/src/common/tileentity/LockCode.java @@ -0,0 +1,42 @@ +package common.tileentity; + +import common.nbt.NBTTagCompound; + +public class LockCode +{ + public static final LockCode EMPTY_CODE = new LockCode(""); + private final String lock; + + public LockCode(String code) + { + this.lock = code; + } + + public boolean isEmpty() + { + return this.lock == null || this.lock.isEmpty(); + } + + public String getLock() + { + return this.lock; + } + + public void toNBT(NBTTagCompound nbt) + { + nbt.setString("Lock", this.lock); + } + + public static LockCode fromNBT(NBTTagCompound nbt) + { + if (nbt.hasKey("Lock", 8)) + { + String s = nbt.getString("Lock"); + return new LockCode(s); + } + else + { + return EMPTY_CODE; + } + } +} diff --git a/common/src/main/java/common/tileentity/MachineResource.java b/common/src/common/tileentity/MachineResource.java similarity index 76% rename from common/src/main/java/common/tileentity/MachineResource.java rename to common/src/common/tileentity/MachineResource.java index b56840c..07075bd 100755 --- a/common/src/main/java/common/tileentity/MachineResource.java +++ b/common/src/common/tileentity/MachineResource.java @@ -1,6 +1,6 @@ package common.tileentity; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; public class MachineResource { public static enum Type { @@ -23,20 +23,20 @@ public class MachineResource { this.overcharge = over; } - public void readFromNbt(TagObject tag) { - this.amount = tag.getInt("Amount"); - this.capacity = tag.getInt("Capacity"); - this.undercharge = tag.getInt("Under"); - this.overcharge = tag.getInt("Over"); - this.entropy = tag.getInt("Entropy"); + public void readFromNbt(NBTTagCompound tag) { + this.amount = tag.getInteger("Amount"); + this.capacity = tag.getInteger("Capacity"); + this.undercharge = tag.getInteger("Under"); + this.overcharge = tag.getInteger("Over"); + this.entropy = tag.getInteger("Entropy"); } - public void writeToNbt(TagObject tag) { - tag.setInt("Amount", this.amount); - tag.setInt("Capacity", this.capacity); - tag.setInt("Under", this.undercharge); - tag.setInt("Over", this.overcharge); - tag.setInt("Entropy", this.entropy); + public void writeToNbt(NBTTagCompound tag) { + tag.setInteger("Amount", this.amount); + tag.setInteger("Capacity", this.capacity); + tag.setInteger("Under", this.undercharge); + tag.setInteger("Over", this.overcharge); + tag.setInteger("Entropy", this.entropy); } public void setValue(int value) { diff --git a/common/src/main/java/common/tileentity/TileEntity.java b/common/src/common/tileentity/TileEntity.java similarity index 86% rename from common/src/main/java/common/tileentity/TileEntity.java rename to common/src/common/tileentity/TileEntity.java index 4892eaa..31da294 100755 --- a/common/src/main/java/common/tileentity/TileEntity.java +++ b/common/src/common/tileentity/TileEntity.java @@ -4,10 +4,9 @@ import common.block.Block; import common.init.Blocks; import common.init.TileRegistry; import common.log.Log; +import common.nbt.NBTTagCompound; import common.network.Packet; -import common.tags.TagObject; import common.util.BlockPos; -import common.world.AWorldServer; import common.world.State; import common.world.World; @@ -53,12 +52,12 @@ public abstract class TileEntity return this.worldObj != null; } - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - this.pos = new BlockPos(compound.getInt("x"), compound.getInt("y"), compound.getInt("z")); + this.pos = new BlockPos(compound.getInteger("x"), compound.getInteger("y"), compound.getInteger("z")); } - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { String s = (String)TileRegistry.CLASS_TO_NAME.get(this.getClass()); @@ -69,16 +68,16 @@ public abstract class TileEntity else { compound.setString("id", s); - compound.setInt("x", this.pos.getX()); - compound.setInt("y", this.pos.getY()); - compound.setInt("z", this.pos.getZ()); + compound.setInteger("x", this.pos.getX()); + compound.setInteger("y", this.pos.getY()); + compound.setInteger("z", this.pos.getZ()); } } /** * Creates a new entity and loads its data from the specified NBT. */ - public static TileEntity createAndLoadEntity(TagObject nbt) + public static TileEntity createAndLoadEntity(NBTTagCompound nbt) { TileEntity tileentity = null; @@ -88,7 +87,7 @@ public abstract class TileEntity if (oclass != null) { - tileentity = (TileEntity)oclass.getConstructor().newInstance(); + tileentity = (TileEntity)oclass.newInstance(); } } catch (Exception exception) @@ -98,11 +97,11 @@ public abstract class TileEntity if (tileentity != null) { - tileentity.readTags(nbt); + tileentity.readFromNBT(nbt); } else { - Log.TICK.warn("Ignoriere Block-Objekt mit ID " + nbt.getString("id")); + Log.JNI.warn("Ignoriere Block-Objekt mit ID " + nbt.getString("id")); } return tileentity; @@ -129,8 +128,7 @@ public abstract class TileEntity { State iblockstate = this.worldObj.getState(this.pos); this.blockMetadata = iblockstate.getBlock().getMetaFromState(iblockstate); - if(!this.worldObj.client) - ((AWorldServer)this.worldObj).markChunkDirty(this.pos); + this.worldObj.markChunkDirty(this.pos, this); if (this.getBlockType() != Blocks.air) { diff --git a/common/src/main/java/common/tileentity/TileEntityBanner.java b/common/src/common/tileentity/TileEntityBanner.java similarity index 82% rename from common/src/main/java/common/tileentity/TileEntityBanner.java rename to common/src/common/tileentity/TileEntityBanner.java index 6f09ac2..90e0668 100755 --- a/common/src/main/java/common/tileentity/TileEntityBanner.java +++ b/common/src/common/tileentity/TileEntityBanner.java @@ -2,22 +2,23 @@ package common.tileentity; import java.util.List; -import common.block.foliage.BlockFlower; +import common.block.BlockFlower; import common.collect.Lists; import common.color.DyeColor; import common.init.Blocks; import common.init.Items; import common.item.ItemStack; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.network.Packet; -import common.packet.SPacketUpdateTileEntity; -import common.tags.TagObject; +import common.packet.S35PacketUpdateTileEntity; public class TileEntityBanner extends TileEntity { private int baseColor; /** A list of all the banner patterns. */ - private List patterns; + private NBTTagList patterns; private boolean field_175119_g; private List patternList; private List colorList; @@ -31,21 +32,18 @@ public class TileEntityBanner extends TileEntity { this.patterns = null; - if (stack.hasTagCompound() && stack.getTagCompound().hasObject("BlockEntityTag")) + if (stack.hasTagCompound() && stack.getTagCompound().hasKey("BlockEntityTag", 10)) { - TagObject nbttagcompound = stack.getTagCompound().getObject("BlockEntityTag"); + NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("BlockEntityTag"); - if (nbttagcompound.hasList("Patterns")) + if (nbttagcompound.hasKey("Patterns")) { - this.patterns = Lists.newArrayList(); - for(TagObject pattern : nbttagcompound.getList("Patterns")) { - this.patterns.add(pattern.copy()); - } + this.patterns = (NBTTagList)nbttagcompound.getTagList("Patterns", 10).copy(); } - if (nbttagcompound.hasInt("Base")) + if (nbttagcompound.hasKey("Base", 99)) { - this.baseColor = nbttagcompound.getInt("Base"); + this.baseColor = nbttagcompound.getInteger("Base"); } else { @@ -63,27 +61,27 @@ public class TileEntityBanner extends TileEntity this.field_175119_g = true; } - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { - super.writeTags(compound); + super.writeToNBT(compound); setBaseColorAndPatterns(compound, this.baseColor, this.patterns); } - public static void setBaseColorAndPatterns(TagObject compound, int baseColorIn, List patternsIn) + public static void setBaseColorAndPatterns(NBTTagCompound compound, int baseColorIn, NBTTagList patternsIn) { - compound.setInt("Base", baseColorIn); + compound.setInteger("Base", baseColorIn); if (patternsIn != null) { - compound.setList("Patterns", patternsIn); + compound.setTag("Patterns", patternsIn); } } - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - super.readTags(compound); - this.baseColor = compound.getInt("Base"); - this.patterns = compound.getList("Patterns"); + super.readFromNBT(compound); + this.baseColor = compound.getInteger("Base"); + this.patterns = compound.getTagList("Patterns", 10); this.patternList = null; this.colorList = null; this.patternResourceLocation = null; @@ -96,7 +94,7 @@ public class TileEntityBanner extends TileEntity */ public Packet getDescriptionPacket() { - return new SPacketUpdateTileEntity(this); + return new S35PacketUpdateTileEntity(this); } public int getBaseColor() @@ -106,8 +104,8 @@ public class TileEntityBanner extends TileEntity public static int getBaseColor(ItemStack stack) { - TagObject nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - return nbttagcompound != null && nbttagcompound.hasInt("Base") ? nbttagcompound.getInt("Base") : stack.getMetadata(); + NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + return nbttagcompound != null && nbttagcompound.hasKey("Base") ? nbttagcompound.getInteger("Base") : stack.getMetadata(); } /** @@ -115,8 +113,8 @@ public class TileEntityBanner extends TileEntity */ public static int getPatterns(ItemStack stack) { - TagObject nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - return nbttagcompound != null && nbttagcompound.hasList("Patterns") ? nbttagcompound.getList("Patterns").size() : 0; + NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + return nbttagcompound != null && nbttagcompound.hasKey("Patterns") ? nbttagcompound.getTagList("Patterns", 10).tagCount() : 0; } public List getPatternList() @@ -125,7 +123,7 @@ public class TileEntityBanner extends TileEntity return this.patternList; } - public List getPatterns() + public NBTTagList getPatterns() { return this.patterns; } @@ -164,15 +162,15 @@ public class TileEntityBanner extends TileEntity if (this.patterns != null) { - for (int i = 0; i < this.patterns.size(); ++i) + for (int i = 0; i < this.patterns.tagCount(); ++i) { - TagObject nbttagcompound = this.patterns.get(i); + NBTTagCompound nbttagcompound = this.patterns.getCompoundTagAt(i); TileEntityBanner.EnumBannerPattern tileentitybanner$enumbannerpattern = TileEntityBanner.EnumBannerPattern.getPatternByID(nbttagcompound.getString("Pattern")); if (tileentitybanner$enumbannerpattern != null) { this.patternList.add(tileentitybanner$enumbannerpattern); - int j = nbttagcompound.getInt("Color"); + int j = nbttagcompound.getInteger("Color"); this.colorList.add(DyeColor.byDyeDamage(j)); this.patternResourceLocation = this.patternResourceLocation + tileentitybanner$enumbannerpattern.getPatternID() + j; } @@ -191,23 +189,23 @@ public class TileEntityBanner extends TileEntity */ public static void removeBannerData(ItemStack stack) { - TagObject nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - if (nbttagcompound != null && nbttagcompound.hasList("Patterns")) + if (nbttagcompound != null && nbttagcompound.hasKey("Patterns", 9)) { - List nbttaglist = nbttagcompound.getList("Patterns"); + NBTTagList nbttaglist = nbttagcompound.getTagList("Patterns", 10); - if (nbttaglist.size() > 0) + if (nbttaglist.tagCount() > 0) { - nbttaglist.remove(nbttaglist.size() - 1); + nbttaglist.removeTag(nbttaglist.tagCount() - 1); - if (nbttaglist.isEmpty()) + if (nbttaglist.hasNoTags()) { - stack.getTagCompound().remove("BlockEntityTag"); + stack.getTagCompound().removeTag("BlockEntityTag"); - if (stack.getTagCompound().isEmpty()) + if (stack.getTagCompound().hasNoTags()) { - stack.setTagCompound((TagObject)null); + stack.setTagCompound((NBTTagCompound)null); } } } diff --git a/common/src/main/java/common/tileentity/TileEntityBeacon.java b/common/src/common/tileentity/TileEntityBeacon.java similarity index 96% rename from common/src/main/java/common/tileentity/TileEntityBeacon.java rename to common/src/common/tileentity/TileEntityBeacon.java index da2d009..e8dc19f 100755 --- a/common/src/main/java/common/tileentity/TileEntityBeacon.java +++ b/common/src/common/tileentity/TileEntityBeacon.java @@ -6,11 +6,11 @@ import common.block.Block; import common.color.DyeColor; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.nbt.NBTTagCompound; import common.network.Packet; -import common.packet.SPacketUpdateTileEntity; +import common.packet.S35PacketUpdateTileEntity; import common.potion.Potion; import common.potion.PotionEffect; -import common.tags.TagObject; import common.util.BlockPos; import common.util.BoundingBox; import common.world.State; @@ -78,7 +78,7 @@ public class TileEntityBeacon extends TileEntity implements ITickable int j = this.pos.getX(); int k = this.pos.getY(); int l = this.pos.getZ(); - BoundingBox axisalignedbb = (new BoundingBox((double)j, (double)k, (double)l, (double)(j + 1), (double)(k + 1), (double)(l + 1))).expand(d0, d0, d0).addCoord(0.0D, (double)World.MAX_SIZE_Y, 0.0D); + BoundingBox axisalignedbb = (new BoundingBox((double)j, (double)k, (double)l, (double)(j + 1), (double)(k + 1), (double)(l + 1))).expand(d0, d0, d0).addCoord(0.0D, (double)World.HEIGHT, 0.0D); List list = this.worldObj.getEntitiesWithinAABB(EntityLiving.class, axisalignedbb); for (EntityLiving entityplayer : list) @@ -280,7 +280,7 @@ public class TileEntityBeacon extends TileEntity implements ITickable */ public Packet getDescriptionPacket() { - return new SPacketUpdateTileEntity(this); + return new S35PacketUpdateTileEntity(this); } public double getMaxRenderDistanceSquared() @@ -301,12 +301,12 @@ public class TileEntityBeacon extends TileEntity implements ITickable // } } - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - super.readTags(compound); - this.primaryEffect = compound.hasString("Primary") ? this.getEffect(compound.getString("Primary")) : null; - this.secondaryEffect = compound.hasString("Secondary") ? this.getEffect(compound.getString("Secondary")) : null; - this.levels = compound.getInt("Levels"); + super.readFromNBT(compound); + this.primaryEffect = compound.hasKey("Primary", 8) ? this.getEffect(compound.getString("Primary")) : null; + this.secondaryEffect = compound.hasKey("Secondary", 8) ? this.getEffect(compound.getString("Secondary")) : null; + this.levels = compound.getInteger("Levels"); // try { this.beamColor = DyeColor.getByName(compound.getString("Color")); // } @@ -315,14 +315,14 @@ public class TileEntityBeacon extends TileEntity implements ITickable // } } - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { - super.writeTags(compound); + super.writeToNBT(compound); if(this.primaryEffect != null) compound.setString("Primary", this.primaryEffect.getName()); if(this.secondaryEffect != null) compound.setString("Secondary", this.secondaryEffect.getName()); - compound.setInt("Levels", this.levels); + compound.setInteger("Levels", this.levels); compound.setString("Color", this.beamColor.getName()); } diff --git a/common/src/main/java/common/tileentity/TileEntityBrewingStand.java b/common/src/common/tileentity/TileEntityBrewingStand.java similarity index 91% rename from common/src/main/java/common/tileentity/TileEntityBrewingStand.java rename to common/src/common/tileentity/TileEntityBrewingStand.java index f883e9b..3ae0f5e 100755 --- a/common/src/main/java/common/tileentity/TileEntityBrewingStand.java +++ b/common/src/common/tileentity/TileEntityBrewingStand.java @@ -3,8 +3,7 @@ package common.tileentity; import java.util.Arrays; import java.util.List; -import common.block.tech.BlockBrewingStand; -import common.collect.Lists; +import common.block.BlockBrewingStand; import common.entity.npc.EntityNPC; import common.init.Items; import common.inventory.Container; @@ -14,9 +13,10 @@ import common.inventory.InventoryPlayer; import common.item.Item; import common.item.ItemPotion; import common.item.ItemStack; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.potion.PotionEffect; import common.potion.PotionHelper; -import common.tags.TagObject; import common.util.Facing; import common.world.State; @@ -129,7 +129,7 @@ public class TileEntityBrewingStand extends TileEntityLockable implements ITicka private boolean canBrew() { - if (this.brewingItemStacks[3] != null && this.brewingItemStacks[3].size > 0) + if (this.brewingItemStacks[3] != null && this.brewingItemStacks[3].stackSize > 0) { ItemStack itemstack = this.brewingItemStacks[3]; @@ -209,9 +209,9 @@ public class TileEntityBrewingStand extends TileEntityLockable implements ITicka } else { - --this.brewingItemStacks[3].size; + --this.brewingItemStacks[3].stackSize; - if (this.brewingItemStacks[3].size <= 0) + if (this.brewingItemStacks[3].stackSize <= 0) { this.brewingItemStacks[3] = null; } @@ -227,49 +227,49 @@ public class TileEntityBrewingStand extends TileEntityLockable implements ITicka return stack == null ? meta : (stack.getItem().isPotionIngredient(stack) ? PotionHelper.applyIngredient(meta, stack.getItem().getPotionEffect(stack)) : meta); } - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - super.readTags(compound); - List nbttaglist = compound.getList("Items"); + super.readFromNBT(compound); + NBTTagList nbttaglist = compound.getTagList("Items", 10); this.brewingItemStacks = new ItemStack[this.getSizeInventory()]; - for (int i = 0; i < nbttaglist.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject nbttagcompound = nbttaglist.get(i); + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); int j = nbttagcompound.getByte("Slot"); if (j >= 0 && j < this.brewingItemStacks.length) { - this.brewingItemStacks[j] = ItemStack.readFromTag(nbttagcompound); + this.brewingItemStacks[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); } } this.brewTime = compound.getShort("BrewTime"); - if (compound.hasString("CustomName")) + if (compound.hasKey("CustomName", 8)) { this.customName = compound.getString("CustomName"); } } - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { - super.writeTags(compound); + super.writeToNBT(compound); compound.setShort("BrewTime", (short)this.brewTime); - List nbttaglist = Lists.newArrayList(); + NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < this.brewingItemStacks.length; ++i) { if (this.brewingItemStacks[i] != null) { - TagObject nbttagcompound = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setByte("Slot", (byte)i); - this.brewingItemStacks[i].writeTags(nbttagcompound); - nbttaglist.add(nbttagcompound); + this.brewingItemStacks[i].writeToNBT(nbttagcompound); + nbttaglist.appendTag(nbttagcompound); } } - compound.setList("Items", nbttaglist); + compound.setTag("Items", nbttaglist); if (this.hasCustomName()) { diff --git a/common/src/main/java/common/tileentity/TileEntityChest.java b/common/src/common/tileentity/TileEntityChest.java similarity index 92% rename from common/src/main/java/common/tileentity/TileEntityChest.java rename to common/src/common/tileentity/TileEntityChest.java index 2e5357c..b85965f 100755 --- a/common/src/main/java/common/tileentity/TileEntityChest.java +++ b/common/src/common/tileentity/TileEntityChest.java @@ -1,8 +1,7 @@ package common.tileentity; import common.block.Block; -import common.block.tech.BlockChest; -import common.collect.Lists; +import common.block.BlockChest; import common.entity.npc.EntityNPC; import common.init.SoundEvent; import common.inventory.Container; @@ -11,8 +10,8 @@ import common.inventory.IInventory; import common.inventory.InventoryLargeChest; import common.inventory.InventoryPlayer; import common.item.ItemStack; -import common.tags.TagObject; -import java.util.List; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.util.BlockPos; import common.util.BoundingBox; import common.util.Facing; @@ -83,7 +82,7 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II { if (this.chestContents[index] != null) { - if (this.chestContents[index].size <= count) + if (this.chestContents[index].stackSize <= count) { ItemStack itemstack1 = this.chestContents[index]; this.chestContents[index] = null; @@ -94,7 +93,7 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II { ItemStack itemstack = this.chestContents[index].splitStack(count); - if (this.chestContents[index].size == 0) + if (this.chestContents[index].stackSize == 0) { this.chestContents[index] = null; } @@ -133,9 +132,9 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II { this.chestContents[index] = stack; - if (stack != null && stack.size > this.getInventoryStackLimit()) + if (stack != null && stack.stackSize > this.getInventoryStackLimit()) { - stack.size = this.getInventoryStackLimit(); + stack.stackSize = this.getInventoryStackLimit(); } this.markDirty(); @@ -162,46 +161,46 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II this.customName = name; } - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - super.readTags(compound); - List nbttaglist = compound.getList("Items"); + super.readFromNBT(compound); + NBTTagList nbttaglist = compound.getTagList("Items", 10); this.chestContents = new ItemStack[this.getSizeInventory()]; - if (compound.hasString("CustomName")) + if (compound.hasKey("CustomName", 8)) { this.customName = compound.getString("CustomName"); } - for (int i = 0; i < nbttaglist.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject nbttagcompound = nbttaglist.get(i); + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); int j = nbttagcompound.getByte("Slot") & 255; if (j >= 0 && j < this.chestContents.length) { - this.chestContents[j] = ItemStack.readFromTag(nbttagcompound); + this.chestContents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); } } } - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { - super.writeTags(compound); - List nbttaglist = Lists.newArrayList(); + super.writeToNBT(compound); + NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < this.chestContents.length; ++i) { if (this.chestContents[i] != null) { - TagObject nbttagcompound = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setByte("Slot", (byte)i); - this.chestContents[i].writeTags(nbttagcompound); - nbttaglist.add(nbttagcompound); + this.chestContents[i].writeToNBT(nbttagcompound); + nbttaglist.appendTag(nbttagcompound); } } - compound.setList("Items", nbttaglist); + compound.setTag("Items", nbttaglist); if (this.hasCustomName()) { diff --git a/common/src/main/java/common/tileentity/TileEntityComparator.java b/common/src/common/tileentity/TileEntityComparator.java similarity index 53% rename from common/src/main/java/common/tileentity/TileEntityComparator.java rename to common/src/common/tileentity/TileEntityComparator.java index 67eeb4f..55b488d 100755 --- a/common/src/main/java/common/tileentity/TileEntityComparator.java +++ b/common/src/common/tileentity/TileEntityComparator.java @@ -1,21 +1,21 @@ package common.tileentity; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; public class TileEntityComparator extends TileEntity { private int outputSignal; - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { - super.writeTags(compound); - compound.setInt("OutputSignal", this.outputSignal); + super.writeToNBT(compound); + compound.setInteger("OutputSignal", this.outputSignal); } - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - super.readTags(compound); - this.outputSignal = compound.getInt("OutputSignal"); + super.readFromNBT(compound); + this.outputSignal = compound.getInteger("OutputSignal"); } public int getOutputSignal() diff --git a/common/src/main/java/common/tileentity/TileEntityDaylightDetector.java b/common/src/common/tileentity/TileEntityDaylightDetector.java similarity index 93% rename from common/src/main/java/common/tileentity/TileEntityDaylightDetector.java rename to common/src/common/tileentity/TileEntityDaylightDetector.java index 6355815..a3518e2 100755 --- a/common/src/main/java/common/tileentity/TileEntityDaylightDetector.java +++ b/common/src/common/tileentity/TileEntityDaylightDetector.java @@ -1,6 +1,6 @@ package common.tileentity; -import common.block.tech.BlockDaylightDetector; +import common.block.BlockDaylightDetector; import common.world.AWorldServer; public class TileEntityDaylightDetector extends TileEntity implements ITickable diff --git a/common/src/main/java/common/tileentity/TileEntityDispenser.java b/common/src/common/tileentity/TileEntityDispenser.java similarity index 83% rename from common/src/main/java/common/tileentity/TileEntityDispenser.java rename to common/src/common/tileentity/TileEntityDispenser.java index 075f70e..d7910b0 100755 --- a/common/src/main/java/common/tileentity/TileEntityDispenser.java +++ b/common/src/common/tileentity/TileEntityDispenser.java @@ -1,15 +1,14 @@ package common.tileentity; -import common.collect.Lists; import common.entity.npc.EntityNPC; import common.inventory.Container; import common.inventory.ContainerDispenser; import common.inventory.IInventory; import common.inventory.InventoryPlayer; import common.item.ItemStack; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.rng.Random; -import common.tags.TagObject; -import java.util.List; public class TileEntityDispenser extends TileEntityLockable implements IInventory { @@ -40,7 +39,7 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor { if (this.stacks[index] != null) { - if (this.stacks[index].size <= count) + if (this.stacks[index].stackSize <= count) { ItemStack itemstack1 = this.stacks[index]; this.stacks[index] = null; @@ -51,7 +50,7 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor { ItemStack itemstack = this.stacks[index].splitStack(count); - if (this.stacks[index].size == 0) + if (this.stacks[index].stackSize == 0) { this.stacks[index] = null; } @@ -106,9 +105,9 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor { this.stacks[index] = stack; - if (stack != null && stack.size > this.getInventoryStackLimit()) + if (stack != null && stack.stackSize > this.getInventoryStackLimit()) { - stack.size = this.getInventoryStackLimit(); + stack.stackSize = this.getInventoryStackLimit(); } this.markDirty(); @@ -153,46 +152,46 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor return this.customName != null; } - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - super.readTags(compound); - List nbttaglist = compound.getList("Items"); + super.readFromNBT(compound); + NBTTagList nbttaglist = compound.getTagList("Items", 10); this.stacks = new ItemStack[this.getSizeInventory()]; - for (int i = 0; i < nbttaglist.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject nbttagcompound = nbttaglist.get(i); + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); int j = nbttagcompound.getByte("Slot") & 255; if (j >= 0 && j < this.stacks.length) { - this.stacks[j] = ItemStack.readFromTag(nbttagcompound); + this.stacks[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); } } - if (compound.hasString("CustomName")) + if (compound.hasKey("CustomName", 8)) { this.customName = compound.getString("CustomName"); } } - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { - super.writeTags(compound); - List nbttaglist = Lists.newArrayList(); + super.writeToNBT(compound); + NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < this.stacks.length; ++i) { if (this.stacks[i] != null) { - TagObject nbttagcompound = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setByte("Slot", (byte)i); - this.stacks[i].writeTags(nbttagcompound); - nbttaglist.add(nbttagcompound); + this.stacks[i].writeToNBT(nbttagcompound); + nbttaglist.appendTag(nbttagcompound); } } - compound.setList("Items", nbttaglist); + compound.setTag("Items", nbttaglist); if (this.hasCustomName()) { diff --git a/common/src/main/java/common/tileentity/TileEntityDropper.java b/common/src/common/tileentity/TileEntityDropper.java similarity index 100% rename from common/src/main/java/common/tileentity/TileEntityDropper.java rename to common/src/common/tileentity/TileEntityDropper.java diff --git a/common/src/main/java/common/tileentity/TileEntityEnchantmentTable.java b/common/src/common/tileentity/TileEntityEnchantmentTable.java similarity index 94% rename from common/src/main/java/common/tileentity/TileEntityEnchantmentTable.java rename to common/src/common/tileentity/TileEntityEnchantmentTable.java index 1a9faba..b3ae645 100755 --- a/common/src/main/java/common/tileentity/TileEntityEnchantmentTable.java +++ b/common/src/common/tileentity/TileEntityEnchantmentTable.java @@ -4,8 +4,8 @@ import common.entity.npc.EntityNPC; import common.inventory.Container; import common.inventory.ContainerEnchantment; import common.inventory.InventoryPlayer; +import common.nbt.NBTTagCompound; import common.rng.Random; -import common.tags.TagObject; import common.util.ExtMath; public class TileEntityEnchantmentTable extends TileEntity implements ITickable, IInteractionObject @@ -23,9 +23,9 @@ public class TileEntityEnchantmentTable extends TileEntity implements ITickable, private static Random rand = new Random(); private String customName; - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { - super.writeTags(compound); + super.writeToNBT(compound); if (this.hasCustomName()) { @@ -33,11 +33,11 @@ public class TileEntityEnchantmentTable extends TileEntity implements ITickable, } } - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - super.readTags(compound); + super.readFromNBT(compound); - if (compound.hasString("CustomName")) + if (compound.hasKey("CustomName", 8)) { this.customName = compound.getString("CustomName"); } diff --git a/common/src/main/java/common/tileentity/TileEntityFurnace.java b/common/src/common/tileentity/TileEntityFurnace.java similarity index 88% rename from common/src/main/java/common/tileentity/TileEntityFurnace.java rename to common/src/common/tileentity/TileEntityFurnace.java index 519647c..af1c0f3 100755 --- a/common/src/main/java/common/tileentity/TileEntityFurnace.java +++ b/common/src/common/tileentity/TileEntityFurnace.java @@ -1,11 +1,9 @@ package common.tileentity; import common.block.Block; -import common.block.Material; -import common.block.artificial.BlockSlab; -import common.block.foliage.BlockSapling; -import common.block.tech.BlockFurnace; -import common.collect.Lists; +import common.block.BlockFurnace; +import common.block.BlockSapling; +import common.block.BlockSlab; import common.entity.npc.EntityNPC; import common.init.Blocks; import common.init.Items; @@ -24,8 +22,9 @@ import common.item.ItemHoe; import common.item.ItemStack; import common.item.ItemSword; import common.item.ItemTool; -import common.tags.TagObject; -import java.util.List; +import common.material.Material; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.util.ExtMath; import common.util.Facing; @@ -74,7 +73,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, { if (this.furnaceItemStacks[index] != null) { - if (this.furnaceItemStacks[index].size <= count) + if (this.furnaceItemStacks[index].stackSize <= count) { ItemStack itemstack1 = this.furnaceItemStacks[index]; this.furnaceItemStacks[index] = null; @@ -84,7 +83,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, { ItemStack itemstack = this.furnaceItemStacks[index].splitStack(count); - if (this.furnaceItemStacks[index].size == 0) + if (this.furnaceItemStacks[index].stackSize == 0) { this.furnaceItemStacks[index] = null; } @@ -123,9 +122,9 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, boolean flag = stack != null && stack.isItemEqual(this.furnaceItemStacks[index]) && ItemStack.areItemStackTagsEqual(stack, this.furnaceItemStacks[index]); this.furnaceItemStacks[index] = stack; - if (stack != null && stack.size > this.getInventoryStackLimit()) + if (stack != null && stack.stackSize > this.getInventoryStackLimit()) { - stack.size = this.getInventoryStackLimit(); + stack.stackSize = this.getInventoryStackLimit(); } if (index == 0 && !flag) @@ -157,20 +156,20 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, this.furnaceCustomName = p_145951_1_; } - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - super.readTags(compound); - List nbttaglist = compound.getList("Items"); + super.readFromNBT(compound); + NBTTagList nbttaglist = compound.getTagList("Items", 10); this.furnaceItemStacks = new ItemStack[this.getSizeInventory()]; - for (int i = 0; i < nbttaglist.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject nbttagcompound = nbttaglist.get(i); + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); int j = nbttagcompound.getByte("Slot"); if (j >= 0 && j < this.furnaceItemStacks.length) { - this.furnaceItemStacks[j] = ItemStack.readFromTag(nbttagcompound); + this.furnaceItemStacks[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); } } @@ -179,32 +178,32 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, this.totalCookTime = compound.getShort("CookTimeTotal"); this.currentItemBurnTime = getItemBurnTime(this.furnaceItemStacks[1]); - if (compound.hasString("CustomName")) + if (compound.hasKey("CustomName", 8)) { this.furnaceCustomName = compound.getString("CustomName"); } } - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { - super.writeTags(compound); + super.writeToNBT(compound); compound.setShort("BurnTime", (short)this.furnaceBurnTime); compound.setShort("CookTime", (short)this.cookTime); compound.setShort("CookTimeTotal", (short)this.totalCookTime); - List nbttaglist = Lists.newArrayList(); + NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < this.furnaceItemStacks.length; ++i) { if (this.furnaceItemStacks[i] != null) { - TagObject nbttagcompound = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setByte("Slot", (byte)i); - this.furnaceItemStacks[i].writeTags(nbttagcompound); - nbttaglist.add(nbttagcompound); + this.furnaceItemStacks[i].writeToNBT(nbttagcompound); + nbttaglist.appendTag(nbttagcompound); } } - compound.setList("Items", nbttaglist); + compound.setTag("Items", nbttaglist); if (this.hasCustomName()) { @@ -260,9 +259,9 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, if (this.furnaceItemStacks[1] != null) { - --this.furnaceItemStacks[1].size; + --this.furnaceItemStacks[1].stackSize; - if (this.furnaceItemStacks[1].size == 0) + if (this.furnaceItemStacks[1].stackSize == 0) { Item item = this.furnaceItemStacks[1].getItem().getContainerItem(); this.furnaceItemStacks[1] = item != null ? new ItemStack(item) : null; @@ -323,7 +322,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, else { ItemStack itemstack = SmeltingRegistry.getResult(this.furnaceItemStacks[0]); - return itemstack == null ? false : (this.furnaceItemStacks[2] == null ? true : (!this.furnaceItemStacks[2].isItemEqual(itemstack) ? false : (this.furnaceItemStacks[2].size < this.getInventoryStackLimit() && this.furnaceItemStacks[2].size < this.furnaceItemStacks[2].getMaxStackSize() ? true : this.furnaceItemStacks[2].size < itemstack.getMaxStackSize()))); + return itemstack == null ? false : (this.furnaceItemStacks[2] == null ? true : (!this.furnaceItemStacks[2].isItemEqual(itemstack) ? false : (this.furnaceItemStacks[2].stackSize < this.getInventoryStackLimit() && this.furnaceItemStacks[2].stackSize < this.furnaceItemStacks[2].getMaxStackSize() ? true : this.furnaceItemStacks[2].stackSize < itemstack.getMaxStackSize()))); } } @@ -342,7 +341,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, } else if (this.furnaceItemStacks[2].getItem() == itemstack.getItem()) { - ++this.furnaceItemStacks[2].size; + ++this.furnaceItemStacks[2].stackSize; } // if (this.furnaceItemStacks[0].getItem() == ItemRegistry.getItemFromBlock(Blocks.sponge) && this.furnaceItemStacks[0].getMetadata() == 1 && this.furnaceItemStacks[1] != null && this.furnaceItemStacks[1].getItem() == Items.bucket) @@ -350,9 +349,9 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, // this.furnaceItemStacks[1] = new ItemStack(Items.water_bucket); // } - --this.furnaceItemStacks[0].size; + --this.furnaceItemStacks[0].stackSize; - if (this.furnaceItemStacks[0].size <= 0) + if (this.furnaceItemStacks[0].stackSize <= 0) { this.furnaceItemStacks[0] = null; } @@ -382,7 +381,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, // return 150; // } - if (block.getMaterial() == Material.WOOD) + if (block.getMaterial() == Material.wood) { return block instanceof BlockSlab ? 150 : 300; } @@ -399,7 +398,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, (item == Items.stick ? 100 : (item == Items.coal ? 1600 : (item instanceof ItemBucket && ((ItemBucket)item).getLiquid() != null && - ((ItemBucket)item).getLiquid().getMaterial() == Material.LAVA ? 20000 : + ((ItemBucket)item).getLiquid().getMaterial() == Material.lava ? 20000 : (item.getBlock() instanceof BlockSapling ? 100 : (item == Items.blaze_rod ? 2400 : 0))))))); } diff --git a/common/src/main/java/common/tileentity/TileEntityHopper.java b/common/src/common/tileentity/TileEntityHopper.java similarity index 88% rename from common/src/main/java/common/tileentity/TileEntityHopper.java rename to common/src/common/tileentity/TileEntityHopper.java index 5da8f31..60db278 100755 --- a/common/src/main/java/common/tileentity/TileEntityHopper.java +++ b/common/src/common/tileentity/TileEntityHopper.java @@ -4,24 +4,24 @@ import java.util.List; import java.util.function.Predicate; import common.block.Block; -import common.block.tech.BlockChest; -import common.block.tech.BlockHopper; -import common.collect.Lists; +import common.block.BlockChest; +import common.block.BlockHopper; import common.entity.Entity; import common.entity.item.EntityItem; import common.entity.npc.EntityNPC; +import common.init.Config; import common.inventory.Container; import common.inventory.ContainerHopper; import common.inventory.IInventory; import common.inventory.ISidedInventory; import common.inventory.InventoryPlayer; import common.item.ItemStack; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; import common.util.Facing; -import common.vars.Vars; import common.world.World; public class TileEntityHopper extends TileEntityLockable implements IHopper, ITickable @@ -30,49 +30,49 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi private String customName; private int transferCooldown = -1; - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - super.readTags(compound); - List nbttaglist = compound.getList("Items"); + super.readFromNBT(compound); + NBTTagList nbttaglist = compound.getTagList("Items", 10); this.inventory = new ItemStack[this.getSizeInventory()]; - if (compound.hasString("CustomName")) + if (compound.hasKey("CustomName", 8)) { this.customName = compound.getString("CustomName"); } - this.transferCooldown = compound.getInt("TransferCooldown"); + this.transferCooldown = compound.getInteger("TransferCooldown"); - for (int i = 0; i < nbttaglist.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject nbttagcompound = nbttaglist.get(i); + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); int j = nbttagcompound.getByte("Slot"); if (j >= 0 && j < this.inventory.length) { - this.inventory[j] = ItemStack.readFromTag(nbttagcompound); + this.inventory[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); } } } - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { - super.writeTags(compound); - List nbttaglist = Lists.newArrayList(); + super.writeToNBT(compound); + NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < this.inventory.length; ++i) { if (this.inventory[i] != null) { - TagObject nbttagcompound = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setByte("Slot", (byte)i); - this.inventory[i].writeTags(nbttagcompound); - nbttaglist.add(nbttagcompound); + this.inventory[i].writeToNBT(nbttagcompound); + nbttaglist.appendTag(nbttagcompound); } } - compound.setList("Items", nbttaglist); - compound.setInt("TransferCooldown", this.transferCooldown); + compound.setTag("Items", nbttaglist); + compound.setInteger("TransferCooldown", this.transferCooldown); if (this.hasCustomName()) { @@ -112,7 +112,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { if (this.inventory[index] != null) { - if (this.inventory[index].size <= count) + if (this.inventory[index].stackSize <= count) { ItemStack itemstack1 = this.inventory[index]; this.inventory[index] = null; @@ -122,7 +122,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { ItemStack itemstack = this.inventory[index].splitStack(count); - if (this.inventory[index].size == 0) + if (this.inventory[index].stackSize == 0) { this.inventory[index] = null; } @@ -160,9 +160,9 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { this.inventory[index] = stack; - if (stack != null && stack.size > this.getInventoryStackLimit()) + if (stack != null && stack.stackSize > this.getInventoryStackLimit()) { - stack.size = this.getInventoryStackLimit(); + stack.stackSize = this.getInventoryStackLimit(); } } @@ -256,7 +256,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi if (flag) { - this.setTransferCooldown(Vars.hopperDelay); + this.setTransferCooldown(Config.hopperDelay); this.markDirty(); return true; } @@ -287,7 +287,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { for (ItemStack itemstack : this.inventory) { - if (itemstack == null || itemstack.size != itemstack.getMaxStackSize()) + if (itemstack == null || itemstack.stackSize != itemstack.getMaxStackSize()) { return false; } @@ -321,7 +321,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi ItemStack itemstack = this.getStackInSlot(i).copy(); ItemStack itemstack1 = putStackInInventoryAllSlots(iinventory, this.decrStackSize(i, 1), enumfacing); - if (itemstack1 == null || itemstack1.size == 0) + if (itemstack1 == null || itemstack1.stackSize == 0) { iinventory.markDirty(); return true; @@ -350,7 +350,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { ItemStack itemstack1 = isidedinventory.getStackInSlot(aint[k]); - if (itemstack1 == null || itemstack1.size != itemstack1.getMaxStackSize()) + if (itemstack1 == null || itemstack1.stackSize != itemstack1.getMaxStackSize()) { return false; } @@ -364,7 +364,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { ItemStack itemstack = inventoryIn.getStackInSlot(j); - if (itemstack == null || itemstack.size != itemstack.getMaxStackSize()) + if (itemstack == null || itemstack.stackSize != itemstack.getMaxStackSize()) { return false; } @@ -474,7 +474,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi ItemStack itemstack1 = itemstack.copy(); ItemStack itemstack2 = putStackInInventoryAllSlots(hopper, inventoryIn.decrStackSize(index, 1), (Facing)null); - if (itemstack2 == null || itemstack2.size == 0) + if (itemstack2 == null || itemstack2.stackSize == 0) { inventoryIn.markDirty(); return true; @@ -503,7 +503,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi ItemStack itemstack = itemIn.getEntityItem().copy(); ItemStack itemstack1 = putStackInInventoryAllSlots(p_145898_0_, itemstack, (Facing)null); - if (itemstack1 != null && itemstack1.size != 0) + if (itemstack1 != null && itemstack1.stackSize != 0) { itemIn.setEntityItemStack(itemstack1); } @@ -527,7 +527,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi ISidedInventory isidedinventory = (ISidedInventory)inventoryIn; int[] aint = isidedinventory.getSlotsForFace(side); - for (int k = 0; k < aint.length && stack != null && stack.size > 0; ++k) + for (int k = 0; k < aint.length && stack != null && stack.stackSize > 0; ++k) { stack = insertStack(inventoryIn, stack, aint[k], side); } @@ -536,13 +536,13 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { int i = inventoryIn.getSizeInventory(); - for (int j = 0; j < i && stack != null && stack.size > 0; ++j) + for (int j = 0; j < i && stack != null && stack.stackSize > 0; ++j) { stack = insertStack(inventoryIn, stack, j, side); } } - if (stack != null && stack.size == 0) + if (stack != null && stack.stackSize == 0) { stack = null; } @@ -585,10 +585,10 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi } else if (canCombine(itemstack, stack)) { - int i = stack.getMaxStackSize() - itemstack.size; - int j = Math.min(stack.size, i); - stack.size -= j; - itemstack.size += j; + int i = stack.getMaxStackSize() - itemstack.stackSize; + int j = Math.min(stack.stackSize, i); + stack.stackSize -= j; + itemstack.stackSize += j; flag = j > 0; } @@ -600,7 +600,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi if (tileentityhopper.mayTransfer()) { - tileentityhopper.setTransferCooldown(Vars.hopperDelay); + tileentityhopper.setTransferCooldown(Config.hopperDelay); } inventoryIn.markDirty(); @@ -685,7 +685,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi public static boolean canCombine(ItemStack stack1, ItemStack stack2) { - return stack1.getItem() != stack2.getItem() ? false : (stack1.getMetadata() != stack2.getMetadata() ? false : (stack1.size > stack1.getMaxStackSize() ? false : ItemStack.areItemStackTagsEqual(stack1, stack2))); + return stack1.getItem() != stack2.getItem() ? false : (stack1.getMetadata() != stack2.getMetadata() ? false : (stack1.stackSize > stack1.getMaxStackSize() ? false : ItemStack.areItemStackTagsEqual(stack1, stack2))); } /** diff --git a/common/src/main/java/common/tileentity/TileEntityLockable.java b/common/src/common/tileentity/TileEntityLockable.java similarity index 63% rename from common/src/main/java/common/tileentity/TileEntityLockable.java rename to common/src/common/tileentity/TileEntityLockable.java index b6ad230..64bb470 100755 --- a/common/src/main/java/common/tileentity/TileEntityLockable.java +++ b/common/src/common/tileentity/TileEntityLockable.java @@ -1,20 +1,20 @@ package common.tileentity; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; public abstract class TileEntityLockable extends TileEntity implements IInteractionObject, ILockableContainer { - private Passcode code = Passcode.EMPTY_CODE; + private LockCode code = LockCode.EMPTY_CODE; - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - super.readTags(compound); - this.code = Passcode.fromNBT(compound); + super.readFromNBT(compound); + this.code = LockCode.fromNBT(compound); } - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { - super.writeTags(compound); + super.writeToNBT(compound); if (this.code != null) { @@ -24,15 +24,15 @@ public abstract class TileEntityLockable extends TileEntity implements IInteract public boolean isLocked() { - return this.code != null && !this.code.empty(); + return this.code != null && !this.code.isEmpty(); } - public Passcode getLockCode() + public LockCode getLockCode() { return this.code; } - public void setLockCode(Passcode code) + public void setLockCode(LockCode code) { this.code = code; } diff --git a/common/src/main/java/common/tileentity/TileEntityDevice.java b/common/src/common/tileentity/TileEntityMachine.java similarity index 68% rename from common/src/main/java/common/tileentity/TileEntityDevice.java rename to common/src/common/tileentity/TileEntityMachine.java index 40d1c1a..ab5df5e 100755 --- a/common/src/main/java/common/tileentity/TileEntityDevice.java +++ b/common/src/common/tileentity/TileEntityMachine.java @@ -1,20 +1,20 @@ package common.tileentity; -import common.collect.Lists; import common.color.TextColor; import common.entity.npc.EntityNPC; import common.inventory.Container; -import common.inventory.ContainerTile; +import common.inventory.ContainerMachine; import common.inventory.InventoryPlayer; import common.item.ItemStack; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.network.Packet; -import common.packet.SPacketUpdateTileEntity; +import common.packet.S35PacketUpdateTileEntity; import common.rng.Random; -import common.tags.TagObject; -import java.util.List; import common.util.ExtMath; +import common.world.AWorldServer; -public abstract class TileEntityDevice extends TileEntityLockable implements IHopper, ITickable { +public abstract class TileEntityMachine extends TileEntityLockable implements IHopper, ITickable { public static enum Status { OFF(TextColor.DGRAY, "Inaktiv"), COOLING(TextColor.YELLOW, "Abkühlen ..."), @@ -34,31 +34,31 @@ public abstract class TileEntityDevice extends TileEntityLockable implements IHo protected final ItemStack[] inventory; protected final MachineResource[] resources; protected final Random rand = new Random(); +// protected boolean isCreative; protected int temperature; protected Status status = Status.OFF; - protected TileEntityDevice(int slots, MachineResource ... resources) { + protected TileEntityMachine(int slots, MachineResource ... resources) { this.inventory = new ItemStack[slots]; this.resources = resources; } - protected int getTempIncrement() { - return -1; - } - - protected int getTempDecrement() { - return -1; - } - - protected int getMaxTemp() { - return Integer.MAX_VALUE; - } - + protected abstract int getTempIncrement(); + protected abstract int getTempDecrement(); + protected abstract int getMaxTemp(); protected abstract boolean executeFunction(); public MachineResource getResource(int slot) { return this.resources[slot]; } + +// public void setCreative(boolean creative) { +// this.isCreative = creative; +// } +// +// public boolean isCreative() { +// return this.isCreative; +// } public int getNumResources() { return this.resources.length; @@ -80,58 +80,65 @@ public abstract class TileEntityDevice extends TileEntityLockable implements IHo this.status = status; } - public void readTags(TagObject compound) { - super.readTags(compound); + public void readFromNBT(NBTTagCompound compound) { + super.readFromNBT(compound); - List nbttaglist = compound.getList("Items"); + NBTTagList nbttaglist = compound.getTagList("Items", 10); this.clear(); - for(int i = 0; i < nbttaglist.size(); ++i) { - TagObject nbttagcompound = nbttaglist.get(i); + for(int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); int j = nbttagcompound.getByte("Slot"); if(j >= 0 && j < this.inventory.length) { - this.inventory[j] = ItemStack.readFromTag(nbttagcompound); + this.inventory[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); } } - nbttaglist = compound.getList("Resources"); + nbttaglist = compound.getTagList("Resources", 10); for(MachineResource res : this.resources) { res.reset(); } - for(int i = 0; i < nbttaglist.size() && i < this.inventory.length; ++i) { - this.resources[i].readFromNbt(nbttaglist.get(i)); + for(int i = 0; i < nbttaglist.tagCount() && i < this.inventory.length; ++i) { + this.resources[i].readFromNbt(nbttaglist.getCompoundTagAt(i)); } - this.temperature = compound.getInt("Temperature"); +// this.isCreative = compound.getBoolean("Creative"); + this.temperature = compound.getInteger("Temperature"); this.status = Status.values()[(int)compound.getByte("Status") % Status.values().length]; } - public void writeTags(TagObject compound) { - super.writeTags(compound); + public void writeToNBT(NBTTagCompound compound) { + super.writeToNBT(compound); - List nbttaglist = Lists.newArrayList(); + NBTTagList nbttaglist = new NBTTagList(); for(int i = 0; i < this.inventory.length; ++i) { if(this.inventory[i] != null) { - TagObject nbttagcompound = new TagObject(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setByte("Slot", (byte)i); - this.inventory[i].writeTags(nbttagcompound); - nbttaglist.add(nbttagcompound); + this.inventory[i].writeToNBT(nbttagcompound); + nbttaglist.appendTag(nbttagcompound); } } - compound.setList("Items", nbttaglist); + compound.setTag("Items", nbttaglist); - nbttaglist = Lists.newArrayList(); + nbttaglist = new NBTTagList(); for(int z = 0; z < this.resources.length; z++) { - TagObject res = new TagObject(); + NBTTagCompound res = new NBTTagCompound(); this.resources[z].writeToNbt(res); - nbttaglist.add(res); + nbttaglist.appendTag(res); } - compound.setList("Resources", nbttaglist); + compound.setTag("Resources", nbttaglist); - compound.setInt("Temperature", this.temperature); +// compound.setBoolean("Creative", this.isCreative); + compound.setInteger("Temperature", this.temperature); compound.setByte("Status", (byte)this.status.ordinal()); } +// public void markDirty() +// { +// super.markDirty(); +// } + public int getSizeInventory() { return this.inventory.length; } @@ -142,7 +149,7 @@ public abstract class TileEntityDevice extends TileEntityLockable implements IHo public ItemStack decrStackSize(int index, int count) { if(this.inventory[index] != null) { - if(this.inventory[index].size <= count) { + if(this.inventory[index].stackSize <= count) { ItemStack itemstack1 = this.inventory[index]; this.inventory[index] = null; return itemstack1; @@ -150,7 +157,7 @@ public abstract class TileEntityDevice extends TileEntityLockable implements IHo else { ItemStack itemstack = this.inventory[index].splitStack(count); - if(this.inventory[index].size == 0) { + if(this.inventory[index].stackSize == 0) { this.inventory[index] = null; } @@ -176,8 +183,8 @@ public abstract class TileEntityDevice extends TileEntityLockable implements IHo public void setInventorySlotContents(int index, ItemStack stack) { this.inventory[index] = stack; - if(stack != null && stack.size > this.getInventoryStackLimit()) { - stack.size = this.getInventoryStackLimit(); + if(stack != null && stack.stackSize > this.getInventoryStackLimit()) { + stack.stackSize = this.getInventoryStackLimit(); } } @@ -210,12 +217,9 @@ public abstract class TileEntityDevice extends TileEntityLockable implements IHo public void update() { if(this.worldObj != null && !this.worldObj.client && this.status != Status.BROKEN) { - int envTemp = (int)this.worldObj.getTemperatureC(this.getPos()); + int envTemp = (int)((AWorldServer)this.worldObj).getTemperatureC(this.getPos()); if(this.executeFunction()) { - if(this.getTempIncrement() < 0) - this.temperature = envTemp; - else - this.temperature += this.getTempIncrement(); + this.temperature += this.getTempIncrement(); this.status = this.temperature >= (this.getMaxTemp() * 9) / 10 ? Status.OVERHEAT : Status.RUNNING; if(this.temperature > this.getMaxTemp()) { this.status = Status.BROKEN; @@ -231,10 +235,7 @@ public abstract class TileEntityDevice extends TileEntityLockable implements IHo int dec = this.getTempDecrement(); if(dec != 0) { int prev = this.temperature; - if(dec < 0) - this.temperature = envTemp; - else - this.temperature -= dec; + this.temperature -= dec; this.temperature = ExtMath.clampi(this.temperature, envTemp, Integer.MAX_VALUE); if(prev != this.temperature) this.markDirty(); @@ -264,7 +265,7 @@ public abstract class TileEntityDevice extends TileEntityLockable implements IHo return true; } else { - return this.inventory[slot] == null || this.inventory[slot].size <= 0; + return this.inventory[slot] == null || this.inventory[slot].stackSize <= 0; } } @@ -272,19 +273,19 @@ public abstract class TileEntityDevice extends TileEntityLockable implements IHo if(slot == -1) { int n = 0; for(ItemStack itemstack : this.inventory) { - if(itemstack != null && itemstack.size >= 1) - n += itemstack.size; + if(itemstack != null && itemstack.stackSize >= 1) + n += itemstack.stackSize; } return n >= amount; } else { - return this.inventory[slot] != null && this.inventory[slot].size >= amount; + return this.inventory[slot] != null && this.inventory[slot].stackSize >= amount; } } public boolean isFull() { for(ItemStack itemstack : this.inventory) { - if(itemstack == null || itemstack.size != itemstack.getMaxStackSize()) { + if(itemstack == null || itemstack.stackSize != itemstack.getMaxStackSize()) { return false; } } @@ -304,7 +305,7 @@ public abstract class TileEntityDevice extends TileEntityLockable implements IHo } public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) { - return new ContainerTile(playerInventory, this, this, playerIn); + return new ContainerMachine(playerInventory, this, this, playerIn); } public int getField(int id) { @@ -326,12 +327,12 @@ public abstract class TileEntityDevice extends TileEntityLockable implements IHo public Packet getDescriptionPacket() { - return new SPacketUpdateTileEntity(this); + return new S35PacketUpdateTileEntity(this); } public int getColor() { return 0x8080ff; } - public abstract String formatDisplay(ContainerTile inv); + public abstract String formatDisplay(); } diff --git a/common/src/common/tileentity/TileEntityMobSpawner.java b/common/src/common/tileentity/TileEntityMobSpawner.java new file mode 100755 index 0000000..0847f04 --- /dev/null +++ b/common/src/common/tileentity/TileEntityMobSpawner.java @@ -0,0 +1,243 @@ +package common.tileentity; + +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.Config; +import common.init.EntityRegistry; +import common.model.ParticleType; +import common.nbt.NBTTagCompound; +import common.network.Packet; +import common.packet.S35PacketUpdateTileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.world.World; + +public class TileEntityMobSpawner extends TileEntity implements ITickable +{ + private int spawnDelay = 20; + private String mobID = "Pig"; + private double mobRotation; + private double prevMobRotation; + private int minSpawnDelay = 200; + private int maxSpawnDelay = 800; + private int spawnCount = 4; + private Entity cachedEntity; + private int maxNearbyEntities = 6; + private int activatingRangeFromPlayer = 16; + private int spawnRange = 4; + + public Packet getDescriptionPacket() + { + return new S35PacketUpdateTileEntity(this); + } + + public boolean receiveClientEvent(int id, int type) + { + if (id == 1 && this.worldObj.client) + { + this.spawnDelay = this.minSpawnDelay; + return true; + } + else + { + return super.receiveClientEvent(id, type); + } + } + +// public boolean hasSpecialNBT() +// { +// return true; +// } + + public int getColor() { + return 0xff0000; + } + + public void update() + { + BlockPos blockpos = this.pos; + if (this.worldObj.isAnyPlayerWithinRangeAt((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D, (double)this.activatingRangeFromPlayer)) + { + if (this.worldObj.client) + { + double d3 = (double)((float)blockpos.getX() + this.worldObj.rand.floatv()); + double d4 = (double)((float)blockpos.getY() + this.worldObj.rand.floatv()); + double d5 = (double)((float)blockpos.getZ() + this.worldObj.rand.floatv()); + this.worldObj.spawnParticle(ParticleType.SMOKE_NORMAL, d3, d4, d5, 0.0D, 0.0D, 0.0D); + this.worldObj.spawnParticle(ParticleType.FLAME, d3, d4, d5, 0.0D, 0.0D, 0.0D); + + if (this.spawnDelay > 0) + { + --this.spawnDelay; + } + + this.prevMobRotation = this.mobRotation; + this.mobRotation = (this.mobRotation + (double)(1000.0F / ((float)this.spawnDelay + 200.0F))) % 360.0D; + } + else + { + if(!Config.mobs || !Config.spawners) { + return; + } + + if (this.spawnDelay == -1) + { + this.resetTimer(); + } + + if (this.spawnDelay > 0) + { + --this.spawnDelay; + return; + } + + boolean flag = false; + + for (int i = 0; i < this.spawnCount; ++i) + { + Entity entity = EntityRegistry.createEntityByName(this.mobID, this.worldObj); + + if (entity == null) + { + return; + } + + int j = this.worldObj.getEntitiesWithinAABB(entity.getClass(), (new BoundingBox((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ(), (double)(blockpos.getX() + 1), (double)(blockpos.getY() + 1), (double)(blockpos.getZ() + 1))).expand((double)this.spawnRange, (double)this.spawnRange, (double)this.spawnRange)).size(); + + if (j >= this.maxNearbyEntities) + { + this.resetTimer(); + return; + } + + double d0 = (double)blockpos.getX() + (this.worldObj.rand.doublev() - this.worldObj.rand.doublev()) * (double)this.spawnRange + 0.5D; + double d1 = (double)(blockpos.getY() + this.worldObj.rand.zrange(3) - 1); + double d2 = (double)blockpos.getZ() + (this.worldObj.rand.doublev() - this.worldObj.rand.doublev()) * (double)this.spawnRange + 0.5D; + EntityLiving entityliving = entity instanceof EntityLiving ? (EntityLiving)entity : null; + entity.setLocationAndAngles(d0, d1, d2, this.worldObj.rand.floatv() * 360.0F, 0.0F); + + if (entityliving == null || entityliving.getCanSpawnHere() && entityliving.isNotColliding()) + { + if (entity instanceof EntityLiving && entity.worldObj != null) + { +// if (entity instanceof EntityLiving) +// { + ((EntityLiving)entity).onInitialSpawn(null); +// } + + entity.worldObj.spawnEntityInWorld(entity); + } + this.worldObj.playAuxSFX(2004, blockpos, 0); + + if (entityliving != null) + { + entityliving.spawnExplosionParticle(); + } + + flag = true; + } + } + + if (flag) + { + this.resetTimer(); + } + } + } + } + + private void resetTimer() + { + if (this.maxSpawnDelay <= this.minSpawnDelay) + { + this.spawnDelay = this.minSpawnDelay; + } + else + { + int i = this.maxSpawnDelay - this.minSpawnDelay; + this.spawnDelay = this.minSpawnDelay + this.worldObj.rand.zrange(i); + } + + this.worldObj.addBlockEvent(TileEntityMobSpawner.this.pos, Blocks.mob_spawner, 1, 0); + } + + public void readFromNBT(NBTTagCompound nbt) + { + super.readFromNBT(nbt); + this.mobID = nbt.getString("EntityId"); + this.spawnDelay = nbt.getShort("Delay"); + + if (nbt.hasKey("MinSpawnDelay", 99)) + { + this.minSpawnDelay = nbt.getShort("MinSpawnDelay"); + this.maxSpawnDelay = nbt.getShort("MaxSpawnDelay"); + this.spawnCount = nbt.getShort("SpawnCount"); + } + + if (nbt.hasKey("MaxNearbyEntities", 99)) + { + this.maxNearbyEntities = nbt.getShort("MaxNearbyEntities"); + this.activatingRangeFromPlayer = nbt.getShort("RequiredPlayerRange"); + } + + if (nbt.hasKey("SpawnRange", 99)) + { + this.spawnRange = nbt.getShort("SpawnRange"); + } + + if (this.worldObj != null) + { + this.cachedEntity = null; + } + } + + public void writeToNBT(NBTTagCompound nbt) + { + super.writeToNBT(nbt); + String s = this.mobID; + + if (s != null && !s.isEmpty()) + { + nbt.setString("EntityId", s); + nbt.setShort("Delay", (short)this.spawnDelay); + nbt.setShort("MinSpawnDelay", (short)this.minSpawnDelay); + nbt.setShort("MaxSpawnDelay", (short)this.maxSpawnDelay); + nbt.setShort("SpawnCount", (short)this.spawnCount); + nbt.setShort("MaxNearbyEntities", (short)this.maxNearbyEntities); + nbt.setShort("RequiredPlayerRange", (short)this.activatingRangeFromPlayer); + nbt.setShort("SpawnRange", (short)this.spawnRange); + } + } + + public Entity createRenderEntity(World worldIn) + { + if (this.cachedEntity == null) + { + this.cachedEntity = EntityRegistry.createEntityByName(this.mobID, worldIn); + +// if (entity != null) +// { +//// entity = this.spawnNewEntity(entity, false); +// this.cachedEntity = entity; +// } + } + + return this.cachedEntity; + } + + public double getMobRotation() + { + return this.mobRotation; + } + + public double getPrevMobRotation() + { + return this.prevMobRotation; + } + + public void setEntityName(String name) + { + this.mobID = name; + } +} diff --git a/common/src/common/tileentity/TileEntityNote.java b/common/src/common/tileentity/TileEntityNote.java new file mode 100755 index 0000000..214d94c --- /dev/null +++ b/common/src/common/tileentity/TileEntityNote.java @@ -0,0 +1,74 @@ +package common.tileentity; + +import common.init.Blocks; +import common.material.Material; +import common.nbt.NBTTagCompound; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.World; + +public class TileEntityNote extends TileEntity +{ + /** Note to play */ + public byte note; + + /** stores the latest redstone state */ + public boolean previousRedstoneState; + + public void writeToNBT(NBTTagCompound compound) + { + super.writeToNBT(compound); + compound.setByte("note", this.note); + } + + public void readFromNBT(NBTTagCompound compound) + { + super.readFromNBT(compound); + this.note = compound.getByte("note"); + this.note = (byte)ExtMath.clampi(this.note, 0, 24); + } + + /** + * change pitch by -> (currentPitch + 1) % 25 + */ + public void changePitch() + { + this.note = (byte)((this.note + 1) % 25); + this.markDirty(); + } + + public void triggerNote(World worldIn, BlockPos p_175108_2_) + { + if (worldIn.getState(p_175108_2_.up()).getBlock().getMaterial() == Material.air) + { +// Material material = worldIn.getBlockState(p_175108_2_.down()).getBlock().getMaterial(); +// int i = 0; +// +// if (material == Material.rock) +// { +// i = 1; +// } +// +// if (material == Material.sand) +// { +// i = 2; +// } +// +// if (material == Material.glass) +// { +// i = 3; +// } +// +// if (material == Material.wood) +// { +// i = 4; +// } + + worldIn.addBlockEvent(p_175108_2_, Blocks.noteblock, 0, this.note); + } + } + + public int getColor() { + return 0x80ff00; + } +} diff --git a/common/src/main/java/common/tileentity/TileEntityPiston.java b/common/src/common/tileentity/TileEntityPiston.java similarity index 88% rename from common/src/main/java/common/tileentity/TileEntityPiston.java rename to common/src/common/tileentity/TileEntityPiston.java index 3feb89a..d4cc931 100755 --- a/common/src/main/java/common/tileentity/TileEntityPiston.java +++ b/common/src/common/tileentity/TileEntityPiston.java @@ -6,7 +6,7 @@ import common.collect.Lists; import common.entity.Entity; import common.init.BlockRegistry; import common.init.Blocks; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.BoundingBox; import common.util.Facing; import common.world.State; @@ -198,23 +198,23 @@ public class TileEntityPiston extends TileEntity implements ITickable } } - public void readTags(TagObject compound) + public void readFromNBT(NBTTagCompound compound) { - super.readTags(compound); - this.pistonState = BlockRegistry.getRegisteredBlock(compound.getString("blockId")).getStateFromMeta(compound.getInt("blockData")); - this.pistonFacing = Facing.getFront(compound.getInt("facing")); + super.readFromNBT(compound); + this.pistonState = BlockRegistry.getBlockById(compound.getInteger("blockId")).getStateFromMeta(compound.getInteger("blockData")); + this.pistonFacing = Facing.getFront(compound.getInteger("facing")); this.lastProgress = this.progress = compound.getFloat("progress"); - this.extending = compound.getBool("extending"); + this.extending = compound.getBoolean("extending"); } - public void writeTags(TagObject compound) + public void writeToNBT(NBTTagCompound compound) { - super.writeTags(compound); - compound.setString("blockId", BlockRegistry.getNameFromBlock(this.pistonState.getBlock())); - compound.setInt("blockData", this.pistonState.getBlock().getMetaFromState(this.pistonState)); - compound.setInt("facing", this.pistonFacing.getIndex()); + super.writeToNBT(compound); + compound.setInteger("blockId", BlockRegistry.getIdFromBlock(this.pistonState.getBlock())); + compound.setInteger("blockData", this.pistonState.getBlock().getMetaFromState(this.pistonState)); + compound.setInteger("facing", this.pistonFacing.getIndex()); compound.setFloat("progress", this.lastProgress); - compound.setBool("extending", this.extending); + compound.setBoolean("extending", this.extending); } public int getColor() { diff --git a/common/src/main/java/common/tileentity/TileEntitySign.java b/common/src/common/tileentity/TileEntitySign.java similarity index 90% rename from common/src/main/java/common/tileentity/TileEntitySign.java rename to common/src/common/tileentity/TileEntitySign.java index 417359e..4c5301a 100755 --- a/common/src/main/java/common/tileentity/TileEntitySign.java +++ b/common/src/common/tileentity/TileEntitySign.java @@ -1,9 +1,9 @@ package common.tileentity; import common.entity.npc.EntityNPC; +import common.nbt.NBTTagCompound; import common.network.Packet; -import common.packet.SPacketUpdateSign; -import common.tags.TagObject; +import common.packet.S33PacketUpdateSign; public class TileEntitySign extends TileEntity { public final String[] signText = new String[] {"", "", "", ""}; @@ -19,8 +19,8 @@ public class TileEntitySign extends TileEntity { private EntityNPC player; // private boolean oldFormat; - public void writeTags(TagObject compound) { - super.writeTags(compound); + public void writeToNBT(NBTTagCompound compound) { + super.writeToNBT(compound); for(int i = 0; i < 4; ++i) { compound.setString("Text" + (i + 1), this.signText[i]); @@ -30,15 +30,15 @@ public class TileEntitySign extends TileEntity { // compound.setString("Command", this.command); } - public void readTags(TagObject compound) { + public void readFromNBT(NBTTagCompound compound) { // this.isEditable = false; - super.readTags(compound); + super.readFromNBT(compound); for(int i = 0; i < 4; ++i) { this.signText[i] = compound.getString("Text" + (i + 1)); } -// if(compound.hasString("Command")) +// if(compound.hasKey("Command", 8)) // this.command = compound.getString("Command"); // if(!compound.getBoolean("NewFormat")) { @@ -95,7 +95,7 @@ public class TileEntitySign extends TileEntity { String[] aichatcomponent = new String[4]; System.arraycopy(this.signText, 0, aichatcomponent, 0, 4); // Sign sign = Server.getServer().getSigns().getEntry(new WorldPos(this).toString()); - return new SPacketUpdateSign(this.worldObj, this.pos, aichatcomponent); + return new S33PacketUpdateSign(this.worldObj, this.pos, aichatcomponent); } // public boolean hasSpecialNBT() { diff --git a/common/src/common/tileentity/TileEntitySkull.java b/common/src/common/tileentity/TileEntitySkull.java new file mode 100755 index 0000000..48f9349 --- /dev/null +++ b/common/src/common/tileentity/TileEntitySkull.java @@ -0,0 +1,61 @@ +package common.tileentity; + +import common.nbt.NBTTagCompound; +import common.network.Packet; +import common.packet.S35PacketUpdateTileEntity; + +public class TileEntitySkull extends TileEntity +{ + private int skullRotation; +// private String user = null; + + public void writeToNBT(NBTTagCompound compound) + { + super.writeToNBT(compound); + compound.setByte("Rot", (byte)(this.skullRotation & 255)); +// if(this.user != null) +// compound.setString("Owner", this.user); + } + + public void readFromNBT(NBTTagCompound compound) + { + super.readFromNBT(compound); + this.skullRotation = compound.getByte("Rot"); +// if(compound.hasKey("Owner", 8)) +// this.user = compound.getString("Owner"); + } + +// public String getUser() +// { +// return this.user; +// } + + /** + * Allows for a specialized description packet to be created. This is often used to sync tile entity data from the + * server to the client easily. For example this is used by signs to synchronise the text to be displayed. + */ + public Packet getDescriptionPacket() + { + return new S35PacketUpdateTileEntity(this); + } + +// public void setUser(String user) +// { +// this.user = user; +// this.markDirty(); +// } + + public int getSkullRotation() + { + return this.skullRotation; + } + + public void setSkullRotation(int rotation) + { + this.skullRotation = rotation; + } + + public int getColor() { + return 0x00ff00; + } +} diff --git a/common/src/main/java/common/tileentity/TileEntityTianReactor.java b/common/src/common/tileentity/TileEntityTianReactor.java similarity index 89% rename from common/src/main/java/common/tileentity/TileEntityTianReactor.java rename to common/src/common/tileentity/TileEntityTianReactor.java index f276bde..b2d4939 100755 --- a/common/src/main/java/common/tileentity/TileEntityTianReactor.java +++ b/common/src/common/tileentity/TileEntityTianReactor.java @@ -3,22 +3,23 @@ package common.tileentity; import common.init.Blocks; import common.init.ItemRegistry; import common.init.Items; -import common.inventory.ContainerTile; import common.item.ItemStack; import common.tileentity.MachineResource.Type; -public class TileEntityTianReactor extends TileEntityDevice { +public class TileEntityTianReactor extends TileEntityMachine { public TileEntityTianReactor() { super(2, new MachineResource(Type.OUTPUT, "output.energy", 1024, 0, 0)); } protected boolean executeFunction() { - if(!this.hasAmount(0, 2)) + if(!this.hasAmount(0, 2)) // && !this.isCreative) return false; if(this.rand.rarity(5)) return true; +// if(!this.isCreative) { this.decrStackSize(0, 2); this.decrStackSize(1, 1); +// } this.getResource(0).add(this.rand.range(this.temperature / 200, this.temperature / 50), 20, false); return true; } @@ -47,7 +48,7 @@ public class TileEntityTianReactor extends TileEntityDevice { return "tian_reactor"; } - public String formatDisplay(ContainerTile inv) { + public String formatDisplay() { return String.format("Gespeicherte Energie: %d TF", this.getResource(0).getValue()); } diff --git a/common/src/main/java/common/util/BlockPos.java b/common/src/common/util/BlockPos.java similarity index 99% rename from common/src/main/java/common/util/BlockPos.java rename to common/src/common/util/BlockPos.java index 526a1f4..160736e 100755 --- a/common/src/main/java/common/util/BlockPos.java +++ b/common/src/common/util/BlockPos.java @@ -185,7 +185,7 @@ public class BlockPos extends Vec3i { return new BlockPos(this.getY() * vec.getZ() - this.getZ() * vec.getY(), this.getZ() * vec.getX() - this.getX() * vec.getZ(), this.getX() * vec.getY() - this.getY() * vec.getX()); } - + public static Iterable getAllInBox(BlockPos from, BlockPos to) { final BlockPos blockpos = new BlockPos(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()), Math.min(from.getZ(), to.getZ())); diff --git a/common/src/main/java/common/util/BoundingBox.java b/common/src/common/util/BoundingBox.java similarity index 100% rename from common/src/main/java/common/util/BoundingBox.java rename to common/src/common/util/BoundingBox.java diff --git a/common/src/main/java/common/util/CharValidator.java b/common/src/common/util/CharValidator.java similarity index 100% rename from common/src/main/java/common/util/CharValidator.java rename to common/src/common/util/CharValidator.java diff --git a/common/src/main/java/common/util/ChunkPos.java b/common/src/common/util/ChunkPos.java similarity index 100% rename from common/src/main/java/common/util/ChunkPos.java rename to common/src/common/util/ChunkPos.java diff --git a/common/src/main/java/common/util/InheritanceMultiMap.java b/common/src/common/util/ClassInheritanceMultiMap.java similarity index 93% rename from common/src/main/java/common/util/InheritanceMultiMap.java rename to common/src/common/util/ClassInheritanceMultiMap.java index 49e336e..78b03ec 100755 --- a/common/src/main/java/common/util/InheritanceMultiMap.java +++ b/common/src/common/util/ClassInheritanceMultiMap.java @@ -12,7 +12,7 @@ import common.collect.Iterators; import common.collect.Lists; import common.collect.Maps; -public class InheritanceMultiMap extends AbstractSet +public class ClassInheritanceMultiMap extends AbstractSet { private static final Set < Class> CLASSES = Collections.newSetFromMap(new ConcurrentHashMap, Boolean>()); // fix exception @@ -21,7 +21,7 @@ public class InheritanceMultiMap extends AbstractSet private final Class baseClass; private final List values = Lists.newArrayList(); - public InheritanceMultiMap(Class baseClassIn) + public ClassInheritanceMultiMap(Class baseClassIn) { this.baseClass = baseClassIn; this.knownKeys.add(baseClassIn); @@ -124,7 +124,7 @@ public class InheritanceMultiMap extends AbstractSet { public Iterator iterator() { - List list = (List)InheritanceMultiMap.this.map.get(InheritanceMultiMap.this.initializeClassLookup(clazz)); + List list = (List)ClassInheritanceMultiMap.this.map.get(ClassInheritanceMultiMap.this.initializeClassLookup(clazz)); if (list == null) { diff --git a/common/src/main/java/common/util/DC32.java b/common/src/common/util/DC32.java similarity index 100% rename from common/src/main/java/common/util/DC32.java rename to common/src/common/util/DC32.java diff --git a/common/src/main/java/common/util/Displayable.java b/common/src/common/util/Displayable.java similarity index 100% rename from common/src/main/java/common/util/Displayable.java rename to common/src/common/util/Displayable.java diff --git a/common/src/common/util/EncryptUtil.java b/common/src/common/util/EncryptUtil.java new file mode 100644 index 0000000..5241f2e --- /dev/null +++ b/common/src/common/util/EncryptUtil.java @@ -0,0 +1,107 @@ +package common.util; + +import java.security.GeneralSecurityException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.EncodedKeySpec; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.KeyGenerator; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import common.log.Log; + +public class EncryptUtil { + public static SecretKey createNewSharedKey() { + try { + KeyGenerator keygen = KeyGenerator.getInstance("AES"); + keygen.init(128); + return keygen.generateKey(); + } + catch(NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + } + + public static KeyPair generateKeyPair() { + try { + KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); + pairgen.initialize(2048); + return pairgen.generateKeyPair(); + } + catch(NoSuchAlgorithmException e) { + Log.SYSTEM.error(e, "Konnte Schlüsselpaar nicht generiren"); + return null; + } + } + + public static PublicKey decodePublicKey(byte[] encoded) { + try { + EncodedKeySpec spec = new X509EncodedKeySpec(encoded); + KeyFactory factory = KeyFactory.getInstance("RSA"); + return factory.generatePublic(spec); + } + catch(NoSuchAlgorithmException | InvalidKeySpecException e) { + Log.SYSTEM.error(e, "Öffentlicher Schlüssel konnte nicht dekodiert werden"); + return null; + } + } + + public static SecretKey decryptSharedKey(PrivateKey key, byte[] secret) { + return new SecretKeySpec(decryptData(key, secret), "AES"); + } + + public static byte[] encryptData(Key key, byte[] data) { + return cipherOperation(Cipher.ENCRYPT_MODE, key, data); + } + + public static byte[] decryptData(Key key, byte[] data) { + return cipherOperation(Cipher.DECRYPT_MODE, key, data); + } + + private static byte[] cipherOperation(int mode, Key key, byte[] data) { + try { + return createCipher(mode, key.getAlgorithm(), key).doFinal(data); + } + catch(IllegalBlockSizeException | BadPaddingException e) { + Log.SYSTEM.error(e, "Konnte Daten nicht ver- oder entschlüsseln"); + return null; + } + } + + private static Cipher createCipher(int mode, String transformation, Key key) { + try { + Cipher cipher = Cipher.getInstance(transformation); + cipher.init(mode, key); + return cipher; + } + catch(InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) { + Log.SYSTEM.error(e, "Konnte Verschlüsselungsverfahren nicht initialisieren"); + return null; + } + } + + public static Cipher createCipher(int mode, Key key) { + try { + Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding"); + cipher.init(mode, (Key)key, (AlgorithmParameterSpec)(new IvParameterSpec(key.getEncoded()))); + return cipher; + } + catch(GeneralSecurityException e) { + throw new RuntimeException(e); + } + } +} diff --git a/common/src/main/java/common/util/ExtMath.java b/common/src/common/util/ExtMath.java similarity index 100% rename from common/src/main/java/common/util/ExtMath.java rename to common/src/common/util/ExtMath.java diff --git a/common/src/main/java/common/util/Facing.java b/common/src/common/util/Facing.java similarity index 100% rename from common/src/main/java/common/util/Facing.java rename to common/src/common/util/Facing.java diff --git a/common/src/common/util/FileUtils.java b/common/src/common/util/FileUtils.java new file mode 100644 index 0000000..5c01c4b --- /dev/null +++ b/common/src/common/util/FileUtils.java @@ -0,0 +1,97 @@ +package common.util; + +import java.io.ByteArrayOutputStream; +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 common.log.Log; +import io.netty.util.CharsetUtil; + +public class FileUtils { + public static String read(InputStream input) throws IOException { + return new String(readBytes(input), CharsetUtil.UTF_8); + } + + public static byte[] readBytes(InputStream input) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + long count = 0L; + int n; + for(boolean u = false; -1 != (n = input.read(buffer)); count += (long)n) { + output.write(buffer, 0, n); + } + return output.toByteArray(); + } + + public static String read(File file) throws IOException { + FileInputStream in = null; + String s; + try { + in = new FileInputStream(file); + s = FileUtils.read(in); + } + finally { + try { + if(in != null) + in.close(); + } + catch(IOException e) { + } + } + return s; + } + + public static void write(File file, String data) throws IOException { + FileOutputStream out = null; + try { + out = new FileOutputStream(file); + if(out != null) { + out.write(data.getBytes(CharsetUtil.UTF_8)); + out.close(); + } + } + finally { + try { + if(out != null) + out.close(); + } + catch(IOException e) { + } + } + } + + public static InputStream getResource(String path) throws FileNotFoundException { + InputStream in = FileUtils.class.getResourceAsStream("/" + path); + if(in == null) + throw new FileNotFoundException(path); + return in; + } + + public static boolean deleteFiles(File[] files) { + if(files == null) { + Log.JNI.warn("Konnte Ordner nicht löschen"); + return false; + } + + for(int i = 0; i < files.length; ++i) { + File file = files[i]; + Log.JNI.info("Lösche " + file); + + if(file.isDirectory() && !deleteFiles(file.listFiles())) { + Log.JNI.warn("Konnte Ordner " + file + " nicht löschen"); + return false; + } + + if(!file.delete()) { + Log.JNI.warn("Konnte Datei " + file + " nicht löschen"); + return false; + } + } + + return true; + } +} diff --git a/common/src/main/java/common/util/HitPosition.java b/common/src/common/util/HitPosition.java similarity index 100% rename from common/src/main/java/common/util/HitPosition.java rename to common/src/common/util/HitPosition.java diff --git a/common/src/main/java/common/util/IObjectIntIterable.java b/common/src/common/util/IObjectIntIterable.java similarity index 100% rename from common/src/main/java/common/util/IObjectIntIterable.java rename to common/src/common/util/IObjectIntIterable.java diff --git a/common/src/main/java/common/util/IRegistry.java b/common/src/common/util/IRegistry.java similarity index 100% rename from common/src/main/java/common/util/IRegistry.java rename to common/src/common/util/IRegistry.java diff --git a/common/src/main/java/common/util/Identifyable.java b/common/src/common/util/Identifyable.java similarity index 100% rename from common/src/main/java/common/util/Identifyable.java rename to common/src/common/util/Identifyable.java diff --git a/common/src/main/java/common/util/IntHashMap.java b/common/src/common/util/IntHashMap.java similarity index 100% rename from common/src/main/java/common/util/IntHashMap.java rename to common/src/common/util/IntHashMap.java diff --git a/common/src/main/java/common/util/LazyLoader.java b/common/src/common/util/LazyLoadBase.java similarity index 88% rename from common/src/main/java/common/util/LazyLoader.java rename to common/src/common/util/LazyLoadBase.java index 2e6801e..11e3858 100755 --- a/common/src/main/java/common/util/LazyLoader.java +++ b/common/src/common/util/LazyLoadBase.java @@ -1,6 +1,6 @@ package common.util; -public abstract class LazyLoader +public abstract class LazyLoadBase { private T value; private boolean isLoaded = false; diff --git a/common/src/common/util/LowerStringMap.java b/common/src/common/util/LowerStringMap.java new file mode 100755 index 0000000..b445a3d --- /dev/null +++ b/common/src/common/util/LowerStringMap.java @@ -0,0 +1,75 @@ +package common.util; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; + +import common.collect.Maps; + +public class LowerStringMap implements Map +{ + private final Map internalMap = Maps.newLinkedHashMap(); + + public int size() + { + return this.internalMap.size(); + } + + public boolean isEmpty() + { + return this.internalMap.isEmpty(); + } + + public boolean containsKey(Object p_containsKey_1_) + { + return this.internalMap.containsKey(p_containsKey_1_.toString().toLowerCase()); + } + + public boolean containsValue(Object p_containsValue_1_) + { + return this.internalMap.containsKey(p_containsValue_1_); + } + + public V get(Object p_get_1_) + { + return this.internalMap.get(p_get_1_.toString().toLowerCase()); + } + + public V put(String p_put_1_, V p_put_2_) + { + return this.internalMap.put(p_put_1_.toLowerCase(), p_put_2_); + } + + public V remove(Object p_remove_1_) + { + return this.internalMap.remove(p_remove_1_.toString().toLowerCase()); + } + + public void putAll(Map p_putAll_1_) + { + for (Entry entry : p_putAll_1_.entrySet()) + { + this.put((String)entry.getKey(), entry.getValue()); + } + } + + public void clear() + { + this.internalMap.clear(); + } + + public Set keySet() + { + return this.internalMap.keySet(); + } + + public Collection values() + { + return this.internalMap.values(); + } + + public Set> entrySet() + { + return this.internalMap.entrySet(); + } +} diff --git a/common/src/main/java/common/util/Matrix4f.java b/common/src/common/util/Matrix4f.java similarity index 100% rename from common/src/main/java/common/util/Matrix4f.java rename to common/src/common/util/Matrix4f.java diff --git a/server/src/main/java/server/world/NextTickListEntry.java b/common/src/common/util/NextTickListEntry.java similarity index 88% rename from server/src/main/java/server/world/NextTickListEntry.java rename to common/src/common/util/NextTickListEntry.java index 1f1878b..6f492ad 100755 --- a/server/src/main/java/server/world/NextTickListEntry.java +++ b/common/src/common/util/NextTickListEntry.java @@ -1,7 +1,7 @@ -package server.world; +package common.util; import common.block.Block; -import common.util.BlockPos; +import common.init.BlockRegistry; public class NextTickListEntry implements Comparable { @@ -61,6 +61,11 @@ public class NextTickListEntry implements Comparable return this.scheduledTime < p_compareTo_1_.scheduledTime ? -1 : (this.scheduledTime > p_compareTo_1_.scheduledTime ? 1 : (this.priority != p_compareTo_1_.priority ? this.priority - p_compareTo_1_.priority : (this.tickEntryID < p_compareTo_1_.tickEntryID ? -1 : (this.tickEntryID > p_compareTo_1_.tickEntryID ? 1 : 0)))); } + public String toString() + { + return BlockRegistry.getIdFromBlock(this.block) + ": " + this.position + ", " + this.scheduledTime + ", " + this.priority + ", " + this.tickEntryID; + } + public Block getBlock() { return this.block; diff --git a/common/src/main/java/common/util/NibbleArray.java b/common/src/common/util/NibbleArray.java similarity index 100% rename from common/src/main/java/common/util/NibbleArray.java rename to common/src/common/util/NibbleArray.java diff --git a/common/src/main/java/common/util/ObjectIntIdentityMap.java b/common/src/common/util/ObjectIntIdentityMap.java similarity index 100% rename from common/src/main/java/common/util/ObjectIntIdentityMap.java rename to common/src/common/util/ObjectIntIdentityMap.java diff --git a/common/src/main/java/common/util/PortalType.java b/common/src/common/util/PortalType.java similarity index 100% rename from common/src/main/java/common/util/PortalType.java rename to common/src/common/util/PortalType.java diff --git a/common/src/common/util/Position.java b/common/src/common/util/Position.java new file mode 100755 index 0000000..8d7aa6c --- /dev/null +++ b/common/src/common/util/Position.java @@ -0,0 +1,19 @@ +package common.util; + +public class Position { + public final double x; + public final double y; + public final double z; + public final float yaw; + public final float pitch; + public final int dim; + + public Position(double x, double y, double z, float yaw, float pitch, int dim) { + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + this.dim = dim; + } +} diff --git a/common/src/main/java/common/util/Predicates.java b/common/src/common/util/Predicates.java similarity index 100% rename from common/src/main/java/common/util/Predicates.java rename to common/src/common/util/Predicates.java diff --git a/common/src/main/java/common/util/RegistryDefaulted.java b/common/src/common/util/RegistryDefaulted.java similarity index 100% rename from common/src/main/java/common/util/RegistryDefaulted.java rename to common/src/common/util/RegistryDefaulted.java diff --git a/common/src/main/java/common/util/RegistryNamespaced.java b/common/src/common/util/RegistryNamespaced.java similarity index 100% rename from common/src/main/java/common/util/RegistryNamespaced.java rename to common/src/common/util/RegistryNamespaced.java diff --git a/common/src/main/java/common/util/RegistryNamespacedDefaultedByKey.java b/common/src/common/util/RegistryNamespacedDefaultedByKey.java similarity index 100% rename from common/src/main/java/common/util/RegistryNamespacedDefaultedByKey.java rename to common/src/common/util/RegistryNamespacedDefaultedByKey.java diff --git a/common/src/main/java/common/util/RegistrySimple.java b/common/src/common/util/RegistrySimple.java similarity index 100% rename from common/src/main/java/common/util/RegistrySimple.java rename to common/src/common/util/RegistrySimple.java diff --git a/common/src/common/util/Triplet.java b/common/src/common/util/Triplet.java new file mode 100644 index 0000000..6029985 --- /dev/null +++ b/common/src/common/util/Triplet.java @@ -0,0 +1,10 @@ +package common.util; + +public class Triplet extends Tuple { + public final U third; + + public Triplet(S first, T second, U third) { + super(first, second); + this.third = third; + } +} diff --git a/common/src/common/util/Tuple.java b/common/src/common/util/Tuple.java new file mode 100644 index 0000000..20a5a73 --- /dev/null +++ b/common/src/common/util/Tuple.java @@ -0,0 +1,11 @@ +package common.util; + +public class Tuple { + public final S first; + public final T second; + + public Tuple(S first, T second) { + this.first = first; + this.second = second; + } +} diff --git a/common/src/main/java/common/util/Util.java b/common/src/common/util/Util.java similarity index 51% rename from common/src/main/java/common/util/Util.java rename to common/src/common/util/Util.java index 2fc2605..629ef96 100644 --- a/common/src/main/java/common/util/Util.java +++ b/common/src/common/util/Util.java @@ -1,39 +1,19 @@ package common.util; -import java.awt.Desktop; import java.awt.GraphicsEnvironment; -import java.io.File; -import java.io.FileOutputStream; -import java.io.PrintStream; -import java.lang.Thread.UncaughtExceptionHandler; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; -import java.text.SimpleDateFormat; -import java.util.Date; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.function.Function; -import javax.imageio.ImageIO; import javax.swing.JOptionPane; -import common.Version; import common.collect.Lists; import common.collect.Maps; import common.log.Log; -import common.rng.Random; public abstract class Util { + public static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows"); private static final long START = getTime(); - private static final int MIN_JAVA_FEATURE = 21; - public static final boolean WINDOWS = System.getProperty("os.name").toLowerCase(Locale.US).contains("win"); - public static final boolean DEVMODE = System.getProperty("runtime.devmode") != null; - public static final int PROTOCOL = Version.MAJOR << 16 | Version.MINOR << 8 | Version.PATCH; - public static final String VERSION = "v" + Version.MAJOR + "." + Version.MINOR + "." + Version.PATCH + Version.RELEASE; - - private static boolean crashed; public static String strip(String str, int offset, int len, char newl, char tab, char unk) { StringBuilder sb = new StringBuilder(); @@ -58,7 +38,100 @@ public abstract class Util { } return sb.toString(); } - + +/* +uint utf_read(const char **ptr) { + uint ch; + byte utf; + char c = *((*ptr)++); + for(utf = 0; (utf < 6) && (c & (0x80 >> utf)); utf++) { + ; + } + if(utf == 1) + return CHR_UNK; + for(ch = ((!utf) || ((((uint)c) << 6) | (((**ptr) & 0x3f) & ~(0xff >> utf)))) ? (c & (0x7f >> utf)) : 0; utf > 1; utf--) { + if(((c = **ptr) & 0xc0) == 0x80) { + // if(ch) { + ch <<= 6; + ch |= c & 0x3f; + // } + } + else { + return c ? CHR_UNK : 0; + } + (*ptr)++; + } + // fprintf(stderr, "%d / %c\n", ch, ch); + return (utf && !ch) ? CHR_UNK : ch; +} + +uint utf_readn(const char *ptr, int *pos) { + const char *str = &ptr[*pos]; + uint ch = utf_read(&str); + *pos = (int)(str-ptr); + return ch; +} + +byte utf_write(char **ptr, int *len, uint ch) { + uint test; + uint mask = 0xffffff80; + char utf; + char c; + if(ch & 0x80000000) { + return 1; + } + for(utf = 0; ch & mask & ~(test = (0xffffffff << ((utf + 1) * 6 + (5 - utf)))); utf++) { + mask &= test; + } + // fprintf(stderr, "%d\n", utf); + if(utf + 1 >= (*len)) { + return 0; + } + (*len) -= utf + 1; + *((*ptr)++) = utf ? (~(0x7f >> utf) | (((uint)(ch >> (utf * 6))) & (0x3f >> utf))) : ch; + for(--utf; utf >= 0; utf--) { + *((*ptr)++) = 0x80 | (((uint)(ch >> (utf * 6))) & 0x3f); + } + return 1; +} + +byte utf_rwriten(char *ptr, int *pos, int len, uint ch) { + char *str = &ptr[*pos]; + len -= (*pos); + byte res = utf_write(&str, &len, ch); + *pos = (int)(str-ptr); + return res; +} + +uint utf_rread(const char **ptr, const char *start) { + const char *tp = *ptr; + uint ch; + char c; + do { + if(tp == start) + return 0; + tp--; + } while(((c = (*tp)) & 0xc0) == 0x80); + *ptr = tp; + return (ch = utf_read(&tp)) ? ch : CHR_UNK; +} + +uint utf_rreadn(const char *ptr, int *pos) { + const char *str = &ptr[*pos]; + uint ch = utf_rread(&str, ptr); + *pos = (int)(str-ptr); + return ch; +} + +int utf_len(const char *str) { + int len; + for(len = 0; utf_read(&str); len++) { + ; + } + return len; +} +*/ + public static int compareLower(String str1, String str2) { if(str2.length() > str1.length()) return 0; @@ -230,26 +303,11 @@ public abstract class Util { (((color & 255) * mul) / 255); } - public static void checkPlatform() { - int feature; - try { - feature = Runtime.version().feature(); - } - catch(Throwable t) { - feature = 0; - } - String info = null; - String msg = null; + public static void checkOs() { if(System.getProperty("os.name").startsWith("Mac")) { - info = "Inkompatibles Betriebssystem"; - msg = "Linux, *BSD oder Windows ist erforderlich, um dieses Programm\n" + + String info = "Inkompatibles Betriebssystem"; + String msg = "Linux, *BSD oder Windows ist erforderlich, um dieses Programm\n" + "auszuführen. Alle Versionen von Mac OS (X) sind nicht kompatibel."; - } - else if(feature < MIN_JAVA_FEATURE) { - info = "Inkompatible Java-Version"; - msg = "Java " + MIN_JAVA_FEATURE + " oder höher ist erforderlich, um dieses Programm auszuführen."; - } - if(info != null) { System.err.println("#################################################################"); System.err.println("*** " + info + " ***"); System.err.println(msg); @@ -260,132 +318,14 @@ public abstract class Util { } } - public static void setupHandlers() { - Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { - public void uncaughtException(Thread thread, Throwable e) { - System.err.println("Fehler in Thread '" + thread.getName() + "'"); - e.printStackTrace(System.err); - if(crashed) - System.exit(1); - if(e instanceof OutOfMemoryError) { - System.gc(); - System.gc(); - } - if(!thread.getName().startsWith("Thread-") || e instanceof OutOfMemoryError) { - System.err.println("Beende!"); - crashed = true; - if(!DEVMODE) { - PrintStream ps = null; - File report = null; - try { - Date date = new Date(); - File file = new File("crash-" + new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(date) + ".txt"); - FileOutputStream out = new FileOutputStream(file); - ps = new PrintStream(out); - ThreadMXBean bean = ManagementFactory.getThreadMXBean(); - ThreadInfo[] info = bean.dumpAllThreads(true, true); - StringBuilder sb = new StringBuilder(); - Error error = new Error(); - for(ThreadInfo threadinfo : info) { - if(threadinfo.getThreadId() == thread.threadId()) - error.setStackTrace(threadinfo.getStackTrace()); - sb.append(threadinfo); - } - ps.println("************************************************ " + new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date) + " ************************************************"); - ps.println(); - ps.println("\"Wie haste das denn nu wieder geschafft, Bursche?\""); - ps.println("Unerwarteter Fehler in Thread '" + thread.getName() + "':"); - e.printStackTrace(ps); - ps.println(); - ps.println("---------------------------------------------- Thread-Dump (" + info.length + " Threads) ---------------------------------------------"); - ps.println(); - ps.print(sb.toString()); - ps.println("*********************************************************************************************************************"); - report = file; - } - catch(Throwable t) { - System.err.println("Konnte Absturzbericht nicht speichern:"); - t.printStackTrace(System.err); - } - finally { - if(ps != null) - ps.close(); - } - if(report != null) { - System.err.println("Absturzbericht gespeichert unter " + report.getPath()); - try { - Desktop.getDesktop().browse(report.toURI()); - } - catch(Throwable e1) { - System.err.println("Konnte " + report + " nicht öffnen: " + e1); - } - } - } - System.exit(1); - } - } - }); - ImageIO.setUseCache(false); - Thread timer = new Thread("Timer Hack Thread") { - public void run() { - while(true) { - try { - Thread.sleep(2147483647L); - } - catch(InterruptedException e) { - ; - } - } - } - }; - timer.setDaemon(true); - timer.start(); - System.setProperty("java.net.preferIPv4Stack", "true"); - } - - public static void addShutdownHook(final Runnable hook) { - Runtime.getRuntime().addShutdownHook(new Thread("Game Shutdown Thread") { - public void run() { - if(!crashed) { - try { - hook.run(); - } - catch(Throwable e) { - e.printStackTrace(); - } - } - } - }); - } - - // plr_play("/home/sen/Musik/midi50k/Video_Games/ff/ff2cecil.mid", 0); - public static void meltdown() { - Random rand = new Random(); - Log.SYSTEM.error("CORE_MELTDOWN: Nuclear processor core meltdown imminent\n\n" + - " ************************ CAUTION ************************\n" + - " KCTL: Processor core #%02d has reached a critical\n" + - " temperature, system explosion is imminent! \n" + - " According to the general core density \n" + - " calculation routine defined by the SKC \n" + - " (Hard) Warfare Testing Facility (SKC-WTF) \n" + - " your processor will cause a detonation with \n" + - " a radius of (roughly) %d.%d kilometers. \n" + - " In addition, it will release appoximately \n" + - " %d megajoules of ionizing radiation. \n" + - " You have an estimate time of %d minutes and \n" + - " %d seconds left to clear the detonation area. \n" + - " ************************ CAUTION ************************\n" - , rand.range(1, 64), rand.range(1, 9), rand.range(0, 9), rand.range(10000, 39999), rand.range(3, 9), rand.range(2, 59)); - } - - public static Pair getKeyValue(String text, char separator) { + public static Tuple getKeyValue(String text, char separator) { int index = text.indexOf(separator); if(index == -1) - return new Pair(text, null); - return new Pair(text.substring(0, index), text.substring(index + 1)); + return new Tuple(text, null); + return new Tuple(text.substring(0, index), text.substring(index + 1)); } - public static Pair getKeyValue(String text) { + public static Tuple getKeyValue(String text) { return getKeyValue(text, ' '); } @@ -457,79 +397,4 @@ public abstract class Util { public static String getRegionName(int x, int z) { return String.format("r.%c%X%c%X.rgn", x < 0 ? 'n' : 'p', ((x < 0) ? -x : x) >> 3, z < 0 ? 'n' : 'p', ((z < 0) ? -z : z) >> 3); } - - public static String repeatString(Object obj, int count) { - StringBuilder sb = new StringBuilder(); - for(int z = 0; z < count; z++) { - sb.append(obj); - } - return sb.toString(); - } - - public static String getHexString(byte[] bytes) { - StringBuilder sb = new StringBuilder(); - for(int z = 0; z < bytes.length; z++) { - sb.append(String.format("%02x", bytes[z])); - } - return sb.toString(); - } - - public static byte[] fromHexString(String str) { - if((str.length() & 1) == 1) - str = "0" + str; - byte[] bytes = new byte[str.length() / 2]; - try { - for(int z = 0; z < bytes.length; z++) { - bytes[z] = (byte)Integer.parseUnsignedInt(str.substring(z * 2, (z + 1) * 2), 16); - } - } - catch(NumberFormatException e) { - return null; - } - return bytes; - } - - public static String breakString(String str, int width) { - StringBuilder sb = new StringBuilder(); - for(int z = 0; z < str.length() / width; z++) { - sb.append(str.substring(z * width, (z + 1) * width)).append('\n'); - } - return sb.append(str.substring(str.length() - (str.length() % width), str.length())).toString(); - } - - public static String sanitizeCommonName(String str) { - str = str.trim(); - StringBuilder sb = new StringBuilder(); - boolean hyphen = true; - for(int z = 0; z < str.length(); z++) { - char ch = Character.toLowerCase(str.charAt(z)); - if((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) { - sb.append(ch); - hyphen = false; - } - else if(ch == '-' || ch == ' ') { - if(!hyphen) - sb.append('-'); - hyphen = true; - } - } - return sb.length() > 0 && sb.charAt(sb.length() - 1) == '-' ? sb.substring(0, sb.length() - 1) : sb.toString(); - } - - public static boolean isValidCommonName(String str) { - boolean hyphen = true; - for(int z = 0; z < str.length(); z++) { - char ch = Character.toLowerCase(str.charAt(z)); - if((ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') && ch != '-') - return false; - if(ch == '-' && hyphen) - return false; - hyphen = ch == '-'; - } - return !hyphen; - } - - public static void throwUnchecked(Throwable t) { - throw t instanceof RuntimeException ? (RuntimeException)t : new RuntimeException(t); - } } diff --git a/common/src/main/java/common/util/Vec3.java b/common/src/common/util/Vec3.java similarity index 100% rename from common/src/main/java/common/util/Vec3.java rename to common/src/common/util/Vec3.java diff --git a/common/src/main/java/common/util/Vec3i.java b/common/src/common/util/Vec3i.java similarity index 100% rename from common/src/main/java/common/util/Vec3i.java rename to common/src/common/util/Vec3i.java diff --git a/common/src/main/java/common/util/Vector.java b/common/src/common/util/Vector.java similarity index 100% rename from common/src/main/java/common/util/Vector.java rename to common/src/common/util/Vector.java diff --git a/common/src/main/java/common/util/Vector3f.java b/common/src/common/util/Vector3f.java similarity index 98% rename from common/src/main/java/common/util/Vector3f.java rename to common/src/common/util/Vector3f.java index 5416ce5..cab132d 100644 --- a/common/src/main/java/common/util/Vector3f.java +++ b/common/src/common/util/Vector3f.java @@ -252,7 +252,7 @@ public class Vector3f extends Vector implements Serializable { /* (non-Javadoc) * @see org.lwjgl.vector.Vector#load(FloatBuffer) */ - public Vector3f load(FloatBuffer buf) { + public Vector load(FloatBuffer buf) { x = buf.get(); y = buf.get(); z = buf.get(); @@ -262,7 +262,7 @@ public class Vector3f extends Vector implements Serializable { /* (non-Javadoc) * @see org.lwjgl.vector.Vector#scale(float) */ - public Vector3f scale(float scale) { + public Vector scale(float scale) { x *= scale; y *= scale; @@ -275,7 +275,7 @@ public class Vector3f extends Vector implements Serializable { /* (non-Javadoc) * @see org.lwjgl.vector.Vector#store(FloatBuffer) */ - public Vector3f store(FloatBuffer buf) { + public Vector store(FloatBuffer buf) { buf.put(x); buf.put(y); diff --git a/common/src/main/java/common/util/Vector4f.java b/common/src/common/util/Vector4f.java similarity index 100% rename from common/src/main/java/common/util/Vector4f.java rename to common/src/common/util/Vector4f.java diff --git a/common/src/main/java/common/util/WorldPos.java b/common/src/common/util/WorldPos.java similarity index 100% rename from common/src/main/java/common/util/WorldPos.java rename to common/src/common/util/WorldPos.java diff --git a/common/src/common/village/MerchantRecipe.java b/common/src/common/village/MerchantRecipe.java new file mode 100755 index 0000000..28e4dfe --- /dev/null +++ b/common/src/common/village/MerchantRecipe.java @@ -0,0 +1,78 @@ +package common.village; + +import common.item.Item; +import common.item.ItemStack; +import common.nbt.NBTTagCompound; + +public class MerchantRecipe +{ + private ItemStack itemToBuy; + private ItemStack secondItemToBuy; + private ItemStack itemToSell; + + public MerchantRecipe(NBTTagCompound tagCompound) + { + this.readFromTags(tagCompound); + } + + public MerchantRecipe(ItemStack buy1, ItemStack buy2, ItemStack sell) + { + this.itemToBuy = buy1; + this.secondItemToBuy = buy2; + this.itemToSell = sell; + } + + public MerchantRecipe(ItemStack buy1, ItemStack sell) + { + this(buy1, (ItemStack)null, sell); + } + + public MerchantRecipe(ItemStack buy1, Item sellItem) + { + this(buy1, new ItemStack(sellItem)); + } + + public ItemStack getItemToBuy() + { + return this.itemToBuy; + } + + public ItemStack getSecondItemToBuy() + { + return this.secondItemToBuy; + } + + public boolean hasSecondItemToBuy() + { + return this.secondItemToBuy != null; + } + + public ItemStack getItemToSell() + { + return this.itemToSell; + } + + public void readFromTags(NBTTagCompound tagCompound) + { + NBTTagCompound nbttagcompound = tagCompound.getCompoundTag("buy"); + this.itemToBuy = ItemStack.loadItemStackFromNBT(nbttagcompound); + NBTTagCompound nbttagcompound1 = tagCompound.getCompoundTag("sell"); + this.itemToSell = ItemStack.loadItemStackFromNBT(nbttagcompound1); + if (tagCompound.hasKey("buyB", 10)) + { + this.secondItemToBuy = ItemStack.loadItemStackFromNBT(tagCompound.getCompoundTag("buyB")); + } + } + + public NBTTagCompound writeToTags() + { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setTag("buy", this.itemToBuy.writeToNBT(new NBTTagCompound())); + nbttagcompound.setTag("sell", this.itemToSell.writeToNBT(new NBTTagCompound())); + if (this.secondItemToBuy != null) + { + nbttagcompound.setTag("buyB", this.secondItemToBuy.writeToNBT(new NBTTagCompound())); + } + return nbttagcompound; + } +} diff --git a/common/src/common/village/MerchantRecipeList.java b/common/src/common/village/MerchantRecipeList.java new file mode 100755 index 0000000..d28a1c7 --- /dev/null +++ b/common/src/common/village/MerchantRecipeList.java @@ -0,0 +1,132 @@ +package common.village; + +import java.util.ArrayList; + +import common.item.ItemStack; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; +import common.nbt.NBTUtil; + +public class MerchantRecipeList extends ArrayList +{ + public MerchantRecipeList() + { + } + + public MerchantRecipeList(NBTTagCompound compound) + { + this.readRecipiesFromTags(compound); + } + + /** + * can par1,par2 be used to in crafting recipe par3 + */ + public MerchantRecipe canRecipeBeUsed(ItemStack p_77203_1_, ItemStack p_77203_2_, int p_77203_3_) + { + if (p_77203_3_ > 0 && p_77203_3_ < this.size()) + { + MerchantRecipe merchantrecipe1 = (MerchantRecipe)this.get(p_77203_3_); + return !this.func_181078_a(p_77203_1_, merchantrecipe1.getItemToBuy()) || (p_77203_2_ != null || merchantrecipe1.hasSecondItemToBuy()) && (!merchantrecipe1.hasSecondItemToBuy() || !this.func_181078_a(p_77203_2_, merchantrecipe1.getSecondItemToBuy())) || p_77203_1_.stackSize < merchantrecipe1.getItemToBuy().stackSize || merchantrecipe1.hasSecondItemToBuy() && p_77203_2_.stackSize < merchantrecipe1.getSecondItemToBuy().stackSize ? null : merchantrecipe1; + } + else + { + for (int i = 0; i < this.size(); ++i) + { + MerchantRecipe merchantrecipe = (MerchantRecipe)this.get(i); + + if (this.func_181078_a(p_77203_1_, merchantrecipe.getItemToBuy()) && p_77203_1_.stackSize >= merchantrecipe.getItemToBuy().stackSize && (!merchantrecipe.hasSecondItemToBuy() && p_77203_2_ == null || merchantrecipe.hasSecondItemToBuy() && this.func_181078_a(p_77203_2_, merchantrecipe.getSecondItemToBuy()) && p_77203_2_.stackSize >= merchantrecipe.getSecondItemToBuy().stackSize)) + { + return merchantrecipe; + } + } + + return null; + } + } + + private boolean func_181078_a(ItemStack p_181078_1_, ItemStack p_181078_2_) + { + return ItemStack.areItemsEqual(p_181078_1_, p_181078_2_) && (!p_181078_2_.hasTagCompound() || p_181078_1_.hasTagCompound() && NBTUtil.compareTags(p_181078_2_.getTagCompound(), p_181078_1_.getTagCompound(), false)); + } + +// public void writeToBuf(PacketBuffer buffer) +// { +// buffer.writeByte((byte)(this.size() & 255)); +// +// for (int i = 0; i < this.size(); ++i) +// { +// MerchantRecipe merchantrecipe = (MerchantRecipe)this.get(i); +// buffer.writeItemStackToBuffer(merchantrecipe.getItemToBuy()); +// buffer.writeItemStackToBuffer(merchantrecipe.getItemToSell()); +// ItemStack itemstack = merchantrecipe.getSecondItemToBuy(); +// buffer.writeBoolean(itemstack != null); +// +// if (itemstack != null) +// { +// buffer.writeItemStackToBuffer(itemstack); +// } +// +// buffer.writeBoolean(merchantrecipe.isRecipeDisabled()); +// buffer.writeInt(merchantrecipe.getToolUses()); +// buffer.writeInt(merchantrecipe.getMaxTradeUses()); +// } +// } +// +// public static MerchantRecipeList readFromBuf(PacketBuffer buffer) throws IOException +// { +// MerchantRecipeList merchantrecipelist = new MerchantRecipeList(); +// int i = buffer.readByte() & 255; +// +// for (int j = 0; j < i; ++j) +// { +// ItemStack itemstack = buffer.readItemStackFromBuffer(); +// ItemStack itemstack1 = buffer.readItemStackFromBuffer(); +// ItemStack itemstack2 = null; +// +// if (buffer.readBoolean()) +// { +// itemstack2 = buffer.readItemStackFromBuffer(); +// } +// +// boolean flag = buffer.readBoolean(); +// int k = buffer.readInt(); +// int l = buffer.readInt(); +// MerchantRecipe merchantrecipe = new MerchantRecipe(itemstack, itemstack2, itemstack1, k, l); +// +// if (flag) +// { +// merchantrecipe.compensateToolUses(); +// } +// +// merchantrecipelist.add(merchantrecipe); +// } +// +// return merchantrecipelist; +// } + + public void readRecipiesFromTags(NBTTagCompound compound) + { + NBTTagList nbttaglist = compound.getTagList("Recipes", 10); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) + { + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + this.add(new MerchantRecipe(nbttagcompound)); + } + } + + public NBTTagCompound getRecipiesAsTags() + { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.size(); ++i) + { + MerchantRecipe merchantrecipe = (MerchantRecipe)this.get(i); + nbttaglist.appendTag(merchantrecipe.writeToTags()); + } + + nbttagcompound.setTag("Recipes", nbttaglist); + return nbttagcompound; + } +} diff --git a/common/src/main/java/common/village/Village.java b/common/src/common/village/Village.java similarity index 66% rename from common/src/main/java/common/village/Village.java rename to common/src/common/village/Village.java index 0e6f693..7ecc458 100755 --- a/common/src/main/java/common/village/Village.java +++ b/common/src/common/village/Village.java @@ -4,10 +4,11 @@ import java.util.Iterator; import java.util.List; import common.block.Block; -import common.block.Material; -import common.block.artificial.BlockDoor; +import common.block.BlockDoor; import common.collect.Lists; -import common.tags.TagObject; +import common.material.Material; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.util.BlockPos; import common.world.AWorldServer; @@ -182,7 +183,7 @@ public class Village private boolean isWoodDoor(AWorldServer world, BlockPos pos) { Block block = world.getState(pos).getBlock(); - return block instanceof BlockDoor ? block.getMaterial() == Material.WOOD : false; + return block instanceof BlockDoor ? block.getMaterial() == Material.wood : false; } private void updatePosition() @@ -208,44 +209,52 @@ public class Village } } - public void readTags(TagObject tag) + public void readVillageDataFromNBT(NBTTagCompound compound) { - this.radius = tag.getInt("Radius"); - this.center = new BlockPos(tag.getInt("CX"), tag.getInt("CY"), tag.getInt("CZ")); - this.doorRange = new BlockPos(tag.getInt("ACX"), tag.getInt("ACY"), tag.getInt("ACZ")); - List doors = tag.getList("Doors"); +// this.numVillagers = compound.getInteger("PopSize"); + this.radius = compound.getInteger("Radius"); +// this.lastDoor = compound.getInteger("Stable"); +// this.tickCounter = compound.getInteger("Tick"); +// this.noBreedTicks = compound.getInteger("MTick"); + this.center = new BlockPos(compound.getInteger("CX"), compound.getInteger("CY"), compound.getInteger("CZ")); + this.doorRange = new BlockPos(compound.getInteger("ACX"), compound.getInteger("ACY"), compound.getInteger("ACZ")); + NBTTagList nbttaglist = compound.getTagList("Doors", 10); - for (int i = 0; i < doors.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject door = doors.get(i); - VillageDoorInfo info = new VillageDoorInfo(new BlockPos(door.getInt("X"), door.getInt("Y"), door.getInt("Z")), door.getInt("IDX"), door.getInt("IDZ"), door.getInt("TS")); - this.doors.add(info); + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + VillageDoorInfo villagedoorinfo = new VillageDoorInfo(new BlockPos(nbttagcompound.getInteger("X"), nbttagcompound.getInteger("Y"), nbttagcompound.getInteger("Z")), nbttagcompound.getInteger("IDX"), nbttagcompound.getInteger("IDZ"), nbttagcompound.getInteger("TS")); + this.doors.add(villagedoorinfo); } } - public void writeTags(TagObject tag) + public void writeVillageDataToNBT(NBTTagCompound compound) { - tag.setInt("Radius", this.radius); - tag.setInt("CX", this.center.getX()); - tag.setInt("CY", this.center.getY()); - tag.setInt("CZ", this.center.getZ()); - tag.setInt("ACX", this.doorRange.getX()); - tag.setInt("ACY", this.doorRange.getY()); - tag.setInt("ACZ", this.doorRange.getZ()); - List doors = Lists.newArrayList(); +// compound.setInteger("PopSize", this.numVillagers); + compound.setInteger("Radius", this.radius); +// compound.setInteger("Stable", this.lastDoor); +// compound.setInteger("Tick", this.tickCounter); +// compound.setInteger("MTick", this.noBreedTicks); + compound.setInteger("CX", this.center.getX()); + compound.setInteger("CY", this.center.getY()); + compound.setInteger("CZ", this.center.getZ()); + compound.setInteger("ACX", this.doorRange.getX()); + compound.setInteger("ACY", this.doorRange.getY()); + compound.setInteger("ACZ", this.doorRange.getZ()); + NBTTagList nbttaglist = new NBTTagList(); - for (VillageDoorInfo info : this.doors) + for (VillageDoorInfo villagedoorinfo : this.doors) { - TagObject door = new TagObject(); - door.setInt("X", info.getDoorBlockPos().getX()); - door.setInt("Y", info.getDoorBlockPos().getY()); - door.setInt("Z", info.getDoorBlockPos().getZ()); - door.setInt("IDX", info.getInsideOffsetX()); - door.setInt("IDZ", info.getInsideOffsetZ()); - door.setInt("TS", info.getInsidePosY()); - doors.add(door); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setInteger("X", villagedoorinfo.getDoorBlockPos().getX()); + nbttagcompound.setInteger("Y", villagedoorinfo.getDoorBlockPos().getY()); + nbttagcompound.setInteger("Z", villagedoorinfo.getDoorBlockPos().getZ()); + nbttagcompound.setInteger("IDX", villagedoorinfo.getInsideOffsetX()); + nbttagcompound.setInteger("IDZ", villagedoorinfo.getInsideOffsetZ()); + nbttagcompound.setInteger("TS", villagedoorinfo.getInsidePosY()); + nbttaglist.appendTag(nbttagcompound); } - tag.setList("Doors", doors); + compound.setTag("Doors", nbttaglist); } } diff --git a/common/src/main/java/common/village/VillageDoorInfo.java b/common/src/common/village/VillageDoorInfo.java similarity index 100% rename from common/src/main/java/common/village/VillageDoorInfo.java rename to common/src/common/village/VillageDoorInfo.java diff --git a/common/src/main/java/common/world/AWorldClient.java b/common/src/common/world/AWorldClient.java similarity index 65% rename from common/src/main/java/common/world/AWorldClient.java rename to common/src/common/world/AWorldClient.java index 3b12d01..c7189f0 100644 --- a/common/src/main/java/common/world/AWorldClient.java +++ b/common/src/common/world/AWorldClient.java @@ -2,14 +2,14 @@ package common.world; import common.dimension.Dimension; import common.init.SoundEvent; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; public abstract class AWorldClient extends World { - protected AWorldClient(Dimension dim) { - super(dim, true); + protected AWorldClient(Dimension dim, boolean debug) { + super(dim, true, debug); } public abstract void playSound(double x, double y, double z, SoundEvent sound, float volume); - public abstract void makeFireworks(double x, double y, double z, double motionX, double motionY, double motionZ, TagObject compund); + public abstract void makeFireworks(double x, double y, double z, double motionX, double motionY, double motionZ, NBTTagCompound compund); public abstract void setLastLightning(int last, int color); } diff --git a/common/src/main/java/common/world/AWorldServer.java b/common/src/common/world/AWorldServer.java similarity index 79% rename from common/src/main/java/common/world/AWorldServer.java rename to common/src/common/world/AWorldServer.java index e91f4ec..b1d4457 100644 --- a/common/src/main/java/common/world/AWorldServer.java +++ b/common/src/common/world/AWorldServer.java @@ -4,6 +4,7 @@ import java.util.List; import common.biome.Biome; import common.block.Block; +import common.block.LeavesType; import common.dimension.Dimension; import common.entity.Entity; import common.entity.npc.EntityNPC; @@ -17,8 +18,8 @@ import common.util.PortalType; import common.village.Village; public abstract class AWorldServer extends World { - protected AWorldServer(Dimension dim) { - super(dim, false); + protected AWorldServer(Dimension dim, boolean debug) { + super(dim, false, debug); } public abstract List getAllPlayers(); @@ -45,6 +46,12 @@ public abstract class AWorldServer extends World { public abstract boolean isBlockinHighHumidity(BlockPos pos); public abstract T findNearestEntityWithinAABB(Class entityType, BoundingBox aabb, T closestTo); public abstract long getTime(); - public abstract void setBiome(BlockPos pos, Biome biome); - public abstract void markChunkDirty(BlockPos pos); + public abstract Biome getBiomeGenForCoords(BlockPos pos); + public abstract boolean canBurnAt(BlockPos pos); + public abstract boolean canFreezeAt(BlockPos pos); + public abstract boolean doesWaterVaporize(BlockPos pos); + public abstract boolean isLavaFaster(BlockPos pos); + public abstract LeavesType getLeavesGen(BlockPos pos); + public abstract float getTemperatureC(BlockPos pos); + public abstract boolean isRainingAt(BlockPos strikePosition, boolean wet); } diff --git a/common/src/main/java/common/world/BlockArray.java b/common/src/common/world/BlockArray.java similarity index 70% rename from common/src/main/java/common/world/BlockArray.java rename to common/src/common/world/BlockArray.java index 12dd515..557e89d 100755 --- a/common/src/main/java/common/world/BlockArray.java +++ b/common/src/common/world/BlockArray.java @@ -1,7 +1,5 @@ package common.world; -import java.util.Arrays; - import common.block.Block; import common.init.BlockRegistry; import common.init.Blocks; @@ -13,19 +11,11 @@ public class BlockArray { private int ticked; private char[] data; private NibbleArray blocklight; - private NibbleArray skylight; - public BlockArray(int y, boolean sky, State filler) { + public BlockArray(int y) { this.yBase = y; this.data = new char[4096]; this.blocklight = new NibbleArray(); - if(sky) - this.skylight = new NibbleArray(); - if(filler != null && filler.getBlock() != Blocks.air) { - Arrays.fill(this.data, (char)BlockRegistry.STATEMAP.get(filler)); - this.blocks = this.data.length; - this.ticked = filler.getBlock().getTickRandomly() ? this.data.length : 0; - } } public State get(int x, int y, int z) { @@ -71,14 +61,6 @@ public class BlockArray { return this.yBase; } - public void setSky(int x, int y, int z, int value) { - this.skylight.set(x, y, z, value); - } - - public int getSky(int x, int y, int z) { - return this.skylight.get(x, y, z); - } - public void setLight(int x, int y, int z, int value) { this.blocklight.set(x, y, z, value); } @@ -112,10 +94,6 @@ public class BlockArray { return this.blocklight; } - public NibbleArray getSkylight() { - return this.skylight; - } - public void setData(char[] data) { this.data = data; } @@ -123,16 +101,4 @@ public class BlockArray { public void setBlocklight(NibbleArray data) { this.blocklight = data; } - - public void setSkylight(NibbleArray data) { - this.skylight = data; - } - - public int hashCode() { - return this.yBase >> 4; - } - - public boolean equals(Object other) { - return other instanceof BlockArray && ((BlockArray)other).yBase == this.yBase; - } } diff --git a/common/src/common/world/Chunk.java b/common/src/common/world/Chunk.java new file mode 100755 index 0000000..5720983 --- /dev/null +++ b/common/src/common/world/Chunk.java @@ -0,0 +1,691 @@ +package common.world; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.function.Predicate; + +import common.biome.Biome; +import common.block.Block; +import common.block.ITileEntityProvider; +import common.collect.Maps; +import common.entity.Entity; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.log.Log; +import common.material.Material; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ChunkPos; +import common.util.ClassInheritanceMultiMap; +import common.util.ExtMath; +import common.util.Facing; +import common.util.NibbleArray; +import common.worldgen.DebugStates; + +public class Chunk { + public final int xPos; + public final int zPos; + private final World world; + private final BlockArray[] blocks = new BlockArray[32]; + private final byte[] biomes = new byte[256]; + private final Map tiles = Maps.newHashMap(); + private final ClassInheritanceMultiMap[] entities = new ClassInheritanceMultiMap[32]; + private final ConcurrentLinkedQueue tileQueue = new ConcurrentLinkedQueue(); + + private boolean loaded; + private boolean populated; + private boolean updated; + private boolean modified; + private boolean hasEntity; + private int lightChecks = 8192; + private long lastSave; + private long inhabited; + + public Chunk(World world, int x, int z) { + this.world = world; + this.xPos = x; + this.zPos = z; + for(int y = 0; y < this.entities.length; ++y) { + this.entities[y] = new ClassInheritanceMultiMap(Entity.class); + } + } + + public Chunk(World world, short[] data, int height, State base, State ceil, Random rand, int x, int z) { + this(world, x, z); + for(int bx = 0; bx < 16; ++bx) { + for(int bz = 0; bz < 16; ++bz) { + for(int by = 0; by < height; ++by) { + State state = BlockRegistry.STATEMAP.getByValue(data[bx << 4 | bz | by << 8]); + if(state != null && state.getBlock().getMaterial() != Material.air) { + int y = by >> 4; + if(this.blocks[y] == null) + this.blocks[y] = new BlockArray(y << 4); + this.blocks[y].set(bx, by & 15, bz, state); + } + } + } + } + if(base != null) { + if(this.blocks[0] == null) + this.blocks[0] = new BlockArray(0); + for(int bx = 0; bx < 16; ++bx) { + for(int bz = 0; bz < 16; ++bz) { + for(int by = 0; by < 5; ++by) { + if(by <= rand.zrange(5)) + this.blocks[0].set(bx, by, bz, base); + } + } + } + } + if(ceil != null) { + int y = (height - 1) >> 4; + if(this.blocks[y] == null) + this.blocks[y] = new BlockArray(y << 4); + y = (height - 5) >> 4; + if(this.blocks[y] == null) + this.blocks[y] = new BlockArray(y << 4); + for(int bx = 0; bx < 16; ++bx) { + for(int bz = 0; bz < 16; ++bz) { + for(int by = height - 1; by >= height - 5; --by) { + if(by >= (height - 1) - rand.zrange(5)) + this.blocks[by >> 4].set(bx, by & 15, bz, ceil); + } + } + } + } + if(ceil != null) + this.resetRelight(); + } + + public BlockArray[] getStorage() { + return this.blocks; + } + + public int getOpacity(BlockPos pos) { + return this.getBlock(pos).getLightOpacity(); + } + + private int getOpacity(int x, int y, int z) { + return this.getBlock0(x, y, z).getLightOpacity(); + } + + private Block getBlock0(int x, int y, int z) { + Block block = Blocks.air; + + if(y >= 0 && y >> 4 < this.blocks.length) { + BlockArray stor = this.blocks[y >> 4]; + + if(stor != null) { + block = stor.getBlock(x, y & 15, z); + } + } + + return block; + } + + public Block getBlock(int x, int y, int z) { + return this.getBlock0(x & 15, y, z & 15); + } + + public Block getBlock(BlockPos pos) { + return this.getBlock0(pos.getX() & 15, pos.getY(), pos.getZ() & 15); + } + + public State getState(BlockPos pos) { + if(this.world.debug) { + State state = null; + +// if(pos.getY() == 60) { +// state = Blocks.glass.getDefaultState(); +// } + + if(pos.getY() == 1) { + state = DebugStates.getState(pos.getX(), pos.getZ()); + } + + return state == null ? Blocks.air.getState() : state; + } + else { + if(pos.getY() >= 0 && pos.getY() >> 4 < this.blocks.length) { + BlockArray stor = this.blocks[pos.getY() >> 4]; + + if(stor != null) { + int x = pos.getX() & 15; + int y = pos.getY() & 15; + int z = pos.getZ() & 15; + return stor.get(x, y, z); + } + } + + return Blocks.air.getState(); + } + } + + private int getMeta(int x, int y, int z) { + if(y >> 4 >= this.blocks.length) { + return 0; + } + else { + BlockArray stor = this.blocks[y >> 4]; + return stor != null ? stor.getMeta(x, y & 15, z) : 0; + } + } + + public int getMeta(BlockPos pos) { + return this.getMeta(pos.getX() & 15, pos.getY(), pos.getZ() & 15); + } + + public State setState(BlockPos pos, State state) { + int x = pos.getX() & 15; + int y = pos.getY(); + int z = pos.getZ() & 15; + int o = z << 4 | x; + + State old = this.getState(pos); + + if(old == state) { + return null; + } + else { + Block block = state.getBlock(); + Block oldb = old.getBlock(); + BlockArray stor = this.blocks[y >> 4]; + + if(stor == null) { + if(block == Blocks.air) { + return null; + } + + stor = this.blocks[y >> 4] = new BlockArray(y >> 4 << 4); + } + + stor.set(x, y & 15, z, state); + + if(oldb != block) { + if(!this.world.client) { + oldb.onBlockRemoved((AWorldServer)this.world, pos, old); + } + else if(oldb instanceof ITileEntityProvider) { + this.world.removeTileEntity(pos); + } + } + + if(stor.getBlock(x, y & 15, z) != block) { + return null; + } + else { + if(oldb instanceof ITileEntityProvider) { + TileEntity tile = this.getTileEntity(pos, TileEntity.EnumCreateEntityType.CHECK); + + if(tile != null) { + tile.updateContainingBlockInfo(); + } + } + + if(!this.world.client && oldb != block) { + block.onBlockAdded((AWorldServer)this.world, pos, state); + } + + if(block instanceof ITileEntityProvider) { + TileEntity tile = this.getTileEntity(pos, TileEntity.EnumCreateEntityType.CHECK); + + if(tile == null) { + tile = ((ITileEntityProvider)block).createNewTileEntity(this.world, block.getMetaFromState(state)); + this.world.setTileEntity(pos, tile); + } + + if(tile != null) { + tile.updateContainingBlockInfo(); + } + } + + this.modified = true; + return old; + } + } + } + + public int getLight(BlockPos pos) { + int x = pos.getX() & 15; + int y = pos.getY(); + int z = pos.getZ() & 15; + BlockArray stor = this.blocks[y >> 4]; + return stor == null ? 0 : stor.getLight(x, y & 15, z); + } + + public void setLight(BlockPos pos, int value) { + int x = pos.getX() & 15; + int y = pos.getY(); + int z = pos.getZ() & 15; + BlockArray stor = this.blocks[y >> 4]; + + if(stor == null) { + stor = this.blocks[y >> 4] = new BlockArray(y >> 4 << 4); + } + + this.modified = true; + + stor.setLight(x, y & 15, z, value); + } + + public int getLightSub(BlockPos pos, int amount) { + int x = pos.getX() & 15; + int y = pos.getY(); + int z = pos.getZ() & 15; + BlockArray stor = this.blocks[y >> 4]; + + if(stor == null) { + return !this.world.dimension.hasNoLight() && amount < 15 + ? 15 - amount : 0; + } + else { + int l = this.world.dimension.hasNoLight() ? 0 : 15; + l = l - amount; + int b = stor.getLight(x, y & 15, z); + + if(b > l) { + l = b; + } + + return l; + } + } + + public void addEntity(Entity entity) { + this.hasEntity = true; + int x = ExtMath.floord(entity.posX / 16.0D); + int z = ExtMath.floord(entity.posZ / 16.0D); + + if(x != this.xPos || z != this.zPos) { + Log.JNI.warn("Falsche Position! (" + x + ", " + z + ") sollte (" + this.xPos + ", " + this.zPos + ") sein, " + entity); + entity.setDead(); + } + + int y = ExtMath.floord(entity.posY / 16.0D); + + if(y < 0) { + y = 0; + } + + if(y >= this.entities.length) { + y = this.entities.length - 1; + } + + entity.addedToChunk = true; + entity.chunkCoordX = this.xPos; + entity.chunkCoordY = y; + entity.chunkCoordZ = this.zPos; + this.entities[y].add(entity); + } + + public void removeEntity(Entity entity) { + int y = entity.chunkCoordY; + + if(y < 0) { + y = 0; + } + + if(y >= this.entities.length) { + y = this.entities.length - 1; + } + + this.entities[y].remove(entity); + } + + private TileEntity createNewTileEntity(BlockPos pos) { + Block block = this.getBlock(pos); + return !block.hasTileEntity() ? null : ((ITileEntityProvider)block).createNewTileEntity(this.world, this.getMeta(pos)); + } + + public TileEntity getTileEntity(BlockPos pos, TileEntity.EnumCreateEntityType type) { + TileEntity tile = this.tiles.get(pos); + + if(tile == null) { + if(type == TileEntity.EnumCreateEntityType.IMMEDIATE) { + tile = this.createNewTileEntity(pos); + this.world.setTileEntity(pos, tile); + } + else if(type == TileEntity.EnumCreateEntityType.QUEUED) { + this.tileQueue.add(pos); + } + } + else if(tile.isInvalid()) { + this.tiles.remove(pos); + return null; + } + + return tile; + } + + public void addTileEntity(TileEntity tile) { + this.addTileEntity(tile.getPos(), tile); + + if(this.loaded) { + this.world.addTileEntity(tile); + } + } + + public void addTileEntity(BlockPos pos, TileEntity tile) { + tile.setWorldObj(this.world); + tile.setPos(pos); + + if(this.getBlock(pos) instanceof ITileEntityProvider) { + if(this.tiles.containsKey(pos)) { + this.tiles.get(pos).invalidate(); + } + + if(tile.validate()) { + this.setModified(); + } + this.tiles.put(pos, tile); + } + } + + public void removeTileEntity(BlockPos pos) { + if(this.loaded) { + TileEntity tile = this.tiles.remove(pos); + + if(tile != null) { + tile.invalidate(); + } + } + } + + public void onChunkLoad() { + this.loaded = true; + this.world.addTileEntities(this.tiles.values()); + + for(int n = 0; n < this.entities.length; ++n) { + for(Entity entity : this.entities[n]) { + entity.onChunkLoad(); + } + + this.world.loadEntities(this.entities[n]); + } + } + + public void onChunkUnload() { + this.loaded = false; + + for(TileEntity tile : this.tiles.values()) { + this.world.markTileEntityForRemoval(tile); + } + + for(int n = 0; n < this.entities.length; ++n) { + this.world.unloadEntities(this.entities[n]); + } + } + + public void setModified() { + this.modified = true; + } + + public void getEntities(Entity exclude, BoundingBox bb, List list, Predicate pred) { + int sy = ExtMath.floord((bb.minY - 2.0D) / 16.0D); + int ey = ExtMath.floord((bb.maxY + 2.0D) / 16.0D); + sy = ExtMath.clampi(sy, 0, this.entities.length - 1); + ey = ExtMath.clampi(ey, 0, this.entities.length - 1); + + for(int y = sy; y <= ey; ++y) { + if(!this.entities[y].isEmpty()) { + for(Entity entity : this.entities[y]) { + if(entity.getEntityBoundingBox().intersectsWith(bb) && entity != exclude) { + if(pred == null || pred.test(entity)) { + list.add(entity); + } + + Entity[] parts = entity.getParts(); + + if(parts != null) { + for(int l = 0; l < parts.length; ++l) { + entity = parts[l]; + + if(entity != exclude && entity.getEntityBoundingBox().intersectsWith(bb) + && (pred == null || pred.test(entity))) { + list.add(entity); + } + } + } + } + } + } + } + } + + public void getEntities(Class clazz, BoundingBox bb, List list, Predicate pred) { + int sy = ExtMath.floord((bb.minY - 2.0D) / 16.0D); + int ey = ExtMath.floord((bb.maxY + 2.0D) / 16.0D); + sy = ExtMath.clampi(sy, 0, this.entities.length - 1); + ey = ExtMath.clampi(ey, 0, this.entities.length - 1); + + for(int y = sy; y <= ey; ++y) { + for(T entity : this.entities[y].getByClass(clazz)) { + if(entity.getEntityBoundingBox().intersectsWith(bb) && (pred == null || pred.test(entity))) { + list.add(entity); + } + } + } + } + + public boolean isDirty(long time) { +// if (all) +// { + if(this.hasEntity && time /* this.world.getTime() */ != this.lastSave || this.modified) { + return true; + } +// } +// else if (this.hasEntity && this.world.getTime() >= this.lastSave + 600L) +// { +// return true; +// } + + return this.modified; + } + + public boolean isEmpty() { + return false; + } + + public void update() { + this.updated = true; + + while(!this.tileQueue.isEmpty()) { + BlockPos pos = (BlockPos)this.tileQueue.poll(); + + if(this.getTileEntity(pos, TileEntity.EnumCreateEntityType.CHECK) == null && this.getBlock(pos).hasTileEntity()) { + TileEntity tile = this.createNewTileEntity(pos); + this.world.setTileEntity(pos, tile); + this.world.markBlockRangeForRenderUpdate(pos, pos); + } + } + } + + public boolean isPopulated() { + return this.updated && this.populated; + } + + public ChunkPos getPos() { + return new ChunkPos(this.xPos, this.zPos); + } + + public boolean isEmpty(int bottom, int top) { + if(bottom < 0) { + bottom = 0; + } + + if(top >= 512) { + top = 511; + } + + for(int y = bottom; y <= top; y += 16) { + BlockArray stor = this.blocks[y >> 4]; + + if(stor != null && !stor.isEmpty()) { + return false; + } + } + + return true; + } + + public void setStorage(BlockArray[] arrays) { + if(this.blocks.length != arrays.length) { + Log.JNI.warn("Konnte Sektionen des Chunks nicht setzen, Länge des Arrays ist " + arrays.length + " statt " + + this.blocks.length); + } + else { + for(int n = 0; n < this.blocks.length; ++n) { + this.blocks[n] = arrays[n]; + } + } + } + + public void setData(byte[] data, int update, boolean resend) { + int pos = 0; + + for(int n = 0; n < this.blocks.length; ++n) { + if((update & 1 << n) != 0) { + if(this.blocks[n] == null) { + this.blocks[n] = new BlockArray(n << 4); + } + + char[] blocks = this.blocks[n].getData(); + + for(int k = 0; k < blocks.length; ++k) { + blocks[k] = (char)((data[pos + 1] & 255) << 8 | data[pos] & 255); + pos += 2; + } + } + else if(resend && this.blocks[n] != null) { + this.blocks[n] = null; + } + } + + for(int n = 0; n < this.blocks.length; ++n) { + if((update & 1 << n) != 0 && this.blocks[n] != null) { + NibbleArray light = this.blocks[n].getBlocklight(); + System.arraycopy(data, pos, light.getData(), 0, light.getData().length); + pos += light.getData().length; + } + } + + for(int n = 0; n < this.blocks.length; ++n) { + if(this.blocks[n] != null && (update & 1 << n) != 0) { + this.blocks[n].update(); + } + } + + this.populated = true; + + for(TileEntity tile : this.tiles.values()) { + tile.updateContainingBlockInfo(); + } + } + + public Biome getBiome(BlockPos pos) { + int x = pos.getX() & 15; + int z = pos.getZ() & 15; + int o = this.biomes[z << 4 | x] & 255; + + if(o == 255) { + o = Biome.DEF_BIOME.id; + this.biomes[z << 4 | x] = (byte)(o & 255); + } + + return Biome.getBiomeDef(o); + } + + public void resetRelight() { + this.lightChecks = 0; + } + + /** + * Called once-per-chunk-per-tick, and advances the round-robin relight check + * index by up to 8 blocks at a time. In a worst-case scenario, can potentially + * take up to 51.2 seconds, calculated via (8192/8)/20, to re-check all blocks + * in a chunk, which may explain lagging light updates on initial world + * generation. + */ + public void enqueueRelight() { + BlockPos pos = new BlockPos(this.xPos << 4, 0, this.zPos << 4); + + for(int n = 0; n < 8; ++n) { + if(this.lightChecks >= 8192) + return; + + int s = this.lightChecks % 31; + int x = this.lightChecks / 31 % 16; + int z = this.lightChecks / 512; + ++this.lightChecks; + + for(int y = 0; y < 16; ++y) { + BlockPos block = pos.add(x, (s << 4) + y, z); + boolean edge = y == 0 || y == 15 || x == 0 || x == 15 || z == 0 || z == 15; + + if(this.blocks[s] == null && edge || this.blocks[s] != null + && this.blocks[s].getBlock(x, y, z).getMaterial() == Material.air) { + for(Facing face : Facing.values()) { + BlockPos side = block.offset(face); + + if(this.world.getState(side).getBlock().getLightValue() > 0) { + this.world.checkLight(side); + } + } + + this.world.checkLight(block); + } + } + } + } + + public boolean isLoaded() { + return this.loaded; + } + + public void setLoaded(boolean loaded) { + this.loaded = loaded; + } + + public World getWorld() { + return this.world; + } + + public Map getTiles() { + return this.tiles; + } + + public ClassInheritanceMultiMap[] getEntities() { + return this.entities; + } + + public boolean isTerrainPopulated() { + return this.populated; + } + + public void setTerrainPopulated(boolean populated) { + this.populated = populated; + } + + public void setModified(boolean modified) { + this.modified = modified; + } + + public void setHasEntities(boolean entities) { + this.hasEntity = entities; + } + + public void setSaved(long time) { + this.lastSave = time; + } + + public long getInhabited() { + return this.inhabited; + } + + public void setInhabited(long time) { + this.inhabited = time; + } +} diff --git a/common/src/common/world/ChunkCache.java b/common/src/common/world/ChunkCache.java new file mode 100755 index 0000000..d495ab1 --- /dev/null +++ b/common/src/common/world/ChunkCache.java @@ -0,0 +1,27 @@ +package common.world; + +import common.util.BlockPos; + +public class ChunkCache +{ + protected final int chunkX; + protected final int chunkZ; + protected final Chunk[][] chunkArray; + + public ChunkCache(World worldIn, BlockPos posFromIn, BlockPos posToIn, int subIn) + { + this.chunkX = posFromIn.getX() - subIn >> 4; + this.chunkZ = posFromIn.getZ() - subIn >> 4; + int i = posToIn.getX() + subIn >> 4; + int j = posToIn.getZ() + subIn >> 4; + this.chunkArray = new Chunk[i - this.chunkX + 1][j - this.chunkZ + 1]; + + for (int k = this.chunkX; k <= i; ++k) + { + for (int l = this.chunkZ; l <= j; ++l) + { + this.chunkArray[k - this.chunkX][l - this.chunkZ] = worldIn.getChunk(k, l); + } + } + } +} diff --git a/common/src/main/java/common/world/Explosion.java b/common/src/common/world/Explosion.java similarity index 94% rename from common/src/main/java/common/world/Explosion.java rename to common/src/common/world/Explosion.java index c9d687e..f3c1e2f 100755 --- a/common/src/main/java/common/world/Explosion.java +++ b/common/src/common/world/Explosion.java @@ -8,21 +8,22 @@ import common.block.Block; import common.collect.Lists; import common.collect.Maps; import common.collect.Sets; -import common.enchantment.Enchantment; +import common.enchantment.EnchantmentProtection; import common.entity.DamageSource; import common.entity.Entity; import common.entity.item.EntityTnt; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.init.Config; import common.init.SoundEvent; +import common.material.Material; import common.model.ParticleType; import common.rng.Random; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ExtMath; import common.util.Vec3; -import common.vars.Vars; public class Explosion { @@ -96,7 +97,7 @@ public class Explosion BlockPos blockpos = new BlockPos(d4, d6, d8); State iblockstate = this.worldObj.getState(blockpos); - if (iblockstate.getBlock() != Blocks.air) + if (iblockstate.getBlock().getMaterial() != Material.air) { float f2 = this.exploder != null ? this.exploder.getExplosionResistance(this, this.worldObj, blockpos, iblockstate) : iblockstate.getBlock().getExplosionResistance((Entity)null); f -= (f2 + 0.3F) * 0.3F; @@ -135,7 +136,7 @@ public class Explosion State iblockstate = this.worldObj.getState(blockpos); float f = this.explosionSize; // * (0.7F + this.worldObj.rand.nextFloat() * 0.6F); - if (iblockstate.getBlock() != Blocks.air) + if (iblockstate.getBlock().getMaterial() != Material.air) { float f2 = this.exploder != null ? this.exploder.getExplosionResistance(this, this.worldObj, blockpos, iblockstate) : iblockstate.getBlock().getExplosionResistance((Entity)null); f -= (f2 + 0.3F) * 0.3F; @@ -167,7 +168,7 @@ public class Explosion (dist < explosionSize && rand.doublev() + ((dist - (explosionSize - falloff)) / falloff) < 1.0d))) { BlockPos blockpos = new BlockPos(explosionX + x, explosionY + y, explosionZ + z); State iblockstate = worldObj.getState(blockpos); - if(iblockstate.getBlock() != Blocks.air && iblockstate.getBlock().getExplosionResistance(null) < 60000.0f) { + if(iblockstate.getBlock().getMaterial() != Material.air && iblockstate.getBlock().getExplosionResistance(null) < 60000.0f) { worldObj.setState(blockpos, Blocks.air.getState(), 3); if(rand.chance(1000)) { worldObj.playSound(SoundEvent.EXPLODE, explosionX + x, explosionY + y, explosionZ + z, 4.0F); @@ -179,7 +180,7 @@ public class Explosion } } - if(worldObj.client || Vars.damageExplosion) { + if(worldObj.client || Config.damageExplosion) { List list = worldObj.getEntitiesWithinAABB(Entity.class, new BoundingBox(explosionX - (5.0 + (double)d), explosionY - (5.0 + (double)d), explosionZ - (5.0 + (double)d), explosionX + 5.0 + (double)d, explosionY + 5.0 + (double)d, explosionZ + 5.0 + (double)d)); @@ -244,9 +245,9 @@ public class Explosion d9 = d9 / d13; double d14 = (double)this.worldObj.getBlockDensity(vec3, entity.getEntityBoundingBox()); double d10 = (1.0D - d12) * d14; - if(this.worldObj.client || Vars.damageExplosion) + if(this.worldObj.client || Config.damageExplosion) entity.attackEntityFrom(DamageSource.causeExplosionDamage(this), ((int)((d10 * d10 + d10) / 2.0D * 8.0D * (double)f3 + 1.0D))); - double d11 = Enchantment.getKnockbackFactor(entity, d10); + double d11 = EnchantmentProtection.getKnockbackFactor(entity, d10); entity.motionX += d5 * d11; entity.motionY += d7 * d11; entity.motionZ += d9 * d11; @@ -305,7 +306,7 @@ public class Explosion this.worldObj.spawnParticle(ParticleType.SMOKE_NORMAL, d0, d1, d2, d3, d4, d5); } - if (block != Blocks.air) + if (block.getMaterial() != Material.air) { if (block.canDropFromExplosion(this)) { @@ -322,7 +323,7 @@ public class Explosion { for (BlockPos blockpos1 : this.affectedBlockPositions) { - if (this.worldObj.getState(blockpos1).getBlock() == Blocks.air && this.worldObj.getState(blockpos1.down()).getBlock().isFullBlock() && this.explosionRNG.zrange(3) == 0) + if (this.worldObj.getState(blockpos1).getBlock().getMaterial() == Material.air && this.worldObj.getState(blockpos1.down()).getBlock().isFullBlock() && this.explosionRNG.zrange(3) == 0) { this.worldObj.setState(blockpos1, Blocks.fire.getState()); } diff --git a/common/src/main/java/common/world/IBlockAccess.java b/common/src/common/world/IBlockAccess.java similarity index 100% rename from common/src/main/java/common/world/IBlockAccess.java rename to common/src/common/world/IBlockAccess.java diff --git a/common/src/main/java/common/world/IWorldAccess.java b/common/src/common/world/IWorldAccess.java similarity index 77% rename from common/src/main/java/common/world/IWorldAccess.java rename to common/src/common/world/IWorldAccess.java index b798152..3986e79 100755 --- a/common/src/main/java/common/world/IWorldAccess.java +++ b/common/src/common/world/IWorldAccess.java @@ -1,6 +1,5 @@ package common.world; -import common.biome.Biome; import common.tileentity.TileEntity; import common.util.BlockPos; @@ -8,5 +7,4 @@ public interface IWorldAccess extends IBlockAccess { TileEntity getTileEntity(BlockPos pos); int getCombinedLight(BlockPos pos, int lightValue); - Biome getBiomeGenForCoords(BlockPos pos); } diff --git a/common/src/main/java/common/world/State.java b/common/src/common/world/State.java similarity index 96% rename from common/src/main/java/common/world/State.java rename to common/src/common/world/State.java index 76772ff..c4ab565 100755 --- a/common/src/main/java/common/world/State.java +++ b/common/src/common/world/State.java @@ -74,7 +74,7 @@ public class State { } else if(!property.getAllowedValues().contains(value)) { throw new IllegalArgumentException("Cannot set property " + property + " to " + value + " on block " - + BlockRegistry.getNameFromBlock(this.block) + ", it is not an allowed value"); + + BlockRegistry.REGISTRY.getNameForObject(this.block) + ", it is not an allowed value"); } else { return (State)(this.properties.get(property) == value ? this : (State)this.map.get(property, value)); @@ -99,7 +99,7 @@ public class State { public String toString() { StringBuilder sb = new StringBuilder(); - sb.append(BlockRegistry.getNameFromBlock(this.getBlock())); + sb.append(BlockRegistry.REGISTRY.getNameForObject(this.getBlock())); if(!this.getProperties().isEmpty()) { sb.append("["); Iterable iter = Iterables.transform(this.getProperties().entrySet(), MAP_ENTRY_TO_STRING); diff --git a/common/src/main/java/common/world/Weather.java b/common/src/common/world/Weather.java similarity index 100% rename from common/src/main/java/common/world/Weather.java rename to common/src/common/world/Weather.java diff --git a/common/src/main/java/common/world/World.java b/common/src/common/world/World.java similarity index 86% rename from common/src/main/java/common/world/World.java rename to common/src/common/world/World.java index c2c668b..67d0743 100755 --- a/common/src/main/java/common/world/World.java +++ b/common/src/common/world/World.java @@ -6,15 +6,12 @@ import java.util.List; import java.util.Set; import java.util.function.Predicate; -import common.biome.Biome; import common.block.Block; -import common.block.Material; -import common.block.artificial.BlockSlab; -import common.block.artificial.BlockStairs; -import common.block.foliage.LeavesType; -import common.block.liquid.BlockLiquid; -import common.block.natural.BlockSnow; -import common.block.tech.BlockHopper; +import common.block.BlockHopper; +import common.block.BlockLiquid; +import common.block.BlockSlab; +import common.block.BlockSnow; +import common.block.BlockStairs; import common.collect.Lists; import common.collect.Sets; import common.dimension.Dimension; @@ -25,6 +22,7 @@ import common.init.BlockRegistry; import common.init.Blocks; import common.init.SoundEvent; import common.item.ItemStack; +import common.material.Material; import common.model.ParticleType; import common.rng.Random; import common.tileentity.ITickable; @@ -51,13 +49,14 @@ public abstract class World implements IWorldAccess { } public static final float[] MOON_PHASES = new float[] {1.0F, 0.75F, 0.5F, 0.25F, 0.0F, 0.25F, 0.5F, 0.75F}; public static final int MAX_SIZE = 67108864; - public static final int MAX_SIZE_Y = 4096; + public static final int HEIGHT = 512; public static final long START_TIME = 4385238000L; public static final float ABSOLUTE_ZERO = -273.15f; // private static final Calendar calendar = Calendar.getInstance(); // private static long lastUpdate; public final boolean client; + public final boolean debug; public double gravity = 1.0; protected long timeFactor = 1L; public final Random rand = new Random(); @@ -79,7 +78,6 @@ public abstract class World implements IWorldAccess { protected float rain; protected float darkness; protected float fog; - protected float temp; protected Weather weather; protected long daytime; @@ -108,20 +106,21 @@ public abstract class World implements IWorldAccess { public static boolean isValid(BlockPos pos) { return pos.getX() >= -MAX_SIZE && pos.getZ() >= -MAX_SIZE && pos.getX() < MAX_SIZE && pos.getZ() < MAX_SIZE && - pos.getY() >= -MAX_SIZE_Y && pos.getY() < MAX_SIZE_Y; + pos.getY() >= 0 && pos.getY() < 512; } public static boolean isValidXZ(BlockPos pos) { return pos.getX() >= -MAX_SIZE && pos.getZ() >= -MAX_SIZE && pos.getX() < MAX_SIZE && pos.getZ() < MAX_SIZE; } - protected World(Dimension dim, boolean client) { + protected World(Dimension dim, boolean client, boolean debug) { // this.profiler = profiler; // this.info = info; // this.dimInfo = info.getDimension(dim.getDimensionId()); this.dimension = dim; // this.storage = storage; this.client = client; + this.debug = debug; this.weather = dim.getWeather(); } @@ -130,11 +129,9 @@ public abstract class World implements IWorldAccess { if(Math.abs(this.gravity) < 0.075) this.gravity = Math.signum(this.gravity) * 0.075; } - - public abstract Biome getBiomeGenForCoords(BlockPos pos); - + public boolean isAirBlock(BlockPos pos) { - return this.getState(pos).getBlock() == Blocks.air; + return this.getState(pos).getBlock().getMaterial() == Material.air; } public boolean isBlockLoaded(BlockPos pos) { @@ -163,7 +160,7 @@ public abstract class World implements IWorldAccess { } private boolean isAreaLoaded(int xStart, int yStart, int zStart, int xEnd, int yEnd, int zEnd, boolean allowEmpty) { - if(yEnd >= -MAX_SIZE_Y && yStart < MAX_SIZE_Y) { + if(yEnd >= 0 && yStart < 512) { xStart = xStart >> 4; zStart = zStart >> 4; xEnd = xEnd >> 4; @@ -184,7 +181,9 @@ public abstract class World implements IWorldAccess { } } - protected abstract boolean isLoaded(int x, int z, boolean allowEmpty); + protected boolean isLoaded(int x, int z, boolean allowEmpty) { + return allowEmpty || !this.getChunk(x, z).isEmpty(); + } public Chunk getChunk(BlockPos pos) { return this.getChunk(pos.getX() >> 4, pos.getZ() >> 4); @@ -198,6 +197,9 @@ public abstract class World implements IWorldAccess { if(!isValid(pos)) { return false; } + else if(!this.client && this.debug) { + return false; + } else { Chunk chunk = this.getChunk(pos); Block block = newState.getBlock(); @@ -220,7 +222,7 @@ public abstract class World implements IWorldAccess { } if(!this.client && (flags & 1) != 0) { - this.notifyNeighborsOfStateChange(pos, iblockstate.getBlock()); + this.notifyNeighborsRespectDebug(pos, iblockstate.getBlock()); if(block.hasComparatorInputOverride()) { this.updateComparatorOutputLevel(pos, block); @@ -244,7 +246,7 @@ public abstract class World implements IWorldAccess { State iblockstate = this.getState(pos); Block block = iblockstate.getBlock(); - if(block == Blocks.air) { + if(block.getMaterial() == Material.air) { return false; } else { @@ -258,19 +260,19 @@ public abstract class World implements IWorldAccess { } } + public void notifyNeighborsRespectDebug(BlockPos pos, Block blockType) { + if(!this.debug) { + this.notifyNeighborsOfStateChange(pos, blockType); + } + } + public void markBlocksDirtyVertical(int x1, int z1, int x2, int z2) { if(x2 > z2) { int i = z2; z2 = x2; x2 = i; } - - if(!this.dimension.hasNoLight()) { - for(int j = x2; j <= z2; ++j) { - this.checkLightFor(LightType.SKY, new BlockPos(x1, j, z1)); - } - } - + this.markBlockRangeForRenderUpdate(x1, x2, z1, x1, z2, z1); } @@ -321,17 +323,13 @@ public abstract class World implements IWorldAccess { } } - public boolean canSeeSky(BlockPos pos) { - return this.getChunk(pos).canSeeSky(pos); - } - public int getLight(BlockPos pos) { - if(pos.getY() < -MAX_SIZE_Y) { + if(pos.getY() < 0) { return 0; } else { - if(pos.getY() >= MAX_SIZE_Y) { - pos = new BlockPos(pos.getX(), MAX_SIZE_Y - 1, pos.getZ()); + if(pos.getY() >= 512) { + pos = new BlockPos(pos.getX(), 511, pos.getZ()); } return this.getChunk(pos).getLightSub(pos, 0); @@ -369,12 +367,12 @@ public abstract class World implements IWorldAccess { return i1; } - else if(pos.getY() < -MAX_SIZE_Y) { + else if(pos.getY() < 0) { return 0; } else { - if(pos.getY() >= MAX_SIZE_Y) { - pos = new BlockPos(pos.getX(), MAX_SIZE_Y - 1, pos.getZ()); + if(pos.getY() >= 512) { + pos = new BlockPos(pos.getX(), 511, pos.getZ()); } Chunk chunk = this.getChunk(pos); @@ -386,122 +384,83 @@ public abstract class World implements IWorldAccess { } } - public BlockPos getHeight(BlockPos pos) { - int i; - - if(pos.getX() >= -MAX_SIZE && pos.getZ() >= -MAX_SIZE && pos.getX() < MAX_SIZE && pos.getZ() < MAX_SIZE) { - if(this.isLoaded(pos.getX() >> 4, pos.getZ() >> 4, true)) { - i = this.getChunk(pos.getX() >> 4, pos.getZ() >> 4).getHeight(pos.getX() & 15, pos.getZ() & 15); - } - else { - i = 0; - } - } - else { - i = this.getSeaLevel() + 1; - } - - return new BlockPos(pos.getX(), i, pos.getZ()); - } - - public int getChunksLowestHorizon(int x, int z) { - if(x >= -MAX_SIZE && z >= -MAX_SIZE && x < MAX_SIZE && z < MAX_SIZE) { - if(!this.isLoaded(x >> 4, z >> 4, true)) { - return 0; - } - else { - Chunk chunk = this.getChunk(x >> 4, z >> 4); - return chunk.getLowest(); - } - } - else { - return this.getSeaLevel() + 1; - } - } - - public int getLightFromNeighborsFor(LightType type, BlockPos pos) { - if(this.dimension.hasNoLight() && type == LightType.SKY) { - return 0; - } - else { - if(pos.getY() < -MAX_SIZE_Y) { - pos = new BlockPos(pos.getX(), -MAX_SIZE_Y, pos.getZ()); - } - - if(!isValid(pos)) { - return type.defValue; - } - else if(!this.isBlockLoaded(pos)) { - return type.defValue; - } - else if(this.getState(pos).getBlock().getSumBrightness()) { - int i1 = this.getLightFor(type, pos.up()); - int i = this.getLightFor(type, pos.east()); - int j = this.getLightFor(type, pos.west()); - int k = this.getLightFor(type, pos.south()); - int l = this.getLightFor(type, pos.north()); - - if(i > i1) { - i1 = i; - } - - if(j > i1) { - i1 = j; - } - - if(k > i1) { - i1 = k; - } - - if(l > i1) { - i1 = l; - } - - return i1; - } - else { - Chunk chunk = this.getChunk(pos); - return chunk.getLight(type, pos); - } - } - } - - public int getLightFor(LightType type, BlockPos pos) { - if(pos.getY() < -MAX_SIZE_Y) { - pos = new BlockPos(pos.getX(), -MAX_SIZE_Y, pos.getZ()); + public int getLightFromNeighborsFor(BlockPos pos) { + if(pos.getY() < 0) { + pos = new BlockPos(pos.getX(), 0, pos.getZ()); } if(!isValid(pos)) { - return type.defValue; + return 0; } else if(!this.isBlockLoaded(pos)) { - return type.defValue; + return 0; + } + else if(this.getState(pos).getBlock().getSumBrightness()) { + int i1 = this.getLightFor(pos.up()); + int i = this.getLightFor(pos.east()); + int j = this.getLightFor(pos.west()); + int k = this.getLightFor(pos.south()); + int l = this.getLightFor(pos.north()); + + if(i > i1) { + i1 = i; + } + + if(j > i1) { + i1 = j; + } + + if(k > i1) { + i1 = k; + } + + if(l > i1) { + i1 = l; + } + + return i1; } else { Chunk chunk = this.getChunk(pos); - return chunk.getLight(type, pos); + return chunk.getLight(pos); } } - public void setLightFor(LightType type, BlockPos pos, int lightValue) { + public int getLightFor(BlockPos pos) { + if(pos.getY() < 0) { + pos = new BlockPos(pos.getX(), 0, pos.getZ()); + } + + if(!isValid(pos)) { + return 0; + } + else if(!this.isBlockLoaded(pos)) { + return 0; + } + else { + Chunk chunk = this.getChunk(pos); + return chunk.getLight(pos); + } + } + + public void setLightFor(BlockPos pos, int lightValue) { if(isValid(pos)) { if(this.isBlockLoaded(pos)) { Chunk chunk = this.getChunk(pos); - chunk.setLight(type, pos, lightValue); + chunk.setLight(pos, lightValue); this.notifyLightSet(pos); } } } public int getCombinedLight(BlockPos pos, int lightValue) { - int i = this.getLightFromNeighborsFor(LightType.SKY, pos); - int j = this.getLightFromNeighborsFor(LightType.BLOCK, pos); + int j = this.getLightFromNeighborsFor(pos); if(j < lightValue) { j = lightValue; } - return i << 20 | j << 4; + return 15 << 20 | j << 4; } public float getLightBrightness(BlockPos pos) { @@ -917,8 +876,30 @@ public abstract class World implements IWorldAccess { return f * (float)Math.PI * 2.0F; } + public BlockPos getPrecipitationHeight(BlockPos pos, int y, int scan) { + scan = y - scan; + BlockPos loc = new BlockPos(pos.getX(), y, pos.getZ()); + y = -1; + + while(loc.getY() > 0 && loc.getY() >= scan && y == -1) { + Block block = this.getState(loc).getBlock(); + Material mat = block.getMaterial(); + + if((!mat.blocksMovement() && !mat.isLiquid()) + || (mat == Material.leaves && ((mat = this.getState(loc.up()).getBlock().getMaterial()) == Material.snow) + || mat == Material.leaves)) { + loc = loc.down(); + } + else { + y = loc.getY() + 1; + } + } + + return new BlockPos(pos.getX(), y, pos.getZ()); + } + public BlockPos getPrecipitationHeight(BlockPos pos) { - return this.getChunk(pos).getPrecipitation(pos); + return this.getPrecipitationHeight(pos, 256, 256); } public void updateEntities() { @@ -1215,7 +1196,7 @@ public abstract class World implements IWorldAccess { for(int i2 = i1; i2 < j1; ++i2) { Block block = this.getState(blockpos$mutableblockpos.set(k1, l1, i2)).getBlock(); - if(block == Blocks.fire || block == Blocks.soul_fire || block == Blocks.flowing_lava || block == Blocks.lava || block.getMaterial().isHotLiquid()) { + if(block == Blocks.fire || block == Blocks.flowing_lava || block == Blocks.lava) { return true; } } @@ -1388,7 +1369,7 @@ public abstract class World implements IWorldAccess { public boolean extinguishFire(EntityNPC player, BlockPos pos, Facing side) { pos = pos.offset(side); - if(this.getState(pos).getBlock().canExtinguish()) { + if(this.getState(pos).getBlock() == Blocks.fire) { this.playAuxSFX(player, 1004, pos, 0); this.setBlockToAir(pos); return true; @@ -1491,7 +1472,6 @@ public abstract class World implements IWorldAccess { this.rain = this.weather.hasDownfall() ? 1.0f : 0.0f; this.darkness = this.weather.isDark() ? 1.0f : 0.0f; this.fog = this.weather.getFogIntensity(); - this.temp = this.getBaseTemperature() + this.weather.getTemperature(); } protected void setActivePlayerChunksAndCheckLight(int l) { @@ -1527,121 +1507,48 @@ public abstract class World implements IWorldAccess { // this.profiler.end(); } - public float getTempOffset() { - return this.temp; - } - - protected float getBaseTemperature() { - return this.dimension.getTemperature() + this.dimension.getOrbitOffset() * - ExtMath.sin((((float)(this.daytime % this.dimension.getOrbitalPeriod()) / (float)this.dimension.getOrbitalPeriod()) - -0.125f) * (float)Math.PI * 2.0f); - } - - public LeavesType getLeavesGen(BlockPos pos) { - return this.canFreezeAt(pos) ? LeavesType.SNOWY : ((!this.dimension.getType().days || this.dimension.getOrbitOffset() == 0.0f) ? - this.dimension.getLeavesType() : LeavesType.values()[(int)((this.daytime % - this.dimension.getOrbitalPeriod()) * (long)LeavesType.values().length / this.dimension.getOrbitalPeriod())]); - } - - public float getTemperatureK(BlockPos pos) { - return Math.max(this.temp + this.getBiomeGenForCoords(pos).getTemperature(pos), 0.0f); - } - - public float getTemperatureC(BlockPos pos) { - return World.ABSOLUTE_ZERO + this.getTemperatureK(pos); - } - - public boolean canFreezeAt(BlockPos pos) { - return this.getTemperatureC(pos) <= 0.0F; - } - - public boolean canBurnAt(BlockPos pos) { - return this.getTemperatureC(pos) >= 194.0f; - } - - public boolean doesWaterVaporize(BlockPos pos) { - return this.getTemperatureC(pos) >= 100.0f; - } - - public boolean isLavaFaster(BlockPos pos) { - return this.getTemperatureC(pos) >= 314.0f; - } - - public boolean canSnowAt(BlockPos pos, boolean checkLight, boolean allowLayers) { - if(!this.canFreezeAt(pos)) { - return false; - } - else if(!checkLight) { - return true; - } - else { - if(pos.getY() >= -MAX_SIZE_Y && pos.getY() < MAX_SIZE_Y && this.getLightFor(LightType.BLOCK, pos) < 10) { - Block block = this.getState(pos).getBlock(); - - if((block == Blocks.air || (allowLayers && block == Blocks.snow_layer)) - && Blocks.snow_layer.canPlaceBlockAt(this, pos)) { - return true; - } - } - - return false; - } - } - public boolean checkLight(BlockPos pos) { - boolean flag = false; - - if(!this.dimension.hasNoLight()) { - flag |= this.checkLightFor(LightType.SKY, pos); - } - - flag = flag | this.checkLightFor(LightType.BLOCK, pos); - return flag; + return this.checkLightFor(pos); } - private int getRawLight(BlockPos pos, LightType lightType) { - if(lightType == LightType.SKY && this.canSeeSky(pos)) { - return 15; + private int getRawLight(BlockPos pos) { + Block block = this.getState(pos).getBlock(); + int i = block.getLightValue(); + int j = block.getLightOpacity(); + + if(j >= 15 && block.getLightValue() > 0) { + j = 1; + } + + if(j < 1) { + j = 1; + } + + if(j >= 15) { + return 0; + } + else if(i >= 14) { + return i; } else { - Block block = this.getState(pos).getBlock(); - int i = lightType == LightType.SKY ? 0 : block.getLightValue(); - int j = block.getLightOpacity(); + for(Facing enumfacing : Facing.values()) { + BlockPos blockpos = pos.offset(enumfacing); + int k = this.getLightFor(blockpos) - j; - if(j >= 15 && block.getLightValue() > 0) { - j = 1; - } - - if(j < 1) { - j = 1; - } - - if(j >= 15) { - return 0; - } - else if(i >= 14) { - return i; - } - else { - for(Facing enumfacing : Facing.values()) { - BlockPos blockpos = pos.offset(enumfacing); - int k = this.getLightFor(lightType, blockpos) - j; - - if(k > i) { - i = k; - } - - if(i >= 14) { - return i; - } + if(k > i) { + i = k; } - return i; + if(i >= 14) { + return i; + } } + + return i; } } - public boolean checkLightFor(LightType lightType, BlockPos pos) { + public boolean checkLightFor(BlockPos pos) { if(!this.isAreaLoaded(pos, 17, false)) { return false; } @@ -1649,8 +1556,8 @@ public abstract class World implements IWorldAccess { int i = 0; int j = 0; // this.profiler.start("getBrightness"); - int k = this.getLightFor(lightType, pos); - int l = this.getRawLight(pos, lightType); + int k = this.getLightFor(pos); + int l = this.getRawLight(pos); int i1 = pos.getX(); int j1 = pos.getY(); int k1 = pos.getZ(); @@ -1668,10 +1575,10 @@ public abstract class World implements IWorldAccess { int k2 = (l1 >> 12 & 63) - 32 + k1; int l2 = l1 >> 18 & 15; BlockPos blockpos = new BlockPos(i2, j2, k2); - int i3 = this.getLightFor(lightType, blockpos); + int i3 = this.getLightFor(blockpos); if(i3 == l2) { - this.setLightFor(lightType, blockpos, 0); + this.setLightFor(blockpos, 0); if(l2 > 0) { int j3 = ExtMath.absi(i2 - i1); @@ -1687,7 +1594,7 @@ public abstract class World implements IWorldAccess { int k4 = k2 + enumfacing.getFrontOffsetZ(); blockpos$mutableblockpos.set(i4, j4, k4); int l4 = Math.max(1, this.getState(blockpos$mutableblockpos).getBlock().getLightOpacity()); - i3 = this.getLightFor(lightType, blockpos$mutableblockpos); + i3 = this.getLightFor(blockpos$mutableblockpos); if(i3 == l2 - l4 && j < this.lightUpdate.length) { this.lightUpdate[j++] = i4 - i1 + 32 | j4 - j1 + 32 << 6 | k4 - k1 + 32 << 12 | l2 - l4 << 18; @@ -1710,11 +1617,11 @@ public abstract class World implements IWorldAccess { int k5 = (i5 >> 6 & 63) - 32 + j1; int l5 = (i5 >> 12 & 63) - 32 + k1; BlockPos blockpos1 = new BlockPos(j5, k5, l5); - int i6 = this.getLightFor(lightType, blockpos1); - int j6 = this.getRawLight(blockpos1, lightType); + int i6 = this.getLightFor(blockpos1); + int j6 = this.getRawLight(blockpos1); if(j6 != i6) { - this.setLightFor(lightType, blockpos1, j6); + this.setLightFor(blockpos1, j6); if(j6 > i6) { int k6 = Math.abs(j5 - i1); @@ -1723,27 +1630,27 @@ public abstract class World implements IWorldAccess { boolean flag = j < this.lightUpdate.length - 6; if(k6 + l6 + i7 < 17 && flag) { - if(this.getLightFor(lightType, blockpos1.west()) < j6) { + if(this.getLightFor(blockpos1.west()) < j6) { this.lightUpdate[j++] = j5 - 1 - i1 + 32 + (k5 - j1 + 32 << 6) + (l5 - k1 + 32 << 12); } - if(this.getLightFor(lightType, blockpos1.east()) < j6) { + if(this.getLightFor(blockpos1.east()) < j6) { this.lightUpdate[j++] = j5 + 1 - i1 + 32 + (k5 - j1 + 32 << 6) + (l5 - k1 + 32 << 12); } - if(this.getLightFor(lightType, blockpos1.down()) < j6) { + if(this.getLightFor(blockpos1.down()) < j6) { this.lightUpdate[j++] = j5 - i1 + 32 + (k5 - 1 - j1 + 32 << 6) + (l5 - k1 + 32 << 12); } - if(this.getLightFor(lightType, blockpos1.up()) < j6) { + if(this.getLightFor(blockpos1.up()) < j6) { this.lightUpdate[j++] = j5 - i1 + 32 + (k5 + 1 - j1 + 32 << 6) + (l5 - k1 + 32 << 12); } - if(this.getLightFor(lightType, blockpos1.north()) < j6) { + if(this.getLightFor(blockpos1.north()) < j6) { this.lightUpdate[j++] = j5 - i1 + 32 + (k5 - j1 + 32 << 6) + (l5 - 1 - k1 + 32 << 12); } - if(this.getLightFor(lightType, blockpos1.south()) < j6) { + if(this.getLightFor(blockpos1.south()) < j6) { this.lightUpdate[j++] = j5 - i1 + 32 + (k5 - j1 + 32 << 6) + (l5 + 1 - k1 + 32 << 12); } } @@ -1804,6 +1711,12 @@ public abstract class World implements IWorldAccess { return (Entity)this.entityIds.lookup(id); } + public void markChunkDirty(BlockPos pos, TileEntity unusedTileEntity) { + if(this.isBlockLoaded(pos)) { + this.getChunk(pos).setModified(); + } + } + public void loadEntities(Collection entityCollection) { this.entities.addAll(entityCollection); @@ -1820,7 +1733,7 @@ public abstract class World implements IWorldAccess { Block block = this.getState(pos).getBlock(); BoundingBox axisalignedbb = p_175716_3_ ? null : blockIn.getCollisionBoundingBox(this, pos, blockIn.getState()); return axisalignedbb != null && !this.checkNoEntityCollision(axisalignedbb, entityIn) ? false - : (block.getMaterial() == Material.SMALL && blockIn == Blocks.anvil ? true + : (block.getMaterial() == Material.circuits && blockIn == Blocks.anvil ? true : block.getMaterial().isReplaceable() && blockIn.canReplace(this, pos, side, itemStackIn)); } @@ -2015,11 +1928,7 @@ public abstract class World implements IWorldAccess { public void setFogStrength(float strength) { this.fog = strength; } - - public void setTemperature(float temp) { - this.temp = temp; - } - + public boolean isDark() { return this.darkness > 0.9f; } @@ -2036,23 +1945,6 @@ public abstract class World implements IWorldAccess { return this.hasDownfall() && this.weather.canRain(); } - public boolean isRainingAt(BlockPos strikePosition, boolean wet) { - if(wet ? !this.isRaining() : !this.hasDownfall()) { - return false; - } - else if(!this.canSeeSky(strikePosition)) { - return false; - } - else if(this.getPrecipitationHeight(strikePosition).getY() > strikePosition.getY()) { - return false; - } - return !this.canSnowAt(strikePosition, false, false); -// else { -// Biome biomegenbase = this.getBiomeGenForCoords(strikePosition); -// return biomegenbase.isSnowyBiome() ? false : ( ? false : biomegenbase.canRain()); -// } - } - // public void setItemData(String dataID, WorldSavedData worldSavedDataIn) { // } // diff --git a/common/src/common/worldgen/DebugStates.java b/common/src/common/worldgen/DebugStates.java new file mode 100644 index 0000000..7487eb7 --- /dev/null +++ b/common/src/common/worldgen/DebugStates.java @@ -0,0 +1,38 @@ +package common.worldgen; + +import java.util.List; + +import common.block.Block; +import common.collect.Lists; +import common.init.BlockRegistry; +import common.util.ExtMath; +import common.world.State; + +public class DebugStates { + private static final List STATES = Lists.newArrayList(); + private static final int XSTRETCH; + private static final int ZSTRETCH; + + static { + for(Block block : BlockRegistry.REGISTRY) { + STATES.addAll(block.getValidStates()); + } + XSTRETCH = ExtMath.ceilf(ExtMath.sqrtf((float)STATES.size())); + ZSTRETCH = ExtMath.ceilf((float)STATES.size() / (float)XSTRETCH); + } + + public static State getState(int x, int z) { + State state = null; + if(x > 0 && z > 0 && x % 2 != 0 && z % 2 != 0) { + x = x / 2; + z = z / 2; + if(x <= XSTRETCH && z <= ZSTRETCH) { + int idx = ExtMath.absi(x * XSTRETCH + z); + if(idx < STATES.size()) { + state = STATES.get(idx); + } + } + } + return state; + } +} diff --git a/common/src/common/worldgen/FeatureLake.java b/common/src/common/worldgen/FeatureLake.java new file mode 100644 index 0000000..b279e52 --- /dev/null +++ b/common/src/common/worldgen/FeatureLake.java @@ -0,0 +1,23 @@ +package common.worldgen; + +import common.world.State; + +public class FeatureLake { + public final State state; + public final State filler; + public final State top; + public final int chance; + public final int minHeight; + public final int maxHeight; + public final boolean ratiod; + + public FeatureLake(State state, State filler, State top, int chance, int minHeight, int maxHeight, boolean ratiod) { + this.state = state; + this.filler = filler; + this.top = top; + this.chance = chance; + this.minHeight = minHeight; + this.maxHeight = maxHeight; + this.ratiod = ratiod; + } +} diff --git a/common/src/common/worldgen/FeatureLiquid.java b/common/src/common/worldgen/FeatureLiquid.java new file mode 100644 index 0000000..d2794c0 --- /dev/null +++ b/common/src/common/worldgen/FeatureLiquid.java @@ -0,0 +1,19 @@ +package common.worldgen; + +import common.world.State; + +public class FeatureLiquid { + public final State state; + public final int chance; + public final int minHeight; + public final int maxHeight; + public final boolean lower; + + public FeatureLiquid(State state, int chance, int minHeight, int maxHeight, boolean lower) { + this.state = state; + this.chance = chance; + this.minHeight = minHeight; + this.maxHeight = maxHeight; + this.lower = lower; + } +} diff --git a/common/src/common/worldgen/FeatureOre.java b/common/src/common/worldgen/FeatureOre.java new file mode 100644 index 0000000..38237ff --- /dev/null +++ b/common/src/common/worldgen/FeatureOre.java @@ -0,0 +1,23 @@ +package common.worldgen; + +import common.world.State; + +public class FeatureOre { + public final State state; + public final int count; + public final int more; + public final int size; + public final int min; + public final int max; + public final boolean dist; + + public FeatureOre(State state, int count, int more, int size, int min, int max, boolean dist) { + this.state = state; + this.count = count; + this.more = more; + this.size = size; + this.min = min; + this.max = max; + this.dist = dist; + } +} diff --git a/common/src/main/java/common/Version.java b/common/src/main/java/common/Version.java deleted file mode 100644 index bc57bfa..0000000 --- a/common/src/main/java/common/Version.java +++ /dev/null @@ -1,11 +0,0 @@ -package common; - -import common.util.ReleaseType; - -public abstract class Version { - public static final String NAME = "TCR"; - public static final ReleaseType RELEASE = ReleaseType.DEV; - public static final int MAJOR = 2; - public static final int MINOR = 3; - public static final int PATCH = 0; -} diff --git a/common/src/main/java/common/ai/EntityAIFleeSun.java b/common/src/main/java/common/ai/EntityAIFleeSun.java deleted file mode 100755 index 85c8c7e..0000000 --- a/common/src/main/java/common/ai/EntityAIFleeSun.java +++ /dev/null @@ -1,95 +0,0 @@ -package common.ai; - -import common.entity.types.EntityLiving; -import common.rng.Random; -import common.util.BlockPos; -import common.util.Vec3; -import common.world.World; -import common.world.AWorldServer; - -public class EntityAIFleeSun extends EntityAIBase -{ - private EntityLiving theCreature; - private double shelterX; - private double shelterY; - private double shelterZ; - private double movementSpeed; - private World theWorld; - - public EntityAIFleeSun(EntityLiving theCreatureIn, double movementSpeedIn) - { - this.theCreature = theCreatureIn; - this.movementSpeed = movementSpeedIn; - this.theWorld = theCreatureIn.worldObj; - this.setMutexBits(1); - } - - /** - * Returns whether the EntityAIBase should begin execution. - */ - public boolean shouldExecute() - { - if (!((AWorldServer)this.theWorld).isDaytime()) - { - return false; - } - else if (!this.theCreature.isBurning()) - { - return false; - } - else if (!this.theWorld.canSeeSky(new BlockPos(this.theCreature.posX, this.theCreature.getEntityBoundingBox().minY, this.theCreature.posZ))) - { - return false; - } - else - { - Vec3 vec3 = this.findPossibleShelter(); - - if (vec3 == null) - { - return false; - } - else - { - this.shelterX = vec3.xCoord; - this.shelterY = vec3.yCoord; - this.shelterZ = vec3.zCoord; - return true; - } - } - } - - /** - * Returns whether an in-progress EntityAIBase should continue executing - */ - public boolean continueExecuting() - { - return !this.theCreature.getNavigator().noPath(); - } - - /** - * Execute a one shot task or start executing a continuous task - */ - public void startExecuting() - { - this.theCreature.getNavigator().tryMoveToXYZ(this.shelterX, this.shelterY, this.shelterZ, this.movementSpeed); - } - - private Vec3 findPossibleShelter() - { - Random random = this.theCreature.getRNG(); - BlockPos blockpos = new BlockPos(this.theCreature.posX, this.theCreature.getEntityBoundingBox().minY, this.theCreature.posZ); - - for (int i = 0; i < 10; ++i) - { - BlockPos blockpos1 = blockpos.add(random.zrange(20) - 10, random.zrange(6) - 3, random.zrange(20) - 10); - - if (!this.theWorld.canSeeSky(blockpos1) && this.theCreature.getBlockPathWeight(blockpos1) < 0.0F) - { - return new Vec3((double)blockpos1.getX(), (double)blockpos1.getY(), (double)blockpos1.getZ()); - } - } - - return null; - } -} diff --git a/common/src/main/java/common/ai/EntityAIRestrictSun.java b/common/src/main/java/common/ai/EntityAIRestrictSun.java deleted file mode 100755 index 50e2901..0000000 --- a/common/src/main/java/common/ai/EntityAIRestrictSun.java +++ /dev/null @@ -1,39 +0,0 @@ -package common.ai; - -import common.entity.types.EntityLiving; -import common.pathfinding.PathNavigateGround; -import common.world.AWorldServer; - -public class EntityAIRestrictSun extends EntityAIBase -{ - private EntityLiving theEntity; - - public EntityAIRestrictSun(EntityLiving creature) - { - this.theEntity = creature; - } - - /** - * Returns whether the EntityAIBase should begin execution. - */ - public boolean shouldExecute() - { - return ((AWorldServer)this.theEntity.worldObj).isDaytime(); - } - - /** - * Execute a one shot task or start executing a continuous task - */ - public void startExecuting() - { - ((PathNavigateGround)this.theEntity.getNavigator()).setAvoidSun(true); - } - - /** - * Resets the task - */ - public void resetTask() - { - ((PathNavigateGround)this.theEntity.getNavigator()).setAvoidSun(false); - } -} diff --git a/common/src/main/java/common/attributes/Attribute.java b/common/src/main/java/common/attributes/Attribute.java deleted file mode 100755 index 571529a..0000000 --- a/common/src/main/java/common/attributes/Attribute.java +++ /dev/null @@ -1,17 +0,0 @@ -package common.attributes; - -public enum Attribute { - RADIATION("Strahlung"), - RADIATION_RESISTANCE("Strahlungsresistenz"), - MAGIC_RESISTANCE("Magieresistenz"); - - private final String display; - - private Attribute(String display) { - this.display = display; - } - - public String toString() { - return this.display; - } -} diff --git a/common/src/main/java/common/attributes/AttributeMap.java b/common/src/main/java/common/attributes/AttributeMap.java deleted file mode 100755 index dfa8512..0000000 --- a/common/src/main/java/common/attributes/AttributeMap.java +++ /dev/null @@ -1,60 +0,0 @@ -package common.attributes; - -import java.util.Map; -import java.util.Map.Entry; - -import common.collect.Maps; - -public class AttributeMap { - private class AttributeInstance { - private final Map slots = Maps.newHashMap(); - - private boolean update = true; - private float value; - - public void applyModifier(int slot, float amount) { - this.slots.put(slot, amount); - this.update = true; - } - - public void removeModifier(int slot) { - if(this.slots.remove(slot) != null) - this.update = true; - } - - public float getAttributeValue() { - if(this.update) { - this.value = 0.0f; - for(Float mod : this.slots.values()) { - this.value += mod; - } - this.update = false; - } - return this.value; - } - } - - private final Map attributes = Maps.newHashMap(); - - public AttributeMap() { - for(Attribute attribute : Attribute.values()) { - this.attributes.put(attribute, new AttributeInstance()); - } - } - - public float get(Attribute attribute) { - return this.attributes.get(attribute).getAttributeValue(); - } - - public void remove(Map modifiers, int slot) { - for(Entry entry : modifiers.entrySet()) { - this.attributes.get(entry.getKey()).removeModifier(slot); - } - } - - public void add(Map modifiers, int slot, int amount) { - for(Entry entry : modifiers.entrySet()) { - this.attributes.get(entry.getKey()).applyModifier(slot, entry.getValue() * (float)amount); - } - } -} diff --git a/common/src/main/java/common/attributes/UsageSlot.java b/common/src/main/java/common/attributes/UsageSlot.java deleted file mode 100644 index 2873075..0000000 --- a/common/src/main/java/common/attributes/UsageSlot.java +++ /dev/null @@ -1,38 +0,0 @@ -package common.attributes; - -public enum UsageSlot { - HAND(0), HEAD(4, 0), BODY(3, 1), LEGS(2, 2), FEET(1, 3), INVENTORY(-1); - - private static final UsageSlot[] LOOKUP = new UsageSlot[UsageSlot.values().length]; - - private final int index; - private final int armor; - - static { - for(UsageSlot slot : values()) { - if(slot.index >= 0) - LOOKUP[slot.index] = slot; - } - } - - private UsageSlot(int index, int armor) { - this.index = index; - this.armor = armor; - } - - private UsageSlot(int index) { - this(index, -1); - } - - public int getIndex() { - return this.index; - } - - public int getArmorSlot() { - return this.armor; - } - - public static UsageSlot getByIndex(int index) { - return index < 0 || index >= LOOKUP.length ? null : LOOKUP[index]; - } -} diff --git a/common/src/main/java/common/block/Block.java b/common/src/main/java/common/block/Block.java deleted file mode 100755 index e7d2cc6..0000000 --- a/common/src/main/java/common/block/Block.java +++ /dev/null @@ -1,1015 +0,0 @@ -package common.block; - -import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.function.Function; - -import common.block.artificial.BlockSlab; -import common.collect.ImmutableList; -import common.collect.ImmutableMap; -import common.collect.Iterables; -import common.collect.Lists; -import common.collect.Maps; -import common.collect.UnmodifiableIterator; -import common.enchantment.EnchantmentHelper; -import common.entity.Entity; -import common.entity.item.EntityItem; -import common.entity.item.EntityXp; -import common.entity.npc.EntityNPC; -import common.entity.types.EntityLiving; -import common.init.ItemRegistry; -import common.item.CheatTab; -import common.item.Item; -import common.item.ItemStack; -import common.model.BlockLayer; -import common.model.Model; -import common.model.ModelProvider; -import common.model.Transforms; -import common.properties.IProperty; -import common.rng.Random; -import common.tileentity.TileEntity; -import common.util.BlockPos; -import common.util.BoundingBox; -import common.util.ExtMath; -import common.util.Facing; -import common.util.HitPosition; -import common.util.Vec3; -import common.util.HitPosition.ObjectType; -import common.vars.Vars; -import common.world.Explosion; -import common.world.IBlockAccess; -import common.world.IWorldAccess; -import common.world.AWorldClient; -import common.world.State; -import common.world.World; -import common.world.AWorldServer; - -public class Block { - private static class Product implements Iterable { - private final Class clazz; - private final Iterable[] iterables; - - private Product(Class clazz, Iterable[] iterables) { - this.clazz = clazz; - this.iterables = iterables; - } - - public Iterator iterator() { - return (Iterator)(this.iterables.length <= 0 ? Collections.singletonList((T[])createArray(this.clazz, 0)).iterator() - : new Product.ProductIterator(this.clazz, this.iterables)); - } - - static class ProductIterator extends UnmodifiableIterator { - private int index; - private final Iterable[] iterables; - private final Iterator[] iterators; - private final T[] results; - - private ProductIterator(Class clazz, Iterable[] iterables) { - this.index = -2; - this.iterables = iterables; - this.iterators = (Iterator[])createArray(Iterator.class, this.iterables.length); - - for(int i = 0; i < this.iterables.length; ++i) { - this.iterators[i] = iterables[i].iterator(); - } - - this.results = createArray(clazz, this.iterators.length); - } - - private void endOfData() { - this.index = -1; - Arrays.fill(this.iterators, (Object)null); - Arrays.fill(this.results, (Object)null); - } - - public boolean hasNext() { - if(this.index == -2) { - this.index = 0; - - for(Iterator iterator : this.iterators) { - if(!iterator.hasNext()) { - this.endOfData(); - break; - } - } - - return true; - } - else { - if(this.index >= this.iterators.length) { - for(this.index = this.iterators.length - 1; this.index >= 0; --this.index) { - Iterator iterator = this.iterators[this.index]; - - if(iterator.hasNext()) { - break; - } - - if(this.index == 0) { - this.endOfData(); - break; - } - - iterator = this.iterables[this.index].iterator(); - this.iterators[this.index] = iterator; - - if(!iterator.hasNext()) { - this.endOfData(); - break; - } - } - } - - return this.index >= 0; - } - } - - public T[] next() { - if(!this.hasNext()) { - throw new NoSuchElementException(); - } - else { - while(this.index < this.iterators.length) { - this.results[this.index] = this.iterators[this.index].next(); - ++this.index; - } - - return (T[])((Object[])this.results.clone()); - } - } - } - } - - private static class GetList implements Function> { - private GetList() { - } - - public List apply(Object[] data) { - return Arrays.asList((T[])data); - } - } - - private final ImmutableList properties; - private final ImmutableList states; - protected final Material material; - - protected boolean fullBlock; - protected boolean translucent; - protected boolean sumBrightness; - protected boolean axeHarvest; - protected boolean shovelHarvest; - protected boolean ticked; - protected boolean hasTile; - protected int lightOpacity; - protected int lightValue; - protected int miningLevel; - protected int shearsEfficiency; - protected float blockHardness; - protected float blockResistance; - protected float radiation; - public float slipperiness; - protected double minX; - protected double minY; - protected double minZ; - protected double maxX; - protected double maxY; - protected double maxZ; - private State defaultState; - private String display; - private CheatTab tab; - public SoundType sound; - - private static Iterable> cartesianProduct(Iterable> sets) { - return arraysAsLists(cartesianProduct(Object.class, sets)); - } - - private static Iterable cartesianProduct(Class clazz, Iterable> sets) { - return new Product(clazz, (Iterable[])toArray(Iterable.class, sets)); - } - - private static Iterable> arraysAsLists(Iterable arrays) { - return Iterables.transform(arrays, new GetList()); - } - - private static T[] toArray(Class clazz, Iterable it) { - List list = Lists.newArrayList(); - - for(T t : it) { - list.add(t); - } - - return (T[])((Object[])list.toArray(createArray(clazz, list.size()))); - } - - private static T[] createArray(Class clazz, int size) { - return (T[])((Object[])((Object[])Array.newInstance(clazz, size))); - } - - private static Map createMap(Iterable keys, Iterable values) { - return populateMap(keys, values, Maps.newLinkedHashMap()); - } - - private static Map populateMap(Iterable keys, Iterable values, Map map) { - Iterator iterator = values.iterator(); - - for(IProperty prop : keys) { - map.put(prop, iterator.next()); - } - - if(iterator.hasNext()) { - throw new NoSuchElementException(); - } - else { - return map; - } - } - - private static List> getAllowedValues(List properties) { - List> list = Lists.>newArrayList(); - for(int z = 0; z < properties.size(); z++) { - list.add((properties.get(z)).getAllowedValues()); - } - return list; - } - - private static ImmutableList getPropertyList(IProperty[] properties) { - Arrays.sort(properties, new Comparator() { - public int compare(IProperty p1, IProperty p2) { - return p1.getName().compareTo(p2.getName()); - } - }); - return ImmutableList.copyOf(properties); - } - - private static ImmutableList getStateList(List properties, Block block) { - Map, State> map = Maps., State>newLinkedHashMap(); - List list = Lists.newArrayList(); - for(List allowed : cartesianProduct(getAllowedValues(properties))) { - Map props = createMap(properties, allowed); - State state = new State(block, ImmutableMap.copyOf(props)); - map.put(props, state); - list.add(state); - } - for(State state : list) { - state.buildTable(map); - } - return ImmutableList.copyOf(list); - } - - public Block(Material material) { - this.miningLevel = (material == Material.SOLID || material == Material.HEAVY) ? 0 : -1; - this.axeHarvest = material == Material.WOOD || material == Material.PLANT || material == Material.BUSH || material == Material.SOFT; - this.shearsEfficiency = (material == Material.LEAVES || material == Material.FLUFF) ? 3 : -1; - this.sound = SoundType.STONE; - this.slipperiness = 0.6F; - this.material = material; - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - this.fullBlock = this.isOpaqueCube(); - this.lightOpacity = this.isOpaqueCube() ? 255 : 0; - this.translucent = !material.blocksLight(); - this.properties = getPropertyList(this.getProperties()); - this.states = getStateList(this.properties, this); - this.setDefaultState(this.getBaseState()); - } - - public Block setStepSound(SoundType sound) { - this.sound = sound; - return this; - } - - public Block setLightOpacity(int opacity) { - this.lightOpacity = opacity; - return this; - } - - public Block setLightLevel(float value) { - this.lightValue = (int)(15.0F * value); - return this; - } - - public Block setResistance(float resistance) { - this.blockResistance = resistance * 3.0F; - return this; - } - - public Block setHardness(float hardness) { - this.blockHardness = hardness; - - if(this.blockResistance < hardness * 5.0F) { - this.blockResistance = hardness * 5.0F; - } - - return this; - } - - protected Block setTickRandomly() { - this.ticked = true; - return this; - } - - public Block setDisplay(String name) { - this.display = name; - return this; - } - - public Block setTab(CheatTab tab) { - this.tab = tab; - return this; - } - - public Block setSumBrightness() { - this.sumBrightness = true; - return this; - } - - public Block setMiningLevel(int level) { - this.miningLevel = level; - return this; - } - - public Block setAxeHarvestable() { - this.axeHarvest = true; - return this; - } - - public Block setShovelHarvestable() { - this.shovelHarvest = true; - return this; - } - - public Block setShearsEfficiency(int efficiency) { - this.shearsEfficiency = efficiency; - return this; - } - - public Block setRadiation(float value) { - this.radiation = value; - if(value > 0.0f) - this.ticked = true; - return this; - } - - public boolean isFullBlock() { - return this.fullBlock; - } - - public int getLightOpacity() { - return this.lightOpacity; - } - - public boolean isTranslucent() { - return this.translucent; - } - - public int getLightValue() { - return this.lightValue; - } - - public boolean getSumBrightness() { - return this.sumBrightness; - } - - public final Material getMaterial() { - return this.material; - } - - public ImmutableList getValidStates() { - return this.states; - } - - public final State getBaseState() { - return this.states.get(0); - } - - public Collection getPropertyMap() { - return this.properties; - } - - public State getStateFromMeta(int meta) { - return this.getState(); - } - - public int getMetaFromState(State state) { - if(state != null && !state.getPropertyNames().isEmpty()) { - throw new IllegalArgumentException("Don\'t know how to convert " + state + " back into data..."); - } - else { - return 0; - } - } - - public State getActualState(State state, IWorldAccess worldIn, BlockPos pos) { - return state; - } - - public boolean isBlockNormalCube() { - return this.material.blocksMovement() && this.isFullCube(); - } - - public boolean isNormalCube() { - return this.material.isOpaque() && this.isFullCube() && !this.canProvidePower(); - } - - public boolean isVisuallyOpaque() { - return this.material.blocksMovement() && this.isFullCube(); - } - - public boolean isFullCube() { - return true; - } - - public boolean isPassable(IBlockAccess worldIn, BlockPos pos) { - return !this.material.blocksMovement(); - } - - public int getRenderType() { - return 3; - } - - public boolean isXrayVisible() { - return false; - } - - public boolean isReplaceable(World worldIn, BlockPos pos) { - return false; - } - - public float getBlockHardness(World worldIn, BlockPos pos) { - return this.blockHardness; - } - - public final float getRawHardness() { - return this.blockHardness; - } - - public final float getRawResistance() { - return this.blockResistance; - } - - public boolean getTickRandomly() { - return this.ticked; - } - - public boolean hasTileEntity() { - return this.hasTile; - } - - protected final void setBlockBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { - this.minX = (double)minX; - this.minY = (double)minY; - this.minZ = (double)minZ; - this.maxX = (double)maxX; - this.maxY = (double)maxY; - this.maxZ = (double)maxZ; - } - - public int getMixedBrightnessForBlock(IWorldAccess worldIn, BlockPos pos) { - Block block = worldIn.getState(pos).getBlock(); - int i = worldIn.getCombinedLight(pos, block.getLightValue()); - - if(i == 0 && block instanceof BlockSlab) { - pos = pos.down(); - block = worldIn.getState(pos).getBlock(); - return worldIn.getCombinedLight(pos, block.getLightValue()); - } - else { - return i; - } - } - - public boolean shouldSideBeRendered(IWorldAccess worldIn, BlockPos pos, Facing side) { - return side == Facing.DOWN && this.minY > 0.0D ? true - : (side == Facing.UP && this.maxY < 1.0D ? true - : (side == Facing.NORTH && this.minZ > 0.0D ? true - : (side == Facing.SOUTH && this.maxZ < 1.0D ? true - : (side == Facing.WEST && this.minX > 0.0D ? true - : (side == Facing.EAST && this.maxX < 1.0D ? true - : !worldIn.getState(pos).getBlock().isOpaqueCube()))))); - } - - public BoundingBox getSelectedBoundingBox(World worldIn, BlockPos pos) { - return new BoundingBox((double)pos.getX() + this.minX, (double)pos.getY() + this.minY, (double)pos.getZ() + this.minZ, - (double)pos.getX() + this.maxX, (double)pos.getY() + this.maxY, (double)pos.getZ() + this.maxZ); - } - - public void addCollisionBoxesToList(World worldIn, BlockPos pos, State state, BoundingBox mask, List list, Entity collidingEntity) { - BoundingBox axisalignedbb = this.getCollisionBoundingBox(worldIn, pos, state); - - if(axisalignedbb != null && mask.intersectsWith(axisalignedbb)) { - list.add(axisalignedbb); - } - } - - public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) { - return new BoundingBox((double)pos.getX() + this.minX, (double)pos.getY() + this.minY, (double)pos.getZ() + this.minZ, - (double)pos.getX() + this.maxX, (double)pos.getY() + this.maxY, (double)pos.getZ() + this.maxZ); - } - - public boolean isOpaqueCube() { - return true; - } - - public boolean canCollideCheck(State state, boolean liquid) { - return this.isCollidable(); - } - - public boolean isCollidable() { - return true; - } - - public void randomTick(AWorldServer worldIn, BlockPos pos, State state, Random random) { - this.updateTick(worldIn, pos, state, random); - if(this.radiation > 0.0f) // && /* worldIn.getTime() % 5L == 0L && */ random.chance(Config.randomTick / 3)) - this.affectEntities(worldIn, pos, state, this.radiation * 8.0f * 0.25f); - } - - private void affectEntities(AWorldServer worldIn, BlockPos pos, State state, float rad) { - float r = ExtMath.clampf(rad * 2.0f, 0.0f, 25.0f); - BoundingBox box = this.getCollisionBoundingBox(worldIn, pos, state); - if(box == null) - box = new BoundingBox(pos, pos.add(1, 1, 1)); - for(EntityLiving entity : worldIn.getEntitiesWithinAABB(EntityLiving.class, box.expand(r, r, r))) { - float effect = rad * 2.0f * (r - ExtMath.sqrtf((float)entity.getDistanceSq(pos))) / r; - if(effect > 0.0f) - entity.addRadiation(effect); - } - } - - public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - } - - public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { - } - - public void onBlockDestroyedByPlayer(World worldIn, BlockPos pos, State state) { - } - - public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) { - } - - public int tickRate(World worldIn, BlockPos pos) { - return 10; - } - - public void onBlockAdded(AWorldServer world, BlockPos pos, State state) { - } - - public void onBlockRemoved(AWorldServer world, BlockPos pos, State state) { - } - - public int quantityDropped(Random random) { - return 1; - } - - public Item getItemDropped(State state, Random rand, int fortune) { - return ItemRegistry.getItemFromBlock(this); - } - - public float getPlayerRelativeBlockHardness(EntityNPC playerIn, World worldIn, BlockPos pos) { - float f = this.getBlockHardness(worldIn, pos); - return f < 0.0F ? 0.0F - : (!playerIn.canHarvestBlock(this) ? playerIn.getToolDigEfficiency(this) / f / 100.0F - : playerIn.getToolDigEfficiency(this) / f / 30.0F); - } - - public final void dropBlockAsItem(World worldIn, BlockPos pos, State state, int forture) { - this.dropBlockAsItemWithChance(worldIn, pos, state, 1.0F, forture); - } - - public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) { - if(!worldIn.client) { - int i = this.quantityDroppedWithBonus(fortune, worldIn.rand); - - for(int j = 0; j < i; ++j) { - if(worldIn.rand.floatv() <= chance) { - Item item = this.getItemDropped(state, worldIn.rand, fortune); - - if(item != null) { - spawnAsEntity(worldIn, pos, new ItemStack(item, 1, this.damageDropped(state))); - } - } - } - } - } - - public static void spawnAsEntity(World worldIn, BlockPos pos, ItemStack stack) { - if(!worldIn.client && Vars.blockDrop) { - float f = 0.5F; - double d0 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; - double d1 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; - double d2 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; - EntityItem entityitem = new EntityItem(worldIn, (double)pos.getX() + d0, (double)pos.getY() + d1, (double)pos.getZ() + d2, stack); - entityitem.setDefaultPickupDelay(); - worldIn.spawnEntityInWorld(entityitem); - } - } - - protected void dropXpOnBlockBreak(World worldIn, BlockPos pos, int amount) { - if(!worldIn.client && Vars.blockXP) { - while(amount > 0) { - int i = EntityXp.getXPSplit(amount); - amount -= i; - worldIn.spawnEntityInWorld(new EntityXp(worldIn, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, i)); - } - } - } - - public int damageDropped(State state) { - return 0; - } - - public float getExplosionResistance(Entity exploder) { - return this.blockResistance / 5.0F; - } - - public HitPosition collisionRayTrace(World worldIn, BlockPos pos, Vec3 start, Vec3 end) { - this.setBlockBoundsBasedOnState(worldIn, pos); - start = start.addVector((double)(-pos.getX()), (double)(-pos.getY()), (double)(-pos.getZ())); - end = end.addVector((double)(-pos.getX()), (double)(-pos.getY()), (double)(-pos.getZ())); - Vec3 vec3 = start.getIntermediateWithXValue(end, this.minX); - Vec3 vec31 = start.getIntermediateWithXValue(end, this.maxX); - Vec3 vec32 = start.getIntermediateWithYValue(end, this.minY); - Vec3 vec33 = start.getIntermediateWithYValue(end, this.maxY); - Vec3 vec34 = start.getIntermediateWithZValue(end, this.minZ); - Vec3 vec35 = start.getIntermediateWithZValue(end, this.maxZ); - - if(!this.isVecInsideYZBounds(vec3)) { - vec3 = null; - } - - if(!this.isVecInsideYZBounds(vec31)) { - vec31 = null; - } - - if(!this.isVecInsideXZBounds(vec32)) { - vec32 = null; - } - - if(!this.isVecInsideXZBounds(vec33)) { - vec33 = null; - } - - if(!this.isVecInsideXYBounds(vec34)) { - vec34 = null; - } - - if(!this.isVecInsideXYBounds(vec35)) { - vec35 = null; - } - - Vec3 vec36 = null; - - if(vec3 != null && (vec36 == null || start.squareDistanceTo(vec3) < start.squareDistanceTo(vec36))) { - vec36 = vec3; - } - - if(vec31 != null && (vec36 == null || start.squareDistanceTo(vec31) < start.squareDistanceTo(vec36))) { - vec36 = vec31; - } - - if(vec32 != null && (vec36 == null || start.squareDistanceTo(vec32) < start.squareDistanceTo(vec36))) { - vec36 = vec32; - } - - if(vec33 != null && (vec36 == null || start.squareDistanceTo(vec33) < start.squareDistanceTo(vec36))) { - vec36 = vec33; - } - - if(vec34 != null && (vec36 == null || start.squareDistanceTo(vec34) < start.squareDistanceTo(vec36))) { - vec36 = vec34; - } - - if(vec35 != null && (vec36 == null || start.squareDistanceTo(vec35) < start.squareDistanceTo(vec36))) { - vec36 = vec35; - } - - if(vec36 == null) { - return null; - } - else { - Facing enumfacing = null; - - if(vec36 == vec3) { - enumfacing = Facing.WEST; - } - - if(vec36 == vec31) { - enumfacing = Facing.EAST; - } - - if(vec36 == vec32) { - enumfacing = Facing.DOWN; - } - - if(vec36 == vec33) { - enumfacing = Facing.UP; - } - - if(vec36 == vec34) { - enumfacing = Facing.NORTH; - } - - if(vec36 == vec35) { - enumfacing = Facing.SOUTH; - } - - return new HitPosition(ObjectType.BLOCK, vec36.addVector((double)pos.getX(), (double)pos.getY(), (double)pos.getZ()), enumfacing, pos); - } - } - - private boolean isVecInsideYZBounds(Vec3 point) { - return point == null ? false - : point.yCoord >= this.minY && point.yCoord <= this.maxY && point.zCoord >= this.minZ && point.zCoord <= this.maxZ; - } - - private boolean isVecInsideXZBounds(Vec3 point) { - return point == null ? false - : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.zCoord >= this.minZ && point.zCoord <= this.maxZ; - } - - private boolean isVecInsideXYBounds(Vec3 point) { - return point == null ? false - : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.yCoord >= this.minY && point.yCoord <= this.maxY; - } - - public void onBlockDestroyedByExplosion(World worldIn, BlockPos pos, Explosion explosionIn, State prevState) { - } - - public BlockLayer getBlockLayer() { - return BlockLayer.SOLID; - } - - public boolean canReplace(World worldIn, BlockPos pos, Facing side, ItemStack stack) { - return this.canPlaceBlockOnSide(worldIn, pos, side); - } - - public boolean canPlaceBlockOnSide(World worldIn, BlockPos pos, Facing side) { - return this.canPlaceBlockAt(worldIn, pos); - } - - public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { - return worldIn.getState(pos).getBlock().getMaterial().isReplaceable(); - } - - public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { - return false; - } - - public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, Entity entityIn) { - } - - public State onBlockPlaced(World worldIn, BlockPos pos, Facing facing, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) { - return this.getStateFromMeta(meta); - } - - public void onBlockClicked(World worldIn, BlockPos pos, EntityNPC playerIn) { - } - - public Vec3 modifyAcceleration(World worldIn, BlockPos pos, Entity entityIn, Vec3 motion) { - return motion; - } - - public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos) { - } - - public final double getBlockBoundsMinX() { - return this.minX; - } - - public final double getBlockBoundsMaxX() { - return this.maxX; - } - - public final double getBlockBoundsMinY() { - return this.minY; - } - - public final double getBlockBoundsMaxY() { - return this.maxY; - } - - public final double getBlockBoundsMinZ() { - return this.minZ; - } - - public final double getBlockBoundsMaxZ() { - return this.maxZ; - } - - public int getRenderColor(State state) { - return 16777215; - } - - public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass) { - return 16777215; - } - - public final int colorMultiplier(IWorldAccess worldIn, BlockPos pos) { - return this.colorMultiplier(worldIn, pos, 0); - } - - public int getWeakPower(IWorldAccess worldIn, BlockPos pos, State state, Facing side) { - return 0; - } - - public boolean canProvidePower() { - return false; - } - - public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, State state, Entity entityIn) { - } - - public int getStrongPower(IWorldAccess worldIn, BlockPos pos, State state, Facing side) { - return 0; - } - - public void setBlockBoundsForItemRender() { - } - - public void harvestBlock(World worldIn, EntityNPC player, BlockPos pos, State state, TileEntity te) { - if(this.canSilkHarvest() && EnchantmentHelper.getSilkTouchModifier(player)) { - ItemStack itemstack = this.createStackedBlock(state); - - if(itemstack != null) { - spawnAsEntity(worldIn, pos, itemstack); - } - } - else { - int i = EnchantmentHelper.getFortuneModifier(player); - this.dropBlockAsItem(worldIn, pos, state, i); - } - } - - public boolean canSilkHarvest() { - return this.isFullCube() && !this.hasTile; - } - - public ItemStack createStackedBlock(State state) { - int i = 0; - Item item = ItemRegistry.getItemFromBlock(this); - - if(item != null && item.getHasSubtypes()) { - i = this.getMetaFromState(state); - } - - return new ItemStack(item, 1, i); - } - - public int quantityDroppedWithBonus(int fortune, Random random) { - return this.quantityDropped(random); - } - - public void onBlockPlacedBy(World worldIn, BlockPos pos, State state, EntityLiving placer, ItemStack stack) { - } - - public boolean canSpawnInBlock() { - return !this.material.isSolid() && !this.material.isLiquid(); - } - - public final String getDisplay() { - return this.display; - } - - public boolean onBlockEventReceived(World worldIn, BlockPos pos, State state, int eventID, int eventParam) { - return false; - } - - public int getMobilityFlag() { - return this.material.getMobility(); - } - - public float getAmbientOcclusionLightValue() { - return this.isBlockNormalCube() ? 0.2F : 1.0F; - } - - public void onFallenUpon(World worldIn, BlockPos pos, Entity entityIn, float fallDistance) { - entityIn.fall(fallDistance, 1.0F); - } - - public void onLanded(World worldIn, Entity entityIn) { - entityIn.motionY = 0.0D; - } - - public Item getItem(World worldIn, BlockPos pos) { - return ItemRegistry.getItemFromBlock(this); - } - - public int getDamageValue(World worldIn, BlockPos pos) { - return this.damageDropped(worldIn.getState(pos)); - } - - public void getSubBlocks(Item itemIn, CheatTab tab, List list) { - list.add(new ItemStack(itemIn, 1, 0)); - } - - public CheatTab getTab() { - return this.tab; - } - - public void onBlockHarvested(World worldIn, BlockPos pos, State state, EntityNPC player) { - } - - public void fillWithRain(World worldIn, BlockPos pos) { - } - - public boolean isPickStrict() { - return false; - } - - public boolean requiresUpdates() { - return true; - } - - public boolean canDropFromExplosion(Explosion explosionIn) { - return true; - } - - public boolean isAssociatedBlock(Block other) { - return this == other; - } - - public static boolean isEqualTo(Block blockIn, Block other) { - return blockIn != null && other != null ? (blockIn == other ? true : blockIn.isAssociatedBlock(other)) : false; - } - - public boolean hasComparatorInputOverride() { - return false; - } - - public int getComparatorInputOverride(World worldIn, BlockPos pos) { - return 0; - } - - public State getStateForEntityRender(State state) { - return state; - } - - protected IProperty[] getProperties() { - return new IProperty[0]; - } - - protected final void setDefaultState(State state) { - this.defaultState = state; - } - - public final State getState() { - return this.defaultState; - } - - public int getMiningLevel() { - return this.miningLevel; - } - - public boolean canAxeHarvest() { - return this.axeHarvest; - } - - public boolean canShovelHarvest() { - return this.shovelHarvest; - } - - public int getShearsEfficiency() { - return this.shearsEfficiency; - } - - public boolean isMagnetic() { - return false; - } - - public Transforms getTransform() { - return Transforms.BLOCK; - } - - public Model getModel(ModelProvider provider, String name, State state) { - return provider.getModel(name).add().all(); - } - - public IProperty[] getIgnoredProperties() { - return null; - } - - public void getAnimatedTextures(Map map) { - } - - public boolean canKeepFire() { - return false; - } - - public boolean canExtinguish() { - return false; - } - - public void onDestroyedByFire(World world, BlockPos pos, State state) { - } - - public boolean onShot(World world, BlockPos pos, State state, Entity projectile) { - return this.material.blocksMovement(); - } -} diff --git a/common/src/main/java/common/block/BlockAir.java b/common/src/main/java/common/block/BlockAir.java deleted file mode 100755 index 588e87e..0000000 --- a/common/src/main/java/common/block/BlockAir.java +++ /dev/null @@ -1,35 +0,0 @@ -package common.block; - -import common.util.BlockPos; -import common.util.BoundingBox; -import common.world.State; -import common.world.World; - -public final class BlockAir extends Block { - public BlockAir() { - super(Material.NONE); - } - - public int getRenderType() { - return -1; - } - - public BoundingBox getCollisionBoundingBox(World world, BlockPos pos, State state) { - return null; - } - - public boolean isOpaqueCube() { - return false; - } - - public boolean canCollideCheck(State state, boolean liquid) { - return false; - } - - public void dropBlockAsItemWithChance(World world, BlockPos pos, State state, float chance, int fortune) { - } - - public boolean isReplaceable(World world, BlockPos pos) { - return true; - } -} diff --git a/common/src/main/java/common/block/BlockColored.java b/common/src/main/java/common/block/BlockColored.java deleted file mode 100755 index 6ff3755..0000000 --- a/common/src/main/java/common/block/BlockColored.java +++ /dev/null @@ -1,49 +0,0 @@ -package common.block; - -import java.util.List; - -import common.color.DyeColor; -import common.item.CheatTab; -import common.item.Item; -import common.item.ItemStack; -import common.model.Model; -import common.model.ModelProvider; -import common.properties.IProperty; -import common.properties.PropertyEnum; -import common.world.State; - -public class BlockColored extends Block { - public static final PropertyEnum COLOR = PropertyEnum.create("color", DyeColor.class); - - public BlockColored(Material material) { - super(material); - this.setDefaultState(this.getBaseState().withProperty(COLOR, DyeColor.WHITE)); - this.setTab(CheatTab.BLOCKS); - } - - public int damageDropped(State state) { - return state.getValue(COLOR).getMetadata(); - } - - public void getSubBlocks(Item item, CheatTab tab, List list) { - for(DyeColor color : DyeColor.values()) { - list.add(new ItemStack(item, 1, color.getMetadata())); - } - } - - public State getStateFromMeta(int meta) { - return this.getState().withProperty(COLOR, DyeColor.byMetadata(meta)); - } - - public int getMetaFromState(State state) { - return state.getValue(COLOR).getMetadata(); - } - - protected IProperty[] getProperties() { - return new IProperty[] {COLOR}; - } - - public Model getModel(ModelProvider provider, String name, State state) { - return provider.getModel(state.getValue(COLOR).getName() + "_" + name).add().all(); - } -} diff --git a/common/src/main/java/common/block/BlockContainer.java b/common/src/main/java/common/block/BlockContainer.java deleted file mode 100755 index 561a8a8..0000000 --- a/common/src/main/java/common/block/BlockContainer.java +++ /dev/null @@ -1,39 +0,0 @@ -package common.block; - -import common.tileentity.TileEntity; -import common.util.BlockPos; -import common.util.Facing; -import common.world.State; -import common.world.World; -import common.world.AWorldServer; - -public abstract class BlockContainer extends Block implements ITileEntityProvider { - public BlockContainer(Material material) { - super(material); - this.hasTile = true; - } - - protected boolean isInvalidNeighbor(World world, BlockPos pos, Facing face) { - return world.getState(pos.offset(face)).getBlock().getMaterial() == Material.BLOCKING; - } - - protected boolean hasInvalidNeighbor(World world, BlockPos pos) { - return this.isInvalidNeighbor(world, pos, Facing.NORTH) || this.isInvalidNeighbor(world, pos, Facing.SOUTH) - || this.isInvalidNeighbor(world, pos, Facing.WEST) || this.isInvalidNeighbor(world, pos, Facing.EAST); - } - - public int getRenderType() { - return -1; - } - - public void onBlockRemoved(AWorldServer world, BlockPos pos, State state) { - super.onBlockRemoved(world, pos, state); - world.removeTileEntity(pos); - } - - public boolean onBlockEventReceived(World world, BlockPos pos, State state, int id, int param) { - super.onBlockEventReceived(world, pos, state, id, param); - TileEntity tile = world.getTileEntity(pos); - return tile == null ? false : tile.receiveClientEvent(id, param); - } -} diff --git a/common/src/main/java/common/block/BlockDirectional.java b/common/src/main/java/common/block/BlockDirectional.java deleted file mode 100755 index 0cb7a7a..0000000 --- a/common/src/main/java/common/block/BlockDirectional.java +++ /dev/null @@ -1,12 +0,0 @@ -package common.block; - -import common.properties.PropertyDirection; -import common.util.Facing; - -public abstract class BlockDirectional extends Block { - public static final PropertyDirection FACING = PropertyDirection.create("facing", Facing.Plane.HORIZONTAL); - - public BlockDirectional(Material material) { - super(material); - } -} diff --git a/common/src/main/java/common/block/BlockFalling.java b/common/src/main/java/common/block/BlockFalling.java deleted file mode 100755 index 7c793f9..0000000 --- a/common/src/main/java/common/block/BlockFalling.java +++ /dev/null @@ -1,72 +0,0 @@ -package common.block; - -import common.block.natural.BlockFire; -import common.entity.item.EntityFalling; -import common.init.Blocks; -import common.rng.Random; -import common.util.BlockPos; -import common.vars.Vars; -import common.world.State; -import common.world.World; -import common.world.AWorldServer; - -public class BlockFalling extends Block { - public static boolean fallInstantly; - - public static boolean canFallInto(World world, BlockPos pos) { - Block block = world.getState(pos).getBlock(); - return block instanceof BlockFire || block == Blocks.air || block.getMaterial().isLiquid(); - } - - public BlockFalling(Material material) { - super(material); - } - - public void onBlockAdded(AWorldServer world, BlockPos pos, State state) { - world.scheduleUpdate(pos, this, this.tickRate(world, pos)); - } - - public void onNeighborBlockChange(World world, BlockPos pos, State state, Block neighbor) { - world.scheduleUpdate(pos, this, this.tickRate(world, pos)); - } - - public void updateTick(AWorldServer world, BlockPos pos, State state, Random rand) { - if(Vars.blockGravity) - this.checkFallable(world, pos); - } - - private void checkFallable(World world, BlockPos pos) { - if(canFallInto(world, pos.down()) && pos.getY() >= 0) { - int range = 32; - if(!fallInstantly && world.isAreaLoaded(pos.add(-range, -range, -range), pos.add(range, range, range))) { - if(!world.client) { - EntityFalling entity = new EntityFalling(world, (double)pos.getX() + 0.5D, (double)pos.getY(), - (double)pos.getZ() + 0.5D, world.getState(pos)); - this.onStartFalling(entity); - world.spawnEntityInWorld(entity); - } - } - else { - world.setBlockToAir(pos); - BlockPos loc; - int limit = 512; - for(loc = pos.down(); canFallInto(world, loc) && loc.getY() > -World.MAX_SIZE_Y; loc = loc.down()) { - if(--limit <= 0) - return; - } - if(loc.getY() > -World.MAX_SIZE_Y) - world.setState(loc.up(), this.getState()); - } - } - } - - public int tickRate(World world, BlockPos pos) { - return 2; - } - - protected void onStartFalling(EntityFalling entity) { - } - - public void onEndFalling(World world, BlockPos pos) { - } -} diff --git a/common/src/main/java/common/block/BlockTranslucent.java b/common/src/main/java/common/block/BlockTranslucent.java deleted file mode 100755 index e74012f..0000000 --- a/common/src/main/java/common/block/BlockTranslucent.java +++ /dev/null @@ -1,27 +0,0 @@ -package common.block; - -import common.model.BlockLayer; -import common.util.BlockPos; -import common.util.Facing; -import common.world.IWorldAccess; -import common.world.State; - -public class BlockTranslucent extends Block { - public BlockTranslucent(Material material) { - super(material); - } - - public final boolean isOpaqueCube() { - return false; - } - - public final BlockLayer getBlockLayer() { - return BlockLayer.TRANSLUCENT; - } - - public boolean shouldSideBeRendered(IWorldAccess world, BlockPos pos, Facing side) { - State state = world.getState(pos); - Block block = state.getBlock(); - return block != this && super.shouldSideBeRendered(world, pos, side); - } -} diff --git a/common/src/main/java/common/block/ITileEntityProvider.java b/common/src/main/java/common/block/ITileEntityProvider.java deleted file mode 100755 index fe4ab9f..0000000 --- a/common/src/main/java/common/block/ITileEntityProvider.java +++ /dev/null @@ -1,8 +0,0 @@ -package common.block; - -import common.tileentity.TileEntity; -import common.world.World; - -public interface ITileEntityProvider { - TileEntity createNewTileEntity(World world); -} diff --git a/common/src/main/java/common/block/Material.java b/common/src/main/java/common/block/Material.java deleted file mode 100755 index 5abbdb0..0000000 --- a/common/src/main/java/common/block/Material.java +++ /dev/null @@ -1,192 +0,0 @@ -package common.block; - -public enum Material { - NONE {{ - this.setNonSolid().setReplaceable(); - }}, - LOOSE {{ - ; - }}, - WOOD {{ - this.setBurning(); - }}, - SOLID {{ - this.setRequiresTool(); - }}, - DIGGABLE {{ // can harvest with shovel - this.setRequiresTool(); - }}, - TRANSLUCENT {{ - this.setTranslucent(); - }}, - BURNABLE {{ - this.setBurning(); - }}, - SOFT {{ // can break faster with sword, can't connect to fences+walls - this.setNoPushMobility(); - }}, - PISTON {{ - this.setImmovableMobility(); - }}, - HEAVY {{ - this.setRequiresTool().setImmovableMobility(); - }}, - PLANT {{ // can break faster with sword - this.setNonSolid().setNoPushMobility(); - }}, - SMALL {{ // can be placed more easily - this.setNonSolid().setNoPushMobility(); - }}, - FLEECE {{ - this.setNonSolid().setBurning(); - }}, - EXPLOSIVE {{ - this.setBurning().setTranslucent(); - }}, - BLOCKING {{ // can't be placed next to signs and banners - this.setTranslucent().setNoPushMobility(); - }}, - PORTAL {{ // not floodable by liquids - this.setNonSolid().setImmovableMobility(); - }}, - WATER {{ - this.setLiquid(false).setReplaceable().setNoPushMobility(); - }}, - COLD {{ - this.setLiquid(false).setReplaceable().setNoPushMobility(); - }}, - LAVA {{ - this.setLiquid(true).setReplaceable().setNoPushMobility(); - }}, - HOT {{ - this.setLiquid(true).setReplaceable().setNoPushMobility(); - }}, - LEAVES {{ // can break faster with sword, precipitation block, special treatment in some worldgen - this.setBurning().setTranslucent().setNoPushMobility(); - }}, - BUSH {{ // can break faster with sword, can be replaced by small tree leaves - this.setNonSolid().setBurning().setNoPushMobility().setReplaceable(); - }}, - FIRE {{ - this.setNonSolid().setReplaceable().setNoPushMobility(); - }}, - POWDER {{ // can harvest with shovel, precipitation block - this.setNonSolid().setReplaceable().setRequiresTool().setNoPushMobility(); - }}, - FLUFF {{ // can harvest with shears - this.setPassable().setRequiresTool().setNoPushMobility(); - }}; - - private boolean solid = true; - private boolean lightOpaque = true; - private boolean unpassable = true; - private boolean opaque = true; - private boolean liquid; - private boolean cold; - private boolean hot; - private boolean burnable; - private boolean replaceable; - private boolean requiresTool; - // 0 - normal; 1 - can't push other blocks; 2 - can't be pushed - private int mobility; - - protected Material setTranslucent() { - this.opaque = false; - return this; - } - - protected Material setNonSolid() { - this.solid = false; - this.lightOpaque = false; - this.unpassable = false; - this.opaque = false; - return this; - } - - protected Material setPassable() { - this.unpassable = false; - this.opaque = false; - return this; - } - - protected Material setLiquid(boolean hot) { - this.solid = false; - this.unpassable = false; - this.opaque = false; - this.liquid = true; - if(hot) - this.hot = true; - else - this.cold = true; - return this; - } - - protected Material setRequiresTool() { - this.requiresTool = true; - return this; - } - - protected Material setBurning() { - this.burnable = true; - return this; - } - - protected Material setReplaceable() { - this.replaceable = true; - return this; - } - - protected Material setNoPushMobility() { - this.mobility = 1; - return this; - } - - protected Material setImmovableMobility() { - this.mobility = 2; - return this; - } - - public boolean isLiquid() { - return this.liquid; - } - - public boolean isColdLiquid() { - return this.cold; - } - - public boolean isHotLiquid() { - return this.hot; - } - - public boolean isSolid() { - return this.solid; - } - - public boolean blocksLight() { - return this.lightOpaque; - } - - public boolean blocksMovement() { - return this.unpassable; - } - - public boolean getCanBurn() { - return this.burnable; - } - - public boolean isReplaceable() { - return this.replaceable; - } - - public boolean isOpaque() { - return this.opaque; - } - - public boolean isToolRequired() { - return this.requiresTool; - } - - public int getMobility() { - return this.mobility; - } -} diff --git a/common/src/main/java/common/block/artificial/BlockGlass.java b/common/src/main/java/common/block/artificial/BlockGlass.java deleted file mode 100755 index e331570..0000000 --- a/common/src/main/java/common/block/artificial/BlockGlass.java +++ /dev/null @@ -1,51 +0,0 @@ -package common.block.artificial; - -import common.block.Block; -import common.block.Material; -import common.entity.Entity; -import common.item.CheatTab; -import common.model.BlockLayer; -import common.rng.Random; -import common.util.BlockPos; -import common.util.Facing; -import common.world.IWorldAccess; -import common.world.State; -import common.world.World; - -public class BlockGlass extends Block { - public BlockGlass() { - super(Material.TRANSLUCENT); - this.setTab(CheatTab.BLOCKS); - } - - public int quantityDropped(Random rand) { - return 0; - } - - public BlockLayer getBlockLayer() { - return BlockLayer.CUTOUT; - } - - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - public boolean canSilkHarvest() { - return true; - } - - public boolean shouldSideBeRendered(IWorldAccess world, BlockPos pos, Facing side) { - State state = world.getState(pos); - Block block = state.getBlock(); - return world.getState(pos.offset(side.getOpposite())) != state || (block != this && super.shouldSideBeRendered(world, pos, side)); - } - - public boolean onShot(World world, BlockPos pos, State state, Entity projectile) { - world.destroyBlock(pos, true); - return false; - } -} diff --git a/common/src/main/java/common/block/artificial/BlockSkull.java b/common/src/main/java/common/block/artificial/BlockSkull.java deleted file mode 100755 index f5f0c26..0000000 --- a/common/src/main/java/common/block/artificial/BlockSkull.java +++ /dev/null @@ -1,75 +0,0 @@ -package common.block.artificial; - -import common.block.BlockDirectional; -import common.block.Material; -import common.entity.Entity; -import common.entity.types.EntityLiving; -import common.init.Items; -import common.item.Item; -import common.model.Model; -import common.model.ModelProvider; -import common.model.ModelRotation; -import common.properties.IProperty; -import common.rng.Random; -import common.util.BlockPos; -import common.util.Facing; -import common.world.State; -import common.world.World; - -public class BlockSkull extends BlockDirectional { - public BlockSkull() { - super(Material.SMALL); - this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); - this.setBlockBounds(0.25F, 0.0F, 0.25F, 0.75F, 0.5F, 0.75F); - } - - public boolean canPlaceBlockAt(World world, BlockPos pos) { - return world.getState(pos).getBlock().getMaterial().isReplaceable() && world.isBlockSolid(pos.down()); - } - - public State onBlockPlaced(World world, BlockPos pos, Facing face, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) { - return this.getState().withProperty(FACING, placer.getHorizontalFacing().getOpposite()); - } - - public State getStateFromMeta(int meta) { - return this.getState().withProperty(FACING, Facing.getHorizontal(meta)); - } - - public int getMetaFromState(State state) { - return state.getValue(FACING).getHorizontalIndex(); - } - - protected IProperty[] getProperties() { - return new IProperty[] {FACING}; - } - - public Model getModel(ModelProvider provider, String name, State state) { - return provider.getModel("skull_top").add(4, 0, 4, 12, 8, 12) - .d("skull_bottom").u().n("skull_front").s("skull_back").w("skull_right").e("skull_left").rotate(ModelRotation.getNorthRot(state.getValue(FACING))); - } - - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - public Item getItemDropped(State state, Random rand, int fortune) { - return Items.skull; - } - - public Item getItem(World worldIn, BlockPos pos) { - return Items.skull; - } - - public boolean isXrayVisible() { - return true; - } - - public boolean onShot(World world, BlockPos pos, State state, Entity projectile) { - world.destroyBlock(pos, true); - return true; - } -} diff --git a/common/src/main/java/common/block/artificial/BlockStainedGlass.java b/common/src/main/java/common/block/artificial/BlockStainedGlass.java deleted file mode 100755 index 8ca8637..0000000 --- a/common/src/main/java/common/block/artificial/BlockStainedGlass.java +++ /dev/null @@ -1,52 +0,0 @@ -package common.block.artificial; - -import java.util.List; - -import common.color.DyeColor; -import common.item.CheatTab; -import common.item.Item; -import common.item.ItemStack; -import common.model.BlockLayer; -import common.model.Model; -import common.model.ModelProvider; -import common.properties.IProperty; -import common.properties.PropertyEnum; -import common.world.State; - -public class BlockStainedGlass extends BlockGlass { - public static final PropertyEnum COLOR = PropertyEnum.create("color", DyeColor.class); - - public BlockStainedGlass() { - this.setDefaultState(this.getBaseState().withProperty(COLOR, DyeColor.WHITE)); - } - - public int damageDropped(State state) { - return state.getValue(COLOR).getMetadata(); - } - - public void getSubBlocks(Item item, CheatTab tab, List list) { - for(DyeColor color : DyeColor.values()) { - list.add(new ItemStack(item, 1, color.getMetadata())); - } - } - - public BlockLayer getBlockLayer() { - return BlockLayer.TRANSLUCENT; - } - - public State getStateFromMeta(int meta) { - return this.getState().withProperty(COLOR, DyeColor.byMetadata(meta)); - } - - public int getMetaFromState(State state) { - return state.getValue(COLOR).getMetadata(); - } - - protected IProperty[] getProperties() { - return new IProperty[] {COLOR}; - } - - public Model getModel(ModelProvider provider, String name, State state) { - return provider.getModel(state.getValue(COLOR).getName() + "_glass").add().all(); - } -} diff --git a/common/src/main/java/common/block/foliage/BlockPumpkin.java b/common/src/main/java/common/block/foliage/BlockPumpkin.java deleted file mode 100755 index 9b70bad..0000000 --- a/common/src/main/java/common/block/foliage/BlockPumpkin.java +++ /dev/null @@ -1,47 +0,0 @@ -package common.block.foliage; - -import common.block.BlockDirectional; -import common.block.Material; -import common.entity.types.EntityLiving; -import common.item.CheatTab; -import common.model.Model; -import common.model.ModelProvider; -import common.model.ModelRotation; -import common.properties.IProperty; -import common.util.BlockPos; -import common.util.Facing; -import common.world.State; -import common.world.World; - -public class BlockPumpkin extends BlockDirectional { - public BlockPumpkin() { - super(Material.SOFT); - this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); - this.setTab(CheatTab.PLANTS); - } - - public boolean canPlaceBlockAt(World world, BlockPos pos) { - return world.getState(pos).getBlock().getMaterial().isReplaceable() && world.isBlockSolid(pos.down()); - } - - public State onBlockPlaced(World world, BlockPos pos, Facing face, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) { - return this.getState().withProperty(FACING, placer.getHorizontalFacing().getOpposite()); - } - - public State getStateFromMeta(int meta) { - return this.getState().withProperty(FACING, Facing.getHorizontal(meta)); - } - - public int getMetaFromState(State state) { - return state.getValue(FACING).getHorizontalIndex(); - } - - protected IProperty[] getProperties() { - return new IProperty[] {FACING}; - } - - public Model getModel(ModelProvider provider, String name, State state) { - return provider.getModel("pumpkin_side").add().du("pumpkin_top").n("pumpkin_face_" + (this.getLightValue() == 0 ? "off" : "on")).s().we() - .rotate(ModelRotation.getNorthRot(state.getValue(FACING))); - } -} diff --git a/common/src/main/java/common/block/natural/BlockIce.java b/common/src/main/java/common/block/natural/BlockIce.java deleted file mode 100755 index 725f6fe..0000000 --- a/common/src/main/java/common/block/natural/BlockIce.java +++ /dev/null @@ -1,65 +0,0 @@ -package common.block.natural; - -import common.block.BlockTranslucent; -import common.block.Material; -import common.enchantment.EnchantmentHelper; -import common.entity.npc.EntityNPC; -import common.init.Blocks; -import common.item.CheatTab; -import common.item.ItemStack; -import common.rng.Random; -import common.tileentity.TileEntity; -import common.util.BlockPos; -import common.vars.Vars; -import common.world.LightType; -import common.world.State; -import common.world.World; -import common.world.AWorldServer; - -public class BlockIce extends BlockTranslucent { - public BlockIce() { - super(Material.TRANSLUCENT); - this.slipperiness = 0.98F; - this.setTickRandomly(); - this.setTab(CheatTab.NATURE); - } - - public void harvestBlock(World world, EntityNPC player, BlockPos pos, State state, TileEntity tile) { - if(this.canSilkHarvest() && EnchantmentHelper.getSilkTouchModifier(player)) { - ItemStack stack = this.createStackedBlock(state); - if(stack != null) - spawnAsEntity(world, pos, stack); - } - else { - if(world.doesWaterVaporize(pos)) { - world.setBlockToAir(pos); - return; - } - int fortune = EnchantmentHelper.getFortuneModifier(player); - this.dropBlockAsItem(world, pos, state, fortune); - Material material = world.getState(pos.down()).getBlock().getMaterial(); - if(material.blocksMovement() || material.isLiquid()) - world.setState(pos, Blocks.flowing_water.getState()); - } - } - - public int quantityDropped(Random rand) { - return 0; - } - - public void updateTick(AWorldServer world, BlockPos pos, State state, Random rand) { - if(Vars.iceMelt && (world.getLightFor(LightType.BLOCK, pos) > 11 - this.getLightOpacity() || !world.canFreezeAt(pos))) { - if(world.doesWaterVaporize(pos)) { - world.setBlockToAir(pos); - } - else { - this.dropBlockAsItem(world, pos, world.getState(pos), 0); - world.setState(pos, Blocks.water.getState()); - } - } - } - - public int getMobilityFlag() { - return 0; - } -} diff --git a/common/src/main/java/common/block/natural/BlockSlime.java b/common/src/main/java/common/block/natural/BlockSlime.java deleted file mode 100755 index 1d1f6f6..0000000 --- a/common/src/main/java/common/block/natural/BlockSlime.java +++ /dev/null @@ -1,63 +0,0 @@ -package common.block.natural; - -import common.block.BlockTranslucent; -import common.block.Material; -import common.entity.Entity; -import common.item.CheatTab; -import common.model.Model; -import common.model.ModelProvider; -import common.util.BlockPos; -import common.world.State; -import common.world.World; - -public class BlockSlime extends BlockTranslucent { - private static final Model slime = ModelProvider.getModelProvider().getModel("slime") - .add(0, 0, 0, 16, 16, 16) - .d().uv(0, 0, 16, 16).noCull() - .u().uv(0, 0, 16, 16).noCull() - .n().uv(0, 0, 16, 16).noCull() - .s().uv(0, 0, 16, 16).noCull() - .w().uv(0, 0, 16, 16).noCull() - .e().uv(0, 0, 16, 16).noCull() - .add(3, 3, 3, 13, 13, 13) - .d().uv(3, 3, 13, 13).noCull() - .u().uv(3, 3, 13, 13).noCull() - .n().uv(3, 3, 13, 13).noCull() - .s().uv(3, 3, 13, 13).noCull() - .w().uv(3, 3, 13, 13).noCull() - .e().uv(3, 3, 13, 13).noCull() - ; - - public BlockSlime() { - super(Material.LOOSE); - this.setTab(CheatTab.TECHNOLOGY); - this.slipperiness = 0.8F; - } - - public void onFallenUpon(World world, BlockPos pos, Entity entity, float distance) { - if(entity.isSneaking()) - super.onFallenUpon(world, pos, entity, distance); - else - entity.fall(distance, 0.0F); - } - - public void onLanded(World world, Entity entity) { - if(entity.isSneaking()) - super.onLanded(world, entity); - else if(entity.motionY < 0.0D) - entity.motionY = -entity.motionY; - } - - public void onEntityCollidedWithBlock(World world, BlockPos pos, Entity entity) { - if(Math.abs(entity.motionY) < 0.1D && !entity.isSneaking()) { - double friction = 0.4D + Math.abs(entity.motionY) * 0.2D; - entity.motionX *= friction; - entity.motionZ *= friction; - } - super.onEntityCollidedWithBlock(world, pos, entity); - } - - public Model getModel(ModelProvider provider, String name, State state) { - return slime; - } -} diff --git a/common/src/main/java/common/block/natural/BlockSnowBlock.java b/common/src/main/java/common/block/natural/BlockSnowBlock.java deleted file mode 100755 index 0e9dd52..0000000 --- a/common/src/main/java/common/block/natural/BlockSnowBlock.java +++ /dev/null @@ -1,36 +0,0 @@ -package common.block.natural; - -import common.block.Block; -import common.block.Material; -import common.init.Items; -import common.item.CheatTab; -import common.item.Item; -import common.rng.Random; -import common.util.BlockPos; -import common.vars.Vars; -import common.world.LightType; -import common.world.State; -import common.world.AWorldServer; - -public class BlockSnowBlock extends Block { - public BlockSnowBlock() { - super(Material.DIGGABLE); - this.setTickRandomly(); - this.setTab(CheatTab.NATURE); - } - - public Item getItemDropped(State state, Random rand, int fortune) { - return Items.snowball; - } - - public int quantityDropped(Random rand) { - return rand.range(2, 4); - } - - public void updateTick(AWorldServer world, BlockPos pos, State state, Random rand) { - if(Vars.snowFullMelt && (world.getLightFor(LightType.BLOCK, pos) > 11 || !world.canFreezeAt(pos))) { - this.dropBlockAsItem(world, pos, world.getState(pos), 0); - world.setBlockToAir(pos); - } - } -} diff --git a/common/src/main/java/common/block/natural/BlockSoulFire.java b/common/src/main/java/common/block/natural/BlockSoulFire.java deleted file mode 100644 index 9cacaeb..0000000 --- a/common/src/main/java/common/block/natural/BlockSoulFire.java +++ /dev/null @@ -1,18 +0,0 @@ -package common.block.natural; - -import common.rng.Random; -import common.util.BlockPos; -import common.world.World; - -public class BlockSoulFire extends BlockTintedFire { - public BlockSoulFire() { - super(0x4010ff); - } - - protected void catchOnFire(World world, BlockPos pos, int chance, Random rand, int age) { - } - - protected boolean canDie(World world, BlockPos pos) { - return super.canDie(world, pos) || world.rand.chance(20); - } -} diff --git a/common/src/main/java/common/block/natural/BlockTintedFire.java b/common/src/main/java/common/block/natural/BlockTintedFire.java deleted file mode 100644 index 70e64c6..0000000 --- a/common/src/main/java/common/block/natural/BlockTintedFire.java +++ /dev/null @@ -1,35 +0,0 @@ -package common.block.natural; - -import java.util.Map; - -import common.model.Model; -import common.model.ModelProvider; -import common.util.BlockPos; -import common.world.IWorldAccess; -import common.world.State; - -public class BlockTintedFire extends BlockFire { - private final int tint; - - public BlockTintedFire(int tint) { - this.tint = tint; - } - - public int getRenderColor(State state) { - return this.tint; - } - - public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass) { - return this.tint; - } - - public Model getModel(ModelProvider provider, String name, State state) { - return getFireModel(state.getValue(ALT) ? "flame_layer_1" : "flame_layer_0", state.getValue(FLIP), state.getValue(UPPER), - state.getValue(NORTH), state.getValue(SOUTH), state.getValue(WEST), state.getValue(EAST)); - } - - public void getAnimatedTextures(Map map) { - map.put("blocks/flame_layer_0", "flame1"); - map.put("blocks/flame_layer_1", "flame2"); - } -} diff --git a/common/src/main/java/common/block/tech/BlockMobSpawner.java b/common/src/main/java/common/block/tech/BlockMobSpawner.java deleted file mode 100755 index 12399c6..0000000 --- a/common/src/main/java/common/block/tech/BlockMobSpawner.java +++ /dev/null @@ -1,11 +0,0 @@ -package common.block.tech; - -import common.tileentity.TileEntity; -import common.tileentity.TileEntityMobSpawner; -import common.world.World; - -public class BlockMobSpawner extends BlockMachine { - public TileEntity createNewTileEntity(World world) { - return new TileEntityMobSpawner(); - } -} diff --git a/common/src/main/java/common/block/tech/BlockNote.java b/common/src/main/java/common/block/tech/BlockNote.java deleted file mode 100755 index f9ce07c..0000000 --- a/common/src/main/java/common/block/tech/BlockNote.java +++ /dev/null @@ -1,47 +0,0 @@ -package common.block.tech; - -import common.block.Block; -import common.block.Material; -import common.entity.npc.EntityNPC; -import common.init.Blocks; -import common.init.SoundEvent; -import common.item.CheatTab; -import common.model.ParticleType; -import common.util.BlockPos; -import common.util.Facing; -import common.world.State; -import common.world.World; - -public class BlockNote extends Block { - public BlockNote() { - super(Material.WOOD); - this.setTab(CheatTab.TECHNOLOGY); - } - - public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) { - if(worldIn.isBlockPowered(pos)) - worldIn.addBlockEvent(pos, Blocks.noteblock, 0, 0); - } - - public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { - if(!worldIn.client) - worldIn.addBlockEvent(pos, Blocks.noteblock, 0, 0); - return true; - } - - public void onBlockClicked(World worldIn, BlockPos pos, EntityNPC playerIn) { - if(!worldIn.client) - worldIn.addBlockEvent(pos, Blocks.noteblock, 0, 0); - } - - public boolean onBlockEventReceived(World worldIn, BlockPos pos, State state, int eventID, int eventParam) { - worldIn.playSound(SoundEvent.NOTE, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, 3.0F); - worldIn.spawnParticle(ParticleType.NOTE, (double)pos.getX() + 0.5D, (double)pos.getY() + 1.2D, (double)pos.getZ() + 0.5D, - (double)eventParam / 24.0D, 0.0D, 0.0D); - return true; - } - - public boolean isMagnetic() { - return true; - } -} diff --git a/common/src/main/java/common/block/tile/BlockBanner.java b/common/src/main/java/common/block/tile/BlockBanner.java deleted file mode 100755 index e34b8e8..0000000 --- a/common/src/main/java/common/block/tile/BlockBanner.java +++ /dev/null @@ -1,165 +0,0 @@ -package common.block.tile; - -import common.block.BlockContainer; -import common.block.Material; -import common.entity.npc.EntityNPC; -import common.init.Items; -import common.item.Item; -import common.item.ItemStack; -import common.model.Transforms; -import common.properties.PropertyDirection; -import common.properties.PropertyInteger; -import common.rng.Random; -import common.tags.TagObject; -import common.tileentity.TileEntity; -import common.tileentity.TileEntityBanner; -import common.util.BlockPos; -import common.util.BoundingBox; -import common.util.Facing; -import common.world.IBlockAccess; -import common.world.State; -import common.world.World; - -public class BlockBanner extends BlockContainer -{ - public static final PropertyDirection FACING = PropertyDirection.create("facing", Facing.Plane.HORIZONTAL); - public static final PropertyInteger ROTATION = PropertyInteger.create("rotation", 0, 15); - - public BlockBanner() - { - super(Material.WOOD); - float f = 0.25F; - float f1 = 1.0F; - this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); - } - -// /** -// * Gets the localized name of this block. Used for the statistics page. -// */ -// public String getLocalizedName() -// { -// return "Banner"; -// } - - public boolean isPickStrict() - { - return true; - } - - public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) - { - return null; - } - - public BoundingBox getSelectedBoundingBox(World worldIn, BlockPos pos) - { - this.setBlockBoundsBasedOnState(worldIn, pos); - return super.getSelectedBoundingBox(worldIn, pos); - } - - public boolean isFullCube() - { - return false; - } - - public boolean isPassable(IBlockAccess worldIn, BlockPos pos) - { - return true; - } - - /** - * Used to determine ambient occlusion and culling when rebuilding chunks for render - */ - public boolean isOpaqueCube() - { - return false; - } - - /** - * Return true if an entity can be spawned inside the block (used to get the player's bed spawn location) - */ - public boolean canSpawnInBlock() - { - return true; - } - - /** - * Returns a new instance of a block's tile entity class. Called on placing the block. - */ - public TileEntity createNewTileEntity(World worldIn) - { - return new TileEntityBanner(); - } - - /** - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(State state, Random rand, int fortune) - { - return Items.banner; - } - - public Item getItem(World worldIn, BlockPos pos) - { - return Items.banner; - } - - public int getDamageValue(World worldIn, BlockPos pos) - { - TileEntity te = worldIn.getTileEntity(pos); - if(te instanceof TileEntityBanner) - return ((TileEntityBanner)te).getBaseColor(); - return super.getDamageValue(worldIn, pos); - } - - /** - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) - { - TileEntity tileentity = worldIn.getTileEntity(pos); - - if (tileentity instanceof TileEntityBanner) - { - ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner)tileentity).getBaseColor()); - TagObject tag = new TagObject(); - tileentity.writeTags(tag); - tag.remove("x"); - tag.remove("y"); - tag.remove("z"); - tag.remove("id"); - itemstack.setTagInfo("BlockEntityTag", tag); - spawnAsEntity(worldIn, pos, itemstack); - } - else - { - super.dropBlockAsItemWithChance(worldIn, pos, state, chance, fortune); - } - } - - public boolean canPlaceBlockAt(World worldIn, BlockPos pos) - { - return !this.hasInvalidNeighbor(worldIn, pos) && super.canPlaceBlockAt(worldIn, pos); - } - - public void harvestBlock(World worldIn, EntityNPC player, BlockPos pos, State state, TileEntity te) - { - if (te instanceof TileEntityBanner) - { - TileEntityBanner tileentitybanner = (TileEntityBanner)te; - ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner)te).getBaseColor()); - TagObject tag = new TagObject(); - TileEntityBanner.setBaseColorAndPatterns(tag, tileentitybanner.getBaseColor(), tileentitybanner.getPatterns()); - itemstack.setTagInfo("BlockEntityTag", tag); - spawnAsEntity(worldIn, pos, itemstack); - } - else - { - super.harvestBlock(worldIn, player, pos, state, (TileEntity)null); - } - } - - public Transforms getTransform() { - return Transforms.BANNER; - } -} diff --git a/common/src/main/java/common/block/tile/BlockBannerHanging.java b/common/src/main/java/common/block/tile/BlockBannerHanging.java deleted file mode 100644 index 1d54303..0000000 --- a/common/src/main/java/common/block/tile/BlockBannerHanging.java +++ /dev/null @@ -1,82 +0,0 @@ -package common.block.tile; - -import common.block.Block; -import common.properties.IProperty; -import common.util.BlockPos; -import common.util.Facing; -import common.world.IWorldAccess; -import common.world.State; -import common.world.World; - -public class BlockBannerHanging extends BlockBanner -{ - public BlockBannerHanging() - { - this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); - } - - public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos) - { - Facing enumfacing = (Facing)worldIn.getState(pos).getValue(FACING); - float f = 0.0F; - float f1 = 0.78125F; - float f2 = 0.0F; - float f3 = 1.0F; - float f4 = 0.125F; - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - - switch (enumfacing) - { - case NORTH: - default: - this.setBlockBounds(f2, f, 1.0F - f4, f3, f1, 1.0F); - break; - - case SOUTH: - this.setBlockBounds(f2, f, 0.0F, f3, f1, f4); - break; - - case WEST: - this.setBlockBounds(1.0F - f4, f, f2, 1.0F, f1, f3); - break; - - case EAST: - this.setBlockBounds(0.0F, f, f2, f4, f1, f3); - } - } - - public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) - { - Facing enumfacing = (Facing)state.getValue(FACING); - - if (!worldIn.getState(pos.offset(enumfacing.getOpposite())).getBlock().getMaterial().isSolid()) - { - this.dropBlockAsItem(worldIn, pos, state, 0); - worldIn.setBlockToAir(pos); - } - - super.onNeighborBlockChange(worldIn, pos, state, neighborBlock); - } - - public State getStateFromMeta(int meta) - { - Facing enumfacing = Facing.getFront(meta); - - if (enumfacing.getAxis() == Facing.Axis.Y) - { - enumfacing = Facing.NORTH; - } - - return this.getState().withProperty(FACING, enumfacing); - } - - public int getMetaFromState(State state) - { - return ((Facing)state.getValue(FACING)).getIndex(); - } - - protected IProperty[] getProperties() - { - return new IProperty[] {FACING}; - } -} \ No newline at end of file diff --git a/common/src/main/java/common/block/tile/BlockBannerStanding.java b/common/src/main/java/common/block/tile/BlockBannerStanding.java deleted file mode 100644 index 9a6e28c..0000000 --- a/common/src/main/java/common/block/tile/BlockBannerStanding.java +++ /dev/null @@ -1,41 +0,0 @@ -package common.block.tile; - -import common.block.Block; -import common.properties.IProperty; -import common.util.BlockPos; -import common.world.State; -import common.world.World; - -public class BlockBannerStanding extends BlockBanner -{ - public BlockBannerStanding() - { - this.setDefaultState(this.getBaseState().withProperty(ROTATION, Integer.valueOf(0))); - } - - public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) - { - if (!worldIn.getState(pos.down()).getBlock().getMaterial().isSolid()) - { - this.dropBlockAsItem(worldIn, pos, state, 0); - worldIn.setBlockToAir(pos); - } - - super.onNeighborBlockChange(worldIn, pos, state, neighborBlock); - } - - public State getStateFromMeta(int meta) - { - return this.getState().withProperty(ROTATION, Integer.valueOf(meta)); - } - - public int getMetaFromState(State state) - { - return ((Integer)state.getValue(ROTATION)).intValue(); - } - - protected IProperty[] getProperties() - { - return new IProperty[] {ROTATION}; - } -} \ No newline at end of file diff --git a/common/src/main/java/common/dimension/CloudType.java b/common/src/main/java/common/dimension/CloudType.java deleted file mode 100644 index a3f1b14..0000000 --- a/common/src/main/java/common/dimension/CloudType.java +++ /dev/null @@ -1,39 +0,0 @@ -package common.dimension; - -import java.util.Map; - -import common.collect.Maps; - -public enum CloudType { - NORMAL("normal", "clouds"), - DENSE("dense", "clouds_dense"); - - private static final Map LOOKUP = Maps.newHashMap(); - - private final String name; - private final String texture; - - private CloudType(String name, String texture) { - this.name = name; - this.texture = texture; - } - - public String toString() { - return this.name; - } - - public String getTexture() { - return this.texture; - } - - public static CloudType getByName(String name) { - CloudType type = LOOKUP.get(name.toLowerCase()); - return type == null ? NORMAL : type; - } - - static { - for(CloudType type : values()) { - LOOKUP.put(type.name, type); - } - } -} \ No newline at end of file diff --git a/common/src/main/java/common/dimension/Lake.java b/common/src/main/java/common/dimension/Lake.java deleted file mode 100644 index 6b32f6b..0000000 --- a/common/src/main/java/common/dimension/Lake.java +++ /dev/null @@ -1,6 +0,0 @@ -package common.dimension; - -import common.world.State; - -public record Lake(State state, State filler, State top, int chance, int minHeight, int maxHeight, boolean ratiod) { -} diff --git a/common/src/main/java/common/dimension/Liquid.java b/common/src/main/java/common/dimension/Liquid.java deleted file mode 100644 index 191a84d..0000000 --- a/common/src/main/java/common/dimension/Liquid.java +++ /dev/null @@ -1,6 +0,0 @@ -package common.dimension; - -import common.world.State; - -public record Liquid(State state, int chance, int minHeight, int maxHeight, boolean lower) { -} diff --git a/common/src/main/java/common/dimension/Ore.java b/common/src/main/java/common/dimension/Ore.java deleted file mode 100644 index 6bbdb93..0000000 --- a/common/src/main/java/common/dimension/Ore.java +++ /dev/null @@ -1,6 +0,0 @@ -package common.dimension; - -import common.world.State; - -public record Ore(State state, int count, int more, int size, int min, int max, boolean dist) { -} diff --git a/common/src/main/java/common/dimension/SkyboxType.java b/common/src/main/java/common/dimension/SkyboxType.java deleted file mode 100644 index 3183956..0000000 --- a/common/src/main/java/common/dimension/SkyboxType.java +++ /dev/null @@ -1,37 +0,0 @@ -package common.dimension; - -import java.util.Map; - -import common.collect.Maps; - -public enum SkyboxType { - ; - - private static final Map LOOKUP = Maps.newHashMap(); - - private final String name; - private final String texture; - - private SkyboxType(String name, String texture) { - this.name = name; - this.texture = texture; - } - - public String toString() { - return this.name; - } - - public String getTexture() { - return this.texture; - } - - public static SkyboxType getByName(String name) { - return LOOKUP.get(name.toLowerCase()); - } - - static { - for(SkyboxType type : values()) { - LOOKUP.put(type.name, type); - } - } -} \ No newline at end of file diff --git a/common/src/main/java/common/dispenser/DispenserPos.java b/common/src/main/java/common/dispenser/DispenserPos.java deleted file mode 100755 index d3e5f5f..0000000 --- a/common/src/main/java/common/dispenser/DispenserPos.java +++ /dev/null @@ -1,4 +0,0 @@ -package common.dispenser; - -public record DispenserPos(double getX, double getY, double getZ) implements IPosition { -} diff --git a/common/src/main/java/common/dispenser/DispenserSource.java b/common/src/main/java/common/dispenser/DispenserSource.java deleted file mode 100755 index 2709dba..0000000 --- a/common/src/main/java/common/dispenser/DispenserSource.java +++ /dev/null @@ -1,29 +0,0 @@ -package common.dispenser; - -import common.tileentity.TileEntity; -import common.util.BlockPos; -import common.world.State; -import common.world.World; - -public record DispenserSource(World getWorld, BlockPos getBlockPos) implements IBlockSource { - public double getX() { - return (double)this.getBlockPos.getX() + 0.5D; - } - - public double getY() { - return (double)this.getBlockPos.getY() + 0.5D; - } - - public double getZ() { - return (double)this.getBlockPos.getZ() + 0.5D; - } - - public int getBlockMetadata() { - State state = this.getWorld.getState(this.getBlockPos); - return state.getBlock().getMetaFromState(state); - } - - public T getBlockTileEntity() { - return (T)this.getWorld.getTileEntity(this.getBlockPos); - } -} diff --git a/common/src/main/java/common/enchantment/Enchantment.java b/common/src/main/java/common/enchantment/Enchantment.java deleted file mode 100755 index 90d69ef..0000000 --- a/common/src/main/java/common/enchantment/Enchantment.java +++ /dev/null @@ -1,650 +0,0 @@ -package common.enchantment; - -import java.util.Map; -import common.collect.Maps; -import common.entity.DamageSource; -import common.entity.Entity; -import common.entity.types.EntityLiving; -import common.item.ItemArmor; -import common.item.ItemAxe; -import common.item.ItemShears; -import common.item.ItemStack; -import common.rng.Random; -import common.util.Displayable; -import common.util.ExtMath; -import common.util.Identifyable; -import common.vars.Vars; - -public enum Enchantment implements Displayable, Identifyable -{ - PROTECTION("protection", 10, EnchantmentType.ARMOR, "Schutz") { - public int getMinEnchantability(int enchantmentLevel) - { - return 1 + (enchantmentLevel - 1) * 11; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 20; - } - - public int getMaxLevel() - { - return 4; - } - - public int calcDamageReduction(int level, DamageSource source) - { - if (source == DamageSource.outOfWorld) - { - return 0; - } - else - { - float f = (float)(6 + level * level) / 3.0F; - return ExtMath.floorf(f * 0.75F); - } - } - }, - FIRE_PROTECTION("fire_protection", 5, EnchantmentType.ARMOR, "Feuerschutz") { - public int getMinEnchantability(int enchantmentLevel) - { - return 10 + (enchantmentLevel - 1) * 8; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 12; - } - - public int getMaxLevel() - { - return 4; - } - - public int calcDamageReduction(int level, DamageSource source) - { - if (source == DamageSource.outOfWorld) - { - return 0; - } - else - { - float f = (float)(6 + level * level) / 3.0F; - return source.isFireDamage() ? ExtMath.floorf(f * 1.25F) : 0; - } - } - }, - FEATHER_FALLING("feather_falling", 5, EnchantmentType.ARMOR_FEET, "Federfall") { - public int getMinEnchantability(int enchantmentLevel) - { - return 5 + (enchantmentLevel - 1) * 6; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 10; - } - - public int getMaxLevel() - { - return 4; - } - - public int calcDamageReduction(int level, DamageSource source) - { - if (source == DamageSource.outOfWorld) - { - return 0; - } - else - { - float f = (float)(6 + level * level) / 3.0F; - return source == DamageSource.fall ? ExtMath.floorf(f * 2.5F) : 0; - } - } - }, - BLAST_PROTECTION("blast_protection", 2, EnchantmentType.ARMOR, "Explosionsschutz") { - public int getMinEnchantability(int enchantmentLevel) - { - return 5 + (enchantmentLevel - 1) * 8; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 12; - } - - public int getMaxLevel() - { - return 4; - } - - public int calcDamageReduction(int level, DamageSource source) - { - if (source == DamageSource.outOfWorld) - { - return 0; - } - else - { - float f = (float)(6 + level * level) / 3.0F; - return source.isExplosion() ? ExtMath.floorf(f * 1.5F) : 0; - } - } - }, - PROJECTILE_PROTECTION("projectile_protection", 5, EnchantmentType.ARMOR, "Schusssicher") { - public int getMinEnchantability(int enchantmentLevel) - { - return 3 + (enchantmentLevel - 1) * 6; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 15; - } - - public int getMaxLevel() - { - return 4; - } - - public int calcDamageReduction(int level, DamageSource source) - { - if (source == DamageSource.outOfWorld) - { - return 0; - } - else - { - float f = (float)(6 + level * level) / 3.0F; - return source.isProjectile() ? ExtMath.floorf(f * 1.5F) : 0; - } - } - }, - THORNS("thorns", 1, EnchantmentType.ARMOR_TORSO, "Dornen") { - public int getMinEnchantability(int enchantmentLevel) - { - return 10 + 20 * (enchantmentLevel - 1); - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - public int getMaxLevel() - { - return 3; - } - - public boolean canApply(ItemStack stack) - { - return stack.getItem() instanceof ItemArmor ? true : super.canApply(stack); - } - - public void onUserHurt(EntityLiving user, Entity attacker, int level) - { - Random random = user.getRNG(); - ItemStack itemstack = EnchantmentHelper.getEnchantedItem(Enchantment.THORNS, user); - - if ((user.worldObj.client || Vars.damageThorns) && isThornsHurting(level, random)) - { - if (attacker != null) - { - attacker.attackEntityFrom(DamageSource.causeThornsDamage(user), getThornsDamage(level, random)); -// attacker.playSound("damage.thorns", 0.5F, 1.0F); - } - - if (itemstack != null) - { - itemstack.damageItem(3, user); - } - } - else if (itemstack != null) - { - itemstack.damageItem(1, user); - } - } - }, - SHARPNESS("sharpness", 10, EnchantmentType.WEAPON, "Schärfe") { - public int getMinEnchantability(int enchantmentLevel) - { - return 1 + (enchantmentLevel - 1) * 11; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 20; - } - - public int getMaxLevel() - { - return 5; - } - - public int calcAdditionalDamage(int level) - { - return (int)(/*this.damageType == 0 ? */ (float)level * 1.25F); // : (this.damageType == 1 && creatureType == CreatureType.UNDEAD ? (float)level * 2.5F : (this.damageType == 2 && creatureType == CreatureType.ARTHROPOD ? (float)level * 2.5F : 0.0F))); - } - - public boolean canApply(ItemStack stack) - { - return stack.getItem() instanceof ItemAxe ? true : super.canApply(stack); - } - -// /** -// * Called whenever a mob is damaged with an item that has this enchantment on it. -// */ -// public void onEntityDamaged(EntityLivingBase user, Entity target, int level) -// { -// if (target instanceof EntityLivingBase) -// { -// EntityLivingBase entitylivingbase = (EntityLivingBase)target; - // -// if (this.damageType == 2 && entitylivingbase.getCreatureType() == CreatureType.ARTHROPOD) -// { -// int i = 20 + user.getRNG().zrange(10 * level); -// entitylivingbase.addEffect(new PotionEffect(Potion.moveSlowdown.id, i, 3)); -// } -// } -// } - }, - KNOCKBACK("knockback", 5, EnchantmentType.WEAPON, "Rückstoß") { - public int getMinEnchantability(int enchantmentLevel) - { - return 5 + 20 * (enchantmentLevel - 1); - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - public int getMaxLevel() - { - return 2; - } - }, - FIRE_ASPECT("fire_aspect", 2, EnchantmentType.WEAPON, "Verbrennung") { - public int getMinEnchantability(int enchantmentLevel) - { - return 10 + 20 * (enchantmentLevel - 1); - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - public int getMaxLevel() - { - return 2; - } - }, - LOOTING("looting", 2, EnchantmentType.WEAPON, "Plünderung") { - public int getMinEnchantability(int enchantmentLevel) - { - return 15 + (enchantmentLevel - 1) * 9; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - public int getMaxLevel() - { - return 3; - } - }, - EFFICIENCY("efficiency", 10, EnchantmentType.DIGGER, "Effizienz") { - public int getMinEnchantability(int enchantmentLevel) - { - return 1 + 10 * (enchantmentLevel - 1); - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - public int getMaxLevel() - { - return 5; - } - - public boolean canApply(ItemStack stack) - { - return stack.getItem() instanceof ItemShears ? true : super.canApply(stack); - } - }, - SILK_TOUCH("silk_touch", 1, EnchantmentType.DIGGER, "Behutsamkeit") { - public int getMinEnchantability(int enchantmentLevel) - { - return 15; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - public int getMaxLevel() - { - return 1; - } - - public boolean canApplyTogether(Enchantment ench) - { - return super.canApplyTogether(ench) && ench != FORTUNE; - } - - public boolean canApply(ItemStack stack) - { - return stack.getItem() instanceof ItemShears ? true : super.canApply(stack); - } - }, - UNBREAKING("unbreaking", 5, EnchantmentType.BREAKABLE, "Haltbarkeit") { - public int getMinEnchantability(int enchantmentLevel) - { - return 5 + (enchantmentLevel - 1) * 8; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - public int getMaxLevel() - { - return 3; - } - - public boolean canApply(ItemStack stack) - { - return stack.isItemStackDamageable() ? true : super.canApply(stack); - } - }, - FORTUNE("fortune", 2, EnchantmentType.DIGGER, "Glück") { - public int getMinEnchantability(int enchantmentLevel) - { - return 15 + (enchantmentLevel - 1) * 9; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - public int getMaxLevel() - { - return 3; - } - - public boolean canApplyTogether(Enchantment ench) - { - return super.canApplyTogether(ench) && ench != SILK_TOUCH; - } - }, - POWER("power", 10, EnchantmentType.BOW, "Stärke") { - public int getMinEnchantability(int enchantmentLevel) - { - return 1 + (enchantmentLevel - 1) * 10; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 15; - } - - public int getMaxLevel() - { - return 5; - } - }, - PUNCH("punch", 2, EnchantmentType.BOW, "Schlag") { - public int getMinEnchantability(int enchantmentLevel) - { - return 12 + (enchantmentLevel - 1) * 20; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 25; - } - - public int getMaxLevel() - { - return 2; - } - }, - FLAME("flame", 2, EnchantmentType.BOW, "Flamme") { - public int getMinEnchantability(int enchantmentLevel) - { - return 20; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return 50; - } - - public int getMaxLevel() - { - return 1; - } - }, - INFINITY("infinity", 1, EnchantmentType.BOW, "Unendlich") { - public int getMinEnchantability(int enchantmentLevel) - { - return 20; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return 50; - } - - public int getMaxLevel() - { - return 1; - } - }, - LUCK_OF_THE_SEA("luck_of_the_sea", 2, EnchantmentType.FISHING_ROD, "Glück des Meeres") { - public int getMinEnchantability(int enchantmentLevel) - { - return 15 + (enchantmentLevel - 1) * 9; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - public int getMaxLevel() - { - return 3; - } - }, - LURE("lure", 2, EnchantmentType.FISHING_ROD, "Köder") { - public int getMinEnchantability(int enchantmentLevel) - { - return 15 + (enchantmentLevel - 1) * 9; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - public int getMaxLevel() - { - return 3; - } - }, - DRAINING("draining", 1, EnchantmentType.WEAPON, "Seelenentzug") { - public int getMinEnchantability(int enchantmentLevel) { - return 2 + (enchantmentLevel - 1) * 11; - } - - public int getMaxEnchantability(int enchantmentLevel) { - return this.getMinEnchantability(enchantmentLevel) + 20; - } - - public int getMaxLevel() { - return 16; - } - - public boolean canApply(ItemStack stack) { - return stack.getItem() instanceof ItemAxe ? true : super.canApply(stack); - } - - public void onEntityDamaged(EntityLiving user, Entity target, int level) { - if(target instanceof EntityLiving) { - EntityLiving entity = (EntityLiving)target; - entity.attackEntityFrom(DamageSource.causeIndirectMagicDamage(user, user), (int)((float)level * 1.25F)); - user.heal((int)((entity.arePotionsInverted() ? 0.2f : 1.0f) * (float)level)); - } - } - }; - - private static final String[] LEVELS = new String[] {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"}; - private static final Map LOOKUP = Maps.newHashMap(); - - private final String name; - private final int weight; - private final EnchantmentType type; - private final String display; - - static { - for(Enchantment ench : values()) { - if(LOOKUP.containsKey(ench.name)) - throw new IllegalArgumentException("Verzauberung " + ench.name + " ist bereits registriert"); - LOOKUP.put(ench.name, ench); - } - } - - public static Enchantment getEnchantment(String name) - { - return LOOKUP.get(name); - } - - private Enchantment(String name, int weight, EnchantmentType type, String display) - { - this.name = name; - this.weight = weight; - this.type = type; - this.display = display; - } - - public int getWeight() - { - return this.weight; - } - - public int getMinLevel() - { - return 1; - } - - public int getMaxLevel() - { - return 1; - } - - public int getMinEnchantability(int enchantmentLevel) - { - return 1 + enchantmentLevel * 10; - } - - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 5; - } - - public int calcDamageReduction(int level, DamageSource source) - { - return 0; - } - - public int calcAdditionalDamage(int level) - { - return 0; - } - - public boolean canApplyTogether(Enchantment ench) - { - return this != ench; - } - - public final String getName() { - return this.name; - } - - public String getDisplay() - { - return this.display; - } - - public EnchantmentType getType() { - return this.type; - } - - public String getFormattedName(int level) - { - return this.getDisplay() + " " + ((level >= 1 && level <= LEVELS.length) ? LEVELS[level - 1] : "" + level); - } - - public boolean canApply(ItemStack stack) - { - return this.type.canEnchantItem(stack.getItem()); - } - - public void onEntityDamaged(EntityLiving user, Entity target, int level) - { - } - - public void onUserHurt(EntityLiving user, Entity attacker, int level) - { - } - - public static int getFireTimeForEntity(Entity entity, int duration) - { - int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.FIRE_PROTECTION, entity.getInventory()); - - if (i > 0) - { - duration -= ExtMath.floorf((float)duration * (float)i * 0.15F); - } - - return duration; - } - - public static double getKnockbackFactor(Entity entity, double strength) - { - int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.BLAST_PROTECTION, entity.getInventory()); - - if (i > 0) - { - strength -= (double)ExtMath.floord(strength * (double)((float)i * 0.15F)); - } - - return strength; - } - - public static boolean negateDamage(ItemStack stack, int level, Random rand) - { - return stack.getItem() instanceof ItemArmor && rand.floatv() < 0.6F ? false : rand.rarity(level + 1); - } - - public static boolean isThornsHurting(int level, Random rand) - { - return level <= 0 ? false : rand.floatv() < 0.15F * (float)level; - } - - public static int getThornsDamage(int level, Random rand) - { - return level > 10 ? level - 10 : rand.roll(4); - } -} diff --git a/common/src/main/java/common/enchantment/EnchantmentType.java b/common/src/main/java/common/enchantment/EnchantmentType.java deleted file mode 100755 index 22ea489..0000000 --- a/common/src/main/java/common/enchantment/EnchantmentType.java +++ /dev/null @@ -1,52 +0,0 @@ -package common.enchantment; - -import common.attributes.UsageSlot; -import common.item.Item; -import common.item.ItemArmor; -import common.item.ItemBow; -import common.item.ItemFishingRod; -import common.item.ItemSword; -import common.item.ItemTool; - -public enum EnchantmentType -{ - ALL, - ARMOR, - ARMOR_FEET, - ARMOR_LEGS, - ARMOR_TORSO, - ARMOR_HEAD, - WEAPON, - DIGGER, - FISHING_ROD, - BREAKABLE, - BOW; - - public boolean canEnchantItem(Item item) - { - if (this == ALL) - { - return true; - } - else if (this == BREAKABLE && item.isDamageable()) - { - return true; - } - else if (item instanceof ItemArmor) - { - if (this == ARMOR) - { - return true; - } - else - { - ItemArmor armor = (ItemArmor)item; - return armor.armorType == UsageSlot.HEAD ? this == ARMOR_HEAD : (armor.armorType == UsageSlot.LEGS ? this == ARMOR_LEGS : (armor.armorType == UsageSlot.BODY ? this == ARMOR_TORSO : (armor.armorType == UsageSlot.FEET ? this == ARMOR_FEET : false))); - } - } - else - { - return item instanceof ItemSword ? this == WEAPON : (item instanceof ItemTool ? this == DIGGER : (item instanceof ItemBow ? this == BOW : (item instanceof ItemFishingRod ? this == FISHING_ROD : false))); - } - } -} diff --git a/common/src/main/java/common/enchantment/RngEnchantment.java b/common/src/main/java/common/enchantment/RngEnchantment.java deleted file mode 100755 index d2ba1ad..0000000 --- a/common/src/main/java/common/enchantment/RngEnchantment.java +++ /dev/null @@ -1,14 +0,0 @@ -package common.enchantment; - -import common.rng.RngItem; - -public class RngEnchantment extends RngItem { - public final Enchantment enchantment; - public final int level; - - public RngEnchantment(Enchantment enchantment, int level) { - super(enchantment.getWeight()); - this.enchantment = enchantment; - this.level = level; - } -} diff --git a/common/src/main/java/common/entity/animal/EntityChicken.java b/common/src/main/java/common/entity/animal/EntityChicken.java deleted file mode 100755 index eeae971..0000000 --- a/common/src/main/java/common/entity/animal/EntityChicken.java +++ /dev/null @@ -1,209 +0,0 @@ -package common.entity.animal; - -import common.ai.EntityAIAttackOnCollide; -import common.ai.EntityAIFollowParent; -import common.ai.EntityAILookIdle; -import common.ai.EntityAIMate; -import common.ai.EntityAINearestAttackableTarget; -import common.ai.EntityAIPanic; -import common.ai.EntityAISwimming; -import common.ai.EntityAITempt; -import common.ai.EntityAIWander; -import common.ai.EntityAIWatchClosest; -import common.entity.DamageSource; -import common.entity.Entity; -import common.entity.npc.Alignment; -import common.entity.npc.EntityNPC; -import common.entity.types.EntityAnimal; -import common.entity.types.EntityLiving; -import common.init.Items; -import common.init.SoundEvent; -import common.item.Item; -import common.item.ItemStack; -import common.tags.TagObject; -import common.util.ExtMath; -import common.vars.Vars; -import common.world.World; - -public class EntityChicken extends EntityAnimal { - private final EntityAIAttackOnCollide attack = new EntityAIAttackOnCollide(this, EntityNPC.class, 1.4, false); - private final EntityAINearestAttackableTarget targetter = new EntityAINearestAttackableTarget(this, EntityNPC.class, true); - - public float wingRotation; - public float lastWingRotation; - public float destPos; - public float lastDestPos; - private float wingRotDelta = 1.0F; - private int eggTimer; - private boolean noEggs; - private boolean attackSet; - - public EntityChicken(World world) { - super(world); - this.setSize(0.4F, 0.7F); - this.eggTimer = world.client || Vars.eggTimer <= 0 ? 1000 : this.rand.excl(Vars.eggTimer, Vars.eggTimer * 2); - this.tasks.addTask(0, new EntityAISwimming(this)); - this.tasks.addTask(1, new EntityAIPanic(this, 1.4D)); - this.tasks.addTask(2, new EntityAIMate(this, 1.0D)); - this.tasks.addTask(3, new EntityAITempt(this, 1.0D, Items.wheat, false)); - this.tasks.addTask(4, new EntityAIFollowParent(this, 1.1D)); - this.tasks.addTask(5, new EntityAIWander(this, 1.0D)); - this.tasks.addTask(6, new EntityAIWatchClosest(this, null, 6.0F)); - this.tasks.addTask(7, new EntityAILookIdle(this)); - } - - public float getEyeHeight() { - return this.height; - } - - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(18, Byte.valueOf((byte)0)); - } - - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.setMaxHealth(4); - this.setSpeedBase(0.25f); - } - - public void onLivingUpdate() { - super.onLivingUpdate(); - this.lastWingRotation = this.wingRotation; - this.lastDestPos = this.destPos; - this.destPos = (float)((double)this.destPos + (double)(this.onGround ? -1 : 4) * 0.3D); - this.destPos = ExtMath.clampf(this.destPos, 0.0F, 1.0F); - if(!this.onGround && this.wingRotDelta < 1.0F) - this.wingRotDelta = 1.0F; - this.wingRotDelta = (float)((double)this.wingRotDelta * 0.9D); - if(!this.onGround && this.motionY < 0.0D) - this.motionY *= 0.6D; - this.wingRotation += this.wingRotDelta * 2.0F; - if(!this.worldObj.client) { - if(Vars.eggTimer > 0 && !this.isChild() && !this.noEggs && --this.eggTimer <= 0) { - this.playSound(SoundEvent.PLOP, 1.0F); - this.dropItem(Items.egg, 1); - this.eggTimer = this.rand.excl(Vars.eggTimer, Vars.eggTimer * 2); - } - boolean evil = this.canBeEvil(); - if(evil != this.attackSet) { - if(evil) { - this.tasks.addTask(1, this.attack); - this.targets.addTask(1, this.targetter); - } - else { - this.tasks.removeTask(this.attack); - this.targets.removeTask(this.targetter); - } - this.attackSet = evil; - } - } - } - - public void fall(float distance, float damage) { - } - - protected SoundEvent getLivingSound() { - return SoundEvent.CHICKEN_IDLE; - } - - protected SoundEvent getHurtSound() { - return SoundEvent.CHICKEN_HIT; - } - - protected SoundEvent getDeathSound() { - return SoundEvent.CHICKEN_HIT; - } - - protected Item getDropItem() { - return Items.feather; - } - - protected void dropFewItems(boolean hit, int looting) { - int amt = this.rand.zrange(3) + this.rand.zrange(1 + looting); - for(int z = 0; z < amt; z++) { - this.dropItem(Items.feather, 1); - } - this.dropItem(this.isBurning() ? Items.cooked_chicken : Items.chicken, 1); - } - - public EntityChicken createChild(EntityLiving entity) { - EntityChicken chick = new EntityChicken(this.worldObj); - chick.setEvil(this.isEvil()); - chick.setNotLaying(this.isNotLaying()); - return chick; - } - - public boolean isBreedingItem(ItemStack stack) { - return stack != null && stack.getItem() == Items.wheat; - } - - public void readEntity(TagObject tag) { - super.readEntity(tag); - this.setEvil(tag.getBool("evil")); - this.noEggs = tag.getBool("noEggs"); - this.eggTimer = tag.getInt("eggTime"); - } - - public void writeEntity(TagObject tag) { - super.writeEntity(tag); - tag.setBool("evil", this.isEvil()); - tag.setBool("noEggs", this.noEggs); - tag.setInt("eggTime", this.eggTimer); - } - - public void updateRiderPosition() { - super.updateRiderPosition(); - float x = ExtMath.sin(this.yawOffset * (float)Math.PI / 180.0F); - float z = ExtMath.cos(this.yawOffset * (float)Math.PI / 180.0F); - float mult = 0.1F; - float off = 0.0F; - this.passenger.setPosition(this.posX + (double)(mult * x), - this.posY + (double)(this.height * 0.5F) + this.passenger.getYOffset() + (double)off, this.posZ - (double)(mult * z)); - if(this.passenger instanceof EntityLiving) - ((EntityLiving)this.passenger).yawOffset = this.yawOffset; - } - - public boolean attackEntityAsMob(Entity entityIn) { - if(!this.worldObj.client && !Vars.damageMobs) - return false; - return entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), this.isChild() ? 1 : 2); - } - - public Object onInitialSpawn(Object livingdata) { - livingdata = super.onInitialSpawn(livingdata); - if(Vars.evilChickenChance > 0 && this.rand.chance(Vars.evilChickenChance)) - this.setEvil(true); - if(this.rand.chance(15)) - this.setGrowingAge(-24000); - return livingdata; - } - - protected boolean canBeEvil() { - return this.isEvil() || Vars.aggressiveChickens; - } - - public boolean isEvil() { - return this.dataWatcher.getWatchableObjectByte(18) != 0; - } - - public void setEvil(boolean evil) { - this.dataWatcher.updateObject(18, (byte)(evil ? 1 : 0)); - } - - public boolean isNotLaying() { - return this.noEggs; - } - - public void setNotLaying(boolean noEggs) { - this.noEggs = noEggs; - } - - public int getColor() { - return 0xdb5152; - } - - public Alignment getAlignment() { - return this.isEvil() ? Alignment.CHAOTIC_EVIL : Alignment.CHAOTIC; - } -} diff --git a/common/src/main/java/common/entity/animal/EntityFox.java b/common/src/main/java/common/entity/animal/EntityFox.java deleted file mode 100644 index 568bf97..0000000 --- a/common/src/main/java/common/entity/animal/EntityFox.java +++ /dev/null @@ -1,111 +0,0 @@ -package common.entity.animal; - -import common.ai.EntityAIAttackOnCollide; -import common.ai.EntityAIHurtByTarget; -import common.ai.EntityAILeapAtTarget; -import common.ai.EntityAILookIdle; -import common.ai.EntityAIMate; -import common.ai.EntityAINearestAttackableTarget; -import common.ai.EntityAISwimming; -import common.ai.EntityAIWander; -import common.ai.EntityAIWatchClosest; -import common.entity.DamageSource; -import common.entity.Entity; -import common.entity.npc.Alignment; -import common.entity.types.EntityAnimal; -import common.entity.types.EntityLiving; -import common.init.Items; -import common.init.SoundEvent; -import common.item.Item; -import common.item.ItemStack; -import common.pathfinding.PathNavigateGround; -import common.vars.Vars; -import common.world.World; - -public class EntityFox extends EntityAnimal -{ - public EntityFox(World worldIn) - { - super(worldIn); - this.setSize(0.6F, 0.8F); - ((PathNavigateGround)this.getNavigator()).setAvoidsWater(true); - this.tasks.addTask(1, new EntityAISwimming(this)); - this.tasks.addTask(3, new EntityAILeapAtTarget(this, 0.4F)); - this.tasks.addTask(4, new EntityAIAttackOnCollide(this, 1.0D, true)); - this.tasks.addTask(6, new EntityAIMate(this, 1.0D)); - this.tasks.addTask(7, new EntityAIWander(this, 1.0D)); - this.tasks.addTask(9, new EntityAIWatchClosest(this, null, 8.0F)); - this.tasks.addTask(9, new EntityAILookIdle(this)); - this.targets.addTask(3, new EntityAIHurtByTarget(this, true)); - this.targets.addTask(5, new EntityAINearestAttackableTarget(this, EntityChicken.class, true)); - } - - protected void applyEntityAttributes() - { - super.applyEntityAttributes(); - this.setSpeedBase(0.35f); - this.setMaxHealth(6); - } - - protected SoundEvent getHurtSound() - { - return SoundEvent.FOX_HURT; - } - - protected SoundEvent getDeathSound() - { - return SoundEvent.FOX_DEATH; - } - - protected float getSoundVolume() - { - return 0.4F; - } - - protected Item getDropItem() - { - return null; - } - - public float getEyeHeight() - { - return this.height * 0.8F; - } - - public boolean attackEntityAsMob(Entity entityIn) - { - if(!this.worldObj.client && !Vars.damageMobs) - return false; - boolean flag = entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), 2); - - if (flag) - { - this.applyEnchantments(this, entityIn); - } - - return flag; - } - - public boolean isBreedingItem(ItemStack stack) - { - return stack != null && stack.getItem() == Items.apple; - } - - public int getMaxChunkSpawns() - { - return 6; - } - - public EntityFox createChild(EntityLiving ageable) - { - return new EntityFox(this.worldObj); - } - - public int getColor() { - return 0xc35d00; - } - - public Alignment getAlignment() { - return Alignment.CHAOTIC; - } -} diff --git a/common/src/main/java/common/entity/npc/PlayerCharacter.java b/common/src/main/java/common/entity/npc/PlayerCharacter.java deleted file mode 100644 index 89874f4..0000000 --- a/common/src/main/java/common/entity/npc/PlayerCharacter.java +++ /dev/null @@ -1,6 +0,0 @@ -package common.entity.npc; - -import common.util.BlockPos; - -public record PlayerCharacter(String name, String info, Alignment align, String dim, BlockPos pos, String type, int level) { -} diff --git a/common/src/main/java/common/entity/projectile/EntityBullet.java b/common/src/main/java/common/entity/projectile/EntityBullet.java deleted file mode 100755 index b471f48..0000000 --- a/common/src/main/java/common/entity/projectile/EntityBullet.java +++ /dev/null @@ -1,289 +0,0 @@ -package common.entity.projectile; - -import java.util.List; - -import common.enchantment.EnchantmentHelper; -import common.entity.DamageSource; -import common.entity.Entity; -import common.entity.EntityType; -import common.entity.types.EntityLiving; -import common.entity.types.IObjectData; -import common.entity.types.IProjectile; -import common.init.SoundEvent; -import common.tags.TagObject; -import common.util.BoundingBox; -import common.util.ExtMath; -import common.util.HitPosition; -import common.util.Vec3; -import common.vars.Vars; -import common.world.State; -import common.world.World; - -public class EntityBullet extends Entity implements IProjectile, IObjectData { - private Entity shooter; - private int ticksMoved; - private int age; - private int damage = 5; - - public EntityBullet(World world) { - super(world); - this.renderDistWeight = 10.0D; - this.setSize(0.5F, 0.5F); - } - - public EntityBullet(World world, double x, double y, double z) { - super(world); - this.renderDistWeight = 10.0D; - this.setSize(0.5F, 0.5F); - this.setPosition(x, y, z); - } - - public EntityBullet(World world, double x, double y, double z, int data) { - this(world, x, y, z); - Entity entity = world.getEntityByID(data); - if(entity instanceof EntityLiving) - this.shooter = entity; - } - - public EntityBullet(World world, EntityLiving shooter, EntityLiving target, float velocity, float innacuracy) { - super(world); - this.renderDistWeight = 10.0D; - this.shooter = shooter; - this.posY = shooter.posY + (double)shooter.getEyeHeight() - 0.10000000149011612D; - double xd = target.posX - shooter.posX; - double yd = target.getEntityBoundingBox().minY + (double)(target.height * 0.7f) - this.posY; - double zd = target.posZ - shooter.posZ; - double xzd = (double)ExtMath.sqrtd(xd * xd + zd * zd); - if(xzd >= 1.0E-7D) { - float yaw = (float)(ExtMath.atan2(zd, xd) * 180.0D / Math.PI) - 90.0F; - float pitch = (float)(-(ExtMath.atan2(yd, xzd) * 180.0D / Math.PI)); - double x = xd / xzd; - double z = zd / xzd; - this.setLocationAndAngles(shooter.posX + x, this.posY, shooter.posZ + z, yaw, pitch); - this.setThrowableHeading(xd, yd, zd, velocity, innacuracy); - } - } - - public EntityBullet(World world, EntityLiving shooter, float velocity) { - super(world); - this.renderDistWeight = 10.0D; - this.shooter = shooter; - this.setSize(0.5F, 0.5F); - this.setLocationAndAngles(shooter.posX, shooter.posY + (double)shooter.getEyeHeight(), shooter.posZ, shooter.rotYaw, shooter.rotPitch); - this.posX -= (double)(ExtMath.cos(this.rotYaw / 180.0F * (float)Math.PI) * 0.16F); - this.posY -= 0.10000000149011612D; - this.posZ -= (double)(ExtMath.sin(this.rotYaw / 180.0F * (float)Math.PI) * 0.16F); - this.setPosition(this.posX, this.posY, this.posZ); - this.motionX = (double)(-ExtMath.sin(this.rotYaw / 180.0F * (float)Math.PI) * ExtMath.cos(this.rotPitch / 180.0F * (float)Math.PI)); - this.motionZ = (double)(ExtMath.cos(this.rotYaw / 180.0F * (float)Math.PI) * ExtMath.cos(this.rotPitch / 180.0F * (float)Math.PI)); - this.motionY = (double)(-ExtMath.sin(this.rotPitch / 180.0F * (float)Math.PI)); - this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, velocity, 0.5F); - } - - protected void entityInit() { - } - - public void setThrowableHeading(double x, double y, double z, float velocity, float inaccuracy) { - float sq = ExtMath.sqrtd(x * x + y * y + z * z); - x = x / (double)sq; - y = y / (double)sq; - z = z / (double)sq; - x = x + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; - y = y + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; - z = z + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; - x = x * (double)velocity; - y = y * (double)velocity; - z = z * (double)velocity; - this.motionX = x; - this.motionY = y; - this.motionZ = z; - float f1 = ExtMath.sqrtd(x * x + z * z); - this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(x, z) * 180.0D / Math.PI); - this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(y, (double)f1) * 180.0D / Math.PI); - } - - public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) { - this.setPosition(x, y, z); - this.setRotation(yaw, pitch); - } - - public void setVelocity(double x, double y, double z) { - this.motionX = x; - this.motionY = y; - this.motionZ = z; - if(this.prevPitch == 0.0F && this.prevYaw == 0.0F) { - float xz = ExtMath.sqrtd(x * x + z * z); - this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(x, z) * 180.0D / Math.PI); - this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(y, (double)xz) * 180.0D / Math.PI); - this.prevPitch = this.rotPitch; - this.prevYaw = this.rotYaw; - this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotYaw, this.rotPitch); - } - } - - public void onUpdate() { - super.onUpdate(); - - if(this.prevPitch == 0.0F && this.prevYaw == 0.0F) { - float xz = ExtMath.sqrtd(this.motionX * this.motionX + this.motionZ * this.motionZ); - this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI); - this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(this.motionY, (double)xz) * 180.0D / Math.PI); - } - - if(!this.worldObj.client && ++this.age >= 200) { - this.setDead(); - return; - } - ++this.ticksMoved; - Vec3 current = new Vec3(this.posX, this.posY, this.posZ); - Vec3 next = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); - HitPosition hit = this.worldObj.rayTraceBlocks(current, next, false, true, false); - current = new Vec3(this.posX, this.posY, this.posZ); - next = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); - - if(hit != null) { - next = new Vec3(hit.vec.xCoord, hit.vec.yCoord, hit.vec.zCoord); - } - - Entity entity = null; - List list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, - this.getEntityBoundingBox().addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D)); - double min = 0.0D; - - for(int i = 0; i < list.size(); ++i) { - Entity ent = list.get(i); - - if(ent.canBeCollidedWith() && (ent != this.shooter || this.ticksMoved >= 5)) { - float expand = 0.3F; - BoundingBox bb = ent.getEntityBoundingBox().expand((double)expand, (double)expand, (double)expand); - HitPosition entityHit = bb.calculateIntercept(current, next); - - if(entityHit != null) { - double dist = current.squareDistanceTo(entityHit.vec); - - if(dist < min || min == 0.0D) { - entity = ent; - min = dist; - } - } - } - } - - if(entity != null) { - hit = new HitPosition(entity); - } - - if(hit != null) { - if(hit.entity != null) { - float velo = ExtMath.sqrtd(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ); - int damage = ExtMath.ceild((double)velo * (double)this.damage); - - DamageSource source; - - if(this.shooter == null) { - source = DamageSource.causeShotDamage(this, this); - } - else { - source = DamageSource.causeShotDamage(this, this.shooter); - } - - if((this.worldObj.client || Vars.damageBullet) && hit.entity.attackEntityFrom(source, damage)) { - if(hit.entity instanceof EntityLiving living && this.shooter instanceof EntityLiving shooter) { - EnchantmentHelper.applyThornEnchantments(living, shooter); - EnchantmentHelper.applyArthropodEnchantments(shooter, living); - } - this.playSound(SoundEvent.METALHIT, 0.2F); - } - this.setDead(); - } - else if(!this.worldObj.client) { - State state = hit.block != null ? this.worldObj.getState(hit.block) : null; - if(state == null || state.getBlock().onShot(this.worldObj, hit.block, state, this)) { - this.playSound(SoundEvent.METALHIT, 0.5F); - this.setDead(); - } - } - } - - this.posX += this.motionX; - this.posY += this.motionY; - this.posZ += this.motionZ; - float xzMotion = ExtMath.sqrtd(this.motionX * this.motionX + this.motionZ * this.motionZ); - this.rotYaw = (float)(ExtMath.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI); - - for(this.rotPitch = (float)(ExtMath.atan2(this.motionY, (double)xzMotion) * 180.0D / Math.PI); this.rotPitch - - this.prevPitch < -180.0F; this.prevPitch -= 360.0F) { - ; - } - - while(this.rotPitch - this.prevPitch >= 180.0F) { - this.prevPitch += 360.0F; - } - - while(this.rotYaw - this.prevYaw < -180.0F) { - this.prevYaw -= 360.0F; - } - - while(this.rotYaw - this.prevYaw >= 180.0F) { - this.prevYaw += 360.0F; - } - - this.rotPitch = this.prevPitch + (this.rotPitch - this.prevPitch) * 0.2F; - this.rotYaw = this.prevYaw + (this.rotYaw - this.prevYaw) * 0.2F; - this.setPosition(this.posX, this.posY, this.posZ); - } - - public void writeEntity(TagObject tag) { - tag.setInt("damage", this.damage); - tag.setInt("age", this.age); - } - - public void readEntity(TagObject tag) { - this.damage = tag.getInt("damage"); - this.age = tag.getInt("age"); - } - - protected boolean canTriggerWalking() { - return false; - } - - public void setDamage(int damage) { - this.damage = damage; - } - - public int getDamage() { - return this.damage; - } - - public boolean canAttackWithItem() { - return false; - } - - public float getEyeHeight() { - return 0.0F; - } - - public int getTrackingRange() { - return 96; - } - - public int getUpdateFrequency() { - return 1; - } - - public boolean isSendingVeloUpdates() { - return false; - } - - public int getPacketData() { - return this.shooter != null ? this.shooter.getId() : this.getId(); - } - - public boolean hasSpawnVelocity() { - return true; - } - - public EntityType getType() { - return EntityType.PROJECTILE; - } -} diff --git a/common/src/main/java/common/entity/types/CombatEntry.java b/common/src/main/java/common/entity/types/CombatEntry.java deleted file mode 100755 index 9d9b6e7..0000000 --- a/common/src/main/java/common/entity/types/CombatEntry.java +++ /dev/null @@ -1,6 +0,0 @@ -package common.entity.types; - -import common.entity.DamageSource; - -public record CombatEntry(DamageSource source, int damage, String blockType, float fallDistance) { -} diff --git a/common/src/main/java/common/init/Blocks.java b/common/src/main/java/common/init/Blocks.java deleted file mode 100755 index 0b163e0..0000000 --- a/common/src/main/java/common/init/Blocks.java +++ /dev/null @@ -1,444 +0,0 @@ -package common.init; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Set; - -import common.block.*; -import common.block.artificial.*; -import common.block.foliage.*; -import common.block.liquid.*; -import common.block.natural.*; -import common.block.tech.*; -import common.block.tile.*; -import common.collect.Lists; -import common.collect.Sets; -import common.util.Util; - - -public abstract class Blocks { - public static final BlockDoor acacia_door = get("acacia_door"); - public static final BlockFence acacia_fence = get("acacia_fence"); - public static final BlockFenceGate acacia_fence_gate = get("acacia_fence_gate"); - public static final BlockLeaves acacia_leaves = get("acacia_leaves"); - public static final BlockLog acacia_log = get("acacia_log"); - public static final Block acacia_planks = get("acacia_planks"); - public static final BlockSapling acacia_sapling = get("acacia_sapling"); - public static final BlockSlab acacia_slab = get("acacia_slab"); - public static final BlockStairs acacia_stairs = get("acacia_stairs"); - public static final BlockStaticLiquid acid = get("acid"); - public static final BlockRailPowered activator_rail = get("activator_rail"); - public static final BlockAir air = get("air"); - public static final Block aluminium_block = get("aluminium_block"); - public static final BlockOre aluminium_ore = get("aluminium_ore"); - public static final Block antimony_block = get("antimony_block"); - public static final BlockOre antimony_ore = get("antimony_ore"); - public static final BlockAnvil anvil = get("anvil"); - public static final Block ardite_block = get("ardite_block"); - public static final BlockOre ardite_ore = get("ardite_ore"); - public static final Block arsenic_block = get("arsenic_block"); - public static final BlockOre arsenic_ore = get("arsenic_ore"); - public static final Block ash = get("ash"); - public static final BlockWorkbench assembly_unit = get("assembly_unit"); - public static final BlockBannerStanding banner = get("banner"); - public static final BlockBeacon beacon = get("beacon"); - public static final BlockBedrock bedrock = get("bedrock"); - public static final BlockDoor birch_door = get("birch_door"); - public static final BlockFence birch_fence = get("birch_fence"); - public static final BlockFenceGate birch_fence_gate = get("birch_fence_gate"); - public static final BlockLeaves birch_leaves = get("birch_leaves"); - public static final BlockLog birch_log = get("birch_log"); - public static final Block birch_planks = get("birch_planks"); - public static final BlockSapling birch_sapling = get("birch_sapling"); - public static final BlockSlab birch_slab = get("birch_slab"); - public static final BlockStairs birch_stairs = get("birch_stairs"); - public static final Block bismuth_block = get("bismuth_block"); - public static final BlockOre bismuth_ore = get("bismuth_ore"); - public static final BlockBed black_bed = get("black_bed"); - public static final Block black_brick = get("black_brick"); - public static final BlockFence black_brick_fence = get("black_brick_fence"); - public static final BlockSlab black_brick_slab = get("black_brick_slab"); - public static final BlockStairs black_brick_stairs = get("black_brick_stairs"); - public static final BlockTintedFire black_fire = get("black_fire"); - public static final Block black_metal_block = get("black_metal_block"); - public static final BlockOre black_metal_ore = get("black_metal_ore"); - public static final BlockQuartz black_quartz_block = get("black_quartz_block"); - public static final BlockOre black_quartz_ore = get("black_quartz_ore"); - public static final BlockSlab black_quartz_slab = get("black_quartz_slab"); - public static final BlockStairs black_quartz_stairs = get("black_quartz_stairs"); - public static final Block blackened_cobble = get("blackened_cobble"); - public static final BlockBlackenedDirt blackened_dirt = get("blackened_dirt"); - public static final BlockBlackenedSoil blackened_soil = get("blackened_soil"); - public static final BlockBlackenedStone blackened_stone = get("blackened_stone"); - public static final BlockDoor blackwood_door = get("blackwood_door"); - public static final BlockFence blackwood_fence = get("blackwood_fence"); - public static final BlockFenceGate blackwood_fence_gate = get("blackwood_fence_gate"); - public static final BlockLeaves blackwood_leaves = get("blackwood_leaves"); - public static final BlockLog blackwood_log = get("blackwood_log"); - public static final Block blackwood_planks = get("blackwood_planks"); - public static final BlockSapling blackwood_sapling = get("blackwood_sapling"); - public static final BlockSlab blackwood_slab = get("blackwood_slab"); - public static final BlockStairs blackwood_stairs = get("blackwood_stairs"); - public static final BlockStaticLiquid blood = get("blood"); - public static final Block blood_brick = get("blood_brick"); - public static final BlockFence blood_brick_fence = get("blood_brick_fence"); - public static final BlockSlab blood_brick_slab = get("blood_brick_slab"); - public static final BlockStairs blood_brick_stairs = get("blood_brick_stairs"); - public static final BlockBlueShroom blue_mushroom = get("blue_mushroom"); - public static final BlockBookshelf bookshelf = get("bookshelf"); - public static final BlockBrewingStand brewing_stand = get("brewing_stand"); - public static final Block brick_block = get("brick_block"); - public static final BlockSlab brick_slab = get("brick_slab"); - public static final BlockStairs brick_stairs = get("brick_stairs"); - public static final BlockMushroom brown_mushroom = get("brown_mushroom"); - public static final BlockHugeMushroom brown_mushroom_block = get("brown_mushroom_block"); - public static final BlockCactus cactus = get("cactus"); - public static final BlockCake cake = get("cake"); - public static final Block calcium_block = get("calcium_block"); - public static final BlockOre calcium_ore = get("calcium_ore"); - public static final BlockCarpet carpet = get("carpet"); - public static final BlockCarrot carrot = get("carrot"); - public static final BlockCauldron cauldron = get("cauldron"); - public static final Block cell_rock = get("cell_rock"); - public static final BlockDoor cherry_door = get("cherry_door"); - public static final BlockFence cherry_fence = get("cherry_fence"); - public static final BlockFenceGate cherry_fence_gate = get("cherry_fence_gate"); - public static final BlockLeaves cherry_leaves = get("cherry_leaves"); - public static final BlockLog cherry_log = get("cherry_log"); - public static final Block cherry_planks = get("cherry_planks"); - public static final BlockSapling cherry_sapling = get("cherry_sapling"); - public static final BlockSlab cherry_slab = get("cherry_slab"); - public static final BlockStairs cherry_stairs = get("cherry_stairs"); - public static final BlockChest chest = get("chest"); - public static final Block chrome_block = get("chrome_block"); - public static final BlockOre chrome_ore = get("chrome_ore"); - public static final Block cinnabar_block = get("cinnabar_block"); - public static final BlockOre cinnabar_ore = get("cinnabar_ore"); - public static final BlockClay clay = get("clay"); - public static final Block coal_block = get("coal_block"); - public static final BlockOre coal_ore = get("coal_ore"); - public static final Block cobalt_block = get("cobalt_block"); - public static final BlockOre cobalt_ore = get("cobalt_ore"); - public static final Block cobblestone = get("cobblestone"); - public static final BlockSlab cobblestone_slab = get("cobblestone_slab"); - public static final BlockStairs cobblestone_stairs = get("cobblestone_stairs"); - public static final BlockWall cobblestone_wall = get("cobblestone_wall"); - public static final BlockCocoa cocoa = get("cocoa"); - public static final BlockRedstoneComparator comparator = get("comparator"); - public static final BlockWorkbench construction_table = get("construction_table"); - public static final Block copper_block = get("copper_block"); - public static final BlockOre copper_ore = get("copper_ore"); - public static final BlockCore core = get("core"); - public static final BlockDoor dark_oak_door = get("dark_oak_door"); - public static final BlockFence dark_oak_fence = get("dark_oak_fence"); - public static final BlockFenceGate dark_oak_fence_gate = get("dark_oak_fence_gate"); - public static final BlockLeaves dark_oak_leaves = get("dark_oak_leaves"); - public static final BlockLog dark_oak_log = get("dark_oak_log"); - public static final Block dark_oak_planks = get("dark_oak_planks"); - public static final BlockSapling dark_oak_sapling = get("dark_oak_sapling"); - public static final BlockSlab dark_oak_slab = get("dark_oak_slab"); - public static final BlockStairs dark_oak_stairs = get("dark_oak_stairs"); - public static final BlockDaylightDetector daylight_detector = get("daylight_detector"); - public static final BlockDaylightDetector daylight_detector_inverted = get("daylight_detector_inverted"); - public static final BlockDeadBush deadbush = get("deadbush"); - public static final BlockRailDetector detector_rail = get("detector_rail"); - public static final Block diamond_block = get("diamond_block"); - public static final BlockOre diamond_ore = get("diamond_ore"); - public static final BlockDirt dirt = get("dirt"); - public static final BlockDispenser dispenser = get("dispenser"); - public static final BlockDoublePlant double_plant = get("double_plant"); - public static final BlockDragonEgg dragon_egg = get("dragon_egg"); - public static final BlockDropper dropper = get("dropper"); - public static final BlockDryLeaves dry_leaves = get("dry_leaves"); - public static final Block emerald_block = get("emerald_block"); - public static final BlockOre emerald_ore = get("emerald_ore"); - public static final BlockEnchantmentTable enchanting_table = get("enchanting_table"); - public static final BlockFarmland farmland = get("farmland"); - public static final BlockFire fire = get("fire"); - public static final BlockFloorPortal floor_portal = get("floor_portal"); - public static final Block floor_tiles = get("floor_tiles"); - public static final Block floor_tiles_black = get("floor_tiles_black"); - public static final Block floor_tiles_red = get("floor_tiles_red"); - public static final Block floor_tiles_white = get("floor_tiles_white"); - public static final BlockBaseFlower flower = get("flower"); - public static final BlockFlowerPot flower_pot = get("flower_pot"); - public static final BlockDynamicLiquid flowing_acid = get("flowing_acid"); - public static final BlockDynamicLiquid flowing_blood = get("flowing_blood"); - public static final BlockDynamicLiquid flowing_goo = get("flowing_goo"); - public static final BlockDynamicLiquid flowing_hydrogen = get("flowing_hydrogen"); - public static final BlockDynamicLiquid flowing_lava = get("flowing_lava"); - public static final BlockDynamicLiquid flowing_magma = get("flowing_magma"); - public static final BlockDynamicLiquid flowing_mercury = get("flowing_mercury"); - public static final BlockDynamicLiquid flowing_nukage = get("flowing_nukage"); - public static final BlockDynamicLiquid flowing_slime = get("flowing_slime"); - public static final BlockDynamicLiquid flowing_water = get("flowing_water"); - public static final BlockFurnace furnace = get("furnace"); - public static final BlockGlass glass = get("glass"); - public static final BlockPane glass_pane = get("glass_pane"); - public static final BlockGlowstone glowstone = get("glowstone"); - public static final Block gold_block = get("gold_block"); - public static final BlockOre gold_ore = get("gold_ore"); - public static final BlockRailPowered golden_rail = get("golden_rail"); - public static final BlockStaticLiquid goo = get("goo"); - public static final BlockGrass grass = get("grass"); - public static final BlockGravel gravel = get("gravel"); - public static final Block gyriyn_block = get("gyriyn_block"); - public static final BlockOre gyriyn_ore = get("gyriyn_ore"); - public static final BlockHardenedClay hardened_clay = get("hardened_clay"); - public static final BlockHay hay_block = get("hay_block"); - public static final BlockPressurePlateWeighted heavy_weighted_pressure_plate = get("heavy_weighted_pressure_plate"); - public static final BlockHellRock hellrock = get("hellrock"); - public static final BlockHopper hopper = get("hopper"); - public static final BlockStaticLiquid hydrogen = get("hydrogen"); - public static final BlockIce ice = get("ice"); - public static final Block iodine_block = get("iodine_block"); - public static final BlockOre iodine_ore = get("iodine_ore"); - public static final BlockPane iron_bars = get("iron_bars"); - public static final Block iron_block = get("iron_block"); - public static final BlockDoor iron_door = get("iron_door"); - public static final BlockOre iron_ore = get("iron_ore"); - public static final BlockTrapDoor iron_trapdoor = get("iron_trapdoor"); - public static final BlockJukebox jukebox = get("jukebox"); - public static final BlockDoor jungle_door = get("jungle_door"); - public static final BlockFence jungle_fence = get("jungle_fence"); - public static final BlockFenceGate jungle_fence_gate = get("jungle_fence_gate"); - public static final BlockLeaves jungle_leaves = get("jungle_leaves"); - public static final BlockLog jungle_log = get("jungle_log"); - public static final Block jungle_planks = get("jungle_planks"); - public static final BlockSapling jungle_sapling = get("jungle_sapling"); - public static final BlockSlab jungle_slab = get("jungle_slab"); - public static final BlockStairs jungle_stairs = get("jungle_stairs"); - public static final BlockLadder ladder = get("ladder"); - public static final Block lamp = get("lamp"); - public static final Block lapis_block = get("lapis_block"); - public static final BlockOre lapis_ore = get("lapis_ore"); - public static final BlockStaticLiquid lava = get("lava"); - public static final Block lead_block = get("lead_block"); - public static final BlockOre lead_ore = get("lead_ore"); - public static final BlockLever lever = get("lever"); - public static final BlockPressurePlateWeighted light_weighted_pressure_plate = get("light_weighted_pressure_plate"); - public static final BlockFurnace lit_furnace = get("lit_furnace"); - public static final BlockPumpkin lit_pumpkin = get("lit_pumpkin"); - public static final BlockRedstoneLight lit_redstone_lamp = get("lit_redstone_lamp"); - public static final BlockRedstoneOre lit_redstone_ore = get("lit_redstone_ore"); - public static final Block lithium_block = get("lithium_block"); - public static final BlockOre lithium_ore = get("lithium_ore"); - public static final BlockStaticLiquid magma = get("magma"); - public static final Block magnesium_block = get("magnesium_block"); - public static final BlockOre magnesium_ore = get("magnesium_ore"); - public static final Block manganese_block = get("manganese_block"); - public static final BlockOre manganese_ore = get("manganese_ore"); - public static final BlockDoor maple_door = get("maple_door"); - public static final BlockFence maple_fence = get("maple_fence"); - public static final BlockFenceGate maple_fence_gate = get("maple_fence_gate"); - public static final BlockLeaves maple_leaves = get("maple_leaves"); - public static final BlockLog maple_log = get("maple_log"); - public static final Block maple_planks = get("maple_planks"); - public static final BlockSapling maple_sapling = get("maple_sapling"); - public static final BlockSlab maple_slab = get("maple_slab"); - public static final BlockStairs maple_stairs = get("maple_stairs"); - public static final BlockMelon melon_block = get("melon_block"); - public static final BlockStem melon_stem = get("melon_stem"); - public static final BlockStaticLiquid mercury = get("mercury"); - public static final BlockMobSpawner mob_spawner = get("mob_spawner"); - public static final BlockTreasure moon_cheese = get("moon_cheese"); - public static final Block moon_rock = get("moon_rock"); - public static final Block mossy_cobblestone = get("mossy_cobblestone"); - public static final BlockMycelium mycelium = get("mycelium"); - public static final Block neodymium_block = get("neodymium_block"); - public static final BlockOre neodymium_ore = get("neodymium_ore"); - public static final Block neptunium_block = get("neptunium_block"); - public static final BlockOre neptunium_ore = get("neptunium_ore"); - public static final Block nichun_block = get("nichun_block"); - public static final BlockOre nichun_ore = get("nichun_ore"); - public static final Block nickel_block = get("nickel_block"); - public static final BlockOre nickel_ore = get("nickel_ore"); - public static final BlockNote noteblock = get("noteblock"); - public static final BlockStaticLiquid nukage = get("nukage"); - public static final BlockNuke nuke = get("nuke"); - public static final BlockDoor oak_door = get("oak_door"); - public static final BlockFence oak_fence = get("oak_fence"); - public static final BlockFenceGate oak_fence_gate = get("oak_fence_gate"); - public static final BlockLeaves oak_leaves = get("oak_leaves"); - public static final BlockLog oak_log = get("oak_log"); - public static final Block oak_planks = get("oak_planks"); - public static final BlockSapling oak_sapling = get("oak_sapling"); - public static final BlockSlab oak_slab = get("oak_slab"); - public static final BlockStairs oak_stairs = get("oak_stairs"); - public static final BlockObsidian obsidian = get("obsidian"); - public static final BlockPackedIce packed_ice = get("packed_ice"); - public static final Block palladium_block = get("palladium_block"); - public static final BlockOre palladium_ore = get("palladium_ore"); - public static final Block pentagram = get("pentagram"); - public static final Block phosphor_block = get("phosphor_block"); - public static final BlockOre phosphor_ore = get("phosphor_ore"); - public static final BlockPistonBase piston = get("piston"); - public static final BlockPistonMoving piston_extension = get("piston_extension"); - public static final BlockPistonHead piston_head = get("piston_head"); - public static final Block platinum_block = get("platinum_block"); - public static final BlockOre platinum_ore = get("platinum_ore"); - public static final Block plutonium_block = get("plutonium_block"); - public static final BlockOre plutonium_ore = get("plutonium_ore"); - public static final BlockPortal portal = get("portal"); - public static final BlockPortalFrame portal_frame = get("portal_frame"); - public static final Block potassium_block = get("potassium_block"); - public static final BlockOre potassium_ore = get("potassium_ore"); - public static final BlockPotato potato = get("potato"); - public static final BlockRedstoneComparator powered_comparator = get("powered_comparator"); - public static final BlockRedstoneRepeater powered_repeater = get("powered_repeater"); - public static final Block praseodymium_block = get("praseodymium_block"); - public static final BlockOre praseodymium_ore = get("praseodymium_ore"); - public static final BlockPumpkin pumpkin = get("pumpkin"); - public static final BlockStem pumpkin_stem = get("pumpkin_stem"); - public static final BlockBed purple_bed = get("purple_bed"); - public static final BlockQuartz quartz_block = get("quartz_block"); - public static final BlockOre quartz_ore = get("quartz_ore"); - public static final BlockSlab quartz_slab = get("quartz_slab"); - public static final BlockStairs quartz_stairs = get("quartz_stairs"); - public static final Block radium_block = get("radium_block"); - public static final BlockOre radium_ore = get("radium_ore"); - public static final BlockRail rail = get("rail"); - public static final BlockBed red_bed = get("red_bed"); - public static final BlockButton red_button = get("red_button"); - public static final BlockMushroom red_mushroom = get("red_mushroom"); - public static final BlockHugeMushroom red_mushroom_block = get("red_mushroom_block"); - public static final BlockRedstoneWire redstone = get("redstone"); - public static final BlockCompressedPowered redstone_block = get("redstone_block"); - public static final BlockRedstoneLight redstone_lamp = get("redstone_lamp"); - public static final BlockRedstoneOre redstone_ore = get("redstone_ore"); - public static final BlockRedstoneTorch redstone_torch = get("redstone_torch"); - public static final BlockReed reeds = get("reeds"); - public static final BlockRedstoneRepeater repeater = get("repeater"); - public static final BlockRock rock = get("rock"); - public static final Block ruby_block = get("ruby_block"); - public static final BlockOre ruby_ore = get("ruby_ore"); - public static final BlockSand sand = get("sand"); - public static final BlockSandStone sandstone = get("sandstone"); - public static final BlockSlab sandstone_slab = get("sandstone_slab"); - public static final BlockStairs sandstone_stairs = get("sandstone_stairs"); - public static final Block selenium_block = get("selenium_block"); - public static final BlockOre selenium_ore = get("selenium_ore"); - public static final BlockStandingSign sign = get("sign"); - public static final Block silicon_block = get("silicon_block"); - public static final BlockOre silicon_ore = get("silicon_ore"); - public static final Block silver_block = get("silver_block"); - public static final BlockOre silver_ore = get("silver_ore"); - public static final BlockSkull skull = get("skull"); - public static final BlockStaticLiquid slime = get("slime"); - public static final BlockSlime slime_block = get("slime_block"); - public static final BlockSnowBlock snow = get("snow"); - public static final BlockSnow snow_layer = get("snow_layer"); - public static final Block sodium_block = get("sodium_block"); - public static final BlockOre sodium_ore = get("sodium_ore"); - public static final BlockSoulFire soul_fire = get("soul_fire"); - public static final BlockSoulSand soul_sand = get("soul_sand"); - public static final BlockWart soul_wart = get("soul_wart"); - public static final Block sponge = get("sponge"); - public static final BlockDoor spruce_door = get("spruce_door"); - public static final BlockFence spruce_fence = get("spruce_fence"); - public static final BlockFenceGate spruce_fence_gate = get("spruce_fence_gate"); - public static final BlockLeaves spruce_leaves = get("spruce_leaves"); - public static final BlockLog spruce_log = get("spruce_log"); - public static final Block spruce_planks = get("spruce_planks"); - public static final BlockSapling spruce_sapling = get("spruce_sapling"); - public static final BlockSlab spruce_slab = get("spruce_slab"); - public static final BlockStairs spruce_stairs = get("spruce_stairs"); - public static final BlockStainedGlass stained_glass = get("stained_glass"); - public static final BlockStainedGlassPane stained_glass_pane = get("stained_glass_pane"); - public static final BlockColored stained_hardened_clay = get("stained_hardened_clay"); - public static final BlockPistonBase sticky_piston = get("sticky_piston"); - public static final BlockStone stone = get("stone"); - public static final BlockButton stone_button = get("stone_button"); - public static final BlockPressurePlate stone_pressure_plate = get("stone_pressure_plate"); - public static final BlockSlab stone_slab = get("stone_slab"); - public static final BlockStairs stone_stairs = get("stone_stairs"); - public static final BlockStoneBrick stonebrick = get("stonebrick"); - public static final BlockSlab stonebrick_slab = get("stonebrick_slab"); - public static final BlockStairs stonebrick_stairs = get("stonebrick_stairs"); - public static final BlockTripWire string = get("string"); - public static final Block sulfur_block = get("sulfur_block"); - public static final BlockOre sulfur_ore = get("sulfur_ore"); - public static final BlockTallGrass tallgrass = get("tallgrass"); - public static final Block thetium_block = get("thetium_block"); - public static final BlockOre thetium_ore = get("thetium_ore"); - public static final Block tian = get("tian"); - public static final BlockDoor tian_door = get("tian_door"); - public static final BlockFence tian_fence = get("tian_fence"); - public static final BlockFenceGate tian_fence_gate = get("tian_fence_gate"); - public static final BlockLeaves tian_leaves = get("tian_leaves"); - public static final BlockLog tian_log = get("tian_log"); - public static final Block tian_planks = get("tian_planks"); - public static final BlockTianReactor tian_reactor = get("tian_reactor"); - public static final BlockSapling tian_sapling = get("tian_sapling"); - public static final BlockSlab tian_slab = get("tian_slab"); - public static final BlockTianSoil tian_soil = get("tian_soil"); - public static final BlockStairs tian_stairs = get("tian_stairs"); - public static final Block tin_block = get("tin_block"); - public static final BlockOre tin_ore = get("tin_ore"); - public static final Block titanium_block = get("titanium_block"); - public static final BlockOre titanium_ore = get("titanium_ore"); - public static final BlockTNT tnt = get("tnt"); - public static final BlockTorch torch = get("torch"); - public static final BlockTrapDoor trapdoor = get("trapdoor"); - public static final BlockChest trapped_chest = get("trapped_chest"); - public static final BlockTripWireHook tripwire_hook = get("tripwire_hook"); - public static final Block tungsten_block = get("tungsten_block"); - public static final BlockOre tungsten_ore = get("tungsten_ore"); - public static final BlockRedstoneTorch unlit_redstone_torch = get("unlit_redstone_torch"); - public static final Block uranium_block = get("uranium_block"); - public static final BlockOre uranium_ore = get("uranium_ore"); - public static final Block vanadium_block = get("vanadium_block"); - public static final BlockOre vanadium_ore = get("vanadium_ore"); - public static final BlockVine vine = get("vine"); - public static final BlockBannerHanging wall_banner = get("wall_banner"); - public static final BlockWallSign wall_sign = get("wall_sign"); - public static final BlockWarpChest warp_chest = get("warp_chest"); - public static final BlockStaticLiquid water = get("water"); - public static final BlockLilyPad waterlily = get("waterlily"); - public static final BlockWeb web = get("web"); - public static final BlockCrops wheat = get("wheat"); - public static final BlockBed white_bed = get("white_bed"); - public static final BlockButton wooden_button = get("wooden_button"); - public static final BlockPressurePlate wooden_pressure_plate = get("wooden_pressure_plate"); - public static final BlockColored wool = get("wool"); - public static final BlockWorkbench workbench = get("workbench"); - public static final Block zinc_block = get("zinc_block"); - public static final BlockOre zinc_ore = get("zinc_ore"); - public static final BlockDynamicLiquid flowing_springwater = get("flowing_springwater"); - public static final BlockStaticLiquid springwater = get("springwater"); - - private static T get(String id) { - if(!BlockRegistry.REGISTRY.containsKey(id)) - throw new RuntimeException("Block " + id + " existiert nicht"); - return (T)BlockRegistry.REGISTRY.getObject(id); - } - - static { - if(Util.DEVMODE) { - Set blocks = Sets.newHashSet(BlockRegistry.REGISTRY); - for(Field field : Blocks.class.getDeclaredFields()) { - if(Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers()) && Block.class.isAssignableFrom(field.getType())) - try { - blocks.remove(field.get(null)); - } - catch(IllegalArgumentException | IllegalAccessException e) { - Util.throwUnchecked(e); - } - } - if(!blocks.isEmpty()) { - List list = Lists.newArrayList(blocks); - Collections.sort(list, Comparator.comparing(block -> BlockRegistry.getNameFromBlock(block))); - System.err.printf("\n*** -------------------------------------------------------------- ***\n\n"); - for(Block block : list) { - String name = BlockRegistry.getNameFromBlock(block); - System.err.printf("\tpublic static final %s %s = get(\"%s\");\n", block.getClass().getSimpleName(), name, name); - } - System.err.printf("\n^^^ " + Blocks.class.getCanonicalName() + ": Blockliste ist unvollständig, Bitte neuen Quellcode einfügen ^^^\n"); - System.exit(1); - } - } - } -} diff --git a/common/src/main/java/common/init/EntityInfo.java b/common/src/main/java/common/init/EntityInfo.java deleted file mode 100755 index 6ea464e..0000000 --- a/common/src/main/java/common/init/EntityInfo.java +++ /dev/null @@ -1,4 +0,0 @@ -package common.init; - -public record EntityInfo(String id, String origin, int color1, int color2) { -} diff --git a/common/src/main/java/common/init/FlammabilityRegistry.java b/common/src/main/java/common/init/FlammabilityRegistry.java deleted file mode 100755 index 0d0a632..0000000 --- a/common/src/main/java/common/init/FlammabilityRegistry.java +++ /dev/null @@ -1,51 +0,0 @@ -package common.init; - -import java.util.Map; - -import common.block.Block; -import common.collect.Maps; - -public abstract class FlammabilityRegistry { - private static final Map ENCOURAGEMENT = Maps.newIdentityHashMap(); - private static final Map FLAMMABILITY = Maps.newIdentityHashMap(); - - private static void setFlammable(Block block, int encouragement, int flammability) { - ENCOURAGEMENT.put(block, encouragement); - FLAMMABILITY.put(block, flammability); - } - - static void register() { - for(WoodType wood : WoodType.values()) { - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_planks"), 5, 20); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_slab"), 5, 20); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_stairs"), 5, 20); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_fence"), 5, 20); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_fence_gate"), 5, 20); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_log"), 5, 5); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_leaves"), 30, 60); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_sapling"), 15, 100); - } - setFlammable(Blocks.bookshelf, 30, 20); - setFlammable(Blocks.tnt, 15, 100); - setFlammable(Blocks.tallgrass, 60, 100); - setFlammable(Blocks.double_plant, 60, 100); - setFlammable(Blocks.flower, 60, 100); - setFlammable(Blocks.deadbush, 60, 100); - setFlammable(Blocks.dry_leaves, 60, 100); - setFlammable(Blocks.wool, 30, 60); - setFlammable(Blocks.vine, 15, 100); - setFlammable(Blocks.coal_block, 5, 5); - setFlammable(Blocks.hay_block, 60, 20); - setFlammable(Blocks.carpet, 60, 20); - } - - public static int getFlammability(Block block) { - Integer value = FLAMMABILITY.get(block); - return value == null ? 0 : value.intValue(); - } - - public static int getEncouragement(Block block) { - Integer value = ENCOURAGEMENT.get(block); - return value == null ? 0 : value.intValue(); - } -} diff --git a/common/src/main/java/common/init/Items.java b/common/src/main/java/common/init/Items.java deleted file mode 100755 index ecd134e..0000000 --- a/common/src/main/java/common/init/Items.java +++ /dev/null @@ -1,680 +0,0 @@ -package common.init; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import common.collect.Lists; -import common.collect.Sets; -import common.item.*; -import common.util.Util; - - -public abstract class Items { - public static final ItemDoor acacia_door = get("acacia_door"); - public static final ItemFence acacia_fence = get("acacia_fence"); - public static final ItemBlock acacia_fence_gate = get("acacia_fence_gate"); - public static final ItemLeaves acacia_leaves = get("acacia_leaves"); - public static final ItemBlock acacia_log = get("acacia_log"); - public static final ItemBlock acacia_planks = get("acacia_planks"); - public static final ItemBlock acacia_sapling = get("acacia_sapling"); - public static final ItemSlab acacia_slab = get("acacia_slab"); - public static final ItemBlock acacia_stairs = get("acacia_stairs"); - public static final ItemBucket acid_bucket = get("acid_bucket"); - public static final ItemBlock activator_rail = get("activator_rail"); - public static final Item ahrd_fragment = get("ahrd_fragment"); - public static final ItemMetalBlock aluminium_block = get("aluminium_block"); - public static final ItemMetal aluminium_ingot = get("aluminium_ingot"); - public static final ItemMetalBlock aluminium_ore = get("aluminium_ore"); - public static final ItemMetalBlock antimony_block = get("antimony_block"); - public static final ItemMetalBlock antimony_ore = get("antimony_ore"); - public static final ItemMetal antimony_powder = get("antimony_powder"); - public static final ItemAnvilBlock anvil = get("anvil"); - public static final ItemFood apple = get("apple"); - public static final ItemBlock ardite_block = get("ardite_block"); - public static final ItemArmor ardite_boots = get("ardite_boots"); - public static final ItemArmor ardite_chestplate = get("ardite_chestplate"); - public static final ItemArmor ardite_helmet = get("ardite_helmet"); - public static final ItemArmor ardite_leggings = get("ardite_leggings"); - public static final ItemBlock ardite_ore = get("ardite_ore"); - public static final ItemSword ardite_sword = get("ardite_sword"); - public static final Item arrow = get("arrow"); - public static final ItemMetalBlock arsenic_block = get("arsenic_block"); - public static final ItemMetalBlock arsenic_ore = get("arsenic_ore"); - public static final ItemMetal arsenic_powder = get("arsenic_powder"); - public static final ItemBlock ash = get("ash"); - public static final ItemBlock assembly_unit = get("assembly_unit"); - public static final ItemFood baked_potato = get("baked_potato"); - public static final ItemBanHammer banhammer = get("banhammer"); - public static final ItemBanner banner = get("banner"); - public static final ItemBlock beacon = get("beacon"); - public static final ItemBlock bedrock = get("bedrock"); - public static final ItemFood beef = get("beef"); - public static final ItemDoor birch_door = get("birch_door"); - public static final ItemFence birch_fence = get("birch_fence"); - public static final ItemBlock birch_fence_gate = get("birch_fence_gate"); - public static final ItemLeaves birch_leaves = get("birch_leaves"); - public static final ItemBlock birch_log = get("birch_log"); - public static final ItemBlock birch_planks = get("birch_planks"); - public static final ItemBlock birch_sapling = get("birch_sapling"); - public static final ItemSlab birch_slab = get("birch_slab"); - public static final ItemBlock birch_stairs = get("birch_stairs"); - public static final ItemMetalBlock bismuth_block = get("bismuth_block"); - public static final ItemMetal bismuth_ingot = get("bismuth_ingot"); - public static final ItemMetalBlock bismuth_ore = get("bismuth_ore"); - public static final ItemBed black_bed = get("black_bed"); - public static final ItemBlock black_brick = get("black_brick"); - public static final ItemFence black_brick_fence = get("black_brick_fence"); - public static final ItemSlab black_brick_slab = get("black_brick_slab"); - public static final ItemBlock black_brick_stairs = get("black_brick_stairs"); - public static final ItemMetalBlock black_metal_block = get("black_metal_block"); - public static final ItemMetal black_metal_ingot = get("black_metal_ingot"); - public static final ItemMetalBlock black_metal_ore = get("black_metal_ore"); - public static final Item black_quartz = get("black_quartz"); - public static final ItemMultiTexture black_quartz_block = get("black_quartz_block"); - public static final ItemBlock black_quartz_ore = get("black_quartz_ore"); - public static final ItemSlab black_quartz_slab = get("black_quartz_slab"); - public static final ItemBlock black_quartz_stairs = get("black_quartz_stairs"); - public static final Item blackbrick = get("blackbrick"); - public static final ItemBlock blackened_cobble = get("blackened_cobble"); - public static final ItemBlock blackened_dirt = get("blackened_dirt"); - public static final ItemBlock blackened_soil = get("blackened_soil"); - public static final ItemBlock blackened_stone = get("blackened_stone"); - public static final ItemDoor blackwood_door = get("blackwood_door"); - public static final ItemFence blackwood_fence = get("blackwood_fence"); - public static final ItemBlock blackwood_fence_gate = get("blackwood_fence_gate"); - public static final ItemLeaves blackwood_leaves = get("blackwood_leaves"); - public static final ItemBlock blackwood_log = get("blackwood_log"); - public static final ItemBlock blackwood_planks = get("blackwood_planks"); - public static final ItemBlock blackwood_sapling = get("blackwood_sapling"); - public static final ItemSlab blackwood_slab = get("blackwood_slab"); - public static final ItemBlock blackwood_stairs = get("blackwood_stairs"); - public static final Item blaze_powder = get("blaze_powder"); - public static final ItemRod blaze_rod = get("blaze_rod"); - public static final ItemBlock blood_brick = get("blood_brick"); - public static final ItemFence blood_brick_fence = get("blood_brick_fence"); - public static final ItemSlab blood_brick_slab = get("blood_brick_slab"); - public static final ItemBlock blood_brick_stairs = get("blood_brick_stairs"); - public static final ItemBucket blood_bucket = get("blood_bucket"); - public static final Item bloodbrick = get("bloodbrick"); - public static final ItemBlock blue_mushroom = get("blue_mushroom"); - public static final ItemBoat boat = get("boat"); - public static final ItemAmmo bolt = get("bolt"); - public static final ItemBoltgun boltgun = get("boltgun"); - public static final ItemStick bone = get("bone"); - public static final ItemBook book = get("book"); - public static final ItemBlock bookshelf = get("bookshelf"); - public static final ItemBow bow = get("bow"); - public static final ItemSmall bowl = get("bowl"); - public static final ItemFood bread = get("bread"); - public static final ItemSmallBlock brewing_stand = get("brewing_stand"); - public static final Item brick = get("brick"); - public static final ItemBlock brick_block = get("brick_block"); - public static final ItemSlab brick_slab = get("brick_slab"); - public static final ItemBlock brick_stairs = get("brick_stairs"); - public static final ItemBlock brown_mushroom = get("brown_mushroom"); - public static final ItemHugeMushroom brown_mushroom_block = get("brown_mushroom_block"); - public static final ItemBucket bucket = get("bucket"); - public static final ItemFlintAndSteel burning_soul = get("burning_soul"); - public static final ItemBlock cactus = get("cactus"); - public static final ItemSmallBlock cake = get("cake"); - public static final ItemMetalBlock calcium_block = get("calcium_block"); - public static final ItemMetalBlock calcium_ore = get("calcium_ore"); - public static final ItemMetal calcium_powder = get("calcium_powder"); - public static final ItemCamera camera = get("camera"); - public static final ItemCloth carpet = get("carpet"); - public static final ItemSeedFood carrot = get("carrot"); - public static final ItemCarrotOnAStick carrot_on_a_stick = get("carrot_on_a_stick"); - public static final ItemSmallBlock cauldron = get("cauldron"); - public static final ItemBlock cell_rock = get("cell_rock"); - public static final ItemMagnetic chain = get("chain"); - public static final ItemArmor chain_boots = get("chain_boots"); - public static final ItemArmor chain_chestplate = get("chain_chestplate"); - public static final ItemArmor chain_helmet = get("chain_helmet"); - public static final ItemArmor chain_leggings = get("chain_leggings"); - public static final ItemEffect charge_crystal = get("charge_crystal"); - public static final ItemChargedOrb charged_orb = get("charged_orb"); - public static final ItemDoor cherry_door = get("cherry_door"); - public static final ItemFence cherry_fence = get("cherry_fence"); - public static final ItemBlock cherry_fence_gate = get("cherry_fence_gate"); - public static final ItemLeaves cherry_leaves = get("cherry_leaves"); - public static final ItemBlock cherry_log = get("cherry_log"); - public static final ItemBlock cherry_planks = get("cherry_planks"); - public static final ItemBlock cherry_sapling = get("cherry_sapling"); - public static final ItemSlab cherry_slab = get("cherry_slab"); - public static final ItemBlock cherry_stairs = get("cherry_stairs"); - public static final ItemChest chest = get("chest"); - public static final ItemMinecart chest_minecart = get("chest_minecart"); - public static final ItemMagnet chick_magnet = get("chick_magnet"); - public static final ItemFood chicken = get("chicken"); - public static final ItemMetalBlock chrome_block = get("chrome_block"); - public static final ItemMetal chrome_ingot = get("chrome_ingot"); - public static final ItemMetalBlock chrome_ore = get("chrome_ore"); - public static final Item cinnabar = get("cinnabar"); - public static final ItemBlock cinnabar_block = get("cinnabar_block"); - public static final ItemBlock cinnabar_ore = get("cinnabar_ore"); - public static final ItemBlock clay = get("clay"); - public static final Item clay_ball = get("clay_ball"); - public static final ItemArmor cloth_boots = get("cloth_boots"); - public static final ItemArmor cloth_chestplate = get("cloth_chestplate"); - public static final ItemArmor cloth_helmet = get("cloth_helmet"); - public static final ItemArmor cloth_leggings = get("cloth_leggings"); - public static final ItemCoal coal = get("coal"); - public static final ItemBlock coal_block = get("coal_block"); - public static final ItemBlock coal_ore = get("coal_ore"); - public static final ItemMetalBlock cobalt_block = get("cobalt_block"); - public static final ItemMetal cobalt_ingot = get("cobalt_ingot"); - public static final ItemMetalBlock cobalt_ore = get("cobalt_ore"); - public static final ItemBlock cobblestone = get("cobblestone"); - public static final ItemSlab cobblestone_slab = get("cobblestone_slab"); - public static final ItemBlock cobblestone_stairs = get("cobblestone_stairs"); - public static final ItemWall cobblestone_wall = get("cobblestone_wall"); - public static final ItemSmallBlock comparator = get("comparator"); - public static final ItemBlock construction_table = get("construction_table"); - public static final ItemFood cooked_beef = get("cooked_beef"); - public static final ItemFood cooked_chicken = get("cooked_chicken"); - public static final ItemFishFood cooked_fish = get("cooked_fish"); - public static final ItemFood cooked_porkchop = get("cooked_porkchop"); - public static final ItemFood cookie = get("cookie"); - public static final ItemMetalBlock copper_block = get("copper_block"); - public static final ItemMetal copper_ingot = get("copper_ingot"); - public static final ItemMetalBlock copper_ore = get("copper_ore"); - public static final ItemBlock core = get("core"); - public static final ItemFlintAndSteel dark_lighter = get("dark_lighter"); - public static final ItemDoor dark_oak_door = get("dark_oak_door"); - public static final ItemFence dark_oak_fence = get("dark_oak_fence"); - public static final ItemBlock dark_oak_fence_gate = get("dark_oak_fence_gate"); - public static final ItemLeaves dark_oak_leaves = get("dark_oak_leaves"); - public static final ItemBlock dark_oak_log = get("dark_oak_log"); - public static final ItemBlock dark_oak_planks = get("dark_oak_planks"); - public static final ItemBlock dark_oak_sapling = get("dark_oak_sapling"); - public static final ItemSlab dark_oak_slab = get("dark_oak_slab"); - public static final ItemBlock dark_oak_stairs = get("dark_oak_stairs"); - public static final ItemBlock daylight_detector = get("daylight_detector"); - public static final ItemBlock deadbush = get("deadbush"); - public static final ItemBlock detector_rail = get("detector_rail"); - public static final Item diamond = get("diamond"); - public static final ItemAxe diamond_axe = get("diamond_axe"); - public static final ItemBlock diamond_block = get("diamond_block"); - public static final ItemArmor diamond_boots = get("diamond_boots"); - public static final ItemArmor diamond_chestplate = get("diamond_chestplate"); - public static final ItemArmor diamond_helmet = get("diamond_helmet"); - public static final ItemHoe diamond_hoe = get("diamond_hoe"); - public static final ItemHorseArmor diamond_horse_armor = get("diamond_horse_armor"); - public static final ItemArmor diamond_leggings = get("diamond_leggings"); - public static final ItemBlock diamond_ore = get("diamond_ore"); - public static final ItemPickaxe diamond_pickaxe = get("diamond_pickaxe"); - public static final ItemShears diamond_shears = get("diamond_shears"); - public static final ItemShovel diamond_shovel = get("diamond_shovel"); - public static final ItemSword diamond_sword = get("diamond_sword"); - public static final ItemDie die = get("die"); - public static final ItemMultiTexture dirt = get("dirt"); - public static final ItemDispenser dispenser = get("dispenser"); - public static final ItemDoublePlant double_plant = get("double_plant"); - public static final ItemBlock dragon_egg = get("dragon_egg"); - public static final ItemDispenser dropper = get("dropper"); - public static final ItemBlock dry_leaves = get("dry_leaves"); - public static final ItemDye dye = get("dye"); - public static final ItemDynamite dynamite = get("dynamite"); - public static final ItemEgg egg = get("egg"); - public static final Item emerald = get("emerald"); - public static final ItemBlock emerald_block = get("emerald_block"); - public static final ItemBlock emerald_ore = get("emerald_ore"); - public static final ItemEnchantedBook enchanted_book = get("enchanted_book"); - public static final ItemBlock enchanting_table = get("enchanting_table"); - public static final ItemExpBottle experience_bottle = get("experience_bottle"); - public static final ItemExterminator exterminator = get("exterminator"); - public static final ItemBlock farmland = get("farmland"); - public static final Item feather = get("feather"); - public static final Item fermented_spider_eye = get("fermented_spider_eye"); - public static final ItemFireball fire_charge = get("fire_charge"); - public static final ItemFireworkCharge firework_charge = get("firework_charge"); - public static final ItemFirework fireworks = get("fireworks"); - public static final ItemFishFood fish = get("fish"); - public static final ItemFishingRod fishing_rod = get("fishing_rod"); - public static final Item flint = get("flint"); - public static final ItemFlintAndSteel flint_and_steel = get("flint_and_steel"); - public static final ItemBlock floor_tiles = get("floor_tiles"); - public static final ItemBlock floor_tiles_black = get("floor_tiles_black"); - public static final ItemBlock floor_tiles_red = get("floor_tiles_red"); - public static final ItemBlock floor_tiles_white = get("floor_tiles_white"); - public static final ItemMultiTexture flower = get("flower"); - public static final ItemSmallBlock flower_pot = get("flower_pot"); - public static final ItemBlock furnace = get("furnace"); - public static final ItemTiny ghast_tear = get("ghast_tear"); - public static final Item ghi_fragment = get("ghi_fragment"); - public static final ItemBlock glass = get("glass"); - public static final ItemGlassBottle glass_bottle = get("glass_bottle"); - public static final ItemBlock glass_pane = get("glass_pane"); - public static final ItemBlock glowstone = get("glowstone"); - public static final Item glowstone_dust = get("glowstone_dust"); - public static final ItemAxe gold_axe = get("gold_axe"); - public static final ItemMetalBlock gold_block = get("gold_block"); - public static final ItemArmor gold_boots = get("gold_boots"); - public static final ItemArmor gold_chestplate = get("gold_chestplate"); - public static final ItemArmor gold_helmet = get("gold_helmet"); - public static final ItemHoe gold_hoe = get("gold_hoe"); - public static final ItemHorseArmor gold_horse_armor = get("gold_horse_armor"); - public static final ItemMetal gold_ingot = get("gold_ingot"); - public static final ItemArmor gold_leggings = get("gold_leggings"); - public static final ItemNugget gold_nugget = get("gold_nugget"); - public static final ItemMetalBlock gold_ore = get("gold_ore"); - public static final ItemPickaxe gold_pickaxe = get("gold_pickaxe"); - public static final ItemShears gold_shears = get("gold_shears"); - public static final ItemShovel gold_shovel = get("gold_shovel"); - public static final ItemSword gold_sword = get("gold_sword"); - public static final ItemAppleGold golden_apple = get("golden_apple"); - public static final ItemFood golden_carrot = get("golden_carrot"); - public static final ItemBlock golden_rail = get("golden_rail"); - public static final ItemBucket goo_bucket = get("goo_bucket"); - public static final ItemColored grass = get("grass"); - public static final ItemBlock gravel = get("gravel"); - public static final Item gunpowder = get("gunpowder"); - public static final ItemAxe gyriyn_axe = get("gyriyn_axe"); - public static final ItemBlock gyriyn_block = get("gyriyn_block"); - public static final ItemHoe gyriyn_hoe = get("gyriyn_hoe"); - public static final ItemBlock gyriyn_ore = get("gyriyn_ore"); - public static final ItemPickaxe gyriyn_pickaxe = get("gyriyn_pickaxe"); - public static final ItemShovel gyriyn_shovel = get("gyriyn_shovel"); - public static final ItemBlock hardened_clay = get("hardened_clay"); - public static final ItemBlock hay_block = get("hay_block"); - public static final ItemPressurePlate heavy_weighted_pressure_plate = get("heavy_weighted_pressure_plate"); - public static final ItemBlock hellrock = get("hellrock"); - public static final ItemBlock hopper = get("hopper"); - public static final ItemMinecart hopper_minecart = get("hopper_minecart"); - public static final ItemBucket hydrogen_bucket = get("hydrogen_bucket"); - public static final ItemBlock ice = get("ice"); - public static final ItemInfoWand info_wand = get("info_wand"); - public static final ItemMetalBlock iodine_block = get("iodine_block"); - public static final ItemMetalBlock iodine_ore = get("iodine_ore"); - public static final ItemMetal iodine_powder = get("iodine_powder"); - public static final ItemAxe iron_axe = get("iron_axe"); - public static final ItemBlock iron_bars = get("iron_bars"); - public static final ItemMetalBlock iron_block = get("iron_block"); - public static final ItemArmor iron_boots = get("iron_boots"); - public static final ItemArmor iron_chestplate = get("iron_chestplate"); - public static final ItemDoor iron_door = get("iron_door"); - public static final ItemArmor iron_helmet = get("iron_helmet"); - public static final ItemHoe iron_hoe = get("iron_hoe"); - public static final ItemHorseArmor iron_horse_armor = get("iron_horse_armor"); - public static final ItemMetal iron_ingot = get("iron_ingot"); - public static final ItemArmor iron_leggings = get("iron_leggings"); - public static final ItemMetalBlock iron_ore = get("iron_ore"); - public static final ItemPickaxe iron_pickaxe = get("iron_pickaxe"); - public static final ItemShears iron_shears = get("iron_shears"); - public static final ItemShovel iron_shovel = get("iron_shovel"); - public static final ItemSword iron_sword = get("iron_sword"); - public static final ItemBlock iron_trapdoor = get("iron_trapdoor"); - public static final ItemBlock jukebox = get("jukebox"); - public static final ItemDoor jungle_door = get("jungle_door"); - public static final ItemFence jungle_fence = get("jungle_fence"); - public static final ItemBlock jungle_fence_gate = get("jungle_fence_gate"); - public static final ItemLeaves jungle_leaves = get("jungle_leaves"); - public static final ItemBlock jungle_log = get("jungle_log"); - public static final ItemBlock jungle_planks = get("jungle_planks"); - public static final ItemBlock jungle_sapling = get("jungle_sapling"); - public static final ItemSlab jungle_slab = get("jungle_slab"); - public static final ItemBlock jungle_stairs = get("jungle_stairs"); - public static final ItemKey key = get("key"); - public static final ItemBlock ladder = get("ladder"); - public static final ItemBlock lamp = get("lamp"); - public static final ItemBlock lapis_block = get("lapis_block"); - public static final ItemBlock lapis_ore = get("lapis_ore"); - public static final ItemBucket lava_bucket = get("lava_bucket"); - public static final ItemLead lead = get("lead"); - public static final ItemMetalBlock lead_block = get("lead_block"); - public static final ItemMetal lead_ingot = get("lead_ingot"); - public static final ItemMetalBlock lead_ore = get("lead_ore"); - public static final Item leather = get("leather"); - public static final ItemArmor leather_boots = get("leather_boots"); - public static final ItemArmor leather_chestplate = get("leather_chestplate"); - public static final ItemArmor leather_helmet = get("leather_helmet"); - public static final ItemArmor leather_leggings = get("leather_leggings"); - public static final ItemBlock lever = get("lever"); - public static final ItemPressurePlate light_weighted_pressure_plate = get("light_weighted_pressure_plate"); - public static final ItemLightning lightning_wand = get("lightning_wand"); - public static final ItemBlock lit_furnace = get("lit_furnace"); - public static final ItemBlock lit_pumpkin = get("lit_pumpkin"); - public static final ItemMetalBlock lithium_block = get("lithium_block"); - public static final ItemMetal lithium_ingot = get("lithium_ingot"); - public static final ItemMetalBlock lithium_ore = get("lithium_ore"); - public static final ItemBucket magma_bucket = get("magma_bucket"); - public static final Item magma_cream = get("magma_cream"); - public static final ItemMetalBlock magnesium_block = get("magnesium_block"); - public static final ItemMetalBlock magnesium_ore = get("magnesium_ore"); - public static final ItemMetal magnesium_powder = get("magnesium_powder"); - public static final ItemMagnet magnet = get("magnet"); - public static final ItemMetalBlock manganese_block = get("manganese_block"); - public static final ItemMetal manganese_ingot = get("manganese_ingot"); - public static final ItemMetalBlock manganese_ore = get("manganese_ore"); - public static final ItemDoor maple_door = get("maple_door"); - public static final ItemFence maple_fence = get("maple_fence"); - public static final ItemBlock maple_fence_gate = get("maple_fence_gate"); - public static final ItemLeaves maple_leaves = get("maple_leaves"); - public static final ItemBlock maple_log = get("maple_log"); - public static final ItemBlock maple_planks = get("maple_planks"); - public static final ItemBlock maple_sapling = get("maple_sapling"); - public static final ItemSlab maple_slab = get("maple_slab"); - public static final ItemBlock maple_stairs = get("maple_stairs"); - public static final ItemFood melon = get("melon"); - public static final ItemBlock melon_block = get("melon_block"); - public static final ItemSeeds melon_stem = get("melon_stem"); - public static final ItemBucket mercury_bucket = get("mercury_bucket"); - public static final ItemBucketMilk milk_bucket = get("milk_bucket"); - public static final ItemMinecart minecart = get("minecart"); - public static final ItemBlock mob_spawner = get("mob_spawner"); - public static final ItemBlock moon_cheese = get("moon_cheese"); - public static final ItemBlock moon_rock = get("moon_rock"); - public static final ItemBlock mossy_cobblestone = get("mossy_cobblestone"); - public static final ItemSoup mushroom_stew = get("mushroom_stew"); - public static final ItemBlock mycelium = get("mycelium"); - public static final ItemNameTag name_tag = get("name_tag"); - public static final ItemSpaceNavigator navigator = get("navigator"); - public static final ItemMetalBlock neodymium_block = get("neodymium_block"); - public static final ItemMetal neodymium_ingot = get("neodymium_ingot"); - public static final ItemMetalBlock neodymium_ore = get("neodymium_ore"); - public static final ItemMetalBlock neptunium_block = get("neptunium_block"); - public static final ItemMetal neptunium_ingot = get("neptunium_ingot"); - public static final ItemMetalBlock neptunium_ore = get("neptunium_ore"); - public static final ItemAxe nichun_axe = get("nichun_axe"); - public static final ItemBlock nichun_block = get("nichun_block"); - public static final ItemArmor nichun_boots = get("nichun_boots"); - public static final ItemArmor nichun_chestplate = get("nichun_chestplate"); - public static final ItemArmor nichun_helmet = get("nichun_helmet"); - public static final ItemHoe nichun_hoe = get("nichun_hoe"); - public static final ItemArmor nichun_leggings = get("nichun_leggings"); - public static final ItemBlock nichun_ore = get("nichun_ore"); - public static final ItemPickaxe nichun_pickaxe = get("nichun_pickaxe"); - public static final ItemShovel nichun_shovel = get("nichun_shovel"); - public static final ItemSword nichun_sword = get("nichun_sword"); - public static final ItemMetalBlock nickel_block = get("nickel_block"); - public static final ItemMetal nickel_ingot = get("nickel_ingot"); - public static final ItemMetalBlock nickel_ore = get("nickel_ore"); - public static final Item nieh_fragment = get("nieh_fragment"); - public static final ItemBlock noteblock = get("noteblock"); - public static final ItemBucket nukage_bucket = get("nukage_bucket"); - public static final ItemBlock nuke = get("nuke"); - public static final ItemDoor oak_door = get("oak_door"); - public static final ItemFence oak_fence = get("oak_fence"); - public static final ItemBlock oak_fence_gate = get("oak_fence_gate"); - public static final ItemLeaves oak_leaves = get("oak_leaves"); - public static final ItemBlock oak_log = get("oak_log"); - public static final ItemBlock oak_planks = get("oak_planks"); - public static final ItemBlock oak_sapling = get("oak_sapling"); - public static final ItemSlab oak_slab = get("oak_slab"); - public static final ItemBlock oak_stairs = get("oak_stairs"); - public static final ItemBlock obsidian = get("obsidian"); - public static final ItemFragile orb = get("orb"); - public static final ItemBlock packed_ice = get("packed_ice"); - public static final ItemMetalBlock palladium_block = get("palladium_block"); - public static final ItemMetal palladium_ingot = get("palladium_ingot"); - public static final ItemMetalBlock palladium_ore = get("palladium_ore"); - public static final Item paper = get("paper"); - public static final ItemBlock pentagram = get("pentagram"); - public static final ItemMetalBlock phosphor_block = get("phosphor_block"); - public static final ItemMetalBlock phosphor_ore = get("phosphor_ore"); - public static final ItemMetal phosphor_powder = get("phosphor_powder"); - public static final ItemPiston piston = get("piston"); - public static final ItemMetalBlock platinum_block = get("platinum_block"); - public static final ItemMetal platinum_ingot = get("platinum_ingot"); - public static final ItemMetalBlock platinum_ore = get("platinum_ore"); - public static final ItemMetalBlock plutonium_block = get("plutonium_block"); - public static final ItemMetal plutonium_ingot = get("plutonium_ingot"); - public static final ItemMetalBlock plutonium_ore = get("plutonium_ore"); - public static final ItemFood poisonous_potato = get("poisonous_potato"); - public static final ItemFood porkchop = get("porkchop"); - public static final ItemBlock portal_frame = get("portal_frame"); - public static final ItemMetalBlock potassium_block = get("potassium_block"); - public static final ItemMetalBlock potassium_ore = get("potassium_ore"); - public static final ItemMetal potassium_powder = get("potassium_powder"); - public static final ItemSeedFood potato = get("potato"); - public static final ItemPotion potion = get("potion"); - public static final ItemMetalBlock praseodymium_block = get("praseodymium_block"); - public static final ItemMetal praseodymium_ingot = get("praseodymium_ingot"); - public static final ItemMetalBlock praseodymium_ore = get("praseodymium_ore"); - public static final ItemBlock pumpkin = get("pumpkin"); - public static final ItemFood pumpkin_pie = get("pumpkin_pie"); - public static final ItemSeeds pumpkin_stem = get("pumpkin_stem"); - public static final ItemBed purple_bed = get("purple_bed"); - public static final Item quartz = get("quartz"); - public static final ItemMultiTexture quartz_block = get("quartz_block"); - public static final ItemBlock quartz_ore = get("quartz_ore"); - public static final ItemSlab quartz_slab = get("quartz_slab"); - public static final ItemBlock quartz_stairs = get("quartz_stairs"); - public static final ItemMetalBlock radium_block = get("radium_block"); - public static final ItemMetal radium_ingot = get("radium_ingot"); - public static final ItemMetalBlock radium_ore = get("radium_ore"); - public static final ItemBlock rail = get("rail"); - public static final ItemRecord record_11 = get("record_11"); - public static final ItemRecord record_13 = get("record_13"); - public static final ItemRecord record_blocks = get("record_blocks"); - public static final ItemRecord record_cat = get("record_cat"); - public static final ItemRecord record_chirp = get("record_chirp"); - public static final ItemRecord record_delay = get("record_delay"); - public static final ItemRecord record_extend = get("record_extend"); - public static final ItemRecord record_far = get("record_far"); - public static final ItemRecord record_mall = get("record_mall"); - public static final ItemRecord record_mellohi = get("record_mellohi"); - public static final ItemRecord record_stal = get("record_stal"); - public static final ItemRecord record_strad = get("record_strad"); - public static final ItemRecord record_wait = get("record_wait"); - public static final ItemRecord record_ward = get("record_ward"); - public static final ItemBucket recursive_acid_bucket = get("recursive_acid_bucket"); - public static final ItemBucket recursive_blood_bucket = get("recursive_blood_bucket"); - public static final ItemBucket recursive_bucket = get("recursive_bucket"); - public static final ItemBucket recursive_goo_bucket = get("recursive_goo_bucket"); - public static final ItemBucket recursive_hydrogen_bucket = get("recursive_hydrogen_bucket"); - public static final ItemBucket recursive_lava_bucket = get("recursive_lava_bucket"); - public static final ItemBucket recursive_magma_bucket = get("recursive_magma_bucket"); - public static final ItemBucket recursive_mercury_bucket = get("recursive_mercury_bucket"); - public static final ItemBucket recursive_nukage_bucket = get("recursive_nukage_bucket"); - public static final ItemBucket recursive_slime_bucket = get("recursive_slime_bucket"); - public static final ItemBucket recursive_water_bucket = get("recursive_water_bucket"); - public static final ItemBed red_bed = get("red_bed"); - public static final ItemButton red_button = get("red_button"); - public static final ItemBlock red_mushroom = get("red_mushroom"); - public static final ItemHugeMushroom red_mushroom_block = get("red_mushroom_block"); - public static final ItemRedstone redstone = get("redstone"); - public static final ItemBlock redstone_block = get("redstone_block"); - public static final ItemBlock redstone_lamp = get("redstone_lamp"); - public static final ItemBlock redstone_ore = get("redstone_ore"); - public static final ItemBlock redstone_torch = get("redstone_torch"); - public static final ItemSmallBlock reeds = get("reeds"); - public static final ItemSmallBlock repeater = get("repeater"); - public static final ItemMultiTexture rock = get("rock"); - public static final ItemFood rotten_flesh = get("rotten_flesh"); - public static final Item ruby = get("ruby"); - public static final ItemBlock ruby_block = get("ruby_block"); - public static final ItemBlock ruby_ore = get("ruby_ore"); - public static final ItemSaddle saddle = get("saddle"); - public static final ItemMultiTexture sand = get("sand"); - public static final ItemMultiTexture sandstone = get("sandstone"); - public static final ItemSlab sandstone_slab = get("sandstone_slab"); - public static final ItemBlock sandstone_stairs = get("sandstone_stairs"); - public static final ItemMetalBlock selenium_block = get("selenium_block"); - public static final ItemMetalBlock selenium_ore = get("selenium_ore"); - public static final ItemMetal selenium_powder = get("selenium_powder"); - public static final ItemSign sign = get("sign"); - public static final ItemMetalBlock silicon_block = get("silicon_block"); - public static final ItemMetal silicon_ingot = get("silicon_ingot"); - public static final ItemMetalBlock silicon_ore = get("silicon_ore"); - public static final ItemMetalBlock silver_block = get("silver_block"); - public static final ItemMetal silver_ingot = get("silver_ingot"); - public static final ItemMetalBlock silver_ore = get("silver_ore"); - public static final ItemSmallBlock skull = get("skull"); - public static final Item slime_ball = get("slime_ball"); - public static final ItemBlock slime_block = get("slime_block"); - public static final ItemBucket slime_bucket = get("slime_bucket"); - public static final ItemBlock snow = get("snow"); - public static final ItemSnow snow_layer = get("snow_layer"); - public static final ItemSnowball snowball = get("snowball"); - public static final ItemMetalBlock sodium_block = get("sodium_block"); - public static final ItemMetalBlock sodium_ore = get("sodium_ore"); - public static final ItemMetal sodium_powder = get("sodium_powder"); - public static final ItemBlock soul_sand = get("soul_sand"); - public static final ItemSeeds soul_wart = get("soul_wart"); - public static final Item speckled_melon = get("speckled_melon"); - public static final ItemFood spider_eye = get("spider_eye"); - public static final ItemBlock sponge = get("sponge"); - public static final ItemDoor spruce_door = get("spruce_door"); - public static final ItemFence spruce_fence = get("spruce_fence"); - public static final ItemBlock spruce_fence_gate = get("spruce_fence_gate"); - public static final ItemLeaves spruce_leaves = get("spruce_leaves"); - public static final ItemBlock spruce_log = get("spruce_log"); - public static final ItemBlock spruce_planks = get("spruce_planks"); - public static final ItemBlock spruce_sapling = get("spruce_sapling"); - public static final ItemSlab spruce_slab = get("spruce_slab"); - public static final ItemBlock spruce_stairs = get("spruce_stairs"); - public static final ItemCloth stained_glass = get("stained_glass"); - public static final ItemCloth stained_glass_pane = get("stained_glass_pane"); - public static final ItemCloth stained_hardened_clay = get("stained_hardened_clay"); - public static final ItemStick stick = get("stick"); - public static final ItemPiston sticky_piston = get("sticky_piston"); - public static final ItemBlock stone = get("stone"); - public static final ItemAxe stone_axe = get("stone_axe"); - public static final ItemButton stone_button = get("stone_button"); - public static final ItemHoe stone_hoe = get("stone_hoe"); - public static final ItemPickaxe stone_pickaxe = get("stone_pickaxe"); - public static final ItemPressurePlate stone_pressure_plate = get("stone_pressure_plate"); - public static final ItemShovel stone_shovel = get("stone_shovel"); - public static final ItemSlab stone_slab = get("stone_slab"); - public static final ItemBlock stone_stairs = get("stone_stairs"); - public static final ItemSword stone_sword = get("stone_sword"); - public static final ItemMultiTexture stonebrick = get("stonebrick"); - public static final ItemSlab stonebrick_slab = get("stonebrick_slab"); - public static final ItemBlock stonebrick_stairs = get("stonebrick_stairs"); - public static final ItemSmallBlock string = get("string"); - public static final Item sugar = get("sugar"); - public static final ItemMetalBlock sulfur_block = get("sulfur_block"); - public static final ItemMetalBlock sulfur_ore = get("sulfur_ore"); - public static final ItemMetal sulfur_powder = get("sulfur_powder"); - public static final ItemColored tallgrass = get("tallgrass"); - public static final ItemAxe thetium_axe = get("thetium_axe"); - public static final ItemBlock thetium_block = get("thetium_block"); - public static final ItemArmor thetium_boots = get("thetium_boots"); - public static final ItemArmor thetium_chestplate = get("thetium_chestplate"); - public static final ItemArmor thetium_helmet = get("thetium_helmet"); - public static final ItemHoe thetium_hoe = get("thetium_hoe"); - public static final ItemArmor thetium_leggings = get("thetium_leggings"); - public static final ItemBlock thetium_ore = get("thetium_ore"); - public static final ItemPickaxe thetium_pickaxe = get("thetium_pickaxe"); - public static final ItemShovel thetium_shovel = get("thetium_shovel"); - public static final ItemSword thetium_sword = get("thetium_sword"); - public static final Item thi_fragment = get("thi_fragment"); - public static final ItemBlock tian = get("tian"); - public static final ItemDoor tian_door = get("tian_door"); - public static final ItemFence tian_fence = get("tian_fence"); - public static final ItemBlock tian_fence_gate = get("tian_fence_gate"); - public static final ItemLeaves tian_leaves = get("tian_leaves"); - public static final ItemBlock tian_log = get("tian_log"); - public static final ItemBlock tian_planks = get("tian_planks"); - public static final ItemBlock tian_reactor = get("tian_reactor"); - public static final ItemBlock tian_sapling = get("tian_sapling"); - public static final ItemSlab tian_slab = get("tian_slab"); - public static final ItemBlock tian_soil = get("tian_soil"); - public static final ItemBlock tian_stairs = get("tian_stairs"); - public static final ItemMetalBlock tin_block = get("tin_block"); - public static final ItemMetal tin_ingot = get("tin_ingot"); - public static final ItemMetalBlock tin_ore = get("tin_ore"); - public static final ItemMetalBlock titanium_block = get("titanium_block"); - public static final ItemMetal titanium_ingot = get("titanium_ingot"); - public static final ItemMetalBlock titanium_ore = get("titanium_ore"); - public static final ItemTNT tnt = get("tnt"); - public static final ItemMinecart tnt_minecart = get("tnt_minecart"); - public static final ItemBlock torch = get("torch"); - public static final ItemBlock trapdoor = get("trapdoor"); - public static final ItemChest trapped_chest = get("trapped_chest"); - public static final ItemBlock tripwire_hook = get("tripwire_hook"); - public static final ItemMetalBlock tungsten_block = get("tungsten_block"); - public static final ItemMetal tungsten_ingot = get("tungsten_ingot"); - public static final ItemMetalBlock tungsten_ore = get("tungsten_ore"); - public static final ItemMetalBlock uranium_block = get("uranium_block"); - public static final ItemMetal uranium_ingot = get("uranium_ingot"); - public static final ItemMetalBlock uranium_ore = get("uranium_ore"); - public static final ItemMetalBlock vanadium_block = get("vanadium_block"); - public static final ItemMetal vanadium_ingot = get("vanadium_ingot"); - public static final ItemMetalBlock vanadium_ore = get("vanadium_ore"); - public static final ItemColored vine = get("vine"); - public static final ItemEditWand wand = get("wand"); - public static final ItemBlock warp_chest = get("warp_chest"); - public static final ItemBucket water_bucket = get("water_bucket"); - public static final ItemLilyPad waterlily = get("waterlily"); - public static final ItemWeatherToken weather_token_chilled = get("weather_token_chilled"); - public static final ItemWeatherToken weather_token_clear = get("weather_token_clear"); - public static final ItemWeatherToken weather_token_cold = get("weather_token_cold"); - public static final ItemWeatherToken weather_token_fire = get("weather_token_fire"); - public static final ItemWeatherToken weather_token_fog = get("weather_token_fog"); - public static final ItemWeatherToken weather_token_frost = get("weather_token_frost"); - public static final ItemWeatherToken weather_token_hail = get("weather_token_hail"); - public static final ItemWeatherToken weather_token_hailstorm = get("weather_token_hailstorm"); - public static final ItemWeatherToken weather_token_hot = get("weather_token_hot"); - public static final ItemWeatherToken weather_token_ice = get("weather_token_ice"); - public static final ItemWeatherToken weather_token_iceage = get("weather_token_iceage"); - public static final ItemWeatherToken weather_token_inferno = get("weather_token_inferno"); - public static final ItemWeatherToken weather_token_rain = get("weather_token_rain"); - public static final ItemWeatherToken weather_token_snow = get("weather_token_snow"); - public static final ItemWeatherToken weather_token_snowstorm = get("weather_token_snowstorm"); - public static final ItemWeatherToken weather_token_storm = get("weather_token_storm"); - public static final ItemWeatherToken weather_token_thunder = get("weather_token_thunder"); - public static final ItemBlock web = get("web"); - public static final ItemSeeds wheat = get("wheat"); - public static final Item wheats = get("wheats"); - public static final ItemBed white_bed = get("white_bed"); - public static final ItemAxe wood_axe = get("wood_axe"); - public static final ItemHoe wood_hoe = get("wood_hoe"); - public static final ItemPickaxe wood_pickaxe = get("wood_pickaxe"); - public static final ItemShovel wood_shovel = get("wood_shovel"); - public static final ItemSword wood_sword = get("wood_sword"); - public static final ItemButton wooden_button = get("wooden_button"); - public static final ItemPressurePlate wooden_pressure_plate = get("wooden_pressure_plate"); - public static final ItemCloth wool = get("wool"); - public static final ItemBlock workbench = get("workbench"); - public static final Item writable_book = get("writable_book"); - public static final Item written_book = get("written_book"); - public static final ItemMetalBlock zinc_block = get("zinc_block"); - public static final ItemMetal zinc_ingot = get("zinc_ingot"); - public static final ItemMetalBlock zinc_ore = get("zinc_ore"); - public static final ItemBucket recursive_springwater_bucket = get("recursive_springwater_bucket"); - public static final ItemBucket springwater_bucket = get("springwater_bucket"); - - private static T get(String id) { - if(!ItemRegistry.REGISTRY.containsKey(id)) - throw new RuntimeException("Gegenstand " + id + " existiert nicht"); - return (T)ItemRegistry.REGISTRY.getObject(id); - } - - static { - if(Util.DEVMODE) { - Set items = Sets.newHashSet(ItemRegistry.REGISTRY); - for(Field field : Items.class.getDeclaredFields()) { - if(Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers()) && Item.class.isAssignableFrom(field.getType())) - try { - items.remove(field.get(null)); - } - catch(IllegalArgumentException | IllegalAccessException e) { - Util.throwUnchecked(e); - } - } - for(Iterator iter = items.iterator(); iter.hasNext();) { - Item item = iter.next(); - if(item instanceof ItemNpcSpawner || item instanceof ItemMonsterPlacer) - iter.remove(); - } - if(!items.isEmpty()) { - List list = Lists.newArrayList(items); - Collections.sort(list, Comparator.comparing(item -> ItemRegistry.getNameFromItem(item))); - System.err.printf("\n*** -------------------------------------------------------------- ***\n\n"); - for(Item item : list) { - String name = ItemRegistry.getNameFromItem(item); - System.err.printf("\tpublic static final %s %s = get(\"%s\");\n", item.getClass().getSimpleName(), name, name); - } - System.err.printf("\n^^^ " + Items.class.getCanonicalName() + ": Gegenstandsliste ist unvollständig, Bitte neuen Quellcode einfügen ^^^\n"); - System.exit(1); - } - } - } -} diff --git a/common/src/main/java/common/init/Registry.java b/common/src/main/java/common/init/Registry.java deleted file mode 100755 index fecbfde..0000000 --- a/common/src/main/java/common/init/Registry.java +++ /dev/null @@ -1,17 +0,0 @@ -package common.init; - -public abstract class Registry { - public static void register() { - NameRegistry.register(); - BlockRegistry.register(); - FlammabilityRegistry.register(); - SpeciesRegistry.register(); - EntityRegistry.registerEggs(); - ItemRegistry.register(); - TileRegistry.register(); - CraftingRegistry.register(); - SmeltingRegistry.register(); - EntityRegistry.register(); - DispenserRegistry.register(); - } -} diff --git a/common/src/main/java/common/inventory/ContainerEnchantment.java b/common/src/main/java/common/inventory/ContainerEnchantment.java deleted file mode 100755 index 32e26de..0000000 --- a/common/src/main/java/common/inventory/ContainerEnchantment.java +++ /dev/null @@ -1,359 +0,0 @@ -package common.inventory; - -import java.util.List; - -import common.enchantment.Enchantment; -import common.enchantment.EnchantmentHelper; -import common.enchantment.RngEnchantment; -import common.entity.npc.EntityNPC; -import common.init.Blocks; -import common.init.Items; -import common.item.ItemStack; -import common.rng.Random; -import common.util.BlockPos; -import common.util.Pair; -import common.world.World; - -public class ContainerEnchantment extends Container -{ - public IInventory table; - private World world; - private BlockPos position; - private Random rand; - public int seed; - public int[] mana; - public Pair[] ench; - - public ContainerEnchantment(InventoryPlayer playerInv, World worldIn) - { - this(playerInv, worldIn, BlockPos.ORIGIN); - } - - public ContainerEnchantment(InventoryPlayer playerInv, World worldIn, BlockPos pos) - { - this.table = new InventoryBasic("Enchant", true, 1) - { - public int getInventoryStackLimit() - { - return ItemStack.MAX_SIZE; - } - public void markDirty() - { - super.markDirty(); - ContainerEnchantment.this.onCraftMatrixChanged(this); - } - }; - this.rand = new Random(); - this.mana = new int[3]; - this.ench = new Pair[] {null, null, null}; - this.world = worldIn; - this.position = pos; - this.seed = playerInv.player.getEnchSeed(); - this.addSlotToContainer(new Slot(this.table, 0, 25, 47) - { - public boolean isItemValid(ItemStack stack) - { - return true; - } - public int getSlotStackLimit() - { - return 1; - } - }); - - for (int i = 0; i < 3; ++i) - { - for (int j = 0; j < 9; ++j) - { - this.addSlotToContainer(new Slot(playerInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); - } - } - - for (int k = 0; k < 9; ++k) - { - this.addSlotToContainer(new Slot(playerInv, k, 8 + k * 18, 142)); - } - } - - public static int encodeData(Pair data) { - return data == null ? -1 : data.first().ordinal() | data.second() << 8; - } - - public static Pair decodeData(int data) { - return data < 0 ? null : new Pair(Enchantment.values()[(data & 0xff) % Enchantment.values().length], data >> 8); - } - - public void onCraftGuiOpened(ICrafting listener) - { - super.onCraftGuiOpened(listener); - listener.sendProgressBarUpdate(this, 0, this.mana[0]); - listener.sendProgressBarUpdate(this, 1, this.mana[1]); - listener.sendProgressBarUpdate(this, 2, this.mana[2]); - listener.sendProgressBarUpdate(this, 3, this.seed & -16); - listener.sendProgressBarUpdate(this, 4, encodeData(this.ench[0])); - listener.sendProgressBarUpdate(this, 5, encodeData(this.ench[1])); - listener.sendProgressBarUpdate(this, 6, encodeData(this.ench[2])); - } - - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - - for (int i = 0; i < this.crafters.size(); ++i) - { - ICrafting icrafting = (ICrafting)this.crafters.get(i); - icrafting.sendProgressBarUpdate(this, 0, this.mana[0]); - icrafting.sendProgressBarUpdate(this, 1, this.mana[1]); - icrafting.sendProgressBarUpdate(this, 2, this.mana[2]); - icrafting.sendProgressBarUpdate(this, 3, this.seed & -16); - icrafting.sendProgressBarUpdate(this, 4, encodeData(this.ench[0])); - icrafting.sendProgressBarUpdate(this, 5, encodeData(this.ench[1])); - icrafting.sendProgressBarUpdate(this, 6, encodeData(this.ench[2])); - } - } - - public void updateProgressBar(int id, int data) - { - if (id >= 0 && id <= 2) - { - this.mana[id] = data; - } - else if (id == 3) - { - this.seed = data; - } - else if (id >= 4 && id <= 6) - { - this.ench[id - 4] = decodeData(data); - } - else - { - super.updateProgressBar(id, data); - } - } - - public void onCraftMatrixChanged(IInventory inventoryIn) - { - if (inventoryIn == this.table) - { - ItemStack itemstack = inventoryIn.getStackInSlot(0); - - if (itemstack != null && itemstack.isItemEnchantable()) - { - if (!this.world.client) - { - int l = 0; - - for (int j = -1; j <= 1; ++j) - { - for (int k = -1; k <= 1; ++k) - { - if ((j != 0 || k != 0) && this.world.isAirBlock(this.position.add(k, 0, j)) && this.world.isAirBlock(this.position.add(k, 1, j))) - { - if (this.world.getState(this.position.add(k * 2, 0, j * 2)).getBlock() == Blocks.bookshelf) - { - ++l; - } - - if (this.world.getState(this.position.add(k * 2, 1, j * 2)).getBlock() == Blocks.bookshelf) - { - ++l; - } - - if (k != 0 && j != 0) - { - if (this.world.getState(this.position.add(k * 2, 0, j)).getBlock() == Blocks.bookshelf) - { - ++l; - } - - if (this.world.getState(this.position.add(k * 2, 1, j)).getBlock() == Blocks.bookshelf) - { - ++l; - } - - if (this.world.getState(this.position.add(k, 0, j * 2)).getBlock() == Blocks.bookshelf) - { - ++l; - } - - if (this.world.getState(this.position.add(k, 1, j * 2)).getBlock() == Blocks.bookshelf) - { - ++l; - } - } - } - } - } - - this.rand.setSeed((long)this.seed); - - for (int i1 = 0; i1 < 3; ++i1) - { - this.mana[i1] = EnchantmentHelper.calcItemStackEnchantability(this.rand, i1, l, itemstack); - this.ench[i1] = null; - - if (this.mana[i1] < i1 + 1) - { - this.mana[i1] = 0; - } - } - - for (int j1 = 0; j1 < 3; ++j1) - { - if (this.mana[j1] > 0) - { - List list = this.getRandomEnchantments(itemstack, j1, this.mana[j1]); - - if (list != null && !list.isEmpty()) - { - RngEnchantment enchantmentdata = (RngEnchantment)list.get(this.rand.zrange(list.size())); - this.ench[j1] = new Pair(enchantmentdata.enchantment, enchantmentdata.level); - } - } - } - - this.detectAndSendChanges(); - } - } - else - { - for (int i = 0; i < 3; ++i) - { - this.mana[i] = 0; - this.ench[i] = null; - } - } - } - } - - public boolean enchantItem(EntityNPC player, int id) { - ItemStack stack = this.table.getStackInSlot(0); - int cost = id + 1; - - if(this.mana[id] > 0 && stack != null && player.getManaPoints() >= cost && player.getManaPoints() >= this.mana[id]) { - if(!this.world.client) { - List ench = this.getRandomEnchantments(stack, id, this.mana[id]); - boolean book = stack.getItem() == Items.book; - - if(ench != null) { - player.useMana(cost); - player.updateEnchSeed(); - - if(book) - stack.setItem(Items.enchanted_book); - - for(int z = 0; z < ench.size(); z++) { - RngEnchantment itm = ench.get(z); - - if(book) - Items.enchanted_book.addEnchantment(stack, itm); - else - stack.addEnchantment(itm.enchantment, itm.level); - } - - this.table.markDirty(); - this.seed = player.getEnchSeed(); - this.onCraftMatrixChanged(this.table); - } - } - - return true; - } - else { - return false; - } - } - - private List getRandomEnchantments(ItemStack stack, int id, int level) - { - this.rand.setSeed((long)(this.seed + id)); - List list = EnchantmentHelper.buildEnchantmentList(this.rand, stack, level); - - if (stack.getItem() == Items.book && list != null && list.size() > 1) - { - list.remove(this.rand.zrange(list.size())); - } - - return list; - } - - public void onContainerClosed(EntityNPC playerIn) - { - super.onContainerClosed(playerIn); - - if (!this.world.client) - { - for (int i = 0; i < this.table.getSizeInventory(); ++i) - { - ItemStack itemstack = this.table.removeStackFromSlot(i); - - if (itemstack != null) - { - playerIn.dropPlayerItemWithRandomChoice(itemstack, false); - } - } - } - } - - public boolean canInteractWith(EntityNPC playerIn) - { - return this.world.getState(this.position).getBlock() != Blocks.enchanting_table ? false : playerIn.getDistanceSq((double)this.position.getX() + 0.5D, (double)this.position.getY() + 0.5D, (double)this.position.getZ() + 0.5D) <= 64.0D; - } - - public ItemStack transferStackInSlot(EntityNPC playerIn, int index) - { - ItemStack itemstack = null; - Slot slot = (Slot)this.inventorySlots.get(index); - - if (slot != null && slot.getHasStack()) - { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - - if (index == 0) - { - if (!this.mergeItemStack(itemstack1, 1, 37, true)) - { - return null; - } - } - else - { - if (((Slot)this.inventorySlots.get(0)).getHasStack() || !((Slot)this.inventorySlots.get(0)).isItemValid(itemstack1)) - { - return null; - } - - if (itemstack1.hasTagCompound() && itemstack1.size == 1) - { - ((Slot)this.inventorySlots.get(0)).putStack(itemstack1.copy()); - itemstack1.size = 0; - } - else if (itemstack1.size >= 1) - { - ((Slot)this.inventorySlots.get(0)).putStack(new ItemStack(itemstack1.getItem(), 1, itemstack1.getMetadata())); - --itemstack1.size; - } - } - - if (itemstack1.size == 0) - { - slot.putStack((ItemStack)null); - } - else - { - slot.onSlotChanged(); - } - - if (itemstack1.size == itemstack.size) - { - return null; - } - - slot.onPickupFromSlot(playerIn, itemstack1); - } - - return itemstack; - } -} diff --git a/common/src/main/java/common/inventory/ContainerEntityInventory.java b/common/src/main/java/common/inventory/ContainerEntityInventory.java deleted file mode 100755 index 32ba225..0000000 --- a/common/src/main/java/common/inventory/ContainerEntityInventory.java +++ /dev/null @@ -1,132 +0,0 @@ -package common.inventory; - -import common.entity.Entity; -import common.entity.animal.EntityHorse; -import common.entity.npc.EntityNPC; -import common.init.Items; -import common.item.ItemStack; - -public class ContainerEntityInventory extends Container -{ - private IInventory entityInventory; - private Entity entity; - - public ContainerEntityInventory(IInventory playerInventory, final IInventory entityInv, final Entity entity, EntityNPC player) - { - this.entityInventory = entityInv; - this.entity = entity; - int i = 3; - entityInv.openInventory(player); - int j = (i - 4) * 18; - if(this.entity instanceof EntityHorse) { - final EntityHorse horse = (EntityHorse)this.entity; - this.addSlotToContainer(new Slot(entityInv, 0, 8, 18) - { - public boolean isItemValid(ItemStack stack) - { - return super.isItemValid(stack) && stack.getItem() == Items.saddle && !this.getHasStack(); - } - }); - this.addSlotToContainer(new Slot(entityInv, 1, 8, 36) - { - public boolean isItemValid(ItemStack stack) - { - return super.isItemValid(stack) && horse.canWearArmor() && EntityHorse.isArmorItem(stack.getItem()); - } - public boolean canBeHovered() - { - return horse.canWearArmor(); - } - }); - if (horse.isChested()) - { - for (int k = 0; k < i; ++k) - { - for (int l = 0; l < 5; ++l) - { - this.addSlotToContainer(new Slot(entityInv, 2 + l + k * 5, 80 + l * 18, 18 + k * 18)); - } - } - } - } - - for (int i1 = 0; i1 < 3; ++i1) - { - for (int k1 = 0; k1 < 9; ++k1) - { - this.addSlotToContainer(new Slot(playerInventory, k1 + i1 * 9 + 9, 8 + k1 * 18, 102 + i1 * 18 + j)); - } - } - - for (int j1 = 0; j1 < 9; ++j1) - { - this.addSlotToContainer(new Slot(playerInventory, j1, 8 + j1 * 18, 160 + j)); - } - } - - public boolean canInteractWith(EntityNPC playerIn) - { - return this.entityInventory.isUseableByPlayer(playerIn) && this.entity.isEntityAlive() && this.entity.getDistanceToEntity(playerIn) < 8.0F; - } - - /** - * Take a stack from the specified inventory slot. - */ - public ItemStack transferStackInSlot(EntityNPC playerIn, int index) - { - ItemStack itemstack = null; - Slot slot = (Slot)this.inventorySlots.get(index); - - if (slot != null && slot.getHasStack()) - { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - - if (index < this.entityInventory.getSizeInventory()) - { - if (!this.mergeItemStack(itemstack1, this.entityInventory.getSizeInventory(), this.inventorySlots.size(), true)) - { - return null; - } - } - else if (this.entity instanceof EntityHorse && this.getSlot(1).isItemValid(itemstack1) && !this.getSlot(1).getHasStack()) - { - if (!this.mergeItemStack(itemstack1, 1, 2, false)) - { - return null; - } - } - else if (this.entity instanceof EntityHorse && this.getSlot(0).isItemValid(itemstack1)) - { - if (!this.mergeItemStack(itemstack1, 0, 1, false)) - { - return null; - } - } - else if (this.entity instanceof EntityHorse && (this.entityInventory.getSizeInventory() <= 2 || !this.mergeItemStack(itemstack1, 2, this.entityInventory.getSizeInventory(), false))) - { - return null; - } - - if (itemstack1.size == 0) - { - slot.putStack((ItemStack)null); - } - else - { - slot.onSlotChanged(); - } - } - - return itemstack; - } - - /** - * Called when the container is closed. - */ - public void onContainerClosed(EntityNPC playerIn) - { - super.onContainerClosed(playerIn); - this.entityInventory.closeInventory(playerIn); - } -} diff --git a/common/src/main/java/common/item/CheatTab.java b/common/src/main/java/common/item/CheatTab.java deleted file mode 100755 index b92c840..0000000 --- a/common/src/main/java/common/item/CheatTab.java +++ /dev/null @@ -1,121 +0,0 @@ -package common.item; - -import java.util.List; - -import common.init.Blocks; -import common.init.ItemRegistry; -import common.init.Items; - -public enum CheatTab { - BLOCKS("Baumaterial") { - protected Item getIconItem() { - return ItemRegistry.getItemFromBlock(Blocks.glass); - } - }, - NATURE("Gestein und Natur") { - protected Item getIconItem() { - return ItemRegistry.getItemFromBlock(Blocks.grass); - } - }, - WOOD("Holz") { - protected Item getIconItem() { - return ItemRegistry.getItemFromBlock(Blocks.maple_planks); - } - }, - PLANTS("Pflanzen") { - protected Item getIconItem() { - return ItemRegistry.getItemFromBlock(Blocks.oak_leaves); - } - }, - DECORATION("Dekoration") { - protected Item getIconItem() { - return ItemRegistry.getItemFromBlock(Blocks.hay_block); - } - }, - TECHNOLOGY("Redstone & Technik") { - protected Item getIconItem() { - return ItemRegistry.getItemFromBlock(Blocks.tnt); - } - }, - GEMS("Erze & Teure Blöcke") { - protected Item getIconItem() { - return ItemRegistry.getItemFromBlock(Blocks.diamond_block); - } - }, - SPAWNERS("Mob & Itemspawner") { - protected Item getIconItem() { - return Items.minecart; - } - }, - TOOLS("Werkzeug") { - protected Item getIconItem() { - return Items.flint_and_steel; - } - }, - LIQUIDS("Flüssigkeiten") { - protected Item getIconItem() { - return Items.water_bucket; - } - }, - COMBAT("Kampf") { - protected Item getIconItem() { - return Items.bow; - } - }, - MAGIC("Tränke & Verzauberungen") { - protected Item getIconItem() { - return Items.potion; - } - }, - MATERIALS("Werkstoffe") { - protected Item getIconItem() { - return Items.leather; - } - }, - METALS("Metalle und Juwelen") { - protected Item getIconItem() { - return Items.iron_ingot; - } - }, - MISC("Verschiedenes & Nahrung") { - protected Item getIconItem() { - return Items.charge_crystal; - } - }; - - private final String name; - - private ItemStack icon; - - private CheatTab(String name) { - this.name = name; - } - - public int getHorizontal() { - return this.ordinal() % 12; - } - - public int getVertical() { - return this.ordinal() / 12; - } - - public String getName() { - return this.name; - } - - public ItemStack getIcon() { - if(this.icon == null) - this.icon = new ItemStack(this.getIconItem()); - return this.icon; - } - - protected abstract Item getIconItem(); - - public void filter(List list) { - for(Item item : ItemRegistry.REGISTRY) { - if(item != null && item.getTab() == this) { - item.getSubItems(item, this, list); - } - } - } -} diff --git a/common/src/main/java/common/item/ItemAxe.java b/common/src/main/java/common/item/ItemAxe.java deleted file mode 100755 index d2230ed..0000000 --- a/common/src/main/java/common/item/ItemAxe.java +++ /dev/null @@ -1,14 +0,0 @@ -package common.item; - -import common.block.Block; -import common.init.ToolMaterial; - -public class ItemAxe extends ItemTool { - public ItemAxe(ToolMaterial material) { - super(3, material); - } - - public boolean canUseOn(ItemStack stack, Block block) { - return block.canAxeHarvest(); - } -} diff --git a/common/src/main/java/common/item/ItemPickaxe.java b/common/src/main/java/common/item/ItemPickaxe.java deleted file mode 100755 index 1a2c7ba..0000000 --- a/common/src/main/java/common/item/ItemPickaxe.java +++ /dev/null @@ -1,18 +0,0 @@ -package common.item; - -import common.block.Block; -import common.init.ToolMaterial; - -public class ItemPickaxe extends ItemTool { - public ItemPickaxe(ToolMaterial material) { - super(2, material); - } - - public boolean canHarvestBlock(Block block) { - return block.getMiningLevel() >= 0 && this.getToolMaterial().getHarvestLevel() >= block.getMiningLevel(); - } - - public boolean canUseOn(ItemStack stack, Block block) { - return block.getMiningLevel() >= 0; - } -} diff --git a/common/src/main/java/common/item/ItemShovel.java b/common/src/main/java/common/item/ItemShovel.java deleted file mode 100755 index 5419e23..0000000 --- a/common/src/main/java/common/item/ItemShovel.java +++ /dev/null @@ -1,19 +0,0 @@ -package common.item; - -import common.block.Block; -import common.block.Material; -import common.init.ToolMaterial; - -public class ItemShovel extends ItemTool { - public ItemShovel(ToolMaterial material) { - super(1, material); - } - - public boolean canUseOn(ItemStack stack, Block block) { - return block.canShovelHarvest(); - } - - public boolean canHarvestBlock(Block block) { - return block.getMaterial() == Material.POWDER || block.getMaterial() == Material.DIGGABLE; - } -} diff --git a/common/src/main/java/common/item/ItemSmallBlock.java b/common/src/main/java/common/item/ItemSmallBlock.java deleted file mode 100755 index a311d63..0000000 --- a/common/src/main/java/common/item/ItemSmallBlock.java +++ /dev/null @@ -1,57 +0,0 @@ -package common.item; - -import common.block.Block; -import common.block.natural.BlockSnow; -import common.entity.npc.EntityNPC; -import common.init.Blocks; -import common.util.BlockPos; -import common.util.Facing; -import common.world.State; -import common.world.World; - -public class ItemSmallBlock extends Item { - private Block block; - - public ItemSmallBlock(Block block) { - this.block = block; - } - - public Block getBlock() { - return this.block; - } - - public boolean onItemUse(ItemStack stack, EntityNPC player, World world, BlockPos pos, Facing side, float hitX, float hitY, float hitZ) { - State state = world.getState(pos); - Block block = state.getBlock(); - - if(block == Blocks.snow_layer && state.getValue(BlockSnow.LAYERS).intValue() < 1) - side = Facing.UP; - else if(!block.isReplaceable(world, pos)) - pos = pos.offset(side); - - if(!player.canPlayerEdit(pos, side, stack) || stack.size == 0) - return false; - if(world.canBlockBePlaced(this.block, pos, false, side, null, stack)) { - State newState = this.block.onBlockPlaced(world, pos, side, hitX, hitY, hitZ, 0, player); - - if(world.setState(pos, newState, 3)) { - newState = world.getState(pos); - - if(newState.getBlock() == this.block) { - ItemBlock.setTileEntityNBT(world, player, pos, stack); - newState.getBlock().onBlockPlacedBy(world, pos, newState, player, stack); - } - - world.playSound(this.block.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), - (double)((float)pos.getZ() + 0.5F), 1.0F); - --stack.size; - return true; - } - } - return false; - } - - public boolean isMagnetic() { - return this.block.isMagnetic(); - } -} diff --git a/common/src/main/java/common/item/ItemTool.java b/common/src/main/java/common/item/ItemTool.java deleted file mode 100755 index 28e0768..0000000 --- a/common/src/main/java/common/item/ItemTool.java +++ /dev/null @@ -1,68 +0,0 @@ -package common.item; - -import common.block.Block; -import common.entity.types.EntityLiving; -import common.init.ToolMaterial; -import common.model.Transforms; -import common.util.BlockPos; -import common.world.World; - -public abstract class ItemTool extends Item { - private final float efficiency; - private final int damage; - private final ToolMaterial material; - - public ItemTool(int damage, ToolMaterial material) { - this.material = material; - this.maxStackSize = 1; - this.setMaxDamage(material.getDurability()); - this.efficiency = material.getEfficiency(); - this.damage = damage + material.getDamage(); - this.setTab(CheatTab.TOOLS); - } - - public abstract boolean canUseOn(ItemStack stack, Block block); - - public float getStrVsBlock(ItemStack stack, Block block) { - return !this.canUseOn(stack, block) ? 1.0F : this.efficiency; - } - - public boolean hitEntity(ItemStack stack, EntityLiving target, EntityLiving attacker) { - stack.damageItem(2, attacker); - return true; - } - - public boolean onBlockDestroyed(ItemStack stack, World world, Block block, BlockPos pos, EntityLiving player) { - if(block.getBlockHardness(world, pos) != 0.0f) - stack.damageItem(1, player); - return true; - } - - public ToolMaterial getToolMaterial() { - return this.material; - } - - public int getItemEnchantability() { - return this.material.getEnchantability(); - } - - public boolean getIsRepairable(ItemStack stack, ItemStack repair) { - return this.material.isRepairItem(repair.getItem()) ? true : super.getIsRepairable(stack, repair); - } - - public int getAttackDamageBonus() { - return this.damage; - } - - public boolean isMagnetic() { - return this.material.isMagnetic(); - } - - public Transforms getTransform() { - return Transforms.TOOL; - } - - public boolean canBeWielded() { - return true; - } -} diff --git a/common/src/main/java/common/model/BlockLayer.java b/common/src/main/java/common/model/BlockLayer.java deleted file mode 100755 index 49d2d51..0000000 --- a/common/src/main/java/common/model/BlockLayer.java +++ /dev/null @@ -1,18 +0,0 @@ -package common.model; - -public enum BlockLayer { - SOLID("Solid"), - CUTOUT_MIPPED("Mipped Cutout"), - CUTOUT("Cutout"), - TRANSLUCENT("Translucent"); - - private final String name; - - private BlockLayer(String name) { - this.name = name; - } - - public String toString() { - return this.name; - } -} diff --git a/common/src/main/java/common/model/Transform.java b/common/src/main/java/common/model/Transform.java deleted file mode 100755 index 7451efd..0000000 --- a/common/src/main/java/common/model/Transform.java +++ /dev/null @@ -1,5 +0,0 @@ -package common.model; - -public record Transform(float rotationX, float rotationY, float rotationZ, float translationX, float translationY, float translationZ, float scale) { - public static final Transform IDENTITY = new Transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); -} diff --git a/common/src/main/java/common/model/Transforms.java b/common/src/main/java/common/model/Transforms.java deleted file mode 100755 index 4ca6fee..0000000 --- a/common/src/main/java/common/model/Transforms.java +++ /dev/null @@ -1,169 +0,0 @@ -package common.model; - -public enum Transforms { - DEFAULT( - Transform.IDENTITY, - Transform.IDENTITY, - Transform.IDENTITY, - Transform.IDENTITY - ), - ANVIL( - transform(10.0f, -45.0f, 170.0f, 0.25f, 1.5f, -2.5f, 0.375f), - Transform.IDENTITY, - Transform.IDENTITY, - Transform.IDENTITY - ), - BLOCK( - transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f), - Transform.IDENTITY, - Transform.IDENTITY, - Transform.IDENTITY - ), - ITEM( - transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -3.0f, 0.55f), - transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - TOOL_FLIP( - transform(180.0f, 90.0f, -35.0f, 0.0f, 0.0f, -3.5f, 0.85f), - transform(0.0f, 45.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - TOOL( - transform(0.0f, 90.0f, -35.0f, 0.0f, 1.25f, -3.5f, 0.85f), - transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - OFFSET2( - transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.25f, 0.55f), - transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - LAYER( - transform(10.0f, -45.0f, 170.0f, 0.0f, 0.25f, -2.75f, 0.375f), - transform(0.0f, 0.0f, 0.0f, 0.0f, 5.25f, 0.0f, 1.0f), - Transform.IDENTITY, - Transform.IDENTITY - ), - DICE( - transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -1.75f, 0.15f), - transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.4f), - transform(135.0f, -55.0f, 180.0f, 0.0f, 0.0f, 0.0f, 1.1f), - transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.4f) - ), - STAIRS( - transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f), - Transform.IDENTITY, - transform(0.0f, 180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), - Transform.IDENTITY - ), - OFFSET1( - transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.5f, 0.55f), - transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - GATE( - transform(0.0f, -90.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f), - transform(0.0f, 90.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), - Transform.IDENTITY, - Transform.IDENTITY - ), - NUGGET( - transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.0f, 0.55f), - transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - SKULL( - transform(180.0f, -45.0f, 0.0f, 0.0f, 1.0f, -2.5f, 0.25f), - transform(0.0f, -180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.55f), - transform(0.0f, 180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.7f), - Transform.IDENTITY - ), - BUTTON( - transform(10.0f, -45.0f, 170.0f, 0.0f, 1.0f, -1.75f, 0.375f), - Transform.IDENTITY, - Transform.IDENTITY, - Transform.IDENTITY - ), - RANGED( - transform(5.0f, 80.0f, -45.0f, 0.75f, 0.0f, 0.25f, 1.0f), - transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - BANNER( - transform(0.0f, 90.0f, -90.0f, 0.0f, 0.0f, -4.0f, 0.5f), - transform(0.0f, 225.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), - transform(0.0f, -65.0f, 0.0f, 0.0f, -3.0f, 0.0f, 0.85f), - Transform.IDENTITY - ), - FENCE( - transform(0.0f, 0.0f, 180.0f, 0.0f, 1.5f, -2.75f, 0.375f), - Transform.IDENTITY, - transform(0.0f, 90.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), - Transform.IDENTITY - ), - FLAT( - transform(10.0f, -45.0f, 170.0f, 0.0f, 0.25f, -2.75f, 0.375f), - transform(0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 0.0f, 1.0f), - Transform.IDENTITY, - Transform.IDENTITY - ), - ROD( - transform(0.0f, 90.0f, -35.0f, 0.0f, 0.75f, -3.5f, 0.85f), - transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - KEY( - transform(0.0f, 270.0f, -35.0f, 0.0f, 1.25f, -3.5f, 0.85f), - transform(180.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ); - - public static enum Camera { - NONE, - THIRD_PERSON, - FIRST_PERSON, - GUI, - GROUND; - } - - private static Transform transform(float rx, float ry, float rz, float tx, float ty, float tz, float scale) { - return new Transform(rx, ry, rz, tx * 0.0625f, ty * 0.0625f, tz * 0.0625f, scale); - } - - public final Transform third; - public final Transform first; - public final Transform gui; - public final Transform ground; - - private Transforms(Transform third, Transform first, Transform gui, Transform ground) { - this.third = third; - this.first = first; - this.gui = gui; - this.ground = ground; - } - - public Transform get(Camera type) { - switch(type) { - case THIRD_PERSON: - return this.third; - case FIRST_PERSON: - return this.first; - case GUI: - return this.gui; - case GROUND: - return this.ground; - default: - return Transform.IDENTITY; - } - } -} diff --git a/common/src/main/java/common/net/bootstrap/AbstractBootstrap.java b/common/src/main/java/common/net/bootstrap/AbstractBootstrap.java deleted file mode 100644 index 51ed7ec..0000000 --- a/common/src/main/java/common/net/bootstrap/AbstractBootstrap.java +++ /dev/null @@ -1,474 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.bootstrap; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.util.LinkedHashMap; -import java.util.Map; - -import common.net.channel.Channel; -import common.net.channel.ChannelException; -import common.net.channel.ChannelFuture; -import common.net.channel.ChannelFutureListener; -import common.net.channel.ChannelHandler; -import common.net.channel.ChannelOption; -import common.net.channel.ChannelPromise; -import common.net.channel.DefaultChannelPromise; -import common.net.channel.EventLoopGroup; -import common.net.util.AttributeKey; -import common.net.util.concurrent.EventExecutor; -import common.net.util.concurrent.GlobalEventExecutor; -import common.net.util.internal.StringUtil; - -/** - * {@link AbstractBootstrap} is a helper class that makes it easy to bootstrap a {@link Channel}. It support - * method-chaining to provide an easy way to configure the {@link AbstractBootstrap}. - * - *

When not used in a {@link ServerBootstrap} context, the {@link #bind()} methods are useful for connectionless - * transports such as datagram (UDP).

- */ -public abstract class AbstractBootstrap, C extends Channel> implements Cloneable { - - private volatile EventLoopGroup group; - private volatile ChannelFactory channelFactory; - private volatile SocketAddress localAddress; - private final Map, Object> options = new LinkedHashMap, Object>(); - private final Map, Object> attrs = new LinkedHashMap, Object>(); - private volatile ChannelHandler handler; - - AbstractBootstrap() { - // Disallow extending from a different package. - } - - AbstractBootstrap(AbstractBootstrap bootstrap) { - group = bootstrap.group; - channelFactory = bootstrap.channelFactory; - handler = bootstrap.handler; - localAddress = bootstrap.localAddress; - synchronized (bootstrap.options) { - options.putAll(bootstrap.options); - } - synchronized (bootstrap.attrs) { - attrs.putAll(bootstrap.attrs); - } - } - - /** - * The {@link EventLoopGroup} which is used to handle all the events for the to-be-creates - * {@link Channel} - */ - - public B group(EventLoopGroup group) { - if (group == null) { - throw new NullPointerException("group"); - } - if (this.group != null) { - throw new IllegalStateException("group set already"); - } - this.group = group; - return (B) this; - } - - /** - * The {@link Class} which is used to create {@link Channel} instances from. - * You either use this or {@link #channelFactory(ChannelFactory)} if your - * {@link Channel} implementation has no no-args constructor. - */ - public B channel(Class channelClass) { - if (channelClass == null) { - throw new NullPointerException("channelClass"); - } - return channelFactory(new BootstrapChannelFactory(channelClass)); - } - - /** - * {@link ChannelFactory} which is used to create {@link Channel} instances from - * when calling {@link #bind()}. This method is usually only used if {@link #channel(Class)} - * is not working for you because of some more complex needs. If your {@link Channel} implementation - * has a no-args constructor, its highly recommend to just use {@link #channel(Class)} for - * simplify your code. - */ - - public B channelFactory(ChannelFactory channelFactory) { - if (channelFactory == null) { - throw new NullPointerException("channelFactory"); - } - if (this.channelFactory != null) { - throw new IllegalStateException("channelFactory set already"); - } - - this.channelFactory = channelFactory; - return (B) this; - } - - /** - * The {@link SocketAddress} which is used to bind the local "end" to. - * - */ - - public B localAddress(SocketAddress localAddress) { - this.localAddress = localAddress; - return (B) this; - } - - /** - * @see {@link #localAddress(SocketAddress)} - */ - public B localAddress(int inetPort) { - return localAddress(new InetSocketAddress(inetPort)); - } - - /** - * @see {@link #localAddress(SocketAddress)} - */ - public B localAddress(String inetHost, int inetPort) { - return localAddress(new InetSocketAddress(inetHost, inetPort)); - } - - /** - * @see {@link #localAddress(SocketAddress)} - */ - public B localAddress(InetAddress inetHost, int inetPort) { - return localAddress(new InetSocketAddress(inetHost, inetPort)); - } - - /** - * Allow to specify a {@link ChannelOption} which is used for the {@link Channel} instances once they got - * created. Use a value of {@code null} to remove a previous set {@link ChannelOption}. - */ - - public B option(ChannelOption option, T value) { - if (option == null) { - throw new NullPointerException("option"); - } - if (value == null) { - synchronized (options) { - options.remove(option); - } - } else { - synchronized (options) { - options.put(option, value); - } - } - return (B) this; - } - - /** - * Allow to specify an initial attribute of the newly created {@link Channel}. If the {@code value} is - * {@code null}, the attribute of the specified {@code key} is removed. - */ - public B attr(AttributeKey key, T value) { - if (key == null) { - throw new NullPointerException("key"); - } - if (value == null) { - synchronized (attrs) { - attrs.remove(key); - } - } else { - synchronized (attrs) { - attrs.put(key, value); - } - } - - - B b = (B) this; - return b; - } - - /** - * Validate all the parameters. Sub-classes may override this, but should - * call the super method in that case. - */ - - public B validate() { - if (group == null) { - throw new IllegalStateException("group not set"); - } - if (channelFactory == null) { - throw new IllegalStateException("channel or channelFactory not set"); - } - return (B) this; - } - - /** - * Returns a deep clone of this bootstrap which has the identical configuration. This method is useful when making - * multiple {@link Channel}s with similar settings. Please note that this method does not clone the - * {@link EventLoopGroup} deeply but shallowly, making the group a shared resource. - */ - @Override - - public abstract B clone(); - - /** - * Create a new {@link Channel} and register it with an {@link EventLoop}. - */ - public ChannelFuture register() { - validate(); - return initAndRegister(); - } - - /** - * Create a new {@link Channel} and bind it. - */ - public ChannelFuture bind() { - validate(); - SocketAddress localAddress = this.localAddress; - if (localAddress == null) { - throw new IllegalStateException("localAddress not set"); - } - return doBind(localAddress); - } - - /** - * Create a new {@link Channel} and bind it. - */ - public ChannelFuture bind(int inetPort) { - return bind(new InetSocketAddress(inetPort)); - } - - /** - * Create a new {@link Channel} and bind it. - */ - public ChannelFuture bind(String inetHost, int inetPort) { - return bind(new InetSocketAddress(inetHost, inetPort)); - } - - /** - * Create a new {@link Channel} and bind it. - */ - public ChannelFuture bind(InetAddress inetHost, int inetPort) { - return bind(new InetSocketAddress(inetHost, inetPort)); - } - - /** - * Create a new {@link Channel} and bind it. - */ - public ChannelFuture bind(SocketAddress localAddress) { - validate(); - if (localAddress == null) { - throw new NullPointerException("localAddress"); - } - return doBind(localAddress); - } - - private ChannelFuture doBind(final SocketAddress localAddress) { - final ChannelFuture regFuture = initAndRegister(); - final Channel channel = regFuture.channel(); - if (regFuture.cause() != null) { - return regFuture; - } - - final ChannelPromise promise; - if (regFuture.isDone()) { - promise = channel.newPromise(); - doBind0(regFuture, channel, localAddress, promise); - } else { - // Registration future is almost always fulfilled already, but just in case it's not. - promise = new PendingRegistrationPromise(channel); - regFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - doBind0(regFuture, channel, localAddress, promise); - } - }); - } - - return promise; - } - - final ChannelFuture initAndRegister() { - final Channel channel = channelFactory().newChannel(); - try { - init(channel); - } catch (Throwable t) { - channel.unsafe().closeForcibly(); - // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor - return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t); - } - - ChannelFuture regFuture = group().register(channel); - if (regFuture.cause() != null) { - if (channel.isRegistered()) { - channel.close(); - } else { - channel.unsafe().closeForcibly(); - } - } - - // If we are here and the promise is not failed, it's one of the following cases: - // 1) If we attempted registration from the event loop, the registration has been completed at this point. - // i.e. It's safe to attempt bind() or connect() now because the channel has been registered. - // 2) If we attempted registration from the other thread, the registration request has been successfully - // added to the event loop's task queue for later execution. - // i.e. It's safe to attempt bind() or connect() now: - // because bind() or connect() will be executed *after* the scheduled registration task is executed - // because register(), bind(), and connect() are all bound to the same thread. - - return regFuture; - } - - abstract void init(Channel channel) throws Exception; - - private static void doBind0( - final ChannelFuture regFuture, final Channel channel, - final SocketAddress localAddress, final ChannelPromise promise) { - - // This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up - // the pipeline in its channelRegistered() implementation. - channel.eventLoop().execute(new Runnable() { - @Override - public void run() { - if (regFuture.isSuccess()) { - channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); - } else { - promise.setFailure(regFuture.cause()); - } - } - }); - } - - /** - * the {@link ChannelHandler} to use for serving the requests. - */ - - public B handler(ChannelHandler handler) { - if (handler == null) { - throw new NullPointerException("handler"); - } - this.handler = handler; - return (B) this; - } - - final SocketAddress localAddress() { - return localAddress; - } - - final ChannelFactory channelFactory() { - return channelFactory; - } - - final ChannelHandler handler() { - return handler; - } - - /** - * Return the configured {@link EventLoopGroup} or {@code null} if non is configured yet. - */ - public final EventLoopGroup group() { - return group; - } - - final Map, Object> options() { - return options; - } - - final Map, Object> attrs() { - return attrs; - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append(StringUtil.simpleClassName(this)); - buf.append('('); - if (group != null) { - buf.append("group: "); - buf.append(StringUtil.simpleClassName(group)); - buf.append(", "); - } - if (channelFactory != null) { - buf.append("channelFactory: "); - buf.append(channelFactory); - buf.append(", "); - } - if (localAddress != null) { - buf.append("localAddress: "); - buf.append(localAddress); - buf.append(", "); - } - synchronized (options) { - if (!options.isEmpty()) { - buf.append("options: "); - buf.append(options); - buf.append(", "); - } - } - synchronized (attrs) { - if (!attrs.isEmpty()) { - buf.append("attrs: "); - buf.append(attrs); - buf.append(", "); - } - } - if (handler != null) { - buf.append("handler: "); - buf.append(handler); - buf.append(", "); - } - if (buf.charAt(buf.length() - 1) == '(') { - buf.append(')'); - } else { - buf.setCharAt(buf.length() - 2, ')'); - buf.setLength(buf.length() - 1); - } - return buf.toString(); - } - - private static final class BootstrapChannelFactory implements ChannelFactory { - private final Class clazz; - - BootstrapChannelFactory(Class clazz) { - this.clazz = clazz; - } - - @Override - public T newChannel() { - try { - return clazz.getConstructor().newInstance(); - } catch (Throwable t) { - throw new ChannelException("Unable to create Channel from class " + clazz, t); - } - } - - @Override - public String toString() { - return StringUtil.simpleClassName(clazz) + ".class"; - } - } - - private static final class PendingRegistrationPromise extends DefaultChannelPromise { - private PendingRegistrationPromise(Channel channel) { - super(channel); - } - - @Override - protected EventExecutor executor() { - if (channel().isRegistered()) { - // If the registration was a success we can just call super.executor() which will return - // channel.eventLoop(). - // - // See https://github.com/netty/netty/issues/2586 - return super.executor(); - } - // The registration failed so we can only use the GlobalEventExecutor as last resort to notify. - return GlobalEventExecutor.INSTANCE; - } - } -} diff --git a/common/src/main/java/common/net/bootstrap/Bootstrap.java b/common/src/main/java/common/net/bootstrap/Bootstrap.java deleted file mode 100644 index dd59fb0..0000000 --- a/common/src/main/java/common/net/bootstrap/Bootstrap.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.bootstrap; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.util.Map; -import java.util.Map.Entry; - -import common.net.channel.Channel; -import common.net.channel.ChannelFuture; -import common.net.channel.ChannelFutureListener; -import common.net.channel.ChannelOption; -import common.net.channel.ChannelPipeline; -import common.net.channel.ChannelPromise; -import common.net.util.AttributeKey; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * A {@link Bootstrap} that makes it easy to bootstrap a {@link Channel} to use - * for clients. - * - *

The {@link #bind()} methods are useful in combination with connectionless transports such as datagram (UDP). - * For regular TCP connections, please use the provided {@link #connect()} methods.

- */ -public final class Bootstrap extends AbstractBootstrap { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(Bootstrap.class); - - private volatile SocketAddress remoteAddress; - - public Bootstrap() { } - - private Bootstrap(Bootstrap bootstrap) { - super(bootstrap); - remoteAddress = bootstrap.remoteAddress; - } - - /** - * The {@link SocketAddress} to connect to once the {@link #connect()} method - * is called. - */ - public Bootstrap remoteAddress(SocketAddress remoteAddress) { - this.remoteAddress = remoteAddress; - return this; - } - - /** - * @see {@link #remoteAddress(SocketAddress)} - */ - public Bootstrap remoteAddress(String inetHost, int inetPort) { - remoteAddress = new InetSocketAddress(inetHost, inetPort); - return this; - } - - /** - * @see {@link #remoteAddress(SocketAddress)} - */ - public Bootstrap remoteAddress(InetAddress inetHost, int inetPort) { - remoteAddress = new InetSocketAddress(inetHost, inetPort); - return this; - } - - /** - * Connect a {@link Channel} to the remote peer. - */ - public ChannelFuture connect() { - validate(); - SocketAddress remoteAddress = this.remoteAddress; - if (remoteAddress == null) { - throw new IllegalStateException("remoteAddress not set"); - } - - return doConnect(remoteAddress, localAddress()); - } - - /** - * Connect a {@link Channel} to the remote peer. - */ - public ChannelFuture connect(String inetHost, int inetPort) { - return connect(new InetSocketAddress(inetHost, inetPort)); - } - - /** - * Connect a {@link Channel} to the remote peer. - */ - public ChannelFuture connect(InetAddress inetHost, int inetPort) { - return connect(new InetSocketAddress(inetHost, inetPort)); - } - - /** - * Connect a {@link Channel} to the remote peer. - */ - public ChannelFuture connect(SocketAddress remoteAddress) { - if (remoteAddress == null) { - throw new NullPointerException("remoteAddress"); - } - - validate(); - return doConnect(remoteAddress, localAddress()); - } - - /** - * Connect a {@link Channel} to the remote peer. - */ - public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { - if (remoteAddress == null) { - throw new NullPointerException("remoteAddress"); - } - validate(); - return doConnect(remoteAddress, localAddress); - } - - /** - * @see {@link #connect()} - */ - private ChannelFuture doConnect(final SocketAddress remoteAddress, final SocketAddress localAddress) { - final ChannelFuture regFuture = initAndRegister(); - final Channel channel = regFuture.channel(); - if (regFuture.cause() != null) { - return regFuture; - } - - final ChannelPromise promise = channel.newPromise(); - if (regFuture.isDone()) { - doConnect0(regFuture, channel, remoteAddress, localAddress, promise); - } else { - regFuture.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - doConnect0(regFuture, channel, remoteAddress, localAddress, promise); - } - }); - } - - return promise; - } - - private static void doConnect0( - final ChannelFuture regFuture, final Channel channel, - final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) { - - // This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up - // the pipeline in its channelRegistered() implementation. - channel.eventLoop().execute(new Runnable() { - @Override - public void run() { - if (regFuture.isSuccess()) { - if (localAddress == null) { - channel.connect(remoteAddress, promise); - } else { - channel.connect(remoteAddress, localAddress, promise); - } - promise.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); - } else { - promise.setFailure(regFuture.cause()); - } - } - }); - } - - @Override - - void init(Channel channel) throws Exception { - ChannelPipeline p = channel.pipeline(); - p.addLast(handler()); - - final Map, Object> options = options(); - synchronized (options) { - for (Entry, Object> e: options.entrySet()) { - try { - if (!channel.config().setOption((ChannelOption) e.getKey(), e.getValue())) { - logger.warn("Unknown channel option: " + e); - } - } catch (Throwable t) { - logger.warn("Failed to set a channel option: " + channel, t); - } - } - } - - final Map, Object> attrs = attrs(); - synchronized (attrs) { - for (Entry, Object> e: attrs.entrySet()) { - channel.attr((AttributeKey) e.getKey()).set(e.getValue()); - } - } - } - - @Override - public Bootstrap validate() { - super.validate(); - if (handler() == null) { - throw new IllegalStateException("handler not set"); - } - return this; - } - - @Override - - public Bootstrap clone() { - return new Bootstrap(this); - } - - @Override - public String toString() { - if (remoteAddress == null) { - return super.toString(); - } - - StringBuilder buf = new StringBuilder(super.toString()); - buf.setLength(buf.length() - 1); - buf.append(", remoteAddress: "); - buf.append(remoteAddress); - buf.append(')'); - - return buf.toString(); - } -} diff --git a/common/src/main/java/common/net/bootstrap/ChannelFactory.java b/common/src/main/java/common/net/bootstrap/ChannelFactory.java deleted file mode 100644 index d6e48e3..0000000 --- a/common/src/main/java/common/net/bootstrap/ChannelFactory.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.bootstrap; - -import common.net.channel.Channel; - -/** - * Factory that creates a new {@link Channel} on {@link Bootstrap#bind()}, {@link Bootstrap#connect()}, and - * {@link ServerBootstrap#bind()}. - */ -public interface ChannelFactory { - /** - * Creates a new channel. - */ - T newChannel(); -} diff --git a/common/src/main/java/common/net/bootstrap/ServerBootstrap.java b/common/src/main/java/common/net/bootstrap/ServerBootstrap.java deleted file mode 100644 index 96144f9..0000000 --- a/common/src/main/java/common/net/bootstrap/ServerBootstrap.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.bootstrap; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; - -import common.net.channel.Channel; -import common.net.channel.ChannelConfig; -import common.net.channel.ChannelFuture; -import common.net.channel.ChannelFutureListener; -import common.net.channel.ChannelHandler; -import common.net.channel.ChannelHandlerContext; -import common.net.channel.ChannelInboundHandlerAdapter; -import common.net.channel.ChannelInitializer; -import common.net.channel.ChannelOption; -import common.net.channel.ChannelPipeline; -import common.net.channel.EventLoopGroup; -import common.net.channel.ServerChannel; -import common.net.util.AttributeKey; -import common.net.util.internal.StringUtil; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * {@link Bootstrap} sub-class which allows easy bootstrap of {@link ServerChannel} - * - */ -public final class ServerBootstrap extends AbstractBootstrap { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(ServerBootstrap.class); - - private final Map, Object> childOptions = new LinkedHashMap, Object>(); - private final Map, Object> childAttrs = new LinkedHashMap, Object>(); - private volatile EventLoopGroup childGroup; - private volatile ChannelHandler childHandler; - - public ServerBootstrap() { } - - private ServerBootstrap(ServerBootstrap bootstrap) { - super(bootstrap); - childGroup = bootstrap.childGroup; - childHandler = bootstrap.childHandler; - synchronized (bootstrap.childOptions) { - childOptions.putAll(bootstrap.childOptions); - } - synchronized (bootstrap.childAttrs) { - childAttrs.putAll(bootstrap.childAttrs); - } - } - - /** - * Specify the {@link EventLoopGroup} which is used for the parent (acceptor) and the child (client). - */ - @Override - public ServerBootstrap group(EventLoopGroup group) { - return group(group, group); - } - - /** - * Set the {@link EventLoopGroup} for the parent (acceptor) and the child (client). These - * {@link EventLoopGroup}'s are used to handle all the events and IO for {@link SocketChannel} and - * {@link Channel}'s. - */ - public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) { - super.group(parentGroup); - if (childGroup == null) { - throw new NullPointerException("childGroup"); - } - if (this.childGroup != null) { - throw new IllegalStateException("childGroup set already"); - } - this.childGroup = childGroup; - return this; - } - - /** - * Allow to specify a {@link ChannelOption} which is used for the {@link Channel} instances once they get created - * (after the acceptor accepted the {@link Channel}). Use a value of {@code null} to remove a previous set - * {@link ChannelOption}. - */ - public ServerBootstrap childOption(ChannelOption childOption, T value) { - if (childOption == null) { - throw new NullPointerException("childOption"); - } - if (value == null) { - synchronized (childOptions) { - childOptions.remove(childOption); - } - } else { - synchronized (childOptions) { - childOptions.put(childOption, value); - } - } - return this; - } - - /** - * Set the specific {@link AttributeKey} with the given value on every child {@link Channel}. If the value is - * {@code null} the {@link AttributeKey} is removed - */ - public ServerBootstrap childAttr(AttributeKey childKey, T value) { - if (childKey == null) { - throw new NullPointerException("childKey"); - } - if (value == null) { - childAttrs.remove(childKey); - } else { - childAttrs.put(childKey, value); - } - return this; - } - - /** - * Set the {@link ChannelHandler} which is used to serve the request for the {@link Channel}'s. - */ - public ServerBootstrap childHandler(ChannelHandler childHandler) { - if (childHandler == null) { - throw new NullPointerException("childHandler"); - } - this.childHandler = childHandler; - return this; - } - - /** - * Return the configured {@link EventLoopGroup} which will be used for the child channels or {@code null} - * if non is configured yet. - */ - public EventLoopGroup childGroup() { - return childGroup; - } - - @Override - void init(Channel channel) throws Exception { - final Map, Object> options = options(); - synchronized (options) { - channel.config().setOptions(options); - } - - final Map, Object> attrs = attrs(); - synchronized (attrs) { - for (Entry, Object> e: attrs.entrySet()) { - - AttributeKey key = (AttributeKey) e.getKey(); - channel.attr(key).set(e.getValue()); - } - } - - ChannelPipeline p = channel.pipeline(); - if (handler() != null) { - p.addLast(handler()); - } - - final EventLoopGroup currentChildGroup = childGroup; - final ChannelHandler currentChildHandler = childHandler; - final Entry, Object>[] currentChildOptions; - final Entry, Object>[] currentChildAttrs; - synchronized (childOptions) { - currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size())); - } - synchronized (childAttrs) { - currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size())); - } - - p.addLast(new ChannelInitializer() { - @Override - public void initChannel(Channel ch) throws Exception { - ch.pipeline().addLast(new ServerBootstrapAcceptor( - currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs)); - } - }); - } - - @Override - public ServerBootstrap validate() { - super.validate(); - if (childHandler == null) { - throw new IllegalStateException("childHandler not set"); - } - if (childGroup == null) { - logger.warn("childGroup is not set. Using parentGroup instead."); - childGroup = group(); - } - return this; - } - - - private static Entry, Object>[] newOptionArray(int size) { - return new Entry[size]; - } - - - private static Entry, Object>[] newAttrArray(int size) { - return new Entry[size]; - } - - private static class ServerBootstrapAcceptor extends ChannelInboundHandlerAdapter { - - private final EventLoopGroup childGroup; - private final ChannelHandler childHandler; - private final Entry, Object>[] childOptions; - private final Entry, Object>[] childAttrs; - - ServerBootstrapAcceptor( - EventLoopGroup childGroup, ChannelHandler childHandler, - Entry, Object>[] childOptions, Entry, Object>[] childAttrs) { - this.childGroup = childGroup; - this.childHandler = childHandler; - this.childOptions = childOptions; - this.childAttrs = childAttrs; - } - - @Override - - public void channelRead(ChannelHandlerContext ctx, Object msg) { - final Channel child = (Channel) msg; - - child.pipeline().addLast(childHandler); - - for (Entry, Object> e: childOptions) { - try { - if (!child.config().setOption((ChannelOption) e.getKey(), e.getValue())) { - logger.warn("Unknown channel option: " + e); - } - } catch (Throwable t) { - logger.warn("Failed to set a channel option: " + child, t); - } - } - - for (Entry, Object> e: childAttrs) { - child.attr((AttributeKey) e.getKey()).set(e.getValue()); - } - - try { - childGroup.register(child).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (!future.isSuccess()) { - forceClose(child, future.cause()); - } - } - }); - } catch (Throwable t) { - forceClose(child, t); - } - } - - private static void forceClose(Channel child, Throwable t) { - child.unsafe().closeForcibly(); - logger.warn("Failed to register an accepted channel: " + child, t); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - final ChannelConfig config = ctx.channel().config(); - if (config.isAutoRead()) { - // stop accept new connections for 1 second to allow the channel to recover - // See https://github.com/netty/netty/issues/1328 - config.setAutoRead(false); - ctx.channel().eventLoop().schedule(new Runnable() { - @Override - public void run() { - config.setAutoRead(true); - } - }, 1, TimeUnit.SECONDS); - } - // still let the exceptionCaught event flow through the pipeline to give the user - // a chance to do something with it - ctx.fireExceptionCaught(cause); - } - } - - @Override - - public ServerBootstrap clone() { - return new ServerBootstrap(this); - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(super.toString()); - buf.setLength(buf.length() - 1); - buf.append(", "); - if (childGroup != null) { - buf.append("childGroup: "); - buf.append(StringUtil.simpleClassName(childGroup)); - buf.append(", "); - } - synchronized (childOptions) { - if (!childOptions.isEmpty()) { - buf.append("childOptions: "); - buf.append(childOptions); - buf.append(", "); - } - } - synchronized (childAttrs) { - if (!childAttrs.isEmpty()) { - buf.append("childAttrs: "); - buf.append(childAttrs); - buf.append(", "); - } - } - if (childHandler != null) { - buf.append("childHandler: "); - buf.append(childHandler); - buf.append(", "); - } - if (buf.charAt(buf.length() - 1) == '(') { - buf.append(')'); - } else { - buf.setCharAt(buf.length() - 2, ')'); - buf.setLength(buf.length() - 1); - } - - return buf.toString(); - } -} diff --git a/common/src/main/java/common/net/buffer/AbstractByteBuf.java b/common/src/main/java/common/net/buffer/AbstractByteBuf.java deleted file mode 100644 index 5c0676f..0000000 --- a/common/src/main/java/common/net/buffer/AbstractByteBuf.java +++ /dev/null @@ -1,1190 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; -import java.nio.charset.Charset; - -import common.net.util.IllegalReferenceCountException; -import common.net.util.ResourceLeakDetector; -import common.net.util.internal.StringUtil; -import common.util.Util; - - -/** - * A skeletal implementation of a buffer. - */ -public abstract class AbstractByteBuf extends ByteBuf { - - static final ResourceLeakDetector leakDetector = new ResourceLeakDetector(ByteBuf.class); - - int readerIndex; - int writerIndex; - private int markedReaderIndex; - private int markedWriterIndex; - - private int maxCapacity; - - private SwappedByteBuf swappedBuf; - - protected AbstractByteBuf(int maxCapacity) { - if (maxCapacity < 0) { - throw new IllegalArgumentException("maxCapacity: " + maxCapacity + " (expected: >= 0)"); - } - this.maxCapacity = maxCapacity; - } - - @Override - public int maxCapacity() { - return maxCapacity; - } - - protected final void maxCapacity(int maxCapacity) { - this.maxCapacity = maxCapacity; - } - - @Override - public int readerIndex() { - return readerIndex; - } - - @Override - public ByteBuf readerIndex(int readerIndex) { - if (readerIndex < 0 || readerIndex > writerIndex) { - throw new IndexOutOfBoundsException(String.format( - "readerIndex: %d (expected: 0 <= readerIndex <= writerIndex(%d))", readerIndex, writerIndex)); - } - this.readerIndex = readerIndex; - return this; - } - - @Override - public int writerIndex() { - return writerIndex; - } - - @Override - public ByteBuf writerIndex(int writerIndex) { - if (writerIndex < readerIndex || writerIndex > capacity()) { - throw new IndexOutOfBoundsException(String.format( - "writerIndex: %d (expected: readerIndex(%d) <= writerIndex <= capacity(%d))", - writerIndex, readerIndex, capacity())); - } - this.writerIndex = writerIndex; - return this; - } - - @Override - public ByteBuf setIndex(int readerIndex, int writerIndex) { - if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) { - throw new IndexOutOfBoundsException(String.format( - "readerIndex: %d, writerIndex: %d (expected: 0 <= readerIndex <= writerIndex <= capacity(%d))", - readerIndex, writerIndex, capacity())); - } - this.readerIndex = readerIndex; - this.writerIndex = writerIndex; - return this; - } - - @Override - public ByteBuf clear() { - readerIndex = writerIndex = 0; - return this; - } - - @Override - public boolean isReadable() { - return writerIndex > readerIndex; - } - - @Override - public boolean isReadable(int numBytes) { - return writerIndex - readerIndex >= numBytes; - } - - @Override - public boolean isWritable() { - return capacity() > writerIndex; - } - - @Override - public boolean isWritable(int numBytes) { - return capacity() - writerIndex >= numBytes; - } - - @Override - public int readableBytes() { - return writerIndex - readerIndex; - } - - @Override - public int writableBytes() { - return capacity() - writerIndex; - } - - @Override - public int maxWritableBytes() { - return maxCapacity() - writerIndex; - } - - @Override - public ByteBuf markReaderIndex() { - markedReaderIndex = readerIndex; - return this; - } - - @Override - public ByteBuf resetReaderIndex() { - readerIndex(markedReaderIndex); - return this; - } - - @Override - public ByteBuf markWriterIndex() { - markedWriterIndex = writerIndex; - return this; - } - - @Override - public ByteBuf resetWriterIndex() { - writerIndex = markedWriterIndex; - return this; - } - - @Override - public ByteBuf discardReadBytes() { - ensureAccessible(); - if (readerIndex == 0) { - return this; - } - - if (readerIndex != writerIndex) { - setBytes(0, this, readerIndex, writerIndex - readerIndex); - writerIndex -= readerIndex; - adjustMarkers(readerIndex); - readerIndex = 0; - } else { - adjustMarkers(readerIndex); - writerIndex = readerIndex = 0; - } - return this; - } - - @Override - public ByteBuf discardSomeReadBytes() { - ensureAccessible(); - if (readerIndex == 0) { - return this; - } - - if (readerIndex == writerIndex) { - adjustMarkers(readerIndex); - writerIndex = readerIndex = 0; - return this; - } - - if (readerIndex >= capacity() >>> 1) { - setBytes(0, this, readerIndex, writerIndex - readerIndex); - writerIndex -= readerIndex; - adjustMarkers(readerIndex); - readerIndex = 0; - } - return this; - } - - protected final void adjustMarkers(int decrement) { - int markedReaderIndex = this.markedReaderIndex; - if (markedReaderIndex <= decrement) { - this.markedReaderIndex = 0; - int markedWriterIndex = this.markedWriterIndex; - if (markedWriterIndex <= decrement) { - this.markedWriterIndex = 0; - } else { - this.markedWriterIndex = markedWriterIndex - decrement; - } - } else { - this.markedReaderIndex = markedReaderIndex - decrement; - markedWriterIndex -= decrement; - } - } - - @Override - public ByteBuf ensureWritable(int minWritableBytes) { - if (minWritableBytes < 0) { - throw new IllegalArgumentException(String.format( - "minWritableBytes: %d (expected: >= 0)", minWritableBytes)); - } - - if (minWritableBytes <= writableBytes()) { - return this; - } - - if (minWritableBytes > maxCapacity - writerIndex) { - throw new IndexOutOfBoundsException(String.format( - "writerIndex(%d) + minWritableBytes(%d) exceeds maxCapacity(%d): %s", - writerIndex, minWritableBytes, maxCapacity, this)); - } - - // Normalize the current capacity to the power of 2. - int newCapacity = calculateNewCapacity(writerIndex + minWritableBytes); - - // Adjust to the new capacity. - capacity(newCapacity); - return this; - } - - @Override - public int ensureWritable(int minWritableBytes, boolean force) { - if (minWritableBytes < 0) { - throw new IllegalArgumentException(String.format( - "minWritableBytes: %d (expected: >= 0)", minWritableBytes)); - } - - if (minWritableBytes <= writableBytes()) { - return 0; - } - - if (minWritableBytes > maxCapacity - writerIndex) { - if (force) { - if (capacity() == maxCapacity()) { - return 1; - } - - capacity(maxCapacity()); - return 3; - } - } - - // Normalize the current capacity to the power of 2. - int newCapacity = calculateNewCapacity(writerIndex + minWritableBytes); - - // Adjust to the new capacity. - capacity(newCapacity); - return 2; - } - - private int calculateNewCapacity(int minNewCapacity) { - final int maxCapacity = this.maxCapacity; - final int threshold = 1048576 * 4; // 4 MiB page - - if (minNewCapacity == threshold) { - return threshold; - } - - // If over threshold, do not double but just increase by threshold. - if (minNewCapacity > threshold) { - int newCapacity = minNewCapacity / threshold * threshold; - if (newCapacity > maxCapacity - threshold) { - newCapacity = maxCapacity; - } else { - newCapacity += threshold; - } - return newCapacity; - } - - // Not over threshold. Double up to 4 MiB, starting from 64. - int newCapacity = 64; - while (newCapacity < minNewCapacity) { - newCapacity <<= 1; - } - - return Math.min(newCapacity, maxCapacity); - } - - @Override - public ByteBuf order(ByteOrder endianness) { - if (endianness == null) { - throw new NullPointerException("endianness"); - } - if (endianness == order()) { - return this; - } - - SwappedByteBuf swappedBuf = this.swappedBuf; - if (swappedBuf == null) { - this.swappedBuf = swappedBuf = newSwappedByteBuf(); - } - return swappedBuf; - } - - /** - * Creates a new {@link SwappedByteBuf} for this {@link ByteBuf} instance. - */ - protected SwappedByteBuf newSwappedByteBuf() { - return new SwappedByteBuf(this); - } - - @Override - public byte getByte(int index) { - checkIndex(index); - return _getByte(index); - } - - protected abstract byte _getByte(int index); - - @Override - public boolean getBoolean(int index) { - return getByte(index) != 0; - } - - @Override - public short getUnsignedByte(int index) { - return (short) (getByte(index) & 0xFF); - } - - @Override - public short getShort(int index) { - checkIndex(index, 2); - return _getShort(index); - } - - protected abstract short _getShort(int index); - - @Override - public int getUnsignedShort(int index) { - return getShort(index) & 0xFFFF; - } - - @Override - public int getUnsignedMedium(int index) { - checkIndex(index, 3); - return _getUnsignedMedium(index); - } - - protected abstract int _getUnsignedMedium(int index); - - @Override - public int getMedium(int index) { - int value = getUnsignedMedium(index); - if ((value & 0x800000) != 0) { - value |= 0xff000000; - } - return value; - } - - @Override - public int getInt(int index) { - checkIndex(index, 4); - return _getInt(index); - } - - protected abstract int _getInt(int index); - - @Override - public long getUnsignedInt(int index) { - return getInt(index) & 0xFFFFFFFFL; - } - - @Override - public long getLong(int index) { - checkIndex(index, 8); - return _getLong(index); - } - - protected abstract long _getLong(int index); - - @Override - public char getChar(int index) { - return (char) getShort(index); - } - - @Override - public float getFloat(int index) { - return Float.intBitsToFloat(getInt(index)); - } - - @Override - public double getDouble(int index) { - return Double.longBitsToDouble(getLong(index)); - } - - @Override - public ByteBuf getBytes(int index, byte[] dst) { - getBytes(index, dst, 0, dst.length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst) { - getBytes(index, dst, dst.writableBytes()); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int length) { - getBytes(index, dst, dst.writerIndex(), length); - dst.writerIndex(dst.writerIndex() + length); - return this; - } - - @Override - public ByteBuf setByte(int index, int value) { - checkIndex(index); - _setByte(index, value); - return this; - } - - protected abstract void _setByte(int index, int value); - - @Override - public ByteBuf setBoolean(int index, boolean value) { - setByte(index, value ? 1 : 0); - return this; - } - - @Override - public ByteBuf setShort(int index, int value) { - checkIndex(index, 2); - _setShort(index, value); - return this; - } - - protected abstract void _setShort(int index, int value); - - @Override - public ByteBuf setChar(int index, int value) { - setShort(index, value); - return this; - } - - @Override - public ByteBuf setMedium(int index, int value) { - checkIndex(index, 3); - _setMedium(index, value); - return this; - } - - protected abstract void _setMedium(int index, int value); - - @Override - public ByteBuf setInt(int index, int value) { - checkIndex(index, 4); - _setInt(index, value); - return this; - } - - protected abstract void _setInt(int index, int value); - - @Override - public ByteBuf setFloat(int index, float value) { - setInt(index, Float.floatToRawIntBits(value)); - return this; - } - - @Override - public ByteBuf setLong(int index, long value) { - checkIndex(index, 8); - _setLong(index, value); - return this; - } - - protected abstract void _setLong(int index, long value); - - @Override - public ByteBuf setDouble(int index, double value) { - setLong(index, Double.doubleToRawLongBits(value)); - return this; - } - - @Override - public ByteBuf setBytes(int index, byte[] src) { - setBytes(index, src, 0, src.length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src) { - setBytes(index, src, src.readableBytes()); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int length) { - checkIndex(index, length); - if (src == null) { - throw new NullPointerException("src"); - } - if (length > src.readableBytes()) { - throw new IndexOutOfBoundsException(String.format( - "length(%d) exceeds src.readableBytes(%d) where src is: %s", length, src.readableBytes(), src)); - } - - setBytes(index, src, src.readerIndex(), length); - src.readerIndex(src.readerIndex() + length); - return this; - } - - @Override - public ByteBuf setZero(int index, int length) { - if (length == 0) { - return this; - } - - checkIndex(index, length); - - int nLong = length >>> 3; - int nBytes = length & 7; - for (int i = nLong; i > 0; i --) { - setLong(index, 0); - index += 8; - } - if (nBytes == 4) { - setInt(index, 0); - } else if (nBytes < 4) { - for (int i = nBytes; i > 0; i --) { - setByte(index, (byte) 0); - index ++; - } - } else { - setInt(index, 0); - index += 4; - for (int i = nBytes - 4; i > 0; i --) { - setByte(index, (byte) 0); - index ++; - } - } - return this; - } - - @Override - public byte readByte() { - checkReadableBytes(1); - int i = readerIndex; - byte b = getByte(i); - readerIndex = i + 1; - return b; - } - - @Override - public boolean readBoolean() { - return readByte() != 0; - } - - @Override - public short readUnsignedByte() { - return (short) (readByte() & 0xFF); - } - - @Override - public short readShort() { - checkReadableBytes(2); - short v = _getShort(readerIndex); - readerIndex += 2; - return v; - } - - @Override - public int readUnsignedShort() { - return readShort() & 0xFFFF; - } - - @Override - public int readMedium() { - int value = readUnsignedMedium(); - if ((value & 0x800000) != 0) { - value |= 0xff000000; - } - return value; - } - - @Override - public int readUnsignedMedium() { - checkReadableBytes(3); - int v = _getUnsignedMedium(readerIndex); - readerIndex += 3; - return v; - } - - @Override - public int readInt() { - checkReadableBytes(4); - int v = _getInt(readerIndex); - readerIndex += 4; - return v; - } - - @Override - public long readUnsignedInt() { - return readInt() & 0xFFFFFFFFL; - } - - @Override - public long readLong() { - checkReadableBytes(8); - long v = _getLong(readerIndex); - readerIndex += 8; - return v; - } - - @Override - public char readChar() { - return (char) readShort(); - } - - @Override - public float readFloat() { - return Float.intBitsToFloat(readInt()); - } - - @Override - public double readDouble() { - return Double.longBitsToDouble(readLong()); - } - - @Override - public ByteBuf readBytes(int length) { - checkReadableBytes(length); - if (length == 0) { - return Unpooled.EMPTY_BUFFER; - } - - // Use an unpooled heap buffer because there's no way to mandate a user to free the returned buffer. - ByteBuf buf = Unpooled.buffer(length, maxCapacity); - buf.writeBytes(this, readerIndex, length); - readerIndex += length; - return buf; - } - - @Override - public ByteBuf readSlice(int length) { - ByteBuf slice = slice(readerIndex, length); - readerIndex += length; - return slice; - } - - @Override - public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { - checkReadableBytes(length); - getBytes(readerIndex, dst, dstIndex, length); - readerIndex += length; - return this; - } - - @Override - public ByteBuf readBytes(byte[] dst) { - readBytes(dst, 0, dst.length); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuf dst) { - readBytes(dst, dst.writableBytes()); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int length) { - if (length > dst.writableBytes()) { - throw new IndexOutOfBoundsException(String.format( - "length(%d) exceeds dst.writableBytes(%d) where dst is: %s", length, dst.writableBytes(), dst)); - } - readBytes(dst, dst.writerIndex(), length); - dst.writerIndex(dst.writerIndex() + length); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { - checkReadableBytes(length); - getBytes(readerIndex, dst, dstIndex, length); - readerIndex += length; - return this; - } - - @Override - public ByteBuf readBytes(ByteBuffer dst) { - int length = dst.remaining(); - checkReadableBytes(length); - getBytes(readerIndex, dst); - readerIndex += length; - return this; - } - - @Override - public int readBytes(GatheringByteChannel out, int length) - throws IOException { - checkReadableBytes(length); - int readBytes = getBytes(readerIndex, out, length); - readerIndex += readBytes; - return readBytes; - } - - @Override - public ByteBuf readBytes(OutputStream out, int length) throws IOException { - checkReadableBytes(length); - getBytes(readerIndex, out, length); - readerIndex += length; - return this; - } - - @Override - public ByteBuf skipBytes(int length) { - checkReadableBytes(length); - readerIndex += length; - return this; - } - - @Override - public ByteBuf writeBoolean(boolean value) { - writeByte(value ? 1 : 0); - return this; - } - - @Override - public ByteBuf writeByte(int value) { - ensureAccessible(); - ensureWritable(1); - _setByte(writerIndex++, value); - return this; - } - - @Override - public ByteBuf writeShort(int value) { - ensureAccessible(); - ensureWritable(2); - _setShort(writerIndex, value); - writerIndex += 2; - return this; - } - - @Override - public ByteBuf writeMedium(int value) { - ensureAccessible(); - ensureWritable(3); - _setMedium(writerIndex, value); - writerIndex += 3; - return this; - } - - @Override - public ByteBuf writeInt(int value) { - ensureAccessible(); - ensureWritable(4); - _setInt(writerIndex, value); - writerIndex += 4; - return this; - } - - @Override - public ByteBuf writeLong(long value) { - ensureAccessible(); - ensureWritable(8); - _setLong(writerIndex, value); - writerIndex += 8; - return this; - } - - @Override - public ByteBuf writeChar(int value) { - writeShort(value); - return this; - } - - @Override - public ByteBuf writeFloat(float value) { - writeInt(Float.floatToRawIntBits(value)); - return this; - } - - @Override - public ByteBuf writeDouble(double value) { - writeLong(Double.doubleToRawLongBits(value)); - return this; - } - - @Override - public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { - ensureAccessible(); - ensureWritable(length); - setBytes(writerIndex, src, srcIndex, length); - writerIndex += length; - return this; - } - - @Override - public ByteBuf writeBytes(byte[] src) { - writeBytes(src, 0, src.length); - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuf src) { - writeBytes(src, src.readableBytes()); - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuf src, int length) { - if (length > src.readableBytes()) { - throw new IndexOutOfBoundsException(String.format( - "length(%d) exceeds src.readableBytes(%d) where src is: %s", length, src.readableBytes(), src)); - } - writeBytes(src, src.readerIndex(), length); - src.readerIndex(src.readerIndex() + length); - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { - ensureAccessible(); - ensureWritable(length); - setBytes(writerIndex, src, srcIndex, length); - writerIndex += length; - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuffer src) { - ensureAccessible(); - int length = src.remaining(); - ensureWritable(length); - setBytes(writerIndex, src); - writerIndex += length; - return this; - } - - @Override - public int writeBytes(InputStream in, int length) - throws IOException { - ensureAccessible(); - ensureWritable(length); - int writtenBytes = setBytes(writerIndex, in, length); - if (writtenBytes > 0) { - writerIndex += writtenBytes; - } - return writtenBytes; - } - - @Override - public int writeBytes(ScatteringByteChannel in, int length) throws IOException { - ensureAccessible(); - ensureWritable(length); - int writtenBytes = setBytes(writerIndex, in, length); - if (writtenBytes > 0) { - writerIndex += writtenBytes; - } - return writtenBytes; - } - - @Override - public ByteBuf writeZero(int length) { - if (length == 0) { - return this; - } - - ensureWritable(length); - checkIndex(writerIndex, length); - - int nLong = length >>> 3; - int nBytes = length & 7; - for (int i = nLong; i > 0; i --) { - writeLong(0); - } - if (nBytes == 4) { - writeInt(0); - } else if (nBytes < 4) { - for (int i = nBytes; i > 0; i --) { - writeByte((byte) 0); - } - } else { - writeInt(0); - for (int i = nBytes - 4; i > 0; i --) { - writeByte((byte) 0); - } - } - return this; - } - - @Override - public ByteBuf copy() { - return copy(readerIndex, readableBytes()); - } - - @Override - public ByteBuf duplicate() { - return new DuplicatedByteBuf(this); - } - - @Override - public ByteBuf slice() { - return slice(readerIndex, readableBytes()); - } - - @Override - public ByteBuf slice(int index, int length) { - if (length == 0) { - return Unpooled.EMPTY_BUFFER; - } - - return new SlicedByteBuf(this, index, length); - } - - @Override - public ByteBuffer nioBuffer() { - return nioBuffer(readerIndex, readableBytes()); - } - - @Override - public ByteBuffer[] nioBuffers() { - return nioBuffers(readerIndex, readableBytes()); - } - - @Override - public String toString(Charset charset) { - return toString(readerIndex, readableBytes(), charset); - } - - @Override - public String toString(int index, int length, Charset charset) { - if (length == 0) { - return ""; - } - - ByteBuffer nioBuffer; - if (nioBufferCount() == 1) { - nioBuffer = nioBuffer(index, length); - } else { - nioBuffer = ByteBuffer.allocate(length); - getBytes(index, nioBuffer); - nioBuffer.flip(); - } - - return ByteBufUtil.decodeString(nioBuffer, charset); - } - - @Override - public int indexOf(int fromIndex, int toIndex, byte value) { - return ByteBufUtil.indexOf(this, fromIndex, toIndex, value); - } - - @Override - public int bytesBefore(byte value) { - return bytesBefore(readerIndex(), readableBytes(), value); - } - - @Override - public int bytesBefore(int length, byte value) { - checkReadableBytes(length); - return bytesBefore(readerIndex(), length, value); - } - - @Override - public int bytesBefore(int index, int length, byte value) { - int endIndex = indexOf(index, index + length, value); - if (endIndex < 0) { - return -1; - } - return endIndex - index; - } - - @Override - public int forEachByte(ByteBufProcessor processor) { - int index = readerIndex; - int length = writerIndex - index; - ensureAccessible(); - return forEachByteAsc0(index, length, processor); - } - - @Override - public int forEachByte(int index, int length, ByteBufProcessor processor) { - checkIndex(index, length); - return forEachByteAsc0(index, length, processor); - } - - private int forEachByteAsc0(int index, int length, ByteBufProcessor processor) { - if (processor == null) { - throw new NullPointerException("processor"); - } - - if (length == 0) { - return -1; - } - - final int endIndex = index + length; - int i = index; - try { - do { - if (processor.process(_getByte(i))) { - i ++; - } else { - return i; - } - } while (i < endIndex); - } catch (Exception e) { - Util.throwUnchecked(e); - } - - return -1; - } - - @Override - public int forEachByteDesc(ByteBufProcessor processor) { - int index = readerIndex; - int length = writerIndex - index; - ensureAccessible(); - return forEachByteDesc0(index, length, processor); - } - - @Override - public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { - checkIndex(index, length); - - return forEachByteDesc0(index, length, processor); - } - - private int forEachByteDesc0(int index, int length, ByteBufProcessor processor) { - - if (processor == null) { - throw new NullPointerException("processor"); - } - - if (length == 0) { - return -1; - } - - int i = index + length - 1; - try { - do { - if (processor.process(_getByte(i))) { - i --; - } else { - return i; - } - } while (i >= index); - } catch (Exception e) { - Util.throwUnchecked(e); - } - - return -1; - } - - @Override - public int hashCode() { - return ByteBufUtil.hashCode(this); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o instanceof ByteBuf) { - return ByteBufUtil.equals(this, (ByteBuf) o); - } - return false; - } - - @Override - public int compareTo(ByteBuf that) { - return ByteBufUtil.compare(this, that); - } - - @Override - public String toString() { - if (refCnt() == 0) { - return StringUtil.simpleClassName(this) + "(freed)"; - } - - StringBuilder buf = new StringBuilder(); - buf.append(StringUtil.simpleClassName(this)); - buf.append("(ridx: "); - buf.append(readerIndex); - buf.append(", widx: "); - buf.append(writerIndex); - buf.append(", cap: "); - buf.append(capacity()); - if (maxCapacity != Integer.MAX_VALUE) { - buf.append('/'); - buf.append(maxCapacity); - } - - ByteBuf unwrapped = unwrap(); - if (unwrapped != null) { - buf.append(", unwrapped: "); - buf.append(unwrapped); - } - buf.append(')'); - return buf.toString(); - } - - protected final void checkIndex(int index) { - ensureAccessible(); - if (index < 0 || index >= capacity()) { - throw new IndexOutOfBoundsException(String.format( - "index: %d (expected: range(0, %d))", index, capacity())); - } - } - - protected final void checkIndex(int index, int fieldLength) { - ensureAccessible(); - if (fieldLength < 0) { - throw new IllegalArgumentException("length: " + fieldLength + " (expected: >= 0)"); - } - if (index < 0 || index > capacity() - fieldLength) { - throw new IndexOutOfBoundsException(String.format( - "index: %d, length: %d (expected: range(0, %d))", index, fieldLength, capacity())); - } - } - - protected final void checkSrcIndex(int index, int length, int srcIndex, int srcCapacity) { - checkIndex(index, length); - if (srcIndex < 0 || srcIndex > srcCapacity - length) { - throw new IndexOutOfBoundsException(String.format( - "srcIndex: %d, length: %d (expected: range(0, %d))", srcIndex, length, srcCapacity)); - } - } - - protected final void checkDstIndex(int index, int length, int dstIndex, int dstCapacity) { - checkIndex(index, length); - if (dstIndex < 0 || dstIndex > dstCapacity - length) { - throw new IndexOutOfBoundsException(String.format( - "dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dstCapacity)); - } - } - - /** - * Throws an {@link IndexOutOfBoundsException} if the current - * {@linkplain #readableBytes() readable bytes} of this buffer is less - * than the specified value. - */ - protected final void checkReadableBytes(int minimumReadableBytes) { - ensureAccessible(); - if (minimumReadableBytes < 0) { - throw new IllegalArgumentException("minimumReadableBytes: " + minimumReadableBytes + " (expected: >= 0)"); - } - if (readerIndex > writerIndex - minimumReadableBytes) { - throw new IndexOutOfBoundsException(String.format( - "readerIndex(%d) + length(%d) exceeds writerIndex(%d): %s", - readerIndex, minimumReadableBytes, writerIndex, this)); - } - } - - /** - * Should be called by every method that tries to access the buffers content to check - * if the buffer was released before. - */ - protected final void ensureAccessible() { - if (refCnt() == 0) { - throw new IllegalReferenceCountException(0); - } - } -} diff --git a/common/src/main/java/common/net/buffer/AbstractByteBufAllocator.java b/common/src/main/java/common/net/buffer/AbstractByteBufAllocator.java deleted file mode 100644 index 0b4cc21..0000000 --- a/common/src/main/java/common/net/buffer/AbstractByteBufAllocator.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import common.net.util.ResourceLeak; -import common.net.util.ResourceLeakDetector; -import common.net.util.internal.StringUtil; - -/** - * Skeletal {@link ByteBufAllocator} implementation to extend. - */ -public abstract class AbstractByteBufAllocator implements ByteBufAllocator { - private static final int DEFAULT_INITIAL_CAPACITY = 256; - private static final int DEFAULT_MAX_COMPONENTS = 16; - - protected static ByteBuf toLeakAwareBuffer(ByteBuf buf) { - ResourceLeak leak; - switch (ResourceLeakDetector.getLevel()) { - case SIMPLE: - leak = AbstractByteBuf.leakDetector.open(buf); - if (leak != null) { - buf = new SimpleLeakAwareByteBuf(buf, leak); - } - break; - case ADVANCED: - case PARANOID: - leak = AbstractByteBuf.leakDetector.open(buf); - if (leak != null) { - buf = new AdvancedLeakAwareByteBuf(buf, leak); - } - break; - } - return buf; - } - - private final ByteBuf emptyBuf; - - /** - * Create new instance - * - * @param preferDirect {@code true} if {@link #buffer(int)} should try to allocate a direct buffer rather than - * a heap buffer - */ - protected AbstractByteBufAllocator() { - emptyBuf = new EmptyByteBuf(this); - } - - @Override - public ByteBuf buffer() { - return heapBuffer(); - } - - @Override - public ByteBuf buffer(int initialCapacity) { - return heapBuffer(initialCapacity); - } - - @Override - public ByteBuf buffer(int initialCapacity, int maxCapacity) { - return heapBuffer(initialCapacity, maxCapacity); - } - - @Override - public ByteBuf ioBuffer() { - return heapBuffer(DEFAULT_INITIAL_CAPACITY); - } - - @Override - public ByteBuf ioBuffer(int initialCapacity) { - return heapBuffer(initialCapacity); - } - - @Override - public ByteBuf ioBuffer(int initialCapacity, int maxCapacity) { - return heapBuffer(initialCapacity, maxCapacity); - } - - @Override - public ByteBuf heapBuffer() { - return heapBuffer(DEFAULT_INITIAL_CAPACITY, Integer.MAX_VALUE); - } - - @Override - public ByteBuf heapBuffer(int initialCapacity) { - return heapBuffer(initialCapacity, Integer.MAX_VALUE); - } - - @Override - public ByteBuf heapBuffer(int initialCapacity, int maxCapacity) { - if (initialCapacity == 0 && maxCapacity == 0) { - return emptyBuf; - } - validate(initialCapacity, maxCapacity); - return newHeapBuffer(initialCapacity, maxCapacity); - } - - @Override - public ByteBuf directBuffer() { - return directBuffer(DEFAULT_INITIAL_CAPACITY, Integer.MAX_VALUE); - } - - @Override - public ByteBuf directBuffer(int initialCapacity) { - return directBuffer(initialCapacity, Integer.MAX_VALUE); - } - - @Override - public ByteBuf directBuffer(int initialCapacity, int maxCapacity) { - if (initialCapacity == 0 && maxCapacity == 0) { - return emptyBuf; - } - validate(initialCapacity, maxCapacity); - return newDirectBuffer(initialCapacity, maxCapacity); - } - - @Override - public CompositeByteBuf compositeBuffer() { - return compositeHeapBuffer(); - } - - @Override - public CompositeByteBuf compositeBuffer(int maxNumComponents) { - return compositeHeapBuffer(maxNumComponents); - } - - @Override - public CompositeByteBuf compositeHeapBuffer() { - return compositeHeapBuffer(DEFAULT_MAX_COMPONENTS); - } - - @Override - public CompositeByteBuf compositeHeapBuffer(int maxNumComponents) { - return new CompositeByteBuf(this, false, maxNumComponents); - } - - @Override - public CompositeByteBuf compositeDirectBuffer() { - return compositeDirectBuffer(DEFAULT_MAX_COMPONENTS); - } - - @Override - public CompositeByteBuf compositeDirectBuffer(int maxNumComponents) { - return new CompositeByteBuf(this, true, maxNumComponents); - } - - private static void validate(int initialCapacity, int maxCapacity) { - if (initialCapacity < 0) { - throw new IllegalArgumentException("initialCapacity: " + initialCapacity + " (expectd: 0+)"); - } - if (initialCapacity > maxCapacity) { - throw new IllegalArgumentException(String.format( - "initialCapacity: %d (expected: not greater than maxCapacity(%d)", - initialCapacity, maxCapacity)); - } - } - - /** - * Create a heap {@link ByteBuf} with the given initialCapacity and maxCapacity. - */ - protected abstract ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity); - - /** - * Create a direct {@link ByteBuf} with the given initialCapacity and maxCapacity. - */ - protected abstract ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity); - - @Override - public String toString() { - return StringUtil.simpleClassName(this); - } -} diff --git a/common/src/main/java/common/net/buffer/AbstractDerivedByteBuf.java b/common/src/main/java/common/net/buffer/AbstractDerivedByteBuf.java deleted file mode 100644 index 5fad3e7..0000000 --- a/common/src/main/java/common/net/buffer/AbstractDerivedByteBuf.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import java.nio.ByteBuffer; - -/** - * Abstract base class for {@link ByteBuf} implementations that wrap another - * {@link ByteBuf}. - */ -public abstract class AbstractDerivedByteBuf extends AbstractByteBuf { - - protected AbstractDerivedByteBuf(int maxCapacity) { - super(maxCapacity); - } - - @Override - public final int refCnt() { - return unwrap().refCnt(); - } - - @Override - public final ByteBuf retain() { - unwrap().retain(); - return this; - } - - @Override - public final ByteBuf retain(int increment) { - unwrap().retain(increment); - return this; - } - - @Override - public final boolean release() { - return unwrap().release(); - } - - @Override - public final boolean release(int decrement) { - return unwrap().release(decrement); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - return nioBuffer(index, length); - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - return unwrap().nioBuffer(index, length); - } -} diff --git a/common/src/main/java/common/net/buffer/AbstractReferenceCountedByteBuf.java b/common/src/main/java/common/net/buffer/AbstractReferenceCountedByteBuf.java deleted file mode 100644 index d15a7e2..0000000 --- a/common/src/main/java/common/net/buffer/AbstractReferenceCountedByteBuf.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; - -import common.net.util.IllegalReferenceCountException; - -/** - * Abstract base class for {@link ByteBuf} implementations that count references. - */ -public abstract class AbstractReferenceCountedByteBuf extends AbstractByteBuf { - - private static final AtomicIntegerFieldUpdater refCntUpdater; - - static { - AtomicIntegerFieldUpdater updater = - null; - if (updater == null) { - updater = AtomicIntegerFieldUpdater.newUpdater(AbstractReferenceCountedByteBuf.class, "refCnt"); - } - refCntUpdater = updater; - } - - private volatile int refCnt = 1; - - protected AbstractReferenceCountedByteBuf(int maxCapacity) { - super(maxCapacity); - } - - @Override - public final int refCnt() { - return refCnt; - } - - /** - * An unsafe operation intended for use by a subclass that sets the reference count of the buffer directly - */ - protected final void setRefCnt(int refCnt) { - this.refCnt = refCnt; - } - - @Override - public ByteBuf retain() { - for (;;) { - int refCnt = this.refCnt; - if (refCnt == 0) { - throw new IllegalReferenceCountException(0, 1); - } - if (refCnt == Integer.MAX_VALUE) { - throw new IllegalReferenceCountException(Integer.MAX_VALUE, 1); - } - if (refCntUpdater.compareAndSet(this, refCnt, refCnt + 1)) { - break; - } - } - return this; - } - - @Override - public ByteBuf retain(int increment) { - if (increment <= 0) { - throw new IllegalArgumentException("increment: " + increment + " (expected: > 0)"); - } - - for (;;) { - int refCnt = this.refCnt; - if (refCnt == 0) { - throw new IllegalReferenceCountException(0, increment); - } - if (refCnt > Integer.MAX_VALUE - increment) { - throw new IllegalReferenceCountException(refCnt, increment); - } - if (refCntUpdater.compareAndSet(this, refCnt, refCnt + increment)) { - break; - } - } - return this; - } - - @Override - public final boolean release() { - for (;;) { - int refCnt = this.refCnt; - if (refCnt == 0) { - throw new IllegalReferenceCountException(0, -1); - } - - if (refCntUpdater.compareAndSet(this, refCnt, refCnt - 1)) { - if (refCnt == 1) { - deallocate(); - return true; - } - return false; - } - } - } - - @Override - public final boolean release(int decrement) { - if (decrement <= 0) { - throw new IllegalArgumentException("decrement: " + decrement + " (expected: > 0)"); - } - - for (;;) { - int refCnt = this.refCnt; - if (refCnt < decrement) { - throw new IllegalReferenceCountException(refCnt, -decrement); - } - - if (refCntUpdater.compareAndSet(this, refCnt, refCnt - decrement)) { - if (refCnt == decrement) { - deallocate(); - return true; - } - return false; - } - } - } - - /** - * Called once {@link #refCnt()} is equals 0. - */ - protected abstract void deallocate(); -} diff --git a/common/src/main/java/common/net/buffer/AdvancedLeakAwareByteBuf.java b/common/src/main/java/common/net/buffer/AdvancedLeakAwareByteBuf.java deleted file mode 100644 index 2cd77b6..0000000 --- a/common/src/main/java/common/net/buffer/AdvancedLeakAwareByteBuf.java +++ /dev/null @@ -1,724 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; -import java.nio.charset.Charset; - -import common.net.util.ResourceLeak; - -final class AdvancedLeakAwareByteBuf extends WrappedByteBuf { - - private final ResourceLeak leak; - - AdvancedLeakAwareByteBuf(ByteBuf buf, ResourceLeak leak) { - super(buf); - this.leak = leak; - } - - @Override - public boolean release() { - boolean deallocated = super.release(); - if (deallocated) { - leak.close(); - } else { - leak.record(); - } - return deallocated; - } - - @Override - public boolean release(int decrement) { - boolean deallocated = super.release(decrement); - if (deallocated) { - leak.close(); - } else { - leak.record(); - } - return deallocated; - } - - @Override - public ByteBuf order(ByteOrder endianness) { - leak.record(); - if (order() == endianness) { - return this; - } else { - return new AdvancedLeakAwareByteBuf(super.order(endianness), leak); - } - } - - @Override - public ByteBuf slice() { - leak.record(); - return new AdvancedLeakAwareByteBuf(super.slice(), leak); - } - - @Override - public ByteBuf slice(int index, int length) { - leak.record(); - return new AdvancedLeakAwareByteBuf(super.slice(index, length), leak); - } - - @Override - public ByteBuf duplicate() { - leak.record(); - return new AdvancedLeakAwareByteBuf(super.duplicate(), leak); - } - - @Override - public ByteBuf readSlice(int length) { - leak.record(); - return new AdvancedLeakAwareByteBuf(super.readSlice(length), leak); - } - - @Override - public ByteBuf discardReadBytes() { - leak.record(); - return super.discardReadBytes(); - } - - @Override - public ByteBuf discardSomeReadBytes() { - leak.record(); - return super.discardSomeReadBytes(); - } - - @Override - public ByteBuf ensureWritable(int minWritableBytes) { - leak.record(); - return super.ensureWritable(minWritableBytes); - } - - @Override - public int ensureWritable(int minWritableBytes, boolean force) { - leak.record(); - return super.ensureWritable(minWritableBytes, force); - } - - @Override - public boolean getBoolean(int index) { - leak.record(); - return super.getBoolean(index); - } - - @Override - public byte getByte(int index) { - leak.record(); - return super.getByte(index); - } - - @Override - public short getUnsignedByte(int index) { - leak.record(); - return super.getUnsignedByte(index); - } - - @Override - public short getShort(int index) { - leak.record(); - return super.getShort(index); - } - - @Override - public int getUnsignedShort(int index) { - leak.record(); - return super.getUnsignedShort(index); - } - - @Override - public int getMedium(int index) { - leak.record(); - return super.getMedium(index); - } - - @Override - public int getUnsignedMedium(int index) { - leak.record(); - return super.getUnsignedMedium(index); - } - - @Override - public int getInt(int index) { - leak.record(); - return super.getInt(index); - } - - @Override - public long getUnsignedInt(int index) { - leak.record(); - return super.getUnsignedInt(index); - } - - @Override - public long getLong(int index) { - leak.record(); - return super.getLong(index); - } - - @Override - public char getChar(int index) { - leak.record(); - return super.getChar(index); - } - - @Override - public float getFloat(int index) { - leak.record(); - return super.getFloat(index); - } - - @Override - public double getDouble(int index) { - leak.record(); - return super.getDouble(index); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst) { - leak.record(); - return super.getBytes(index, dst); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int length) { - leak.record(); - return super.getBytes(index, dst, length); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - leak.record(); - return super.getBytes(index, dst, dstIndex, length); - } - - @Override - public ByteBuf getBytes(int index, byte[] dst) { - leak.record(); - return super.getBytes(index, dst); - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - leak.record(); - return super.getBytes(index, dst, dstIndex, length); - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - leak.record(); - return super.getBytes(index, dst); - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { - leak.record(); - return super.getBytes(index, out, length); - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { - leak.record(); - return super.getBytes(index, out, length); - } - - @Override - public ByteBuf setBoolean(int index, boolean value) { - leak.record(); - return super.setBoolean(index, value); - } - - @Override - public ByteBuf setByte(int index, int value) { - leak.record(); - return super.setByte(index, value); - } - - @Override - public ByteBuf setShort(int index, int value) { - leak.record(); - return super.setShort(index, value); - } - - @Override - public ByteBuf setMedium(int index, int value) { - leak.record(); - return super.setMedium(index, value); - } - - @Override - public ByteBuf setInt(int index, int value) { - leak.record(); - return super.setInt(index, value); - } - - @Override - public ByteBuf setLong(int index, long value) { - leak.record(); - return super.setLong(index, value); - } - - @Override - public ByteBuf setChar(int index, int value) { - leak.record(); - return super.setChar(index, value); - } - - @Override - public ByteBuf setFloat(int index, float value) { - leak.record(); - return super.setFloat(index, value); - } - - @Override - public ByteBuf setDouble(int index, double value) { - leak.record(); - return super.setDouble(index, value); - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src) { - leak.record(); - return super.setBytes(index, src); - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int length) { - leak.record(); - return super.setBytes(index, src, length); - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - leak.record(); - return super.setBytes(index, src, srcIndex, length); - } - - @Override - public ByteBuf setBytes(int index, byte[] src) { - leak.record(); - return super.setBytes(index, src); - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - leak.record(); - return super.setBytes(index, src, srcIndex, length); - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - leak.record(); - return super.setBytes(index, src); - } - - @Override - public int setBytes(int index, InputStream in, int length) throws IOException { - leak.record(); - return super.setBytes(index, in, length); - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { - leak.record(); - return super.setBytes(index, in, length); - } - - @Override - public ByteBuf setZero(int index, int length) { - leak.record(); - return super.setZero(index, length); - } - - @Override - public boolean readBoolean() { - leak.record(); - return super.readBoolean(); - } - - @Override - public byte readByte() { - leak.record(); - return super.readByte(); - } - - @Override - public short readUnsignedByte() { - leak.record(); - return super.readUnsignedByte(); - } - - @Override - public short readShort() { - leak.record(); - return super.readShort(); - } - - @Override - public int readUnsignedShort() { - leak.record(); - return super.readUnsignedShort(); - } - - @Override - public int readMedium() { - leak.record(); - return super.readMedium(); - } - - @Override - public int readUnsignedMedium() { - leak.record(); - return super.readUnsignedMedium(); - } - - @Override - public int readInt() { - leak.record(); - return super.readInt(); - } - - @Override - public long readUnsignedInt() { - leak.record(); - return super.readUnsignedInt(); - } - - @Override - public long readLong() { - leak.record(); - return super.readLong(); - } - - @Override - public char readChar() { - leak.record(); - return super.readChar(); - } - - @Override - public float readFloat() { - leak.record(); - return super.readFloat(); - } - - @Override - public double readDouble() { - leak.record(); - return super.readDouble(); - } - - @Override - public ByteBuf readBytes(int length) { - leak.record(); - return super.readBytes(length); - } - - @Override - public ByteBuf readBytes(ByteBuf dst) { - leak.record(); - return super.readBytes(dst); - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int length) { - leak.record(); - return super.readBytes(dst, length); - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { - leak.record(); - return super.readBytes(dst, dstIndex, length); - } - - @Override - public ByteBuf readBytes(byte[] dst) { - leak.record(); - return super.readBytes(dst); - } - - @Override - public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { - leak.record(); - return super.readBytes(dst, dstIndex, length); - } - - @Override - public ByteBuf readBytes(ByteBuffer dst) { - leak.record(); - return super.readBytes(dst); - } - - @Override - public ByteBuf readBytes(OutputStream out, int length) throws IOException { - leak.record(); - return super.readBytes(out, length); - } - - @Override - public int readBytes(GatheringByteChannel out, int length) throws IOException { - leak.record(); - return super.readBytes(out, length); - } - - @Override - public ByteBuf skipBytes(int length) { - leak.record(); - return super.skipBytes(length); - } - - @Override - public ByteBuf writeBoolean(boolean value) { - leak.record(); - return super.writeBoolean(value); - } - - @Override - public ByteBuf writeByte(int value) { - leak.record(); - return super.writeByte(value); - } - - @Override - public ByteBuf writeShort(int value) { - leak.record(); - return super.writeShort(value); - } - - @Override - public ByteBuf writeMedium(int value) { - leak.record(); - return super.writeMedium(value); - } - - @Override - public ByteBuf writeInt(int value) { - leak.record(); - return super.writeInt(value); - } - - @Override - public ByteBuf writeLong(long value) { - leak.record(); - return super.writeLong(value); - } - - @Override - public ByteBuf writeChar(int value) { - leak.record(); - return super.writeChar(value); - } - - @Override - public ByteBuf writeFloat(float value) { - leak.record(); - return super.writeFloat(value); - } - - @Override - public ByteBuf writeDouble(double value) { - leak.record(); - return super.writeDouble(value); - } - - @Override - public ByteBuf writeBytes(ByteBuf src) { - leak.record(); - return super.writeBytes(src); - } - - @Override - public ByteBuf writeBytes(ByteBuf src, int length) { - leak.record(); - return super.writeBytes(src, length); - } - - @Override - public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { - leak.record(); - return super.writeBytes(src, srcIndex, length); - } - - @Override - public ByteBuf writeBytes(byte[] src) { - leak.record(); - return super.writeBytes(src); - } - - @Override - public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { - leak.record(); - return super.writeBytes(src, srcIndex, length); - } - - @Override - public ByteBuf writeBytes(ByteBuffer src) { - leak.record(); - return super.writeBytes(src); - } - - @Override - public int writeBytes(InputStream in, int length) throws IOException { - leak.record(); - return super.writeBytes(in, length); - } - - @Override - public int writeBytes(ScatteringByteChannel in, int length) throws IOException { - leak.record(); - return super.writeBytes(in, length); - } - - @Override - public ByteBuf writeZero(int length) { - leak.record(); - return super.writeZero(length); - } - - @Override - public int indexOf(int fromIndex, int toIndex, byte value) { - leak.record(); - return super.indexOf(fromIndex, toIndex, value); - } - - @Override - public int bytesBefore(byte value) { - leak.record(); - return super.bytesBefore(value); - } - - @Override - public int bytesBefore(int length, byte value) { - leak.record(); - return super.bytesBefore(length, value); - } - - @Override - public int bytesBefore(int index, int length, byte value) { - leak.record(); - return super.bytesBefore(index, length, value); - } - - @Override - public int forEachByte(ByteBufProcessor processor) { - leak.record(); - return super.forEachByte(processor); - } - - @Override - public int forEachByte(int index, int length, ByteBufProcessor processor) { - leak.record(); - return super.forEachByte(index, length, processor); - } - - @Override - public int forEachByteDesc(ByteBufProcessor processor) { - leak.record(); - return super.forEachByteDesc(processor); - } - - @Override - public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { - leak.record(); - return super.forEachByteDesc(index, length, processor); - } - - @Override - public ByteBuf copy() { - leak.record(); - return super.copy(); - } - - @Override - public ByteBuf copy(int index, int length) { - leak.record(); - return super.copy(index, length); - } - - @Override - public int nioBufferCount() { - leak.record(); - return super.nioBufferCount(); - } - - @Override - public ByteBuffer nioBuffer() { - leak.record(); - return super.nioBuffer(); - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - leak.record(); - return super.nioBuffer(index, length); - } - - @Override - public ByteBuffer[] nioBuffers() { - leak.record(); - return super.nioBuffers(); - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - leak.record(); - return super.nioBuffers(index, length); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - leak.record(); - return super.internalNioBuffer(index, length); - } - - @Override - public String toString(Charset charset) { - leak.record(); - return super.toString(charset); - } - - @Override - public String toString(int index, int length, Charset charset) { - leak.record(); - return super.toString(index, length, charset); - } - - @Override - public ByteBuf retain() { - leak.record(); - return super.retain(); - } - - @Override - public ByteBuf retain(int increment) { - leak.record(); - return super.retain(increment); - } - - @Override - public ByteBuf capacity(int newCapacity) { - leak.record(); - return super.capacity(newCapacity); - } -} diff --git a/common/src/main/java/common/net/buffer/ByteBuf.java b/common/src/main/java/common/net/buffer/ByteBuf.java deleted file mode 100644 index fabaf0c..0000000 --- a/common/src/main/java/common/net/buffer/ByteBuf.java +++ /dev/null @@ -1,1875 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; -import java.nio.charset.Charset; - -import common.net.util.ReferenceCounted; - -/** - * A random and sequential accessible sequence of zero or more bytes (octets). - * This interface provides an abstract view for one or more primitive byte - * arrays ({@code byte[]}) and {@linkplain ByteBuffer NIO buffers}. - * - *

Creation of a buffer

- * - * It is recommended to create a new buffer using the helper methods in - * {@link Unpooled} rather than calling an individual implementation's - * constructor. - * - *

Random Access Indexing

- * - * Just like an ordinary primitive byte array, {@link ByteBuf} uses - * zero-based indexing. - * It means the index of the first byte is always {@code 0} and the index of the last byte is - * always {@link #capacity() capacity - 1}. For example, to iterate all bytes of a buffer, you - * can do the following, regardless of its internal implementation: - * - *
- * {@link ByteBuf} buffer = ...;
- * for (int i = 0; i < buffer.capacity(); i ++) {
- *     byte b = buffer.getByte(i);
- *     System.out.println((char) b);
- * }
- * 
- * - *

Sequential Access Indexing

- * - * {@link ByteBuf} provides two pointer variables to support sequential - * read and write operations - {@link #readerIndex() readerIndex} for a read - * operation and {@link #writerIndex() writerIndex} for a write operation - * respectively. The following diagram shows how a buffer is segmented into - * three areas by the two pointers: - * - *
- *      +-------------------+------------------+------------------+
- *      | discardable bytes |  readable bytes  |  writable bytes  |
- *      |                   |     (CONTENT)    |                  |
- *      +-------------------+------------------+------------------+
- *      |                   |                  |                  |
- *      0      <=      readerIndex   <=   writerIndex    <=    capacity
- * 
- * - *

Readable bytes (the actual content)

- * - * This segment is where the actual data is stored. Any operation whose name - * starts with {@code read} or {@code skip} will get or skip the data at the - * current {@link #readerIndex() readerIndex} and increase it by the number of - * read bytes. If the argument of the read operation is also a - * {@link ByteBuf} and no destination index is specified, the specified - * buffer's {@link #writerIndex() writerIndex} is increased together. - *

- * If there's not enough content left, {@link IndexOutOfBoundsException} is - * raised. The default value of newly allocated, wrapped or copied buffer's - * {@link #readerIndex() readerIndex} is {@code 0}. - * - *

- * // Iterates the readable bytes of a buffer.
- * {@link ByteBuf} buffer = ...;
- * while (buffer.readable()) {
- *     System.out.println(buffer.readByte());
- * }
- * 
- * - *

Writable bytes

- * - * This segment is a undefined space which needs to be filled. Any operation - * whose name ends with {@code write} will write the data at the current - * {@link #writerIndex() writerIndex} and increase it by the number of written - * bytes. If the argument of the write operation is also a {@link ByteBuf}, - * and no source index is specified, the specified buffer's - * {@link #readerIndex() readerIndex} is increased together. - *

- * If there's not enough writable bytes left, {@link IndexOutOfBoundsException} - * is raised. The default value of newly allocated buffer's - * {@link #writerIndex() writerIndex} is {@code 0}. The default value of - * wrapped or copied buffer's {@link #writerIndex() writerIndex} is the - * {@link #capacity() capacity} of the buffer. - * - *

- * // Fills the writable bytes of a buffer with random integers.
- * {@link ByteBuf} buffer = ...;
- * while (buffer.maxWritableBytes() >= 4) {
- *     buffer.writeInt(random.nextInt());
- * }
- * 
- * - *

Discardable bytes

- * - * This segment contains the bytes which were read already by a read operation. - * Initially, the size of this segment is {@code 0}, but its size increases up - * to the {@link #writerIndex() writerIndex} as read operations are executed. - * The read bytes can be discarded by calling {@link #discardReadBytes()} to - * reclaim unused area as depicted by the following diagram: - * - *
- *  BEFORE discardReadBytes()
- *
- *      +-------------------+------------------+------------------+
- *      | discardable bytes |  readable bytes  |  writable bytes  |
- *      +-------------------+------------------+------------------+
- *      |                   |                  |                  |
- *      0      <=      readerIndex   <=   writerIndex    <=    capacity
- *
- *
- *  AFTER discardReadBytes()
- *
- *      +------------------+--------------------------------------+
- *      |  readable bytes  |    writable bytes (got more space)   |
- *      +------------------+--------------------------------------+
- *      |                  |                                      |
- * readerIndex (0) <= writerIndex (decreased)        <=        capacity
- * 
- * - * Please note that there is no guarantee about the content of writable bytes - * after calling {@link #discardReadBytes()}. The writable bytes will not be - * moved in most cases and could even be filled with completely different data - * depending on the underlying buffer implementation. - * - *

Clearing the buffer indexes

- * - * You can set both {@link #readerIndex() readerIndex} and - * {@link #writerIndex() writerIndex} to {@code 0} by calling {@link #clear()}. - * It does not clear the buffer content (e.g. filling with {@code 0}) but just - * clears the two pointers. Please also note that the semantic of this - * operation is different from {@link ByteBuffer#clear()}. - * - *
- *  BEFORE clear()
- *
- *      +-------------------+------------------+------------------+
- *      | discardable bytes |  readable bytes  |  writable bytes  |
- *      +-------------------+------------------+------------------+
- *      |                   |                  |                  |
- *      0      <=      readerIndex   <=   writerIndex    <=    capacity
- *
- *
- *  AFTER clear()
- *
- *      +---------------------------------------------------------+
- *      |             writable bytes (got more space)             |
- *      +---------------------------------------------------------+
- *      |                                                         |
- *      0 = readerIndex = writerIndex            <=            capacity
- * 
- * - *

Search operations

- * - * For simple single-byte searches, use {@link #indexOf(int, int, byte)} and {@link #bytesBefore(int, int, byte)}. - * {@link #bytesBefore(byte)} is especially useful when you deal with a {@code NUL}-terminated string. - * For complicated searches, use {@link #forEachByte(int, int, ByteBufProcessor)} with a {@link ByteBufProcessor} - * implementation. - * - *

Mark and reset

- * - * There are two marker indexes in every buffer. One is for storing - * {@link #readerIndex() readerIndex} and the other is for storing - * {@link #writerIndex() writerIndex}. You can always reposition one of the - * two indexes by calling a reset method. It works in a similar fashion to - * the mark and reset methods in {@link InputStream} except that there's no - * {@code readlimit}. - * - *

Derived buffers

- * - * You can create a view of an existing buffer by calling either - * {@link #duplicate()}, {@link #slice()} or {@link #slice(int, int)}. - * A derived buffer will have an independent {@link #readerIndex() readerIndex}, - * {@link #writerIndex() writerIndex} and marker indexes, while it shares - * other internal data representation, just like a NIO buffer does. - *

- * In case a completely fresh copy of an existing buffer is required, please - * call {@link #copy()} method instead. - * - *

Conversion to existing JDK types

- * - *

Byte array

- * - * If a {@link ByteBuf} is backed by a byte array (i.e. {@code byte[]}), - * you can access it directly via the {@link #array()} method. To determine - * if a buffer is backed by a byte array, {@link #hasArray()} should be used. - * - *

NIO Buffers

- * - * If a {@link ByteBuf} can be converted into an NIO {@link ByteBuffer} which shares its - * content (i.e. view buffer), you can get it via the {@link #nioBuffer()} method. To determine - * if a buffer can be converted into an NIO buffer, use {@link #nioBufferCount()}. - * - *

Strings

- * - * Various {@link #toString(Charset)} methods convert a {@link ByteBuf} - * into a {@link String}. Please note that {@link #toString()} is not a - * conversion method. - * - *

I/O Streams

- * - * Please refer to {@link ByteBufInputStream} and - * {@link ByteBufOutputStream}. - */ - -public abstract class ByteBuf implements ReferenceCounted, Comparable { - - /** - * Returns the number of bytes (octets) this buffer can contain. - */ - public abstract int capacity(); - - /** - * Adjusts the capacity of this buffer. If the {@code newCapacity} is less than the current - * capacity, the content of this buffer is truncated. If the {@code newCapacity} is greater - * than the current capacity, the buffer is appended with unspecified data whose length is - * {@code (newCapacity - currentCapacity)}. - */ - public abstract ByteBuf capacity(int newCapacity); - - /** - * Returns the maximum allowed capacity of this buffer. If a user attempts to increase the - * capacity of this buffer beyond the maximum capacity using {@link #capacity(int)} or - * {@link #ensureWritable(int)}, those methods will raise an - * {@link IllegalArgumentException}. - */ - public abstract int maxCapacity(); - - /** - * Returns the {@link ByteBufAllocator} which created this buffer. - */ - public abstract ByteBufAllocator alloc(); - - /** - * Returns the endianness - * of this buffer. - */ - public abstract ByteOrder order(); - - /** - * Returns a buffer with the specified {@code endianness} which shares the whole region, - * indexes, and marks of this buffer. Modifying the content, the indexes, or the marks of the - * returned buffer or this buffer affects each other's content, indexes, and marks. If the - * specified {@code endianness} is identical to this buffer's byte order, this method can - * return {@code this}. This method does not modify {@code readerIndex} or {@code writerIndex} - * of this buffer. - */ - public abstract ByteBuf order(ByteOrder endianness); - - /** - * Return the underlying buffer instance if this buffer is a wrapper of another buffer. - * - * @return {@code null} if this buffer is not a wrapper - */ - public abstract ByteBuf unwrap(); - - /** - * Returns {@code true} if and only if this buffer is backed by an - * NIO direct buffer. - */ - public abstract boolean isDirect(); - - /** - * Returns the {@code readerIndex} of this buffer. - */ - public abstract int readerIndex(); - - /** - * Sets the {@code readerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code readerIndex} is - * less than {@code 0} or - * greater than {@code this.writerIndex} - */ - public abstract ByteBuf readerIndex(int readerIndex); - - /** - * Returns the {@code writerIndex} of this buffer. - */ - public abstract int writerIndex(); - - /** - * Sets the {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code writerIndex} is - * less than {@code this.readerIndex} or - * greater than {@code this.capacity} - */ - public abstract ByteBuf writerIndex(int writerIndex); - - /** - * Sets the {@code readerIndex} and {@code writerIndex} of this buffer - * in one shot. This method is useful when you have to worry about the - * invocation order of {@link #readerIndex(int)} and {@link #writerIndex(int)} - * methods. For example, the following code will fail: - * - *
-     * // Create a buffer whose readerIndex, writerIndex and capacity are
-     * // 0, 0 and 8 respectively.
-     * {@link ByteBuf} buf = {@link Unpooled}.buffer(8);
-     *
-     * // IndexOutOfBoundsException is thrown because the specified
-     * // readerIndex (2) cannot be greater than the current writerIndex (0).
-     * buf.readerIndex(2);
-     * buf.writerIndex(4);
-     * 
- * - * The following code will also fail: - * - *
-     * // Create a buffer whose readerIndex, writerIndex and capacity are
-     * // 0, 8 and 8 respectively.
-     * {@link ByteBuf} buf = {@link Unpooled}.wrappedBuffer(new byte[8]);
-     *
-     * // readerIndex becomes 8.
-     * buf.readLong();
-     *
-     * // IndexOutOfBoundsException is thrown because the specified
-     * // writerIndex (4) cannot be less than the current readerIndex (8).
-     * buf.writerIndex(4);
-     * buf.readerIndex(2);
-     * 
- * - * By contrast, this method guarantees that it never - * throws an {@link IndexOutOfBoundsException} as long as the specified - * indexes meet basic constraints, regardless what the current index - * values of the buffer are: - * - *
-     * // No matter what the current state of the buffer is, the following
-     * // call always succeeds as long as the capacity of the buffer is not
-     * // less than 4.
-     * buf.setIndex(2, 4);
-     * 
- * - * @throws IndexOutOfBoundsException - * if the specified {@code readerIndex} is less than 0, - * if the specified {@code writerIndex} is less than the specified - * {@code readerIndex} or if the specified {@code writerIndex} is - * greater than {@code this.capacity} - */ - public abstract ByteBuf setIndex(int readerIndex, int writerIndex); - - /** - * Returns the number of readable bytes which is equal to - * {@code (this.writerIndex - this.readerIndex)}. - */ - public abstract int readableBytes(); - - /** - * Returns the number of writable bytes which is equal to - * {@code (this.capacity - this.writerIndex)}. - */ - public abstract int writableBytes(); - - /** - * Returns the maximum possible number of writable bytes, which is equal to - * {@code (this.maxCapacity - this.writerIndex)}. - */ - public abstract int maxWritableBytes(); - - /** - * Returns {@code true} - * if and only if {@code (this.writerIndex - this.readerIndex)} is greater - * than {@code 0}. - */ - public abstract boolean isReadable(); - - /** - * Returns {@code true} if and only if this buffer contains equal to or more than the specified number of elements. - */ - public abstract boolean isReadable(int size); - - /** - * Returns {@code true} - * if and only if {@code (this.capacity - this.writerIndex)} is greater - * than {@code 0}. - */ - public abstract boolean isWritable(); - - /** - * Returns {@code true} if and only if this buffer has enough room to allow writing the specified number of - * elements. - */ - public abstract boolean isWritable(int size); - - /** - * Sets the {@code readerIndex} and {@code writerIndex} of this buffer to - * {@code 0}. - * This method is identical to {@link #setIndex(int, int) setIndex(0, 0)}. - *

- * Please note that the behavior of this method is different - * from that of NIO buffer, which sets the {@code limit} to - * the {@code capacity} of the buffer. - */ - public abstract ByteBuf clear(); - - /** - * Marks the current {@code readerIndex} in this buffer. You can - * reposition the current {@code readerIndex} to the marked - * {@code readerIndex} by calling {@link #resetReaderIndex()}. - * The initial value of the marked {@code readerIndex} is {@code 0}. - */ - public abstract ByteBuf markReaderIndex(); - - /** - * Repositions the current {@code readerIndex} to the marked - * {@code readerIndex} in this buffer. - * - * @throws IndexOutOfBoundsException - * if the current {@code writerIndex} is less than the marked - * {@code readerIndex} - */ - public abstract ByteBuf resetReaderIndex(); - - /** - * Marks the current {@code writerIndex} in this buffer. You can - * reposition the current {@code writerIndex} to the marked - * {@code writerIndex} by calling {@link #resetWriterIndex()}. - * The initial value of the marked {@code writerIndex} is {@code 0}. - */ - public abstract ByteBuf markWriterIndex(); - - /** - * Repositions the current {@code writerIndex} to the marked - * {@code writerIndex} in this buffer. - * - * @throws IndexOutOfBoundsException - * if the current {@code readerIndex} is greater than the marked - * {@code writerIndex} - */ - public abstract ByteBuf resetWriterIndex(); - - /** - * Discards the bytes between the 0th index and {@code readerIndex}. - * It moves the bytes between {@code readerIndex} and {@code writerIndex} - * to the 0th index, and sets {@code readerIndex} and {@code writerIndex} - * to {@code 0} and {@code oldWriterIndex - oldReaderIndex} respectively. - *

- * Please refer to the class documentation for more detailed explanation. - */ - public abstract ByteBuf discardReadBytes(); - - /** - * Similar to {@link ByteBuf#discardReadBytes()} except that this method might discard - * some, all, or none of read bytes depending on its internal implementation to reduce - * overall memory bandwidth consumption at the cost of potentially additional memory - * consumption. - */ - public abstract ByteBuf discardSomeReadBytes(); - - /** - * Makes sure the number of {@linkplain #writableBytes() the writable bytes} - * is equal to or greater than the specified value. If there is enough - * writable bytes in this buffer, this method returns with no side effect. - * Otherwise, it raises an {@link IllegalArgumentException}. - * - * @param minWritableBytes - * the expected minimum number of writable bytes - * @throws IndexOutOfBoundsException - * if {@link #writerIndex()} + {@code minWritableBytes} > {@link #maxCapacity()} - */ - public abstract ByteBuf ensureWritable(int minWritableBytes); - - /** - * Tries to make sure the number of {@linkplain #writableBytes() the writable bytes} - * is equal to or greater than the specified value. Unlike {@link #ensureWritable(int)}, - * this method does not raise an exception but returns a code. - * - * @param minWritableBytes - * the expected minimum number of writable bytes - * @param force - * When {@link #writerIndex()} + {@code minWritableBytes} > {@link #maxCapacity()}: - *

    - *
  • {@code true} - the capacity of the buffer is expanded to {@link #maxCapacity()}
  • - *
  • {@code false} - the capacity of the buffer is unchanged
  • - *
- * @return {@code 0} if the buffer has enough writable bytes, and its capacity is unchanged. - * {@code 1} if the buffer does not have enough bytes, and its capacity is unchanged. - * {@code 2} if the buffer has enough writable bytes, and its capacity has been increased. - * {@code 3} if the buffer does not have enough bytes, but its capacity has been - * increased to its maximum. - */ - public abstract int ensureWritable(int minWritableBytes, boolean force); - - /** - * Gets a boolean at the specified absolute (@code index) in this buffer. - * This method does not modify the {@code readerIndex} or {@code writerIndex} - * of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 1} is greater than {@code this.capacity} - */ - public abstract boolean getBoolean(int index); - - /** - * Gets a byte at the specified absolute {@code index} in this buffer. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 1} is greater than {@code this.capacity} - */ - public abstract byte getByte(int index); - - /** - * Gets an unsigned byte at the specified absolute {@code index} in this - * buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 1} is greater than {@code this.capacity} - */ - public abstract short getUnsignedByte(int index); - - /** - * Gets a 16-bit short integer at the specified absolute {@code index} in - * this buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 2} is greater than {@code this.capacity} - */ - public abstract short getShort(int index); - - /** - * Gets an unsigned 16-bit short integer at the specified absolute - * {@code index} in this buffer. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 2} is greater than {@code this.capacity} - */ - public abstract int getUnsignedShort(int index); - - /** - * Gets a 24-bit medium integer at the specified absolute {@code index} in - * this buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 3} is greater than {@code this.capacity} - */ - public abstract int getMedium(int index); - - /** - * Gets an unsigned 24-bit medium integer at the specified absolute - * {@code index} in this buffer. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 3} is greater than {@code this.capacity} - */ - public abstract int getUnsignedMedium(int index); - - /** - * Gets a 32-bit integer at the specified absolute {@code index} in - * this buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 4} is greater than {@code this.capacity} - */ - public abstract int getInt(int index); - - /** - * Gets an unsigned 32-bit integer at the specified absolute {@code index} - * in this buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 4} is greater than {@code this.capacity} - */ - public abstract long getUnsignedInt(int index); - - /** - * Gets a 64-bit long integer at the specified absolute {@code index} in - * this buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 8} is greater than {@code this.capacity} - */ - public abstract long getLong(int index); - - /** - * Gets a 2-byte UTF-16 character at the specified absolute - * {@code index} in this buffer. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 2} is greater than {@code this.capacity} - */ - public abstract char getChar(int index); - - /** - * Gets a 32-bit floating point number at the specified absolute - * {@code index} in this buffer. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 4} is greater than {@code this.capacity} - */ - public abstract float getFloat(int index); - - /** - * Gets a 64-bit floating point number at the specified absolute - * {@code index} in this buffer. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 8} is greater than {@code this.capacity} - */ - public abstract double getDouble(int index); - - /** - * Transfers this buffer's data to the specified destination starting at - * the specified absolute {@code index} until the destination becomes - * non-writable. This method is basically same with - * {@link #getBytes(int, ByteBuf, int, int)}, except that this - * method increases the {@code writerIndex} of the destination by the - * number of the transferred bytes while - * {@link #getBytes(int, ByteBuf, int, int)} does not. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * the source buffer (i.e. {@code this}). - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + dst.writableBytes} is greater than - * {@code this.capacity} - */ - public abstract ByteBuf getBytes(int index, ByteBuf dst); - - /** - * Transfers this buffer's data to the specified destination starting at - * the specified absolute {@code index}. This method is basically same - * with {@link #getBytes(int, ByteBuf, int, int)}, except that this - * method increases the {@code writerIndex} of the destination by the - * number of the transferred bytes while - * {@link #getBytes(int, ByteBuf, int, int)} does not. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * the source buffer (i.e. {@code this}). - * - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code length} is greater than {@code dst.writableBytes} - */ - public abstract ByteBuf getBytes(int index, ByteBuf dst, int length); - - /** - * Transfers this buffer's data to the specified destination starting at - * the specified absolute {@code index}. - * This method does not modify {@code readerIndex} or {@code writerIndex} - * of both the source (i.e. {@code this}) and the destination. - * - * @param dstIndex the first index of the destination - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if the specified {@code dstIndex} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code dstIndex + length} is greater than - * {@code dst.capacity} - */ - public abstract ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length); - - /** - * Transfers this buffer's data to the specified destination starting at - * the specified absolute {@code index}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + dst.length} is greater than - * {@code this.capacity} - */ - public abstract ByteBuf getBytes(int index, byte[] dst); - - /** - * Transfers this buffer's data to the specified destination starting at - * the specified absolute {@code index}. - * This method does not modify {@code readerIndex} or {@code writerIndex} - * of this buffer. - * - * @param dstIndex the first index of the destination - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if the specified {@code dstIndex} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code dstIndex + length} is greater than - * {@code dst.length} - */ - public abstract ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length); - - /** - * Transfers this buffer's data to the specified destination starting at - * the specified absolute {@code index} until the destination's position - * reaches its limit. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer while the destination's {@code position} will be increased. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + dst.remaining()} is greater than - * {@code this.capacity} - */ - public abstract ByteBuf getBytes(int index, ByteBuffer dst); - - /** - * Transfers this buffer's data to the specified stream starting at the - * specified absolute {@code index}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + length} is greater than - * {@code this.capacity} - * @throws IOException - * if the specified stream threw an exception during I/O - */ - public abstract ByteBuf getBytes(int index, OutputStream out, int length) throws IOException; - - /** - * Transfers this buffer's data to the specified channel starting at the - * specified absolute {@code index}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @param length the maximum number of bytes to transfer - * - * @return the actual number of bytes written out to the specified channel - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + length} is greater than - * {@code this.capacity} - * @throws IOException - * if the specified channel threw an exception during I/O - */ - public abstract int getBytes(int index, GatheringByteChannel out, int length) throws IOException; - - /** - * Sets the specified boolean at the specified absolute {@code index} in this - * buffer. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 1} is greater than {@code this.capacity} - */ - public abstract ByteBuf setBoolean(int index, boolean value); - - /** - * Sets the specified byte at the specified absolute {@code index} in this - * buffer. The 24 high-order bits of the specified value are ignored. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 1} is greater than {@code this.capacity} - */ - public abstract ByteBuf setByte(int index, int value); - - /** - * Sets the specified 16-bit short integer at the specified absolute - * {@code index} in this buffer. The 16 high-order bits of the specified - * value are ignored. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 2} is greater than {@code this.capacity} - */ - public abstract ByteBuf setShort(int index, int value); - - /** - * Sets the specified 24-bit medium integer at the specified absolute - * {@code index} in this buffer. Please note that the most significant - * byte is ignored in the specified value. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 3} is greater than {@code this.capacity} - */ - public abstract ByteBuf setMedium(int index, int value); - - /** - * Sets the specified 32-bit integer at the specified absolute - * {@code index} in this buffer. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 4} is greater than {@code this.capacity} - */ - public abstract ByteBuf setInt(int index, int value); - - /** - * Sets the specified 64-bit long integer at the specified absolute - * {@code index} in this buffer. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 8} is greater than {@code this.capacity} - */ - public abstract ByteBuf setLong(int index, long value); - - /** - * Sets the specified 2-byte UTF-16 character at the specified absolute - * {@code index} in this buffer. - * The 16 high-order bits of the specified value are ignored. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 2} is greater than {@code this.capacity} - */ - public abstract ByteBuf setChar(int index, int value); - - /** - * Sets the specified 32-bit floating-point number at the specified - * absolute {@code index} in this buffer. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 4} is greater than {@code this.capacity} - */ - public abstract ByteBuf setFloat(int index, float value); - - /** - * Sets the specified 64-bit floating-point number at the specified - * absolute {@code index} in this buffer. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * {@code index + 8} is greater than {@code this.capacity} - */ - public abstract ByteBuf setDouble(int index, double value); - - /** - * Transfers the specified source buffer's data to this buffer starting at - * the specified absolute {@code index} until the source buffer becomes - * unreadable. This method is basically same with - * {@link #setBytes(int, ByteBuf, int, int)}, except that this - * method increases the {@code readerIndex} of the source buffer by - * the number of the transferred bytes while - * {@link #setBytes(int, ByteBuf, int, int)} does not. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * the source buffer (i.e. {@code this}). - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + src.readableBytes} is greater than - * {@code this.capacity} - */ - public abstract ByteBuf setBytes(int index, ByteBuf src); - - /** - * Transfers the specified source buffer's data to this buffer starting at - * the specified absolute {@code index}. This method is basically same - * with {@link #setBytes(int, ByteBuf, int, int)}, except that this - * method increases the {@code readerIndex} of the source buffer by - * the number of the transferred bytes while - * {@link #setBytes(int, ByteBuf, int, int)} does not. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * the source buffer (i.e. {@code this}). - * - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code length} is greater than {@code src.readableBytes} - */ - public abstract ByteBuf setBytes(int index, ByteBuf src, int length); - - /** - * Transfers the specified source buffer's data to this buffer starting at - * the specified absolute {@code index}. - * This method does not modify {@code readerIndex} or {@code writerIndex} - * of both the source (i.e. {@code this}) and the destination. - * - * @param srcIndex the first index of the source - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if the specified {@code srcIndex} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code srcIndex + length} is greater than - * {@code src.capacity} - */ - public abstract ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length); - - /** - * Transfers the specified source array's data to this buffer starting at - * the specified absolute {@code index}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + src.length} is greater than - * {@code this.capacity} - */ - public abstract ByteBuf setBytes(int index, byte[] src); - - /** - * Transfers the specified source array's data to this buffer starting at - * the specified absolute {@code index}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0}, - * if the specified {@code srcIndex} is less than {@code 0}, - * if {@code index + length} is greater than - * {@code this.capacity}, or - * if {@code srcIndex + length} is greater than {@code src.length} - */ - public abstract ByteBuf setBytes(int index, byte[] src, int srcIndex, int length); - - /** - * Transfers the specified source buffer's data to this buffer starting at - * the specified absolute {@code index} until the source buffer's position - * reaches its limit. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + src.remaining()} is greater than - * {@code this.capacity} - */ - public abstract ByteBuf setBytes(int index, ByteBuffer src); - - /** - * Transfers the content of the specified source stream to this buffer - * starting at the specified absolute {@code index}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @param length the number of bytes to transfer - * - * @return the actual number of bytes read in from the specified channel. - * {@code -1} if the specified channel is closed. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + length} is greater than {@code this.capacity} - * @throws IOException - * if the specified stream threw an exception during I/O - */ - public abstract int setBytes(int index, InputStream in, int length) throws IOException; - - /** - * Transfers the content of the specified source channel to this buffer - * starting at the specified absolute {@code index}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @param length the maximum number of bytes to transfer - * - * @return the actual number of bytes read in from the specified channel. - * {@code -1} if the specified channel is closed. - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + length} is greater than {@code this.capacity} - * @throws IOException - * if the specified channel threw an exception during I/O - */ - public abstract int setBytes(int index, ScatteringByteChannel in, int length) throws IOException; - - /** - * Fills this buffer with NUL (0x00) starting at the specified - * absolute {@code index}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @param length the number of NULs to write to the buffer - * - * @throws IndexOutOfBoundsException - * if the specified {@code index} is less than {@code 0} or - * if {@code index + length} is greater than {@code this.capacity} - */ - public abstract ByteBuf setZero(int index, int length); - - /** - * Gets a boolean at the current {@code readerIndex} and increases - * the {@code readerIndex} by {@code 1} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 1} - */ - public abstract boolean readBoolean(); - - /** - * Gets a byte at the current {@code readerIndex} and increases - * the {@code readerIndex} by {@code 1} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 1} - */ - public abstract byte readByte(); - - /** - * Gets an unsigned byte at the current {@code readerIndex} and increases - * the {@code readerIndex} by {@code 1} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 1} - */ - public abstract short readUnsignedByte(); - - /** - * Gets a 16-bit short integer at the current {@code readerIndex} - * and increases the {@code readerIndex} by {@code 2} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 2} - */ - public abstract short readShort(); - - /** - * Gets an unsigned 16-bit short integer at the current {@code readerIndex} - * and increases the {@code readerIndex} by {@code 2} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 2} - */ - public abstract int readUnsignedShort(); - - /** - * Gets a 24-bit medium integer at the current {@code readerIndex} - * and increases the {@code readerIndex} by {@code 3} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 3} - */ - public abstract int readMedium(); - - /** - * Gets an unsigned 24-bit medium integer at the current {@code readerIndex} - * and increases the {@code readerIndex} by {@code 3} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 3} - */ - public abstract int readUnsignedMedium(); - - /** - * Gets a 32-bit integer at the current {@code readerIndex} - * and increases the {@code readerIndex} by {@code 4} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 4} - */ - public abstract int readInt(); - - /** - * Gets an unsigned 32-bit integer at the current {@code readerIndex} - * and increases the {@code readerIndex} by {@code 4} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 4} - */ - public abstract long readUnsignedInt(); - - /** - * Gets a 64-bit integer at the current {@code readerIndex} - * and increases the {@code readerIndex} by {@code 8} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 8} - */ - public abstract long readLong(); - - /** - * Gets a 2-byte UTF-16 character at the current {@code readerIndex} - * and increases the {@code readerIndex} by {@code 2} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 2} - */ - public abstract char readChar(); - - /** - * Gets a 32-bit floating point number at the current {@code readerIndex} - * and increases the {@code readerIndex} by {@code 4} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 4} - */ - public abstract float readFloat(); - - /** - * Gets a 64-bit floating point number at the current {@code readerIndex} - * and increases the {@code readerIndex} by {@code 8} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.readableBytes} is less than {@code 8} - */ - public abstract double readDouble(); - - /** - * Transfers this buffer's data to a newly created buffer starting at - * the current {@code readerIndex} and increases the {@code readerIndex} - * by the number of the transferred bytes (= {@code length}). - * The returned buffer's {@code readerIndex} and {@code writerIndex} are - * {@code 0} and {@code length} respectively. - * - * @param length the number of bytes to transfer - * - * @return the newly created buffer which contains the transferred bytes - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.readableBytes} - */ - public abstract ByteBuf readBytes(int length); - - /** - * Returns a new slice of this buffer's sub-region starting at the current - * {@code readerIndex} and increases the {@code readerIndex} by the size - * of the new slice (= {@code length}). - * - * @param length the size of the new slice - * - * @return the newly created slice - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.readableBytes} - */ - public abstract ByteBuf readSlice(int length); - - /** - * Transfers this buffer's data to the specified destination starting at - * the current {@code readerIndex} until the destination becomes - * non-writable, and increases the {@code readerIndex} by the number of the - * transferred bytes. This method is basically same with - * {@link #readBytes(ByteBuf, int, int)}, except that this method - * increases the {@code writerIndex} of the destination by the number of - * the transferred bytes while {@link #readBytes(ByteBuf, int, int)} - * does not. - * - * @throws IndexOutOfBoundsException - * if {@code dst.writableBytes} is greater than - * {@code this.readableBytes} - */ - public abstract ByteBuf readBytes(ByteBuf dst); - - /** - * Transfers this buffer's data to the specified destination starting at - * the current {@code readerIndex} and increases the {@code readerIndex} - * by the number of the transferred bytes (= {@code length}). This method - * is basically same with {@link #readBytes(ByteBuf, int, int)}, - * except that this method increases the {@code writerIndex} of the - * destination by the number of the transferred bytes (= {@code length}) - * while {@link #readBytes(ByteBuf, int, int)} does not. - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.readableBytes} or - * if {@code length} is greater than {@code dst.writableBytes} - */ - public abstract ByteBuf readBytes(ByteBuf dst, int length); - - /** - * Transfers this buffer's data to the specified destination starting at - * the current {@code readerIndex} and increases the {@code readerIndex} - * by the number of the transferred bytes (= {@code length}). - * - * @param dstIndex the first index of the destination - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if the specified {@code dstIndex} is less than {@code 0}, - * if {@code length} is greater than {@code this.readableBytes}, or - * if {@code dstIndex + length} is greater than - * {@code dst.capacity} - */ - public abstract ByteBuf readBytes(ByteBuf dst, int dstIndex, int length); - - /** - * Transfers this buffer's data to the specified destination starting at - * the current {@code readerIndex} and increases the {@code readerIndex} - * by the number of the transferred bytes (= {@code dst.length}). - * - * @throws IndexOutOfBoundsException - * if {@code dst.length} is greater than {@code this.readableBytes} - */ - public abstract ByteBuf readBytes(byte[] dst); - - /** - * Transfers this buffer's data to the specified destination starting at - * the current {@code readerIndex} and increases the {@code readerIndex} - * by the number of the transferred bytes (= {@code length}). - * - * @param dstIndex the first index of the destination - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if the specified {@code dstIndex} is less than {@code 0}, - * if {@code length} is greater than {@code this.readableBytes}, or - * if {@code dstIndex + length} is greater than {@code dst.length} - */ - public abstract ByteBuf readBytes(byte[] dst, int dstIndex, int length); - - /** - * Transfers this buffer's data to the specified destination starting at - * the current {@code readerIndex} until the destination's position - * reaches its limit, and increases the {@code readerIndex} by the - * number of the transferred bytes. - * - * @throws IndexOutOfBoundsException - * if {@code dst.remaining()} is greater than - * {@code this.readableBytes} - */ - public abstract ByteBuf readBytes(ByteBuffer dst); - - /** - * Transfers this buffer's data to the specified stream starting at the - * current {@code readerIndex}. - * - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.readableBytes} - * @throws IOException - * if the specified stream threw an exception during I/O - */ - public abstract ByteBuf readBytes(OutputStream out, int length) throws IOException; - - /** - * Transfers this buffer's data to the specified stream starting at the - * current {@code readerIndex}. - * - * @param length the maximum number of bytes to transfer - * - * @return the actual number of bytes written out to the specified channel - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.readableBytes} - * @throws IOException - * if the specified channel threw an exception during I/O - */ - public abstract int readBytes(GatheringByteChannel out, int length) throws IOException; - - /** - * Increases the current {@code readerIndex} by the specified - * {@code length} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.readableBytes} - */ - public abstract ByteBuf skipBytes(int length); - - /** - * Sets the specified boolean at the current {@code writerIndex} - * and increases the {@code writerIndex} by {@code 1} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 1} - */ - public abstract ByteBuf writeBoolean(boolean value); - - /** - * Sets the specified byte at the current {@code writerIndex} - * and increases the {@code writerIndex} by {@code 1} in this buffer. - * The 24 high-order bits of the specified value are ignored. - * - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 1} - */ - public abstract ByteBuf writeByte(int value); - - /** - * Sets the specified 16-bit short integer at the current - * {@code writerIndex} and increases the {@code writerIndex} by {@code 2} - * in this buffer. The 16 high-order bits of the specified value are ignored. - * - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 2} - */ - public abstract ByteBuf writeShort(int value); - - /** - * Sets the specified 24-bit medium integer at the current - * {@code writerIndex} and increases the {@code writerIndex} by {@code 3} - * in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 3} - */ - public abstract ByteBuf writeMedium(int value); - - /** - * Sets the specified 32-bit integer at the current {@code writerIndex} - * and increases the {@code writerIndex} by {@code 4} in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 4} - */ - public abstract ByteBuf writeInt(int value); - - /** - * Sets the specified 64-bit long integer at the current - * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} - * in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 8} - */ - public abstract ByteBuf writeLong(long value); - - /** - * Sets the specified 2-byte UTF-16 character at the current - * {@code writerIndex} and increases the {@code writerIndex} by {@code 2} - * in this buffer. The 16 high-order bits of the specified value are ignored. - * - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 2} - */ - public abstract ByteBuf writeChar(int value); - - /** - * Sets the specified 32-bit floating point number at the current - * {@code writerIndex} and increases the {@code writerIndex} by {@code 4} - * in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 4} - */ - public abstract ByteBuf writeFloat(float value); - - /** - * Sets the specified 64-bit floating point number at the current - * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} - * in this buffer. - * - * @throws IndexOutOfBoundsException - * if {@code this.writableBytes} is less than {@code 8} - */ - public abstract ByteBuf writeDouble(double value); - - /** - * Transfers the specified source buffer's data to this buffer starting at - * the current {@code writerIndex} until the source buffer becomes - * unreadable, and increases the {@code writerIndex} by the number of - * the transferred bytes. This method is basically same with - * {@link #writeBytes(ByteBuf, int, int)}, except that this method - * increases the {@code readerIndex} of the source buffer by the number of - * the transferred bytes while {@link #writeBytes(ByteBuf, int, int)} - * does not. - * - * @throws IndexOutOfBoundsException - * if {@code src.readableBytes} is greater than - * {@code this.writableBytes} - */ - public abstract ByteBuf writeBytes(ByteBuf src); - - /** - * Transfers the specified source buffer's data to this buffer starting at - * the current {@code writerIndex} and increases the {@code writerIndex} - * by the number of the transferred bytes (= {@code length}). This method - * is basically same with {@link #writeBytes(ByteBuf, int, int)}, - * except that this method increases the {@code readerIndex} of the source - * buffer by the number of the transferred bytes (= {@code length}) while - * {@link #writeBytes(ByteBuf, int, int)} does not. - * - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.writableBytes} or - * if {@code length} is greater then {@code src.readableBytes} - */ - public abstract ByteBuf writeBytes(ByteBuf src, int length); - - /** - * Transfers the specified source buffer's data to this buffer starting at - * the current {@code writerIndex} and increases the {@code writerIndex} - * by the number of the transferred bytes (= {@code length}). - * - * @param srcIndex the first index of the source - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if the specified {@code srcIndex} is less than {@code 0}, - * if {@code srcIndex + length} is greater than - * {@code src.capacity}, or - * if {@code length} is greater than {@code this.writableBytes} - */ - public abstract ByteBuf writeBytes(ByteBuf src, int srcIndex, int length); - - /** - * Transfers the specified source array's data to this buffer starting at - * the current {@code writerIndex} and increases the {@code writerIndex} - * by the number of the transferred bytes (= {@code src.length}). - * - * @throws IndexOutOfBoundsException - * if {@code src.length} is greater than {@code this.writableBytes} - */ - public abstract ByteBuf writeBytes(byte[] src); - - /** - * Transfers the specified source array's data to this buffer starting at - * the current {@code writerIndex} and increases the {@code writerIndex} - * by the number of the transferred bytes (= {@code length}). - * - * @param srcIndex the first index of the source - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException - * if the specified {@code srcIndex} is less than {@code 0}, - * if {@code srcIndex + length} is greater than - * {@code src.length}, or - * if {@code length} is greater than {@code this.writableBytes} - */ - public abstract ByteBuf writeBytes(byte[] src, int srcIndex, int length); - - /** - * Transfers the specified source buffer's data to this buffer starting at - * the current {@code writerIndex} until the source buffer's position - * reaches its limit, and increases the {@code writerIndex} by the - * number of the transferred bytes. - * - * @throws IndexOutOfBoundsException - * if {@code src.remaining()} is greater than - * {@code this.writableBytes} - */ - public abstract ByteBuf writeBytes(ByteBuffer src); - - /** - * Transfers the content of the specified stream to this buffer - * starting at the current {@code writerIndex} and increases the - * {@code writerIndex} by the number of the transferred bytes. - * - * @param length the number of bytes to transfer - * - * @return the actual number of bytes read in from the specified stream - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.writableBytes} - * @throws IOException - * if the specified stream threw an exception during I/O - */ - public abstract int writeBytes(InputStream in, int length) throws IOException; - - /** - * Transfers the content of the specified channel to this buffer - * starting at the current {@code writerIndex} and increases the - * {@code writerIndex} by the number of the transferred bytes. - * - * @param length the maximum number of bytes to transfer - * - * @return the actual number of bytes read in from the specified channel - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.writableBytes} - * @throws IOException - * if the specified channel threw an exception during I/O - */ - public abstract int writeBytes(ScatteringByteChannel in, int length) throws IOException; - - /** - * Fills this buffer with NUL (0x00) starting at the current - * {@code writerIndex} and increases the {@code writerIndex} by the - * specified {@code length}. - * - * @param length the number of NULs to write to the buffer - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.writableBytes} - */ - public abstract ByteBuf writeZero(int length); - - /** - * Locates the first occurrence of the specified {@code value} in this - * buffer. The search takes place from the specified {@code fromIndex} - * (inclusive) to the specified {@code toIndex} (exclusive). - *

- * If {@code fromIndex} is greater than {@code toIndex}, the search is - * performed in a reversed order. - *

- * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @return the absolute index of the first occurrence if found. - * {@code -1} otherwise. - */ - public abstract int indexOf(int fromIndex, int toIndex, byte value); - - /** - * Locates the first occurrence of the specified {@code value} in this - * buffer. The search takes place from the current {@code readerIndex} - * (inclusive) to the current {@code writerIndex} (exclusive). - *

- * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @return the number of bytes between the current {@code readerIndex} - * and the first occurrence if found. {@code -1} otherwise. - */ - public abstract int bytesBefore(byte value); - - /** - * Locates the first occurrence of the specified {@code value} in this - * buffer. The search starts from the current {@code readerIndex} - * (inclusive) and lasts for the specified {@code length}. - *

- * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @return the number of bytes between the current {@code readerIndex} - * and the first occurrence if found. {@code -1} otherwise. - * - * @throws IndexOutOfBoundsException - * if {@code length} is greater than {@code this.readableBytes} - */ - public abstract int bytesBefore(int length, byte value); - - /** - * Locates the first occurrence of the specified {@code value} in this - * buffer. The search starts from the specified {@code index} (inclusive) - * and lasts for the specified {@code length}. - *

- * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @return the number of bytes between the specified {@code index} - * and the first occurrence if found. {@code -1} otherwise. - * - * @throws IndexOutOfBoundsException - * if {@code index + length} is greater than {@code this.capacity} - */ - public abstract int bytesBefore(int index, int length, byte value); - - /** - * Iterates over the readable bytes of this buffer with the specified {@code processor} in ascending order. - * - * @return {@code -1} if the processor iterated to or beyond the end of the readable bytes. - * The last-visited index If the {@link ByteBufProcessor#process(byte)} returned {@code false}. - */ - public abstract int forEachByte(ByteBufProcessor processor); - - /** - * Iterates over the specified area of this buffer with the specified {@code processor} in ascending order. - * (i.e. {@code index}, {@code (index + 1)}, .. {@code (index + length - 1)}) - * - * @return {@code -1} if the processor iterated to or beyond the end of the specified area. - * The last-visited index If the {@link ByteBufProcessor#process(byte)} returned {@code false}. - */ - public abstract int forEachByte(int index, int length, ByteBufProcessor processor); - - /** - * Iterates over the readable bytes of this buffer with the specified {@code processor} in descending order. - * - * @return {@code -1} if the processor iterated to or beyond the beginning of the readable bytes. - * The last-visited index If the {@link ByteBufProcessor#process(byte)} returned {@code false}. - */ - public abstract int forEachByteDesc(ByteBufProcessor processor); - - /** - * Iterates over the specified area of this buffer with the specified {@code processor} in descending order. - * (i.e. {@code (index + length - 1)}, {@code (index + length - 2)}, ... {@code index}) - * - * - * @return {@code -1} if the processor iterated to or beyond the beginning of the specified area. - * The last-visited index If the {@link ByteBufProcessor#process(byte)} returned {@code false}. - */ - public abstract int forEachByteDesc(int index, int length, ByteBufProcessor processor); - - /** - * Returns a copy of this buffer's readable bytes. Modifying the content - * of the returned buffer or this buffer does not affect each other at all. - * This method is identical to {@code buf.copy(buf.readerIndex(), buf.readableBytes())}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - */ - public abstract ByteBuf copy(); - - /** - * Returns a copy of this buffer's sub-region. Modifying the content of - * the returned buffer or this buffer does not affect each other at all. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - */ - public abstract ByteBuf copy(int index, int length); - - /** - * Returns a slice of this buffer's readable bytes. Modifying the content - * of the returned buffer or this buffer affects each other's content - * while they maintain separate indexes and marks. This method is - * identical to {@code buf.slice(buf.readerIndex(), buf.readableBytes())}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - */ - public abstract ByteBuf slice(); - - /** - * Returns a slice of this buffer's sub-region. Modifying the content of - * the returned buffer or this buffer affects each other's content while - * they maintain separate indexes and marks. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - */ - public abstract ByteBuf slice(int index, int length); - - /** - * Returns a buffer which shares the whole region of this buffer. - * Modifying the content of the returned buffer or this buffer affects - * each other's content while they maintain separate indexes and marks. - * This method is identical to {@code buf.slice(0, buf.capacity())}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - */ - public abstract ByteBuf duplicate(); - - /** - * Returns the maximum number of NIO {@link ByteBuffer}s that consist this buffer. Note that {@link #nioBuffers()} - * or {@link #nioBuffers(int, int)} might return a less number of {@link ByteBuffer}s. - * - * @return {@code -1} if this buffer has no underlying {@link ByteBuffer}. - * the number of the underlying {@link ByteBuffer}s if this buffer has at least one underlying - * {@link ByteBuffer}. Note that this method does not return {@code 0} to avoid confusion. - * - * @see #nioBuffer() - * @see #nioBuffer(int, int) - * @see #nioBuffers() - * @see #nioBuffers(int, int) - */ - public abstract int nioBufferCount(); - - /** - * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}. The returned buffer - * shares the content with this buffer, while changing the position and limit of the returned - * NIO buffer does not affect the indexes and marks of this buffer. This method is identical - * to {@code buf.nioBuffer(buf.readerIndex(), buf.readableBytes())}. This method does not - * modify {@code readerIndex} or {@code writerIndex} of this buffer. Please note that the - * returned NIO buffer will not see the changes of this buffer if this buffer is a dynamic - * buffer and it adjusted its capacity. - * - * @throws UnsupportedOperationException - * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself - * - * @see #nioBufferCount() - * @see #nioBuffers() - * @see #nioBuffers(int, int) - */ - public abstract ByteBuffer nioBuffer(); - - /** - * Exposes this buffer's sub-region as an NIO {@link ByteBuffer}. The returned buffer - * shares the content with this buffer, while changing the position and limit of the returned - * NIO buffer does not affect the indexes and marks of this buffer. This method does not - * modify {@code readerIndex} or {@code writerIndex} of this buffer. Please note that the - * returned NIO buffer will not see the changes of this buffer if this buffer is a dynamic - * buffer and it adjusted its capacity. - * - * @throws UnsupportedOperationException - * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself - * - * @see #nioBufferCount() - * @see #nioBuffers() - * @see #nioBuffers(int, int) - */ - public abstract ByteBuffer nioBuffer(int index, int length); - - /** - * Internal use only: Exposes the internal NIO buffer. - */ - public abstract ByteBuffer internalNioBuffer(int index, int length); - - /** - * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}'s. The returned buffer - * shares the content with this buffer, while changing the position and limit of the returned - * NIO buffer does not affect the indexes and marks of this buffer. This method does not - * modify {@code readerIndex} or {@code writerIndex} of this buffer. Please note that the - * returned NIO buffer will not see the changes of this buffer if this buffer is a dynamic - * buffer and it adjusted its capacity. - * - * - * @throws UnsupportedOperationException - * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself - * - * @see #nioBufferCount() - * @see #nioBuffer() - * @see #nioBuffer(int, int) - */ - public abstract ByteBuffer[] nioBuffers(); - - /** - * Exposes this buffer's bytes as an NIO {@link ByteBuffer}'s for the specified index and length - * The returned buffer shares the content with this buffer, while changing the position and limit - * of the returned NIO buffer does not affect the indexes and marks of this buffer. This method does - * not modify {@code readerIndex} or {@code writerIndex} of this buffer. Please note that the - * returned NIO buffer will not see the changes of this buffer if this buffer is a dynamic - * buffer and it adjusted its capacity. - * - * @throws UnsupportedOperationException - * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself - * - * @see #nioBufferCount() - * @see #nioBuffer() - * @see #nioBuffer(int, int) - */ - public abstract ByteBuffer[] nioBuffers(int index, int length); - - /** - * Returns {@code true} if and only if this buffer has a backing byte array. - * If this method returns true, you can safely call {@link #array()} and - * {@link #arrayOffset()}. - */ - public abstract boolean hasArray(); - - /** - * Returns the backing byte array of this buffer. - * - * @throws UnsupportedOperationException - * if there no accessible backing byte array - */ - public abstract byte[] array(); - - /** - * Returns the offset of the first byte within the backing byte array of - * this buffer. - * - * @throws UnsupportedOperationException - * if there no accessible backing byte array - */ - public abstract int arrayOffset(); - - /** - * Returns the low-level memory address that point to the first byte of ths backing data. - * - * @throws UnsupportedOperationException - * if this buffer does not support accessing the low-level memory address - */ - public final long memoryAddress() { - throw new UnsupportedOperationException(); - } - - /** - * Decodes this buffer's readable bytes into a string with the specified - * character set name. This method is identical to - * {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName)}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws UnsupportedCharsetException - * if the specified character set name is not supported by the - * current VM - */ - public abstract String toString(Charset charset); - - /** - * Decodes this buffer's sub-region into a string with the specified - * character set. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - */ - public abstract String toString(int index, int length, Charset charset); - - /** - * Returns a hash code which was calculated from the content of this - * buffer. If there's a byte array which is - * {@linkplain #equals(Object) equal to} this array, both arrays should - * return the same value. - */ - @Override - public abstract int hashCode(); - - /** - * Determines if the content of the specified buffer is identical to the - * content of this array. 'Identical' here means: - *

    - *
  • the size of the contents of the two buffers are same and
  • - *
  • every single byte of the content of the two buffers are same.
  • - *
- * Please note that it does not compare {@link #readerIndex()} nor - * {@link #writerIndex()}. This method also returns {@code false} for - * {@code null} and an object which is not an instance of - * {@link ByteBuf} type. - */ - @Override - public abstract boolean equals(Object obj); - - /** - * Compares the content of the specified buffer to the content of this - * buffer. Comparison is performed in the same manner with the string - * comparison functions of various languages such as {@code strcmp}, - * {@code memcmp} and {@link String#compareTo(String)}. - */ - @Override - public abstract int compareTo(ByteBuf buffer); - - /** - * Returns the string representation of this buffer. This method does not - * necessarily return the whole content of the buffer but returns - * the values of the key properties such as {@link #readerIndex()}, - * {@link #writerIndex()} and {@link #capacity()}. - */ - @Override - public abstract String toString(); - - @Override - public abstract ByteBuf retain(int increment); - - @Override - public abstract ByteBuf retain(); -} diff --git a/common/src/main/java/common/net/buffer/ByteBufAllocator.java b/common/src/main/java/common/net/buffer/ByteBufAllocator.java deleted file mode 100644 index 045f669..0000000 --- a/common/src/main/java/common/net/buffer/ByteBufAllocator.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -/** - * Implementations are responsible to allocate buffers. Implementations of this interface are expected to be - * thread-safe. - */ -public interface ByteBufAllocator { - - ByteBufAllocator DEFAULT = ByteBufUtil.DEFAULT_ALLOCATOR; - - /** - * Allocate a {@link ByteBuf}. If it is a direct or heap buffer - * depends on the actual implementation. - */ - ByteBuf buffer(); - - /** - * Allocate a {@link ByteBuf} with the given initial capacity. - * If it is a direct or heap buffer depends on the actual implementation. - */ - ByteBuf buffer(int initialCapacity); - - /** - * Allocate a {@link ByteBuf} with the given initial capacity and the given - * maximal capacity. If it is a direct or heap buffer depends on the actual - * implementation. - */ - ByteBuf buffer(int initialCapacity, int maxCapacity); - - /** - * Allocate a {@link ByteBuf}, preferably a direct buffer which is suitable for I/O. - */ - ByteBuf ioBuffer(); - - /** - * Allocate a {@link ByteBuf}, preferably a direct buffer which is suitable for I/O. - */ - ByteBuf ioBuffer(int initialCapacity); - - /** - * Allocate a {@link ByteBuf}, preferably a direct buffer which is suitable for I/O. - */ - ByteBuf ioBuffer(int initialCapacity, int maxCapacity); - - /** - * Allocate a heap {@link ByteBuf}. - */ - ByteBuf heapBuffer(); - - /** - * Allocate a heap {@link ByteBuf} with the given initial capacity. - */ - ByteBuf heapBuffer(int initialCapacity); - - /** - * Allocate a heap {@link ByteBuf} with the given initial capacity and the given - * maximal capacity. - */ - ByteBuf heapBuffer(int initialCapacity, int maxCapacity); - - /** - * Allocate a direct {@link ByteBuf}. - */ - ByteBuf directBuffer(); - - /** - * Allocate a direct {@link ByteBuf} with the given initial capacity. - */ - ByteBuf directBuffer(int initialCapacity); - - /** - * Allocate a direct {@link ByteBuf} with the given initial capacity and the given - * maximal capacity. - */ - ByteBuf directBuffer(int initialCapacity, int maxCapacity); - - /** - * Allocate a {@link CompositeByteBuf}. - * If it is a direct or heap buffer depends on the actual implementation. - */ - CompositeByteBuf compositeBuffer(); - - /** - * Allocate a {@link CompositeByteBuf} with the given maximum number of components that can be stored in it. - * If it is a direct or heap buffer depends on the actual implementation. - */ - CompositeByteBuf compositeBuffer(int maxNumComponents); - - /** - * Allocate a heap {@link CompositeByteBuf}. - */ - CompositeByteBuf compositeHeapBuffer(); - - /** - * Allocate a heap {@link CompositeByteBuf} with the given maximum number of components that can be stored in it. - */ - CompositeByteBuf compositeHeapBuffer(int maxNumComponents); - - /** - * Allocate a direct {@link CompositeByteBuf}. - */ - CompositeByteBuf compositeDirectBuffer(); - - /** - * Allocate a direct {@link CompositeByteBuf} with the given maximum number of components that can be stored in it. - */ - CompositeByteBuf compositeDirectBuffer(int maxNumComponents); - - /** - * Returns {@code true} if direct {@link ByteBuf}'s are pooled - */ - boolean isDirectBufferPooled(); -} diff --git a/common/src/main/java/common/net/buffer/ByteBufInputStream.java b/common/src/main/java/common/net/buffer/ByteBufInputStream.java deleted file mode 100644 index 70a0925..0000000 --- a/common/src/main/java/common/net/buffer/ByteBufInputStream.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; - -/** - * An {@link InputStream} which reads data from a {@link ByteBuf}. - *

- * A read operation against this stream will occur at the {@code readerIndex} - * of its underlying buffer and the {@code readerIndex} will increase during - * the read operation. Please note that it only reads up to the number of - * readable bytes determined at the moment of construction. Therefore, - * updating {@link ByteBuf#writerIndex()} will not affect the return - * value of {@link #available()}. - *

- * This stream implements {@link DataInput} for your convenience. - * The endianness of the stream is not always big endian but depends on - * the endianness of the underlying buffer. - * - * @see ByteBufOutputStream - */ -public class ByteBufInputStream extends InputStream implements DataInput { - - private final ByteBuf buffer; - private final int startIndex; - private final int endIndex; - - /** - * Creates a new stream which reads data from the specified {@code buffer} - * starting at the current {@code readerIndex} and ending at the current - * {@code writerIndex}. - */ - public ByteBufInputStream(ByteBuf buffer) { - this(buffer, buffer.readableBytes()); - } - - /** - * Creates a new stream which reads data from the specified {@code buffer} - * starting at the current {@code readerIndex} and ending at - * {@code readerIndex + length}. - * - * @throws IndexOutOfBoundsException - * if {@code readerIndex + length} is greater than - * {@code writerIndex} - */ - public ByteBufInputStream(ByteBuf buffer, int length) { - if (buffer == null) { - throw new NullPointerException("buffer"); - } - if (length < 0) { - throw new IllegalArgumentException("length: " + length); - } - if (length > buffer.readableBytes()) { - throw new IndexOutOfBoundsException("Too many bytes to be read - Needs " - + length + ", maximum is " + buffer.readableBytes()); - } - - this.buffer = buffer; - startIndex = buffer.readerIndex(); - endIndex = startIndex + length; - buffer.markReaderIndex(); - } - - /** - * Returns the number of read bytes by this stream so far. - */ - public int readBytes() { - return buffer.readerIndex() - startIndex; - } - - @Override - public int available() throws IOException { - return endIndex - buffer.readerIndex(); - } - - @Override - public void mark(int readlimit) { - buffer.markReaderIndex(); - } - - @Override - public boolean markSupported() { - return true; - } - - @Override - public int read() throws IOException { - if (!buffer.isReadable()) { - return -1; - } - return buffer.readByte() & 0xff; - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - int available = available(); - if (available == 0) { - return -1; - } - - len = Math.min(available, len); - buffer.readBytes(b, off, len); - return len; - } - - @Override - public void reset() throws IOException { - buffer.resetReaderIndex(); - } - - @Override - public long skip(long n) throws IOException { - if (n > Integer.MAX_VALUE) { - return skipBytes(Integer.MAX_VALUE); - } else { - return skipBytes((int) n); - } - } - - @Override - public boolean readBoolean() throws IOException { - checkAvailable(1); - return read() != 0; - } - - @Override - public byte readByte() throws IOException { - if (!buffer.isReadable()) { - throw new EOFException(); - } - return buffer.readByte(); - } - - @Override - public char readChar() throws IOException { - return (char) readShort(); - } - - @Override - public double readDouble() throws IOException { - return Double.longBitsToDouble(readLong()); - } - - @Override - public float readFloat() throws IOException { - return Float.intBitsToFloat(readInt()); - } - - @Override - public void readFully(byte[] b) throws IOException { - readFully(b, 0, b.length); - } - - @Override - public void readFully(byte[] b, int off, int len) throws IOException { - checkAvailable(len); - buffer.readBytes(b, off, len); - } - - @Override - public int readInt() throws IOException { - checkAvailable(4); - return buffer.readInt(); - } - - private final StringBuilder lineBuf = new StringBuilder(); - - @Override - public String readLine() throws IOException { - lineBuf.setLength(0); - - loop: while (true) { - if (!buffer.isReadable()) { - return lineBuf.length() > 0 ? lineBuf.toString() : null; - } - - int c = buffer.readUnsignedByte(); - switch (c) { - case '\n': - break loop; - - case '\r': - if (buffer.isReadable() && (char) buffer.getUnsignedByte(buffer.readerIndex()) == '\n') { - buffer.skipBytes(1); - } - break loop; - - default: - lineBuf.append((char) c); - } - } - - return lineBuf.toString(); - } - - @Override - public long readLong() throws IOException { - checkAvailable(8); - return buffer.readLong(); - } - - @Override - public short readShort() throws IOException { - checkAvailable(2); - return buffer.readShort(); - } - - @Override - public String readUTF() throws IOException { - return DataInputStream.readUTF(this); - } - - @Override - public int readUnsignedByte() throws IOException { - return readByte() & 0xff; - } - - @Override - public int readUnsignedShort() throws IOException { - return readShort() & 0xffff; - } - - @Override - public int skipBytes(int n) throws IOException { - int nBytes = Math.min(available(), n); - buffer.skipBytes(nBytes); - return nBytes; - } - - private void checkAvailable(int fieldSize) throws IOException { - if (fieldSize < 0) { - throw new IndexOutOfBoundsException("fieldSize cannot be a negative number"); - } - if (fieldSize > available()) { - throw new EOFException("fieldSize is too long! Length is " + fieldSize - + ", but maximum is " + available()); - } - } -} diff --git a/common/src/main/java/common/net/buffer/ByteBufOutputStream.java b/common/src/main/java/common/net/buffer/ByteBufOutputStream.java deleted file mode 100644 index 81af491..0000000 --- a/common/src/main/java/common/net/buffer/ByteBufOutputStream.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -/** - * An {@link OutputStream} which writes data to a {@link ByteBuf}. - *

- * A write operation against this stream will occur at the {@code writerIndex} - * of its underlying buffer and the {@code writerIndex} will increase during - * the write operation. - *

- * This stream implements {@link DataOutput} for your convenience. - * The endianness of the stream is not always big endian but depends on - * the endianness of the underlying buffer. - * - * @see ByteBufInputStream - */ -public class ByteBufOutputStream extends OutputStream implements DataOutput { - - private final ByteBuf buffer; - private final int startIndex; - private final DataOutputStream utf8out = new DataOutputStream(this); - - /** - * Creates a new stream which writes data to the specified {@code buffer}. - */ - public ByteBufOutputStream(ByteBuf buffer) { - if (buffer == null) { - throw new NullPointerException("buffer"); - } - this.buffer = buffer; - startIndex = buffer.writerIndex(); - } - - /** - * Returns the number of written bytes by this stream so far. - */ - public int writtenBytes() { - return buffer.writerIndex() - startIndex; - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - if (len == 0) { - return; - } - - buffer.writeBytes(b, off, len); - } - - @Override - public void write(byte[] b) throws IOException { - buffer.writeBytes(b); - } - - @Override - public void write(int b) throws IOException { - buffer.writeByte((byte) b); - } - - @Override - public void writeBoolean(boolean v) throws IOException { - write(v? (byte) 1 : (byte) 0); - } - - @Override - public void writeByte(int v) throws IOException { - write(v); - } - - @Override - public void writeBytes(String s) throws IOException { - int len = s.length(); - for (int i = 0; i < len; i ++) { - write((byte) s.charAt(i)); - } - } - - @Override - public void writeChar(int v) throws IOException { - writeShort((short) v); - } - - @Override - public void writeChars(String s) throws IOException { - int len = s.length(); - for (int i = 0 ; i < len ; i ++) { - writeChar(s.charAt(i)); - } - } - - @Override - public void writeDouble(double v) throws IOException { - writeLong(Double.doubleToLongBits(v)); - } - - @Override - public void writeFloat(float v) throws IOException { - writeInt(Float.floatToIntBits(v)); - } - - @Override - public void writeInt(int v) throws IOException { - buffer.writeInt(v); - } - - @Override - public void writeLong(long v) throws IOException { - buffer.writeLong(v); - } - - @Override - public void writeShort(int v) throws IOException { - buffer.writeShort((short) v); - } - - @Override - public void writeUTF(String s) throws IOException { - utf8out.writeUTF(s); - } - - /** - * Returns the buffer where this stream is writing data. - */ - public ByteBuf buffer() { - return buffer; - } -} diff --git a/common/src/main/java/common/net/buffer/ByteBufProcessor.java b/common/src/main/java/common/net/buffer/ByteBufProcessor.java deleted file mode 100644 index 67f4ad4..0000000 --- a/common/src/main/java/common/net/buffer/ByteBufProcessor.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -public interface ByteBufProcessor { - - /** - * Aborts on a {@code NUL (0x00)}. - */ - ByteBufProcessor FIND_NUL = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value != 0; - } - }; - - /** - * Aborts on a non-{@code NUL (0x00)}. - */ - ByteBufProcessor FIND_NON_NUL = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value == 0; - } - }; - - /** - * Aborts on a {@code CR ('\r')}. - */ - ByteBufProcessor FIND_CR = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value != '\r'; - } - }; - - /** - * Aborts on a non-{@code CR ('\r')}. - */ - ByteBufProcessor FIND_NON_CR = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value == '\r'; - } - }; - - /** - * Aborts on a {@code LF ('\n')}. - */ - ByteBufProcessor FIND_LF = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value != '\n'; - } - }; - - /** - * Aborts on a non-{@code LF ('\n')}. - */ - ByteBufProcessor FIND_NON_LF = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value == '\n'; - } - }; - - /** - * Aborts on a {@code CR ('\r')} or a {@code LF ('\n')}. - */ - ByteBufProcessor FIND_CRLF = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value != '\r' && value != '\n'; - } - }; - - /** - * Aborts on a byte which is neither a {@code CR ('\r')} nor a {@code LF ('\n')}. - */ - ByteBufProcessor FIND_NON_CRLF = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value == '\r' || value == '\n'; - } - }; - - /** - * Aborts on a linear whitespace (a ({@code ' '} or a {@code '\t'}). - */ - ByteBufProcessor FIND_LINEAR_WHITESPACE = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value != ' ' && value != '\t'; - } - }; - - /** - * Aborts on a byte which is not a linear whitespace (neither {@code ' '} nor {@code '\t'}). - */ - ByteBufProcessor FIND_NON_LINEAR_WHITESPACE = new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - return value == ' ' || value == '\t'; - } - }; - - /** - * @return {@code true} if the processor wants to continue the loop and handle the next byte in the buffer. - * {@code false} if the processor wants to stop handling bytes and abort the loop. - */ - boolean process(byte value) throws Exception; -} diff --git a/common/src/main/java/common/net/buffer/ByteBufUtil.java b/common/src/main/java/common/net/buffer/ByteBufUtil.java deleted file mode 100644 index 0aa19d6..0000000 --- a/common/src/main/java/common/net/buffer/ByteBufUtil.java +++ /dev/null @@ -1,444 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CoderResult; -import java.util.Locale; - -import common.net.util.CharsetUtil; -import common.net.util.Recycler; -import common.net.util.Recycler.Handle; -import common.net.util.internal.SystemPropertyUtil; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * A collection of utility methods that is related with handling {@link ByteBuf}. - */ -public final class ByteBufUtil { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(ByteBufUtil.class); - - private static final char[] HEXDUMP_TABLE = new char[256 * 4]; - - static final ByteBufAllocator DEFAULT_ALLOCATOR; - - private static final int THREAD_LOCAL_BUFFER_SIZE; - - static { - final char[] DIGITS = "0123456789abcdef".toCharArray(); - for (int i = 0; i < 256; i ++) { - HEXDUMP_TABLE[ i << 1 ] = DIGITS[i >>> 4 & 0x0F]; - HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F]; - } - - String allocType = SystemPropertyUtil.get("game.net.allocator.type", "unpooled").toLowerCase(Locale.US).trim(); - ByteBufAllocator alloc; - if ("unpooled".equals(allocType)) { - alloc = UnpooledByteBufAllocator.DEFAULT; - logger.debug("-Dgame.net.allocator.type: {}", allocType); - } else if ("pooled".equals(allocType)) { - alloc = PooledByteBufAllocator.DEFAULT; - logger.debug("-Dgame.net.allocator.type: {}", allocType); - } else { - alloc = UnpooledByteBufAllocator.DEFAULT; - logger.debug("-Dgame.net.allocator.type: unpooled (unknown: {})", allocType); - } - - DEFAULT_ALLOCATOR = alloc; - - THREAD_LOCAL_BUFFER_SIZE = SystemPropertyUtil.getInt("game.net.threadLocalDirectBufferSize", 64 * 1024); - logger.debug("-Dgame.net.threadLocalDirectBufferSize: {}", THREAD_LOCAL_BUFFER_SIZE); - } - - /** - * Returns a hex dump - * of the specified buffer's readable bytes. - */ - public static String hexDump(ByteBuf buffer) { - return hexDump(buffer, buffer.readerIndex(), buffer.readableBytes()); - } - - /** - * Returns a hex dump - * of the specified buffer's sub-region. - */ - public static String hexDump(ByteBuf buffer, int fromIndex, int length) { - if (length < 0) { - throw new IllegalArgumentException("length: " + length); - } - if (length == 0) { - return ""; - } - - int endIndex = fromIndex + length; - char[] buf = new char[length << 1]; - - int srcIdx = fromIndex; - int dstIdx = 0; - for (; srcIdx < endIndex; srcIdx ++, dstIdx += 2) { - System.arraycopy( - HEXDUMP_TABLE, buffer.getUnsignedByte(srcIdx) << 1, - buf, dstIdx, 2); - } - - return new String(buf); - } - - /** - * Calculates the hash code of the specified buffer. This method is - * useful when implementing a new buffer type. - */ - public static int hashCode(ByteBuf buffer) { - final int aLen = buffer.readableBytes(); - final int intCount = aLen >>> 2; - final int byteCount = aLen & 3; - - int hashCode = 1; - int arrayIndex = buffer.readerIndex(); - if (buffer.order() == ByteOrder.BIG_ENDIAN) { - for (int i = intCount; i > 0; i --) { - hashCode = 31 * hashCode + buffer.getInt(arrayIndex); - arrayIndex += 4; - } - } else { - for (int i = intCount; i > 0; i --) { - hashCode = 31 * hashCode + swapInt(buffer.getInt(arrayIndex)); - arrayIndex += 4; - } - } - - for (int i = byteCount; i > 0; i --) { - hashCode = 31 * hashCode + buffer.getByte(arrayIndex ++); - } - - if (hashCode == 0) { - hashCode = 1; - } - - return hashCode; - } - - /** - * Returns {@code true} if and only if the two specified buffers are - * identical to each other as described in {@code ChannelBuffer#equals(Object)}. - * This method is useful when implementing a new buffer type. - */ - public static boolean equals(ByteBuf bufferA, ByteBuf bufferB) { - final int aLen = bufferA.readableBytes(); - if (aLen != bufferB.readableBytes()) { - return false; - } - - final int longCount = aLen >>> 3; - final int byteCount = aLen & 7; - - int aIndex = bufferA.readerIndex(); - int bIndex = bufferB.readerIndex(); - - if (bufferA.order() == bufferB.order()) { - for (int i = longCount; i > 0; i --) { - if (bufferA.getLong(aIndex) != bufferB.getLong(bIndex)) { - return false; - } - aIndex += 8; - bIndex += 8; - } - } else { - for (int i = longCount; i > 0; i --) { - if (bufferA.getLong(aIndex) != swapLong(bufferB.getLong(bIndex))) { - return false; - } - aIndex += 8; - bIndex += 8; - } - } - - for (int i = byteCount; i > 0; i --) { - if (bufferA.getByte(aIndex) != bufferB.getByte(bIndex)) { - return false; - } - aIndex ++; - bIndex ++; - } - - return true; - } - - /** - * Compares the two specified buffers as described in {@link ByteBuf#compareTo(ByteBuf)}. - * This method is useful when implementing a new buffer type. - */ - public static int compare(ByteBuf bufferA, ByteBuf bufferB) { - final int aLen = bufferA.readableBytes(); - final int bLen = bufferB.readableBytes(); - final int minLength = Math.min(aLen, bLen); - final int uintCount = minLength >>> 2; - final int byteCount = minLength & 3; - - int aIndex = bufferA.readerIndex(); - int bIndex = bufferB.readerIndex(); - - if (bufferA.order() == bufferB.order()) { - for (int i = uintCount; i > 0; i --) { - long va = bufferA.getUnsignedInt(aIndex); - long vb = bufferB.getUnsignedInt(bIndex); - if (va > vb) { - return 1; - } - if (va < vb) { - return -1; - } - aIndex += 4; - bIndex += 4; - } - } else { - for (int i = uintCount; i > 0; i --) { - long va = bufferA.getUnsignedInt(aIndex); - long vb = swapInt(bufferB.getInt(bIndex)) & 0xFFFFFFFFL; - if (va > vb) { - return 1; - } - if (va < vb) { - return -1; - } - aIndex += 4; - bIndex += 4; - } - } - - for (int i = byteCount; i > 0; i --) { - short va = bufferA.getUnsignedByte(aIndex); - short vb = bufferB.getUnsignedByte(bIndex); - if (va > vb) { - return 1; - } - if (va < vb) { - return -1; - } - aIndex ++; - bIndex ++; - } - - return aLen - bLen; - } - - /** - * The default implementation of {@link ByteBuf#indexOf(int, int, byte)}. - * This method is useful when implementing a new buffer type. - */ - public static int indexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { - if (fromIndex <= toIndex) { - return firstIndexOf(buffer, fromIndex, toIndex, value); - } else { - return lastIndexOf(buffer, fromIndex, toIndex, value); - } - } - - /** - * Toggles the endianness of the specified 16-bit short integer. - */ - public static short swapShort(short value) { - return Short.reverseBytes(value); - } - - /** - * Toggles the endianness of the specified 24-bit medium integer. - */ - public static int swapMedium(int value) { - int swapped = value << 16 & 0xff0000 | value & 0xff00 | value >>> 16 & 0xff; - if ((swapped & 0x800000) != 0) { - swapped |= 0xff000000; - } - return swapped; - } - - /** - * Toggles the endianness of the specified 32-bit integer. - */ - public static int swapInt(int value) { - return Integer.reverseBytes(value); - } - - /** - * Toggles the endianness of the specified 64-bit long integer. - */ - public static long swapLong(long value) { - return Long.reverseBytes(value); - } - - /** - * Read the given amount of bytes into a new {@link ByteBuf} that is allocated from the {@link ByteBufAllocator}. - */ - public static ByteBuf readBytes(ByteBufAllocator alloc, ByteBuf buffer, int length) { - boolean release = true; - ByteBuf dst = alloc.buffer(length); - try { - buffer.readBytes(dst); - release = false; - return dst; - } finally { - if (release) { - dst.release(); - } - } - } - - private static int firstIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { - fromIndex = Math.max(fromIndex, 0); - if (fromIndex >= toIndex || buffer.capacity() == 0) { - return -1; - } - - for (int i = fromIndex; i < toIndex; i ++) { - if (buffer.getByte(i) == value) { - return i; - } - } - - return -1; - } - - private static int lastIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { - fromIndex = Math.min(fromIndex, buffer.capacity()); - if (fromIndex < 0 || buffer.capacity() == 0) { - return -1; - } - - for (int i = fromIndex - 1; i >= toIndex; i --) { - if (buffer.getByte(i) == value) { - return i; - } - } - - return -1; - } - - /** - * Encode the given {@link CharBuffer} using the given {@link Charset} into a new {@link ByteBuf} which - * is allocated via the {@link ByteBufAllocator}. - */ - public static ByteBuf encodeString(ByteBufAllocator alloc, CharBuffer src, Charset charset) { - return encodeString0(alloc, false, src, charset); - } - - static ByteBuf encodeString0(ByteBufAllocator alloc, boolean enforceHeap, CharBuffer src, Charset charset) { - final CharsetEncoder encoder = CharsetUtil.getEncoder(charset); - int length = (int) ((double) src.remaining() * encoder.maxBytesPerChar()); - boolean release = true; - final ByteBuf dst; - if (enforceHeap) { - dst = alloc.heapBuffer(length); - } else { - dst = alloc.buffer(length); - } - try { - final ByteBuffer dstBuf = dst.internalNioBuffer(0, length); - final int pos = dstBuf.position(); - CoderResult cr = encoder.encode(src, dstBuf, true); - if (!cr.isUnderflow()) { - cr.throwException(); - } - cr = encoder.flush(dstBuf); - if (!cr.isUnderflow()) { - cr.throwException(); - } - dst.writerIndex(dst.writerIndex() + dstBuf.position() - pos); - release = false; - return dst; - } catch (CharacterCodingException x) { - throw new IllegalStateException(x); - } finally { - if (release) { - dst.release(); - } - } - } - - static String decodeString(ByteBuffer src, Charset charset) { - final CharsetDecoder decoder = CharsetUtil.getDecoder(charset); - final CharBuffer dst = CharBuffer.allocate( - (int) ((double) src.remaining() * decoder.maxCharsPerByte())); - try { - CoderResult cr = decoder.decode(src, dst, true); - if (!cr.isUnderflow()) { - cr.throwException(); - } - cr = decoder.flush(dst); - if (!cr.isUnderflow()) { - cr.throwException(); - } - } catch (CharacterCodingException x) { - throw new IllegalStateException(x); - } - return dst.flip().toString(); - } - - /** - * Returns a cached thread-local direct buffer, if available. - * - * @return a cached thread-local direct buffer, if available. {@code null} otherwise. - */ - public static ByteBuf threadLocalDirectBuffer() { - if (THREAD_LOCAL_BUFFER_SIZE <= 0) { - return null; - } - - return ThreadLocalDirectByteBuf.newInstance(); - } - - static final class ThreadLocalDirectByteBuf extends UnpooledDirectByteBuf { - - private static final Recycler RECYCLER = new Recycler() { - @Override - protected ThreadLocalDirectByteBuf newObject(Handle handle) { - return new ThreadLocalDirectByteBuf(handle); - } - }; - - static ThreadLocalDirectByteBuf newInstance() { - ThreadLocalDirectByteBuf buf = RECYCLER.get(); - buf.setRefCnt(1); - return buf; - } - - private final Handle handle; - - private ThreadLocalDirectByteBuf(Handle handle) { - super(UnpooledByteBufAllocator.DEFAULT, 256, Integer.MAX_VALUE); - this.handle = handle; - } - - @Override - protected void deallocate() { - if (capacity() > THREAD_LOCAL_BUFFER_SIZE) { - super.deallocate(); - } else { - clear(); - RECYCLER.recycle(this, handle); - } - } - } - - private ByteBufUtil() { } -} diff --git a/common/src/main/java/common/net/buffer/CompositeByteBuf.java b/common/src/main/java/common/net/buffer/CompositeByteBuf.java deleted file mode 100644 index 1c93f11..0000000 --- a/common/src/main/java/common/net/buffer/CompositeByteBuf.java +++ /dev/null @@ -1,1586 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import common.net.util.ResourceLeak; -import common.net.util.internal.EmptyArrays; - -/** - * A virtual buffer which shows multiple buffers as a single merged buffer. It is recommended to use - * {@link ByteBufAllocator#compositeBuffer()} or {@link Unpooled#wrappedBuffer(ByteBuf...)} instead of calling the - * constructor explicitly. - */ -public class CompositeByteBuf extends AbstractReferenceCountedByteBuf { - - private final ResourceLeak leak; - private final ByteBufAllocator alloc; - private final boolean direct; - private final List components = new ArrayList(); - private final int maxNumComponents; - private static final ByteBuffer FULL_BYTEBUFFER = (ByteBuffer) ByteBuffer.allocate(1).position(1); - - private boolean freed; - - public CompositeByteBuf(ByteBufAllocator alloc, boolean direct, int maxNumComponents) { - super(Integer.MAX_VALUE); - if (alloc == null) { - throw new NullPointerException("alloc"); - } - this.alloc = alloc; - this.direct = direct; - this.maxNumComponents = maxNumComponents; - leak = leakDetector.open(this); - } - - public CompositeByteBuf(ByteBufAllocator alloc, boolean direct, int maxNumComponents, ByteBuf... buffers) { - super(Integer.MAX_VALUE); - if (alloc == null) { - throw new NullPointerException("alloc"); - } - if (maxNumComponents < 2) { - throw new IllegalArgumentException( - "maxNumComponents: " + maxNumComponents + " (expected: >= 2)"); - } - - this.alloc = alloc; - this.direct = direct; - this.maxNumComponents = maxNumComponents; - - addComponents0(0, buffers); - consolidateIfNeeded(); - setIndex(0, capacity()); - leak = leakDetector.open(this); - } - - public CompositeByteBuf( - ByteBufAllocator alloc, boolean direct, int maxNumComponents, Iterable buffers) { - super(Integer.MAX_VALUE); - if (alloc == null) { - throw new NullPointerException("alloc"); - } - if (maxNumComponents < 2) { - throw new IllegalArgumentException( - "maxNumComponents: " + maxNumComponents + " (expected: >= 2)"); - } - - this.alloc = alloc; - this.direct = direct; - this.maxNumComponents = maxNumComponents; - addComponents0(0, buffers); - consolidateIfNeeded(); - setIndex(0, capacity()); - leak = leakDetector.open(this); - } - - /** - * Add the given {@link ByteBuf}. - * - * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. - * If you need to have it increased you need to handle it by your own. - * - * @param buffer the {@link ByteBuf} to add - */ - public CompositeByteBuf addComponent(ByteBuf buffer) { - addComponent0(components.size(), buffer); - consolidateIfNeeded(); - return this; - } - - /** - * Add the given {@link ByteBuf}s. - * - * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. - * If you need to have it increased you need to handle it by your own. - * - * @param buffers the {@link ByteBuf}s to add - */ - public CompositeByteBuf addComponents(ByteBuf... buffers) { - addComponents0(components.size(), buffers); - consolidateIfNeeded(); - return this; - } - - /** - * Add the given {@link ByteBuf}s. - * - * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. - * If you need to have it increased you need to handle it by your own. - * - * @param buffers the {@link ByteBuf}s to add - */ - public CompositeByteBuf addComponents(Iterable buffers) { - addComponents0(components.size(), buffers); - consolidateIfNeeded(); - return this; - } - - /** - * Add the given {@link ByteBuf} on the specific index. - * - * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. - * If you need to have it increased you need to handle it by your own. - * - * @param cIndex the index on which the {@link ByteBuf} will be added - * @param buffer the {@link ByteBuf} to add - */ - public CompositeByteBuf addComponent(int cIndex, ByteBuf buffer) { - addComponent0(cIndex, buffer); - consolidateIfNeeded(); - return this; - } - - private int addComponent0(int cIndex, ByteBuf buffer) { - checkComponentIndex(cIndex); - - if (buffer == null) { - throw new NullPointerException("buffer"); - } - - int readableBytes = buffer.readableBytes(); - if (readableBytes == 0) { - return cIndex; - } - - // No need to consolidate - just add a component to the list. - Component c = new Component(buffer.order(ByteOrder.BIG_ENDIAN).slice()); - if (cIndex == components.size()) { - components.add(c); - if (cIndex == 0) { - c.endOffset = readableBytes; - } else { - Component prev = components.get(cIndex - 1); - c.offset = prev.endOffset; - c.endOffset = c.offset + readableBytes; - } - } else { - components.add(cIndex, c); - updateComponentOffsets(cIndex); - } - return cIndex; - } - - /** - * Add the given {@link ByteBuf}s on the specific index - * - * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. - * If you need to have it increased you need to handle it by your own. - * - * @param cIndex the index on which the {@link ByteBuf} will be added. - * @param buffers the {@link ByteBuf}s to add - */ - public CompositeByteBuf addComponents(int cIndex, ByteBuf... buffers) { - addComponents0(cIndex, buffers); - consolidateIfNeeded(); - return this; - } - - private int addComponents0(int cIndex, ByteBuf... buffers) { - checkComponentIndex(cIndex); - - if (buffers == null) { - throw new NullPointerException("buffers"); - } - - int readableBytes = 0; - for (ByteBuf b: buffers) { - if (b == null) { - break; - } - readableBytes += b.readableBytes(); - } - - if (readableBytes == 0) { - return cIndex; - } - - // No need for consolidation - for (ByteBuf b: buffers) { - if (b == null) { - break; - } - if (b.isReadable()) { - cIndex = addComponent0(cIndex, b) + 1; - int size = components.size(); - if (cIndex > size) { - cIndex = size; - } - } else { - b.release(); - } - } - return cIndex; - } - - /** - * Add the given {@link ByteBuf}s on the specific index - * - * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. - * If you need to have it increased you need to handle it by your own. - * - * @param cIndex the index on which the {@link ByteBuf} will be added. - * @param buffers the {@link ByteBuf}s to add - */ - public CompositeByteBuf addComponents(int cIndex, Iterable buffers) { - addComponents0(cIndex, buffers); - consolidateIfNeeded(); - return this; - } - - private int addComponents0(int cIndex, Iterable buffers) { - if (buffers == null) { - throw new NullPointerException("buffers"); - } - - if (buffers instanceof ByteBuf) { - // If buffers also implements ByteBuf (e.g. CompositeByteBuf), it has to go to addComponent(ByteBuf). - return addComponent0(cIndex, (ByteBuf) buffers); - } - - if (!(buffers instanceof Collection)) { - List list = new ArrayList(); - for (ByteBuf b: buffers) { - list.add(b); - } - buffers = list; - } - - Collection col = (Collection) buffers; - return addComponents0(cIndex, col.toArray(new ByteBuf[col.size()])); - } - - /** - * This should only be called as last operation from a method as this may adjust the underlying - * array of components and so affect the index etc. - */ - private void consolidateIfNeeded() { - // Consolidate if the number of components will exceed the allowed maximum by the current - // operation. - final int numComponents = components.size(); - if (numComponents > maxNumComponents) { - final int capacity = components.get(numComponents - 1).endOffset; - - ByteBuf consolidated = allocBuffer(capacity); - - // We're not using foreach to avoid creating an iterator. - for (int i = 0; i < numComponents; i ++) { - Component c = components.get(i); - ByteBuf b = c.buf; - consolidated.writeBytes(b); - c.freeIfNecessary(); - } - Component c = new Component(consolidated); - c.endOffset = c.length; - components.clear(); - components.add(c); - } - } - - private void checkComponentIndex(int cIndex) { - ensureAccessible(); - if (cIndex < 0 || cIndex > components.size()) { - throw new IndexOutOfBoundsException(String.format( - "cIndex: %d (expected: >= 0 && <= numComponents(%d))", - cIndex, components.size())); - } - } - - private void checkComponentIndex(int cIndex, int numComponents) { - ensureAccessible(); - if (cIndex < 0 || cIndex + numComponents > components.size()) { - throw new IndexOutOfBoundsException(String.format( - "cIndex: %d, numComponents: %d " + - "(expected: cIndex >= 0 && cIndex + numComponents <= totalNumComponents(%d))", - cIndex, numComponents, components.size())); - } - } - - private void updateComponentOffsets(int cIndex) { - int size = components.size(); - if (size <= cIndex) { - return; - } - - Component c = components.get(cIndex); - if (cIndex == 0) { - c.offset = 0; - c.endOffset = c.length; - cIndex ++; - } - - for (int i = cIndex; i < size; i ++) { - Component prev = components.get(i - 1); - Component cur = components.get(i); - cur.offset = prev.endOffset; - cur.endOffset = cur.offset + cur.length; - } - } - - /** - * Remove the {@link ByteBuf} from the given index. - * - * @param cIndex the index on from which the {@link ByteBuf} will be remove - */ - public CompositeByteBuf removeComponent(int cIndex) { - checkComponentIndex(cIndex); - components.remove(cIndex).freeIfNecessary(); - updateComponentOffsets(cIndex); - return this; - } - - /** - * Remove the number of {@link ByteBuf}s starting from the given index. - * - * @param cIndex the index on which the {@link ByteBuf}s will be started to removed - * @param numComponents the number of components to remove - */ - public CompositeByteBuf removeComponents(int cIndex, int numComponents) { - checkComponentIndex(cIndex, numComponents); - - List toRemove = components.subList(cIndex, cIndex + numComponents); - for (Component c: toRemove) { - c.freeIfNecessary(); - } - toRemove.clear(); - - updateComponentOffsets(cIndex); - return this; - } - - public Iterator iterator() { - ensureAccessible(); - List list = new ArrayList(components.size()); - for (Component c: components) { - list.add(c.buf); - } - return list.iterator(); - } - - /** - * Same with {@link #slice(int, int)} except that this method returns a list. - */ - public List decompose(int offset, int length) { - checkIndex(offset, length); - if (length == 0) { - return Collections.emptyList(); - } - - int componentId = toComponentIndex(offset); - List slice = new ArrayList(components.size()); - - // The first component - Component firstC = components.get(componentId); - ByteBuf first = firstC.buf.duplicate(); - first.readerIndex(offset - firstC.offset); - - ByteBuf buf = first; - int bytesToSlice = length; - do { - int readableBytes = buf.readableBytes(); - if (bytesToSlice <= readableBytes) { - // Last component - buf.writerIndex(buf.readerIndex() + bytesToSlice); - slice.add(buf); - break; - } else { - // Not the last component - slice.add(buf); - bytesToSlice -= readableBytes; - componentId ++; - - // Fetch the next component. - buf = components.get(componentId).buf.duplicate(); - } - } while (bytesToSlice > 0); - - // Slice all components because only readable bytes are interesting. - for (int i = 0; i < slice.size(); i ++) { - slice.set(i, slice.get(i).slice()); - } - - return slice; - } - - @Override - public boolean isDirect() { - int size = components.size(); - if (size == 0) { - return false; - } - for (int i = 0; i < size; i++) { - if (!components.get(i).buf.isDirect()) { - return false; - } - } - return true; - } - - @Override - public boolean hasArray() { - if (components.size() == 1) { - return components.get(0).buf.hasArray(); - } - return false; - } - - @Override - public byte[] array() { - if (components.size() == 1) { - return components.get(0).buf.array(); - } - throw new UnsupportedOperationException(); - } - - @Override - public int arrayOffset() { - if (components.size() == 1) { - return components.get(0).buf.arrayOffset(); - } - throw new UnsupportedOperationException(); - } - - @Override - public int capacity() { - if (components.isEmpty()) { - return 0; - } - return components.get(components.size() - 1).endOffset; - } - - @Override - public CompositeByteBuf capacity(int newCapacity) { - ensureAccessible(); - if (newCapacity < 0 || newCapacity > maxCapacity()) { - throw new IllegalArgumentException("newCapacity: " + newCapacity); - } - - int oldCapacity = capacity(); - if (newCapacity > oldCapacity) { - final int paddingLength = newCapacity - oldCapacity; - ByteBuf padding; - int nComponents = components.size(); - if (nComponents < maxNumComponents) { - padding = allocBuffer(paddingLength); - padding.setIndex(0, paddingLength); - addComponent0(components.size(), padding); - } else { - padding = allocBuffer(paddingLength); - padding.setIndex(0, paddingLength); - // FIXME: No need to create a padding buffer and consolidate. - // Just create a big single buffer and put the current content there. - addComponent0(components.size(), padding); - consolidateIfNeeded(); - } - } else if (newCapacity < oldCapacity) { - int bytesToTrim = oldCapacity - newCapacity; - for (ListIterator i = components.listIterator(components.size()); i.hasPrevious();) { - Component c = i.previous(); - if (bytesToTrim >= c.length) { - bytesToTrim -= c.length; - i.remove(); - continue; - } - - // Replace the last component with the trimmed slice. - Component newC = new Component(c.buf.slice(0, c.length - bytesToTrim)); - newC.offset = c.offset; - newC.endOffset = newC.offset + newC.length; - i.set(newC); - break; - } - - if (readerIndex() > newCapacity) { - setIndex(newCapacity, newCapacity); - } else if (writerIndex() > newCapacity) { - writerIndex(newCapacity); - } - } - return this; - } - - @Override - public ByteBufAllocator alloc() { - return alloc; - } - - @Override - public ByteOrder order() { - return ByteOrder.BIG_ENDIAN; - } - - /** - * Return the current number of {@link ByteBuf}'s that are composed in this instance - */ - public int numComponents() { - return components.size(); - } - - /** - * Return the max number of {@link ByteBuf}'s that are composed in this instance - */ - public int maxNumComponents() { - return maxNumComponents; - } - - /** - * Return the index for the given offset - */ - public int toComponentIndex(int offset) { - checkIndex(offset); - - for (int low = 0, high = components.size(); low <= high;) { - int mid = low + high >>> 1; - Component c = components.get(mid); - if (offset >= c.endOffset) { - low = mid + 1; - } else if (offset < c.offset) { - high = mid - 1; - } else { - return mid; - } - } - - throw new Error("should not reach here"); - } - - public int toByteIndex(int cIndex) { - checkComponentIndex(cIndex); - return components.get(cIndex).offset; - } - - @Override - public byte getByte(int index) { - return _getByte(index); - } - - @Override - protected byte _getByte(int index) { - Component c = findComponent(index); - return c.buf.getByte(index - c.offset); - } - - @Override - protected short _getShort(int index) { - Component c = findComponent(index); - if (index + 2 <= c.endOffset) { - return c.buf.getShort(index - c.offset); - } else if (order() == ByteOrder.BIG_ENDIAN) { - return (short) ((_getByte(index) & 0xff) << 8 | _getByte(index + 1) & 0xff); - } else { - return (short) (_getByte(index) & 0xff | (_getByte(index + 1) & 0xff) << 8); - } - } - - @Override - protected int _getUnsignedMedium(int index) { - Component c = findComponent(index); - if (index + 3 <= c.endOffset) { - return c.buf.getUnsignedMedium(index - c.offset); - } else if (order() == ByteOrder.BIG_ENDIAN) { - return (_getShort(index) & 0xffff) << 8 | _getByte(index + 2) & 0xff; - } else { - return _getShort(index) & 0xFFFF | (_getByte(index + 2) & 0xFF) << 16; - } - } - - @Override - protected int _getInt(int index) { - Component c = findComponent(index); - if (index + 4 <= c.endOffset) { - return c.buf.getInt(index - c.offset); - } else if (order() == ByteOrder.BIG_ENDIAN) { - return (_getShort(index) & 0xffff) << 16 | _getShort(index + 2) & 0xffff; - } else { - return _getShort(index) & 0xFFFF | (_getShort(index + 2) & 0xFFFF) << 16; - } - } - - @Override - protected long _getLong(int index) { - Component c = findComponent(index); - if (index + 8 <= c.endOffset) { - return c.buf.getLong(index - c.offset); - } else if (order() == ByteOrder.BIG_ENDIAN) { - return (_getInt(index) & 0xffffffffL) << 32 | _getInt(index + 4) & 0xffffffffL; - } else { - return _getInt(index) & 0xFFFFFFFFL | (_getInt(index + 4) & 0xFFFFFFFFL) << 32; - } - } - - @Override - public CompositeByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - checkDstIndex(index, length, dstIndex, dst.length); - if (length == 0) { - return this; - } - - int i = toComponentIndex(index); - while (length > 0) { - Component c = components.get(i); - ByteBuf s = c.buf; - int adjustment = c.offset; - int localLength = Math.min(length, s.capacity() - (index - adjustment)); - s.getBytes(index - adjustment, dst, dstIndex, localLength); - index += localLength; - dstIndex += localLength; - length -= localLength; - i ++; - } - return this; - } - - @Override - public CompositeByteBuf getBytes(int index, ByteBuffer dst) { - int limit = dst.limit(); - int length = dst.remaining(); - - checkIndex(index, length); - if (length == 0) { - return this; - } - - int i = toComponentIndex(index); - try { - while (length > 0) { - Component c = components.get(i); - ByteBuf s = c.buf; - int adjustment = c.offset; - int localLength = Math.min(length, s.capacity() - (index - adjustment)); - dst.limit(dst.position() + localLength); - s.getBytes(index - adjustment, dst); - index += localLength; - length -= localLength; - i ++; - } - } finally { - dst.limit(limit); - } - return this; - } - - @Override - public CompositeByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - checkDstIndex(index, length, dstIndex, dst.capacity()); - if (length == 0) { - return this; - } - - int i = toComponentIndex(index); - while (length > 0) { - Component c = components.get(i); - ByteBuf s = c.buf; - int adjustment = c.offset; - int localLength = Math.min(length, s.capacity() - (index - adjustment)); - s.getBytes(index - adjustment, dst, dstIndex, localLength); - index += localLength; - dstIndex += localLength; - length -= localLength; - i ++; - } - return this; - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) - throws IOException { - int count = nioBufferCount(); - if (count == 1) { - return out.write(internalNioBuffer(index, length)); - } else { - long writtenBytes = out.write(nioBuffers(index, length)); - if (writtenBytes > Integer.MAX_VALUE) { - return Integer.MAX_VALUE; - } else { - return (int) writtenBytes; - } - } - } - - @Override - public CompositeByteBuf getBytes(int index, OutputStream out, int length) throws IOException { - checkIndex(index, length); - if (length == 0) { - return this; - } - - int i = toComponentIndex(index); - while (length > 0) { - Component c = components.get(i); - ByteBuf s = c.buf; - int adjustment = c.offset; - int localLength = Math.min(length, s.capacity() - (index - adjustment)); - s.getBytes(index - adjustment, out, localLength); - index += localLength; - length -= localLength; - i ++; - } - return this; - } - - @Override - public CompositeByteBuf setByte(int index, int value) { - Component c = findComponent(index); - c.buf.setByte(index - c.offset, value); - return this; - } - - @Override - protected void _setByte(int index, int value) { - setByte(index, value); - } - - @Override - public CompositeByteBuf setShort(int index, int value) { - return (CompositeByteBuf) super.setShort(index, value); - } - - @Override - protected void _setShort(int index, int value) { - Component c = findComponent(index); - if (index + 2 <= c.endOffset) { - c.buf.setShort(index - c.offset, value); - } else if (order() == ByteOrder.BIG_ENDIAN) { - _setByte(index, (byte) (value >>> 8)); - _setByte(index + 1, (byte) value); - } else { - _setByte(index, (byte) value); - _setByte(index + 1, (byte) (value >>> 8)); - } - } - - @Override - public CompositeByteBuf setMedium(int index, int value) { - return (CompositeByteBuf) super.setMedium(index, value); - } - - @Override - protected void _setMedium(int index, int value) { - Component c = findComponent(index); - if (index + 3 <= c.endOffset) { - c.buf.setMedium(index - c.offset, value); - } else if (order() == ByteOrder.BIG_ENDIAN) { - _setShort(index, (short) (value >> 8)); - _setByte(index + 2, (byte) value); - } else { - _setShort(index, (short) value); - _setByte(index + 2, (byte) (value >>> 16)); - } - } - - @Override - public CompositeByteBuf setInt(int index, int value) { - return (CompositeByteBuf) super.setInt(index, value); - } - - @Override - protected void _setInt(int index, int value) { - Component c = findComponent(index); - if (index + 4 <= c.endOffset) { - c.buf.setInt(index - c.offset, value); - } else if (order() == ByteOrder.BIG_ENDIAN) { - _setShort(index, (short) (value >>> 16)); - _setShort(index + 2, (short) value); - } else { - _setShort(index, (short) value); - _setShort(index + 2, (short) (value >>> 16)); - } - } - - @Override - public CompositeByteBuf setLong(int index, long value) { - return (CompositeByteBuf) super.setLong(index, value); - } - - @Override - protected void _setLong(int index, long value) { - Component c = findComponent(index); - if (index + 8 <= c.endOffset) { - c.buf.setLong(index - c.offset, value); - } else if (order() == ByteOrder.BIG_ENDIAN) { - _setInt(index, (int) (value >>> 32)); - _setInt(index + 4, (int) value); - } else { - _setInt(index, (int) value); - _setInt(index + 4, (int) (value >>> 32)); - } - } - - @Override - public CompositeByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - checkSrcIndex(index, length, srcIndex, src.length); - if (length == 0) { - return this; - } - - int i = toComponentIndex(index); - while (length > 0) { - Component c = components.get(i); - ByteBuf s = c.buf; - int adjustment = c.offset; - int localLength = Math.min(length, s.capacity() - (index - adjustment)); - s.setBytes(index - adjustment, src, srcIndex, localLength); - index += localLength; - srcIndex += localLength; - length -= localLength; - i ++; - } - return this; - } - - @Override - public CompositeByteBuf setBytes(int index, ByteBuffer src) { - int limit = src.limit(); - int length = src.remaining(); - - checkIndex(index, length); - if (length == 0) { - return this; - } - - int i = toComponentIndex(index); - try { - while (length > 0) { - Component c = components.get(i); - ByteBuf s = c.buf; - int adjustment = c.offset; - int localLength = Math.min(length, s.capacity() - (index - adjustment)); - src.limit(src.position() + localLength); - s.setBytes(index - adjustment, src); - index += localLength; - length -= localLength; - i ++; - } - } finally { - src.limit(limit); - } - return this; - } - - @Override - public CompositeByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - checkSrcIndex(index, length, srcIndex, src.capacity()); - if (length == 0) { - return this; - } - - int i = toComponentIndex(index); - while (length > 0) { - Component c = components.get(i); - ByteBuf s = c.buf; - int adjustment = c.offset; - int localLength = Math.min(length, s.capacity() - (index - adjustment)); - s.setBytes(index - adjustment, src, srcIndex, localLength); - index += localLength; - srcIndex += localLength; - length -= localLength; - i ++; - } - return this; - } - - @Override - public int setBytes(int index, InputStream in, int length) throws IOException { - checkIndex(index, length); - if (length == 0) { - return in.read(EmptyArrays.EMPTY_BYTES); - } - - int i = toComponentIndex(index); - int readBytes = 0; - - do { - Component c = components.get(i); - ByteBuf s = c.buf; - int adjustment = c.offset; - int localLength = Math.min(length, s.capacity() - (index - adjustment)); - int localReadBytes = s.setBytes(index - adjustment, in, localLength); - if (localReadBytes < 0) { - if (readBytes == 0) { - return -1; - } else { - break; - } - } - - if (localReadBytes == localLength) { - index += localLength; - length -= localLength; - readBytes += localLength; - i ++; - } else { - index += localReadBytes; - length -= localReadBytes; - readBytes += localReadBytes; - } - } while (length > 0); - - return readBytes; - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { - checkIndex(index, length); - if (length == 0) { - return in.read(FULL_BYTEBUFFER); - } - - int i = toComponentIndex(index); - int readBytes = 0; - do { - Component c = components.get(i); - ByteBuf s = c.buf; - int adjustment = c.offset; - int localLength = Math.min(length, s.capacity() - (index - adjustment)); - int localReadBytes = s.setBytes(index - adjustment, in, localLength); - - if (localReadBytes == 0) { - break; - } - - if (localReadBytes < 0) { - if (readBytes == 0) { - return -1; - } else { - break; - } - } - - if (localReadBytes == localLength) { - index += localLength; - length -= localLength; - readBytes += localLength; - i ++; - } else { - index += localReadBytes; - length -= localReadBytes; - readBytes += localReadBytes; - } - } while (length > 0); - - return readBytes; - } - - @Override - public ByteBuf copy(int index, int length) { - checkIndex(index, length); - ByteBuf dst = Unpooled.buffer(length); - if (length != 0) { - copyTo(index, length, toComponentIndex(index), dst); - } - return dst; - } - - private void copyTo(int index, int length, int componentId, ByteBuf dst) { - int dstIndex = 0; - int i = componentId; - - while (length > 0) { - Component c = components.get(i); - ByteBuf s = c.buf; - int adjustment = c.offset; - int localLength = Math.min(length, s.capacity() - (index - adjustment)); - s.getBytes(index - adjustment, dst, dstIndex, localLength); - index += localLength; - dstIndex += localLength; - length -= localLength; - i ++; - } - - dst.writerIndex(dst.capacity()); - } - - /** - * Return the {@link ByteBuf} on the specified index - * - * @param cIndex the index for which the {@link ByteBuf} should be returned - * @return buf the {@link ByteBuf} on the specified index - */ - public ByteBuf component(int cIndex) { - return internalComponent(cIndex).duplicate(); - } - - /** - * Return the {@link ByteBuf} on the specified index - * - * @param offset the offset for which the {@link ByteBuf} should be returned - * @return the {@link ByteBuf} on the specified index - */ - public ByteBuf componentAtOffset(int offset) { - return internalComponentAtOffset(offset).duplicate(); - } - - /** - * Return the internal {@link ByteBuf} on the specified index. Note that updating the indexes of the returned - * buffer will lead to an undefined behavior of this buffer. - * - * @param cIndex the index for which the {@link ByteBuf} should be returned - */ - public ByteBuf internalComponent(int cIndex) { - checkComponentIndex(cIndex); - return components.get(cIndex).buf; - } - - /** - * Return the internal {@link ByteBuf} on the specified offset. Note that updating the indexes of the returned - * buffer will lead to an undefined behavior of this buffer. - * - * @param offset the offset for which the {@link ByteBuf} should be returned - */ - public ByteBuf internalComponentAtOffset(int offset) { - return findComponent(offset).buf; - } - - private Component findComponent(int offset) { - checkIndex(offset); - - for (int low = 0, high = components.size(); low <= high;) { - int mid = low + high >>> 1; - Component c = components.get(mid); - if (offset >= c.endOffset) { - low = mid + 1; - } else if (offset < c.offset) { - high = mid - 1; - } else { - return c; - } - } - - throw new Error("should not reach here"); - } - - @Override - public int nioBufferCount() { - if (components.size() == 1) { - return components.get(0).buf.nioBufferCount(); - } else { - int count = 0; - int componentsCount = components.size(); - for (int i = 0; i < componentsCount; i++) { - Component c = components.get(i); - count += c.buf.nioBufferCount(); - } - return count; - } - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - if (components.size() == 1) { - return components.get(0).buf.internalNioBuffer(index, length); - } - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - if (components.size() == 1) { - ByteBuf buf = components.get(0).buf; - if (buf.nioBufferCount() == 1) { - return components.get(0).buf.nioBuffer(index, length); - } - } - ByteBuffer merged = ByteBuffer.allocate(length).order(order()); - ByteBuffer[] buffers = nioBuffers(index, length); - - //noinspection ForLoopReplaceableByForEach - for (int i = 0; i < buffers.length; i++) { - merged.put(buffers[i]); - } - - merged.flip(); - return merged; - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - checkIndex(index, length); - if (length == 0) { - return EmptyArrays.EMPTY_BYTE_BUFFERS; - } - - List buffers = new ArrayList(components.size()); - int i = toComponentIndex(index); - while (length > 0) { - Component c = components.get(i); - ByteBuf s = c.buf; - int adjustment = c.offset; - int localLength = Math.min(length, s.capacity() - (index - adjustment)); - switch (s.nioBufferCount()) { - case 0: - throw new UnsupportedOperationException(); - case 1: - buffers.add(s.nioBuffer(index - adjustment, localLength)); - break; - default: - Collections.addAll(buffers, s.nioBuffers(index - adjustment, localLength)); - } - - index += localLength; - length -= localLength; - i ++; - } - - return buffers.toArray(new ByteBuffer[buffers.size()]); - } - - /** - * Consolidate the composed {@link ByteBuf}s - */ - public CompositeByteBuf consolidate() { - ensureAccessible(); - final int numComponents = numComponents(); - if (numComponents <= 1) { - return this; - } - - final Component last = components.get(numComponents - 1); - final int capacity = last.endOffset; - final ByteBuf consolidated = allocBuffer(capacity); - - for (int i = 0; i < numComponents; i ++) { - Component c = components.get(i); - ByteBuf b = c.buf; - consolidated.writeBytes(b); - c.freeIfNecessary(); - } - - components.clear(); - components.add(new Component(consolidated)); - updateComponentOffsets(0); - return this; - } - - /** - * Consolidate the composed {@link ByteBuf}s - * - * @param cIndex the index on which to start to compose - * @param numComponents the number of components to compose - */ - public CompositeByteBuf consolidate(int cIndex, int numComponents) { - checkComponentIndex(cIndex, numComponents); - if (numComponents <= 1) { - return this; - } - - final int endCIndex = cIndex + numComponents; - final Component last = components.get(endCIndex - 1); - final int capacity = last.endOffset - components.get(cIndex).offset; - final ByteBuf consolidated = allocBuffer(capacity); - - for (int i = cIndex; i < endCIndex; i ++) { - Component c = components.get(i); - ByteBuf b = c.buf; - consolidated.writeBytes(b); - c.freeIfNecessary(); - } - - components.subList(cIndex + 1, endCIndex).clear(); - components.set(cIndex, new Component(consolidated)); - updateComponentOffsets(cIndex); - return this; - } - - /** - * Discard all {@link ByteBuf}s which are read. - */ - public CompositeByteBuf discardReadComponents() { - ensureAccessible(); - final int readerIndex = readerIndex(); - if (readerIndex == 0) { - return this; - } - - // Discard everything if (readerIndex = writerIndex = capacity). - int writerIndex = writerIndex(); - if (readerIndex == writerIndex && writerIndex == capacity()) { - for (Component c: components) { - c.freeIfNecessary(); - } - components.clear(); - setIndex(0, 0); - adjustMarkers(readerIndex); - return this; - } - - // Remove read components. - int firstComponentId = toComponentIndex(readerIndex); - for (int i = 0; i < firstComponentId; i ++) { - components.get(i).freeIfNecessary(); - } - components.subList(0, firstComponentId).clear(); - - // Update indexes and markers. - Component first = components.get(0); - int offset = first.offset; - updateComponentOffsets(0); - setIndex(readerIndex - offset, writerIndex - offset); - adjustMarkers(offset); - return this; - } - - @Override - public CompositeByteBuf discardReadBytes() { - ensureAccessible(); - final int readerIndex = readerIndex(); - if (readerIndex == 0) { - return this; - } - - // Discard everything if (readerIndex = writerIndex = capacity). - int writerIndex = writerIndex(); - if (readerIndex == writerIndex && writerIndex == capacity()) { - for (Component c: components) { - c.freeIfNecessary(); - } - components.clear(); - setIndex(0, 0); - adjustMarkers(readerIndex); - return this; - } - - // Remove read components. - int firstComponentId = toComponentIndex(readerIndex); - for (int i = 0; i < firstComponentId; i ++) { - components.get(i).freeIfNecessary(); - } - components.subList(0, firstComponentId).clear(); - - // Remove or replace the first readable component with a new slice. - Component c = components.get(0); - int adjustment = readerIndex - c.offset; - if (adjustment == c.length) { - // new slice would be empty, so remove instead - components.remove(0); - } else { - Component newC = new Component(c.buf.slice(adjustment, c.length - adjustment)); - components.set(0, newC); - } - - // Update indexes and markers. - updateComponentOffsets(0); - setIndex(0, writerIndex - readerIndex); - adjustMarkers(readerIndex); - return this; - } - - private ByteBuf allocBuffer(int capacity) { - if (direct) { - return alloc().directBuffer(capacity); - } - return alloc().heapBuffer(capacity); - } - - @Override - public String toString() { - String result = super.toString(); - result = result.substring(0, result.length() - 1); - return result + ", components=" + components.size() + ')'; - } - - private static final class Component { - final ByteBuf buf; - final int length; - int offset; - int endOffset; - - Component(ByteBuf buf) { - this.buf = buf; - length = buf.readableBytes(); - } - - void freeIfNecessary() { - // Unwrap so that we can free slices, too. - buf.release(); // We should not get a NPE here. If so, it must be a bug. - } - } - - @Override - public CompositeByteBuf readerIndex(int readerIndex) { - return (CompositeByteBuf) super.readerIndex(readerIndex); - } - - @Override - public CompositeByteBuf writerIndex(int writerIndex) { - return (CompositeByteBuf) super.writerIndex(writerIndex); - } - - @Override - public CompositeByteBuf setIndex(int readerIndex, int writerIndex) { - return (CompositeByteBuf) super.setIndex(readerIndex, writerIndex); - } - - @Override - public CompositeByteBuf clear() { - return (CompositeByteBuf) super.clear(); - } - - @Override - public CompositeByteBuf markReaderIndex() { - return (CompositeByteBuf) super.markReaderIndex(); - } - - @Override - public CompositeByteBuf resetReaderIndex() { - return (CompositeByteBuf) super.resetReaderIndex(); - } - - @Override - public CompositeByteBuf markWriterIndex() { - return (CompositeByteBuf) super.markWriterIndex(); - } - - @Override - public CompositeByteBuf resetWriterIndex() { - return (CompositeByteBuf) super.resetWriterIndex(); - } - - @Override - public CompositeByteBuf ensureWritable(int minWritableBytes) { - return (CompositeByteBuf) super.ensureWritable(minWritableBytes); - } - - @Override - public CompositeByteBuf getBytes(int index, ByteBuf dst) { - return (CompositeByteBuf) super.getBytes(index, dst); - } - - @Override - public CompositeByteBuf getBytes(int index, ByteBuf dst, int length) { - return (CompositeByteBuf) super.getBytes(index, dst, length); - } - - @Override - public CompositeByteBuf getBytes(int index, byte[] dst) { - return (CompositeByteBuf) super.getBytes(index, dst); - } - - @Override - public CompositeByteBuf setBoolean(int index, boolean value) { - return (CompositeByteBuf) super.setBoolean(index, value); - } - - @Override - public CompositeByteBuf setChar(int index, int value) { - return (CompositeByteBuf) super.setChar(index, value); - } - - @Override - public CompositeByteBuf setFloat(int index, float value) { - return (CompositeByteBuf) super.setFloat(index, value); - } - - @Override - public CompositeByteBuf setDouble(int index, double value) { - return (CompositeByteBuf) super.setDouble(index, value); - } - - @Override - public CompositeByteBuf setBytes(int index, ByteBuf src) { - return (CompositeByteBuf) super.setBytes(index, src); - } - - @Override - public CompositeByteBuf setBytes(int index, ByteBuf src, int length) { - return (CompositeByteBuf) super.setBytes(index, src, length); - } - - @Override - public CompositeByteBuf setBytes(int index, byte[] src) { - return (CompositeByteBuf) super.setBytes(index, src); - } - - @Override - public CompositeByteBuf setZero(int index, int length) { - return (CompositeByteBuf) super.setZero(index, length); - } - - @Override - public CompositeByteBuf readBytes(ByteBuf dst) { - return (CompositeByteBuf) super.readBytes(dst); - } - - @Override - public CompositeByteBuf readBytes(ByteBuf dst, int length) { - return (CompositeByteBuf) super.readBytes(dst, length); - } - - @Override - public CompositeByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { - return (CompositeByteBuf) super.readBytes(dst, dstIndex, length); - } - - @Override - public CompositeByteBuf readBytes(byte[] dst) { - return (CompositeByteBuf) super.readBytes(dst); - } - - @Override - public CompositeByteBuf readBytes(byte[] dst, int dstIndex, int length) { - return (CompositeByteBuf) super.readBytes(dst, dstIndex, length); - } - - @Override - public CompositeByteBuf readBytes(ByteBuffer dst) { - return (CompositeByteBuf) super.readBytes(dst); - } - - @Override - public CompositeByteBuf readBytes(OutputStream out, int length) throws IOException { - return (CompositeByteBuf) super.readBytes(out, length); - } - - @Override - public CompositeByteBuf skipBytes(int length) { - return (CompositeByteBuf) super.skipBytes(length); - } - - @Override - public CompositeByteBuf writeBoolean(boolean value) { - return (CompositeByteBuf) super.writeBoolean(value); - } - - @Override - public CompositeByteBuf writeByte(int value) { - return (CompositeByteBuf) super.writeByte(value); - } - - @Override - public CompositeByteBuf writeShort(int value) { - return (CompositeByteBuf) super.writeShort(value); - } - - @Override - public CompositeByteBuf writeMedium(int value) { - return (CompositeByteBuf) super.writeMedium(value); - } - - @Override - public CompositeByteBuf writeInt(int value) { - return (CompositeByteBuf) super.writeInt(value); - } - - @Override - public CompositeByteBuf writeLong(long value) { - return (CompositeByteBuf) super.writeLong(value); - } - - @Override - public CompositeByteBuf writeChar(int value) { - return (CompositeByteBuf) super.writeChar(value); - } - - @Override - public CompositeByteBuf writeFloat(float value) { - return (CompositeByteBuf) super.writeFloat(value); - } - - @Override - public CompositeByteBuf writeDouble(double value) { - return (CompositeByteBuf) super.writeDouble(value); - } - - @Override - public CompositeByteBuf writeBytes(ByteBuf src) { - return (CompositeByteBuf) super.writeBytes(src); - } - - @Override - public CompositeByteBuf writeBytes(ByteBuf src, int length) { - return (CompositeByteBuf) super.writeBytes(src, length); - } - - @Override - public CompositeByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { - return (CompositeByteBuf) super.writeBytes(src, srcIndex, length); - } - - @Override - public CompositeByteBuf writeBytes(byte[] src) { - return (CompositeByteBuf) super.writeBytes(src); - } - - @Override - public CompositeByteBuf writeBytes(byte[] src, int srcIndex, int length) { - return (CompositeByteBuf) super.writeBytes(src, srcIndex, length); - } - - @Override - public CompositeByteBuf writeBytes(ByteBuffer src) { - return (CompositeByteBuf) super.writeBytes(src); - } - - @Override - public CompositeByteBuf writeZero(int length) { - return (CompositeByteBuf) super.writeZero(length); - } - - @Override - public CompositeByteBuf retain(int increment) { - return (CompositeByteBuf) super.retain(increment); - } - - @Override - public CompositeByteBuf retain() { - return (CompositeByteBuf) super.retain(); - } - - @Override - public ByteBuffer[] nioBuffers() { - return nioBuffers(readerIndex(), readableBytes()); - } - - @Override - public CompositeByteBuf discardSomeReadBytes() { - return discardReadComponents(); - } - - @Override - protected void deallocate() { - if (freed) { - return; - } - - freed = true; - int size = components.size(); - // We're not using foreach to avoid creating an iterator. - // see https://github.com/netty/netty/issues/2642 - for (int i = 0; i < size; i++) { - components.get(i).freeIfNecessary(); - } - - if (leak != null) { - leak.close(); - } - } - - @Override - public ByteBuf unwrap() { - return null; - } -} diff --git a/common/src/main/java/common/net/buffer/DuplicatedByteBuf.java b/common/src/main/java/common/net/buffer/DuplicatedByteBuf.java deleted file mode 100644 index a888cd6..0000000 --- a/common/src/main/java/common/net/buffer/DuplicatedByteBuf.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; - - -/** - * A derived buffer which simply forwards all data access requests to its - * parent. It is recommended to use {@link ByteBuf#duplicate()} instead - * of calling the constructor explicitly. - */ -public class DuplicatedByteBuf extends AbstractDerivedByteBuf { - - private final ByteBuf buffer; - - public DuplicatedByteBuf(ByteBuf buffer) { - super(buffer.maxCapacity()); - - if (buffer instanceof DuplicatedByteBuf) { - this.buffer = ((DuplicatedByteBuf) buffer).buffer; - } else { - this.buffer = buffer; - } - - setIndex(buffer.readerIndex(), buffer.writerIndex()); - } - - @Override - public ByteBuf unwrap() { - return buffer; - } - - @Override - public ByteBufAllocator alloc() { - return buffer.alloc(); - } - - @Override - public ByteOrder order() { - return buffer.order(); - } - - @Override - public boolean isDirect() { - return buffer.isDirect(); - } - - @Override - public int capacity() { - return buffer.capacity(); - } - - @Override - public ByteBuf capacity(int newCapacity) { - buffer.capacity(newCapacity); - return this; - } - - @Override - public boolean hasArray() { - return buffer.hasArray(); - } - - @Override - public byte[] array() { - return buffer.array(); - } - - @Override - public int arrayOffset() { - return buffer.arrayOffset(); - } - - @Override - public byte getByte(int index) { - return _getByte(index); - } - - @Override - protected byte _getByte(int index) { - return buffer.getByte(index); - } - - @Override - public short getShort(int index) { - return _getShort(index); - } - - @Override - protected short _getShort(int index) { - return buffer.getShort(index); - } - - @Override - public int getUnsignedMedium(int index) { - return _getUnsignedMedium(index); - } - - @Override - protected int _getUnsignedMedium(int index) { - return buffer.getUnsignedMedium(index); - } - - @Override - public int getInt(int index) { - return _getInt(index); - } - - @Override - protected int _getInt(int index) { - return buffer.getInt(index); - } - - @Override - public long getLong(int index) { - return _getLong(index); - } - - @Override - protected long _getLong(int index) { - return buffer.getLong(index); - } - - @Override - public ByteBuf copy(int index, int length) { - return buffer.copy(index, length); - } - - @Override - public ByteBuf slice(int index, int length) { - return buffer.slice(index, length); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - buffer.getBytes(index, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - buffer.getBytes(index, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - buffer.getBytes(index, dst); - return this; - } - - @Override - public ByteBuf setByte(int index, int value) { - _setByte(index, value); - return this; - } - - @Override - protected void _setByte(int index, int value) { - buffer.setByte(index, value); - } - - @Override - public ByteBuf setShort(int index, int value) { - _setShort(index, value); - return this; - } - - @Override - protected void _setShort(int index, int value) { - buffer.setShort(index, value); - } - - @Override - public ByteBuf setMedium(int index, int value) { - _setMedium(index, value); - return this; - } - - @Override - protected void _setMedium(int index, int value) { - buffer.setMedium(index, value); - } - - @Override - public ByteBuf setInt(int index, int value) { - _setInt(index, value); - return this; - } - - @Override - protected void _setInt(int index, int value) { - buffer.setInt(index, value); - } - - @Override - public ByteBuf setLong(int index, long value) { - _setLong(index, value); - return this; - } - - @Override - protected void _setLong(int index, long value) { - buffer.setLong(index, value); - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - buffer.setBytes(index, src, srcIndex, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - buffer.setBytes(index, src, srcIndex, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - buffer.setBytes(index, src); - return this; - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) - throws IOException { - buffer.getBytes(index, out, length); - return this; - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) - throws IOException { - return buffer.getBytes(index, out, length); - } - - @Override - public int setBytes(int index, InputStream in, int length) - throws IOException { - return buffer.setBytes(index, in, length); - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) - throws IOException { - return buffer.setBytes(index, in, length); - } - - @Override - public int nioBufferCount() { - return buffer.nioBufferCount(); - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - return buffer.nioBuffers(index, length); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - return nioBuffer(index, length); - } - - @Override - public int forEachByte(int index, int length, ByteBufProcessor processor) { - return buffer.forEachByte(index, length, processor); - } - - @Override - public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { - return buffer.forEachByteDesc(index, length, processor); - } -} - diff --git a/common/src/main/java/common/net/buffer/EmptyByteBuf.java b/common/src/main/java/common/net/buffer/EmptyByteBuf.java deleted file mode 100644 index 6c48eea..0000000 --- a/common/src/main/java/common/net/buffer/EmptyByteBuf.java +++ /dev/null @@ -1,842 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.ReadOnlyBufferException; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; -import java.nio.charset.Charset; - -import common.net.util.internal.EmptyArrays; -import common.net.util.internal.StringUtil; - -/** - * An empty {@link ByteBuf} whose capacity and maximum capacity are all {@code 0}. - */ -public final class EmptyByteBuf extends ByteBuf { - - private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocateDirect(0); - - private final ByteBufAllocator alloc; - private final ByteOrder order; - private final String str; - private EmptyByteBuf swapped; - - public EmptyByteBuf(ByteBufAllocator alloc) { - this(alloc, ByteOrder.BIG_ENDIAN); - } - - private EmptyByteBuf(ByteBufAllocator alloc, ByteOrder order) { - if (alloc == null) { - throw new NullPointerException("alloc"); - } - - this.alloc = alloc; - this.order = order; - str = StringUtil.simpleClassName(this) + (order == ByteOrder.BIG_ENDIAN? "BE" : "LE"); - } - - @Override - public int capacity() { - return 0; - } - - @Override - public ByteBuf capacity(int newCapacity) { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBufAllocator alloc() { - return alloc; - } - - @Override - public ByteOrder order() { - return order; - } - - @Override - public ByteBuf unwrap() { - return null; - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - public int maxCapacity() { - return 0; - } - - @Override - public ByteBuf order(ByteOrder endianness) { - if (endianness == null) { - throw new NullPointerException("endianness"); - } - if (endianness == order()) { - return this; - } - - EmptyByteBuf swapped = this.swapped; - if (swapped != null) { - return swapped; - } - - this.swapped = swapped = new EmptyByteBuf(alloc(), endianness); - return swapped; - } - - @Override - public int readerIndex() { - return 0; - } - - @Override - public ByteBuf readerIndex(int readerIndex) { - return checkIndex(readerIndex); - } - - @Override - public int writerIndex() { - return 0; - } - - @Override - public ByteBuf writerIndex(int writerIndex) { - return checkIndex(writerIndex); - } - - @Override - public ByteBuf setIndex(int readerIndex, int writerIndex) { - checkIndex(readerIndex); - checkIndex(writerIndex); - return this; - } - - @Override - public int readableBytes() { - return 0; - } - - @Override - public int writableBytes() { - return 0; - } - - @Override - public int maxWritableBytes() { - return 0; - } - - @Override - public boolean isReadable() { - return false; - } - - @Override - public boolean isWritable() { - return false; - } - - @Override - public ByteBuf clear() { - return this; - } - - @Override - public ByteBuf markReaderIndex() { - return this; - } - - @Override - public ByteBuf resetReaderIndex() { - return this; - } - - @Override - public ByteBuf markWriterIndex() { - return this; - } - - @Override - public ByteBuf resetWriterIndex() { - return this; - } - - @Override - public ByteBuf discardReadBytes() { - return this; - } - - @Override - public ByteBuf discardSomeReadBytes() { - return this; - } - - @Override - public ByteBuf ensureWritable(int minWritableBytes) { - if (minWritableBytes < 0) { - throw new IllegalArgumentException("minWritableBytes: " + minWritableBytes + " (expected: >= 0)"); - } - if (minWritableBytes != 0) { - throw new IndexOutOfBoundsException(); - } - return this; - } - - @Override - public int ensureWritable(int minWritableBytes, boolean force) { - if (minWritableBytes < 0) { - throw new IllegalArgumentException("minWritableBytes: " + minWritableBytes + " (expected: >= 0)"); - } - - if (minWritableBytes == 0) { - return 0; - } - - return 1; - } - - @Override - public boolean getBoolean(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public byte getByte(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public short getUnsignedByte(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public short getShort(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public int getUnsignedShort(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public int getMedium(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public int getUnsignedMedium(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public int getInt(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public long getUnsignedInt(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public long getLong(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public char getChar(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public float getFloat(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public double getDouble(int index) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst) { - return checkIndex(index, dst.writableBytes()); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int length) { - return checkIndex(index, length); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - return checkIndex(index, length); - } - - @Override - public ByteBuf getBytes(int index, byte[] dst) { - return checkIndex(index, dst.length); - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - return checkIndex(index, length); - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - return checkIndex(index, dst.remaining()); - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) { - return checkIndex(index, length); - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) { - checkIndex(index, length); - return 0; - } - - @Override - public ByteBuf setBoolean(int index, boolean value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf setByte(int index, int value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf setShort(int index, int value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf setMedium(int index, int value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf setInt(int index, int value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf setLong(int index, long value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf setChar(int index, int value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf setFloat(int index, float value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf setDouble(int index, double value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int length) { - return checkIndex(index, length); - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - return checkIndex(index, length); - } - - @Override - public ByteBuf setBytes(int index, byte[] src) { - return checkIndex(index, src.length); - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - return checkIndex(index, length); - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - return checkIndex(index, src.remaining()); - } - - @Override - public int setBytes(int index, InputStream in, int length) { - checkIndex(index, length); - return 0; - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) { - checkIndex(index, length); - return 0; - } - - @Override - public ByteBuf setZero(int index, int length) { - return checkIndex(index, length); - } - - @Override - public boolean readBoolean() { - throw new IndexOutOfBoundsException(); - } - - @Override - public byte readByte() { - throw new IndexOutOfBoundsException(); - } - - @Override - public short readUnsignedByte() { - throw new IndexOutOfBoundsException(); - } - - @Override - public short readShort() { - throw new IndexOutOfBoundsException(); - } - - @Override - public int readUnsignedShort() { - throw new IndexOutOfBoundsException(); - } - - @Override - public int readMedium() { - throw new IndexOutOfBoundsException(); - } - - @Override - public int readUnsignedMedium() { - throw new IndexOutOfBoundsException(); - } - - @Override - public int readInt() { - throw new IndexOutOfBoundsException(); - } - - @Override - public long readUnsignedInt() { - throw new IndexOutOfBoundsException(); - } - - @Override - public long readLong() { - throw new IndexOutOfBoundsException(); - } - - @Override - public char readChar() { - throw new IndexOutOfBoundsException(); - } - - @Override - public float readFloat() { - throw new IndexOutOfBoundsException(); - } - - @Override - public double readDouble() { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf readBytes(int length) { - return checkLength(length); - } - - @Override - public ByteBuf readSlice(int length) { - return checkLength(length); - } - - @Override - public ByteBuf readBytes(ByteBuf dst) { - return checkLength(dst.writableBytes()); - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int length) { - return checkLength(length); - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { - return checkLength(length); - } - - @Override - public ByteBuf readBytes(byte[] dst) { - return checkLength(dst.length); - } - - @Override - public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { - return checkLength(length); - } - - @Override - public ByteBuf readBytes(ByteBuffer dst) { - return checkLength(dst.remaining()); - } - - @Override - public ByteBuf readBytes(OutputStream out, int length) { - return checkLength(length); - } - - @Override - public int readBytes(GatheringByteChannel out, int length) { - checkLength(length); - return 0; - } - - @Override - public ByteBuf skipBytes(int length) { - return checkLength(length); - } - - @Override - public ByteBuf writeBoolean(boolean value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf writeByte(int value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf writeShort(int value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf writeMedium(int value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf writeInt(int value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf writeLong(long value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf writeChar(int value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf writeFloat(float value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf writeDouble(double value) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf writeBytes(ByteBuf src) { - throw new IndexOutOfBoundsException(); - } - - @Override - public ByteBuf writeBytes(ByteBuf src, int length) { - return checkLength(length); - } - - @Override - public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { - return checkLength(length); - } - - @Override - public ByteBuf writeBytes(byte[] src) { - return checkLength(src.length); - } - - @Override - public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { - return checkLength(length); - } - - @Override - public ByteBuf writeBytes(ByteBuffer src) { - return checkLength(src.remaining()); - } - - @Override - public int writeBytes(InputStream in, int length) { - checkLength(length); - return 0; - } - - @Override - public int writeBytes(ScatteringByteChannel in, int length) { - checkLength(length); - return 0; - } - - @Override - public ByteBuf writeZero(int length) { - return checkLength(length); - } - - @Override - public int indexOf(int fromIndex, int toIndex, byte value) { - checkIndex(fromIndex); - checkIndex(toIndex); - return -1; - } - - @Override - public int bytesBefore(byte value) { - return -1; - } - - @Override - public int bytesBefore(int length, byte value) { - checkLength(length); - return -1; - } - - @Override - public int bytesBefore(int index, int length, byte value) { - checkIndex(index, length); - return -1; - } - - @Override - public int forEachByte(ByteBufProcessor processor) { - return -1; - } - - @Override - public int forEachByte(int index, int length, ByteBufProcessor processor) { - checkIndex(index, length); - return -1; - } - - @Override - public int forEachByteDesc(ByteBufProcessor processor) { - return -1; - } - - @Override - public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { - checkIndex(index, length); - return -1; - } - - @Override - public ByteBuf copy() { - return this; - } - - @Override - public ByteBuf copy(int index, int length) { - return checkIndex(index, length); - } - - @Override - public ByteBuf slice() { - return this; - } - - @Override - public ByteBuf slice(int index, int length) { - return checkIndex(index, length); - } - - @Override - public ByteBuf duplicate() { - return this; - } - - @Override - public int nioBufferCount() { - return 1; - } - - @Override - public ByteBuffer nioBuffer() { - return EMPTY_BYTE_BUFFER; - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - checkIndex(index, length); - return nioBuffer(); - } - - @Override - public ByteBuffer[] nioBuffers() { - return new ByteBuffer[] { EMPTY_BYTE_BUFFER }; - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - checkIndex(index, length); - return nioBuffers(); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - return EMPTY_BYTE_BUFFER; - } - - @Override - public boolean hasArray() { - return true; - } - - @Override - public byte[] array() { - return EmptyArrays.EMPTY_BYTES; - } - - @Override - public int arrayOffset() { - return 0; - } - - @Override - public String toString(Charset charset) { - return ""; - } - - @Override - public String toString(int index, int length, Charset charset) { - checkIndex(index, length); - return toString(charset); - } - - @Override - public int hashCode() { - return 0; - } - - @Override - public boolean equals(Object obj) { - return obj instanceof ByteBuf && !((ByteBuf) obj).isReadable(); - } - - @Override - public int compareTo(ByteBuf buffer) { - return buffer.isReadable()? -1 : 0; - } - - @Override - public String toString() { - return str; - } - - @Override - public boolean isReadable(int size) { - return false; - } - - @Override - public boolean isWritable(int size) { - return false; - } - - @Override - public int refCnt() { - return 1; - } - - @Override - public ByteBuf retain() { - return this; - } - - @Override - public ByteBuf retain(int increment) { - return this; - } - - @Override - public boolean release() { - return false; - } - - @Override - public boolean release(int decrement) { - return false; - } - - private ByteBuf checkIndex(int index) { - if (index != 0) { - throw new IndexOutOfBoundsException(); - } - return this; - } - - private ByteBuf checkIndex(int index, int length) { - if (length < 0) { - throw new IllegalArgumentException("length: " + length); - } - if (index != 0 || length != 0) { - throw new IndexOutOfBoundsException(); - } - return this; - } - - private ByteBuf checkLength(int length) { - if (length < 0) { - throw new IllegalArgumentException("length: " + length + " (expected: >= 0)"); - } - if (length != 0) { - throw new IndexOutOfBoundsException(); - } - return this; - } -} diff --git a/common/src/main/java/common/net/buffer/PoolArena.java b/common/src/main/java/common/net/buffer/PoolArena.java deleted file mode 100644 index 6752ab3..0000000 --- a/common/src/main/java/common/net/buffer/PoolArena.java +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import java.nio.ByteBuffer; - -import common.net.util.internal.StringUtil; - -abstract class PoolArena { - - static final int numTinySubpagePools = 512 >>> 4; - - final PooledByteBufAllocator parent; - - private final int maxOrder; - final int pageSize; - final int pageShifts; - final int chunkSize; - final int subpageOverflowMask; - final int numSmallSubpagePools; - private final PoolSubpage[] tinySubpagePools; - private final PoolSubpage[] smallSubpagePools; - - private final PoolChunkList q050; - private final PoolChunkList q025; - private final PoolChunkList q000; - private final PoolChunkList qInit; - private final PoolChunkList q075; - private final PoolChunkList q100; - - // TODO: Test if adding padding helps under contention - //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; - - protected PoolArena(PooledByteBufAllocator parent, int pageSize, int maxOrder, int pageShifts, int chunkSize) { - this.parent = parent; - this.pageSize = pageSize; - this.maxOrder = maxOrder; - this.pageShifts = pageShifts; - this.chunkSize = chunkSize; - subpageOverflowMask = ~(pageSize - 1); - tinySubpagePools = newSubpagePoolArray(numTinySubpagePools); - for (int i = 0; i < tinySubpagePools.length; i ++) { - tinySubpagePools[i] = newSubpagePoolHead(pageSize); - } - - numSmallSubpagePools = pageShifts - 9; - smallSubpagePools = newSubpagePoolArray(numSmallSubpagePools); - for (int i = 0; i < smallSubpagePools.length; i ++) { - smallSubpagePools[i] = newSubpagePoolHead(pageSize); - } - - q100 = new PoolChunkList(this, null, 100, Integer.MAX_VALUE); - q075 = new PoolChunkList(this, q100, 75, 100); - q050 = new PoolChunkList(this, q075, 50, 100); - q025 = new PoolChunkList(this, q050, 25, 75); - q000 = new PoolChunkList(this, q025, 1, 50); - qInit = new PoolChunkList(this, q000, Integer.MIN_VALUE, 25); - - q100.prevList = q075; - q075.prevList = q050; - q050.prevList = q025; - q025.prevList = q000; - q000.prevList = null; - qInit.prevList = qInit; - } - - private PoolSubpage newSubpagePoolHead(int pageSize) { - PoolSubpage head = new PoolSubpage(pageSize); - head.prev = head; - head.next = head; - return head; - } - - - private PoolSubpage[] newSubpagePoolArray(int size) { - return new PoolSubpage[size]; - } - - abstract boolean isDirect(); - - PooledByteBuf allocate(PoolThreadCache cache, int reqCapacity, int maxCapacity) { - PooledByteBuf buf = newByteBuf(maxCapacity); - allocate(cache, buf, reqCapacity); - return buf; - } - - static int tinyIdx(int normCapacity) { - return normCapacity >>> 4; - } - - static int smallIdx(int normCapacity) { - int tableIdx = 0; - int i = normCapacity >>> 10; - while (i != 0) { - i >>>= 1; - tableIdx ++; - } - return tableIdx; - } - - // capacity < pageSize - boolean isTinyOrSmall(int normCapacity) { - return (normCapacity & subpageOverflowMask) == 0; - } - - // normCapacity < 512 - static boolean isTiny(int normCapacity) { - return (normCapacity & 0xFFFFFE00) == 0; - } - - private void allocate(PoolThreadCache cache, PooledByteBuf buf, final int reqCapacity) { - final int normCapacity = normalizeCapacity(reqCapacity); - if (isTinyOrSmall(normCapacity)) { // capacity < pageSize - int tableIdx; - PoolSubpage[] table; - if (isTiny(normCapacity)) { // < 512 - if (cache.allocateTiny(this, buf, reqCapacity, normCapacity)) { - // was able to allocate out of the cache so move on - return; - } - tableIdx = tinyIdx(normCapacity); - table = tinySubpagePools; - } else { - if (cache.allocateSmall(this, buf, reqCapacity, normCapacity)) { - // was able to allocate out of the cache so move on - return; - } - tableIdx = smallIdx(normCapacity); - table = smallSubpagePools; - } - - synchronized (this) { - final PoolSubpage head = table[tableIdx]; - final PoolSubpage s = head.next; - if (s != head) { - assert s.doNotDestroy && s.elemSize == normCapacity; - long handle = s.allocate(); - assert handle >= 0; - s.chunk.initBufWithSubpage(buf, handle, reqCapacity); - return; - } - } - } else if (normCapacity <= chunkSize) { - if (cache.allocateNormal(this, buf, reqCapacity, normCapacity)) { - // was able to allocate out of the cache so move on - return; - } - } else { - // Huge allocations are never served via the cache so just call allocateHuge - allocateHuge(buf, reqCapacity); - return; - } - allocateNormal(buf, reqCapacity, normCapacity); - } - - private synchronized void allocateNormal(PooledByteBuf buf, int reqCapacity, int normCapacity) { - if (q050.allocate(buf, reqCapacity, normCapacity) || q025.allocate(buf, reqCapacity, normCapacity) || - q000.allocate(buf, reqCapacity, normCapacity) || qInit.allocate(buf, reqCapacity, normCapacity) || - q075.allocate(buf, reqCapacity, normCapacity) || q100.allocate(buf, reqCapacity, normCapacity)) { - return; - } - - // Add a new chunk. - PoolChunk c = newChunk(pageSize, maxOrder, pageShifts, chunkSize); - long handle = c.allocate(normCapacity); - assert handle > 0; - c.initBuf(buf, handle, reqCapacity); - qInit.add(c); - } - - private void allocateHuge(PooledByteBuf buf, int reqCapacity) { - buf.initUnpooled(newUnpooledChunk(reqCapacity), reqCapacity); - } - - void free(PoolChunk chunk, long handle, int normCapacity) { - if (chunk.unpooled) { - destroyChunk(chunk); - } else { - PoolThreadCache cache = parent.threadCache.get(); - if (cache.add(this, chunk, handle, normCapacity)) { - // cached so not free it. - return; - } - synchronized (this) { - chunk.parent.free(chunk, handle); - } - } - } - - PoolSubpage findSubpagePoolHead(int elemSize) { - int tableIdx; - PoolSubpage[] table; - if (isTiny(elemSize)) { // < 512 - tableIdx = elemSize >>> 4; - table = tinySubpagePools; - } else { - tableIdx = 0; - elemSize >>>= 10; - while (elemSize != 0) { - elemSize >>>= 1; - tableIdx ++; - } - table = smallSubpagePools; - } - - return table[tableIdx]; - } - - int normalizeCapacity(int reqCapacity) { - if (reqCapacity < 0) { - throw new IllegalArgumentException("capacity: " + reqCapacity + " (expected: 0+)"); - } - if (reqCapacity >= chunkSize) { - return reqCapacity; - } - - if (!isTiny(reqCapacity)) { // >= 512 - // Doubled - - int normalizedCapacity = reqCapacity; - normalizedCapacity --; - normalizedCapacity |= normalizedCapacity >>> 1; - normalizedCapacity |= normalizedCapacity >>> 2; - normalizedCapacity |= normalizedCapacity >>> 4; - normalizedCapacity |= normalizedCapacity >>> 8; - normalizedCapacity |= normalizedCapacity >>> 16; - normalizedCapacity ++; - - if (normalizedCapacity < 0) { - normalizedCapacity >>>= 1; - } - - return normalizedCapacity; - } - - // Quantum-spaced - if ((reqCapacity & 15) == 0) { - return reqCapacity; - } - - return (reqCapacity & ~15) + 16; - } - - void reallocate(PooledByteBuf buf, int newCapacity, boolean freeOldMemory) { - if (newCapacity < 0 || newCapacity > buf.maxCapacity()) { - throw new IllegalArgumentException("newCapacity: " + newCapacity); - } - - int oldCapacity = buf.length; - if (oldCapacity == newCapacity) { - return; - } - - PoolChunk oldChunk = buf.chunk; - long oldHandle = buf.handle; - T oldMemory = buf.memory; - int oldOffset = buf.offset; - int oldMaxLength = buf.maxLength; - int readerIndex = buf.readerIndex(); - int writerIndex = buf.writerIndex(); - - allocate(parent.threadCache.get(), buf, newCapacity); - if (newCapacity > oldCapacity) { - memoryCopy( - oldMemory, oldOffset, - buf.memory, buf.offset, oldCapacity); - } else if (newCapacity < oldCapacity) { - if (readerIndex < newCapacity) { - if (writerIndex > newCapacity) { - writerIndex = newCapacity; - } - memoryCopy( - oldMemory, oldOffset + readerIndex, - buf.memory, buf.offset + readerIndex, writerIndex - readerIndex); - } else { - readerIndex = writerIndex = newCapacity; - } - } - - buf.setIndex(readerIndex, writerIndex); - - if (freeOldMemory) { - free(oldChunk, oldHandle, oldMaxLength); - } - } - - protected abstract PoolChunk newChunk(int pageSize, int maxOrder, int pageShifts, int chunkSize); - protected abstract PoolChunk newUnpooledChunk(int capacity); - protected abstract PooledByteBuf newByteBuf(int maxCapacity); - protected abstract void memoryCopy(T src, int srcOffset, T dst, int dstOffset, int length); - protected abstract void destroyChunk(PoolChunk chunk); - - public synchronized String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("Chunk(s) at 0~25%:"); - buf.append(StringUtil.NEWLINE); - buf.append(qInit); - buf.append(StringUtil.NEWLINE); - buf.append("Chunk(s) at 0~50%:"); - buf.append(StringUtil.NEWLINE); - buf.append(q000); - buf.append(StringUtil.NEWLINE); - buf.append("Chunk(s) at 25~75%:"); - buf.append(StringUtil.NEWLINE); - buf.append(q025); - buf.append(StringUtil.NEWLINE); - buf.append("Chunk(s) at 50~100%:"); - buf.append(StringUtil.NEWLINE); - buf.append(q050); - buf.append(StringUtil.NEWLINE); - buf.append("Chunk(s) at 75~100%:"); - buf.append(StringUtil.NEWLINE); - buf.append(q075); - buf.append(StringUtil.NEWLINE); - buf.append("Chunk(s) at 100%:"); - buf.append(StringUtil.NEWLINE); - buf.append(q100); - buf.append(StringUtil.NEWLINE); - buf.append("tiny subpages:"); - for (int i = 1; i < tinySubpagePools.length; i ++) { - PoolSubpage head = tinySubpagePools[i]; - if (head.next == head) { - continue; - } - - buf.append(StringUtil.NEWLINE); - buf.append(i); - buf.append(": "); - PoolSubpage s = head.next; - for (;;) { - buf.append(s); - s = s.next; - if (s == head) { - break; - } - } - } - buf.append(StringUtil.NEWLINE); - buf.append("small subpages:"); - for (int i = 1; i < smallSubpagePools.length; i ++) { - PoolSubpage head = smallSubpagePools[i]; - if (head.next == head) { - continue; - } - - buf.append(StringUtil.NEWLINE); - buf.append(i); - buf.append(": "); - PoolSubpage s = head.next; - for (;;) { - buf.append(s); - s = s.next; - if (s == head) { - break; - } - } - } - buf.append(StringUtil.NEWLINE); - - return buf.toString(); - } - - static final class HeapArena extends PoolArena { - - HeapArena(PooledByteBufAllocator parent, int pageSize, int maxOrder, int pageShifts, int chunkSize) { - super(parent, pageSize, maxOrder, pageShifts, chunkSize); - } - - @Override - boolean isDirect() { - return false; - } - - @Override - protected PoolChunk newChunk(int pageSize, int maxOrder, int pageShifts, int chunkSize) { - return new PoolChunk(this, new byte[chunkSize], pageSize, maxOrder, pageShifts, chunkSize); - } - - @Override - protected PoolChunk newUnpooledChunk(int capacity) { - return new PoolChunk(this, new byte[capacity], capacity); - } - - @Override - protected void destroyChunk(PoolChunk chunk) { - // Rely on GC. - } - - @Override - protected PooledByteBuf newByteBuf(int maxCapacity) { - return PooledHeapByteBuf.newInstance(maxCapacity); - } - - @Override - protected void memoryCopy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int length) { - if (length == 0) { - return; - } - - System.arraycopy(src, srcOffset, dst, dstOffset, length); - } - } - - static final class DirectArena extends PoolArena { - DirectArena(PooledByteBufAllocator parent, int pageSize, int maxOrder, int pageShifts, int chunkSize) { - super(parent, pageSize, maxOrder, pageShifts, chunkSize); - } - - @Override - boolean isDirect() { - return true; - } - - @Override - protected PoolChunk newChunk(int pageSize, int maxOrder, int pageShifts, int chunkSize) { - return new PoolChunk( - this, ByteBuffer.allocateDirect(chunkSize), pageSize, maxOrder, pageShifts, chunkSize); - } - - @Override - protected PoolChunk newUnpooledChunk(int capacity) { - return new PoolChunk(this, ByteBuffer.allocateDirect(capacity), capacity); - } - - @Override - protected void destroyChunk(PoolChunk chunk) { - } - - @Override - protected PooledByteBuf newByteBuf(int maxCapacity) { - return PooledDirectByteBuf.newInstance(maxCapacity); - } - - @Override - protected void memoryCopy(ByteBuffer src, int srcOffset, ByteBuffer dst, int dstOffset, int length) { - if (length == 0) { - return; - } - - // We must duplicate the NIO buffers because they may be accessed by other Netty buffers. - src = src.duplicate(); - dst = dst.duplicate(); - src.position(srcOffset).limit(srcOffset + length); - dst.position(dstOffset); - dst.put(src); - } - } -} diff --git a/common/src/main/java/common/net/buffer/PoolChunk.java b/common/src/main/java/common/net/buffer/PoolChunk.java deleted file mode 100644 index 87234ec..0000000 --- a/common/src/main/java/common/net/buffer/PoolChunk.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -/** - * Description of algorithm for PageRun/PoolSubpage allocation from PoolChunk - * - * Notation: The following terms are important to understand the code - * > page - a page is the smallest unit of memory chunk that can be allocated - * > chunk - a chunk is a collection of pages - * > in this code chunkSize = 2^{maxOrder} * pageSize - * - * To begin we allocate a byte array of size = chunkSize - * Whenever a ByteBuf of given size needs to be created we search for the first position - * in the byte array that has enough empty space to accommodate the requested size and - * return a (long) handle that encodes this offset information, (this memory segment is then - * marked as reserved so it is always used by exactly one ByteBuf and no more) - * - * For simplicity all sizes are normalized according to PoolArena#normalizeCapacity method - * This ensures that when we request for memory segments of size >= pageSize the normalizedCapacity - * equals the next nearest power of 2 - * - * To search for the first offset in chunk that has at least requested size available we construct a - * complete balanced binary tree and store it in an array (just like heaps) - memoryMap - * - * The tree looks like this (the size of each node being mentioned in the parenthesis) - * - * depth=0 1 node (chunkSize) - * depth=1 2 nodes (chunkSize/2) - * .. - * .. - * depth=d 2^d nodes (chunkSize/2^d) - * .. - * depth=maxOrder 2^maxOrder nodes (chunkSize/2^{maxOrder} = pageSize) - * - * depth=maxOrder is the last level and the leafs consist of pages - * - * With this tree available searching in chunkArray translates like this: - * To allocate a memory segment of size chunkSize/2^k we search for the first node (from left) at height k - * which is unused - * - * Algorithm: - * ---------- - * Encode the tree in memoryMap with the notation - * memoryMap[id] = x => in the subtree rooted at id, the first node that is free to be allocated - * is at depth x (counted from depth=0) i.e., at depths [depth_of_id, x), there is no node that is free - * - * As we allocate & free nodes, we update values stored in memoryMap so that the property is maintained - * - * Initialization - - * In the beginning we construct the memoryMap array by storing the depth of a node at each node - * i.e., memoryMap[id] = depth_of_id - * - * Observations: - * ------------- - * 1) memoryMap[id] = depth_of_id => it is free / unallocated - * 2) memoryMap[id] > depth_of_id => at least one of its child nodes is allocated, so we cannot allocate it, but - * some of its children can still be allocated based on their availability - * 3) memoryMap[id] = maxOrder + 1 => the node is fully allocated & thus none of its children can be allocated, it - * is thus marked as unusable - * - * Algorithm: [allocateNode(d) => we want to find the first node (from left) at height h that can be allocated] - * ---------- - * 1) start at root (i.e., depth = 0 or id = 1) - * 2) if memoryMap[1] > d => cannot be allocated from this chunk - * 3) if left node value <= h; we can allocate from left subtree so move to left and repeat until found - * 4) else try in right subtree - * - * Algorithm: [allocateRun(size)] - * ---------- - * 1) Compute d = log_2(chunkSize/size) - * 2) Return allocateNode(d) - * - * Algorithm: [allocateSubpage(size)] - * ---------- - * 1) use allocateNode(maxOrder) to find an empty (i.e., unused) leaf (i.e., page) - * 2) use this handle to construct the PoolSubpage object or if it already exists just call init(normCapacity) - * note that this PoolSubpage object is added to subpagesPool in the PoolArena when we init() it - * - * Note: - * ----- - * In the implementation for improving cache coherence, - * we store 2 pieces of information (i.e, 2 byte vals) as a short value in memoryMap - * - * memoryMap[id]= (depth_of_id, x) - * where as per convention defined above - * the second value (i.e, x) indicates that the first node which is free to be allocated is at depth x (from root) - */ - -final class PoolChunk { - - final PoolArena arena; - final T memory; - final boolean unpooled; - - private final byte[] memoryMap; - private final byte[] depthMap; - private final PoolSubpage[] subpages; - /** Used to determine if the requested capacity is equal to or greater than pageSize. */ - private final int subpageOverflowMask; - private final int pageSize; - private final int pageShifts; - private final int maxOrder; - private final int chunkSize; - private final int log2ChunkSize; - private final int maxSubpageAllocs; - /** Used to mark memory as unusable */ - private final byte unusable; - - private int freeBytes; - - PoolChunkList parent; - PoolChunk prev; - PoolChunk next; - - // TODO: Test if adding padding helps under contention - //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; - - PoolChunk(PoolArena arena, T memory, int pageSize, int maxOrder, int pageShifts, int chunkSize) { - unpooled = false; - this.arena = arena; - this.memory = memory; - this.pageSize = pageSize; - this.pageShifts = pageShifts; - this.maxOrder = maxOrder; - this.chunkSize = chunkSize; - unusable = (byte) (maxOrder + 1); - log2ChunkSize = log2(chunkSize); - subpageOverflowMask = ~(pageSize - 1); - freeBytes = chunkSize; - - assert maxOrder < 30 : "maxOrder should be < 30, but is: " + maxOrder; - maxSubpageAllocs = 1 << maxOrder; - - // Generate the memory map. - memoryMap = new byte[maxSubpageAllocs << 1]; - depthMap = new byte[memoryMap.length]; - int memoryMapIndex = 1; - for (int d = 0; d <= maxOrder; ++ d) { // move down the tree one level at a time - int depth = 1 << d; - for (int p = 0; p < depth; ++ p) { - // in each level traverse left to right and set value to the depth of subtree - memoryMap[memoryMapIndex] = (byte) d; - depthMap[memoryMapIndex] = (byte) d; - memoryMapIndex ++; - } - } - - subpages = newSubpageArray(maxSubpageAllocs); - } - - /** Creates a special chunk that is not pooled. */ - PoolChunk(PoolArena arena, T memory, int size) { - unpooled = true; - this.arena = arena; - this.memory = memory; - memoryMap = null; - depthMap = null; - subpages = null; - subpageOverflowMask = 0; - pageSize = 0; - pageShifts = 0; - maxOrder = 0; - unusable = (byte) (maxOrder + 1); - chunkSize = size; - log2ChunkSize = log2(chunkSize); - maxSubpageAllocs = 0; - } - - - private PoolSubpage[] newSubpageArray(int size) { - return new PoolSubpage[size]; - } - - int usage() { - final int freeBytes = this.freeBytes; - if (freeBytes == 0) { - return 100; - } - - int freePercentage = (int) (freeBytes * 100L / chunkSize); - if (freePercentage == 0) { - return 99; - } - return 100 - freePercentage; - } - - long allocate(int normCapacity) { - if ((normCapacity & subpageOverflowMask) != 0) { // >= pageSize - return allocateRun(normCapacity); - } else { - return allocateSubpage(normCapacity); - } - } - - /** - * Update method used by allocate - * This is triggered only when a successor is allocated and all its predecessors - * need to update their state - * The minimal depth at which subtree rooted at id has some free space - * - * @param id id - */ - private void updateParentsAlloc(int id) { - while (id > 1) { - int parentId = id >>> 1; - byte val1 = value(id); - byte val2 = value(id ^ 1); - byte val = val1 < val2 ? val1 : val2; - setValue(parentId, val); - id = parentId; - } - } - - /** - * Update method used by free - * This needs to handle the special case when both children are completely free - * in which case parent be directly allocated on request of size = child-size * 2 - * - * @param id id - */ - private void updateParentsFree(int id) { - int logChild = depth(id) + 1; - while (id > 1) { - int parentId = id >>> 1; - byte val1 = value(id); - byte val2 = value(id ^ 1); - logChild -= 1; // in first iteration equals log, subsequently reduce 1 from logChild as we traverse up - - if (val1 == logChild && val2 == logChild) { - setValue(parentId, (byte) (logChild - 1)); - } else { - byte val = val1 < val2 ? val1 : val2; - setValue(parentId, val); - } - - id = parentId; - } - } - - /** - * Algorithm to allocate an index in memoryMap when we query for a free node - * at depth d - * - * @param d depth - * @return index in memoryMap - */ - private int allocateNode(int d) { - int id = 1; - int initial = - (1 << d); // has last d bits = 0 and rest all = 1 - byte val = value(id); - if (val > d) { // unusable - return -1; - } - while (val < d || (id & initial) == 0) { // id & initial == 1 << d for all ids at depth d, for < d it is 0 - id <<= 1; - val = value(id); - if (val > d) { - id ^= 1; - val = value(id); - } - } - byte value = value(id); - assert value == d && (id & initial) == 1 << d : String.format("val = %d, id & initial = %d, d = %d", - value, id & initial, d); - setValue(id, unusable); // mark as unusable - updateParentsAlloc(id); - return id; - } - - /** - * Allocate a run of pages (>=1) - * - * @param normCapacity normalized capacity - * @return index in memoryMap - */ - private long allocateRun(int normCapacity) { - int d = maxOrder - (log2(normCapacity) - pageShifts); - int id = allocateNode(d); - if (id < 0) { - return id; - } - freeBytes -= runLength(id); - return id; - } - - /** - * Create/ initialize a new PoolSubpage of normCapacity - * Any PoolSubpage created/ initialized here is added to subpage pool in the PoolArena that owns this PoolChunk - * - * @param normCapacity normalized capacity - * @return index in memoryMap - */ - private long allocateSubpage(int normCapacity) { - int d = maxOrder; // subpages are only be allocated from pages i.e., leaves - int id = allocateNode(d); - if (id < 0) { - return id; - } - - final PoolSubpage[] subpages = this.subpages; - final int pageSize = this.pageSize; - - freeBytes -= pageSize; - - int subpageIdx = subpageIdx(id); - PoolSubpage subpage = subpages[subpageIdx]; - if (subpage == null) { - subpage = new PoolSubpage(this, id, runOffset(id), pageSize, normCapacity); - subpages[subpageIdx] = subpage; - } else { - subpage.init(normCapacity); - } - return subpage.allocate(); - } - - /** - * Free a subpage or a run of pages - * When a subpage is freed from PoolSubpage, it might be added back to subpage pool of the owning PoolArena - * If the subpage pool in PoolArena has at least one other PoolSubpage of given elemSize, we can - * completely free the owning Page so it is available for subsequent allocations - * - * @param handle handle to free - */ - void free(long handle) { - int memoryMapIdx = (int) handle; - int bitmapIdx = (int) (handle >>> Integer.SIZE); - - if (bitmapIdx != 0) { // free a subpage - PoolSubpage subpage = subpages[subpageIdx(memoryMapIdx)]; - assert subpage != null && subpage.doNotDestroy; - if (subpage.free(bitmapIdx & 0x3FFFFFFF)) { - return; - } - } - freeBytes += runLength(memoryMapIdx); - setValue(memoryMapIdx, depth(memoryMapIdx)); - updateParentsFree(memoryMapIdx); - } - - void initBuf(PooledByteBuf buf, long handle, int reqCapacity) { - int memoryMapIdx = (int) handle; - int bitmapIdx = (int) (handle >>> Integer.SIZE); - if (bitmapIdx == 0) { - byte val = value(memoryMapIdx); - assert val == unusable : String.valueOf(val); - buf.init(this, handle, runOffset(memoryMapIdx), reqCapacity, runLength(memoryMapIdx)); - } else { - initBufWithSubpage(buf, handle, bitmapIdx, reqCapacity); - } - } - - void initBufWithSubpage(PooledByteBuf buf, long handle, int reqCapacity) { - initBufWithSubpage(buf, handle, (int) (handle >>> Integer.SIZE), reqCapacity); - } - - private void initBufWithSubpage(PooledByteBuf buf, long handle, int bitmapIdx, int reqCapacity) { - assert bitmapIdx != 0; - - int memoryMapIdx = (int) handle; - - PoolSubpage subpage = subpages[subpageIdx(memoryMapIdx)]; - assert subpage.doNotDestroy; - assert reqCapacity <= subpage.elemSize; - - buf.init( - this, handle, - runOffset(memoryMapIdx) + (bitmapIdx & 0x3FFFFFFF) * subpage.elemSize, reqCapacity, subpage.elemSize); - } - - private byte value(int id) { - return memoryMap[id]; - } - - private void setValue(int id, byte val) { - memoryMap[id] = val; - } - - private byte depth(int id) { - return depthMap[id]; - } - - private static int log2(int val) { - // compute the (0-based, with lsb = 0) position of highest set bit i.e, log2 - return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(val); - } - - private int runLength(int id) { - // represents the size in #bytes supported by node 'id' in the tree - return 1 << log2ChunkSize - depth(id); - } - - private int runOffset(int id) { - // represents the 0-based offset in #bytes from start of the byte-array chunk - int shift = id ^ 1 << depth(id); - return shift * runLength(id); - } - - private int subpageIdx(int memoryMapIdx) { - return memoryMapIdx ^ maxSubpageAllocs; // remove highest set bit, to get offset - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("Chunk("); - buf.append(Integer.toHexString(System.identityHashCode(this))); - buf.append(": "); - buf.append(usage()); - buf.append("%, "); - buf.append(chunkSize - freeBytes); - buf.append('/'); - buf.append(chunkSize); - buf.append(')'); - return buf.toString(); - } -} diff --git a/common/src/main/java/common/net/buffer/PoolChunkList.java b/common/src/main/java/common/net/buffer/PoolChunkList.java deleted file mode 100644 index f0a5f40..0000000 --- a/common/src/main/java/common/net/buffer/PoolChunkList.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import common.net.util.internal.StringUtil; - -final class PoolChunkList { - private final PoolArena arena; - private final PoolChunkList nextList; - PoolChunkList prevList; - - private final int minUsage; - private final int maxUsage; - - private PoolChunk head; - - // TODO: Test if adding padding helps under contention - //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; - - PoolChunkList(PoolArena arena, PoolChunkList nextList, int minUsage, int maxUsage) { - this.arena = arena; - this.nextList = nextList; - this.minUsage = minUsage; - this.maxUsage = maxUsage; - } - - boolean allocate(PooledByteBuf buf, int reqCapacity, int normCapacity) { - if (head == null) { - return false; - } - - for (PoolChunk cur = head;;) { - long handle = cur.allocate(normCapacity); - if (handle < 0) { - cur = cur.next; - if (cur == null) { - return false; - } - } else { - cur.initBuf(buf, handle, reqCapacity); - if (cur.usage() >= maxUsage) { - remove(cur); - nextList.add(cur); - } - return true; - } - } - } - - void free(PoolChunk chunk, long handle) { - chunk.free(handle); - if (chunk.usage() < minUsage) { - remove(chunk); - if (prevList == null) { - assert chunk.usage() == 0; - arena.destroyChunk(chunk); - } else { - prevList.add(chunk); - } - } - } - - void add(PoolChunk chunk) { - if (chunk.usage() >= maxUsage) { - nextList.add(chunk); - return; - } - - chunk.parent = this; - if (head == null) { - head = chunk; - chunk.prev = null; - chunk.next = null; - } else { - chunk.prev = null; - chunk.next = head; - head.prev = chunk; - head = chunk; - } - } - - private void remove(PoolChunk cur) { - if (cur == head) { - head = cur.next; - if (head != null) { - head.prev = null; - } - } else { - PoolChunk next = cur.next; - cur.prev.next = next; - if (next != null) { - next.prev = cur.prev; - } - } - } - - @Override - public String toString() { - if (head == null) { - return "none"; - } - - StringBuilder buf = new StringBuilder(); - for (PoolChunk cur = head;;) { - buf.append(cur); - cur = cur.next; - if (cur == null) { - break; - } - buf.append(StringUtil.NEWLINE); - } - - return buf.toString(); - } -} diff --git a/common/src/main/java/common/net/buffer/PoolSubpage.java b/common/src/main/java/common/net/buffer/PoolSubpage.java deleted file mode 100644 index ae643c7..0000000 --- a/common/src/main/java/common/net/buffer/PoolSubpage.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -final class PoolSubpage { - - final PoolChunk chunk; - private final int memoryMapIdx; - private final int runOffset; - private final int pageSize; - private final long[] bitmap; - - PoolSubpage prev; - PoolSubpage next; - - boolean doNotDestroy; - int elemSize; - private int maxNumElems; - private int bitmapLength; - private int nextAvail; - private int numAvail; - - // TODO: Test if adding padding helps under contention - //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; - - /** Special constructor that creates a linked list head */ - PoolSubpage(int pageSize) { - chunk = null; - memoryMapIdx = -1; - runOffset = -1; - elemSize = -1; - this.pageSize = pageSize; - bitmap = null; - } - - PoolSubpage(PoolChunk chunk, int memoryMapIdx, int runOffset, int pageSize, int elemSize) { - this.chunk = chunk; - this.memoryMapIdx = memoryMapIdx; - this.runOffset = runOffset; - this.pageSize = pageSize; - bitmap = new long[pageSize >>> 10]; // pageSize / 16 / 64 - init(elemSize); - } - - void init(int elemSize) { - doNotDestroy = true; - this.elemSize = elemSize; - if (elemSize != 0) { - maxNumElems = numAvail = pageSize / elemSize; - nextAvail = 0; - bitmapLength = maxNumElems >>> 6; - if ((maxNumElems & 63) != 0) { - bitmapLength ++; - } - - for (int i = 0; i < bitmapLength; i ++) { - bitmap[i] = 0; - } - } - - addToPool(); - } - - /** - * Returns the bitmap index of the subpage allocation. - */ - long allocate() { - if (elemSize == 0) { - return toHandle(0); - } - - if (numAvail == 0 || !doNotDestroy) { - return -1; - } - - final int bitmapIdx = getNextAvail(); - int q = bitmapIdx >>> 6; - int r = bitmapIdx & 63; - assert (bitmap[q] >>> r & 1) == 0; - bitmap[q] |= 1L << r; - - if (-- numAvail == 0) { - removeFromPool(); - } - - return toHandle(bitmapIdx); - } - - /** - * @return {@code true} if this subpage is in use. - * {@code false} if this subpage is not used by its chunk and thus it's OK to be released. - */ - boolean free(int bitmapIdx) { - - if (elemSize == 0) { - return true; - } - - int q = bitmapIdx >>> 6; - int r = bitmapIdx & 63; - assert (bitmap[q] >>> r & 1) != 0; - bitmap[q] ^= 1L << r; - - setNextAvail(bitmapIdx); - - if (numAvail ++ == 0) { - addToPool(); - return true; - } - - if (numAvail != maxNumElems) { - return true; - } else { - // Subpage not in use (numAvail == maxNumElems) - if (prev == next) { - // Do not remove if this subpage is the only one left in the pool. - return true; - } - - // Remove this subpage from the pool if there are other subpages left in the pool. - doNotDestroy = false; - removeFromPool(); - return false; - } - } - - private void addToPool() { - PoolSubpage head = chunk.arena.findSubpagePoolHead(elemSize); - assert prev == null && next == null; - prev = head; - next = head.next; - next.prev = this; - head.next = this; - } - - private void removeFromPool() { - assert prev != null && next != null; - prev.next = next; - next.prev = prev; - next = null; - prev = null; - } - - private void setNextAvail(int bitmapIdx) { - nextAvail = bitmapIdx; - } - - private int getNextAvail() { - int nextAvail = this.nextAvail; - if (nextAvail >= 0) { - this.nextAvail = -1; - return nextAvail; - } - return findNextAvail(); - } - - private int findNextAvail() { - final long[] bitmap = this.bitmap; - final int bitmapLength = this.bitmapLength; - for (int i = 0; i < bitmapLength; i ++) { - long bits = bitmap[i]; - if (~bits != 0) { - return findNextAvail0(i, bits); - } - } - return -1; - } - - private int findNextAvail0(int i, long bits) { - final int maxNumElems = this.maxNumElems; - final int baseVal = i << 6; - - for (int j = 0; j < 64; j ++) { - if ((bits & 1) == 0) { - int val = baseVal | j; - if (val < maxNumElems) { - return val; - } else { - break; - } - } - bits >>>= 1; - } - return -1; - } - - private long toHandle(int bitmapIdx) { - return 0x4000000000000000L | (long) bitmapIdx << 32 | memoryMapIdx; - } - - public String toString() { - if (!doNotDestroy) { - return "(" + memoryMapIdx + ": not in use)"; - } - - return String.valueOf('(') + memoryMapIdx + ": " + (maxNumElems - numAvail) + '/' + maxNumElems + - ", offset: " + runOffset + ", length: " + pageSize + ", elemSize: " + elemSize + ')'; - } -} diff --git a/common/src/main/java/common/net/buffer/PoolThreadCache.java b/common/src/main/java/common/net/buffer/PoolThreadCache.java deleted file mode 100644 index 1a41c18..0000000 --- a/common/src/main/java/common/net/buffer/PoolThreadCache.java +++ /dev/null @@ -1,485 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - - -import java.nio.ByteBuffer; - -import common.net.util.ThreadDeathWatcher; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * Acts a Thread cache for allocations. This implementation is moduled after - * jemalloc and the descripted - * technics of Scalable memory allocation using jemalloc. - */ -final class PoolThreadCache { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(PoolThreadCache.class); - - final PoolArena heapArena; - final PoolArena directArena; - - // Hold the caches for the different size classes, which are tiny, small and normal. - private final MemoryRegionCache[] tinySubPageHeapCaches; - private final MemoryRegionCache[] smallSubPageHeapCaches; - private final MemoryRegionCache[] tinySubPageDirectCaches; - private final MemoryRegionCache[] smallSubPageDirectCaches; - private final MemoryRegionCache[] normalHeapCaches; - private final MemoryRegionCache[] normalDirectCaches; - - // Used for bitshifting when calculate the index of normal caches later - private final int numShiftsNormalDirect; - private final int numShiftsNormalHeap; - private final int freeSweepAllocationThreshold; - - private int allocations; - - private final Thread thread = Thread.currentThread(); - private final Runnable freeTask = new Runnable() { - @Override - public void run() { - free0(); - } - }; - - // TODO: Test if adding padding helps under contention - //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; - - PoolThreadCache(PoolArena heapArena, PoolArena directArena, - int tinyCacheSize, int smallCacheSize, int normalCacheSize, - int maxCachedBufferCapacity, int freeSweepAllocationThreshold) { - if (maxCachedBufferCapacity < 0) { - throw new IllegalArgumentException("maxCachedBufferCapacity: " - + maxCachedBufferCapacity + " (expected: >= 0)"); - } - if (freeSweepAllocationThreshold < 1) { - throw new IllegalArgumentException("freeSweepAllocationThreshold: " - + maxCachedBufferCapacity + " (expected: > 0)"); - } - this.freeSweepAllocationThreshold = freeSweepAllocationThreshold; - this.heapArena = heapArena; - this.directArena = directArena; - if (directArena != null) { - tinySubPageDirectCaches = createSubPageCaches(tinyCacheSize, PoolArena.numTinySubpagePools); - smallSubPageDirectCaches = createSubPageCaches(smallCacheSize, directArena.numSmallSubpagePools); - - numShiftsNormalDirect = log2(directArena.pageSize); - normalDirectCaches = createNormalCaches( - normalCacheSize, maxCachedBufferCapacity, directArena); - } else { - // No directArea is configured so just null out all caches - tinySubPageDirectCaches = null; - smallSubPageDirectCaches = null; - normalDirectCaches = null; - numShiftsNormalDirect = -1; - } - if (heapArena != null) { - // Create the caches for the heap allocations - tinySubPageHeapCaches = createSubPageCaches(tinyCacheSize, PoolArena.numTinySubpagePools); - smallSubPageHeapCaches = createSubPageCaches(smallCacheSize, heapArena.numSmallSubpagePools); - - numShiftsNormalHeap = log2(heapArena.pageSize); - normalHeapCaches = createNormalCaches( - normalCacheSize, maxCachedBufferCapacity, heapArena); - } else { - // No heapArea is configured so just null out all caches - tinySubPageHeapCaches = null; - smallSubPageHeapCaches = null; - normalHeapCaches = null; - numShiftsNormalHeap = -1; - } - - // The thread-local cache will keep a list of pooled buffers which must be returned to - // the pool when the thread is not alive anymore. - ThreadDeathWatcher.watch(thread, freeTask); - } - - private static SubPageMemoryRegionCache[] createSubPageCaches(int cacheSize, int numCaches) { - if (cacheSize > 0) { - - SubPageMemoryRegionCache[] cache = new SubPageMemoryRegionCache[numCaches]; - for (int i = 0; i < cache.length; i++) { - // TODO: maybe use cacheSize / cache.length - cache[i] = new SubPageMemoryRegionCache(cacheSize); - } - return cache; - } else { - return null; - } - } - - private static NormalMemoryRegionCache[] createNormalCaches( - int cacheSize, int maxCachedBufferCapacity, PoolArena area) { - if (cacheSize > 0) { - int max = Math.min(area.chunkSize, maxCachedBufferCapacity); - int arraySize = Math.max(1, max / area.pageSize); - - - NormalMemoryRegionCache[] cache = new NormalMemoryRegionCache[arraySize]; - for (int i = 0; i < cache.length; i++) { - cache[i] = new NormalMemoryRegionCache(cacheSize); - } - return cache; - } else { - return null; - } - } - - private static int log2(int val) { - int res = 0; - while (val > 1) { - val >>= 1; - res++; - } - return res; - } - - /** - * Try to allocate a tiny buffer out of the cache. Returns {@code true} if successful {@code false} otherwise - */ - boolean allocateTiny(PoolArena area, PooledByteBuf buf, int reqCapacity, int normCapacity) { - return allocate(cacheForTiny(area, normCapacity), buf, reqCapacity); - } - - /** - * Try to allocate a small buffer out of the cache. Returns {@code true} if successful {@code false} otherwise - */ - boolean allocateSmall(PoolArena area, PooledByteBuf buf, int reqCapacity, int normCapacity) { - return allocate(cacheForSmall(area, normCapacity), buf, reqCapacity); - } - - /** - * Try to allocate a small buffer out of the cache. Returns {@code true} if successful {@code false} otherwise - */ - boolean allocateNormal(PoolArena area, PooledByteBuf buf, int reqCapacity, int normCapacity) { - return allocate(cacheForNormal(area, normCapacity), buf, reqCapacity); - } - - - private boolean allocate(MemoryRegionCache cache, PooledByteBuf buf, int reqCapacity) { - if (cache == null) { - // no cache found so just return false here - return false; - } - boolean allocated = cache.allocate(buf, reqCapacity); - if (++ allocations >= freeSweepAllocationThreshold) { - allocations = 0; - trim(); - } - return allocated; - } - - /** - * Add {@link PoolChunk} and {@code handle} to the cache if there is enough room. - * Returns {@code true} if it fit into the cache {@code false} otherwise. - */ - - boolean add(PoolArena area, PoolChunk chunk, long handle, int normCapacity) { - MemoryRegionCache cache; - if (area.isTinyOrSmall(normCapacity)) { - if (PoolArena.isTiny(normCapacity)) { - cache = cacheForTiny(area, normCapacity); - } else { - cache = cacheForSmall(area, normCapacity); - } - } else { - cache = cacheForNormal(area, normCapacity); - } - if (cache == null) { - return false; - } - return cache.add(chunk, handle); - } - - /** - * Should be called if the Thread that uses this cache is about to exist to release resources out of the cache - */ - void free() { - ThreadDeathWatcher.unwatch(thread, freeTask); - free0(); - } - - private void free0() { - int numFreed = free(tinySubPageDirectCaches) + - free(smallSubPageDirectCaches) + - free(normalDirectCaches) + - free(tinySubPageHeapCaches) + - free(smallSubPageHeapCaches) + - free(normalHeapCaches); - - if (numFreed > 0 && logger.isDebugEnabled()) { - logger.debug("Freed {} thread-local buffer(s) from thread: {}", numFreed, thread.getName()); - } - } - - private static int free(MemoryRegionCache[] caches) { - if (caches == null) { - return 0; - } - - int numFreed = 0; - for (MemoryRegionCache c: caches) { - numFreed += free(c); - } - return numFreed; - } - - private static int free(MemoryRegionCache cache) { - if (cache == null) { - return 0; - } - return cache.free(); - } - - void trim() { - trim(tinySubPageDirectCaches); - trim(smallSubPageDirectCaches); - trim(normalDirectCaches); - trim(tinySubPageHeapCaches); - trim(smallSubPageHeapCaches); - trim(normalHeapCaches); - } - - private static void trim(MemoryRegionCache[] caches) { - if (caches == null) { - return; - } - for (MemoryRegionCache c: caches) { - trim(c); - } - } - - private static void trim(MemoryRegionCache cache) { - if (cache == null) { - return; - } - cache.trim(); - } - - private MemoryRegionCache cacheForTiny(PoolArena area, int normCapacity) { - int idx = PoolArena.tinyIdx(normCapacity); - if (area.isDirect()) { - return cache(tinySubPageDirectCaches, idx); - } - return cache(tinySubPageHeapCaches, idx); - } - - private MemoryRegionCache cacheForSmall(PoolArena area, int normCapacity) { - int idx = PoolArena.smallIdx(normCapacity); - if (area.isDirect()) { - return cache(smallSubPageDirectCaches, idx); - } - return cache(smallSubPageHeapCaches, idx); - } - - private MemoryRegionCache cacheForNormal(PoolArena area, int normCapacity) { - if (area.isDirect()) { - int idx = log2(normCapacity >> numShiftsNormalDirect); - return cache(normalDirectCaches, idx); - } - int idx = log2(normCapacity >> numShiftsNormalHeap); - return cache(normalHeapCaches, idx); - } - - private static MemoryRegionCache cache(MemoryRegionCache[] cache, int idx) { - if (cache == null || idx > cache.length - 1) { - return null; - } - return cache[idx]; - } - - /** - * Cache used for buffers which are backed by TINY or SMALL size. - */ - private static final class SubPageMemoryRegionCache extends MemoryRegionCache { - SubPageMemoryRegionCache(int size) { - super(size); - } - - @Override - protected void initBuf( - PoolChunk chunk, long handle, PooledByteBuf buf, int reqCapacity) { - chunk.initBufWithSubpage(buf, handle, reqCapacity); - } - } - - /** - * Cache used for buffers which are backed by NORMAL size. - */ - private static final class NormalMemoryRegionCache extends MemoryRegionCache { - NormalMemoryRegionCache(int size) { - super(size); - } - - @Override - protected void initBuf( - PoolChunk chunk, long handle, PooledByteBuf buf, int reqCapacity) { - chunk.initBuf(buf, handle, reqCapacity); - } - } - - /** - * Cache of {@link PoolChunk} and handles which can be used to allocate a buffer without locking at all. - */ - private abstract static class MemoryRegionCache { - private final Entry[] entries; - private final int maxUnusedCached; - private int head; - private int tail; - private int maxEntriesInUse; - private int entriesInUse; - - - MemoryRegionCache(int size) { - entries = new Entry[powerOfTwo(size)]; - for (int i = 0; i < entries.length; i++) { - entries[i] = new Entry(); - } - maxUnusedCached = size / 2; - } - - private static int powerOfTwo(int res) { - if (res <= 2) { - return 2; - } - res--; - res |= res >> 1; - res |= res >> 2; - res |= res >> 4; - res |= res >> 8; - res |= res >> 16; - res++; - return res; - } - - /** - * Init the {@link PooledByteBuf} using the provided chunk and handle with the capacity restrictions. - */ - protected abstract void initBuf(PoolChunk chunk, long handle, - PooledByteBuf buf, int reqCapacity); - - /** - * Add to cache if not already full. - */ - public boolean add(PoolChunk chunk, long handle) { - Entry entry = entries[tail]; - if (entry.chunk != null) { - // cache is full - return false; - } - entriesInUse --; - - entry.chunk = chunk; - entry.handle = handle; - tail = nextIdx(tail); - return true; - } - - /** - * Allocate something out of the cache if possible and remove the entry from the cache. - */ - public boolean allocate(PooledByteBuf buf, int reqCapacity) { - Entry entry = entries[head]; - if (entry.chunk == null) { - return false; - } - - entriesInUse ++; - if (maxEntriesInUse < entriesInUse) { - maxEntriesInUse = entriesInUse; - } - initBuf(entry.chunk, entry.handle, buf, reqCapacity); - // only null out the chunk as we only use the chunk to check if the buffer is full or not. - entry.chunk = null; - head = nextIdx(head); - return true; - } - - /** - * Clear out this cache and free up all previous cached {@link PoolChunk}s and {@code handle}s. - */ - public int free() { - int numFreed = 0; - entriesInUse = 0; - maxEntriesInUse = 0; - for (int i = head;; i = nextIdx(i)) { - if (freeEntry(entries[i])) { - numFreed++; - } else { - // all cleared - return numFreed; - } - } - } - - /** - * Free up cached {@link PoolChunk}s if not allocated frequently enough. - */ - private void trim() { - int free = size() - maxEntriesInUse; - entriesInUse = 0; - maxEntriesInUse = 0; - - if (free <= maxUnusedCached) { - return; - } - - int i = head; - for (; free > 0; free--) { - if (!freeEntry(entries[i])) { - // all freed - return; - } - i = nextIdx(i); - } - } - - - private static boolean freeEntry(Entry entry) { - PoolChunk chunk = entry.chunk; - if (chunk == null) { - return false; - } - // need to synchronize on the area from which it was allocated before. - synchronized (chunk.arena) { - chunk.parent.free(chunk, entry.handle); - } - entry.chunk = null; - return true; - } - - /** - * Return the number of cached entries. - */ - private int size() { - return tail - head & entries.length - 1; - } - - private int nextIdx(int index) { - // use bitwise operation as this is faster as using modulo. - return index + 1 & entries.length - 1; - } - - private static final class Entry { - PoolChunk chunk; - long handle; - } - } -} diff --git a/common/src/main/java/common/net/buffer/PooledByteBuf.java b/common/src/main/java/common/net/buffer/PooledByteBuf.java deleted file mode 100644 index 34324d7..0000000 --- a/common/src/main/java/common/net/buffer/PooledByteBuf.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import common.net.util.Recycler; - -abstract class PooledByteBuf extends AbstractReferenceCountedByteBuf { - - private final Recycler.Handle recyclerHandle; - - protected PoolChunk chunk; - protected long handle; - protected T memory; - protected int offset; - protected int length; - int maxLength; - - private ByteBuffer tmpNioBuf; - - protected PooledByteBuf(Recycler.Handle recyclerHandle, int maxCapacity) { - super(maxCapacity); - this.recyclerHandle = recyclerHandle; - } - - void init(PoolChunk chunk, long handle, int offset, int length, int maxLength) { - assert handle >= 0; - assert chunk != null; - - this.chunk = chunk; - this.handle = handle; - memory = chunk.memory; - this.offset = offset; - this.length = length; - this.maxLength = maxLength; - setIndex(0, 0); - tmpNioBuf = null; - } - - void initUnpooled(PoolChunk chunk, int length) { - assert chunk != null; - - this.chunk = chunk; - handle = 0; - memory = chunk.memory; - offset = 0; - this.length = maxLength = length; - setIndex(0, 0); - tmpNioBuf = null; - } - - @Override - public final int capacity() { - return length; - } - - @Override - public final ByteBuf capacity(int newCapacity) { - ensureAccessible(); - - // If the request capacity does not require reallocation, just update the length of the memory. - if (chunk.unpooled) { - if (newCapacity == length) { - return this; - } - } else { - if (newCapacity > length) { - if (newCapacity <= maxLength) { - length = newCapacity; - return this; - } - } else if (newCapacity < length) { - if (newCapacity > maxLength >>> 1) { - if (maxLength <= 512) { - if (newCapacity > maxLength - 16) { - length = newCapacity; - setIndex(Math.min(readerIndex(), newCapacity), Math.min(writerIndex(), newCapacity)); - return this; - } - } else { // > 512 (i.e. >= 1024) - length = newCapacity; - setIndex(Math.min(readerIndex(), newCapacity), Math.min(writerIndex(), newCapacity)); - return this; - } - } - } else { - return this; - } - } - - // Reallocation required. - chunk.arena.reallocate(this, newCapacity, true); - return this; - } - - @Override - public final ByteBufAllocator alloc() { - return chunk.arena.parent; - } - - @Override - public final ByteOrder order() { - return ByteOrder.BIG_ENDIAN; - } - - @Override - public final ByteBuf unwrap() { - return null; - } - - protected final ByteBuffer internalNioBuffer() { - ByteBuffer tmpNioBuf = this.tmpNioBuf; - if (tmpNioBuf == null) { - this.tmpNioBuf = tmpNioBuf = newInternalNioBuffer(memory); - } - return tmpNioBuf; - } - - protected abstract ByteBuffer newInternalNioBuffer(T memory); - - @Override - protected final void deallocate() { - if (handle >= 0) { - final long handle = this.handle; - this.handle = -1; - memory = null; - chunk.arena.free(chunk, handle, maxLength); - recycle(); - } - } - - private void recycle() { - Recycler.Handle recyclerHandle = this.recyclerHandle; - if (recyclerHandle != null) { - ((Recycler) recycler()).recycle(this, recyclerHandle); - } - } - - protected abstract Recycler recycler(); - - protected final int idx(int index) { - return offset + index; - } -} diff --git a/common/src/main/java/common/net/buffer/PooledByteBufAllocator.java b/common/src/main/java/common/net/buffer/PooledByteBufAllocator.java deleted file mode 100644 index a0b0ca4..0000000 --- a/common/src/main/java/common/net/buffer/PooledByteBufAllocator.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import java.nio.ByteBuffer; -import java.util.concurrent.atomic.AtomicInteger; - -import common.net.util.concurrent.FastThreadLocal; -import common.net.util.internal.SystemPropertyUtil; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -public class PooledByteBufAllocator extends AbstractByteBufAllocator { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(PooledByteBufAllocator.class); - private static final int DEFAULT_NUM_HEAP_ARENA; - private static final int DEFAULT_NUM_DIRECT_ARENA; - - private static final int DEFAULT_PAGE_SIZE; - private static final int DEFAULT_MAX_ORDER; // 8192 << 11 = 16 MiB per chunk - private static final int DEFAULT_TINY_CACHE_SIZE; - private static final int DEFAULT_SMALL_CACHE_SIZE; - private static final int DEFAULT_NORMAL_CACHE_SIZE; - private static final int DEFAULT_MAX_CACHED_BUFFER_CAPACITY; - private static final int DEFAULT_CACHE_TRIM_INTERVAL; - - private static final int MIN_PAGE_SIZE = 4096; - private static final int MAX_CHUNK_SIZE = (int) (((long) Integer.MAX_VALUE + 1) / 2); - - static { - int defaultPageSize = SystemPropertyUtil.getInt("game.net.allocator.pageSize", 8192); - Throwable pageSizeFallbackCause = null; - try { - validateAndCalculatePageShifts(defaultPageSize); - } catch (Throwable t) { - pageSizeFallbackCause = t; - defaultPageSize = 8192; - } - DEFAULT_PAGE_SIZE = defaultPageSize; - - int defaultMaxOrder = SystemPropertyUtil.getInt("game.net.allocator.maxOrder", 11); - Throwable maxOrderFallbackCause = null; - try { - validateAndCalculateChunkSize(DEFAULT_PAGE_SIZE, defaultMaxOrder); - } catch (Throwable t) { - maxOrderFallbackCause = t; - defaultMaxOrder = 11; - } - DEFAULT_MAX_ORDER = defaultMaxOrder; - - // Determine reasonable default for nHeapArena and nDirectArena. - // Assuming each arena has 3 chunks, the pool should not consume more than 50% of max memory. - final Runtime runtime = Runtime.getRuntime(); - final int defaultChunkSize = DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER; - DEFAULT_NUM_HEAP_ARENA = Math.max(0, - SystemPropertyUtil.getInt( - "game.net.allocator.numHeapArenas", - (int) Math.min( - runtime.availableProcessors(), - Runtime.getRuntime().maxMemory() / defaultChunkSize / 2 / 3))); - DEFAULT_NUM_DIRECT_ARENA = Math.max(0, - SystemPropertyUtil.getInt( - "game.net.allocator.numDirectArenas", - (int) Math.min( - runtime.availableProcessors(), - Runtime.getRuntime().maxMemory() / defaultChunkSize / 2 / 3))); - - // cache sizes - DEFAULT_TINY_CACHE_SIZE = SystemPropertyUtil.getInt("game.net.allocator.tinyCacheSize", 512); - DEFAULT_SMALL_CACHE_SIZE = SystemPropertyUtil.getInt("game.net.allocator.smallCacheSize", 256); - DEFAULT_NORMAL_CACHE_SIZE = SystemPropertyUtil.getInt("game.net.allocator.normalCacheSize", 64); - - // 32 kb is the default maximum capacity of the cached buffer. Similar to what is explained in - // 'Scalable memory allocation using jemalloc' - DEFAULT_MAX_CACHED_BUFFER_CAPACITY = SystemPropertyUtil.getInt( - "game.net.allocator.maxCachedBufferCapacity", 32 * 1024); - - // the number of threshold of allocations when cached entries will be freed up if not frequently used - DEFAULT_CACHE_TRIM_INTERVAL = SystemPropertyUtil.getInt( - "game.net.allocator.cacheTrimInterval", 8192); - - if (logger.isDebugEnabled()) { - logger.debug("-Dgame.net.allocator.numHeapArenas: {}", DEFAULT_NUM_HEAP_ARENA); - logger.debug("-Dgame.net.allocator.numDirectArenas: {}", DEFAULT_NUM_DIRECT_ARENA); - if (pageSizeFallbackCause == null) { - logger.debug("-Dgame.net.allocator.pageSize: {}", DEFAULT_PAGE_SIZE); - } else { - logger.debug("-Dgame.net.allocator.pageSize: {}", DEFAULT_PAGE_SIZE, pageSizeFallbackCause); - } - if (maxOrderFallbackCause == null) { - logger.debug("-Dgame.net.allocator.maxOrder: {}", DEFAULT_MAX_ORDER); - } else { - logger.debug("-Dgame.net.allocator.maxOrder: {}", DEFAULT_MAX_ORDER, maxOrderFallbackCause); - } - logger.debug("-Dgame.net.allocator.chunkSize: {}", DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER); - logger.debug("-Dgame.net.allocator.tinyCacheSize: {}", DEFAULT_TINY_CACHE_SIZE); - logger.debug("-Dgame.net.allocator.smallCacheSize: {}", DEFAULT_SMALL_CACHE_SIZE); - logger.debug("-Dgame.net.allocator.normalCacheSize: {}", DEFAULT_NORMAL_CACHE_SIZE); - logger.debug("-Dgame.net.allocator.maxCachedBufferCapacity: {}", DEFAULT_MAX_CACHED_BUFFER_CAPACITY); - logger.debug("-Dgame.net.allocator.cacheTrimInterval: {}", DEFAULT_CACHE_TRIM_INTERVAL); - } - } - - public static final PooledByteBufAllocator DEFAULT = new PooledByteBufAllocator(); - - private final PoolArena[] heapArenas; - private final PoolArena[] directArenas; - private final int tinyCacheSize; - private final int smallCacheSize; - private final int normalCacheSize; - - final PoolThreadLocalCache threadCache; - - public PooledByteBufAllocator() { - this(DEFAULT_NUM_HEAP_ARENA, DEFAULT_NUM_DIRECT_ARENA, DEFAULT_PAGE_SIZE, DEFAULT_MAX_ORDER); - } - - public PooledByteBufAllocator(int nHeapArena, int nDirectArena, int pageSize, int maxOrder) { - this(nHeapArena, nDirectArena, pageSize, maxOrder, - DEFAULT_TINY_CACHE_SIZE, DEFAULT_SMALL_CACHE_SIZE, DEFAULT_NORMAL_CACHE_SIZE); - } - - public PooledByteBufAllocator(int nHeapArena, int nDirectArena, int pageSize, int maxOrder, - int tinyCacheSize, int smallCacheSize, int normalCacheSize) { - threadCache = new PoolThreadLocalCache(); - this.tinyCacheSize = tinyCacheSize; - this.smallCacheSize = smallCacheSize; - this.normalCacheSize = normalCacheSize; - final int chunkSize = validateAndCalculateChunkSize(pageSize, maxOrder); - - if (nHeapArena < 0) { - throw new IllegalArgumentException("nHeapArena: " + nHeapArena + " (expected: >= 0)"); - } - if (nDirectArena < 0) { - throw new IllegalArgumentException("nDirectArea: " + nDirectArena + " (expected: >= 0)"); - } - - int pageShifts = validateAndCalculatePageShifts(pageSize); - - if (nHeapArena > 0) { - heapArenas = newArenaArray(nHeapArena); - for (int i = 0; i < heapArenas.length; i ++) { - heapArenas[i] = new PoolArena.HeapArena(this, pageSize, maxOrder, pageShifts, chunkSize); - } - } else { - heapArenas = null; - } - - if (nDirectArena > 0) { - directArenas = newArenaArray(nDirectArena); - for (int i = 0; i < directArenas.length; i ++) { - directArenas[i] = new PoolArena.DirectArena(this, pageSize, maxOrder, pageShifts, chunkSize); - } - } else { - directArenas = null; - } - } - - - private static PoolArena[] newArenaArray(int size) { - return new PoolArena[size]; - } - - private static int validateAndCalculatePageShifts(int pageSize) { - if (pageSize < MIN_PAGE_SIZE) { - throw new IllegalArgumentException("pageSize: " + pageSize + " (expected: " + MIN_PAGE_SIZE + "+)"); - } - - if ((pageSize & pageSize - 1) != 0) { - throw new IllegalArgumentException("pageSize: " + pageSize + " (expected: power of 2)"); - } - - // Logarithm base 2. At this point we know that pageSize is a power of two. - return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(pageSize); - } - - private static int validateAndCalculateChunkSize(int pageSize, int maxOrder) { - if (maxOrder > 14) { - throw new IllegalArgumentException("maxOrder: " + maxOrder + " (expected: 0-14)"); - } - - // Ensure the resulting chunkSize does not overflow. - int chunkSize = pageSize; - for (int i = maxOrder; i > 0; i --) { - if (chunkSize > MAX_CHUNK_SIZE / 2) { - throw new IllegalArgumentException(String.format( - "pageSize (%d) << maxOrder (%d) must not exceed %d", pageSize, maxOrder, MAX_CHUNK_SIZE)); - } - chunkSize <<= 1; - } - return chunkSize; - } - - @Override - protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) { - PoolThreadCache cache = threadCache.get(); - PoolArena heapArena = cache.heapArena; - - ByteBuf buf; - if (heapArena != null) { - buf = heapArena.allocate(cache, initialCapacity, maxCapacity); - } else { - buf = new UnpooledHeapByteBuf(this, initialCapacity, maxCapacity); - } - - return toLeakAwareBuffer(buf); - } - - @Override - protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) { - PoolThreadCache cache = threadCache.get(); - PoolArena directArena = cache.directArena; - - ByteBuf buf; - if (directArena != null) { - buf = directArena.allocate(cache, initialCapacity, maxCapacity); - } else { - buf = new UnpooledDirectByteBuf(this, initialCapacity, maxCapacity); - } - - return toLeakAwareBuffer(buf); - } - - @Override - public boolean isDirectBufferPooled() { - return directArenas != null; - } - - final class PoolThreadLocalCache extends FastThreadLocal { - private final AtomicInteger index = new AtomicInteger(); - - @Override - protected PoolThreadCache initialValue() { - final int idx = index.getAndIncrement(); - final PoolArena heapArena; - final PoolArena directArena; - - if (heapArenas != null) { - heapArena = heapArenas[Math.abs(idx % heapArenas.length)]; - } else { - heapArena = null; - } - - if (directArenas != null) { - directArena = directArenas[Math.abs(idx % directArenas.length)]; - } else { - directArena = null; - } - - return new PoolThreadCache( - heapArena, directArena, tinyCacheSize, smallCacheSize, normalCacheSize, - DEFAULT_MAX_CACHED_BUFFER_CAPACITY, DEFAULT_CACHE_TRIM_INTERVAL); - } - - @Override - protected void onRemoval(PoolThreadCache value) { - value.free(); - } - } - -// Too noisy at the moment. -// -// public String toString() { -// StringBuilder buf = new StringBuilder(); -// buf.append(heapArenas.length); -// buf.append(" heap arena(s):"); -// buf.append(StringUtil.NEWLINE); -// for (PoolArena a: heapArenas) { -// buf.append(a); -// } -// buf.append(directArenas.length); -// buf.append(" direct arena(s):"); -// buf.append(StringUtil.NEWLINE); -// for (PoolArena a: directArenas) { -// buf.append(a); -// } -// return buf.toString(); -// } -} diff --git a/common/src/main/java/common/net/buffer/PooledDirectByteBuf.java b/common/src/main/java/common/net/buffer/PooledDirectByteBuf.java deleted file mode 100644 index e8f4ec7..0000000 --- a/common/src/main/java/common/net/buffer/PooledDirectByteBuf.java +++ /dev/null @@ -1,367 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; - -import common.net.util.Recycler; - -final class PooledDirectByteBuf extends PooledByteBuf { - - private static final Recycler RECYCLER = new Recycler() { - @Override - protected PooledDirectByteBuf newObject(Handle handle) { - return new PooledDirectByteBuf(handle, 0); - } - }; - - static PooledDirectByteBuf newInstance(int maxCapacity) { - PooledDirectByteBuf buf = RECYCLER.get(); - buf.setRefCnt(1); - buf.maxCapacity(maxCapacity); - return buf; - } - - private PooledDirectByteBuf(Recycler.Handle recyclerHandle, int maxCapacity) { - super(recyclerHandle, maxCapacity); - } - - @Override - protected ByteBuffer newInternalNioBuffer(ByteBuffer memory) { - return memory.duplicate(); - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - protected byte _getByte(int index) { - return memory.get(idx(index)); - } - - @Override - protected short _getShort(int index) { - return memory.getShort(idx(index)); - } - - @Override - protected int _getUnsignedMedium(int index) { - index = idx(index); - return (memory.get(index) & 0xff) << 16 | (memory.get(index + 1) & 0xff) << 8 | memory.get(index + 2) & 0xff; - } - - @Override - protected int _getInt(int index) { - return memory.getInt(idx(index)); - } - - @Override - protected long _getLong(int index) { - return memory.getLong(idx(index)); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - checkDstIndex(index, length, dstIndex, dst.capacity()); - if (dst.hasArray()) { - getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length); - } else if (dst.nioBufferCount() > 0) { - for (ByteBuffer bb: dst.nioBuffers(dstIndex, length)) { - int bbLen = bb.remaining(); - getBytes(index, bb); - index += bbLen; - } - } else { - dst.setBytes(dstIndex, this, index, length); - } - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - getBytes(index, dst, dstIndex, length, false); - return this; - } - - private void getBytes(int index, byte[] dst, int dstIndex, int length, boolean internal) { - checkDstIndex(index, length, dstIndex, dst.length); - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = memory.duplicate(); - } - index = idx(index); - tmpBuf.clear().position(index).limit(index + length); - tmpBuf.get(dst, dstIndex, length); - } - - @Override - public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { - checkReadableBytes(length); - getBytes(readerIndex, dst, dstIndex, length, true); - readerIndex += length; - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - getBytes(index, dst, false); - return this; - } - - private void getBytes(int index, ByteBuffer dst, boolean internal) { - checkIndex(index); - int bytesToCopy = Math.min(capacity() - index, dst.remaining()); - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = memory.duplicate(); - } - index = idx(index); - tmpBuf.clear().position(index).limit(index + bytesToCopy); - dst.put(tmpBuf); - } - - @Override - public ByteBuf readBytes(ByteBuffer dst) { - int length = dst.remaining(); - checkReadableBytes(length); - getBytes(readerIndex, dst, true); - readerIndex += length; - return this; - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { - getBytes(index, out, length, false); - return this; - } - - private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException { - checkIndex(index, length); - if (length == 0) { - return; - } - - byte[] tmp = new byte[length]; - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = memory.duplicate(); - } - tmpBuf.clear().position(idx(index)); - tmpBuf.get(tmp); - out.write(tmp); - } - - @Override - public ByteBuf readBytes(OutputStream out, int length) throws IOException { - checkReadableBytes(length); - getBytes(readerIndex, out, length, true); - readerIndex += length; - return this; - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { - return getBytes(index, out, length, false); - } - - private int getBytes(int index, GatheringByteChannel out, int length, boolean internal) throws IOException { - checkIndex(index, length); - if (length == 0) { - return 0; - } - - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = memory.duplicate(); - } - index = idx(index); - tmpBuf.clear().position(index).limit(index + length); - return out.write(tmpBuf); - } - - @Override - public int readBytes(GatheringByteChannel out, int length) throws IOException { - checkReadableBytes(length); - int readBytes = getBytes(readerIndex, out, length, true); - readerIndex += readBytes; - return readBytes; - } - - @Override - protected void _setByte(int index, int value) { - memory.put(idx(index), (byte) value); - } - - @Override - protected void _setShort(int index, int value) { - memory.putShort(idx(index), (short) value); - } - - @Override - protected void _setMedium(int index, int value) { - index = idx(index); - memory.put(index, (byte) (value >>> 16)); - memory.put(index + 1, (byte) (value >>> 8)); - memory.put(index + 2, (byte) value); - } - - @Override - protected void _setInt(int index, int value) { - memory.putInt(idx(index), value); - } - - @Override - protected void _setLong(int index, long value) { - memory.putLong(idx(index), value); - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - checkSrcIndex(index, length, srcIndex, src.capacity()); - if (src.hasArray()) { - setBytes(index, src.array(), src.arrayOffset() + srcIndex, length); - } else if (src.nioBufferCount() > 0) { - for (ByteBuffer bb: src.nioBuffers(srcIndex, length)) { - int bbLen = bb.remaining(); - setBytes(index, bb); - index += bbLen; - } - } else { - src.getBytes(srcIndex, this, index, length); - } - return this; - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - checkSrcIndex(index, length, srcIndex, src.length); - ByteBuffer tmpBuf = internalNioBuffer(); - index = idx(index); - tmpBuf.clear().position(index).limit(index + length); - tmpBuf.put(src, srcIndex, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - checkIndex(index, src.remaining()); - ByteBuffer tmpBuf = internalNioBuffer(); - if (src == tmpBuf) { - src = src.duplicate(); - } - - index = idx(index); - tmpBuf.clear().position(index).limit(index + src.remaining()); - tmpBuf.put(src); - return this; - } - - @Override - public int setBytes(int index, InputStream in, int length) throws IOException { - checkIndex(index, length); - byte[] tmp = new byte[length]; - int readBytes = in.read(tmp); - if (readBytes <= 0) { - return readBytes; - } - ByteBuffer tmpBuf = internalNioBuffer(); - tmpBuf.clear().position(idx(index)); - tmpBuf.put(tmp, 0, readBytes); - return readBytes; - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { - checkIndex(index, length); - ByteBuffer tmpBuf = internalNioBuffer(); - index = idx(index); - tmpBuf.clear().position(index).limit(index + length); - try { - return in.read(tmpBuf); - } catch (ClosedChannelException ignored) { - return -1; - } - } - - @Override - public ByteBuf copy(int index, int length) { - checkIndex(index, length); - ByteBuf copy = alloc().directBuffer(length, maxCapacity()); - copy.writeBytes(this, index, length); - return copy; - } - - @Override - public int nioBufferCount() { - return 1; - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - checkIndex(index, length); - index = idx(index); - return ((ByteBuffer) memory.duplicate().position(index).limit(index + length)).slice(); - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - return new ByteBuffer[] { nioBuffer(index, length) }; - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - checkIndex(index, length); - index = idx(index); - return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); - } - - @Override - public boolean hasArray() { - return false; - } - - @Override - public byte[] array() { - throw new UnsupportedOperationException("direct buffer"); - } - - @Override - public int arrayOffset() { - throw new UnsupportedOperationException("direct buffer"); - } - - @Override - protected Recycler recycler() { - return RECYCLER; - } -} diff --git a/common/src/main/java/common/net/buffer/PooledHeapByteBuf.java b/common/src/main/java/common/net/buffer/PooledHeapByteBuf.java deleted file mode 100644 index 5f75f03..0000000 --- a/common/src/main/java/common/net/buffer/PooledHeapByteBuf.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file tothe License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; - -import common.net.util.Recycler; - -final class PooledHeapByteBuf extends PooledByteBuf { - - private static final Recycler RECYCLER = new Recycler() { - @Override - protected PooledHeapByteBuf newObject(Handle handle) { - return new PooledHeapByteBuf(handle, 0); - } - }; - - static PooledHeapByteBuf newInstance(int maxCapacity) { - PooledHeapByteBuf buf = RECYCLER.get(); - buf.setRefCnt(1); - buf.maxCapacity(maxCapacity); - return buf; - } - - private PooledHeapByteBuf(Recycler.Handle recyclerHandle, int maxCapacity) { - super(recyclerHandle, maxCapacity); - } - - @Override - public boolean isDirect() { - return false; - } - - @Override - protected byte _getByte(int index) { - return memory[idx(index)]; - } - - @Override - protected short _getShort(int index) { - index = idx(index); - return (short) (memory[index] << 8 | memory[index + 1] & 0xFF); - } - - @Override - protected int _getUnsignedMedium(int index) { - index = idx(index); - return (memory[index] & 0xff) << 16 | - (memory[index + 1] & 0xff) << 8 | - memory[index + 2] & 0xff; - } - - @Override - protected int _getInt(int index) { - index = idx(index); - return (memory[index] & 0xff) << 24 | - (memory[index + 1] & 0xff) << 16 | - (memory[index + 2] & 0xff) << 8 | - memory[index + 3] & 0xff; - } - - @Override - protected long _getLong(int index) { - index = idx(index); - return ((long) memory[index] & 0xff) << 56 | - ((long) memory[index + 1] & 0xff) << 48 | - ((long) memory[index + 2] & 0xff) << 40 | - ((long) memory[index + 3] & 0xff) << 32 | - ((long) memory[index + 4] & 0xff) << 24 | - ((long) memory[index + 5] & 0xff) << 16 | - ((long) memory[index + 6] & 0xff) << 8 | - (long) memory[index + 7] & 0xff; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - checkDstIndex(index, length, dstIndex, dst.capacity()); - if (dst.hasArray()) { - getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length); - } else { - dst.setBytes(dstIndex, memory, idx(index), length); - } - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - checkDstIndex(index, length, dstIndex, dst.length); - System.arraycopy(memory, idx(index), dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - checkIndex(index); - dst.put(memory, idx(index), Math.min(capacity() - index, dst.remaining())); - return this; - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { - checkIndex(index, length); - out.write(memory, idx(index), length); - return this; - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { - return getBytes(index, out, length, false); - } - - private int getBytes(int index, GatheringByteChannel out, int length, boolean internal) throws IOException { - checkIndex(index, length); - index = idx(index); - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = ByteBuffer.wrap(memory); - } - return out.write((ByteBuffer) tmpBuf.clear().position(index).limit(index + length)); - } - - @Override - public int readBytes(GatheringByteChannel out, int length) throws IOException { - checkReadableBytes(length); - int readBytes = getBytes(readerIndex, out, length, true); - readerIndex += readBytes; - return readBytes; - } - - @Override - protected void _setByte(int index, int value) { - memory[idx(index)] = (byte) value; - } - - @Override - protected void _setShort(int index, int value) { - index = idx(index); - memory[index] = (byte) (value >>> 8); - memory[index + 1] = (byte) value; - } - - @Override - protected void _setMedium(int index, int value) { - index = idx(index); - memory[index] = (byte) (value >>> 16); - memory[index + 1] = (byte) (value >>> 8); - memory[index + 2] = (byte) value; - } - - @Override - protected void _setInt(int index, int value) { - index = idx(index); - memory[index] = (byte) (value >>> 24); - memory[index + 1] = (byte) (value >>> 16); - memory[index + 2] = (byte) (value >>> 8); - memory[index + 3] = (byte) value; - } - - @Override - protected void _setLong(int index, long value) { - index = idx(index); - memory[index] = (byte) (value >>> 56); - memory[index + 1] = (byte) (value >>> 48); - memory[index + 2] = (byte) (value >>> 40); - memory[index + 3] = (byte) (value >>> 32); - memory[index + 4] = (byte) (value >>> 24); - memory[index + 5] = (byte) (value >>> 16); - memory[index + 6] = (byte) (value >>> 8); - memory[index + 7] = (byte) value; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - checkSrcIndex(index, length, srcIndex, src.capacity()); - if (src.hasArray()) { - setBytes(index, src.array(), src.arrayOffset() + srcIndex, length); - } else { - src.getBytes(srcIndex, memory, idx(index), length); - } - return this; - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - checkSrcIndex(index, length, srcIndex, src.length); - System.arraycopy(src, srcIndex, memory, idx(index), length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - int length = src.remaining(); - checkIndex(index, length); - src.get(memory, idx(index), length); - return this; - } - - @Override - public int setBytes(int index, InputStream in, int length) throws IOException { - checkIndex(index, length); - return in.read(memory, idx(index), length); - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { - checkIndex(index, length); - index = idx(index); - try { - return in.read((ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length)); - } catch (ClosedChannelException ignored) { - return -1; - } - } - - @Override - public ByteBuf copy(int index, int length) { - checkIndex(index, length); - ByteBuf copy = alloc().heapBuffer(length, maxCapacity()); - copy.writeBytes(memory, idx(index), length); - return copy; - } - - @Override - public int nioBufferCount() { - return 1; - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - return new ByteBuffer[] { nioBuffer(index, length) }; - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - checkIndex(index, length); - index = idx(index); - ByteBuffer buf = ByteBuffer.wrap(memory, index, length); - return buf.slice(); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - checkIndex(index, length); - index = idx(index); - return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); - } - - @Override - public boolean hasArray() { - return true; - } - - @Override - public byte[] array() { - return memory; - } - - @Override - public int arrayOffset() { - return offset; - } - - @Override - protected ByteBuffer newInternalNioBuffer(byte[] memory) { - return ByteBuffer.wrap(memory); - } - - @Override - protected Recycler recycler() { - return RECYCLER; - } -} diff --git a/common/src/main/java/common/net/buffer/ReadOnlyByteBuf.java b/common/src/main/java/common/net/buffer/ReadOnlyByteBuf.java deleted file mode 100644 index 810a1b4..0000000 --- a/common/src/main/java/common/net/buffer/ReadOnlyByteBuf.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.ReadOnlyBufferException; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; - -/** - * A derived buffer which forbids any write requests to its parent. It is - * recommended to use {@link Unpooled#unmodifiableBuffer(ByteBuf)} - * instead of calling the constructor explicitly. - */ -public class ReadOnlyByteBuf extends AbstractDerivedByteBuf { - - private final ByteBuf buffer; - - public ReadOnlyByteBuf(ByteBuf buffer) { - super(buffer.maxCapacity()); - - if (buffer instanceof ReadOnlyByteBuf || buffer instanceof DuplicatedByteBuf) { - this.buffer = buffer.unwrap(); - } else { - this.buffer = buffer; - } - setIndex(buffer.readerIndex(), buffer.writerIndex()); - } - - @Override - public boolean isWritable() { - return false; - } - - @Override - public boolean isWritable(int numBytes) { - return false; - } - - @Override - public ByteBuf unwrap() { - return buffer; - } - - @Override - public ByteBufAllocator alloc() { - return buffer.alloc(); - } - - @Override - public ByteOrder order() { - return buffer.order(); - } - - @Override - public boolean isDirect() { - return buffer.isDirect(); - } - - @Override - public boolean hasArray() { - return false; - } - - @Override - public byte[] array() { - throw new ReadOnlyBufferException(); - } - - @Override - public int arrayOffset() { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBuf discardReadBytes() { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBuf setByte(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - protected void _setByte(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBuf setShort(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - protected void _setShort(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBuf setMedium(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - protected void _setMedium(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBuf setInt(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - protected void _setInt(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBuf setLong(int index, long value) { - throw new ReadOnlyBufferException(); - } - - @Override - protected void _setLong(int index, long value) { - throw new ReadOnlyBufferException(); - } - - @Override - public int setBytes(int index, InputStream in, int length) { - throw new ReadOnlyBufferException(); - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) { - throw new ReadOnlyBufferException(); - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) - throws IOException { - return buffer.getBytes(index, out, length); - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) - throws IOException { - buffer.getBytes(index, out, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - buffer.getBytes(index, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - buffer.getBytes(index, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - buffer.getBytes(index, dst); - return this; - } - - @Override - public ByteBuf duplicate() { - return new ReadOnlyByteBuf(this); - } - - @Override - public ByteBuf copy(int index, int length) { - return buffer.copy(index, length); - } - - @Override - public ByteBuf slice(int index, int length) { - return Unpooled.unmodifiableBuffer(buffer.slice(index, length)); - } - - @Override - public byte getByte(int index) { - return _getByte(index); - } - - @Override - protected byte _getByte(int index) { - return buffer.getByte(index); - } - - @Override - public short getShort(int index) { - return _getShort(index); - } - - @Override - protected short _getShort(int index) { - return buffer.getShort(index); - } - - @Override - public int getUnsignedMedium(int index) { - return _getUnsignedMedium(index); - } - - @Override - protected int _getUnsignedMedium(int index) { - return buffer.getUnsignedMedium(index); - } - - @Override - public int getInt(int index) { - return _getInt(index); - } - - @Override - protected int _getInt(int index) { - return buffer.getInt(index); - } - - @Override - public long getLong(int index) { - return _getLong(index); - } - - @Override - protected long _getLong(int index) { - return buffer.getLong(index); - } - - @Override - public int nioBufferCount() { - return buffer.nioBufferCount(); - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - return buffer.nioBuffer(index, length).asReadOnlyBuffer(); - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - return buffer.nioBuffers(index, length); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - return nioBuffer(index, length); - } - - @Override - public int forEachByte(int index, int length, ByteBufProcessor processor) { - return buffer.forEachByte(index, length, processor); - } - - @Override - public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { - return buffer.forEachByteDesc(index, length, processor); - } - - @Override - public int capacity() { - return buffer.capacity(); - } - - @Override - public ByteBuf capacity(int newCapacity) { - throw new ReadOnlyBufferException(); - } -} diff --git a/common/src/main/java/common/net/buffer/ReadOnlyByteBufferBuf.java b/common/src/main/java/common/net/buffer/ReadOnlyByteBufferBuf.java deleted file mode 100644 index 46bd366..0000000 --- a/common/src/main/java/common/net/buffer/ReadOnlyByteBufferBuf.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.ReadOnlyBufferException; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; - -import common.net.util.internal.StringUtil; - - -/** - * Read-only ByteBuf which wraps a read-only ByteBuffer. - */ -class ReadOnlyByteBufferBuf extends AbstractReferenceCountedByteBuf { - - protected final ByteBuffer buffer; - private final ByteBufAllocator allocator; - private ByteBuffer tmpNioBuf; - - ReadOnlyByteBufferBuf(ByteBufAllocator allocator, ByteBuffer buffer) { - super(buffer.remaining()); - if (!buffer.isReadOnly()) { - throw new IllegalArgumentException("must be a readonly buffer: " + StringUtil.simpleClassName(buffer)); - } - - this.allocator = allocator; - this.buffer = buffer.slice().order(ByteOrder.BIG_ENDIAN); - writerIndex(this.buffer.limit()); - } - - @Override - protected void deallocate() { } - - @Override - public byte getByte(int index) { - ensureAccessible(); - return _getByte(index); - } - - @Override - protected byte _getByte(int index) { - return buffer.get(index); - } - - @Override - public short getShort(int index) { - ensureAccessible(); - return _getShort(index); - } - - @Override - protected short _getShort(int index) { - return buffer.getShort(index); - } - - @Override - public int getUnsignedMedium(int index) { - ensureAccessible(); - return _getUnsignedMedium(index); - } - - @Override - protected int _getUnsignedMedium(int index) { - return (getByte(index) & 0xff) << 16 | (getByte(index + 1) & 0xff) << 8 | getByte(index + 2) & 0xff; - } - - @Override - public int getInt(int index) { - ensureAccessible(); - return _getInt(index); - } - - @Override - protected int _getInt(int index) { - return buffer.getInt(index); - } - - @Override - public long getLong(int index) { - ensureAccessible(); - return _getLong(index); - } - - @Override - protected long _getLong(int index) { - return buffer.getLong(index); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - checkDstIndex(index, length, dstIndex, dst.capacity()); - if (dst.hasArray()) { - getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length); - } else if (dst.nioBufferCount() > 0) { - for (ByteBuffer bb: dst.nioBuffers(dstIndex, length)) { - int bbLen = bb.remaining(); - getBytes(index, bb); - index += bbLen; - } - } else { - dst.setBytes(dstIndex, this, index, length); - } - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - checkDstIndex(index, length, dstIndex, dst.length); - - if (dstIndex < 0 || dstIndex > dst.length - length) { - throw new IndexOutOfBoundsException(String.format( - "dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dst.length)); - } - - ByteBuffer tmpBuf = internalNioBuffer(); - tmpBuf.clear().position(index).limit(index + length); - tmpBuf.get(dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - checkIndex(index); - if (dst == null) { - throw new NullPointerException("dst"); - } - - int bytesToCopy = Math.min(capacity() - index, dst.remaining()); - ByteBuffer tmpBuf = internalNioBuffer(); - tmpBuf.clear().position(index).limit(index + bytesToCopy); - dst.put(tmpBuf); - return this; - } - - @Override - protected void _setByte(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - protected void _setShort(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - protected void _setMedium(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - protected void _setInt(int index, int value) { - throw new ReadOnlyBufferException(); - } - - @Override - protected void _setLong(int index, long value) { - throw new ReadOnlyBufferException(); - } - - @Override - public int capacity() { - return maxCapacity(); - } - - @Override - public ByteBuf capacity(int newCapacity) { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBufAllocator alloc() { - return allocator; - } - - @Override - public ByteOrder order() { - return ByteOrder.BIG_ENDIAN; - } - - @Override - public ByteBuf unwrap() { - return null; - } - - @Override - public boolean isDirect() { - return buffer.isDirect(); - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { - ensureAccessible(); - if (length == 0) { - return this; - } - - if (buffer.hasArray()) { - out.write(buffer.array(), index + buffer.arrayOffset(), length); - } else { - byte[] tmp = new byte[length]; - ByteBuffer tmpBuf = internalNioBuffer(); - tmpBuf.clear().position(index); - tmpBuf.get(tmp); - out.write(tmp); - } - return this; - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { - ensureAccessible(); - if (length == 0) { - return 0; - } - - ByteBuffer tmpBuf = internalNioBuffer(); - tmpBuf.clear().position(index).limit(index + length); - return out.write(tmpBuf); - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - throw new ReadOnlyBufferException(); - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - throw new ReadOnlyBufferException(); - } - - @Override - public int setBytes(int index, InputStream in, int length) throws IOException { - throw new ReadOnlyBufferException(); - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { - throw new ReadOnlyBufferException(); - } - - protected final ByteBuffer internalNioBuffer() { - ByteBuffer tmpNioBuf = this.tmpNioBuf; - if (tmpNioBuf == null) { - this.tmpNioBuf = tmpNioBuf = buffer.duplicate(); - } - return tmpNioBuf; - } - - @Override - public ByteBuf copy(int index, int length) { - ensureAccessible(); - ByteBuffer src; - try { - src = (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); - } catch (IllegalArgumentException ignored) { - throw new IndexOutOfBoundsException("Too many bytes to read - Need " + (index + length)); - } - - ByteBuffer dst = ByteBuffer.allocateDirect(length); - dst.put(src); - dst.order(order()); - dst.clear(); - return new UnpooledDirectByteBuf(alloc(), dst, maxCapacity()); - } - - @Override - public int nioBufferCount() { - return 1; - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - return new ByteBuffer[] { nioBuffer(index, length) }; - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - return (ByteBuffer) buffer.duplicate().position(index).limit(index + length); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - ensureAccessible(); - return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); - } - - @Override - public boolean hasArray() { - return buffer.hasArray(); - } - - @Override - public byte[] array() { - return buffer.array(); - } - - @Override - public int arrayOffset() { - return buffer.arrayOffset(); - } -} diff --git a/common/src/main/java/common/net/buffer/SimpleLeakAwareByteBuf.java b/common/src/main/java/common/net/buffer/SimpleLeakAwareByteBuf.java deleted file mode 100644 index 688af60..0000000 --- a/common/src/main/java/common/net/buffer/SimpleLeakAwareByteBuf.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import java.nio.ByteOrder; - -import common.net.util.ResourceLeak; - -final class SimpleLeakAwareByteBuf extends WrappedByteBuf { - - private final ResourceLeak leak; - - SimpleLeakAwareByteBuf(ByteBuf buf, ResourceLeak leak) { - super(buf); - this.leak = leak; - } - - @Override - public boolean release() { - boolean deallocated = super.release(); - if (deallocated) { - leak.close(); - } - return deallocated; - } - - @Override - public boolean release(int decrement) { - boolean deallocated = super.release(decrement); - if (deallocated) { - leak.close(); - } - return deallocated; - } - - @Override - public ByteBuf order(ByteOrder endianness) { - leak.record(); - if (order() == endianness) { - return this; - } else { - return new SimpleLeakAwareByteBuf(super.order(endianness), leak); - } - } - - @Override - public ByteBuf slice() { - return new SimpleLeakAwareByteBuf(super.slice(), leak); - } - - @Override - public ByteBuf slice(int index, int length) { - return new SimpleLeakAwareByteBuf(super.slice(index, length), leak); - } - - @Override - public ByteBuf duplicate() { - return new SimpleLeakAwareByteBuf(super.duplicate(), leak); - } - - @Override - public ByteBuf readSlice(int length) { - return new SimpleLeakAwareByteBuf(super.readSlice(length), leak); - } -} diff --git a/common/src/main/java/common/net/buffer/SlicedByteBuf.java b/common/src/main/java/common/net/buffer/SlicedByteBuf.java deleted file mode 100644 index d0b26eb..0000000 --- a/common/src/main/java/common/net/buffer/SlicedByteBuf.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; - - -/** - * A derived buffer which exposes its parent's sub-region only. It is - * recommended to use {@link ByteBuf#slice()} and - * {@link ByteBuf#slice(int, int)} instead of calling the constructor - * explicitly. - */ -public class SlicedByteBuf extends AbstractDerivedByteBuf { - - private final ByteBuf buffer; - private final int adjustment; - private final int length; - - public SlicedByteBuf(ByteBuf buffer, int index, int length) { - super(length); - if (index < 0 || index > buffer.capacity() - length) { - throw new IndexOutOfBoundsException(buffer + ".slice(" + index + ", " + length + ')'); - } - - if (buffer instanceof SlicedByteBuf) { - this.buffer = ((SlicedByteBuf) buffer).buffer; - adjustment = ((SlicedByteBuf) buffer).adjustment + index; - } else if (buffer instanceof DuplicatedByteBuf) { - this.buffer = buffer.unwrap(); - adjustment = index; - } else { - this.buffer = buffer; - adjustment = index; - } - this.length = length; - - writerIndex(length); - } - - @Override - public ByteBuf unwrap() { - return buffer; - } - - @Override - public ByteBufAllocator alloc() { - return buffer.alloc(); - } - - @Override - public ByteOrder order() { - return buffer.order(); - } - - @Override - public boolean isDirect() { - return buffer.isDirect(); - } - - @Override - public int capacity() { - return length; - } - - @Override - public ByteBuf capacity(int newCapacity) { - throw new UnsupportedOperationException("sliced buffer"); - } - - @Override - public boolean hasArray() { - return buffer.hasArray(); - } - - @Override - public byte[] array() { - return buffer.array(); - } - - @Override - public int arrayOffset() { - return buffer.arrayOffset() + adjustment; - } - - @Override - protected byte _getByte(int index) { - return buffer.getByte(index + adjustment); - } - - @Override - protected short _getShort(int index) { - return buffer.getShort(index + adjustment); - } - - @Override - protected int _getUnsignedMedium(int index) { - return buffer.getUnsignedMedium(index + adjustment); - } - - @Override - protected int _getInt(int index) { - return buffer.getInt(index + adjustment); - } - - @Override - protected long _getLong(int index) { - return buffer.getLong(index + adjustment); - } - - @Override - public ByteBuf duplicate() { - ByteBuf duplicate = buffer.slice(adjustment, length); - duplicate.setIndex(readerIndex(), writerIndex()); - return duplicate; - } - - @Override - public ByteBuf copy(int index, int length) { - checkIndex(index, length); - return buffer.copy(index + adjustment, length); - } - - @Override - public ByteBuf slice(int index, int length) { - checkIndex(index, length); - if (length == 0) { - return Unpooled.EMPTY_BUFFER; - } - return buffer.slice(index + adjustment, length); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - checkIndex(index, length); - buffer.getBytes(index + adjustment, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - checkIndex(index, length); - buffer.getBytes(index + adjustment, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - checkIndex(index, dst.remaining()); - buffer.getBytes(index + adjustment, dst); - return this; - } - - @Override - protected void _setByte(int index, int value) { - buffer.setByte(index + adjustment, value); - } - - @Override - protected void _setShort(int index, int value) { - buffer.setShort(index + adjustment, value); - } - - @Override - protected void _setMedium(int index, int value) { - buffer.setMedium(index + adjustment, value); - } - - @Override - protected void _setInt(int index, int value) { - buffer.setInt(index + adjustment, value); - } - - @Override - protected void _setLong(int index, long value) { - buffer.setLong(index + adjustment, value); - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - checkIndex(index, length); - buffer.setBytes(index + adjustment, src, srcIndex, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - checkIndex(index, length); - buffer.setBytes(index + adjustment, src, srcIndex, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - checkIndex(index, src.remaining()); - buffer.setBytes(index + adjustment, src); - return this; - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { - checkIndex(index, length); - buffer.getBytes(index + adjustment, out, length); - return this; - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { - checkIndex(index, length); - return buffer.getBytes(index + adjustment, out, length); - } - - @Override - public int setBytes(int index, InputStream in, int length) throws IOException { - checkIndex(index, length); - return buffer.setBytes(index + adjustment, in, length); - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { - checkIndex(index, length); - return buffer.setBytes(index + adjustment, in, length); - } - - @Override - public int nioBufferCount() { - return buffer.nioBufferCount(); - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - checkIndex(index, length); - return buffer.nioBuffer(index + adjustment, length); - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - checkIndex(index, length); - return buffer.nioBuffers(index + adjustment, length); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - checkIndex(index, length); - return nioBuffer(index, length); - } - - @Override - public int forEachByte(int index, int length, ByteBufProcessor processor) { - int ret = buffer.forEachByte(index + adjustment, length, processor); - if (ret >= adjustment) { - return ret - adjustment; - } else { - return -1; - } - } - - @Override - public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { - int ret = buffer.forEachByteDesc(index + adjustment, length, processor); - if (ret >= adjustment) { - return ret - adjustment; - } else { - return -1; - } - } -} diff --git a/common/src/main/java/common/net/buffer/SwappedByteBuf.java b/common/src/main/java/common/net/buffer/SwappedByteBuf.java deleted file mode 100644 index d5c0a96..0000000 --- a/common/src/main/java/common/net/buffer/SwappedByteBuf.java +++ /dev/null @@ -1,842 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; -import java.nio.charset.Charset; - -/** - * Wrapper which swap the {@link ByteOrder} of a {@link ByteBuf}. - */ -public class SwappedByteBuf extends ByteBuf { - - private final ByteBuf buf; - private final ByteOrder order; - - public SwappedByteBuf(ByteBuf buf) { - if (buf == null) { - throw new NullPointerException("buf"); - } - this.buf = buf; - if (buf.order() == ByteOrder.BIG_ENDIAN) { - order = ByteOrder.LITTLE_ENDIAN; - } else { - order = ByteOrder.BIG_ENDIAN; - } - } - - @Override - public ByteOrder order() { - return order; - } - - @Override - public ByteBuf order(ByteOrder endianness) { - if (endianness == null) { - throw new NullPointerException("endianness"); - } - if (endianness == order) { - return this; - } - return buf; - } - - @Override - public ByteBuf unwrap() { - return buf.unwrap(); - } - - @Override - public ByteBufAllocator alloc() { - return buf.alloc(); - } - - @Override - public int capacity() { - return buf.capacity(); - } - - @Override - public ByteBuf capacity(int newCapacity) { - buf.capacity(newCapacity); - return this; - } - - @Override - public int maxCapacity() { - return buf.maxCapacity(); - } - - @Override - public boolean isDirect() { - return buf.isDirect(); - } - - @Override - public int readerIndex() { - return buf.readerIndex(); - } - - @Override - public ByteBuf readerIndex(int readerIndex) { - buf.readerIndex(readerIndex); - return this; - } - - @Override - public int writerIndex() { - return buf.writerIndex(); - } - - @Override - public ByteBuf writerIndex(int writerIndex) { - buf.writerIndex(writerIndex); - return this; - } - - @Override - public ByteBuf setIndex(int readerIndex, int writerIndex) { - buf.setIndex(readerIndex, writerIndex); - return this; - } - - @Override - public int readableBytes() { - return buf.readableBytes(); - } - - @Override - public int writableBytes() { - return buf.writableBytes(); - } - - @Override - public int maxWritableBytes() { - return buf.maxWritableBytes(); - } - - @Override - public boolean isReadable() { - return buf.isReadable(); - } - - @Override - public boolean isReadable(int size) { - return buf.isReadable(size); - } - - @Override - public boolean isWritable() { - return buf.isWritable(); - } - - @Override - public boolean isWritable(int size) { - return buf.isWritable(size); - } - - @Override - public ByteBuf clear() { - buf.clear(); - return this; - } - - @Override - public ByteBuf markReaderIndex() { - buf.markReaderIndex(); - return this; - } - - @Override - public ByteBuf resetReaderIndex() { - buf.resetReaderIndex(); - return this; - } - - @Override - public ByteBuf markWriterIndex() { - buf.markWriterIndex(); - return this; - } - - @Override - public ByteBuf resetWriterIndex() { - buf.resetWriterIndex(); - return this; - } - - @Override - public ByteBuf discardReadBytes() { - buf.discardReadBytes(); - return this; - } - - @Override - public ByteBuf discardSomeReadBytes() { - buf.discardSomeReadBytes(); - return this; - } - - @Override - public ByteBuf ensureWritable(int writableBytes) { - buf.ensureWritable(writableBytes); - return this; - } - - @Override - public int ensureWritable(int minWritableBytes, boolean force) { - return buf.ensureWritable(minWritableBytes, force); - } - - @Override - public boolean getBoolean(int index) { - return buf.getBoolean(index); - } - - @Override - public byte getByte(int index) { - return buf.getByte(index); - } - - @Override - public short getUnsignedByte(int index) { - return buf.getUnsignedByte(index); - } - - @Override - public short getShort(int index) { - return ByteBufUtil.swapShort(buf.getShort(index)); - } - - @Override - public int getUnsignedShort(int index) { - return getShort(index) & 0xFFFF; - } - - @Override - public int getMedium(int index) { - return ByteBufUtil.swapMedium(buf.getMedium(index)); - } - - @Override - public int getUnsignedMedium(int index) { - return getMedium(index) & 0xFFFFFF; - } - - @Override - public int getInt(int index) { - return ByteBufUtil.swapInt(buf.getInt(index)); - } - - @Override - public long getUnsignedInt(int index) { - return getInt(index) & 0xFFFFFFFFL; - } - - @Override - public long getLong(int index) { - return ByteBufUtil.swapLong(buf.getLong(index)); - } - - @Override - public char getChar(int index) { - return (char) getShort(index); - } - - @Override - public float getFloat(int index) { - return Float.intBitsToFloat(getInt(index)); - } - - @Override - public double getDouble(int index) { - return Double.longBitsToDouble(getLong(index)); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst) { - buf.getBytes(index, dst); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int length) { - buf.getBytes(index, dst, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - buf.getBytes(index, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst) { - buf.getBytes(index, dst); - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - buf.getBytes(index, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - buf.getBytes(index, dst); - return this; - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { - buf.getBytes(index, out, length); - return this; - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { - return buf.getBytes(index, out, length); - } - - @Override - public ByteBuf setBoolean(int index, boolean value) { - buf.setBoolean(index, value); - return this; - } - - @Override - public ByteBuf setByte(int index, int value) { - buf.setByte(index, value); - return this; - } - - @Override - public ByteBuf setShort(int index, int value) { - buf.setShort(index, ByteBufUtil.swapShort((short) value)); - return this; - } - - @Override - public ByteBuf setMedium(int index, int value) { - buf.setMedium(index, ByteBufUtil.swapMedium(value)); - return this; - } - - @Override - public ByteBuf setInt(int index, int value) { - buf.setInt(index, ByteBufUtil.swapInt(value)); - return this; - } - - @Override - public ByteBuf setLong(int index, long value) { - buf.setLong(index, ByteBufUtil.swapLong(value)); - return this; - } - - @Override - public ByteBuf setChar(int index, int value) { - setShort(index, value); - return this; - } - - @Override - public ByteBuf setFloat(int index, float value) { - setInt(index, Float.floatToRawIntBits(value)); - return this; - } - - @Override - public ByteBuf setDouble(int index, double value) { - setLong(index, Double.doubleToRawLongBits(value)); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src) { - buf.setBytes(index, src); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int length) { - buf.setBytes(index, src, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - buf.setBytes(index, src, srcIndex, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, byte[] src) { - buf.setBytes(index, src); - return this; - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - buf.setBytes(index, src, srcIndex, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - buf.setBytes(index, src); - return this; - } - - @Override - public int setBytes(int index, InputStream in, int length) throws IOException { - return buf.setBytes(index, in, length); - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { - return buf.setBytes(index, in, length); - } - - @Override - public ByteBuf setZero(int index, int length) { - buf.setZero(index, length); - return this; - } - - @Override - public boolean readBoolean() { - return buf.readBoolean(); - } - - @Override - public byte readByte() { - return buf.readByte(); - } - - @Override - public short readUnsignedByte() { - return buf.readUnsignedByte(); - } - - @Override - public short readShort() { - return ByteBufUtil.swapShort(buf.readShort()); - } - - @Override - public int readUnsignedShort() { - return readShort() & 0xFFFF; - } - - @Override - public int readMedium() { - return ByteBufUtil.swapMedium(buf.readMedium()); - } - - @Override - public int readUnsignedMedium() { - return readMedium() & 0xFFFFFF; - } - - @Override - public int readInt() { - return ByteBufUtil.swapInt(buf.readInt()); - } - - @Override - public long readUnsignedInt() { - return readInt() & 0xFFFFFFFFL; - } - - @Override - public long readLong() { - return ByteBufUtil.swapLong(buf.readLong()); - } - - @Override - public char readChar() { - return (char) readShort(); - } - - @Override - public float readFloat() { - return Float.intBitsToFloat(readInt()); - } - - @Override - public double readDouble() { - return Double.longBitsToDouble(readLong()); - } - - @Override - public ByteBuf readBytes(int length) { - return buf.readBytes(length).order(order()); - } - - @Override - public ByteBuf readSlice(int length) { - return buf.readSlice(length).order(order); - } - - @Override - public ByteBuf readBytes(ByteBuf dst) { - buf.readBytes(dst); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int length) { - buf.readBytes(dst, length); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { - buf.readBytes(dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf readBytes(byte[] dst) { - buf.readBytes(dst); - return this; - } - - @Override - public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { - buf.readBytes(dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuffer dst) { - buf.readBytes(dst); - return this; - } - - @Override - public ByteBuf readBytes(OutputStream out, int length) throws IOException { - buf.readBytes(out, length); - return this; - } - - @Override - public int readBytes(GatheringByteChannel out, int length) throws IOException { - return buf.readBytes(out, length); - } - - @Override - public ByteBuf skipBytes(int length) { - buf.skipBytes(length); - return this; - } - - @Override - public ByteBuf writeBoolean(boolean value) { - buf.writeBoolean(value); - return this; - } - - @Override - public ByteBuf writeByte(int value) { - buf.writeByte(value); - return this; - } - - @Override - public ByteBuf writeShort(int value) { - buf.writeShort(ByteBufUtil.swapShort((short) value)); - return this; - } - - @Override - public ByteBuf writeMedium(int value) { - buf.writeMedium(ByteBufUtil.swapMedium(value)); - return this; - } - - @Override - public ByteBuf writeInt(int value) { - buf.writeInt(ByteBufUtil.swapInt(value)); - return this; - } - - @Override - public ByteBuf writeLong(long value) { - buf.writeLong(ByteBufUtil.swapLong(value)); - return this; - } - - @Override - public ByteBuf writeChar(int value) { - writeShort(value); - return this; - } - - @Override - public ByteBuf writeFloat(float value) { - writeInt(Float.floatToRawIntBits(value)); - return this; - } - - @Override - public ByteBuf writeDouble(double value) { - writeLong(Double.doubleToRawLongBits(value)); - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuf src) { - buf.writeBytes(src); - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuf src, int length) { - buf.writeBytes(src, length); - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { - buf.writeBytes(src, srcIndex, length); - return this; - } - - @Override - public ByteBuf writeBytes(byte[] src) { - buf.writeBytes(src); - return this; - } - - @Override - public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { - buf.writeBytes(src, srcIndex, length); - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuffer src) { - buf.writeBytes(src); - return this; - } - - @Override - public int writeBytes(InputStream in, int length) throws IOException { - return buf.writeBytes(in, length); - } - - @Override - public int writeBytes(ScatteringByteChannel in, int length) throws IOException { - return buf.writeBytes(in, length); - } - - @Override - public ByteBuf writeZero(int length) { - buf.writeZero(length); - return this; - } - - @Override - public int indexOf(int fromIndex, int toIndex, byte value) { - return buf.indexOf(fromIndex, toIndex, value); - } - - @Override - public int bytesBefore(byte value) { - return buf.bytesBefore(value); - } - - @Override - public int bytesBefore(int length, byte value) { - return buf.bytesBefore(length, value); - } - - @Override - public int bytesBefore(int index, int length, byte value) { - return buf.bytesBefore(index, length, value); - } - - @Override - public int forEachByte(ByteBufProcessor processor) { - return buf.forEachByte(processor); - } - - @Override - public int forEachByte(int index, int length, ByteBufProcessor processor) { - return buf.forEachByte(index, length, processor); - } - - @Override - public int forEachByteDesc(ByteBufProcessor processor) { - return buf.forEachByteDesc(processor); - } - - @Override - public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { - return buf.forEachByteDesc(index, length, processor); - } - - @Override - public ByteBuf copy() { - return buf.copy().order(order); - } - - @Override - public ByteBuf copy(int index, int length) { - return buf.copy(index, length).order(order); - } - - @Override - public ByteBuf slice() { - return buf.slice().order(order); - } - - @Override - public ByteBuf slice(int index, int length) { - return buf.slice(index, length).order(order); - } - - @Override - public ByteBuf duplicate() { - return buf.duplicate().order(order); - } - - @Override - public int nioBufferCount() { - return buf.nioBufferCount(); - } - - @Override - public ByteBuffer nioBuffer() { - return buf.nioBuffer().order(order); - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - return buf.nioBuffer(index, length).order(order); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - return nioBuffer(index, length); - } - - @Override - public ByteBuffer[] nioBuffers() { - ByteBuffer[] nioBuffers = buf.nioBuffers(); - for (int i = 0; i < nioBuffers.length; i++) { - nioBuffers[i] = nioBuffers[i].order(order); - } - return nioBuffers; - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - ByteBuffer[] nioBuffers = buf.nioBuffers(index, length); - for (int i = 0; i < nioBuffers.length; i++) { - nioBuffers[i] = nioBuffers[i].order(order); - } - return nioBuffers; - } - - @Override - public boolean hasArray() { - return buf.hasArray(); - } - - @Override - public byte[] array() { - return buf.array(); - } - - @Override - public int arrayOffset() { - return buf.arrayOffset(); - } - - @Override - public String toString(Charset charset) { - return buf.toString(charset); - } - - @Override - public String toString(int index, int length, Charset charset) { - return buf.toString(index, length, charset); - } - - @Override - public int refCnt() { - return buf.refCnt(); - } - - @Override - public ByteBuf retain() { - buf.retain(); - return this; - } - - @Override - public ByteBuf retain(int increment) { - buf.retain(increment); - return this; - } - - @Override - public boolean release() { - return buf.release(); - } - - @Override - public boolean release(int decrement) { - return buf.release(decrement); - } - - @Override - public int hashCode() { - return buf.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof ByteBuf) { - return ByteBufUtil.equals(this, (ByteBuf) obj); - } - return false; - } - - @Override - public int compareTo(ByteBuf buffer) { - return ByteBufUtil.compare(this, buffer); - } - - @Override - public String toString() { - return "Swapped(" + buf.toString() + ')'; - } -} diff --git a/common/src/main/java/common/net/buffer/Unpooled.java b/common/src/main/java/common/net/buffer/Unpooled.java deleted file mode 100644 index ffd166e..0000000 --- a/common/src/main/java/common/net/buffer/Unpooled.java +++ /dev/null @@ -1,850 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; - - -/** - * Creates a new {@link ByteBuf} by allocating new space or by wrapping - * or copying existing byte arrays, byte buffers and a string. - * - *

Use static import

- * This classes is intended to be used with Java 5 static import statement: - * - *
- * import static game.net.buffer.{@link Unpooled}.*;
- *
- * {@link ByteBuf} heapBuffer    = buffer(128);
- * {@link ByteBuf} directBuffer  = directBuffer(256);
- * {@link ByteBuf} wrappedBuffer = wrappedBuffer(new byte[128], new byte[256]);
- * {@link ByteBuf} copiedBuffe r = copiedBuffer({@link ByteBuffer}.allocate(128));
- * 
- * - *

Allocating a new buffer

- * - * Three buffer types are provided out of the box. - * - *
    - *
  • {@link #buffer(int)} allocates a new fixed-capacity heap buffer.
  • - *
  • {@link #directBuffer(int)} allocates a new fixed-capacity direct buffer.
  • - *
- * - *

Creating a wrapped buffer

- * - * Wrapped buffer is a buffer which is a view of one or more existing - * byte arrays and byte buffers. Any changes in the content of the original - * array or buffer will be visible in the wrapped buffer. Various wrapper - * methods are provided and their name is all {@code wrappedBuffer()}. - * You might want to take a look at the methods that accept varargs closely if - * you want to create a buffer which is composed of more than one array to - * reduce the number of memory copy. - * - *

Creating a copied buffer

- * - * Copied buffer is a deep copy of one or more existing byte arrays, byte - * buffers or a string. Unlike a wrapped buffer, there's no shared data - * between the original data and the copied buffer. Various copy methods are - * provided and their name is all {@code copiedBuffer()}. It is also convenient - * to use this operation to merge multiple buffers into one buffer. - * - *

Miscellaneous utility methods

- * - * This class also provides various utility methods to help implementation - * of a new buffer type, generation of hex dump and swapping an integer's - * byte order. - */ -public final class Unpooled { - - private static final ByteBufAllocator ALLOC = UnpooledByteBufAllocator.DEFAULT; - - /** - * Big endian byte order. - */ - public static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN; - - /** - * Little endian byte order. - */ - public static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN; - - /** - * A buffer whose capacity is {@code 0}. - */ - public static final ByteBuf EMPTY_BUFFER = ALLOC.buffer(0, 0); - - /** - * Creates a new big-endian Java heap buffer with reasonably small initial capacity, which - * expands its capacity boundlessly on demand. - */ - public static ByteBuf buffer() { - return ALLOC.heapBuffer(); - } - - /** - * Creates a new big-endian direct buffer with reasonably small initial capacity, which - * expands its capacity boundlessly on demand. - */ - public static ByteBuf directBuffer() { - return ALLOC.directBuffer(); - } - - /** - * Creates a new big-endian Java heap buffer with the specified {@code capacity}, which - * expands its capacity boundlessly on demand. The new buffer's {@code readerIndex} and - * {@code writerIndex} are {@code 0}. - */ - public static ByteBuf buffer(int initialCapacity) { - return ALLOC.heapBuffer(initialCapacity); - } - - /** - * Creates a new big-endian direct buffer with the specified {@code capacity}, which - * expands its capacity boundlessly on demand. The new buffer's {@code readerIndex} and - * {@code writerIndex} are {@code 0}. - */ - public static ByteBuf directBuffer(int initialCapacity) { - return ALLOC.directBuffer(initialCapacity); - } - - /** - * Creates a new big-endian Java heap buffer with the specified - * {@code initialCapacity}, that may grow up to {@code maxCapacity} - * The new buffer's {@code readerIndex} and {@code writerIndex} are - * {@code 0}. - */ - public static ByteBuf buffer(int initialCapacity, int maxCapacity) { - return ALLOC.heapBuffer(initialCapacity, maxCapacity); - } - - /** - * Creates a new big-endian direct buffer with the specified - * {@code initialCapacity}, that may grow up to {@code maxCapacity}. - * The new buffer's {@code readerIndex} and {@code writerIndex} are - * {@code 0}. - */ - public static ByteBuf directBuffer(int initialCapacity, int maxCapacity) { - return ALLOC.directBuffer(initialCapacity, maxCapacity); - } - - /** - * Creates a new big-endian buffer which wraps the specified {@code array}. - * A modification on the specified array's content will be visible to the - * returned buffer. - */ - public static ByteBuf wrappedBuffer(byte[] array) { - if (array.length == 0) { - return EMPTY_BUFFER; - } - return new UnpooledHeapByteBuf(ALLOC, array, array.length); - } - - /** - * Creates a new big-endian buffer which wraps the sub-region of the - * specified {@code array}. A modification on the specified array's - * content will be visible to the returned buffer. - */ - public static ByteBuf wrappedBuffer(byte[] array, int offset, int length) { - if (length == 0) { - return EMPTY_BUFFER; - } - - if (offset == 0 && length == array.length) { - return wrappedBuffer(array); - } - - return wrappedBuffer(array).slice(offset, length); - } - - /** - * Creates a new buffer which wraps the specified NIO buffer's current - * slice. A modification on the specified buffer's content will be - * visible to the returned buffer. - */ - public static ByteBuf wrappedBuffer(ByteBuffer buffer) { - if (!buffer.hasRemaining()) { - return EMPTY_BUFFER; - } - if (buffer.hasArray()) { - return wrappedBuffer( - buffer.array(), - buffer.arrayOffset() + buffer.position(), - buffer.remaining()).order(buffer.order()); - } - else { - if (buffer.isReadOnly()) { - return new ReadOnlyByteBufferBuf(ALLOC, buffer); - } else { - return new UnpooledDirectByteBuf(ALLOC, buffer, buffer.remaining()); - } - } - } - - /** - * Creates a new buffer which wraps the specified buffer's readable bytes. - * A modification on the specified buffer's content will be visible to the - * returned buffer. - */ - public static ByteBuf wrappedBuffer(ByteBuf buffer) { - if (buffer.isReadable()) { - return buffer.slice(); - } else { - return EMPTY_BUFFER; - } - } - - /** - * Creates a new big-endian composite buffer which wraps the specified - * arrays without copying them. A modification on the specified arrays' - * content will be visible to the returned buffer. - */ - public static ByteBuf wrappedBuffer(byte[]... arrays) { - return wrappedBuffer(16, arrays); - } - - /** - * Creates a new big-endian composite buffer which wraps the readable bytes of the - * specified buffers without copying them. A modification on the content - * of the specified buffers will be visible to the returned buffer. - */ - public static ByteBuf wrappedBuffer(ByteBuf... buffers) { - return wrappedBuffer(16, buffers); - } - - /** - * Creates a new big-endian composite buffer which wraps the slices of the specified - * NIO buffers without copying them. A modification on the content of the - * specified buffers will be visible to the returned buffer. - */ - public static ByteBuf wrappedBuffer(ByteBuffer... buffers) { - return wrappedBuffer(16, buffers); - } - - /** - * Creates a new big-endian composite buffer which wraps the specified - * arrays without copying them. A modification on the specified arrays' - * content will be visible to the returned buffer. - */ - public static ByteBuf wrappedBuffer(int maxNumComponents, byte[]... arrays) { - switch (arrays.length) { - case 0: - break; - case 1: - if (arrays[0].length != 0) { - return wrappedBuffer(arrays[0]); - } - break; - default: - // Get the list of the component, while guessing the byte order. - final List components = new ArrayList(arrays.length); - for (byte[] a: arrays) { - if (a == null) { - break; - } - if (a.length > 0) { - components.add(wrappedBuffer(a)); - } - } - - if (!components.isEmpty()) { - return new CompositeByteBuf(ALLOC, false, maxNumComponents, components); - } - } - - return EMPTY_BUFFER; - } - - /** - * Creates a new big-endian composite buffer which wraps the readable bytes of the - * specified buffers without copying them. A modification on the content - * of the specified buffers will be visible to the returned buffer. - */ - public static ByteBuf wrappedBuffer(int maxNumComponents, ByteBuf... buffers) { - switch (buffers.length) { - case 0: - break; - case 1: - if (buffers[0].isReadable()) { - return wrappedBuffer(buffers[0].order(BIG_ENDIAN)); - } - break; - default: - for (ByteBuf b: buffers) { - if (b.isReadable()) { - return new CompositeByteBuf(ALLOC, false, maxNumComponents, buffers); - } - } - } - return EMPTY_BUFFER; - } - - /** - * Creates a new big-endian composite buffer which wraps the slices of the specified - * NIO buffers without copying them. A modification on the content of the - * specified buffers will be visible to the returned buffer. - */ - public static ByteBuf wrappedBuffer(int maxNumComponents, ByteBuffer... buffers) { - switch (buffers.length) { - case 0: - break; - case 1: - if (buffers[0].hasRemaining()) { - return wrappedBuffer(buffers[0].order(BIG_ENDIAN)); - } - break; - default: - // Get the list of the component, while guessing the byte order. - final List components = new ArrayList(buffers.length); - for (ByteBuffer b: buffers) { - if (b == null) { - break; - } - if (b.remaining() > 0) { - components.add(wrappedBuffer(b.order(BIG_ENDIAN))); - } - } - - if (!components.isEmpty()) { - return new CompositeByteBuf(ALLOC, false, maxNumComponents, components); - } - } - - return EMPTY_BUFFER; - } - - /** - * Returns a new big-endian composite buffer with no components. - */ - public static CompositeByteBuf compositeBuffer() { - return compositeBuffer(16); - } - - /** - * Returns a new big-endian composite buffer with no components. - */ - public static CompositeByteBuf compositeBuffer(int maxNumComponents) { - return new CompositeByteBuf(ALLOC, false, maxNumComponents); - } - - /** - * Creates a new big-endian buffer whose content is a copy of the - * specified {@code array}. The new buffer's {@code readerIndex} and - * {@code writerIndex} are {@code 0} and {@code array.length} respectively. - */ - public static ByteBuf copiedBuffer(byte[] array) { - if (array.length == 0) { - return EMPTY_BUFFER; - } - return wrappedBuffer(array.clone()); - } - - /** - * Creates a new big-endian buffer whose content is a copy of the - * specified {@code array}'s sub-region. The new buffer's - * {@code readerIndex} and {@code writerIndex} are {@code 0} and - * the specified {@code length} respectively. - */ - public static ByteBuf copiedBuffer(byte[] array, int offset, int length) { - if (length == 0) { - return EMPTY_BUFFER; - } - byte[] copy = new byte[length]; - System.arraycopy(array, offset, copy, 0, length); - return wrappedBuffer(copy); - } - - /** - * Creates a new buffer whose content is a copy of the specified - * {@code buffer}'s current slice. The new buffer's {@code readerIndex} - * and {@code writerIndex} are {@code 0} and {@code buffer.remaining} - * respectively. - */ - public static ByteBuf copiedBuffer(ByteBuffer buffer) { - int length = buffer.remaining(); - if (length == 0) { - return EMPTY_BUFFER; - } - byte[] copy = new byte[length]; - int position = buffer.position(); - try { - buffer.get(copy); - } finally { - buffer.position(position); - } - return wrappedBuffer(copy).order(buffer.order()); - } - - /** - * Creates a new buffer whose content is a copy of the specified - * {@code buffer}'s readable bytes. The new buffer's {@code readerIndex} - * and {@code writerIndex} are {@code 0} and {@code buffer.readableBytes} - * respectively. - */ - public static ByteBuf copiedBuffer(ByteBuf buffer) { - int readable = buffer.readableBytes(); - if (readable > 0) { - ByteBuf copy = buffer(readable); - copy.writeBytes(buffer, buffer.readerIndex(), readable); - return copy; - } else { - return EMPTY_BUFFER; - } - } - - /** - * Creates a new big-endian buffer whose content is a merged copy of - * the specified {@code arrays}. The new buffer's {@code readerIndex} - * and {@code writerIndex} are {@code 0} and the sum of all arrays' - * {@code length} respectively. - */ - public static ByteBuf copiedBuffer(byte[]... arrays) { - switch (arrays.length) { - case 0: - return EMPTY_BUFFER; - case 1: - if (arrays[0].length == 0) { - return EMPTY_BUFFER; - } else { - return copiedBuffer(arrays[0]); - } - } - - // Merge the specified arrays into one array. - int length = 0; - for (byte[] a: arrays) { - if (Integer.MAX_VALUE - length < a.length) { - throw new IllegalArgumentException( - "The total length of the specified arrays is too big."); - } - length += a.length; - } - - if (length == 0) { - return EMPTY_BUFFER; - } - - byte[] mergedArray = new byte[length]; - for (int i = 0, j = 0; i < arrays.length; i ++) { - byte[] a = arrays[i]; - System.arraycopy(a, 0, mergedArray, j, a.length); - j += a.length; - } - - return wrappedBuffer(mergedArray); - } - - /** - * Creates a new buffer whose content is a merged copy of the specified - * {@code buffers}' readable bytes. The new buffer's {@code readerIndex} - * and {@code writerIndex} are {@code 0} and the sum of all buffers' - * {@code readableBytes} respectively. - * - * @throws IllegalArgumentException - * if the specified buffers' endianness are different from each - * other - */ - public static ByteBuf copiedBuffer(ByteBuf... buffers) { - switch (buffers.length) { - case 0: - return EMPTY_BUFFER; - case 1: - return copiedBuffer(buffers[0]); - } - - // Merge the specified buffers into one buffer. - ByteOrder order = null; - int length = 0; - for (ByteBuf b: buffers) { - int bLen = b.readableBytes(); - if (bLen <= 0) { - continue; - } - if (Integer.MAX_VALUE - length < bLen) { - throw new IllegalArgumentException( - "The total length of the specified buffers is too big."); - } - length += bLen; - if (order != null) { - if (!order.equals(b.order())) { - throw new IllegalArgumentException("inconsistent byte order"); - } - } else { - order = b.order(); - } - } - - if (length == 0) { - return EMPTY_BUFFER; - } - - byte[] mergedArray = new byte[length]; - for (int i = 0, j = 0; i < buffers.length; i ++) { - ByteBuf b = buffers[i]; - int bLen = b.readableBytes(); - b.getBytes(b.readerIndex(), mergedArray, j, bLen); - j += bLen; - } - - return wrappedBuffer(mergedArray).order(order); - } - - /** - * Creates a new buffer whose content is a merged copy of the specified - * {@code buffers}' slices. The new buffer's {@code readerIndex} and - * {@code writerIndex} are {@code 0} and the sum of all buffers' - * {@code remaining} respectively. - * - * @throws IllegalArgumentException - * if the specified buffers' endianness are different from each - * other - */ - public static ByteBuf copiedBuffer(ByteBuffer... buffers) { - switch (buffers.length) { - case 0: - return EMPTY_BUFFER; - case 1: - return copiedBuffer(buffers[0]); - } - - // Merge the specified buffers into one buffer. - ByteOrder order = null; - int length = 0; - for (ByteBuffer b: buffers) { - int bLen = b.remaining(); - if (bLen <= 0) { - continue; - } - if (Integer.MAX_VALUE - length < bLen) { - throw new IllegalArgumentException( - "The total length of the specified buffers is too big."); - } - length += bLen; - if (order != null) { - if (!order.equals(b.order())) { - throw new IllegalArgumentException("inconsistent byte order"); - } - } else { - order = b.order(); - } - } - - if (length == 0) { - return EMPTY_BUFFER; - } - - byte[] mergedArray = new byte[length]; - for (int i = 0, j = 0; i < buffers.length; i ++) { - ByteBuffer b = buffers[i]; - int bLen = b.remaining(); - int oldPos = b.position(); - b.get(mergedArray, j, bLen); - b.position(oldPos); - j += bLen; - } - - return wrappedBuffer(mergedArray).order(order); - } - - /** - * Creates a new big-endian buffer whose content is the specified - * {@code string} encoded in the specified {@code charset}. - * The new buffer's {@code readerIndex} and {@code writerIndex} are - * {@code 0} and the length of the encoded string respectively. - */ - public static ByteBuf copiedBuffer(CharSequence string, Charset charset) { - if (string == null) { - throw new NullPointerException("string"); - } - - if (string instanceof CharBuffer) { - return copiedBuffer((CharBuffer) string, charset); - } - - return copiedBuffer(CharBuffer.wrap(string), charset); - } - - /** - * Creates a new big-endian buffer whose content is a subregion of - * the specified {@code string} encoded in the specified {@code charset}. - * The new buffer's {@code readerIndex} and {@code writerIndex} are - * {@code 0} and the length of the encoded string respectively. - */ - public static ByteBuf copiedBuffer( - CharSequence string, int offset, int length, Charset charset) { - if (string == null) { - throw new NullPointerException("string"); - } - if (length == 0) { - return EMPTY_BUFFER; - } - - if (string instanceof CharBuffer) { - CharBuffer buf = (CharBuffer) string; - if (buf.hasArray()) { - return copiedBuffer( - buf.array(), - buf.arrayOffset() + buf.position() + offset, - length, charset); - } - - buf = buf.slice(); - buf.limit(length); - buf.position(offset); - return copiedBuffer(buf, charset); - } - - return copiedBuffer(CharBuffer.wrap(string, offset, offset + length), charset); - } - - /** - * Creates a new big-endian buffer whose content is the specified - * {@code array} encoded in the specified {@code charset}. - * The new buffer's {@code readerIndex} and {@code writerIndex} are - * {@code 0} and the length of the encoded string respectively. - */ - public static ByteBuf copiedBuffer(char[] array, Charset charset) { - if (array == null) { - throw new NullPointerException("array"); - } - return copiedBuffer(array, 0, array.length, charset); - } - - /** - * Creates a new big-endian buffer whose content is a subregion of - * the specified {@code array} encoded in the specified {@code charset}. - * The new buffer's {@code readerIndex} and {@code writerIndex} are - * {@code 0} and the length of the encoded string respectively. - */ - public static ByteBuf copiedBuffer(char[] array, int offset, int length, Charset charset) { - if (array == null) { - throw new NullPointerException("array"); - } - if (length == 0) { - return EMPTY_BUFFER; - } - return copiedBuffer(CharBuffer.wrap(array, offset, length), charset); - } - - private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset) { - return ByteBufUtil.encodeString0(ALLOC, true, buffer, charset); - } - - /** - * Creates a read-only buffer which disallows any modification operations - * on the specified {@code buffer}. The new buffer has the same - * {@code readerIndex} and {@code writerIndex} with the specified - * {@code buffer}. - */ - public static ByteBuf unmodifiableBuffer(ByteBuf buffer) { - ByteOrder endianness = buffer.order(); - if (endianness == BIG_ENDIAN) { - return new ReadOnlyByteBuf(buffer); - } - - return new ReadOnlyByteBuf(buffer.order(BIG_ENDIAN)).order(LITTLE_ENDIAN); - } - - /** - * Creates a new 4-byte big-endian buffer that holds the specified 32-bit integer. - */ - public static ByteBuf copyInt(int value) { - ByteBuf buf = buffer(4); - buf.writeInt(value); - return buf; - } - - /** - * Create a big-endian buffer that holds a sequence of the specified 32-bit integers. - */ - public static ByteBuf copyInt(int... values) { - if (values == null || values.length == 0) { - return EMPTY_BUFFER; - } - ByteBuf buffer = buffer(values.length * 4); - for (int v: values) { - buffer.writeInt(v); - } - return buffer; - } - - /** - * Creates a new 2-byte big-endian buffer that holds the specified 16-bit integer. - */ - public static ByteBuf copyShort(int value) { - ByteBuf buf = buffer(2); - buf.writeShort(value); - return buf; - } - - /** - * Create a new big-endian buffer that holds a sequence of the specified 16-bit integers. - */ - public static ByteBuf copyShort(short... values) { - if (values == null || values.length == 0) { - return EMPTY_BUFFER; - } - ByteBuf buffer = buffer(values.length * 2); - for (int v: values) { - buffer.writeShort(v); - } - return buffer; - } - - /** - * Create a new big-endian buffer that holds a sequence of the specified 16-bit integers. - */ - public static ByteBuf copyShort(int... values) { - if (values == null || values.length == 0) { - return EMPTY_BUFFER; - } - ByteBuf buffer = buffer(values.length * 2); - for (int v: values) { - buffer.writeShort(v); - } - return buffer; - } - - /** - * Creates a new 3-byte big-endian buffer that holds the specified 24-bit integer. - */ - public static ByteBuf copyMedium(int value) { - ByteBuf buf = buffer(3); - buf.writeMedium(value); - return buf; - } - - /** - * Create a new big-endian buffer that holds a sequence of the specified 24-bit integers. - */ - public static ByteBuf copyMedium(int... values) { - if (values == null || values.length == 0) { - return EMPTY_BUFFER; - } - ByteBuf buffer = buffer(values.length * 3); - for (int v: values) { - buffer.writeMedium(v); - } - return buffer; - } - - /** - * Creates a new 8-byte big-endian buffer that holds the specified 64-bit integer. - */ - public static ByteBuf copyLong(long value) { - ByteBuf buf = buffer(8); - buf.writeLong(value); - return buf; - } - - /** - * Create a new big-endian buffer that holds a sequence of the specified 64-bit integers. - */ - public static ByteBuf copyLong(long... values) { - if (values == null || values.length == 0) { - return EMPTY_BUFFER; - } - ByteBuf buffer = buffer(values.length * 8); - for (long v: values) { - buffer.writeLong(v); - } - return buffer; - } - - /** - * Creates a new single-byte big-endian buffer that holds the specified boolean value. - */ - public static ByteBuf copyBoolean(boolean value) { - ByteBuf buf = buffer(1); - buf.writeBoolean(value); - return buf; - } - - /** - * Create a new big-endian buffer that holds a sequence of the specified boolean values. - */ - public static ByteBuf copyBoolean(boolean... values) { - if (values == null || values.length == 0) { - return EMPTY_BUFFER; - } - ByteBuf buffer = buffer(values.length); - for (boolean v: values) { - buffer.writeBoolean(v); - } - return buffer; - } - - /** - * Creates a new 4-byte big-endian buffer that holds the specified 32-bit floating point number. - */ - public static ByteBuf copyFloat(float value) { - ByteBuf buf = buffer(4); - buf.writeFloat(value); - return buf; - } - - /** - * Create a new big-endian buffer that holds a sequence of the specified 32-bit floating point numbers. - */ - public static ByteBuf copyFloat(float... values) { - if (values == null || values.length == 0) { - return EMPTY_BUFFER; - } - ByteBuf buffer = buffer(values.length * 4); - for (float v: values) { - buffer.writeFloat(v); - } - return buffer; - } - - /** - * Creates a new 8-byte big-endian buffer that holds the specified 64-bit floating point number. - */ - public static ByteBuf copyDouble(double value) { - ByteBuf buf = buffer(8); - buf.writeDouble(value); - return buf; - } - - /** - * Create a new big-endian buffer that holds a sequence of the specified 64-bit floating point numbers. - */ - public static ByteBuf copyDouble(double... values) { - if (values == null || values.length == 0) { - return EMPTY_BUFFER; - } - ByteBuf buffer = buffer(values.length * 8); - for (double v: values) { - buffer.writeDouble(v); - } - return buffer; - } - - /** - * Return a unreleasable view on the given {@link ByteBuf} which will just ignore release and retain calls. - */ - public static ByteBuf unreleasableBuffer(ByteBuf buf) { - return new UnreleasableByteBuf(buf); - } - - private Unpooled() { - // Unused - } -} diff --git a/common/src/main/java/common/net/buffer/UnpooledByteBufAllocator.java b/common/src/main/java/common/net/buffer/UnpooledByteBufAllocator.java deleted file mode 100644 index 5d5d70d..0000000 --- a/common/src/main/java/common/net/buffer/UnpooledByteBufAllocator.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -/** - * Simplistic {@link ByteBufAllocator} implementation that does not pool anything. - */ -public final class UnpooledByteBufAllocator extends AbstractByteBufAllocator { - - /** - * Default instance - */ - public static final UnpooledByteBufAllocator DEFAULT = new UnpooledByteBufAllocator(); - - @Override - protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) { - return new UnpooledHeapByteBuf(this, initialCapacity, maxCapacity); - } - - @Override - protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) { - ByteBuf buf; - buf = new UnpooledDirectByteBuf(this, initialCapacity, maxCapacity); - - return toLeakAwareBuffer(buf); - } - - @Override - public boolean isDirectBufferPooled() { - return false; - } -} diff --git a/common/src/main/java/common/net/buffer/UnpooledDirectByteBuf.java b/common/src/main/java/common/net/buffer/UnpooledDirectByteBuf.java deleted file mode 100644 index 22950dc..0000000 --- a/common/src/main/java/common/net/buffer/UnpooledDirectByteBuf.java +++ /dev/null @@ -1,591 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; - -/** - * A NIO {@link ByteBuffer} based buffer. It is recommended to use {@link Unpooled#directBuffer(int)} - * and {@link Unpooled#wrappedBuffer(ByteBuffer)} instead of calling the - * constructor explicitly. - */ -public class UnpooledDirectByteBuf extends AbstractReferenceCountedByteBuf { - - private final ByteBufAllocator alloc; - - private ByteBuffer buffer; - private ByteBuffer tmpNioBuf; - private int capacity; - private boolean doNotFree; - - /** - * Creates a new direct buffer. - * - * @param initialCapacity the initial capacity of the underlying direct buffer - * @param maxCapacity the maximum capacity of the underlying direct buffer - */ - protected UnpooledDirectByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) { - super(maxCapacity); - if (alloc == null) { - throw new NullPointerException("alloc"); - } - if (initialCapacity < 0) { - throw new IllegalArgumentException("initialCapacity: " + initialCapacity); - } - if (maxCapacity < 0) { - throw new IllegalArgumentException("maxCapacity: " + maxCapacity); - } - if (initialCapacity > maxCapacity) { - throw new IllegalArgumentException(String.format( - "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity)); - } - - this.alloc = alloc; - setByteBuffer(ByteBuffer.allocateDirect(initialCapacity)); - } - - /** - * Creates a new direct buffer by wrapping the specified initial buffer. - * - * @param maxCapacity the maximum capacity of the underlying direct buffer - */ - protected UnpooledDirectByteBuf(ByteBufAllocator alloc, ByteBuffer initialBuffer, int maxCapacity) { - super(maxCapacity); - if (alloc == null) { - throw new NullPointerException("alloc"); - } - if (initialBuffer == null) { - throw new NullPointerException("initialBuffer"); - } - if (!initialBuffer.isDirect()) { - throw new IllegalArgumentException("initialBuffer is not a direct buffer."); - } - if (initialBuffer.isReadOnly()) { - throw new IllegalArgumentException("initialBuffer is a read-only buffer."); - } - - int initialCapacity = initialBuffer.remaining(); - if (initialCapacity > maxCapacity) { - throw new IllegalArgumentException(String.format( - "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity)); - } - - this.alloc = alloc; - doNotFree = true; - setByteBuffer(initialBuffer.slice().order(ByteOrder.BIG_ENDIAN)); - writerIndex(initialCapacity); - } - - /** - * Allocate a new direct {@link ByteBuffer} with the given initialCapacity. - */ - protected ByteBuffer allocateDirect(int initialCapacity) { - return ByteBuffer.allocateDirect(initialCapacity); - } - - /** - * Free a direct {@link ByteBuffer} - */ - protected void freeDirect(ByteBuffer buffer) { - } - - private void setByteBuffer(ByteBuffer buffer) { - ByteBuffer oldBuffer = this.buffer; - if (oldBuffer != null) { - if (doNotFree) { - doNotFree = false; - } else { - freeDirect(oldBuffer); - } - } - - this.buffer = buffer; - tmpNioBuf = null; - capacity = buffer.remaining(); - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - public int capacity() { - return capacity; - } - - @Override - public ByteBuf capacity(int newCapacity) { - ensureAccessible(); - if (newCapacity < 0 || newCapacity > maxCapacity()) { - throw new IllegalArgumentException("newCapacity: " + newCapacity); - } - - int readerIndex = readerIndex(); - int writerIndex = writerIndex(); - - int oldCapacity = capacity; - if (newCapacity > oldCapacity) { - ByteBuffer oldBuffer = buffer; - ByteBuffer newBuffer = allocateDirect(newCapacity); - oldBuffer.position(0).limit(oldBuffer.capacity()); - newBuffer.position(0).limit(oldBuffer.capacity()); - newBuffer.put(oldBuffer); - newBuffer.clear(); - setByteBuffer(newBuffer); - } else if (newCapacity < oldCapacity) { - ByteBuffer oldBuffer = buffer; - ByteBuffer newBuffer = allocateDirect(newCapacity); - if (readerIndex < newCapacity) { - if (writerIndex > newCapacity) { - writerIndex(writerIndex = newCapacity); - } - oldBuffer.position(readerIndex).limit(writerIndex); - newBuffer.position(readerIndex).limit(writerIndex); - newBuffer.put(oldBuffer); - newBuffer.clear(); - } else { - setIndex(newCapacity, newCapacity); - } - setByteBuffer(newBuffer); - } - return this; - } - - @Override - public ByteBufAllocator alloc() { - return alloc; - } - - @Override - public ByteOrder order() { - return ByteOrder.BIG_ENDIAN; - } - - @Override - public boolean hasArray() { - return false; - } - - @Override - public byte[] array() { - throw new UnsupportedOperationException("direct buffer"); - } - - @Override - public int arrayOffset() { - throw new UnsupportedOperationException("direct buffer"); - } - - @Override - public byte getByte(int index) { - ensureAccessible(); - return _getByte(index); - } - - @Override - protected byte _getByte(int index) { - return buffer.get(index); - } - - @Override - public short getShort(int index) { - ensureAccessible(); - return _getShort(index); - } - - @Override - protected short _getShort(int index) { - return buffer.getShort(index); - } - - @Override - public int getUnsignedMedium(int index) { - ensureAccessible(); - return _getUnsignedMedium(index); - } - - @Override - protected int _getUnsignedMedium(int index) { - return (getByte(index) & 0xff) << 16 | (getByte(index + 1) & 0xff) << 8 | getByte(index + 2) & 0xff; - } - - @Override - public int getInt(int index) { - ensureAccessible(); - return _getInt(index); - } - - @Override - protected int _getInt(int index) { - return buffer.getInt(index); - } - - @Override - public long getLong(int index) { - ensureAccessible(); - return _getLong(index); - } - - @Override - protected long _getLong(int index) { - return buffer.getLong(index); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - checkDstIndex(index, length, dstIndex, dst.capacity()); - if (dst.hasArray()) { - getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length); - } else if (dst.nioBufferCount() > 0) { - for (ByteBuffer bb: dst.nioBuffers(dstIndex, length)) { - int bbLen = bb.remaining(); - getBytes(index, bb); - index += bbLen; - } - } else { - dst.setBytes(dstIndex, this, index, length); - } - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - getBytes(index, dst, dstIndex, length, false); - return this; - } - - private void getBytes(int index, byte[] dst, int dstIndex, int length, boolean internal) { - checkDstIndex(index, length, dstIndex, dst.length); - - if (dstIndex < 0 || dstIndex > dst.length - length) { - throw new IndexOutOfBoundsException(String.format( - "dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dst.length)); - } - - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = buffer.duplicate(); - } - tmpBuf.clear().position(index).limit(index + length); - tmpBuf.get(dst, dstIndex, length); - } - - @Override - public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { - checkReadableBytes(length); - getBytes(readerIndex, dst, dstIndex, length, true); - readerIndex += length; - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - getBytes(index, dst, false); - return this; - } - - private void getBytes(int index, ByteBuffer dst, boolean internal) { - checkIndex(index); - if (dst == null) { - throw new NullPointerException("dst"); - } - - int bytesToCopy = Math.min(capacity() - index, dst.remaining()); - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = buffer.duplicate(); - } - tmpBuf.clear().position(index).limit(index + bytesToCopy); - dst.put(tmpBuf); - } - - @Override - public ByteBuf readBytes(ByteBuffer dst) { - int length = dst.remaining(); - checkReadableBytes(length); - getBytes(readerIndex, dst, true); - readerIndex += length; - return this; - } - - @Override - public ByteBuf setByte(int index, int value) { - ensureAccessible(); - _setByte(index, value); - return this; - } - - @Override - protected void _setByte(int index, int value) { - buffer.put(index, (byte) value); - } - - @Override - public ByteBuf setShort(int index, int value) { - ensureAccessible(); - _setShort(index, value); - return this; - } - - @Override - protected void _setShort(int index, int value) { - buffer.putShort(index, (short) value); - } - - @Override - public ByteBuf setMedium(int index, int value) { - ensureAccessible(); - _setMedium(index, value); - return this; - } - - @Override - protected void _setMedium(int index, int value) { - setByte(index, (byte) (value >>> 16)); - setByte(index + 1, (byte) (value >>> 8)); - setByte(index + 2, (byte) value); - } - - @Override - public ByteBuf setInt(int index, int value) { - ensureAccessible(); - _setInt(index, value); - return this; - } - - @Override - protected void _setInt(int index, int value) { - buffer.putInt(index, value); - } - - @Override - public ByteBuf setLong(int index, long value) { - ensureAccessible(); - _setLong(index, value); - return this; - } - - @Override - protected void _setLong(int index, long value) { - buffer.putLong(index, value); - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - checkSrcIndex(index, length, srcIndex, src.capacity()); - if (src.nioBufferCount() > 0) { - for (ByteBuffer bb: src.nioBuffers(srcIndex, length)) { - int bbLen = bb.remaining(); - setBytes(index, bb); - index += bbLen; - } - } else { - src.getBytes(srcIndex, this, index, length); - } - return this; - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - checkSrcIndex(index, length, srcIndex, src.length); - ByteBuffer tmpBuf = internalNioBuffer(); - tmpBuf.clear().position(index).limit(index + length); - tmpBuf.put(src, srcIndex, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - ensureAccessible(); - ByteBuffer tmpBuf = internalNioBuffer(); - if (src == tmpBuf) { - src = src.duplicate(); - } - - tmpBuf.clear().position(index).limit(index + src.remaining()); - tmpBuf.put(src); - return this; - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { - getBytes(index, out, length, false); - return this; - } - - private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException { - ensureAccessible(); - if (length == 0) { - return; - } - - if (buffer.hasArray()) { - out.write(buffer.array(), index + buffer.arrayOffset(), length); - } else { - byte[] tmp = new byte[length]; - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = buffer.duplicate(); - } - tmpBuf.clear().position(index); - tmpBuf.get(tmp); - out.write(tmp); - } - } - - @Override - public ByteBuf readBytes(OutputStream out, int length) throws IOException { - checkReadableBytes(length); - getBytes(readerIndex, out, length, true); - readerIndex += length; - return this; - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { - return getBytes(index, out, length, false); - } - - private int getBytes(int index, GatheringByteChannel out, int length, boolean internal) throws IOException { - ensureAccessible(); - if (length == 0) { - return 0; - } - - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = buffer.duplicate(); - } - tmpBuf.clear().position(index).limit(index + length); - return out.write(tmpBuf); - } - - @Override - public int readBytes(GatheringByteChannel out, int length) throws IOException { - checkReadableBytes(length); - int readBytes = getBytes(readerIndex, out, length, true); - readerIndex += readBytes; - return readBytes; - } - - @Override - public int setBytes(int index, InputStream in, int length) throws IOException { - ensureAccessible(); - if (buffer.hasArray()) { - return in.read(buffer.array(), buffer.arrayOffset() + index, length); - } else { - byte[] tmp = new byte[length]; - int readBytes = in.read(tmp); - if (readBytes <= 0) { - return readBytes; - } - ByteBuffer tmpBuf = internalNioBuffer(); - tmpBuf.clear().position(index); - tmpBuf.put(tmp, 0, readBytes); - return readBytes; - } - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { - ensureAccessible(); - ByteBuffer tmpBuf = internalNioBuffer(); - tmpBuf.clear().position(index).limit(index + length); - try { - return in.read(tmpNioBuf); - } catch (ClosedChannelException ignored) { - return -1; - } - } - - @Override - public int nioBufferCount() { - return 1; - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - return new ByteBuffer[] { nioBuffer(index, length) }; - } - - @Override - public ByteBuf copy(int index, int length) { - ensureAccessible(); - ByteBuffer src; - try { - src = (ByteBuffer) buffer.duplicate().clear().position(index).limit(index + length); - } catch (IllegalArgumentException ignored) { - throw new IndexOutOfBoundsException("Too many bytes to read - Need " + (index + length)); - } - - return alloc().directBuffer(length, maxCapacity()).writeBytes(src); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - checkIndex(index, length); - return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); - } - - private ByteBuffer internalNioBuffer() { - ByteBuffer tmpNioBuf = this.tmpNioBuf; - if (tmpNioBuf == null) { - this.tmpNioBuf = tmpNioBuf = buffer.duplicate(); - } - return tmpNioBuf; - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - checkIndex(index, length); - return ((ByteBuffer) buffer.duplicate().position(index).limit(index + length)).slice(); - } - - @Override - protected void deallocate() { - ByteBuffer buffer = this.buffer; - if (buffer == null) { - return; - } - - this.buffer = null; - - if (!doNotFree) { - freeDirect(buffer); - } - } - - @Override - public ByteBuf unwrap() { - return null; - } -} diff --git a/common/src/main/java/common/net/buffer/UnpooledHeapByteBuf.java b/common/src/main/java/common/net/buffer/UnpooledHeapByteBuf.java deleted file mode 100644 index d94c172..0000000 --- a/common/src/main/java/common/net/buffer/UnpooledHeapByteBuf.java +++ /dev/null @@ -1,433 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; - -/** - * Big endian Java heap buffer implementation. - */ -public class UnpooledHeapByteBuf extends AbstractReferenceCountedByteBuf { - - private final ByteBufAllocator alloc; - private byte[] array; - private ByteBuffer tmpNioBuf; - - /** - * Creates a new heap buffer with a newly allocated byte array. - * - * @param initialCapacity the initial capacity of the underlying byte array - * @param maxCapacity the max capacity of the underlying byte array - */ - protected UnpooledHeapByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) { - this(alloc, new byte[initialCapacity], 0, 0, maxCapacity); - } - - /** - * Creates a new heap buffer with an existing byte array. - * - * @param initialArray the initial underlying byte array - * @param maxCapacity the max capacity of the underlying byte array - */ - protected UnpooledHeapByteBuf(ByteBufAllocator alloc, byte[] initialArray, int maxCapacity) { - this(alloc, initialArray, 0, initialArray.length, maxCapacity); - } - - private UnpooledHeapByteBuf( - ByteBufAllocator alloc, byte[] initialArray, int readerIndex, int writerIndex, int maxCapacity) { - - super(maxCapacity); - - if (alloc == null) { - throw new NullPointerException("alloc"); - } - if (initialArray == null) { - throw new NullPointerException("initialArray"); - } - if (initialArray.length > maxCapacity) { - throw new IllegalArgumentException(String.format( - "initialCapacity(%d) > maxCapacity(%d)", initialArray.length, maxCapacity)); - } - - this.alloc = alloc; - setArray(initialArray); - setIndex(readerIndex, writerIndex); - } - - private void setArray(byte[] initialArray) { - array = initialArray; - tmpNioBuf = null; - } - - @Override - public ByteBufAllocator alloc() { - return alloc; - } - - @Override - public ByteOrder order() { - return ByteOrder.BIG_ENDIAN; - } - - @Override - public boolean isDirect() { - return false; - } - - @Override - public int capacity() { - ensureAccessible(); - return array.length; - } - - @Override - public ByteBuf capacity(int newCapacity) { - ensureAccessible(); - if (newCapacity < 0 || newCapacity > maxCapacity()) { - throw new IllegalArgumentException("newCapacity: " + newCapacity); - } - - int oldCapacity = array.length; - if (newCapacity > oldCapacity) { - byte[] newArray = new byte[newCapacity]; - System.arraycopy(array, 0, newArray, 0, array.length); - setArray(newArray); - } else if (newCapacity < oldCapacity) { - byte[] newArray = new byte[newCapacity]; - int readerIndex = readerIndex(); - if (readerIndex < newCapacity) { - int writerIndex = writerIndex(); - if (writerIndex > newCapacity) { - writerIndex(writerIndex = newCapacity); - } - System.arraycopy(array, readerIndex, newArray, readerIndex, writerIndex - readerIndex); - } else { - setIndex(newCapacity, newCapacity); - } - setArray(newArray); - } - return this; - } - - @Override - public boolean hasArray() { - return true; - } - - @Override - public byte[] array() { - ensureAccessible(); - return array; - } - - @Override - public int arrayOffset() { - return 0; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - checkDstIndex(index, length, dstIndex, dst.capacity()); - if (dst.hasArray()) { - getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length); - } else { - dst.setBytes(dstIndex, array, index, length); - } - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - checkDstIndex(index, length, dstIndex, dst.length); - System.arraycopy(array, index, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - ensureAccessible(); - dst.put(array, index, Math.min(capacity() - index, dst.remaining())); - return this; - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { - ensureAccessible(); - out.write(array, index, length); - return this; - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { - ensureAccessible(); - return getBytes(index, out, length, false); - } - - private int getBytes(int index, GatheringByteChannel out, int length, boolean internal) throws IOException { - ensureAccessible(); - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = ByteBuffer.wrap(array); - } - return out.write((ByteBuffer) tmpBuf.clear().position(index).limit(index + length)); - } - - @Override - public int readBytes(GatheringByteChannel out, int length) throws IOException { - checkReadableBytes(length); - int readBytes = getBytes(readerIndex, out, length, true); - readerIndex += readBytes; - return readBytes; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - checkSrcIndex(index, length, srcIndex, src.capacity()); - if (src.hasArray()) { - setBytes(index, src.array(), src.arrayOffset() + srcIndex, length); - } else { - src.getBytes(srcIndex, array, index, length); - } - return this; - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - checkSrcIndex(index, length, srcIndex, src.length); - System.arraycopy(src, srcIndex, array, index, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - ensureAccessible(); - src.get(array, index, src.remaining()); - return this; - } - - @Override - public int setBytes(int index, InputStream in, int length) throws IOException { - ensureAccessible(); - return in.read(array, index, length); - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { - ensureAccessible(); - try { - return in.read((ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length)); - } catch (ClosedChannelException ignored) { - return -1; - } - } - - @Override - public int nioBufferCount() { - return 1; - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - ensureAccessible(); - return ByteBuffer.wrap(array, index, length).slice(); - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - return new ByteBuffer[] { nioBuffer(index, length) }; - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - checkIndex(index, length); - return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); - } - - @Override - public byte getByte(int index) { - ensureAccessible(); - return _getByte(index); - } - - @Override - protected byte _getByte(int index) { - return array[index]; - } - - @Override - public short getShort(int index) { - ensureAccessible(); - return _getShort(index); - } - - @Override - protected short _getShort(int index) { - return (short) (array[index] << 8 | array[index + 1] & 0xFF); - } - - @Override - public int getUnsignedMedium(int index) { - ensureAccessible(); - return _getUnsignedMedium(index); - } - - @Override - protected int _getUnsignedMedium(int index) { - return (array[index] & 0xff) << 16 | - (array[index + 1] & 0xff) << 8 | - array[index + 2] & 0xff; - } - - @Override - public int getInt(int index) { - ensureAccessible(); - return _getInt(index); - } - - @Override - protected int _getInt(int index) { - return (array[index] & 0xff) << 24 | - (array[index + 1] & 0xff) << 16 | - (array[index + 2] & 0xff) << 8 | - array[index + 3] & 0xff; - } - - @Override - public long getLong(int index) { - ensureAccessible(); - return _getLong(index); - } - - @Override - protected long _getLong(int index) { - return ((long) array[index] & 0xff) << 56 | - ((long) array[index + 1] & 0xff) << 48 | - ((long) array[index + 2] & 0xff) << 40 | - ((long) array[index + 3] & 0xff) << 32 | - ((long) array[index + 4] & 0xff) << 24 | - ((long) array[index + 5] & 0xff) << 16 | - ((long) array[index + 6] & 0xff) << 8 | - (long) array[index + 7] & 0xff; - } - - @Override - public ByteBuf setByte(int index, int value) { - ensureAccessible(); - _setByte(index, value); - return this; - } - - @Override - protected void _setByte(int index, int value) { - array[index] = (byte) value; - } - - @Override - public ByteBuf setShort(int index, int value) { - ensureAccessible(); - _setShort(index, value); - return this; - } - - @Override - protected void _setShort(int index, int value) { - array[index] = (byte) (value >>> 8); - array[index + 1] = (byte) value; - } - - @Override - public ByteBuf setMedium(int index, int value) { - ensureAccessible(); - _setMedium(index, value); - return this; - } - - @Override - protected void _setMedium(int index, int value) { - array[index] = (byte) (value >>> 16); - array[index + 1] = (byte) (value >>> 8); - array[index + 2] = (byte) value; - } - - @Override - public ByteBuf setInt(int index, int value) { - ensureAccessible(); - _setInt(index, value); - return this; - } - - @Override - protected void _setInt(int index, int value) { - array[index] = (byte) (value >>> 24); - array[index + 1] = (byte) (value >>> 16); - array[index + 2] = (byte) (value >>> 8); - array[index + 3] = (byte) value; - } - - @Override - public ByteBuf setLong(int index, long value) { - ensureAccessible(); - _setLong(index, value); - return this; - } - - @Override - protected void _setLong(int index, long value) { - array[index] = (byte) (value >>> 56); - array[index + 1] = (byte) (value >>> 48); - array[index + 2] = (byte) (value >>> 40); - array[index + 3] = (byte) (value >>> 32); - array[index + 4] = (byte) (value >>> 24); - array[index + 5] = (byte) (value >>> 16); - array[index + 6] = (byte) (value >>> 8); - array[index + 7] = (byte) value; - } - - @Override - public ByteBuf copy(int index, int length) { - checkIndex(index, length); - byte[] copiedArray = new byte[length]; - System.arraycopy(array, index, copiedArray, 0, length); - return new UnpooledHeapByteBuf(alloc(), copiedArray, maxCapacity()); - } - - private ByteBuffer internalNioBuffer() { - ByteBuffer tmpNioBuf = this.tmpNioBuf; - if (tmpNioBuf == null) { - this.tmpNioBuf = tmpNioBuf = ByteBuffer.wrap(array); - } - return tmpNioBuf; - } - - @Override - protected void deallocate() { - array = null; - } - - @Override - public ByteBuf unwrap() { - return null; - } -} diff --git a/common/src/main/java/common/net/buffer/UnreleasableByteBuf.java b/common/src/main/java/common/net/buffer/UnreleasableByteBuf.java deleted file mode 100644 index 3a677ba..0000000 --- a/common/src/main/java/common/net/buffer/UnreleasableByteBuf.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.buffer; - -import java.nio.ByteOrder; - -/** - * A {@link ByteBuf} implementation that wraps another buffer to prevent a user from increasing or decreasing the - * wrapped buffer's reference count. - */ -final class UnreleasableByteBuf extends WrappedByteBuf { - - private SwappedByteBuf swappedBuf; - - UnreleasableByteBuf(ByteBuf buf) { - super(buf); - } - - @Override - public ByteBuf order(ByteOrder endianness) { - if (endianness == null) { - throw new NullPointerException("endianness"); - } - if (endianness == order()) { - return this; - } - - SwappedByteBuf swappedBuf = this.swappedBuf; - if (swappedBuf == null) { - this.swappedBuf = swappedBuf = new SwappedByteBuf(this); - } - return swappedBuf; - } - - @Override - public ByteBuf readSlice(int length) { - return new UnreleasableByteBuf(buf.readSlice(length)); - } - - @Override - public ByteBuf slice() { - return new UnreleasableByteBuf(buf.slice()); - } - - @Override - public ByteBuf slice(int index, int length) { - return new UnreleasableByteBuf(buf.slice(index, length)); - } - - @Override - public ByteBuf duplicate() { - return new UnreleasableByteBuf(buf.duplicate()); - } - - @Override - public ByteBuf retain(int increment) { - return this; - } - - @Override - public ByteBuf retain() { - return this; - } - - @Override - public boolean release() { - return false; - } - - @Override - public boolean release(int decrement) { - return false; - } -} diff --git a/common/src/main/java/common/net/buffer/WrappedByteBuf.java b/common/src/main/java/common/net/buffer/WrappedByteBuf.java deleted file mode 100644 index 8cbec40..0000000 --- a/common/src/main/java/common/net/buffer/WrappedByteBuf.java +++ /dev/null @@ -1,817 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.buffer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ScatteringByteChannel; -import java.nio.charset.Charset; - -import common.net.util.internal.StringUtil; - -class WrappedByteBuf extends ByteBuf { - - protected final ByteBuf buf; - - protected WrappedByteBuf(ByteBuf buf) { - if (buf == null) { - throw new NullPointerException("buf"); - } - this.buf = buf; - } - - @Override - public int capacity() { - return buf.capacity(); - } - - @Override - public ByteBuf capacity(int newCapacity) { - buf.capacity(newCapacity); - return this; - } - - @Override - public int maxCapacity() { - return buf.maxCapacity(); - } - - @Override - public ByteBufAllocator alloc() { - return buf.alloc(); - } - - @Override - public ByteOrder order() { - return buf.order(); - } - - @Override - public ByteBuf order(ByteOrder endianness) { - return buf.order(endianness); - } - - @Override - public ByteBuf unwrap() { - return buf; - } - - @Override - public boolean isDirect() { - return buf.isDirect(); - } - - @Override - public int readerIndex() { - return buf.readerIndex(); - } - - @Override - public ByteBuf readerIndex(int readerIndex) { - buf.readerIndex(readerIndex); - return this; - } - - @Override - public int writerIndex() { - return buf.writerIndex(); - } - - @Override - public ByteBuf writerIndex(int writerIndex) { - buf.writerIndex(writerIndex); - return this; - } - - @Override - public ByteBuf setIndex(int readerIndex, int writerIndex) { - buf.setIndex(readerIndex, writerIndex); - return this; - } - - @Override - public int readableBytes() { - return buf.readableBytes(); - } - - @Override - public int writableBytes() { - return buf.writableBytes(); - } - - @Override - public int maxWritableBytes() { - return buf.maxWritableBytes(); - } - - @Override - public boolean isReadable() { - return buf.isReadable(); - } - - @Override - public boolean isWritable() { - return buf.isWritable(); - } - - @Override - public ByteBuf clear() { - buf.clear(); - return this; - } - - @Override - public ByteBuf markReaderIndex() { - buf.markReaderIndex(); - return this; - } - - @Override - public ByteBuf resetReaderIndex() { - buf.resetReaderIndex(); - return this; - } - - @Override - public ByteBuf markWriterIndex() { - buf.markWriterIndex(); - return this; - } - - @Override - public ByteBuf resetWriterIndex() { - buf.resetWriterIndex(); - return this; - } - - @Override - public ByteBuf discardReadBytes() { - buf.discardReadBytes(); - return this; - } - - @Override - public ByteBuf discardSomeReadBytes() { - buf.discardSomeReadBytes(); - return this; - } - - @Override - public ByteBuf ensureWritable(int minWritableBytes) { - buf.ensureWritable(minWritableBytes); - return this; - } - - @Override - public int ensureWritable(int minWritableBytes, boolean force) { - return buf.ensureWritable(minWritableBytes, force); - } - - @Override - public boolean getBoolean(int index) { - return buf.getBoolean(index); - } - - @Override - public byte getByte(int index) { - return buf.getByte(index); - } - - @Override - public short getUnsignedByte(int index) { - return buf.getUnsignedByte(index); - } - - @Override - public short getShort(int index) { - return buf.getShort(index); - } - - @Override - public int getUnsignedShort(int index) { - return buf.getUnsignedShort(index); - } - - @Override - public int getMedium(int index) { - return buf.getMedium(index); - } - - @Override - public int getUnsignedMedium(int index) { - return buf.getUnsignedMedium(index); - } - - @Override - public int getInt(int index) { - return buf.getInt(index); - } - - @Override - public long getUnsignedInt(int index) { - return buf.getUnsignedInt(index); - } - - @Override - public long getLong(int index) { - return buf.getLong(index); - } - - @Override - public char getChar(int index) { - return buf.getChar(index); - } - - @Override - public float getFloat(int index) { - return buf.getFloat(index); - } - - @Override - public double getDouble(int index) { - return buf.getDouble(index); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst) { - buf.getBytes(index, dst); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int length) { - buf.getBytes(index, dst, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - buf.getBytes(index, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst) { - buf.getBytes(index, dst); - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - buf.getBytes(index, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - buf.getBytes(index, dst); - return this; - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { - buf.getBytes(index, out, length); - return this; - } - - @Override - public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { - return buf.getBytes(index, out, length); - } - - @Override - public ByteBuf setBoolean(int index, boolean value) { - buf.setBoolean(index, value); - return this; - } - - @Override - public ByteBuf setByte(int index, int value) { - buf.setByte(index, value); - return this; - } - - @Override - public ByteBuf setShort(int index, int value) { - buf.setShort(index, value); - return this; - } - - @Override - public ByteBuf setMedium(int index, int value) { - buf.setMedium(index, value); - return this; - } - - @Override - public ByteBuf setInt(int index, int value) { - buf.setInt(index, value); - return this; - } - - @Override - public ByteBuf setLong(int index, long value) { - buf.setLong(index, value); - return this; - } - - @Override - public ByteBuf setChar(int index, int value) { - buf.setChar(index, value); - return this; - } - - @Override - public ByteBuf setFloat(int index, float value) { - buf.setFloat(index, value); - return this; - } - - @Override - public ByteBuf setDouble(int index, double value) { - buf.setDouble(index, value); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src) { - buf.setBytes(index, src); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int length) { - buf.setBytes(index, src, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - buf.setBytes(index, src, srcIndex, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, byte[] src) { - buf.setBytes(index, src); - return this; - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - buf.setBytes(index, src, srcIndex, length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuffer src) { - buf.setBytes(index, src); - return this; - } - - @Override - public int setBytes(int index, InputStream in, int length) throws IOException { - return buf.setBytes(index, in, length); - } - - @Override - public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { - return buf.setBytes(index, in, length); - } - - @Override - public ByteBuf setZero(int index, int length) { - buf.setZero(index, length); - return this; - } - - @Override - public boolean readBoolean() { - return buf.readBoolean(); - } - - @Override - public byte readByte() { - return buf.readByte(); - } - - @Override - public short readUnsignedByte() { - return buf.readUnsignedByte(); - } - - @Override - public short readShort() { - return buf.readShort(); - } - - @Override - public int readUnsignedShort() { - return buf.readUnsignedShort(); - } - - @Override - public int readMedium() { - return buf.readMedium(); - } - - @Override - public int readUnsignedMedium() { - return buf.readUnsignedMedium(); - } - - @Override - public int readInt() { - return buf.readInt(); - } - - @Override - public long readUnsignedInt() { - return buf.readUnsignedInt(); - } - - @Override - public long readLong() { - return buf.readLong(); - } - - @Override - public char readChar() { - return buf.readChar(); - } - - @Override - public float readFloat() { - return buf.readFloat(); - } - - @Override - public double readDouble() { - return buf.readDouble(); - } - - @Override - public ByteBuf readBytes(int length) { - return buf.readBytes(length); - } - - @Override - public ByteBuf readSlice(int length) { - return buf.readSlice(length); - } - - @Override - public ByteBuf readBytes(ByteBuf dst) { - buf.readBytes(dst); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int length) { - buf.readBytes(dst, length); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { - buf.readBytes(dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf readBytes(byte[] dst) { - buf.readBytes(dst); - return this; - } - - @Override - public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { - buf.readBytes(dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuffer dst) { - buf.readBytes(dst); - return this; - } - - @Override - public ByteBuf readBytes(OutputStream out, int length) throws IOException { - buf.readBytes(out, length); - return this; - } - - @Override - public int readBytes(GatheringByteChannel out, int length) throws IOException { - return buf.readBytes(out, length); - } - - @Override - public ByteBuf skipBytes(int length) { - buf.skipBytes(length); - return this; - } - - @Override - public ByteBuf writeBoolean(boolean value) { - buf.writeBoolean(value); - return this; - } - - @Override - public ByteBuf writeByte(int value) { - buf.writeByte(value); - return this; - } - - @Override - public ByteBuf writeShort(int value) { - buf.writeShort(value); - return this; - } - - @Override - public ByteBuf writeMedium(int value) { - buf.writeMedium(value); - return this; - } - - @Override - public ByteBuf writeInt(int value) { - buf.writeInt(value); - return this; - } - - @Override - public ByteBuf writeLong(long value) { - buf.writeLong(value); - return this; - } - - @Override - public ByteBuf writeChar(int value) { - buf.writeChar(value); - return this; - } - - @Override - public ByteBuf writeFloat(float value) { - buf.writeFloat(value); - return this; - } - - @Override - public ByteBuf writeDouble(double value) { - buf.writeDouble(value); - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuf src) { - buf.writeBytes(src); - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuf src, int length) { - buf.writeBytes(src, length); - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { - buf.writeBytes(src, srcIndex, length); - return this; - } - - @Override - public ByteBuf writeBytes(byte[] src) { - buf.writeBytes(src); - return this; - } - - @Override - public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { - buf.writeBytes(src, srcIndex, length); - return this; - } - - @Override - public ByteBuf writeBytes(ByteBuffer src) { - buf.writeBytes(src); - return this; - } - - @Override - public int writeBytes(InputStream in, int length) throws IOException { - return buf.writeBytes(in, length); - } - - @Override - public int writeBytes(ScatteringByteChannel in, int length) throws IOException { - return buf.writeBytes(in, length); - } - - @Override - public ByteBuf writeZero(int length) { - buf.writeZero(length); - return this; - } - - @Override - public int indexOf(int fromIndex, int toIndex, byte value) { - return buf.indexOf(fromIndex, toIndex, value); - } - - @Override - public int bytesBefore(byte value) { - return buf.bytesBefore(value); - } - - @Override - public int bytesBefore(int length, byte value) { - return buf.bytesBefore(length, value); - } - - @Override - public int bytesBefore(int index, int length, byte value) { - return buf.bytesBefore(index, length, value); - } - - @Override - public int forEachByte(ByteBufProcessor processor) { - return buf.forEachByte(processor); - } - - @Override - public int forEachByte(int index, int length, ByteBufProcessor processor) { - return buf.forEachByte(index, length, processor); - } - - @Override - public int forEachByteDesc(ByteBufProcessor processor) { - return buf.forEachByteDesc(processor); - } - - @Override - public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { - return buf.forEachByteDesc(index, length, processor); - } - - @Override - public ByteBuf copy() { - return buf.copy(); - } - - @Override - public ByteBuf copy(int index, int length) { - return buf.copy(index, length); - } - - @Override - public ByteBuf slice() { - return buf.slice(); - } - - @Override - public ByteBuf slice(int index, int length) { - return buf.slice(index, length); - } - - @Override - public ByteBuf duplicate() { - return buf.duplicate(); - } - - @Override - public int nioBufferCount() { - return buf.nioBufferCount(); - } - - @Override - public ByteBuffer nioBuffer() { - return buf.nioBuffer(); - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - return buf.nioBuffer(index, length); - } - - @Override - public ByteBuffer[] nioBuffers() { - return buf.nioBuffers(); - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - return buf.nioBuffers(index, length); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - return buf.internalNioBuffer(index, length); - } - - @Override - public boolean hasArray() { - return buf.hasArray(); - } - - @Override - public byte[] array() { - return buf.array(); - } - - @Override - public int arrayOffset() { - return buf.arrayOffset(); - } - - @Override - public String toString(Charset charset) { - return buf.toString(charset); - } - - @Override - public String toString(int index, int length, Charset charset) { - return buf.toString(index, length, charset); - } - - @Override - public int hashCode() { - return buf.hashCode(); - } - - @Override - - public boolean equals(Object obj) { - return buf.equals(obj); - } - - @Override - public int compareTo(ByteBuf buffer) { - return buf.compareTo(buffer); - } - - @Override - public String toString() { - return StringUtil.simpleClassName(this) + '(' + buf.toString() + ')'; - } - - @Override - public ByteBuf retain(int increment) { - buf.retain(increment); - return this; - } - - @Override - public ByteBuf retain() { - buf.retain(); - return this; - } - - @Override - public boolean isReadable(int size) { - return buf.isReadable(size); - } - - @Override - public boolean isWritable(int size) { - return buf.isWritable(size); - } - - @Override - public int refCnt() { - return buf.refCnt(); - } - - @Override - public boolean release() { - return buf.release(); - } - - @Override - public boolean release(int decrement) { - return buf.release(decrement); - } -} diff --git a/common/src/main/java/common/net/channel/AbstractChannel.java b/common/src/main/java/common/net/channel/AbstractChannel.java deleted file mode 100644 index 2330ef8..0000000 --- a/common/src/main/java/common/net/channel/AbstractChannel.java +++ /dev/null @@ -1,858 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.io.IOException; -import java.net.SocketAddress; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.NotYetConnectedException; -import java.util.concurrent.RejectedExecutionException; - -import common.net.buffer.ByteBufAllocator; -import common.net.util.DefaultAttributeMap; -import common.net.util.ReferenceCountUtil; -import common.net.util.internal.EmptyArrays; -import common.net.util.internal.OneTimeTask; -import common.net.util.internal.ThreadLocalRandom; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * A skeletal {@link Channel} implementation. - */ -public abstract class AbstractChannel extends DefaultAttributeMap implements Channel { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractChannel.class); - - static final ClosedChannelException CLOSED_CHANNEL_EXCEPTION = new ClosedChannelException(); - static final NotYetConnectedException NOT_YET_CONNECTED_EXCEPTION = new NotYetConnectedException(); - - static { - CLOSED_CHANNEL_EXCEPTION.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); - NOT_YET_CONNECTED_EXCEPTION.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); - } - - private MessageSizeEstimator.Handle estimatorHandle; - - private final Channel parent; - private final long hashCode = ThreadLocalRandom.current().nextLong(); - private final Unsafe unsafe; - private final DefaultChannelPipeline pipeline; - private final ChannelFuture succeededFuture = new SucceededChannelFuture(this, null); - private final VoidChannelPromise voidPromise = new VoidChannelPromise(this, true); - private final VoidChannelPromise unsafeVoidPromise = new VoidChannelPromise(this, false); - private final CloseFuture closeFuture = new CloseFuture(this); - - private volatile SocketAddress localAddress; - private volatile SocketAddress remoteAddress; - private volatile EventLoop eventLoop; - private volatile boolean registered; - - /** Cache for the string representation of this channel */ - private boolean strValActive; - private String strVal; - - /** - * Creates a new instance. - * - * @param parent - * the parent of this channel. {@code null} if there's no parent. - */ - protected AbstractChannel(Channel parent) { - this.parent = parent; - unsafe = newUnsafe(); - pipeline = new DefaultChannelPipeline(this); - } - - @Override - public boolean isWritable() { - ChannelOutboundBuffer buf = unsafe.outboundBuffer(); - return buf != null && buf.isWritable(); - } - - @Override - public Channel parent() { - return parent; - } - - @Override - public ChannelPipeline pipeline() { - return pipeline; - } - - @Override - public ByteBufAllocator alloc() { - return config().getAllocator(); - } - - @Override - public EventLoop eventLoop() { - EventLoop eventLoop = this.eventLoop; - if (eventLoop == null) { - throw new IllegalStateException("channel not registered to an event loop"); - } - return eventLoop; - } - - @Override - public SocketAddress localAddress() { - SocketAddress localAddress = this.localAddress; - if (localAddress == null) { - try { - this.localAddress = localAddress = unsafe().localAddress(); - } catch (Throwable t) { - // Sometimes fails on a closed socket in Windows. - return null; - } - } - return localAddress; - } - - protected void invalidateLocalAddress() { - localAddress = null; - } - - @Override - public SocketAddress remoteAddress() { - SocketAddress remoteAddress = this.remoteAddress; - if (remoteAddress == null) { - try { - this.remoteAddress = remoteAddress = unsafe().remoteAddress(); - } catch (Throwable t) { - // Sometimes fails on a closed socket in Windows. - return null; - } - } - return remoteAddress; - } - - /** - * Reset the stored remoteAddress - */ - protected void invalidateRemoteAddress() { - remoteAddress = null; - } - - @Override - public boolean isRegistered() { - return registered; - } - - @Override - public ChannelFuture bind(SocketAddress localAddress) { - return pipeline.bind(localAddress); - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress) { - return pipeline.connect(remoteAddress); - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { - return pipeline.connect(remoteAddress, localAddress); - } - - @Override - public ChannelFuture disconnect() { - return pipeline.disconnect(); - } - - @Override - public ChannelFuture close() { - return pipeline.close(); - } - - @Override - public ChannelFuture deregister() { - return pipeline.deregister(); - } - - @Override - public Channel flush() { - pipeline.flush(); - return this; - } - - @Override - public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { - return pipeline.bind(localAddress, promise); - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { - return pipeline.connect(remoteAddress, promise); - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { - return pipeline.connect(remoteAddress, localAddress, promise); - } - - @Override - public ChannelFuture disconnect(ChannelPromise promise) { - return pipeline.disconnect(promise); - } - - @Override - public ChannelFuture close(ChannelPromise promise) { - return pipeline.close(promise); - } - - @Override - public ChannelFuture deregister(ChannelPromise promise) { - return pipeline.deregister(promise); - } - - @Override - public Channel read() { - pipeline.read(); - return this; - } - - @Override - public ChannelFuture write(Object msg) { - return pipeline.write(msg); - } - - @Override - public ChannelFuture write(Object msg, ChannelPromise promise) { - return pipeline.write(msg, promise); - } - - @Override - public ChannelFuture writeAndFlush(Object msg) { - return pipeline.writeAndFlush(msg); - } - - @Override - public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { - return pipeline.writeAndFlush(msg, promise); - } - - @Override - public ChannelPromise newPromise() { - return new DefaultChannelPromise(this); - } - -// @Override -// public ChannelProgressivePromise newProgressivePromise() { -// return new DefaultChannelProgressivePromise(this); -// } - - @Override - public ChannelFuture newSucceededFuture() { - return succeededFuture; - } - - @Override - public ChannelFuture newFailedFuture(Throwable cause) { - return new FailedChannelFuture(this, null, cause); - } - - @Override - public ChannelFuture closeFuture() { - return closeFuture; - } - - @Override - public Unsafe unsafe() { - return unsafe; - } - - /** - * Create a new {@link AbstractUnsafe} instance which will be used for the life-time of the {@link Channel} - */ - protected abstract AbstractUnsafe newUnsafe(); - - /** - * Returns the ID of this channel. - */ - @Override - public final int hashCode() { - return (int) hashCode; - } - - /** - * Returns {@code true} if and only if the specified object is identical - * with this channel (i.e: {@code this == o}). - */ - @Override - public final boolean equals(Object o) { - return this == o; - } - - @Override - public final int compareTo(Channel o) { - if (this == o) { - return 0; - } - - long ret = hashCode - o.hashCode(); - if (ret > 0) { - return 1; - } - if (ret < 0) { - return -1; - } - - ret = System.identityHashCode(this) - System.identityHashCode(o); - if (ret != 0) { - return (int) ret; - } - - // Jackpot! - different objects with same hashes - throw new Error(); - } - - /** - * Returns the {@link String} representation of this channel. The returned - * string contains the {@linkplain #hashCode()} ID}, {@linkplain #localAddress() local address}, - * and {@linkplain #remoteAddress() remote address} of this channel for - * easier identification. - */ - @Override - public String toString() { - boolean active = isActive(); - if (strValActive == active && strVal != null) { - return strVal; - } - - SocketAddress remoteAddr = remoteAddress(); - SocketAddress localAddr = localAddress(); - if (remoteAddr != null) { - SocketAddress srcAddr; - SocketAddress dstAddr; - if (parent == null) { - srcAddr = localAddr; - dstAddr = remoteAddr; - } else { - srcAddr = remoteAddr; - dstAddr = localAddr; - } - strVal = String.format("[id: 0x%08x, %s %s %s]", (int) hashCode, srcAddr, active? "=>" : ":>", dstAddr); - } else if (localAddr != null) { - strVal = String.format("[id: 0x%08x, %s]", (int) hashCode, localAddr); - } else { - strVal = String.format("[id: 0x%08x]", (int) hashCode); - } - - strValActive = active; - return strVal; - } - - @Override - public final ChannelPromise voidPromise() { - return voidPromise; - } - - final MessageSizeEstimator.Handle estimatorHandle() { - if (estimatorHandle == null) { - estimatorHandle = config().getMessageSizeEstimator().newHandle(); - } - return estimatorHandle; - } - - /** - * {@link Unsafe} implementation which sub-classes must extend and use. - */ - protected abstract class AbstractUnsafe implements Unsafe { - - private ChannelOutboundBuffer outboundBuffer = new ChannelOutboundBuffer(AbstractChannel.this); - private boolean inFlush0; - - @Override - public final ChannelOutboundBuffer outboundBuffer() { - return outboundBuffer; - } - - @Override - public final SocketAddress localAddress() { - return localAddress0(); - } - - @Override - public final SocketAddress remoteAddress() { - return remoteAddress0(); - } - - @Override - public final void register(EventLoop eventLoop, final ChannelPromise promise) { - if (eventLoop == null) { - throw new NullPointerException("eventLoop"); - } - if (isRegistered()) { - promise.setFailure(new IllegalStateException("registered to an event loop already")); - return; - } - if (!isCompatible(eventLoop)) { - promise.setFailure( - new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName())); - return; - } - - AbstractChannel.this.eventLoop = eventLoop; - - if (eventLoop.inEventLoop()) { - register0(promise); - } else { - try { - eventLoop.execute(new OneTimeTask() { - @Override - public void run() { - register0(promise); - } - }); - } catch (Throwable t) { - logger.warn( - "Force-closing a channel whose registration task was not accepted by an event loop: {}", - AbstractChannel.this, t); - closeForcibly(); - closeFuture.setClosed(); - safeSetFailure(promise, t); - } - } - } - - private void register0(ChannelPromise promise) { - try { - // check if the channel is still open as it could be closed in the mean time when the register - // call was outside of the eventLoop - if (!promise.setUncancellable() || !ensureOpen(promise)) { - return; - } - doRegister(); - registered = true; - safeSetSuccess(promise); - pipeline.fireChannelRegistered(); - if (isActive()) { - pipeline.fireChannelActive(); - } - } catch (Throwable t) { - // Close the channel directly to avoid FD leak. - closeForcibly(); - closeFuture.setClosed(); - safeSetFailure(promise, t); - } - } - - @Override - public final void bind(final SocketAddress localAddress, final ChannelPromise promise) { - if (!promise.setUncancellable() || !ensureOpen(promise)) { - return; - } - - boolean wasActive = isActive(); - try { - doBind(localAddress); - } catch (Throwable t) { - safeSetFailure(promise, t); - closeIfClosed(); - return; - } - - if (!wasActive && isActive()) { - invokeLater(new OneTimeTask() { - @Override - public void run() { - pipeline.fireChannelActive(); - } - }); - } - - safeSetSuccess(promise); - } - - @Override - public final void disconnect(final ChannelPromise promise) { - if (!promise.setUncancellable()) { - return; - } - - boolean wasActive = isActive(); - try { - doDisconnect(); - } catch (Throwable t) { - safeSetFailure(promise, t); - closeIfClosed(); - return; - } - - if (wasActive && !isActive()) { - invokeLater(new OneTimeTask() { - @Override - public void run() { - pipeline.fireChannelInactive(); - } - }); - } - - safeSetSuccess(promise); - closeIfClosed(); // doDisconnect() might have closed the channel - } - - @Override - public final void close(final ChannelPromise promise) { - if (!promise.setUncancellable()) { - return; - } - - if (inFlush0) { - invokeLater(new OneTimeTask() { - @Override - public void run() { - close(promise); - } - }); - return; - } - - if (closeFuture.isDone()) { - // Closed already. - safeSetSuccess(promise); - return; - } - - boolean wasActive = isActive(); - ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; - this.outboundBuffer = null; // Disallow adding any messages and flushes to outboundBuffer. - - try { - doClose(); - closeFuture.setClosed(); - safeSetSuccess(promise); - } catch (Throwable t) { - closeFuture.setClosed(); - safeSetFailure(promise, t); - } - - // Fail all the queued messages - try { - outboundBuffer.failFlushed(CLOSED_CHANNEL_EXCEPTION); - outboundBuffer.close(CLOSED_CHANNEL_EXCEPTION); - } finally { - - if (wasActive && !isActive()) { - invokeLater(new OneTimeTask() { - @Override - public void run() { - pipeline.fireChannelInactive(); - } - }); - } - - deregister(voidPromise()); - } - } - - @Override - public final void closeForcibly() { - try { - doClose(); - } catch (Exception e) { - logger.warn("Failed to close a channel.", e); - } - } - - @Override - public final void deregister(final ChannelPromise promise) { - if (!promise.setUncancellable()) { - return; - } - - if (!registered) { - safeSetSuccess(promise); - return; - } - - try { - doDeregister(); - } catch (Throwable t) { - logger.warn("Unexpected exception occurred while deregistering a channel.", t); - } finally { - if (registered) { - registered = false; - invokeLater(new OneTimeTask() { - @Override - public void run() { - pipeline.fireChannelUnregistered(); - } - }); - safeSetSuccess(promise); - } else { - // Some transports like local and AIO does not allow the deregistration of - // an open channel. Their doDeregister() calls close(). Consequently, - // close() calls deregister() again - no need to fire channelUnregistered. - safeSetSuccess(promise); - } - } - } - - @Override - public final void beginRead() { - if (!isActive()) { - return; - } - - try { - doBeginRead(); - } catch (final Exception e) { - invokeLater(new OneTimeTask() { - @Override - public void run() { - pipeline.fireExceptionCaught(e); - } - }); - close(voidPromise()); - } - } - - @Override - public final void write(Object msg, ChannelPromise promise) { - ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; - if (outboundBuffer == null) { - // If the outboundBuffer is null we know the channel was closed and so - // need to fail the future right away. If it is not null the handling of the rest - // will be done in flush0() - // See https://github.com/netty/netty/issues/2362 - safeSetFailure(promise, CLOSED_CHANNEL_EXCEPTION); - // release message now to prevent resource-leak - ReferenceCountUtil.release(msg); - return; - } - - int size; - try { - msg = filterOutboundMessage(msg); - size = estimatorHandle().size(msg); - if (size < 0) { - size = 0; - } - } catch (Throwable t) { - safeSetFailure(promise, t); - ReferenceCountUtil.release(msg); - return; - } - - outboundBuffer.addMessage(msg, size, promise); - } - - @Override - public final void flush() { - ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; - if (outboundBuffer == null) { - return; - } - - outboundBuffer.addFlush(); - flush0(); - } - - protected void flush0() { - if (inFlush0) { - // Avoid re-entrance - return; - } - - final ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; - if (outboundBuffer == null || outboundBuffer.isEmpty()) { - return; - } - - inFlush0 = true; - - // Mark all pending write requests as failure if the channel is inactive. - if (!isActive()) { - try { - if (isOpen()) { - outboundBuffer.failFlushed(NOT_YET_CONNECTED_EXCEPTION); - } else { - outboundBuffer.failFlushed(CLOSED_CHANNEL_EXCEPTION); - } - } finally { - inFlush0 = false; - } - return; - } - - try { - doWrite(outboundBuffer); - } catch (Throwable t) { - outboundBuffer.failFlushed(t); - if (t instanceof IOException) { - close(voidPromise()); - } - } finally { - inFlush0 = false; - } - } - - @Override - public final ChannelPromise voidPromise() { - return unsafeVoidPromise; - } - - protected final boolean ensureOpen(ChannelPromise promise) { - if (isOpen()) { - return true; - } - - safeSetFailure(promise, CLOSED_CHANNEL_EXCEPTION); - return false; - } - - /** - * Marks the specified {@code promise} as success. If the {@code promise} is done already, log a message. - */ - protected final void safeSetSuccess(ChannelPromise promise) { - if (!(promise instanceof VoidChannelPromise) && !promise.trySuccess()) { - logger.warn("Failed to mark a promise as success because it is done already: {}", promise); - } - } - - /** - * Marks the specified {@code promise} as failure. If the {@code promise} is done already, log a message. - */ - protected final void safeSetFailure(ChannelPromise promise, Throwable cause) { - if (!(promise instanceof VoidChannelPromise) && !promise.tryFailure(cause)) { - logger.warn("Failed to mark a promise as failure because it's done already: {}", promise, cause); - } - } - - protected final void closeIfClosed() { - if (isOpen()) { - return; - } - close(voidPromise()); - } - - private void invokeLater(Runnable task) { - try { - // This method is used by outbound operation implementations to trigger an inbound event later. - // They do not trigger an inbound event immediately because an outbound operation might have been - // triggered by another inbound event handler method. If fired immediately, the call stack - // will look like this for example: - // - // handlerA.inboundBufferUpdated() - (1) an inbound handler method closes a connection. - // -> handlerA.ctx.close() - // -> channel.unsafe.close() - // -> handlerA.channelInactive() - (2) another inbound handler method called while in (1) yet - // - // which means the execution of two inbound handler methods of the same handler overlap undesirably. - eventLoop().execute(task); - } catch (RejectedExecutionException e) { - logger.warn("Can't invoke task later as EventLoop rejected it", e); - } - } - } - - /** - * Return {@code true} if the given {@link EventLoop} is compatible with this instance. - */ - protected abstract boolean isCompatible(EventLoop loop); - - /** - * Returns the {@link SocketAddress} which is bound locally. - */ - protected abstract SocketAddress localAddress0(); - - /** - * Return the {@link SocketAddress} which the {@link Channel} is connected to. - */ - protected abstract SocketAddress remoteAddress0(); - - /** - * Is called after the {@link Channel} is registered with its {@link EventLoop} as part of the register process. - * - * Sub-classes may override this method - */ - protected void doRegister() throws Exception { - // NOOP - } - - /** - * Bind the {@link Channel} to the {@link SocketAddress} - */ - protected abstract void doBind(SocketAddress localAddress) throws Exception; - - /** - * Disconnect this {@link Channel} from its remote peer - */ - protected abstract void doDisconnect() throws Exception; - - /** - * Close the {@link Channel} - */ - protected abstract void doClose() throws Exception; - - /** - * Deregister the {@link Channel} from its {@link EventLoop}. - * - * Sub-classes may override this method - */ - protected void doDeregister() throws Exception { - // NOOP - } - - /** - * Schedule a read operation. - */ - protected abstract void doBeginRead() throws Exception; - - /** - * Flush the content of the given buffer to the remote peer. - */ - protected abstract void doWrite(ChannelOutboundBuffer in) throws Exception; - - /** - * Invoked when a new message is added to a {@link ChannelOutboundBuffer} of this {@link AbstractChannel}, so that - * the {@link Channel} implementation converts the message to another. (e.g. heap buffer -> direct buffer) - */ - protected Object filterOutboundMessage(Object msg) throws Exception { - return msg; - } - - static final class CloseFuture extends DefaultChannelPromise { - - CloseFuture(AbstractChannel ch) { - super(ch); - } - - @Override - public ChannelPromise setSuccess() { - throw new IllegalStateException(); - } - - @Override - public ChannelPromise setFailure(Throwable cause) { - throw new IllegalStateException(); - } - - @Override - public boolean trySuccess() { - throw new IllegalStateException(); - } - - @Override - public boolean tryFailure(Throwable cause) { - throw new IllegalStateException(); - } - - boolean setClosed() { - return super.trySuccess(); - } - } -} diff --git a/common/src/main/java/common/net/channel/AbstractChannelHandlerContext.java b/common/src/main/java/common/net/channel/AbstractChannelHandlerContext.java deleted file mode 100644 index 204bd7a..0000000 --- a/common/src/main/java/common/net/channel/AbstractChannelHandlerContext.java +++ /dev/null @@ -1,1000 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import static common.net.channel.DefaultChannelPipeline.logger; - -import java.net.SocketAddress; - -import common.net.buffer.ByteBufAllocator; -import common.net.util.DefaultAttributeMap; -import common.net.util.Recycler; -import common.net.util.ReferenceCountUtil; -import common.net.util.concurrent.EventExecutor; -import common.net.util.concurrent.EventExecutorGroup; -import common.net.util.internal.OneTimeTask; -import common.net.util.internal.RecyclableMpscLinkedQueueNode; -import common.net.util.internal.StringUtil; - -abstract class AbstractChannelHandlerContext extends DefaultAttributeMap implements ChannelHandlerContext { - - volatile AbstractChannelHandlerContext next; - volatile AbstractChannelHandlerContext prev; - - private final boolean inbound; - private final boolean outbound; - private final AbstractChannel channel; - private final DefaultChannelPipeline pipeline; - private final String name; - private boolean removed; - - // Will be set to null if no child executor should be used, otherwise it will be set to the - // child executor. - final EventExecutor executor; - private ChannelFuture succeededFuture; - - // Lazily instantiated tasks used to trigger events to a handler with different executor. - // These needs to be volatile as otherwise an other Thread may see an half initialized instance. - // See the JMM for more details - private volatile Runnable invokeChannelReadCompleteTask; - private volatile Runnable invokeReadTask; - private volatile Runnable invokeChannelWritableStateChangedTask; - private volatile Runnable invokeFlushTask; - - AbstractChannelHandlerContext(DefaultChannelPipeline pipeline, EventExecutorGroup group, String name, - boolean inbound, boolean outbound) { - - if (name == null) { - throw new NullPointerException("name"); - } - - channel = pipeline.channel; - this.pipeline = pipeline; - this.name = name; - - if (group != null) { - // Pin one of the child executors once and remember it so that the same child executor - // is used to fire events for the same channel. - EventExecutor childExecutor = pipeline.childExecutors.get(group); - if (childExecutor == null) { - childExecutor = group.next(); - pipeline.childExecutors.put(group, childExecutor); - } - executor = childExecutor; - } else { - executor = null; - } - - this.inbound = inbound; - this.outbound = outbound; - } - - /** Invocation initiated by {@link DefaultChannelPipeline#teardownAll()}}. */ - void teardown() { - EventExecutor executor = executor(); - if (executor.inEventLoop()) { - teardown0(); - } else { - executor.execute(new Runnable() { - @Override - public void run() { - teardown0(); - } - }); - } - } - - private void teardown0() { - AbstractChannelHandlerContext prev = this.prev; - if (prev != null) { - synchronized (pipeline) { - pipeline.remove0(this); - } - prev.teardown(); - } - } - - @Override - public Channel channel() { - return channel; - } - - @Override - public ChannelPipeline pipeline() { - return pipeline; - } - - @Override - public ByteBufAllocator alloc() { - return channel().config().getAllocator(); - } - - @Override - public EventExecutor executor() { - if (executor == null) { - return channel().eventLoop(); - } else { - return executor; - } - } - - @Override - public String name() { - return name; - } - - @Override - public ChannelHandlerContext fireChannelRegistered() { - final AbstractChannelHandlerContext next = findContextInbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeChannelRegistered(); - } else { - executor.execute(new OneTimeTask() { - @Override - public void run() { - next.invokeChannelRegistered(); - } - }); - } - return this; - } - - private void invokeChannelRegistered() { - try { - ((ChannelInboundHandler) handler()).channelRegistered(this); - } catch (Throwable t) { - notifyHandlerException(t); - } - } - - @Override - public ChannelHandlerContext fireChannelUnregistered() { - final AbstractChannelHandlerContext next = findContextInbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeChannelUnregistered(); - } else { - executor.execute(new OneTimeTask() { - @Override - public void run() { - next.invokeChannelUnregistered(); - } - }); - } - return this; - } - - private void invokeChannelUnregistered() { - try { - ((ChannelInboundHandler) handler()).channelUnregistered(this); - } catch (Throwable t) { - notifyHandlerException(t); - } - } - - @Override - public ChannelHandlerContext fireChannelActive() { - final AbstractChannelHandlerContext next = findContextInbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeChannelActive(); - } else { - executor.execute(new OneTimeTask() { - @Override - public void run() { - next.invokeChannelActive(); - } - }); - } - return this; - } - - private void invokeChannelActive() { - try { - ((ChannelInboundHandler) handler()).channelActive(this); - } catch (Throwable t) { - notifyHandlerException(t); - } - } - - @Override - public ChannelHandlerContext fireChannelInactive() { - final AbstractChannelHandlerContext next = findContextInbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeChannelInactive(); - } else { - executor.execute(new OneTimeTask() { - @Override - public void run() { - next.invokeChannelInactive(); - } - }); - } - return this; - } - - private void invokeChannelInactive() { - try { - ((ChannelInboundHandler) handler()).channelInactive(this); - } catch (Throwable t) { - notifyHandlerException(t); - } - } - - @Override - public ChannelHandlerContext fireExceptionCaught(final Throwable cause) { - if (cause == null) { - throw new NullPointerException("cause"); - } - - final AbstractChannelHandlerContext next = this.next; - - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeExceptionCaught(cause); - } else { - try { - executor.execute(new OneTimeTask() { - @Override - public void run() { - next.invokeExceptionCaught(cause); - } - }); - } catch (Throwable t) { - if (logger.isWarnEnabled()) { - logger.warn("Failed to submit an exceptionCaught() event.", t); - logger.warn("The exceptionCaught() event that was failed to submit was:", cause); - } - } - } - - return this; - } - - private void invokeExceptionCaught(final Throwable cause) { - try { - handler().exceptionCaught(this, cause); - } catch (Throwable t) { - if (logger.isWarnEnabled()) { - logger.warn( - "An exception was thrown by a user handler's " + - "exceptionCaught() method while handling the following exception:", cause); - } - } - } - - @Override - public ChannelHandlerContext fireUserEventTriggered(final Object event) { - if (event == null) { - throw new NullPointerException("event"); - } - - final AbstractChannelHandlerContext next = findContextInbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeUserEventTriggered(event); - } else { - executor.execute(new OneTimeTask() { - @Override - public void run() { - next.invokeUserEventTriggered(event); - } - }); - } - return this; - } - - private void invokeUserEventTriggered(Object event) { - try { - ((ChannelInboundHandler) handler()).userEventTriggered(this, event); - } catch (Throwable t) { - notifyHandlerException(t); - } - } - - @Override - public ChannelHandlerContext fireChannelRead(final Object msg) { - if (msg == null) { - throw new NullPointerException("msg"); - } - - final AbstractChannelHandlerContext next = findContextInbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeChannelRead(msg); - } else { - executor.execute(new OneTimeTask() { - @Override - public void run() { - next.invokeChannelRead(msg); - } - }); - } - return this; - } - - private void invokeChannelRead(Object msg) { - try { - ((ChannelInboundHandler) handler()).channelRead(this, msg); - } catch (Throwable t) { - notifyHandlerException(t); - } - } - - @Override - public ChannelHandlerContext fireChannelReadComplete() { - final AbstractChannelHandlerContext next = findContextInbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeChannelReadComplete(); - } else { - Runnable task = next.invokeChannelReadCompleteTask; - if (task == null) { - next.invokeChannelReadCompleteTask = task = new Runnable() { - @Override - public void run() { - next.invokeChannelReadComplete(); - } - }; - } - executor.execute(task); - } - return this; - } - - private void invokeChannelReadComplete() { - try { - ((ChannelInboundHandler) handler()).channelReadComplete(this); - } catch (Throwable t) { - notifyHandlerException(t); - } - } - - @Override - public ChannelHandlerContext fireChannelWritabilityChanged() { - final AbstractChannelHandlerContext next = findContextInbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeChannelWritabilityChanged(); - } else { - Runnable task = next.invokeChannelWritableStateChangedTask; - if (task == null) { - next.invokeChannelWritableStateChangedTask = task = new Runnable() { - @Override - public void run() { - next.invokeChannelWritabilityChanged(); - } - }; - } - executor.execute(task); - } - return this; - } - - private void invokeChannelWritabilityChanged() { - try { - ((ChannelInboundHandler) handler()).channelWritabilityChanged(this); - } catch (Throwable t) { - notifyHandlerException(t); - } - } - - @Override - public ChannelFuture bind(SocketAddress localAddress) { - return bind(localAddress, newPromise()); - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress) { - return connect(remoteAddress, newPromise()); - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { - return connect(remoteAddress, localAddress, newPromise()); - } - - @Override - public ChannelFuture disconnect() { - return disconnect(newPromise()); - } - - @Override - public ChannelFuture close() { - return close(newPromise()); - } - - @Override - public ChannelFuture deregister() { - return deregister(newPromise()); - } - - @Override - public ChannelFuture bind(final SocketAddress localAddress, final ChannelPromise promise) { - if (localAddress == null) { - throw new NullPointerException("localAddress"); - } - if (!validatePromise(promise, false)) { - // cancelled - return promise; - } - - final AbstractChannelHandlerContext next = findContextOutbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeBind(localAddress, promise); - } else { - safeExecute(executor, new OneTimeTask() { - @Override - public void run() { - next.invokeBind(localAddress, promise); - } - }, promise, null); - } - - return promise; - } - - private void invokeBind(SocketAddress localAddress, ChannelPromise promise) { - try { - ((ChannelOutboundHandler) handler()).bind(this, localAddress, promise); - } catch (Throwable t) { - notifyOutboundHandlerException(t, promise); - } - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { - return connect(remoteAddress, null, promise); - } - - @Override - public ChannelFuture connect( - final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) { - - if (remoteAddress == null) { - throw new NullPointerException("remoteAddress"); - } - if (!validatePromise(promise, false)) { - // cancelled - return promise; - } - - final AbstractChannelHandlerContext next = findContextOutbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeConnect(remoteAddress, localAddress, promise); - } else { - safeExecute(executor, new OneTimeTask() { - @Override - public void run() { - next.invokeConnect(remoteAddress, localAddress, promise); - } - }, promise, null); - } - - return promise; - } - - private void invokeConnect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { - try { - ((ChannelOutboundHandler) handler()).connect(this, remoteAddress, localAddress, promise); - } catch (Throwable t) { - notifyOutboundHandlerException(t, promise); - } - } - - @Override - public ChannelFuture disconnect(final ChannelPromise promise) { - if (!validatePromise(promise, false)) { - // cancelled - return promise; - } - - final AbstractChannelHandlerContext next = findContextOutbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - // Translate disconnect to close if the channel has no notion of disconnect-reconnect. - // So far, UDP/IP is the only transport that has such behavior. - if (!channel().metadata().hasDisconnect()) { - next.invokeClose(promise); - } else { - next.invokeDisconnect(promise); - } - } else { - safeExecute(executor, new OneTimeTask() { - @Override - public void run() { - if (!channel().metadata().hasDisconnect()) { - next.invokeClose(promise); - } else { - next.invokeDisconnect(promise); - } - } - }, promise, null); - } - - return promise; - } - - private void invokeDisconnect(ChannelPromise promise) { - try { - ((ChannelOutboundHandler) handler()).disconnect(this, promise); - } catch (Throwable t) { - notifyOutboundHandlerException(t, promise); - } - } - - @Override - public ChannelFuture close(final ChannelPromise promise) { - if (!validatePromise(promise, false)) { - // cancelled - return promise; - } - - final AbstractChannelHandlerContext next = findContextOutbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeClose(promise); - } else { - safeExecute(executor, new OneTimeTask() { - @Override - public void run() { - next.invokeClose(promise); - } - }, promise, null); - } - - return promise; - } - - private void invokeClose(ChannelPromise promise) { - try { - ((ChannelOutboundHandler) handler()).close(this, promise); - } catch (Throwable t) { - notifyOutboundHandlerException(t, promise); - } - } - - @Override - public ChannelFuture deregister(final ChannelPromise promise) { - if (!validatePromise(promise, false)) { - // cancelled - return promise; - } - - final AbstractChannelHandlerContext next = findContextOutbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeDeregister(promise); - } else { - safeExecute(executor, new OneTimeTask() { - @Override - public void run() { - next.invokeDeregister(promise); - } - }, promise, null); - } - - return promise; - } - - private void invokeDeregister(ChannelPromise promise) { - try { - ((ChannelOutboundHandler) handler()).deregister(this, promise); - } catch (Throwable t) { - notifyOutboundHandlerException(t, promise); - } - } - - @Override - public ChannelHandlerContext read() { - final AbstractChannelHandlerContext next = findContextOutbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeRead(); - } else { - Runnable task = next.invokeReadTask; - if (task == null) { - next.invokeReadTask = task = new Runnable() { - @Override - public void run() { - next.invokeRead(); - } - }; - } - executor.execute(task); - } - - return this; - } - - private void invokeRead() { - try { - ((ChannelOutboundHandler) handler()).read(this); - } catch (Throwable t) { - notifyHandlerException(t); - } - } - - @Override - public ChannelFuture write(Object msg) { - return write(msg, newPromise()); - } - - @Override - public ChannelFuture write(final Object msg, final ChannelPromise promise) { - if (msg == null) { - throw new NullPointerException("msg"); - } - - if (!validatePromise(promise, true)) { - ReferenceCountUtil.release(msg); - // cancelled - return promise; - } - write(msg, false, promise); - - return promise; - } - - private void invokeWrite(Object msg, ChannelPromise promise) { - try { - ((ChannelOutboundHandler) handler()).write(this, msg, promise); - } catch (Throwable t) { - notifyOutboundHandlerException(t, promise); - } - } - - @Override - public ChannelHandlerContext flush() { - final AbstractChannelHandlerContext next = findContextOutbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeFlush(); - } else { - Runnable task = next.invokeFlushTask; - if (task == null) { - next.invokeFlushTask = task = new Runnable() { - @Override - public void run() { - next.invokeFlush(); - } - }; - } - safeExecute(executor, task, channel.voidPromise(), null); - } - - return this; - } - - private void invokeFlush() { - try { - ((ChannelOutboundHandler) handler()).flush(this); - } catch (Throwable t) { - notifyHandlerException(t); - } - } - - @Override - public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { - if (msg == null) { - throw new NullPointerException("msg"); - } - - if (!validatePromise(promise, true)) { - ReferenceCountUtil.release(msg); - // cancelled - return promise; - } - - write(msg, true, promise); - - return promise; - } - - private void write(Object msg, boolean flush, ChannelPromise promise) { - - AbstractChannelHandlerContext next = findContextOutbound(); - EventExecutor executor = next.executor(); - if (executor.inEventLoop()) { - next.invokeWrite(msg, promise); - if (flush) { - next.invokeFlush(); - } - } else { - int size = channel.estimatorHandle().size(msg); - if (size > 0) { - ChannelOutboundBuffer buffer = channel.unsafe().outboundBuffer(); - // Check for null as it may be set to null if the channel is closed already - if (buffer != null) { - buffer.incrementPendingOutboundBytes(size); - } - } - Runnable task; - if (flush) { - task = WriteAndFlushTask.newInstance(next, msg, size, promise); - } else { - task = WriteTask.newInstance(next, msg, size, promise); - } - safeExecute(executor, task, promise, msg); - } - } - - @Override - public ChannelFuture writeAndFlush(Object msg) { - return writeAndFlush(msg, newPromise()); - } - - private static void notifyOutboundHandlerException(Throwable cause, ChannelPromise promise) { - // only try to fail the promise if its not a VoidChannelPromise, as - // the VoidChannelPromise would also fire the cause through the pipeline - if (promise instanceof VoidChannelPromise) { - return; - } - - if (!promise.tryFailure(cause)) { - if (logger.isWarnEnabled()) { - logger.warn("Failed to fail the promise because it's done already: {}", promise, cause); - } - } - } - - private void notifyHandlerException(Throwable cause) { - if (inExceptionCaught(cause)) { - if (logger.isWarnEnabled()) { - logger.warn( - "An exception was thrown by a user handler " + - "while handling an exceptionCaught event", cause); - } - return; - } - - invokeExceptionCaught(cause); - } - - private static boolean inExceptionCaught(Throwable cause) { - do { - StackTraceElement[] trace = cause.getStackTrace(); - if (trace != null) { - for (StackTraceElement t : trace) { - if (t == null) { - break; - } - if ("exceptionCaught".equals(t.getMethodName())) { - return true; - } - } - } - - cause = cause.getCause(); - } while (cause != null); - - return false; - } - - @Override - public ChannelPromise newPromise() { - return new DefaultChannelPromise(channel(), executor()); - } - -// @Override -// public ChannelProgressivePromise newProgressivePromise() { -// return new DefaultChannelProgressivePromise(channel(), executor()); -// } - - @Override - public ChannelFuture newSucceededFuture() { - ChannelFuture succeededFuture = this.succeededFuture; - if (succeededFuture == null) { - this.succeededFuture = succeededFuture = new SucceededChannelFuture(channel(), executor()); - } - return succeededFuture; - } - - @Override - public ChannelFuture newFailedFuture(Throwable cause) { - return new FailedChannelFuture(channel(), executor(), cause); - } - - private boolean validatePromise(ChannelPromise promise, boolean allowVoidPromise) { - if (promise == null) { - throw new NullPointerException("promise"); - } - - if (promise.isDone()) { - // Check if the promise was cancelled and if so signal that the processing of the operation - // should not be performed. - // - // See https://github.com/netty/netty/issues/2349 - if (promise.isCancelled()) { - return false; - } - throw new IllegalArgumentException("promise already done: " + promise); - } - - if (promise.channel() != channel()) { - throw new IllegalArgumentException(String.format( - "promise.channel does not match: %s (expected: %s)", promise.channel(), channel())); - } - - if (promise.getClass() == DefaultChannelPromise.class) { - return true; - } - - if (!allowVoidPromise && promise instanceof VoidChannelPromise) { - throw new IllegalArgumentException( - StringUtil.simpleClassName(VoidChannelPromise.class) + " not allowed for this operation"); - } - - if (promise instanceof AbstractChannel.CloseFuture) { - throw new IllegalArgumentException( - StringUtil.simpleClassName(AbstractChannel.CloseFuture.class) + " not allowed in a pipeline"); - } - return true; - } - - private AbstractChannelHandlerContext findContextInbound() { - AbstractChannelHandlerContext ctx = this; - do { - ctx = ctx.next; - } while (!ctx.inbound); - return ctx; - } - - private AbstractChannelHandlerContext findContextOutbound() { - AbstractChannelHandlerContext ctx = this; - do { - ctx = ctx.prev; - } while (!ctx.outbound); - return ctx; - } - - @Override - public ChannelPromise voidPromise() { - return channel.voidPromise(); - } - - void setRemoved() { - removed = true; - } - - @Override - public boolean isRemoved() { - return removed; - } - - private static void safeExecute(EventExecutor executor, Runnable runnable, ChannelPromise promise, Object msg) { - try { - executor.execute(runnable); - } catch (Throwable cause) { - try { - promise.setFailure(cause); - } finally { - if (msg != null) { - ReferenceCountUtil.release(msg); - } - } - } - } - - abstract static class AbstractWriteTask extends RecyclableMpscLinkedQueueNode implements Runnable { - private AbstractChannelHandlerContext ctx; - private Object msg; - private ChannelPromise promise; - private int size; - - private AbstractWriteTask(Recycler.Handle handle) { - super(handle); - } - - protected static void init(AbstractWriteTask task, AbstractChannelHandlerContext ctx, - Object msg, int size, ChannelPromise promise) { - task.ctx = ctx; - task.msg = msg; - task.promise = promise; - task.size = size; - } - - @Override - public final void run() { - try { - if (size > 0) { - ChannelOutboundBuffer buffer = ctx.channel.unsafe().outboundBuffer(); - // Check for null as it may be set to null if the channel is closed already - if (buffer != null) { - buffer.decrementPendingOutboundBytes(size); - } - } - write(ctx, msg, promise); - } finally { - // Set to null so the GC can collect them directly - ctx = null; - msg = null; - promise = null; - } - } - - @Override - public Runnable value() { - return this; - } - - protected void write(AbstractChannelHandlerContext ctx, Object msg, ChannelPromise promise) { - ctx.invokeWrite(msg, promise); - } - } - - static final class WriteTask extends AbstractWriteTask implements SingleThreadEventLoop.NonWakeupRunnable { - - private static final Recycler RECYCLER = new Recycler() { - @Override - protected WriteTask newObject(Handle handle) { - return new WriteTask(handle); - } - }; - - private static WriteTask newInstance( - AbstractChannelHandlerContext ctx, Object msg, int size, ChannelPromise promise) { - WriteTask task = RECYCLER.get(); - init(task, ctx, msg, size, promise); - return task; - } - - private WriteTask(Recycler.Handle handle) { - super(handle); - } - - @Override - protected void recycle(Recycler.Handle handle) { - RECYCLER.recycle(this, handle); - } - } - - static final class WriteAndFlushTask extends AbstractWriteTask { - - private static final Recycler RECYCLER = new Recycler() { - @Override - protected WriteAndFlushTask newObject(Handle handle) { - return new WriteAndFlushTask(handle); - } - }; - - private static WriteAndFlushTask newInstance( - AbstractChannelHandlerContext ctx, Object msg, int size, ChannelPromise promise) { - WriteAndFlushTask task = RECYCLER.get(); - init(task, ctx, msg, size, promise); - return task; - } - - private WriteAndFlushTask(Recycler.Handle handle) { - super(handle); - } - - @Override - public void write(AbstractChannelHandlerContext ctx, Object msg, ChannelPromise promise) { - super.write(ctx, msg, promise); - ctx.invokeFlush(); - } - - @Override - protected void recycle(Recycler.Handle handle) { - RECYCLER.recycle(this, handle); - } - } -} diff --git a/common/src/main/java/common/net/channel/AbstractServerChannel.java b/common/src/main/java/common/net/channel/AbstractServerChannel.java deleted file mode 100644 index ae1bd45..0000000 --- a/common/src/main/java/common/net/channel/AbstractServerChannel.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.net.SocketAddress; - -/** - * A skeletal server-side {@link Channel} implementation. A server-side - * {@link Channel} does not allow the following operations: - *
    - *
  • {@link #connect(SocketAddress, ChannelPromise)}
  • - *
  • {@link #disconnect(ChannelPromise)}
  • - *
  • {@link #write(Object, ChannelPromise)}
  • - *
  • {@link #flush()}
  • - *
  • and the shortcut methods which calls the methods mentioned above - *
- */ -public abstract class AbstractServerChannel extends AbstractChannel implements ServerChannel { - - private static final ChannelMetadata METADATA = new ChannelMetadata(false); - - /** - * Creates a new instance. - */ - protected AbstractServerChannel() { - super(null); - } - - @Override - public ChannelMetadata metadata() { - return METADATA; - } - - @Override - public SocketAddress remoteAddress() { - return null; - } - - @Override - protected SocketAddress remoteAddress0() { - return null; - } - - @Override - protected void doDisconnect() throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - protected AbstractUnsafe newUnsafe() { - return new DefaultServerUnsafe(); - } - - @Override - protected void doWrite(ChannelOutboundBuffer in) throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - protected final Object filterOutboundMessage(Object msg) { - throw new UnsupportedOperationException(); - } - - private final class DefaultServerUnsafe extends AbstractUnsafe { - @Override - public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { - safeSetFailure(promise, new UnsupportedOperationException()); - } - } -} diff --git a/common/src/main/java/common/net/channel/AdaptiveRecvByteBufAllocator.java b/common/src/main/java/common/net/channel/AdaptiveRecvByteBufAllocator.java deleted file mode 100644 index f1eb52d..0000000 --- a/common/src/main/java/common/net/channel/AdaptiveRecvByteBufAllocator.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.util.ArrayList; -import java.util.List; - -import common.net.buffer.ByteBuf; -import common.net.buffer.ByteBufAllocator; - -/** - * The {@link RecvByteBufAllocator} that automatically increases and - * decreases the predicted buffer size on feed back. - *

- * It gradually increases the expected number of readable bytes if the previous - * read fully filled the allocated buffer. It gradually decreases the expected - * number of readable bytes if the read operation was not able to fill a certain - * amount of the allocated buffer two times consecutively. Otherwise, it keeps - * returning the same prediction. - */ -public class AdaptiveRecvByteBufAllocator implements RecvByteBufAllocator { - - static final int DEFAULT_MINIMUM = 64; - static final int DEFAULT_INITIAL = 1024; - static final int DEFAULT_MAXIMUM = 65536; - - private static final int INDEX_INCREMENT = 4; - private static final int INDEX_DECREMENT = 1; - - private static final int[] SIZE_TABLE; - - static { - List sizeTable = new ArrayList(); - for (int i = 16; i < 512; i += 16) { - sizeTable.add(i); - } - - for (int i = 512; i > 0; i <<= 1) { - sizeTable.add(i); - } - - SIZE_TABLE = new int[sizeTable.size()]; - for (int i = 0; i < SIZE_TABLE.length; i ++) { - SIZE_TABLE[i] = sizeTable.get(i); - } - } - - public static final AdaptiveRecvByteBufAllocator DEFAULT = new AdaptiveRecvByteBufAllocator(); - - private static int getSizeTableIndex(final int size) { - for (int low = 0, high = SIZE_TABLE.length - 1;;) { - if (high < low) { - return low; - } - if (high == low) { - return high; - } - - int mid = low + high >>> 1; - int a = SIZE_TABLE[mid]; - int b = SIZE_TABLE[mid + 1]; - if (size > b) { - low = mid + 1; - } else if (size < a) { - high = mid - 1; - } else if (size == a) { - return mid; - } else { - return mid + 1; - } - } - } - - private static final class HandleImpl implements Handle { - private final int minIndex; - private final int maxIndex; - private int index; - private int nextReceiveBufferSize; - private boolean decreaseNow; - - HandleImpl(int minIndex, int maxIndex, int initial) { - this.minIndex = minIndex; - this.maxIndex = maxIndex; - - index = getSizeTableIndex(initial); - nextReceiveBufferSize = SIZE_TABLE[index]; - } - - @Override - public ByteBuf allocate(ByteBufAllocator alloc) { - return alloc.ioBuffer(nextReceiveBufferSize); - } - - @Override - public int guess() { - return nextReceiveBufferSize; - } - - @Override - public void record(int actualReadBytes) { - if (actualReadBytes <= SIZE_TABLE[Math.max(0, index - INDEX_DECREMENT - 1)]) { - if (decreaseNow) { - index = Math.max(index - INDEX_DECREMENT, minIndex); - nextReceiveBufferSize = SIZE_TABLE[index]; - decreaseNow = false; - } else { - decreaseNow = true; - } - } else if (actualReadBytes >= nextReceiveBufferSize) { - index = Math.min(index + INDEX_INCREMENT, maxIndex); - nextReceiveBufferSize = SIZE_TABLE[index]; - decreaseNow = false; - } - } - } - - private final int minIndex; - private final int maxIndex; - private final int initial; - - /** - * Creates a new predictor with the default parameters. With the default - * parameters, the expected buffer size starts from {@code 1024}, does not - * go down below {@code 64}, and does not go up above {@code 65536}. - */ - private AdaptiveRecvByteBufAllocator() { - this(DEFAULT_MINIMUM, DEFAULT_INITIAL, DEFAULT_MAXIMUM); - } - - /** - * Creates a new predictor with the specified parameters. - * - * @param minimum the inclusive lower bound of the expected buffer size - * @param initial the initial buffer size when no feed back was received - * @param maximum the inclusive upper bound of the expected buffer size - */ - public AdaptiveRecvByteBufAllocator(int minimum, int initial, int maximum) { - if (minimum <= 0) { - throw new IllegalArgumentException("minimum: " + minimum); - } - if (initial < minimum) { - throw new IllegalArgumentException("initial: " + initial); - } - if (maximum < initial) { - throw new IllegalArgumentException("maximum: " + maximum); - } - - int minIndex = getSizeTableIndex(minimum); - if (SIZE_TABLE[minIndex] < minimum) { - this.minIndex = minIndex + 1; - } else { - this.minIndex = minIndex; - } - - int maxIndex = getSizeTableIndex(maximum); - if (SIZE_TABLE[maxIndex] > maximum) { - this.maxIndex = maxIndex - 1; - } else { - this.maxIndex = maxIndex; - } - - this.initial = initial; - } - - @Override - public Handle newHandle() { - return new HandleImpl(minIndex, maxIndex, initial); - } -} diff --git a/common/src/main/java/common/net/channel/Channel.java b/common/src/main/java/common/net/channel/Channel.java deleted file mode 100644 index 464bbff..0000000 --- a/common/src/main/java/common/net/channel/Channel.java +++ /dev/null @@ -1,511 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.net.SocketAddress; - -import common.net.buffer.ByteBufAllocator; -import common.net.util.AttributeMap; - - -/** - * A nexus to a network socket or a component which is capable of I/O - * operations such as read, write, connect, and bind. - *

- * A channel provides a user: - *

    - *
  • the current state of the channel (e.g. is it open? is it connected?),
  • - *
  • the {@linkplain ChannelConfig configuration parameters} of the channel (e.g. receive buffer size),
  • - *
  • the I/O operations that the channel supports (e.g. read, write, connect, and bind), and
  • - *
  • the {@link ChannelPipeline} which handles all I/O events and requests - * associated with the channel.
  • - *
- * - *

All I/O operations are asynchronous.

- *

- * All I/O operations in Netty are asynchronous. It means any I/O calls will - * return immediately with no guarantee that the requested I/O operation has - * been completed at the end of the call. Instead, you will be returned with - * a {@link ChannelFuture} instance which will notify you when the requested I/O - * operation has succeeded, failed, or canceled. - * - *

Channels are hierarchical

- *

- * A {@link Channel} can have a {@linkplain #parent() parent} depending on - * how it was created. For instance, a {@link SocketChannel}, that was accepted - * by {@link ServerSocketChannel}, will return the {@link ServerSocketChannel} - * as its parent on {@link #parent()}. - *

- * The semantics of the hierarchical structure depends on the transport - * implementation where the {@link Channel} belongs to. For example, you could - * write a new {@link Channel} implementation that creates the sub-channels that - * share one socket connection, as BEEP and - * SSH do. - * - *

Downcast to access transport-specific operations

- *

- * Some transports exposes additional operations that is specific to the - * transport. Down-cast the {@link Channel} to sub-type to invoke such - * operations. For example, with the old I/O datagram transport, multicast - * join / leave operations are provided by {@link DatagramChannel}. - * - *

Release resources

- *

- * It is important to call {@link #close()} or {@link #close(ChannelPromise)} to release all - * resources once you are done with the {@link Channel}. This ensures all resources are - * released in a proper way, i.e. filehandles. - */ -public interface Channel extends AttributeMap, Comparable { - - /** - * Return the {@link EventLoop} this {@link Channel} was registered too. - */ - EventLoop eventLoop(); - - /** - * Returns the parent of this channel. - * - * @return the parent channel. - * {@code null} if this channel does not have a parent channel. - */ - Channel parent(); - - /** - * Returns the configuration of this channel. - */ - ChannelConfig config(); - - /** - * Returns {@code true} if the {@link Channel} is open an may get active later - */ - boolean isOpen(); - - /** - * Returns {@code true} if the {@link Channel} is registered with an {@link EventLoop}. - */ - boolean isRegistered(); - - /** - * Return {@code true} if the {@link Channel} is active and so connected. - */ - boolean isActive(); - - /** - * Return the {@link ChannelMetadata} of the {@link Channel} which describe the nature of the {@link Channel}. - */ - ChannelMetadata metadata(); - - /** - * Returns the local address where this channel is bound to. The returned - * {@link SocketAddress} is supposed to be down-cast into more concrete - * type such as {@link InetSocketAddress} to retrieve the detailed - * information. - * - * @return the local address of this channel. - * {@code null} if this channel is not bound. - */ - SocketAddress localAddress(); - - /** - * Returns the remote address where this channel is connected to. The - * returned {@link SocketAddress} is supposed to be down-cast into more - * concrete type such as {@link InetSocketAddress} to retrieve the detailed - * information. - * - * @return the remote address of this channel. - * {@code null} if this channel is not connected. - * If this channel is not connected but it can receive messages - * from arbitrary remote addresses (e.g. {@link DatagramChannel}, - * use {@link DatagramPacket#recipient()} to determine - * the origination of the received message as this method will - * return {@code null}. - */ - SocketAddress remoteAddress(); - - /** - * Returns the {@link ChannelFuture} which will be notified when this - * channel is closed. This method always returns the same future instance. - */ - ChannelFuture closeFuture(); - - /** - * Returns {@code true} if and only if the I/O thread will perform the - * requested write operation immediately. Any write requests made when - * this method returns {@code false} are queued until the I/O thread is - * ready to process the queued write requests. - */ - boolean isWritable(); - - /** - * Returns an internal-use-only object that provides unsafe operations. - */ - Unsafe unsafe(); - - /** - * Return the assigned {@link ChannelPipeline} - */ - ChannelPipeline pipeline(); - - /** - * Return the assigned {@link ByteBufAllocator} which will be used to allocate {@link ByteBuf}s. - */ - ByteBufAllocator alloc(); - - /** - * Return a new {@link ChannelPromise}. - */ - ChannelPromise newPromise(); - - /** - * Return an new {@link ChannelProgressivePromise} - */ -// ChannelProgressivePromise newProgressivePromise(); - - /** - * Create a new {@link ChannelFuture} which is marked as succeeded already. So {@link ChannelFuture#isSuccess()} - * will return {@code true}. All {@link FutureListener} added to it will be notified directly. Also - * every call of blocking methods will just return without blocking. - */ - ChannelFuture newSucceededFuture(); - - /** - * Create a new {@link ChannelFuture} which is marked as failed already. So {@link ChannelFuture#isSuccess()} - * will return {@code false}. All {@link FutureListener} added to it will be notified directly. Also - * every call of blocking methods will just return without blocking. - */ - ChannelFuture newFailedFuture(Throwable cause); - - /** - * Return a special ChannelPromise which can be reused for different operations. - *

- * It's only supported to use - * it for {@link Channel#write(Object, ChannelPromise)}. - *

- *

- * Be aware that the returned {@link ChannelPromise} will not support most operations and should only be used - * if you want to save an object allocation for every write operation. You will not be able to detect if the - * operation was complete, only if it failed as the implementation will call - * {@link ChannelPipeline#fireExceptionCaught(Throwable)} in this case. - *

- * Be aware this is an expert feature and should be used with care! - */ - ChannelPromise voidPromise(); - - /** - * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method - * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture bind(SocketAddress localAddress); - - /** - * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - *

- * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with - * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} - * will be used. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress); - - /** - * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the - * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of - * an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress); - - /** - * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, - * either because the operation was successful or because of an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture disconnect(); - - /** - * Request to close this {@link Channel} and notify the {@link ChannelFuture} once the operation completes, - * either because the operation was successful or because of - * an error. - * - * After it is closed it is not possible to reuse it again. - *

- * This will result in having the - * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture close(); - - /** - * Request to deregister this {@link Channel} from the previous assigned {@link EventExecutor} and notify the - * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of - * an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - * - */ - ChannelFuture deregister(); - - /** - * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - * - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method - * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise); - - /** - * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - * - * The given {@link ChannelFuture} will be notified. - * - *

- * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with - * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} - * will be used. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise); - - /** - * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the - * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of - * an error. - * - * The given {@link ChannelPromise} will be notified and also returned. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise); - - /** - * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, - * either because the operation was successful or because of an error. - * - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture disconnect(ChannelPromise promise); - - /** - * Request to close this {@link Channel} and notify the {@link ChannelFuture} once the operation completes, - * either because the operation was successful or because of - * an error. - * - * After it is closed it is not possible to reuse it again. - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture close(ChannelPromise promise); - - /** - * Request to deregister this {@link Channel} from the previous assigned {@link EventExecutor} and notify the - * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of - * an error. - * - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture deregister(ChannelPromise promise); - - /** - * Request to Read data from the {@link Channel} into the first inbound buffer, triggers an - * {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)} event if data was - * read, and triggers a - * {@link ChannelInboundHandler#channelReadComplete(ChannelHandlerContext) channelReadComplete} event so the - * handler can decide to continue reading. If there's a pending read operation already, this method does nothing. - *

- * This will result in having the - * {@link ChannelOutboundHandler#read(ChannelHandlerContext)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - Channel read(); - - /** - * Request to write a message via this {@link Channel} through the {@link ChannelPipeline}. - * This method will not request to actual flush, so be sure to call {@link #flush()} - * once you want to request to flush all pending data to the actual transport. - */ - ChannelFuture write(Object msg); - - /** - * Request to write a message via this {@link Channel} through the {@link ChannelPipeline}. - * This method will not request to actual flush, so be sure to call {@link #flush()} - * once you want to request to flush all pending data to the actual transport. - */ - ChannelFuture write(Object msg, ChannelPromise promise); - - /** - * Request to flush all pending messages. - */ - Channel flush(); - - /** - * Shortcut for call {@link #write(Object, ChannelPromise)} and {@link #flush()}. - */ - ChannelFuture writeAndFlush(Object msg, ChannelPromise promise); - - /** - * Shortcut for call {@link #write(Object)} and {@link #flush()}. - */ - ChannelFuture writeAndFlush(Object msg); - - /** - * Unsafe operations that should never be called from user-code. These methods - * are only provided to implement the actual transport, and must be invoked from an I/O thread except for the - * following methods: - *

    - *
  • {@link #localAddress()}
  • - *
  • {@link #remoteAddress()}
  • - *
  • {@link #closeForcibly()}
  • - *
  • {@link #register(EventLoop, ChannelPromise)}
  • - *
  • {@link #voidPromise()}
  • - *
- */ - interface Unsafe { - /** - * Return the {@link SocketAddress} to which is bound local or - * {@code null} if none. - */ - SocketAddress localAddress(); - - /** - * Return the {@link SocketAddress} to which is bound remote or - * {@code null} if none is bound yet. - */ - SocketAddress remoteAddress(); - - /** - * Register the {@link Channel} of the {@link ChannelPromise} with the {@link EventLoop} and notify - * the {@link ChannelFuture} once the registration was complete. - */ - void register(EventLoop eventLoop, ChannelPromise promise); - - /** - * Bind the {@link SocketAddress} to the {@link Channel} of the {@link ChannelPromise} and notify - * it once its done. - */ - void bind(SocketAddress localAddress, ChannelPromise promise); - - /** - * Connect the {@link Channel} of the given {@link ChannelFuture} with the given remote {@link SocketAddress}. - * If a specific local {@link SocketAddress} should be used it need to be given as argument. Otherwise just - * pass {@code null} to it. - * - * The {@link ChannelPromise} will get notified once the connect operation was complete. - */ - void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise); - - /** - * Disconnect the {@link Channel} of the {@link ChannelFuture} and notify the {@link ChannelPromise} once the - * operation was complete. - */ - void disconnect(ChannelPromise promise); - - /** - * Close the {@link Channel} of the {@link ChannelPromise} and notify the {@link ChannelPromise} once the - * operation was complete. - */ - void close(ChannelPromise promise); - - /** - * Closes the {@link Channel} immediately without firing any events. Probably only useful - * when registration attempt failed. - */ - void closeForcibly(); - - /** - * Deregister the {@link Channel} of the {@link ChannelPromise} from {@link EventLoop} and notify the - * {@link ChannelPromise} once the operation was complete. - */ - void deregister(ChannelPromise promise); - - /** - * Schedules a read operation that fills the inbound buffer of the first {@link ChannelInboundHandler} in the - * {@link ChannelPipeline}. If there's already a pending read operation, this method does nothing. - */ - void beginRead(); - - /** - * Schedules a write operation. - */ - void write(Object msg, ChannelPromise promise); - - /** - * Flush out all write operations scheduled via {@link #write(Object, ChannelPromise)}. - */ - void flush(); - - /** - * Return a special ChannelPromise which can be reused and passed to the operations in {@link Unsafe}. - * It will never be notified of a success or error and so is only a placeholder for operations - * that take a {@link ChannelPromise} as argument but for which you not want to get notified. - */ - ChannelPromise voidPromise(); - - /** - * Returns the {@link ChannelOutboundBuffer} of the {@link Channel} where the pending write requests are stored. - */ - ChannelOutboundBuffer outboundBuffer(); - } -} diff --git a/common/src/main/java/common/net/channel/ChannelConfig.java b/common/src/main/java/common/net/channel/ChannelConfig.java deleted file mode 100644 index 50e300f..0000000 --- a/common/src/main/java/common/net/channel/ChannelConfig.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.util.Map; - -import common.net.buffer.ByteBufAllocator; - -/** - * A set of configuration properties of a {@link Channel}. - *

- * Please down-cast to more specific configuration type such as - * {@link SocketChannelConfig} or use {@link #setOptions(Map)} to set the - * transport-specific properties: - *

- * {@link Channel} ch = ...;
- * {@link SocketChannelConfig} cfg = ({@link SocketChannelConfig}) ch.getConfig();
- * cfg.setTcpNoDelay(false);
- * 
- * - *

Option map

- * - * An option map property is a dynamic write-only property which allows - * the configuration of a {@link Channel} without down-casting its associated - * {@link ChannelConfig}. To update an option map, please call {@link #setOptions(Map)}. - *

- * All {@link ChannelConfig} has the following options: - * - * - * - * - * - * - * - * - * - * - * - * - * - *
NameAssociated setter method
{@link ChannelOption#CONNECT_TIMEOUT_MILLIS}{@link #setConnectTimeoutMillis(int)}
{@link ChannelOption#WRITE_SPIN_COUNT}{@link #setWriteSpinCount(int)}
{@link ChannelOption#ALLOCATOR}{@link #setAllocator(ByteBufAllocator)}
{@link ChannelOption#AUTO_READ}{@link #setAutoRead(boolean)}
- *

- * More options are available in the sub-types of {@link ChannelConfig}. For - * example, you can configure the parameters which are specific to a TCP/IP - * socket as explained in {@link SocketChannelConfig}. - */ -public interface ChannelConfig { - - /** - * Return all set {@link ChannelOption}'s. - */ - Map, Object> getOptions(); - - /** - * Sets the configuration properties from the specified {@link Map}. - */ - boolean setOptions(Map, ?> options); - - /** - * Return the value of the given {@link ChannelOption} - */ - T getOption(ChannelOption option); - - /** - * Sets a configuration property with the specified name and value. - * To override this method properly, you must call the super class: - *

-     * public boolean setOption(ChannelOption<T> option, T value) {
-     *     if (super.setOption(option, value)) {
-     *         return true;
-     *     }
-     *
-     *     if (option.equals(additionalOption)) {
-     *         ....
-     *         return true;
-     *     }
-     *
-     *     return false;
-     * }
-     * 
- * - * @return {@code true} if and only if the property has been set - */ - boolean setOption(ChannelOption option, T value); - - /** - * Returns the connect timeout of the channel in milliseconds. If the - * {@link Channel} does not support connect operation, this property is not - * used at all, and therefore will be ignored. - * - * @return the connect timeout in milliseconds. {@code 0} if disabled. - */ - int getConnectTimeoutMillis(); - - /** - * Sets the connect timeout of the channel in milliseconds. If the - * {@link Channel} does not support connect operation, this property is not - * used at all, and therefore will be ignored. - * - * @param connectTimeoutMillis the connect timeout in milliseconds. - * {@code 0} to disable. - */ - ChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis); - - /** - * Returns the maximum number of messages to read per read loop. - * a {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object) channelRead()} event. - * If this value is greater than 1, an event loop might attempt to read multiple times to procure multiple messages. - */ - int getMaxMessagesPerRead(); - - /** - * Sets the maximum number of messages to read per read loop. - * If this value is greater than 1, an event loop might attempt to read multiple times to procure multiple messages. - */ - ChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead); - - /** - * Returns the maximum loop count for a write operation until - * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. - * It is similar to what a spin lock is used for in concurrency programming. - * It improves memory utilization and write throughput depending on - * the platform that JVM runs on. The default value is {@code 16}. - */ - int getWriteSpinCount(); - - /** - * Sets the maximum loop count for a write operation until - * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. - * It is similar to what a spin lock is used for in concurrency programming. - * It improves memory utilization and write throughput depending on - * the platform that JVM runs on. The default value is {@code 16}. - * - * @throws IllegalArgumentException - * if the specified value is {@code 0} or less than {@code 0} - */ - ChannelConfig setWriteSpinCount(int writeSpinCount); - - /** - * Returns {@link ByteBufAllocator} which is used for the channel - * to allocate buffers. - */ - ByteBufAllocator getAllocator(); - - /** - * Set the {@link ByteBufAllocator} which is used for the channel - * to allocate buffers. - */ - ChannelConfig setAllocator(ByteBufAllocator allocator); - - /** - * Returns {@link RecvByteBufAllocator} which is used for the channel - * to allocate receive buffers. - */ - RecvByteBufAllocator getRecvByteBufAllocator(); - - /** - * Set the {@link ByteBufAllocator} which is used for the channel - * to allocate receive buffers. - */ - ChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator); - - /** - * Returns {@code true} if and only if {@link ChannelHandlerContext#read()} will be invoked automatically so that - * a user application doesn't need to call it at all. The default value is {@code true}. - */ - boolean isAutoRead(); - - /** - * Sets if {@link ChannelHandlerContext#read()} will be invoked automatically so that a user application doesn't - * need to call it at all. The default value is {@code true}. - */ - ChannelConfig setAutoRead(boolean autoRead); - - /** - * Returns the high water mark of the write buffer. If the number of bytes - * queued in the write buffer exceeds this value, {@link Channel#isWritable()} - * will start to return {@code false}. - */ - int getWriteBufferHighWaterMark(); - - /** - * Sets the high water mark of the write buffer. If the number of bytes - * queued in the write buffer exceeds this value, {@link Channel#isWritable()} - * will start to return {@code false}. - */ - ChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark); - - /** - * Returns the low water mark of the write buffer. Once the number of bytes - * queued in the write buffer exceeded the - * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then - * dropped down below this value, {@link Channel#isWritable()} will start to return - * {@code true} again. - */ - int getWriteBufferLowWaterMark(); - - /** - * Sets the low water mark of the write buffer. Once the number of bytes - * queued in the write buffer exceeded the - * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then - * dropped down below this value, {@link Channel#isWritable()} will start to return - * {@code true} again. - */ - ChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark); - - /** - * Returns {@link MessageSizeEstimator} which is used for the channel - * to detect the size of a message. - */ - MessageSizeEstimator getMessageSizeEstimator(); - - /** - * Set the {@link ByteBufAllocator} which is used for the channel - * to detect the size of a message. - */ - ChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator); -} diff --git a/common/src/main/java/common/net/channel/ChannelException.java b/common/src/main/java/common/net/channel/ChannelException.java deleted file mode 100644 index 721d03f..0000000 --- a/common/src/main/java/common/net/channel/ChannelException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -/** - * A {@link RuntimeException} which is thrown when an I/O operation fails. - */ -public class ChannelException extends RuntimeException { - - private static final long serialVersionUID = 2908618315971075004L; - - /** - * Creates a new exception. - */ - public ChannelException() { - } - - /** - * Creates a new exception. - */ - public ChannelException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Creates a new exception. - */ - public ChannelException(String message) { - super(message); - } - - /** - * Creates a new exception. - */ - public ChannelException(Throwable cause) { - super(cause); - } -} diff --git a/common/src/main/java/common/net/channel/ChannelFuture.java b/common/src/main/java/common/net/channel/ChannelFuture.java deleted file mode 100644 index e849ad5..0000000 --- a/common/src/main/java/common/net/channel/ChannelFuture.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; - - -/** - * The result of an asynchronous {@link Channel} I/O operation. - *

- * All I/O operations in Netty are asynchronous. It means any I/O calls will - * return immediately with no guarantee that the requested I/O operation has - * been completed at the end of the call. Instead, you will be returned with - * a {@link ChannelFuture} instance which gives you the information about the - * result or status of the I/O operation. - *

- * A {@link ChannelFuture} is either uncompleted or completed. - * When an I/O operation begins, a new future object is created. The new future - * is uncompleted initially - it is neither succeeded, failed, nor cancelled - * because the I/O operation is not finished yet. If the I/O operation is - * finished either successfully, with failure, or by cancellation, the future is - * marked as completed with more specific information, such as the cause of the - * failure. Please note that even failure and cancellation belong to the - * completed state. - *

- *                                      +---------------------------+
- *                                      | Completed successfully    |
- *                                      +---------------------------+
- *                                 +---->      isDone() = true      |
- * +--------------------------+    |    |   isSuccess() = true      |
- * |        Uncompleted       |    |    +===========================+
- * +--------------------------+    |    | Completed with failure    |
- * |      isDone() = false    |    |    +---------------------------+
- * |   isSuccess() = false    |----+---->   isDone() = true         |
- * | isCancelled() = false    |    |    | cause() = non-null     |
- * |    cause() = null     |    |    +===========================+
- * +--------------------------+    |    | Completed by cancellation |
- *                                 |    +---------------------------+
- *                                 +---->      isDone() = true      |
- *                                      | isCancelled() = true      |
- *                                      +---------------------------+
- * 
- * - * Various methods are provided to let you check if the I/O operation has been - * completed, wait for the completion, and retrieve the result of the I/O - * operation. It also allows you to add {@link ChannelFutureListener}s so you - * can get notified when the I/O operation is completed. - * - *

Prefer {@link #addListener(GenericFutureListener)} to {@link #await()}

- * - * It is recommended to prefer {@link #addListener(GenericFutureListener)} to - * {@link #await()} wherever possible to get notified when an I/O operation is - * done and to do any follow-up tasks. - *

- * {@link #addListener(GenericFutureListener)} is non-blocking. It simply adds - * the specified {@link ChannelFutureListener} to the {@link ChannelFuture}, and - * I/O thread will notify the listeners when the I/O operation associated with - * the future is done. {@link ChannelFutureListener} yields the best - * performance and resource utilization because it does not block at all, but - * it could be tricky to implement a sequential logic if you are not used to - * event-driven programming. - *

- * By contrast, {@link #await()} is a blocking operation. Once called, the - * caller thread blocks until the operation is done. It is easier to implement - * a sequential logic with {@link #await()}, but the caller thread blocks - * unnecessarily until the I/O operation is done and there's relatively - * expensive cost of inter-thread notification. Moreover, there's a chance of - * dead lock in a particular circumstance, which is described below. - * - *

Do not call {@link #await()} inside {@link ChannelHandler}

- *

- * The event handler methods in {@link ChannelHandler} is usually called by - * an I/O thread. If {@link #await()} is called by an event handler - * method, which is called by the I/O thread, the I/O operation it is waiting - * for might never be complete because {@link #await()} can block the I/O - * operation it is waiting for, which is a dead lock. - *

- * // BAD - NEVER DO THIS
- * {@code @Override}
- * public void channelRead({@link ChannelHandlerContext} ctx, GoodByeMessage msg) {
- *     {@link ChannelFuture} future = ctx.channel().close();
- *     future.awaitUninterruptibly();
- *     // Perform post-closure operation
- *     // ...
- * }
- *
- * // GOOD
- * {@code @Override}
- * public void channelRead({@link ChannelHandlerContext} ctx,  GoodByeMessage msg) {
- *     {@link ChannelFuture} future = ctx.channel().close();
- *     future.addListener(new {@link ChannelFutureListener}() {
- *         public void operationComplete({@link ChannelFuture} future) {
- *             // Perform post-closure operation
- *             // ...
- *         }
- *     });
- * }
- * 
- *

- * In spite of the disadvantages mentioned above, there are certainly the cases - * where it is more convenient to call {@link #await()}. In such a case, please - * make sure you do not call {@link #await()} in an I/O thread. Otherwise, - * {@link BlockingOperationException} will be raised to prevent a dead lock. - * - *

Do not confuse I/O timeout and await timeout

- * - * The timeout value you specify with {@link #await(long)}, - * {@link #await(long, TimeUnit)}, {@link #awaitUninterruptibly(long)}, or - * {@link #awaitUninterruptibly(long, TimeUnit)} are not related with I/O - * timeout at all. If an I/O operation times out, the future will be marked as - * 'completed with failure,' as depicted in the diagram above. For example, - * connect timeout should be configured via a transport-specific option: - *
- * // BAD - NEVER DO THIS
- * {@link Bootstrap} b = ...;
- * {@link ChannelFuture} f = b.connect(...);
- * f.awaitUninterruptibly(10, TimeUnit.SECONDS);
- * if (f.isCancelled()) {
- *     // Connection attempt cancelled by user
- * } else if (!f.isSuccess()) {
- *     // You might get a NullPointerException here because the future
- *     // might not be completed yet.
- *     f.cause().printStackTrace();
- * } else {
- *     // Connection established successfully
- * }
- *
- * // GOOD
- * {@link Bootstrap} b = ...;
- * // Configure the connect timeout option.
- * b.option({@link ChannelOption}.CONNECT_TIMEOUT_MILLIS, 10000);
- * {@link ChannelFuture} f = b.connect(...);
- * f.awaitUninterruptibly();
- *
- * // Now we are sure the future is completed.
- * assert f.isDone();
- *
- * if (f.isCancelled()) {
- *     // Connection attempt cancelled by user
- * } else if (!f.isSuccess()) {
- *     f.cause().printStackTrace();
- * } else {
- *     // Connection established successfully
- * }
- * 
- */ -public interface ChannelFuture extends Future { - - /** - * Returns a channel where the I/O operation associated with this - * future takes place. - */ - Channel channel(); - - @Override - ChannelFuture addListener(GenericFutureListener> listener); - - @Override - ChannelFuture addListeners(GenericFutureListener>... listeners); - - @Override - ChannelFuture removeListener(GenericFutureListener> listener); - - @Override - ChannelFuture removeListeners(GenericFutureListener>... listeners); - - @Override - ChannelFuture sync() throws InterruptedException; - - @Override - ChannelFuture syncUninterruptibly(); - - @Override - ChannelFuture await() throws InterruptedException; - - @Override - ChannelFuture awaitUninterruptibly(); -} diff --git a/common/src/main/java/common/net/channel/ChannelFutureListener.java b/common/src/main/java/common/net/channel/ChannelFutureListener.java deleted file mode 100644 index ec088b6..0000000 --- a/common/src/main/java/common/net/channel/ChannelFutureListener.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.util.concurrent.GenericFutureListener; - - -/** - * Listens to the result of a {@link ChannelFuture}. The result of the - * asynchronous {@link Channel} I/O operation is notified once this listener - * is added by calling {@link ChannelFuture#addListener(GenericFutureListener)}. - * - *

Return the control to the caller quickly

- * - * {@link #operationComplete(Future)} is directly called by an I/O - * thread. Therefore, performing a time consuming task or a blocking operation - * in the handler method can cause an unexpected pause during I/O. If you need - * to perform a blocking operation on I/O completion, try to execute the - * operation in a different thread using a thread pool. - */ -public interface ChannelFutureListener extends GenericFutureListener { - - /** - * A {@link ChannelFutureListener} that closes the {@link Channel} which is - * associated with the specified {@link ChannelFuture}. - */ - ChannelFutureListener CLOSE = new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - future.channel().close(); - } - }; - - /** - * A {@link ChannelFutureListener} that closes the {@link Channel} when the - * operation ended up with a failure or cancellation rather than a success. - */ - ChannelFutureListener CLOSE_ON_FAILURE = new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - if (!future.isSuccess()) { - future.channel().close(); - } - } - }; - - /** - * A {@link ChannelFutureListener} that forwards the {@link Throwable} of the {@link ChannelFuture} into the - * {@link ChannelPipeline}. This mimics the old behavior of Netty 3. - */ - ChannelFutureListener FIRE_EXCEPTION_ON_FAILURE = new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) { - if (!future.isSuccess()) { - future.channel().pipeline().fireExceptionCaught(future.cause()); - } - } - }; - - // Just a type alias -} diff --git a/common/src/main/java/common/net/channel/ChannelHandler.java b/common/src/main/java/common/net/channel/ChannelHandler.java deleted file mode 100644 index 4b78cde..0000000 --- a/common/src/main/java/common/net/channel/ChannelHandler.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Handles or intercepts a {@link ChannelInboundInvoker} or {@link ChannelOutboundInvoker} operation, and forwards it - * to the next handler in a {@link ChannelPipeline}. - * - *

Sub-types

- *

- * {@link ChannelHandler} itself does not provide many methods. To handle a - * a {@link ChannelInboundInvoker} or {@link ChannelOutboundInvoker} operation - * you need to implement its sub-interfaces. There are many different sub-interfaces - * which handles inbound and outbound operations. - * - * But the most useful for developers may be: - *

    - *
  • {@link ChannelInboundHandlerAdapter} handles and intercepts inbound operations
  • - *
  • {@link ChannelOutboundHandlerAdapter} handles and intercepts outbound operations
  • - *
- * - * You will also find more detailed explanation from the documentation of - * each sub-interface on how an event is interpreted when it goes upstream and - * downstream respectively. - * - *

The context object

- *

- * A {@link ChannelHandler} is provided with a {@link ChannelHandlerContext} - * object. A {@link ChannelHandler} is supposed to interact with the - * {@link ChannelPipeline} it belongs to via a context object. Using the - * context object, the {@link ChannelHandler} can pass events upstream or - * downstream, modify the pipeline dynamically, or store the information - * (using {@link AttributeKey}s) which is specific to the handler. - * - *

State management

- * - * A {@link ChannelHandler} often needs to store some stateful information. - * The simplest and recommended approach is to use member variables: - *
- * public interface Message {
- *     // your methods here
- * }
- *
- * public class DataServerHandler extends {@link SimpleChannelInboundHandler}<Message> {
- *
- *     private boolean loggedIn;
- *
- *     {@code @Override}
- *     public void channelRead0({@link ChannelHandlerContext} ctx, Message message) {
- *         {@link Channel} ch = e.getChannel();
- *         if (message instanceof LoginMessage) {
- *             authenticate((LoginMessage) message);
- *             loggedIn = true;
- *         } else (message instanceof GetDataMessage) {
- *             if (loggedIn) {
- *                 ch.write(fetchSecret((GetDataMessage) message));
- *             } else {
- *                 fail();
- *             }
- *         }
- *     }
- *     ...
- * }
- * 
- * Because the handler instance has a state variable which is dedicated to - * one connection, you have to create a new handler instance for each new - * channel to avoid a race condition where a unauthenticated client can get - * the confidential information: - *
- * // Create a new handler instance per channel.
- * // See {@link ChannelInitializer#initChannel(Channel)}.
- * public class DataServerInitializer extends {@link ChannelInitializer}<{@link Channel}> {
- *     {@code @Override}
- *     public void initChannel({@link Channel} channel) {
- *         channel.pipeline().addLast("handler", new DataServerHandler());
- *     }
- * }
- *
- * 
- * - *

Using {@link AttributeKey}

- * - * Although it's recommended to use member variables to store the state of a - * handler, for some reason you might not want to create many handler instances. - * In such a case, you can use {@link AttributeKey}s which is provided by - * {@link ChannelHandlerContext}: - *
- * public interface Message {
- *     // your methods here
- * }
- *
- * {@code @Sharable}
- * public class DataServerHandler extends {@link SimpleChannelInboundHandler}<Message> {
- *     private final {@link AttributeKey}<{@link Boolean}> auth =
- *           {@link AttributeKey#valueOf(String) AttributeKey.valueOf("auth")};
- *
- *     {@code @Override}
- *     public void channelRead({@link ChannelHandlerContext} ctx, Message message) {
- *         {@link Attribute}<{@link Boolean}> attr = ctx.attr(auth);
- *         {@link Channel} ch = ctx.channel();
- *         if (message instanceof LoginMessage) {
- *             authenticate((LoginMessage) o);
- *             attr.set(true);
- *         } else (message instanceof GetDataMessage) {
- *             if (Boolean.TRUE.equals(attr.get())) {
- *                 ch.write(fetchSecret((GetDataMessage) o));
- *             } else {
- *                 fail();
- *             }
- *         }
- *     }
- *     ...
- * }
- * 
- * Now that the state of the handler isattached to the {@link ChannelHandlerContext}, you can add the - * same handler instance to different pipelines: - *
- * public class DataServerInitializer extends {@link ChannelInitializer}<{@link Channel}> {
- *
- *     private static final DataServerHandler SHARED = new DataServerHandler();
- *
- *     {@code @Override}
- *     public void initChannel({@link Channel} channel) {
- *         channel.pipeline().addLast("handler", SHARED);
- *     }
- * }
- * 
- * - * - *

The {@code @Sharable} annotation

- *

- * In the example above which used an {@link AttributeKey}, - * you might have noticed the {@code @Sharable} annotation. - *

- * If a {@link ChannelHandler} is annotated with the {@code @Sharable} - * annotation, it means you can create an instance of the handler just once and - * add it to one or more {@link ChannelPipeline}s multiple times without - * a race condition. - *

- * If this annotation is not specified, you have to create a new handler - * instance every time you add it to a pipeline because it has unshared state - * such as member variables. - *

- * This annotation is provided for documentation purpose, just like - * the JCIP annotations. - * - *

Additional resources worth reading

- *

- * Please refer to the {@link ChannelHandler}, and - * {@link ChannelPipeline} to find out more about inbound and outbound operations, - * what fundamental differences they have, how they flow in a pipeline, and how to handle - * the operation in your application. - */ -public interface ChannelHandler { - - /** - * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. - */ - void handlerAdded(ChannelHandlerContext ctx) throws Exception; - - /** - * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events - * anymore. - */ - void handlerRemoved(ChannelHandlerContext ctx) throws Exception; - - /** - * Gets called if a {@link Throwable} was thrown. - */ - void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception; - - /** - * Indicates that the same instance of the annotated {@link ChannelHandler} - * can be added to one or more {@link ChannelPipeline}s multiple times - * without a race condition. - *

- * If this annotation is not specified, you have to create a new handler - * instance every time you add it to a pipeline because it has unshared - * state such as member variables. - *

- * This annotation is provided for documentation purpose, just like - * the JCIP annotations. - */ - @Inherited - @Documented - @Target(ElementType.TYPE) - @Retention(RetentionPolicy.RUNTIME) - @interface Sharable { - // no value - } -} diff --git a/common/src/main/java/common/net/channel/ChannelHandlerAdapter.java b/common/src/main/java/common/net/channel/ChannelHandlerAdapter.java deleted file mode 100644 index 7137333..0000000 --- a/common/src/main/java/common/net/channel/ChannelHandlerAdapter.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.channel; - -import java.util.Map; - -import common.net.util.internal.InternalThreadLocalMap; - -/** - * Skelton implementation of a {@link ChannelHandler}. - */ -public abstract class ChannelHandlerAdapter implements ChannelHandler { - - // Not using volatile because it's used only for a sanity check. - boolean added; - - /** - * Return {@code true} if the implementation is {@link Sharable} and so can be added - * to different {@link ChannelPipeline}s. - */ - public boolean isSharable() { - /** - * Cache the result of {@link Sharable} annotation detection to workaround a condition. We use a - * {@link ThreadLocal} and {@link WeakHashMap} to eliminate the volatile write/reads. Using different - * {@link WeakHashMap} instances per {@link Thread} is good enough for us and the number of - * {@link Thread}s are quite limited anyway. - * - * See #2289. - */ - Class clazz = getClass(); - Map, Boolean> cache = InternalThreadLocalMap.get().handlerSharableCache(); - Boolean sharable = cache.get(clazz); - if (sharable == null) { - sharable = clazz.isAnnotationPresent(Sharable.class); - cache.put(clazz, sharable); - } - return sharable; - } - - /** - * Do nothing by default, sub-classes may override this method. - */ - @Override - public void handlerAdded(ChannelHandlerContext ctx) throws Exception { - // NOOP - } - - /** - * Do nothing by default, sub-classes may override this method. - */ - @Override - public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { - // NOOP - } - - /** - * Calls {@link ChannelHandlerContext#fireExceptionCaught(Throwable)} to forward - * to the next {@link ChannelHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - ctx.fireExceptionCaught(cause); - } -} diff --git a/common/src/main/java/common/net/channel/ChannelHandlerContext.java b/common/src/main/java/common/net/channel/ChannelHandlerContext.java deleted file mode 100644 index 81da8c7..0000000 --- a/common/src/main/java/common/net/channel/ChannelHandlerContext.java +++ /dev/null @@ -1,489 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - - -import java.net.SocketAddress; - -import common.net.buffer.ByteBufAllocator; -import common.net.util.AttributeMap; -import common.net.util.concurrent.EventExecutor; - -/** - * Enables a {@link ChannelHandler} to interact with its {@link ChannelPipeline} - * and other handlers. A handler can notify the next {@link ChannelHandler} in the {@link ChannelPipeline}, - * modify the {@link ChannelPipeline} it belongs to dynamically. - * - *

Notify

- * - * You can notify the closest handler in the - * same {@link ChannelPipeline} by calling one of the various methods provided here. - * Please refer to {@link ChannelPipeline} to understand how an event flows. - * - *

Modifying a pipeline

- * - * You can get the {@link ChannelPipeline} your handler belongs to by calling - * {@link #pipeline()}. A non-trivial application could insert, remove, or - * replace handlers in the pipeline dynamically at runtime. - * - *

Retrieving for later use

- * - * You can keep the {@link ChannelHandlerContext} for later use, such as - * triggering an event outside the handler methods, even from a different thread. - *
- * public class MyHandler extends {@link ChannelDuplexHandler} {
- *
- *     private {@link ChannelHandlerContext} ctx;
- *
- *     public void beforeAdd({@link ChannelHandlerContext} ctx) {
- *         this.ctx = ctx;
- *     }
- *
- *     public void login(String username, password) {
- *         ctx.write(new LoginMessage(username, password));
- *     }
- *     ...
- * }
- * 
- * - *

Storing stateful information

- * - * {@link #attr(AttributeKey)} allow you to - * store and access stateful information that is related with a handler and its - * context. Please refer to {@link ChannelHandler} to learn various recommended - * ways to manage stateful information. - * - *

A handler can have more than one context

- * - * Please note that a {@link ChannelHandler} instance can be added to more than - * one {@link ChannelPipeline}. It means a single {@link ChannelHandler} - * instance can have more than one {@link ChannelHandlerContext} and therefore - * the single instance can be invoked with different - * {@link ChannelHandlerContext}s if it is added to one or more - * {@link ChannelPipeline}s more than once. - *

- * For example, the following handler will have as many independent {@link AttributeKey}s - * as how many times it is added to pipelines, regardless if it is added to the - * same pipeline multiple times or added to different pipelines multiple times: - *

- * public class FactorialHandler extends {@link ChannelInboundHandlerAdapter}<{@link Integer}> {
- *
- *   private final {@link AttributeKey}<{@link Integer}> counter =
- *           new {@link AttributeKey}<{@link Integer}>("counter");
- *
- *   // This handler will receive a sequence of increasing integers starting
- *   // from 1.
- *   {@code @Override}
- *   public void channelRead({@link ChannelHandlerContext} ctx, {@link Integer} integer) {
- *     {@link Attribute}<{@link Integer}> attr = ctx.getAttr(counter);
- *     Integer a = ctx.getAttr(counter).get();
- *
- *     if (a == null) {
- *       a = 1;
- *     }
- *
- *     attr.set(a * integer));
- *   }
- * }
- *
- * // Different context objects are given to "f1", "f2", "f3", and "f4" even if
- * // they refer to the same handler instance.  Because the FactorialHandler
- * // stores its state in a context object (as an (using an {@link AttributeKey}), the factorial is
- * // calculated correctly 4 times once the two pipelines (p1 and p2) are active.
- * FactorialHandler fh = new FactorialHandler();
- *
- * {@link ChannelPipeline} p1 = {@link Channels}.pipeline();
- * p1.addLast("f1", fh);
- * p1.addLast("f2", fh);
- *
- * {@link ChannelPipeline} p2 = {@link Channels}.pipeline();
- * p2.addLast("f3", fh);
- * p2.addLast("f4", fh);
- * 
- * - *

Additional resources worth reading

- *

- * Please refer to the {@link ChannelHandler}, and - * {@link ChannelPipeline} to find out more about inbound and outbound operations, - * what fundamental differences they have, how they flow in a pipeline, and how to handle - * the operation in your application. - */ -public interface ChannelHandlerContext - extends AttributeMap { - - /** - * Return the {@link Channel} which is bound to the {@link ChannelHandlerContext}. - */ - Channel channel(); - - /** - * The {@link EventExecutor} that is used to dispatch the events. This can also be used to directly - * submit tasks that get executed in the event loop. For more information please refer to the - * {@link EventExecutor} javadoc. - */ - EventExecutor executor(); - - /** - * The unique name of the {@link ChannelHandlerContext}.The name was used when then {@link ChannelHandler} - * was added to the {@link ChannelPipeline}. This name can also be used to access the registered - * {@link ChannelHandler} from the {@link ChannelPipeline}. - */ - String name(); - - /** - * The {@link ChannelHandler} that is bound this {@link ChannelHandlerContext}. - */ - ChannelHandler handler(); - - /** - * Return {@code true} if the {@link ChannelHandler} which belongs to this {@link ChannelHandler} was removed - * from the {@link ChannelPipeline}. Note that this method is only meant to be called from with in the - * {@link EventLoop}. - */ - boolean isRemoved(); - - /** - * A {@link Channel} was registered to its {@link EventLoop}. - * - * This will result in having the {@link ChannelInboundHandler#channelRegistered(ChannelHandlerContext)} method - * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelHandlerContext fireChannelRegistered(); - - /** - * A {@link Channel} was unregistered from its {@link EventLoop}. - * - * This will result in having the {@link ChannelInboundHandler#channelUnregistered(ChannelHandlerContext)} method - * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelHandlerContext fireChannelUnregistered(); - - /** - * A {@link Channel} is active now, which means it is connected. - * - * This will result in having the {@link ChannelInboundHandler#channelActive(ChannelHandlerContext)} method - * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelHandlerContext fireChannelActive(); - - /** - * A {@link Channel} is inactive now, which means it is closed. - * - * This will result in having the {@link ChannelInboundHandler#channelInactive(ChannelHandlerContext)} method - * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelHandlerContext fireChannelInactive(); - - /** - * A {@link Channel} received an {@link Throwable} in one of its inbound operations. - * - * This will result in having the {@link ChannelInboundHandler#exceptionCaught(ChannelHandlerContext, Throwable)} - * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelHandlerContext fireExceptionCaught(Throwable cause); - - /** - * A {@link Channel} received an user defined event. - * - * This will result in having the {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)} - * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelHandlerContext fireUserEventTriggered(Object event); - - /** - * A {@link Channel} received a message. - * - * This will result in having the {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)} - * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelHandlerContext fireChannelRead(Object msg); - - /** - * Triggers an {@link ChannelInboundHandler#channelWritabilityChanged(ChannelHandlerContext)} - * event to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - */ - ChannelHandlerContext fireChannelReadComplete(); - - /** - * Triggers an {@link ChannelInboundHandler#channelWritabilityChanged(ChannelHandlerContext)} - * event to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - */ - ChannelHandlerContext fireChannelWritabilityChanged(); - - /** - * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method - * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture bind(SocketAddress localAddress); - - /** - * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - *

- * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with - * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} - * will be used. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress); - - /** - * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the - * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of - * an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress); - - /** - * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, - * either because the operation was successful or because of an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture disconnect(); - - /** - * Request to close the {@link Channel} and notify the {@link ChannelFuture} once the operation completes, - * either because the operation was successful or because of - * an error. - * - * After it is closed it is not possible to reuse it again. - *

- * This will result in having the - * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture close(); - - /** - * Request to deregister from the previous assigned {@link EventExecutor} and notify the - * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of - * an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - * - */ - ChannelFuture deregister(); - - /** - * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - * - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method - * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise); - - /** - * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - * - * The given {@link ChannelFuture} will be notified. - * - *

- * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with - * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} - * will be used. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise); - - /** - * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the - * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of - * an error. - * - * The given {@link ChannelPromise} will be notified and also returned. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise); - - /** - * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, - * either because the operation was successful or because of an error. - * - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture disconnect(ChannelPromise promise); - - /** - * Request to close the {@link Channel} and notify the {@link ChannelFuture} once the operation completes, - * either because the operation was successful or because of - * an error. - * - * After it is closed it is not possible to reuse it again. - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture close(ChannelPromise promise); - - /** - * Request to deregister from the previous assigned {@link EventExecutor} and notify the - * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of - * an error. - * - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture deregister(ChannelPromise promise); - - /** - * Request to Read data from the {@link Channel} into the first inbound buffer, triggers an - * {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)} event if data was - * read, and triggers a - * {@link ChannelInboundHandler#channelReadComplete(ChannelHandlerContext) channelReadComplete} event so the - * handler can decide to continue reading. If there's a pending read operation already, this method does nothing. - *

- * This will result in having the - * {@link ChannelOutboundHandler#read(ChannelHandlerContext)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelHandlerContext read(); - - /** - * Request to write a message via this {@link ChannelHandlerContext} through the {@link ChannelPipeline}. - * This method will not request to actual flush, so be sure to call {@link #flush()} - * once you want to request to flush all pending data to the actual transport. - */ - ChannelFuture write(Object msg); - - /** - * Request to write a message via this {@link ChannelHandlerContext} through the {@link ChannelPipeline}. - * This method will not request to actual flush, so be sure to call {@link #flush()} - * once you want to request to flush all pending data to the actual transport. - */ - ChannelFuture write(Object msg, ChannelPromise promise); - - /** - * Request to flush all pending messages via this ChannelOutboundInvoker. - */ - ChannelHandlerContext flush(); - - /** - * Shortcut for call {@link #write(Object, ChannelPromise)} and {@link #flush()}. - */ - ChannelFuture writeAndFlush(Object msg, ChannelPromise promise); - - /** - * Shortcut for call {@link #write(Object)} and {@link #flush()}. - */ - ChannelFuture writeAndFlush(Object msg); - - /** - * Return the assigned {@link ChannelPipeline} - */ - ChannelPipeline pipeline(); - - /** - * Return the assigned {@link ByteBufAllocator} which will be used to allocate {@link ByteBuf}s. - */ - ByteBufAllocator alloc(); - - /** - * Return a new {@link ChannelPromise}. - */ - ChannelPromise newPromise(); - - /** - * Return an new {@link ChannelProgressivePromise} - */ -// ChannelProgressivePromise newProgressivePromise(); - - /** - * Create a new {@link ChannelFuture} which is marked as succeeded already. So {@link ChannelFuture#isSuccess()} - * will return {@code true}. All {@link FutureListener} added to it will be notified directly. Also - * every call of blocking methods will just return without blocking. - */ - ChannelFuture newSucceededFuture(); - - /** - * Create a new {@link ChannelFuture} which is marked as failed already. So {@link ChannelFuture#isSuccess()} - * will return {@code false}. All {@link FutureListener} added to it will be notified directly. Also - * every call of blocking methods will just return without blocking. - */ - ChannelFuture newFailedFuture(Throwable cause); - - /** - * Return a special ChannelPromise which can be reused for different operations. - *

- * It's only supported to use - * it for {@link ChannelHandlerContext#write(Object, ChannelPromise)}. - *

- *

- * Be aware that the returned {@link ChannelPromise} will not support most operations and should only be used - * if you want to save an object allocation for every write operation. You will not be able to detect if the - * operation was complete, only if it failed as the implementation will call - * {@link ChannelPipeline#fireExceptionCaught(Throwable)} in this case. - *

- * Be aware this is an expert feature and should be used with care! - */ - ChannelPromise voidPromise(); - -} diff --git a/common/src/main/java/common/net/channel/ChannelInboundHandler.java b/common/src/main/java/common/net/channel/ChannelInboundHandler.java deleted file mode 100644 index 97c9691..0000000 --- a/common/src/main/java/common/net/channel/ChannelInboundHandler.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -/** - * {@link ChannelHandler} which adds callbacks for state changes. This allows the user - * to hook in to state changes easily. - */ -public interface ChannelInboundHandler extends ChannelHandler { - - /** - * The {@link Channel} of the {@link ChannelHandlerContext} was registered with its {@link EventLoop} - */ - void channelRegistered(ChannelHandlerContext ctx) throws Exception; - - /** - * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} - */ - void channelUnregistered(ChannelHandlerContext ctx) throws Exception; - - /** - * The {@link Channel} of the {@link ChannelHandlerContext} is now active - */ - void channelActive(ChannelHandlerContext ctx) throws Exception; - - /** - * The {@link Channel} of the {@link ChannelHandlerContext} was registered is now inactive and reached its - * end of lifetime. - */ - void channelInactive(ChannelHandlerContext ctx) throws Exception; - - /** - * Invoked when the current {@link Channel} has read a message from the peer. - */ - void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception; - - /** - * Invoked when the last message read by the current read operation has been consumed by - * {@link #channelRead(ChannelHandlerContext, Object)}. If {@link ChannelOption#AUTO_READ} is off, no further - * attempt to read an inbound data from the current {@link Channel} will be made until - * {@link ChannelHandlerContext#read()} is called. - */ - void channelReadComplete(ChannelHandlerContext ctx) throws Exception; - - /** - * Gets called if an user event was triggered. - */ - void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception; - - /** - * Gets called once the writable state of a {@link Channel} changed. You can check the state with - * {@link Channel#isWritable()}. - */ - void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception; - - /** - * Gets called if a {@link Throwable} was thrown. - */ - @Override - void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception; -} diff --git a/common/src/main/java/common/net/channel/ChannelInboundHandlerAdapter.java b/common/src/main/java/common/net/channel/ChannelInboundHandlerAdapter.java deleted file mode 100644 index 7f6e8a2..0000000 --- a/common/src/main/java/common/net/channel/ChannelInboundHandlerAdapter.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -/** - * Abstract base class for {@link ChannelInboundHandler} implementations which provide - * implementations of all of their methods. - * - *

- * This implementation just forward the operation to the next {@link ChannelHandler} in the - * {@link ChannelPipeline}. Sub-classes may override a method implementation to change this. - *

- *

- * Be aware that messages are not released after the {@link #channelRead(ChannelHandlerContext, Object)} - * method returns automatically. If you are looking for a {@link ChannelInboundHandler} implementation that - * releases the received messages automatically, please see {@link SimpleChannelInboundHandler}. - *

- */ -public class ChannelInboundHandlerAdapter extends ChannelHandlerAdapter implements ChannelInboundHandler { - - /** - * Calls {@link ChannelHandlerContext#fireChannelRegistered()} to forward - * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void channelRegistered(ChannelHandlerContext ctx) throws Exception { - ctx.fireChannelRegistered(); - } - - /** - * Calls {@link ChannelHandlerContext#fireChannelUnregistered()} to forward - * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { - ctx.fireChannelUnregistered(); - } - - /** - * Calls {@link ChannelHandlerContext#fireChannelActive()} to forward - * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - ctx.fireChannelActive(); - } - - /** - * Calls {@link ChannelHandlerContext#fireChannelInactive()} to forward - * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { - ctx.fireChannelInactive(); - } - - /** - * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward - * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - ctx.fireChannelRead(msg); - } - - /** - * Calls {@link ChannelHandlerContext#fireChannelReadComplete()} to forward - * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { - ctx.fireChannelReadComplete(); - } - - /** - * Calls {@link ChannelHandlerContext#fireUserEventTriggered(Object)} to forward - * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { - ctx.fireUserEventTriggered(evt); - } - - /** - * Calls {@link ChannelHandlerContext#fireChannelWritabilityChanged()} to forward - * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { - ctx.fireChannelWritabilityChanged(); - } - - /** - * Calls {@link ChannelHandlerContext#fireExceptionCaught(Throwable)} to forward - * to the next {@link ChannelHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) - throws Exception { - ctx.fireExceptionCaught(cause); - } -} diff --git a/common/src/main/java/common/net/channel/ChannelInitializer.java b/common/src/main/java/common/net/channel/ChannelInitializer.java deleted file mode 100644 index 31ad3ab..0000000 --- a/common/src/main/java/common/net/channel/ChannelInitializer.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.channel.ChannelHandler.Sharable; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * A special {@link ChannelInboundHandler} which offers an easy way to initialize a {@link Channel} once it was - * registered to its {@link EventLoop}. - * - * Implementations are most often used in the context of {@link Bootstrap#handler(ChannelHandler)} , - * {@link ServerBootstrap#handler(ChannelHandler)} and {@link ServerBootstrap#childHandler(ChannelHandler)} to - * setup the {@link ChannelPipeline} of a {@link Channel}. - * - *
- *
- * public class MyChannelInitializer extends {@link ChannelInitializer} {
- *     public void initChannel({@link Channel} channel) {
- *         channel.pipeline().addLast("myHandler", new MyHandler());
- *     }
- * }
- *
- * {@link ServerBootstrap} bootstrap = ...;
- * ...
- * bootstrap.childHandler(new MyChannelInitializer());
- * ...
- * 
- * Be aware that this class is marked as {@link Sharable} and so the implementation must be safe to be re-used. - * - * @param A sub-type of {@link Channel} - */ -@Sharable -public abstract class ChannelInitializer extends ChannelInboundHandlerAdapter { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(ChannelInitializer.class); - - /** - * This method will be called once the {@link Channel} was registered. After the method returns this instance - * will be removed from the {@link ChannelPipeline} of the {@link Channel}. - * - * @param ch the {@link Channel} which was registered. - * @throws Exception is thrown if an error occurs. In that case the {@link Channel} will be closed. - */ - protected abstract void initChannel(C ch) throws Exception; - - @Override - - public final void channelRegistered(ChannelHandlerContext ctx) throws Exception { - ChannelPipeline pipeline = ctx.pipeline(); - boolean success = false; - try { - initChannel((C) ctx.channel()); - pipeline.remove(this); - ctx.fireChannelRegistered(); - success = true; - } catch (Throwable t) { - logger.warn("Failed to initialize a channel. Closing: " + ctx.channel(), t); - } finally { - if (pipeline.context(this) != null) { - pipeline.remove(this); - } - if (!success) { - ctx.close(); - } - } - } -} diff --git a/common/src/main/java/common/net/channel/ChannelMetadata.java b/common/src/main/java/common/net/channel/ChannelMetadata.java deleted file mode 100644 index 375acb9..0000000 --- a/common/src/main/java/common/net/channel/ChannelMetadata.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -/** - * Represents the properties of a {@link Channel} implementation. - */ -public final class ChannelMetadata { - - private final boolean hasDisconnect; - - /** - * Create a new instance - * - * @param hasDisconnect {@code true} if and only if the channel has the {@code disconnect()} operation - * that allows a user to disconnect and then call {@link Channel#connect(SocketAddress)} - * again, such as UDP/IP. - */ - public ChannelMetadata(boolean hasDisconnect) { - this.hasDisconnect = hasDisconnect; - } - - /** - * Returns {@code true} if and only if the channel has the {@code disconnect()} operation - * that allows a user to disconnect and then call {@link Channel#connect(SocketAddress)} again, - * such as UDP/IP. - */ - public boolean hasDisconnect() { - return hasDisconnect; - } -} diff --git a/common/src/main/java/common/net/channel/ChannelOption.java b/common/src/main/java/common/net/channel/ChannelOption.java deleted file mode 100644 index 629d2fe..0000000 --- a/common/src/main/java/common/net/channel/ChannelOption.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import common.net.buffer.ByteBufAllocator; -import common.net.util.UniqueName; - -/** - * A {@link ChannelOption} allows to configure a {@link ChannelConfig} in a type-safe - * way. Which {@link ChannelOption} is supported depends on the actual implementation - * of {@link ChannelConfig} and may depend on the nature of the transport it belongs - * to. - * - * @param the type of the value which is valid for the {@link ChannelOption} - */ - -public class ChannelOption extends UniqueName { - - private static final ConcurrentMap names = new ConcurrentHashMap(); - - public static final ChannelOption ALLOCATOR = valueOf("ALLOCATOR"); - public static final ChannelOption RCVBUF_ALLOCATOR = valueOf("RCVBUF_ALLOCATOR"); - public static final ChannelOption MESSAGE_SIZE_ESTIMATOR = valueOf("MESSAGE_SIZE_ESTIMATOR"); - - public static final ChannelOption CONNECT_TIMEOUT_MILLIS = valueOf("CONNECT_TIMEOUT_MILLIS"); - public static final ChannelOption MAX_MESSAGES_PER_READ = valueOf("MAX_MESSAGES_PER_READ"); - public static final ChannelOption WRITE_SPIN_COUNT = valueOf("WRITE_SPIN_COUNT"); - public static final ChannelOption WRITE_BUFFER_HIGH_WATER_MARK = valueOf("WRITE_BUFFER_HIGH_WATER_MARK"); - public static final ChannelOption WRITE_BUFFER_LOW_WATER_MARK = valueOf("WRITE_BUFFER_LOW_WATER_MARK"); - - public static final ChannelOption ALLOW_HALF_CLOSURE = valueOf("ALLOW_HALF_CLOSURE"); - public static final ChannelOption AUTO_READ = valueOf("AUTO_READ"); - - public static final ChannelOption SO_BROADCAST = valueOf("SO_BROADCAST"); - public static final ChannelOption SO_KEEPALIVE = valueOf("SO_KEEPALIVE"); - public static final ChannelOption SO_SNDBUF = valueOf("SO_SNDBUF"); - public static final ChannelOption SO_RCVBUF = valueOf("SO_RCVBUF"); - public static final ChannelOption SO_REUSEADDR = valueOf("SO_REUSEADDR"); - public static final ChannelOption SO_LINGER = valueOf("SO_LINGER"); - public static final ChannelOption SO_BACKLOG = valueOf("SO_BACKLOG"); - public static final ChannelOption SO_TIMEOUT = valueOf("SO_TIMEOUT"); - - public static final ChannelOption IP_TOS = valueOf("IP_TOS"); - public static final ChannelOption IP_MULTICAST_ADDR = valueOf("IP_MULTICAST_ADDR"); - public static final ChannelOption IP_MULTICAST_IF = valueOf("IP_MULTICAST_IF"); - public static final ChannelOption IP_MULTICAST_TTL = valueOf("IP_MULTICAST_TTL"); - public static final ChannelOption IP_MULTICAST_LOOP_DISABLED = valueOf("IP_MULTICAST_LOOP_DISABLED"); - - public static final ChannelOption TCP_NODELAY = valueOf("TCP_NODELAY"); - - /** - * Creates a new {@link ChannelOption} with the specified {@code name}. - */ - public static ChannelOption valueOf(String name) { - return new ChannelOption(name); - } - - private ChannelOption(String name) { - super(names, name); - } - - /** - * Validate the value which is set for the {@link ChannelOption}. Sub-classes - * may override this for special checks. - */ - public void validate(T value) { - if (value == null) { - throw new NullPointerException("value"); - } - } -} diff --git a/common/src/main/java/common/net/channel/ChannelOutboundBuffer.java b/common/src/main/java/common/net/channel/ChannelOutboundBuffer.java deleted file mode 100644 index e362114..0000000 --- a/common/src/main/java/common/net/channel/ChannelOutboundBuffer.java +++ /dev/null @@ -1,644 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.nio.ByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; -import java.util.concurrent.atomic.AtomicLongFieldUpdater; - -import common.net.buffer.ByteBuf; -import common.net.buffer.Unpooled; -import common.net.util.Recycler; -import common.net.util.ReferenceCountUtil; -import common.net.util.Recycler.Handle; -import common.net.util.concurrent.FastThreadLocal; -import common.net.util.internal.InternalThreadLocalMap; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * (Transport implementors only) an internal data structure used by {@link AbstractChannel} to store its pending - * outbound write requests. - * - * All the methods should only be called by the {@link EventLoop} of the {@link Channel}. - */ -public final class ChannelOutboundBuffer { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(ChannelOutboundBuffer.class); - - private static final FastThreadLocal NIO_BUFFERS = new FastThreadLocal() { - @Override - protected ByteBuffer[] initialValue() throws Exception { - return new ByteBuffer[1024]; - } - }; - - private final Channel channel; - - // Entry(flushedEntry) --> ... Entry(unflushedEntry) --> ... Entry(tailEntry) - // - // The Entry that is the first in the linked-list structure that was flushed - private Entry flushedEntry; - // The Entry which is the first unflushed in the linked-list structure - private Entry unflushedEntry; - // The Entry which represents the tail of the buffer - private Entry tailEntry; - // The number of flushed entries that are not written yet - private int flushed; - - private int nioBufferCount; - private long nioBufferSize; - - private boolean inFail; - - private static final AtomicLongFieldUpdater TOTAL_PENDING_SIZE_UPDATER; - - - private volatile long totalPendingSize; - - private static final AtomicIntegerFieldUpdater WRITABLE_UPDATER; - - - private volatile int writable = 1; - - static { - AtomicIntegerFieldUpdater writableUpdater = - null; - if (writableUpdater == null) { - writableUpdater = AtomicIntegerFieldUpdater.newUpdater(ChannelOutboundBuffer.class, "writable"); - } - WRITABLE_UPDATER = writableUpdater; - - AtomicLongFieldUpdater pendingSizeUpdater = - null; - if (pendingSizeUpdater == null) { - pendingSizeUpdater = AtomicLongFieldUpdater.newUpdater(ChannelOutboundBuffer.class, "totalPendingSize"); - } - TOTAL_PENDING_SIZE_UPDATER = pendingSizeUpdater; - } - - ChannelOutboundBuffer(AbstractChannel channel) { - this.channel = channel; - } - - /** - * Add given message to this {@link ChannelOutboundBuffer}. The given {@link ChannelPromise} will be notified once - * the message was written. - */ - public void addMessage(Object msg, int size, ChannelPromise promise) { - Entry entry = Entry.newInstance(msg, size, total(msg), promise); - if (tailEntry == null) { - flushedEntry = null; - tailEntry = entry; - } else { - Entry tail = tailEntry; - tail.next = entry; - tailEntry = entry; - } - if (unflushedEntry == null) { - unflushedEntry = entry; - } - - // increment pending bytes after adding message to the unflushed arrays. - // See https://github.com/netty/netty/issues/1619 - incrementPendingOutboundBytes(size); - } - - /** - * Add a flush to this {@link ChannelOutboundBuffer}. This means all previous added messages are marked as flushed - * and so you will be able to handle them. - */ - public void addFlush() { - // There is no need to process all entries if there was already a flush before and no new messages - // where added in the meantime. - // - // See https://github.com/netty/netty/issues/2577 - Entry entry = unflushedEntry; - if (entry != null) { - if (flushedEntry == null) { - // there is no flushedEntry yet, so start with the entry - flushedEntry = entry; - } - do { - flushed ++; - if (!entry.promise.setUncancellable()) { - // Was cancelled so make sure we free up memory and notify about the freed bytes - int pending = entry.cancel(); - decrementPendingOutboundBytes(pending); - } - entry = entry.next; - } while (entry != null); - - // All flushed so reset unflushedEntry - unflushedEntry = null; - } - } - - /** - * Increment the pending bytes which will be written at some point. - * This method is thread-safe! - */ - void incrementPendingOutboundBytes(long size) { - if (size == 0) { - return; - } - - long newWriteBufferSize = TOTAL_PENDING_SIZE_UPDATER.addAndGet(this, size); - if (newWriteBufferSize > channel.config().getWriteBufferHighWaterMark()) { - if (WRITABLE_UPDATER.compareAndSet(this, 1, 0)) { - channel.pipeline().fireChannelWritabilityChanged(); - } - } - } - - /** - * Decrement the pending bytes which will be written at some point. - * This method is thread-safe! - */ - void decrementPendingOutboundBytes(long size) { - if (size == 0) { - return; - } - - long newWriteBufferSize = TOTAL_PENDING_SIZE_UPDATER.addAndGet(this, -size); - if (newWriteBufferSize == 0 || newWriteBufferSize < channel.config().getWriteBufferLowWaterMark()) { - if (WRITABLE_UPDATER.compareAndSet(this, 0, 1)) { - channel.pipeline().fireChannelWritabilityChanged(); - } - } - } - - private static long total(Object msg) { - if (msg instanceof ByteBuf) { - return ((ByteBuf) msg).readableBytes(); - } -// if (msg instanceof FileRegion) { -// return ((FileRegion) msg).count(); -// } -// if (msg instanceof ByteBufHolder) { -// return ((ByteBufHolder) msg).content().readableBytes(); -// } - return -1; - } - - /** - * Return the current message to write or {@code null} if nothing was flushed before and so is ready to be written. - */ - public Object current() { - Entry entry = flushedEntry; - if (entry == null) { - return null; - } - - return entry.msg; - } - - /** - * Notify the {@link ChannelPromise} of the current message about writing progress. - */ - public void progress(long amount) { - Entry e = flushedEntry; - assert e != null; - ChannelPromise p = e.promise; - if (p instanceof ChannelProgressivePromise) { - long progress = e.progress + amount; - e.progress = progress; - ((ChannelProgressivePromise) p).tryProgress(progress, e.total); - } - } - - /** - * Will remove the current message, mark its {@link ChannelPromise} as success and return {@code true}. If no - * flushed message exists at the time this method is called it will return {@code false} to signal that no more - * messages are ready to be handled. - */ - public boolean remove() { - Entry e = flushedEntry; - if (e == null) { - return false; - } - Object msg = e.msg; - - ChannelPromise promise = e.promise; - int size = e.pendingSize; - - removeEntry(e); - - if (!e.cancelled) { - // only release message, notify and decrement if it was not canceled before. - ReferenceCountUtil.safeRelease(msg); - safeSuccess(promise); - decrementPendingOutboundBytes(size); - } - - // recycle the entry - e.recycle(); - - return true; - } - - /** - * Will remove the current message, mark its {@link ChannelPromise} as failure using the given {@link Throwable} - * and return {@code true}. If no flushed message exists at the time this method is called it will return - * {@code false} to signal that no more messages are ready to be handled. - */ - public boolean remove(Throwable cause) { - Entry e = flushedEntry; - if (e == null) { - return false; - } - Object msg = e.msg; - - ChannelPromise promise = e.promise; - int size = e.pendingSize; - - removeEntry(e); - - if (!e.cancelled) { - // only release message, fail and decrement if it was not canceled before. - ReferenceCountUtil.safeRelease(msg); - - safeFail(promise, cause); - decrementPendingOutboundBytes(size); - } - - // recycle the entry - e.recycle(); - - return true; - } - - private void removeEntry(Entry e) { - if (-- flushed == 0) { - // processed everything - flushedEntry = null; - if (e == tailEntry) { - tailEntry = null; - unflushedEntry = null; - } - } else { - flushedEntry = e.next; - } - } - - /** - * Removes the fully written entries and update the reader index of the partially written entry. - * This operation assumes all messages in this buffer is {@link ByteBuf}. - */ - public void removeBytes(long writtenBytes) { - for (;;) { - Object msg = current(); - if (!(msg instanceof ByteBuf)) { - assert writtenBytes == 0; - break; - } - - final ByteBuf buf = (ByteBuf) msg; - final int readerIndex = buf.readerIndex(); - final int readableBytes = buf.writerIndex() - readerIndex; - - if (readableBytes <= writtenBytes) { - if (writtenBytes != 0) { - progress(readableBytes); - writtenBytes -= readableBytes; - } - remove(); - } else { // readableBytes > writtenBytes - if (writtenBytes != 0) { - buf.readerIndex(readerIndex + (int) writtenBytes); - progress(writtenBytes); - } - break; - } - } - } - - /** - * Returns an array of direct NIO buffers if the currently pending messages are made of {@link ByteBuf} only. - * {@link #nioBufferCount()} and {@link #nioBufferSize()} will return the number of NIO buffers in the returned - * array and the total number of readable bytes of the NIO buffers respectively. - *

- * Note that the returned array is reused and thus should not escape - * {@link AbstractChannel#doWrite(ChannelOutboundBuffer)}. - * Refer to {@link NioSocketChannel#doWrite(ChannelOutboundBuffer)} for an example. - *

- */ - public ByteBuffer[] nioBuffers() { - long nioBufferSize = 0; - int nioBufferCount = 0; - final InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.get(); - ByteBuffer[] nioBuffers = NIO_BUFFERS.get(threadLocalMap); - Entry entry = flushedEntry; - while (isFlushedEntry(entry) && entry.msg instanceof ByteBuf) { - if (!entry.cancelled) { - ByteBuf buf = (ByteBuf) entry.msg; - final int readerIndex = buf.readerIndex(); - final int readableBytes = buf.writerIndex() - readerIndex; - - if (readableBytes > 0) { - nioBufferSize += readableBytes; - int count = entry.count; - if (count == -1) { - //noinspection ConstantValueVariableUse - entry.count = count = buf.nioBufferCount(); - } - int neededSpace = nioBufferCount + count; - if (neededSpace > nioBuffers.length) { - nioBuffers = expandNioBufferArray(nioBuffers, neededSpace, nioBufferCount); - NIO_BUFFERS.set(threadLocalMap, nioBuffers); - } - if (count == 1) { - ByteBuffer nioBuf = entry.buf; - if (nioBuf == null) { - // cache ByteBuffer as it may need to create a new ByteBuffer instance if its a - // derived buffer - entry.buf = nioBuf = buf.internalNioBuffer(readerIndex, readableBytes); - } - nioBuffers[nioBufferCount ++] = nioBuf; - } else { - ByteBuffer[] nioBufs = entry.bufs; - if (nioBufs == null) { - // cached ByteBuffers as they may be expensive to create in terms - // of Object allocation - entry.bufs = nioBufs = buf.nioBuffers(); - } - nioBufferCount = fillBufferArray(nioBufs, nioBuffers, nioBufferCount); - } - } - } - entry = entry.next; - } - this.nioBufferCount = nioBufferCount; - this.nioBufferSize = nioBufferSize; - - return nioBuffers; - } - - private static int fillBufferArray(ByteBuffer[] nioBufs, ByteBuffer[] nioBuffers, int nioBufferCount) { - for (ByteBuffer nioBuf: nioBufs) { - if (nioBuf == null) { - break; - } - nioBuffers[nioBufferCount ++] = nioBuf; - } - return nioBufferCount; - } - - private static ByteBuffer[] expandNioBufferArray(ByteBuffer[] array, int neededSpace, int size) { - int newCapacity = array.length; - do { - // double capacity until it is big enough - // See https://github.com/netty/netty/issues/1890 - newCapacity <<= 1; - - if (newCapacity < 0) { - throw new IllegalStateException(); - } - - } while (neededSpace > newCapacity); - - ByteBuffer[] newArray = new ByteBuffer[newCapacity]; - System.arraycopy(array, 0, newArray, 0, size); - - return newArray; - } - - /** - * Returns the number of {@link ByteBuffer} that can be written out of the {@link ByteBuffer} array that was - * obtained via {@link #nioBuffers()}. This method MUST be called after {@link #nioBuffers()} - * was called. - */ - public int nioBufferCount() { - return nioBufferCount; - } - - /** - * Returns the number of bytes that can be written out of the {@link ByteBuffer} array that was - * obtained via {@link #nioBuffers()}. This method MUST be called after {@link #nioBuffers()} - * was called. - */ - public long nioBufferSize() { - return nioBufferSize; - } - - boolean isWritable() { - return writable != 0; - } - - /** - * Returns the number of flushed messages in this {@link ChannelOutboundBuffer}. - */ - public int size() { - return flushed; - } - - /** - * Returns {@code true} if there are flushed messages in this {@link ChannelOutboundBuffer} or {@code false} - * otherwise. - */ - public boolean isEmpty() { - return flushed == 0; - } - - void failFlushed(Throwable cause) { - // Make sure that this method does not reenter. A listener added to the current promise can be notified by the - // current thread in the tryFailure() call of the loop below, and the listener can trigger another fail() call - // indirectly (usually by closing the channel.) - // - // See https://github.com/netty/netty/issues/1501 - if (inFail) { - return; - } - - try { - inFail = true; - for (;;) { - if (!remove(cause)) { - break; - } - } - } finally { - inFail = false; - } - } - - void close(final ClosedChannelException cause) { - if (inFail) { - channel.eventLoop().execute(new Runnable() { - @Override - public void run() { - close(cause); - } - }); - return; - } - - inFail = true; - - if (channel.isOpen()) { - throw new IllegalStateException("close() must be invoked after the channel is closed."); - } - - if (!isEmpty()) { - throw new IllegalStateException("close() must be invoked after all flushed writes are handled."); - } - - // Release all unflushed messages. - try { - Entry e = unflushedEntry; - while (e != null) { - // Just decrease; do not trigger any events via decrementPendingOutboundBytes() - int size = e.pendingSize; - TOTAL_PENDING_SIZE_UPDATER.addAndGet(this, -size); - - if (!e.cancelled) { - ReferenceCountUtil.safeRelease(e.msg); - safeFail(e.promise, cause); - } - e = e.recycleAndGetNext(); - } - } finally { - inFail = false; - } - } - - private static void safeSuccess(ChannelPromise promise) { - if (!(promise instanceof VoidChannelPromise) && !promise.trySuccess()) { - logger.warn("Failed to mark a promise as success because it is done already: {}", promise); - } - } - - private static void safeFail(ChannelPromise promise, Throwable cause) { - if (!(promise instanceof VoidChannelPromise) && !promise.tryFailure(cause)) { - logger.warn("Failed to mark a promise as failure because it's done already: {}", promise, cause); - } - } - - public long totalPendingWriteBytes() { - return totalPendingSize; - } - - /** - * Call {@link MessageProcessor#processMessage(Object)} for each flushed message - * in this {@link ChannelOutboundBuffer} until {@link MessageProcessor#processMessage(Object)} - * returns {@code false} or there are no more flushed messages to process. - */ - public void forEachFlushedMessage(MessageProcessor processor) throws Exception { - if (processor == null) { - throw new NullPointerException("processor"); - } - - Entry entry = flushedEntry; - if (entry == null) { - return; - } - - do { - if (!entry.cancelled) { - if (!processor.processMessage(entry.msg)) { - return; - } - } - entry = entry.next; - } while (isFlushedEntry(entry)); - } - - private boolean isFlushedEntry(Entry e) { - return e != null && e != unflushedEntry; - } - - public interface MessageProcessor { - /** - * Will be called for each flushed message until it either there are no more flushed messages or this - * method returns {@code false}. - */ - boolean processMessage(Object msg) throws Exception; - } - - static final class Entry { - private static final Recycler RECYCLER = new Recycler() { - @Override - protected Entry newObject(Handle handle) { - return new Entry(handle); - } - }; - - private final Handle handle; - Entry next; - Object msg; - ByteBuffer[] bufs; - ByteBuffer buf; - ChannelPromise promise; - long progress; - long total; - int pendingSize; - int count = -1; - boolean cancelled; - - private Entry(Handle handle) { - this.handle = handle; - } - - static Entry newInstance(Object msg, int size, long total, ChannelPromise promise) { - Entry entry = RECYCLER.get(); - entry.msg = msg; - entry.pendingSize = size; - entry.total = total; - entry.promise = promise; - return entry; - } - - int cancel() { - if (!cancelled) { - cancelled = true; - int pSize = pendingSize; - - // release message and replace with an empty buffer - ReferenceCountUtil.safeRelease(msg); - msg = Unpooled.EMPTY_BUFFER; - - pendingSize = 0; - total = 0; - progress = 0; - bufs = null; - buf = null; - return pSize; - } - return 0; - } - - void recycle() { - next = null; - bufs = null; - buf = null; - msg = null; - promise = null; - progress = 0; - total = 0; - pendingSize = 0; - count = -1; - cancelled = false; - RECYCLER.recycle(this, handle); - } - - Entry recycleAndGetNext() { - Entry next = this.next; - recycle(); - return next; - } - } -} diff --git a/common/src/main/java/common/net/channel/ChannelOutboundHandler.java b/common/src/main/java/common/net/channel/ChannelOutboundHandler.java deleted file mode 100644 index 9cce0d7..0000000 --- a/common/src/main/java/common/net/channel/ChannelOutboundHandler.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.net.SocketAddress; - -/** - * {@link ChannelHandler} which will get notified for IO-outbound-operations. - */ -public interface ChannelOutboundHandler extends ChannelHandler { - /** - * Called once a bind operation is made. - * - * @param ctx the {@link ChannelHandlerContext} for which the bind operation is made - * @param localAddress the {@link SocketAddress} to which it should bound - * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error accour - */ - void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception; - - /** - * Called once a connect operation is made. - * - * @param ctx the {@link ChannelHandlerContext} for which the connect operation is made - * @param remoteAddress the {@link SocketAddress} to which it should connect - * @param localAddress the {@link SocketAddress} which is used as source on connect - * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error accour - */ - void connect( - ChannelHandlerContext ctx, SocketAddress remoteAddress, - SocketAddress localAddress, ChannelPromise promise) throws Exception; - - /** - * Called once a disconnect operation is made. - * - * @param ctx the {@link ChannelHandlerContext} for which the disconnect operation is made - * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error accour - */ - void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception; - - /** - * Called once a close operation is made. - * - * @param ctx the {@link ChannelHandlerContext} for which the close operation is made - * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error accour - */ - void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception; - - /** - * Called once a deregister operation is made from the current registered {@link EventLoop}. - * - * @param ctx the {@link ChannelHandlerContext} for which the close operation is made - * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error accour - */ - void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception; - - /** - * Intercepts {@link ChannelHandlerContext#read()}. - */ - void read(ChannelHandlerContext ctx) throws Exception; - - /** - * Called once a write operation is made. The write operation will write the messages through the - * {@link ChannelPipeline}. Those are then ready to be flushed to the actual {@link Channel} once - * {@link Channel#flush()} is called - * - * @param ctx the {@link ChannelHandlerContext} for which the write operation is made - * @param msg the message to write - * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error accour - */ - void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception; - - /** - * Called once a flush operation is made. The flush operation will try to flush out all previous written messages - * that are pending. - * - * @param ctx the {@link ChannelHandlerContext} for which the flush operation is made - * @throws Exception thrown if an error accour - */ - void flush(ChannelHandlerContext ctx) throws Exception; -} diff --git a/common/src/main/java/common/net/channel/ChannelOutboundHandlerAdapter.java b/common/src/main/java/common/net/channel/ChannelOutboundHandlerAdapter.java deleted file mode 100644 index 0ce2ac8..0000000 --- a/common/src/main/java/common/net/channel/ChannelOutboundHandlerAdapter.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.net.SocketAddress; - -/** - * Skelton implementation of a {@link ChannelOutboundHandler}. This implementation just forwards each method call via - * the {@link ChannelHandlerContext}. - */ -public class ChannelOutboundHandlerAdapter extends ChannelHandlerAdapter implements ChannelOutboundHandler { - - /** - * Calls {@link ChannelHandlerContext#bind(SocketAddress, ChannelPromise)} to forward - * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, - ChannelPromise promise) throws Exception { - ctx.bind(localAddress, promise); - } - - /** - * Calls {@link ChannelHandlerContext#connect(SocketAddress, SocketAddress, ChannelPromise)} to forward - * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, - SocketAddress localAddress, ChannelPromise promise) throws Exception { - ctx.connect(remoteAddress, localAddress, promise); - } - - /** - * Calls {@link ChannelHandlerContext#disconnect(ChannelPromise)} to forward - * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) - throws Exception { - ctx.disconnect(promise); - } - - /** - * Calls {@link ChannelHandlerContext#close(ChannelPromise)} to forward - * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void close(ChannelHandlerContext ctx, ChannelPromise promise) - throws Exception { - ctx.close(promise); - } - - /** - * Calls {@link ChannelHandlerContext#close(ChannelPromise)} to forward - * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { - ctx.deregister(promise); - } - - /** - * Calls {@link ChannelHandlerContext#read()} to forward - * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void read(ChannelHandlerContext ctx) throws Exception { - ctx.read(); - } - - /** - * Calls {@link ChannelHandlerContext#write(Object)} to forward - * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { - ctx.write(msg, promise); - } - - /** - * Calls {@link ChannelHandlerContext#flush()} to forward - * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. - * - * Sub-classes may override this method to change behavior. - */ - @Override - public void flush(ChannelHandlerContext ctx) throws Exception { - ctx.flush(); - } -} diff --git a/common/src/main/java/common/net/channel/ChannelPipeline.java b/common/src/main/java/common/net/channel/ChannelPipeline.java deleted file mode 100644 index ed5ac6f..0000000 --- a/common/src/main/java/common/net/channel/ChannelPipeline.java +++ /dev/null @@ -1,872 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.net.SocketAddress; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import common.net.util.concurrent.EventExecutorGroup; - - -/** - * A list of {@link ChannelHandler}s which handles or intercepts inbound events and outbound operations of a - * {@link Channel}. {@link ChannelPipeline} implements an advanced form of the - * Intercepting Filter pattern - * to give a user full control over how an event is handled and how the {@link ChannelHandler}s in a pipeline - * interact with each other. - * - *

Creation of a pipeline

- * - * Each channel has its own pipeline and it is created automatically when a new channel is created. - * - *

How an event flows in a pipeline

- * - * The following diagram describes how I/O events are processed by {@link ChannelHandler}s in a {@link ChannelPipeline} - * typically. An I/O event is handled by either a {@link ChannelInboundHandler} or a {@link ChannelOutboundHandler} - * and be forwarded to its closest handler by calling the event propagation methods defined in - * {@link ChannelHandlerContext}, such as {@link ChannelHandlerContext#fireChannelRead(Object)} and - * {@link ChannelHandlerContext#write(Object)}. - * - *
- *                                                 I/O Request
- *                                            via {@link Channel} or
- *                                        {@link ChannelHandlerContext}
- *                                                      |
- *  +---------------------------------------------------+---------------+
- *  |                           ChannelPipeline         |               |
- *  |                                                  \|/              |
- *  |    +---------------------+            +-----------+----------+    |
- *  |    | Inbound Handler  N  |            | Outbound Handler  1  |    |
- *  |    +----------+----------+            +-----------+----------+    |
- *  |              /|\                                  |               |
- *  |               |                                  \|/              |
- *  |    +----------+----------+            +-----------+----------+    |
- *  |    | Inbound Handler N-1 |            | Outbound Handler  2  |    |
- *  |    +----------+----------+            +-----------+----------+    |
- *  |              /|\                                  .               |
- *  |               .                                   .               |
- *  | ChannelHandlerContext.fireIN_EVT() ChannelHandlerContext.OUT_EVT()|
- *  |        [ method call]                       [method call]         |
- *  |               .                                   .               |
- *  |               .                                  \|/              |
- *  |    +----------+----------+            +-----------+----------+    |
- *  |    | Inbound Handler  2  |            | Outbound Handler M-1 |    |
- *  |    +----------+----------+            +-----------+----------+    |
- *  |              /|\                                  |               |
- *  |               |                                  \|/              |
- *  |    +----------+----------+            +-----------+----------+    |
- *  |    | Inbound Handler  1  |            | Outbound Handler  M  |    |
- *  |    +----------+----------+            +-----------+----------+    |
- *  |              /|\                                  |               |
- *  +---------------+-----------------------------------+---------------+
- *                  |                                  \|/
- *  +---------------+-----------------------------------+---------------+
- *  |               |                                   |               |
- *  |       [ Socket.read() ]                    [ Socket.write() ]     |
- *  |                                                                   |
- *  |  Netty Internal I/O Threads (Transport Implementation)            |
- *  +-------------------------------------------------------------------+
- * 
- * An inbound event is handled by the inbound handlers in the bottom-up direction as shown on the left side of the - * diagram. An inbound handler usually handles the inbound data generated by the I/O thread on the bottom of the - * diagram. The inbound data is often read from a remote peer via the actual input operation such as - * {@link SocketChannel#read(ByteBuffer)}. If an inbound event goes beyond the top inbound handler, it is discarded - * silently, or logged if it needs your attention. - *

- * An outbound event is handled by the outbound handler in the top-down direction as shown on the right side of the - * diagram. An outbound handler usually generates or transforms the outbound traffic such as write requests. - * If an outbound event goes beyond the bottom outbound handler, it is handled by an I/O thread associated with the - * {@link Channel}. The I/O thread often performs the actual output operation such as - * {@link SocketChannel#write(ByteBuffer)}. - *

- * For example, let us assume that we created the following pipeline: - *

- * {@link ChannelPipeline} p = ...;
- * p.addLast("1", new InboundHandlerA());
- * p.addLast("2", new InboundHandlerB());
- * p.addLast("3", new OutboundHandlerA());
- * p.addLast("4", new OutboundHandlerB());
- * p.addLast("5", new InboundOutboundHandlerX());
- * 
- * In the example above, the class whose name starts with {@code Inbound} means it is an inbound handler. - * The class whose name starts with {@code Outbound} means it is a outbound handler. - *

- * In the given example configuration, the handler evaluation order is 1, 2, 3, 4, 5 when an event goes inbound. - * When an event goes outbound, the order is 5, 4, 3, 2, 1. On top of this principle, {@link ChannelPipeline} skips - * the evaluation of certain handlers to shorten the stack depth: - *

    - *
  • 3 and 4 don't implement {@link ChannelInboundHandler}, and therefore the actual evaluation order of an inbound - * event will be: 1, 2, and 5.
  • - *
  • 1 and 2 don't implement {@link ChannelOutboundHandler}, and therefore the actual evaluation order of a - * outbound event will be: 5, 4, and 3.
  • - *
  • If 5 implements both {@link ChannelInboundHandler} and {@link ChannelOutboundHandler}, the evaluation order of - * an inbound and a outbound event could be 125 and 543 respectively.
  • - *
- * - *

Forwarding an event to the next handler

- * - * As you might noticed in the diagram shows, a handler has to invoke the event propagation methods in - * {@link ChannelHandlerContext} to forward an event to its next handler. Those methods include: - *
    - *
  • Inbound event propagation methods: - *
      - *
    • {@link ChannelHandlerContext#fireChannelRegistered()}
    • - *
    • {@link ChannelHandlerContext#fireChannelActive()}
    • - *
    • {@link ChannelHandlerContext#fireChannelRead(Object)}
    • - *
    • {@link ChannelHandlerContext#fireChannelReadComplete()}
    • - *
    • {@link ChannelHandlerContext#fireExceptionCaught(Throwable)}
    • - *
    • {@link ChannelHandlerContext#fireUserEventTriggered(Object)}
    • - *
    • {@link ChannelHandlerContext#fireChannelWritabilityChanged()}
    • - *
    • {@link ChannelHandlerContext#fireChannelInactive()}
    • - *
    • {@link ChannelHandlerContext#fireChannelUnregistered()}
    • - *
    - *
  • - *
  • Outbound event propagation methods: - *
      - *
    • {@link ChannelHandlerContext#bind(SocketAddress, ChannelPromise)}
    • - *
    • {@link ChannelHandlerContext#connect(SocketAddress, SocketAddress, ChannelPromise)}
    • - *
    • {@link ChannelHandlerContext#write(Object, ChannelPromise)}
    • - *
    • {@link ChannelHandlerContext#flush()}
    • - *
    • {@link ChannelHandlerContext#read()}
    • - *
    • {@link ChannelHandlerContext#disconnect(ChannelPromise)}
    • - *
    • {@link ChannelHandlerContext#close(ChannelPromise)}
    • - *
    • {@link ChannelHandlerContext#deregister(ChannelPromise)}
    • - *
    - *
  • - *
- * - * and the following example shows how the event propagation is usually done: - * - *
- * public class MyInboundHandler extends {@link ChannelInboundHandlerAdapter} {
- *     {@code @Override}
- *     public void channelActive({@link ChannelHandlerContext} ctx) {
- *         System.out.println("Connected!");
- *         ctx.fireChannelActive();
- *     }
- * }
- *
- * public clas MyOutboundHandler extends {@link ChannelOutboundHandlerAdapter} {
- *     {@code @Override}
- *     public void close({@link ChannelHandlerContext} ctx, {@link ChannelPromise} promise) {
- *         System.out.println("Closing ..");
- *         ctx.close(promise);
- *     }
- * }
- * 
- * - *

Building a pipeline

- *

- * A user is supposed to have one or more {@link ChannelHandler}s in a pipeline to receive I/O events (e.g. read) and - * to request I/O operations (e.g. write and close). For example, a typical server will have the following handlers - * in each channel's pipeline, but your mileage may vary depending on the complexity and characteristics of the - * protocol and business logic: - * - *

    - *
  1. Protocol Decoder - translates binary data (e.g. {@link ByteBuf}) into a Java object.
  2. - *
  3. Protocol Encoder - translates a Java object into binary data.
  4. - *
  5. Business Logic Handler - performs the actual business logic (e.g. database access).
  6. - *
- * - * and it could be represented as shown in the following example: - * - *
- * static final {@link EventExecutorGroup} group = new {@link DefaultEventExecutorGroup}(16);
- * ...
- *
- * {@link ChannelPipeline} pipeline = ch.pipeline();
- *
- * pipeline.addLast("decoder", new MyProtocolDecoder());
- * pipeline.addLast("encoder", new MyProtocolEncoder());
- *
- * // Tell the pipeline to run MyBusinessLogicHandler's event handler methods
- * // in a different thread than an I/O thread so that the I/O thread is not blocked by
- * // a time-consuming task.
- * // If your business logic is fully asynchronous or finished very quickly, you don't
- * // need to specify a group.
- * pipeline.addLast(group, "handler", new MyBusinessLogicHandler());
- * 
- * - *

Thread safety

- *

- * A {@link ChannelHandler} can be added or removed at any time because a {@link ChannelPipeline} is thread safe. - * For example, you can insert an encryption handler when sensitive information is about to be exchanged, and remove it - * after the exchange. - */ -public interface ChannelPipeline - extends Iterable> { - - /** - * Inserts a {@link ChannelHandler} at the first position of this pipeline. - * - * @param name the name of the handler to insert first - * @param handler the handler to insert first - * - * @throws IllegalArgumentException - * if there's an entry with the same name already in the pipeline - * @throws NullPointerException - * if the specified name or handler is {@code null} - */ - ChannelPipeline addFirst(String name, ChannelHandler handler); - - /** - * Inserts a {@link ChannelHandler} at the first position of this pipeline. - * - * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler} - * methods - * @param name the name of the handler to insert first - * @param handler the handler to insert first - * - * @throws IllegalArgumentException - * if there's an entry with the same name already in the pipeline - * @throws NullPointerException - * if the specified name or handler is {@code null} - */ - ChannelPipeline addFirst(EventExecutorGroup group, String name, ChannelHandler handler); - - /** - * Appends a {@link ChannelHandler} at the last position of this pipeline. - * - * @param name the name of the handler to append - * @param handler the handler to append - * - * @throws IllegalArgumentException - * if there's an entry with the same name already in the pipeline - * @throws NullPointerException - * if the specified name or handler is {@code null} - */ - ChannelPipeline addLast(String name, ChannelHandler handler); - - /** - * Appends a {@link ChannelHandler} at the last position of this pipeline. - * - * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler} - * methods - * @param name the name of the handler to append - * @param handler the handler to append - * - * @throws IllegalArgumentException - * if there's an entry with the same name already in the pipeline - * @throws NullPointerException - * if the specified name or handler is {@code null} - */ - ChannelPipeline addLast(EventExecutorGroup group, String name, ChannelHandler handler); - - /** - * Inserts a {@link ChannelHandler} before an existing handler of this - * pipeline. - * - * @param baseName the name of the existing handler - * @param name the name of the handler to insert before - * @param handler the handler to insert before - * - * @throws NoSuchElementException - * if there's no such entry with the specified {@code baseName} - * @throws IllegalArgumentException - * if there's an entry with the same name already in the pipeline - * @throws NullPointerException - * if the specified baseName, name, or handler is {@code null} - */ - ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler); - - /** - * Inserts a {@link ChannelHandler} before an existing handler of this - * pipeline. - * - * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler} - * methods - * @param baseName the name of the existing handler - * @param name the name of the handler to insert before - * @param handler the handler to insert before - * - * @throws NoSuchElementException - * if there's no such entry with the specified {@code baseName} - * @throws IllegalArgumentException - * if there's an entry with the same name already in the pipeline - * @throws NullPointerException - * if the specified baseName, name, or handler is {@code null} - */ - ChannelPipeline addBefore(EventExecutorGroup group, String baseName, String name, ChannelHandler handler); - - /** - * Inserts a {@link ChannelHandler} after an existing handler of this - * pipeline. - * - * @param baseName the name of the existing handler - * @param name the name of the handler to insert after - * @param handler the handler to insert after - * - * @throws NoSuchElementException - * if there's no such entry with the specified {@code baseName} - * @throws IllegalArgumentException - * if there's an entry with the same name already in the pipeline - * @throws NullPointerException - * if the specified baseName, name, or handler is {@code null} - */ - ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler); - - /** - * Inserts a {@link ChannelHandler} after an existing handler of this - * pipeline. - * - * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler} - * methods - * @param baseName the name of the existing handler - * @param name the name of the handler to insert after - * @param handler the handler to insert after - * - * @throws NoSuchElementException - * if there's no such entry with the specified {@code baseName} - * @throws IllegalArgumentException - * if there's an entry with the same name already in the pipeline - * @throws NullPointerException - * if the specified baseName, name, or handler is {@code null} - */ - ChannelPipeline addAfter(EventExecutorGroup group, String baseName, String name, ChannelHandler handler); - - /** - * Inserts a {@link ChannelHandler}s at the first position of this pipeline. - * - * @param handlers the handlers to insert first - * - */ - ChannelPipeline addFirst(ChannelHandler... handlers); - - /** - * Inserts a {@link ChannelHandler}s at the first position of this pipeline. - * - * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler}s - * methods. - * @param handlers the handlers to insert first - * - */ - ChannelPipeline addFirst(EventExecutorGroup group, ChannelHandler... handlers); - - /** - * Inserts a {@link ChannelHandler}s at the last position of this pipeline. - * - * @param handlers the handlers to insert last - * - */ - ChannelPipeline addLast(ChannelHandler... handlers); - - /** - * Inserts a {@link ChannelHandler}s at the last position of this pipeline. - * - * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler}s - * methods. - * @param handlers the handlers to insert last - * - */ - ChannelPipeline addLast(EventExecutorGroup group, ChannelHandler... handlers); - - /** - * Removes the specified {@link ChannelHandler} from this pipeline. - * - * @param handler the {@link ChannelHandler} to remove - * - * @throws NoSuchElementException - * if there's no such handler in this pipeline - * @throws NullPointerException - * if the specified handler is {@code null} - */ - ChannelPipeline remove(ChannelHandler handler); - - /** - * Removes the {@link ChannelHandler} with the specified name from this pipeline. - * - * @param name the name under which the {@link ChannelHandler} was stored. - * - * @return the removed handler - * - * @throws NoSuchElementException - * if there's no such handler with the specified name in this pipeline - * @throws NullPointerException - * if the specified name is {@code null} - */ - ChannelHandler remove(String name); - - /** - * Removes the {@link ChannelHandler} of the specified type from this pipeline. - * - * @param the type of the handler - * @param handlerType the type of the handler - * - * @return the removed handler - * - * @throws NoSuchElementException - * if there's no such handler of the specified type in this pipeline - * @throws NullPointerException - * if the specified handler type is {@code null} - */ - T remove(Class handlerType); - - /** - * Removes the first {@link ChannelHandler} in this pipeline. - * - * @return the removed handler - * - * @throws NoSuchElementException - * if this pipeline is empty - */ - ChannelHandler removeFirst(); - - /** - * Removes the last {@link ChannelHandler} in this pipeline. - * - * @return the removed handler - * - * @throws NoSuchElementException - * if this pipeline is empty - */ - ChannelHandler removeLast(); - - /** - * Replaces the specified {@link ChannelHandler} with a new handler in this pipeline. - * - * @param oldHandler the {@link ChannelHandler} to be replaced - * @param newName the name under which the replacement should be added - * @param newHandler the {@link ChannelHandler} which is used as replacement - * - * @return itself - - * @throws NoSuchElementException - * if the specified old handler does not exist in this pipeline - * @throws IllegalArgumentException - * if a handler with the specified new name already exists in this - * pipeline, except for the handler to be replaced - * @throws NullPointerException - * if the specified old handler, new name, or new handler is - * {@code null} - */ - ChannelPipeline replace(ChannelHandler oldHandler, String newName, ChannelHandler newHandler); - - /** - * Replaces the {@link ChannelHandler} of the specified name with a new handler in this pipeline. - * - * @param oldName the name of the {@link ChannelHandler} to be replaced - * @param newName the name under which the replacement should be added - * @param newHandler the {@link ChannelHandler} which is used as replacement - * - * @return the removed handler - * - * @throws NoSuchElementException - * if the handler with the specified old name does not exist in this pipeline - * @throws IllegalArgumentException - * if a handler with the specified new name already exists in this - * pipeline, except for the handler to be replaced - * @throws NullPointerException - * if the specified old handler, new name, or new handler is - * {@code null} - */ - ChannelHandler replace(String oldName, String newName, ChannelHandler newHandler); - - /** - * Replaces the {@link ChannelHandler} of the specified type with a new handler in this pipeline. - * - * @param oldHandlerType the type of the handler to be removed - * @param newName the name under which the replacement should be added - * @param newHandler the {@link ChannelHandler} which is used as replacement - * - * @return the removed handler - * - * @throws NoSuchElementException - * if the handler of the specified old handler type does not exist - * in this pipeline - * @throws IllegalArgumentException - * if a handler with the specified new name already exists in this - * pipeline, except for the handler to be replaced - * @throws NullPointerException - * if the specified old handler, new name, or new handler is - * {@code null} - */ - T replace(Class oldHandlerType, String newName, - ChannelHandler newHandler); - - /** - * Returns the first {@link ChannelHandler} in this pipeline. - * - * @return the first handler. {@code null} if this pipeline is empty. - */ - ChannelHandler first(); - - /** - * Returns the context of the first {@link ChannelHandler} in this pipeline. - * - * @return the context of the first handler. {@code null} if this pipeline is empty. - */ - ChannelHandlerContext firstContext(); - - /** - * Returns the last {@link ChannelHandler} in this pipeline. - * - * @return the last handler. {@code null} if this pipeline is empty. - */ - ChannelHandler last(); - - /** - * Returns the context of the last {@link ChannelHandler} in this pipeline. - * - * @return the context of the last handler. {@code null} if this pipeline is empty. - */ - ChannelHandlerContext lastContext(); - - /** - * Returns the {@link ChannelHandler} with the specified name in this - * pipeline. - * - * @return the handler with the specified name. - * {@code null} if there's no such handler in this pipeline. - */ - ChannelHandler get(String name); - - /** - * Returns the {@link ChannelHandler} of the specified type in this - * pipeline. - * - * @return the handler of the specified handler type. - * {@code null} if there's no such handler in this pipeline. - */ - T get(Class handlerType); - - /** - * Returns the context object of the specified {@link ChannelHandler} in - * this pipeline. - * - * @return the context object of the specified handler. - * {@code null} if there's no such handler in this pipeline. - */ - ChannelHandlerContext context(ChannelHandler handler); - - /** - * Returns the context object of the {@link ChannelHandler} with the - * specified name in this pipeline. - * - * @return the context object of the handler with the specified name. - * {@code null} if there's no such handler in this pipeline. - */ - ChannelHandlerContext context(String name); - - /** - * Returns the context object of the {@link ChannelHandler} of the - * specified type in this pipeline. - * - * @return the context object of the handler of the specified type. - * {@code null} if there's no such handler in this pipeline. - */ - ChannelHandlerContext context(Class handlerType); - - /** - * Returns the {@link Channel} that this pipeline is attached to. - * - * @return the channel. {@code null} if this pipeline is not attached yet. - */ - Channel channel(); - - /** - * Returns the {@link List} of the handler names. - */ - List names(); - - /** - * Converts this pipeline into an ordered {@link Map} whose keys are - * handler names and whose values are handlers. - */ - Map toMap(); - - /** - * A {@link Channel} was registered to its {@link EventLoop}. - * - * This will result in having the {@link ChannelInboundHandler#channelRegistered(ChannelHandlerContext)} method - * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelPipeline fireChannelRegistered(); - - /** - * A {@link Channel} was unregistered from its {@link EventLoop}. - * - * This will result in having the {@link ChannelInboundHandler#channelUnregistered(ChannelHandlerContext)} method - * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelPipeline fireChannelUnregistered(); - - /** - * A {@link Channel} is active now, which means it is connected. - * - * This will result in having the {@link ChannelInboundHandler#channelActive(ChannelHandlerContext)} method - * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelPipeline fireChannelActive(); - - /** - * A {@link Channel} is inactive now, which means it is closed. - * - * This will result in having the {@link ChannelInboundHandler#channelInactive(ChannelHandlerContext)} method - * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelPipeline fireChannelInactive(); - - /** - * A {@link Channel} received an {@link Throwable} in one of its inbound operations. - * - * This will result in having the {@link ChannelInboundHandler#exceptionCaught(ChannelHandlerContext, Throwable)} - * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelPipeline fireExceptionCaught(Throwable cause); - - /** - * A {@link Channel} received an user defined event. - * - * This will result in having the {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)} - * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelPipeline fireUserEventTriggered(Object event); - - /** - * A {@link Channel} received a message. - * - * This will result in having the {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)} - * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelPipeline fireChannelRead(Object msg); - - /** - * Triggers an {@link ChannelInboundHandler#channelWritabilityChanged(ChannelHandlerContext)} - * event to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - */ - ChannelPipeline fireChannelReadComplete(); - - /** - * Triggers an {@link ChannelInboundHandler#channelWritabilityChanged(ChannelHandlerContext)} - * event to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - */ - ChannelPipeline fireChannelWritabilityChanged(); - - /** - * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method - * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture bind(SocketAddress localAddress); - - /** - * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - *

- * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with - * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} - * will be used. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress); - - /** - * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the - * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of - * an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress); - - /** - * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, - * either because the operation was successful or because of an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture disconnect(); - - /** - * Request to close the {@link Channel} and notify the {@link ChannelFuture} once the operation completes, - * either because the operation was successful or because of - * an error. - * - * After it is closed it is not possible to reuse it again. - *

- * This will result in having the - * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture close(); - - /** - * Request to deregister the {@link Channel} from the previous assigned {@link EventExecutor} and notify the - * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of - * an error. - *

- * This will result in having the - * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - * - */ - ChannelFuture deregister(); - - /** - * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - * - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method - * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise); - - /** - * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation - * completes, either because the operation was successful or because of an error. - * - * The given {@link ChannelFuture} will be notified. - * - *

- * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with - * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} - * will be used. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise); - - /** - * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the - * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of - * an error. - * - * The given {@link ChannelPromise} will be notified and also returned. - *

- * This will result in having the - * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise); - - /** - * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, - * either because the operation was successful or because of an error. - * - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture disconnect(ChannelPromise promise); - - /** - * Request to close the {@link Channel} bound to this {@link ChannelPipeline} and notify the {@link ChannelFuture} - * once the operation completes, either because the operation was successful or because of - * an error. - * - * After it is closed it is not possible to reuse it again. - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture close(ChannelPromise promise); - - /** - * Request to deregister the {@link Channel} bound this {@link ChannelPipeline} from the previous assigned - * {@link EventExecutor} and notify the {@link ChannelFuture} once the operation completes, either because the - * operation was successful or because of an error. - * - * The given {@link ChannelPromise} will be notified. - *

- * This will result in having the - * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelFuture deregister(ChannelPromise promise); - - /** - * Request to Read data from the {@link Channel} into the first inbound buffer, triggers an - * {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)} event if data was - * read, and triggers a - * {@link ChannelInboundHandler#channelReadComplete(ChannelHandlerContext) channelReadComplete} event so the - * handler can decide to continue reading. If there's a pending read operation already, this method does nothing. - *

- * This will result in having the - * {@link ChannelOutboundHandler#read(ChannelHandlerContext)} - * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the - * {@link Channel}. - */ - ChannelPipeline read(); - - /** - * Request to write a message via this {@link ChannelPipeline}. - * This method will not request to actual flush, so be sure to call {@link #flush()} - * once you want to request to flush all pending data to the actual transport. - */ - ChannelFuture write(Object msg); - - /** - * Request to write a message via this {@link ChannelPipeline}. - * This method will not request to actual flush, so be sure to call {@link #flush()} - * once you want to request to flush all pending data to the actual transport. - */ - ChannelFuture write(Object msg, ChannelPromise promise); - - /** - * Request to flush all pending messages. - */ - ChannelPipeline flush(); - - /** - * Shortcut for call {@link #write(Object, ChannelPromise)} and {@link #flush()}. - */ - ChannelFuture writeAndFlush(Object msg, ChannelPromise promise); - - /** - * Shortcut for call {@link #write(Object)} and {@link #flush()}. - */ - ChannelFuture writeAndFlush(Object msg); -} diff --git a/common/src/main/java/common/net/channel/ChannelPipelineException.java b/common/src/main/java/common/net/channel/ChannelPipelineException.java deleted file mode 100644 index d1f8628..0000000 --- a/common/src/main/java/common/net/channel/ChannelPipelineException.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -/** - * A {@link ChannelException} which is thrown when a {@link ChannelPipeline} - * failed to execute an operation. - */ -public class ChannelPipelineException extends ChannelException { - - private static final long serialVersionUID = 3379174210419885980L; - - /** - * Creates a new instance. - */ - public ChannelPipelineException() { - } - - /** - * Creates a new instance. - */ - public ChannelPipelineException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Creates a new instance. - */ - public ChannelPipelineException(String message) { - super(message); - } - - /** - * Creates a new instance. - */ - public ChannelPipelineException(Throwable cause) { - super(cause); - } -} diff --git a/common/src/main/java/common/net/channel/ChannelProgressivePromise.java b/common/src/main/java/common/net/channel/ChannelProgressivePromise.java deleted file mode 100644 index 530e252..0000000 --- a/common/src/main/java/common/net/channel/ChannelProgressivePromise.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; -import common.net.util.concurrent.ProgressiveFuture; -import common.net.util.concurrent.ProgressivePromise; - -/** - * Special {@link ChannelPromise} which will be notified once the associated bytes is transferring. - */ -public interface ChannelProgressivePromise extends ProgressivePromise, ChannelFuture, ProgressiveFuture, ChannelPromise { -// @Override -// ChannelProgressiveFuture addListener(GenericFutureListener> listener); -// -// @Override -// ChannelProgressiveFuture addListeners(GenericFutureListener>... listeners); -// -// @Override -// ChannelProgressiveFuture removeListener(GenericFutureListener> listener); -// -// @Override -// ChannelProgressiveFuture removeListeners(GenericFutureListener>... listeners); -// -// @Override -// ChannelProgressiveFuture sync() throws InterruptedException; -// -// @Override -// ChannelProgressiveFuture syncUninterruptibly(); -// -// @Override -// ChannelProgressiveFuture await() throws InterruptedException; -// -// @Override -// ChannelProgressiveFuture awaitUninterruptibly(); - - @Override - ChannelProgressivePromise addListener(GenericFutureListener> listener); - - @Override - ChannelProgressivePromise addListeners(GenericFutureListener>... listeners); - - @Override - ChannelProgressivePromise removeListener(GenericFutureListener> listener); - - @Override - ChannelProgressivePromise removeListeners(GenericFutureListener>... listeners); - - @Override - ChannelProgressivePromise sync() throws InterruptedException; - - @Override - ChannelProgressivePromise syncUninterruptibly(); - - @Override - ChannelProgressivePromise await() throws InterruptedException; - - @Override - ChannelProgressivePromise awaitUninterruptibly(); - - @Override - ChannelProgressivePromise setSuccess(Void result); - - @Override - ChannelProgressivePromise setSuccess(); - - @Override - ChannelProgressivePromise setFailure(Throwable cause); - - @Override - ChannelProgressivePromise setProgress(long progress, long total); -} diff --git a/common/src/main/java/common/net/channel/ChannelPromise.java b/common/src/main/java/common/net/channel/ChannelPromise.java deleted file mode 100644 index fda7072..0000000 --- a/common/src/main/java/common/net/channel/ChannelPromise.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; -import common.net.util.concurrent.Promise; - -/** - * Special {@link ChannelFuture} which is writable. - */ -public interface ChannelPromise extends ChannelFuture, Promise { - - @Override - Channel channel(); - - @Override - ChannelPromise setSuccess(Void result); - - ChannelPromise setSuccess(); - - boolean trySuccess(); - - @Override - ChannelPromise setFailure(Throwable cause); - - @Override - ChannelPromise addListener(GenericFutureListener> listener); - - @Override - ChannelPromise addListeners(GenericFutureListener>... listeners); - - @Override - ChannelPromise removeListener(GenericFutureListener> listener); - - @Override - ChannelPromise removeListeners(GenericFutureListener>... listeners); - - @Override - ChannelPromise sync() throws InterruptedException; - - @Override - ChannelPromise syncUninterruptibly(); - - @Override - ChannelPromise await() throws InterruptedException; - - @Override - ChannelPromise awaitUninterruptibly(); -} diff --git a/common/src/main/java/common/net/channel/CompleteChannelFuture.java b/common/src/main/java/common/net/channel/CompleteChannelFuture.java deleted file mode 100644 index 2e8dac6..0000000 --- a/common/src/main/java/common/net/channel/CompleteChannelFuture.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.util.concurrent.CompleteFuture; -import common.net.util.concurrent.EventExecutor; -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; - -/** - * A skeletal {@link ChannelFuture} implementation which represents a - * {@link ChannelFuture} which has been completed already. - */ -abstract class CompleteChannelFuture extends CompleteFuture implements ChannelFuture { - - private final Channel channel; - - /** - * Creates a new instance. - * - * @param channel the {@link Channel} associated with this future - */ - protected CompleteChannelFuture(Channel channel, EventExecutor executor) { - super(executor); - if (channel == null) { - throw new NullPointerException("channel"); - } - this.channel = channel; - } - - @Override - protected EventExecutor executor() { - EventExecutor e = super.executor(); - if (e == null) { - return channel().eventLoop(); - } else { - return e; - } - } - - @Override - public ChannelFuture addListener(GenericFutureListener> listener) { - super.addListener(listener); - return this; - } - - @Override - public ChannelFuture addListeners(GenericFutureListener>... listeners) { - super.addListeners(listeners); - return this; - } - - @Override - public ChannelFuture removeListener(GenericFutureListener> listener) { - super.removeListener(listener); - return this; - } - - @Override - public ChannelFuture removeListeners(GenericFutureListener>... listeners) { - super.removeListeners(listeners); - return this; - } - - @Override - public ChannelFuture syncUninterruptibly() { - return this; - } - - @Override - public ChannelFuture sync() throws InterruptedException { - return this; - } - - @Override - public ChannelFuture await() throws InterruptedException { - return this; - } - - @Override - public ChannelFuture awaitUninterruptibly() { - return this; - } - - @Override - public Channel channel() { - return channel; - } - - @Override - public Void getNow() { - return null; - } -} diff --git a/common/src/main/java/common/net/channel/ConnectTimeoutException.java b/common/src/main/java/common/net/channel/ConnectTimeoutException.java deleted file mode 100644 index 831cbe6..0000000 --- a/common/src/main/java/common/net/channel/ConnectTimeoutException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.net.ConnectException; - -/** - * {@link ConnectException} which will be thrown if a connection could - * not be established because of a connection timeout. - */ -public class ConnectTimeoutException extends ConnectException { - private static final long serialVersionUID = 2317065249988317463L; - - public ConnectTimeoutException(String msg) { - super(msg); - } - - public ConnectTimeoutException() { - } -} diff --git a/common/src/main/java/common/net/channel/DefaultChannelConfig.java b/common/src/main/java/common/net/channel/DefaultChannelConfig.java deleted file mode 100644 index 5d94a1c..0000000 --- a/common/src/main/java/common/net/channel/DefaultChannelConfig.java +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import static common.net.channel.ChannelOption.ALLOCATOR; -import static common.net.channel.ChannelOption.AUTO_READ; -import static common.net.channel.ChannelOption.CONNECT_TIMEOUT_MILLIS; -import static common.net.channel.ChannelOption.MAX_MESSAGES_PER_READ; -import static common.net.channel.ChannelOption.MESSAGE_SIZE_ESTIMATOR; -import static common.net.channel.ChannelOption.RCVBUF_ALLOCATOR; -import static common.net.channel.ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK; -import static common.net.channel.ChannelOption.WRITE_BUFFER_LOW_WATER_MARK; -import static common.net.channel.ChannelOption.WRITE_SPIN_COUNT; - -import java.util.IdentityHashMap; -import java.util.Map; -import java.util.Map.Entry; - -import common.net.buffer.ByteBufAllocator; -import common.net.channel.nio.AbstractNioByteChannel; - -/** - * The default {@link SocketChannelConfig} implementation. - */ -public class DefaultChannelConfig implements ChannelConfig { - - private static final RecvByteBufAllocator DEFAULT_RCVBUF_ALLOCATOR = AdaptiveRecvByteBufAllocator.DEFAULT; - private static final MessageSizeEstimator DEFAULT_MSG_SIZE_ESTIMATOR = DefaultMessageSizeEstimator.DEFAULT; - - private static final int DEFAULT_CONNECT_TIMEOUT = 30000; - - protected final Channel channel; - - private volatile ByteBufAllocator allocator = ByteBufAllocator.DEFAULT; - private volatile RecvByteBufAllocator rcvBufAllocator = DEFAULT_RCVBUF_ALLOCATOR; - private volatile MessageSizeEstimator msgSizeEstimator = DEFAULT_MSG_SIZE_ESTIMATOR; - - private volatile int connectTimeoutMillis = DEFAULT_CONNECT_TIMEOUT; - private volatile int maxMessagesPerRead; - private volatile int writeSpinCount = 16; - private volatile boolean autoRead = true; - private volatile int writeBufferHighWaterMark = 64 * 1024; - private volatile int writeBufferLowWaterMark = 32 * 1024; - - public DefaultChannelConfig(Channel channel) { - if (channel == null) { - throw new NullPointerException("channel"); - } - this.channel = channel; - - if (channel instanceof ServerChannel || channel instanceof AbstractNioByteChannel) { - // Server channels: Accept as many incoming connections as possible. - // NIO byte channels: Implemented to reduce unnecessary system calls even if it's > 1. - // See https://github.com/netty/netty/issues/2079 - // TODO: Add some property to ChannelMetadata so we can remove the ugly instanceof - maxMessagesPerRead = 16; - } else { - maxMessagesPerRead = 1; - } - } - - @Override - - public Map, Object> getOptions() { - return getOptions( - null, - CONNECT_TIMEOUT_MILLIS, MAX_MESSAGES_PER_READ, WRITE_SPIN_COUNT, - ALLOCATOR, AUTO_READ, RCVBUF_ALLOCATOR, WRITE_BUFFER_HIGH_WATER_MARK, - WRITE_BUFFER_LOW_WATER_MARK, MESSAGE_SIZE_ESTIMATOR); - } - - protected Map, Object> getOptions( - Map, Object> result, ChannelOption... options) { - if (result == null) { - result = new IdentityHashMap, Object>(); - } - for (ChannelOption o: options) { - result.put(o, getOption(o)); - } - return result; - } - - - @Override - public boolean setOptions(Map, ?> options) { - if (options == null) { - throw new NullPointerException("options"); - } - - boolean setAllOptions = true; - for (Entry, ?> e: options.entrySet()) { - if (!setOption((ChannelOption) e.getKey(), e.getValue())) { - setAllOptions = false; - } - } - - return setAllOptions; - } - - @Override - - public T getOption(ChannelOption option) { - if (option == null) { - throw new NullPointerException("option"); - } - - if (option == CONNECT_TIMEOUT_MILLIS) { - return (T) Integer.valueOf(getConnectTimeoutMillis()); - } - if (option == MAX_MESSAGES_PER_READ) { - return (T) Integer.valueOf(getMaxMessagesPerRead()); - } - if (option == WRITE_SPIN_COUNT) { - return (T) Integer.valueOf(getWriteSpinCount()); - } - if (option == ALLOCATOR) { - return (T) getAllocator(); - } - if (option == RCVBUF_ALLOCATOR) { - return (T) getRecvByteBufAllocator(); - } - if (option == AUTO_READ) { - return (T) Boolean.valueOf(isAutoRead()); - } - if (option == WRITE_BUFFER_HIGH_WATER_MARK) { - return (T) Integer.valueOf(getWriteBufferHighWaterMark()); - } - if (option == WRITE_BUFFER_LOW_WATER_MARK) { - return (T) Integer.valueOf(getWriteBufferLowWaterMark()); - } - if (option == MESSAGE_SIZE_ESTIMATOR) { - return (T) getMessageSizeEstimator(); - } - return null; - } - - @Override - - public boolean setOption(ChannelOption option, T value) { - validate(option, value); - - if (option == CONNECT_TIMEOUT_MILLIS) { - setConnectTimeoutMillis((Integer) value); - } else if (option == MAX_MESSAGES_PER_READ) { - setMaxMessagesPerRead((Integer) value); - } else if (option == WRITE_SPIN_COUNT) { - setWriteSpinCount((Integer) value); - } else if (option == ALLOCATOR) { - setAllocator((ByteBufAllocator) value); - } else if (option == RCVBUF_ALLOCATOR) { - setRecvByteBufAllocator((RecvByteBufAllocator) value); - } else if (option == AUTO_READ) { - setAutoRead((Boolean) value); - } else if (option == WRITE_BUFFER_HIGH_WATER_MARK) { - setWriteBufferHighWaterMark((Integer) value); - } else if (option == WRITE_BUFFER_LOW_WATER_MARK) { - setWriteBufferLowWaterMark((Integer) value); - } else if (option == MESSAGE_SIZE_ESTIMATOR) { - setMessageSizeEstimator((MessageSizeEstimator) value); - } else { - return false; - } - - return true; - } - - protected void validate(ChannelOption option, T value) { - if (option == null) { - throw new NullPointerException("option"); - } - option.validate(value); - } - - @Override - public int getConnectTimeoutMillis() { - return connectTimeoutMillis; - } - - @Override - public ChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) { - if (connectTimeoutMillis < 0) { - throw new IllegalArgumentException(String.format( - "connectTimeoutMillis: %d (expected: >= 0)", connectTimeoutMillis)); - } - this.connectTimeoutMillis = connectTimeoutMillis; - return this; - } - - @Override - public int getMaxMessagesPerRead() { - return maxMessagesPerRead; - } - - @Override - public ChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) { - if (maxMessagesPerRead <= 0) { - throw new IllegalArgumentException("maxMessagesPerRead: " + maxMessagesPerRead + " (expected: > 0)"); - } - this.maxMessagesPerRead = maxMessagesPerRead; - return this; - } - - @Override - public int getWriteSpinCount() { - return writeSpinCount; - } - - @Override - public ChannelConfig setWriteSpinCount(int writeSpinCount) { - if (writeSpinCount <= 0) { - throw new IllegalArgumentException( - "writeSpinCount must be a positive integer."); - } - this.writeSpinCount = writeSpinCount; - return this; - } - - @Override - public ByteBufAllocator getAllocator() { - return allocator; - } - - @Override - public ChannelConfig setAllocator(ByteBufAllocator allocator) { - if (allocator == null) { - throw new NullPointerException("allocator"); - } - this.allocator = allocator; - return this; - } - - @Override - public RecvByteBufAllocator getRecvByteBufAllocator() { - return rcvBufAllocator; - } - - @Override - public ChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) { - if (allocator == null) { - throw new NullPointerException("allocator"); - } - rcvBufAllocator = allocator; - return this; - } - - @Override - public boolean isAutoRead() { - return autoRead; - } - - @Override - public ChannelConfig setAutoRead(boolean autoRead) { - boolean oldAutoRead = this.autoRead; - this.autoRead = autoRead; - if (autoRead && !oldAutoRead) { - channel.read(); - } else if (!autoRead && oldAutoRead) { - autoReadCleared(); - } - return this; - } - - /** - * Is called once {@link #setAutoRead(boolean)} is called with {@code false} and {@link #isAutoRead()} was - * {@code true} before. - */ - protected void autoReadCleared() { } - - @Override - public int getWriteBufferHighWaterMark() { - return writeBufferHighWaterMark; - } - - @Override - public ChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark) { - if (writeBufferHighWaterMark < getWriteBufferLowWaterMark()) { - throw new IllegalArgumentException( - "writeBufferHighWaterMark cannot be less than " + - "writeBufferLowWaterMark (" + getWriteBufferLowWaterMark() + "): " + - writeBufferHighWaterMark); - } - if (writeBufferHighWaterMark < 0) { - throw new IllegalArgumentException( - "writeBufferHighWaterMark must be >= 0"); - } - this.writeBufferHighWaterMark = writeBufferHighWaterMark; - return this; - } - - @Override - public int getWriteBufferLowWaterMark() { - return writeBufferLowWaterMark; - } - - @Override - public ChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark) { - if (writeBufferLowWaterMark > getWriteBufferHighWaterMark()) { - throw new IllegalArgumentException( - "writeBufferLowWaterMark cannot be greater than " + - "writeBufferHighWaterMark (" + getWriteBufferHighWaterMark() + "): " + - writeBufferLowWaterMark); - } - if (writeBufferLowWaterMark < 0) { - throw new IllegalArgumentException( - "writeBufferLowWaterMark must be >= 0"); - } - this.writeBufferLowWaterMark = writeBufferLowWaterMark; - return this; - } - - @Override - public MessageSizeEstimator getMessageSizeEstimator() { - return msgSizeEstimator; - } - - @Override - public ChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) { - if (estimator == null) { - throw new NullPointerException("estimator"); - } - msgSizeEstimator = estimator; - return this; - } -} diff --git a/common/src/main/java/common/net/channel/DefaultChannelHandlerContext.java b/common/src/main/java/common/net/channel/DefaultChannelHandlerContext.java deleted file mode 100644 index 9c24e1e..0000000 --- a/common/src/main/java/common/net/channel/DefaultChannelHandlerContext.java +++ /dev/null @@ -1,45 +0,0 @@ -/* -* Copyright 2014 The Netty Project -* -* The Netty Project licenses this file to you under the Apache License, -* version 2.0 (the "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at: -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -* License for the specific language governing permissions and limitations -* under the License. -*/ -package common.net.channel; - -import common.net.util.concurrent.EventExecutorGroup; - -final class DefaultChannelHandlerContext extends AbstractChannelHandlerContext { - - private final ChannelHandler handler; - - DefaultChannelHandlerContext( - DefaultChannelPipeline pipeline, EventExecutorGroup group, String name, ChannelHandler handler) { - super(pipeline, group, name, isInbound(handler), isOutbound(handler)); - if (handler == null) { - throw new NullPointerException("handler"); - } - this.handler = handler; - } - - @Override - public ChannelHandler handler() { - return handler; - } - - private static boolean isInbound(ChannelHandler handler) { - return handler instanceof ChannelInboundHandler; - } - - private static boolean isOutbound(ChannelHandler handler) { - return handler instanceof ChannelOutboundHandler; - } -} diff --git a/common/src/main/java/common/net/channel/DefaultChannelPipeline.java b/common/src/main/java/common/net/channel/DefaultChannelPipeline.java deleted file mode 100644 index 86d549c..0000000 --- a/common/src/main/java/common/net/channel/DefaultChannelPipeline.java +++ /dev/null @@ -1,1067 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.net.SocketAddress; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.WeakHashMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -import common.net.channel.Channel.Unsafe; -import common.net.util.ReferenceCountUtil; -import common.net.util.concurrent.EventExecutor; -import common.net.util.concurrent.EventExecutorGroup; -import common.net.util.internal.StringUtil; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; -import common.util.Util; - -/** - * The default {@link ChannelPipeline} implementation. It is usually created - * by a {@link Channel} implementation when the {@link Channel} is created. - */ -final class DefaultChannelPipeline implements ChannelPipeline { - - static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelPipeline.class); - - - private static final WeakHashMap, String>[] nameCaches = - new WeakHashMap[Runtime.getRuntime().availableProcessors()]; - - static { - for (int i = 0; i < nameCaches.length; i ++) { - nameCaches[i] = new WeakHashMap, String>(); - } - } - - final AbstractChannel channel; - - final AbstractChannelHandlerContext head; - final AbstractChannelHandlerContext tail; - - private final Map name2ctx = - new HashMap(4); - - final Map childExecutors = - new IdentityHashMap(); - - public DefaultChannelPipeline(AbstractChannel channel) { - if (channel == null) { - throw new NullPointerException("channel"); - } - this.channel = channel; - - tail = new TailContext(this); - head = new HeadContext(this); - - head.next = tail; - tail.prev = head; - } - - @Override - public Channel channel() { - return channel; - } - - @Override - public ChannelPipeline addFirst(String name, ChannelHandler handler) { - return addFirst(null, name, handler); - } - - @Override - public ChannelPipeline addFirst(EventExecutorGroup group, final String name, ChannelHandler handler) { - synchronized (this) { - checkDuplicateName(name); - AbstractChannelHandlerContext newCtx = new DefaultChannelHandlerContext(this, group, name, handler); - addFirst0(name, newCtx); - } - - return this; - } - - private void addFirst0(String name, AbstractChannelHandlerContext newCtx) { - checkMultiplicity(newCtx); - - AbstractChannelHandlerContext nextCtx = head.next; - newCtx.prev = head; - newCtx.next = nextCtx; - head.next = newCtx; - nextCtx.prev = newCtx; - - name2ctx.put(name, newCtx); - - callHandlerAdded(newCtx); - } - - @Override - public ChannelPipeline addLast(String name, ChannelHandler handler) { - return addLast(null, name, handler); - } - - @Override - public ChannelPipeline addLast(EventExecutorGroup group, final String name, ChannelHandler handler) { - synchronized (this) { - checkDuplicateName(name); - - AbstractChannelHandlerContext newCtx = new DefaultChannelHandlerContext(this, group, name, handler); - addLast0(name, newCtx); - } - - return this; - } - - private void addLast0(final String name, AbstractChannelHandlerContext newCtx) { - checkMultiplicity(newCtx); - - AbstractChannelHandlerContext prev = tail.prev; - newCtx.prev = prev; - newCtx.next = tail; - prev.next = newCtx; - tail.prev = newCtx; - - name2ctx.put(name, newCtx); - - callHandlerAdded(newCtx); - } - - @Override - public ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler) { - return addBefore(null, baseName, name, handler); - } - - @Override - public ChannelPipeline addBefore( - EventExecutorGroup group, String baseName, final String name, ChannelHandler handler) { - synchronized (this) { - AbstractChannelHandlerContext ctx = getContextOrDie(baseName); - checkDuplicateName(name); - AbstractChannelHandlerContext newCtx = new DefaultChannelHandlerContext(this, group, name, handler); - addBefore0(name, ctx, newCtx); - } - return this; - } - - private void addBefore0( - final String name, AbstractChannelHandlerContext ctx, AbstractChannelHandlerContext newCtx) { - checkMultiplicity(newCtx); - - newCtx.prev = ctx.prev; - newCtx.next = ctx; - ctx.prev.next = newCtx; - ctx.prev = newCtx; - - name2ctx.put(name, newCtx); - - callHandlerAdded(newCtx); - } - - @Override - public ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler) { - return addAfter(null, baseName, name, handler); - } - - @Override - public ChannelPipeline addAfter( - EventExecutorGroup group, String baseName, final String name, ChannelHandler handler) { - synchronized (this) { - AbstractChannelHandlerContext ctx = getContextOrDie(baseName); - checkDuplicateName(name); - AbstractChannelHandlerContext newCtx = new DefaultChannelHandlerContext(this, group, name, handler); - - addAfter0(name, ctx, newCtx); - } - - return this; - } - - private void addAfter0(final String name, AbstractChannelHandlerContext ctx, AbstractChannelHandlerContext newCtx) { - checkDuplicateName(name); - checkMultiplicity(newCtx); - - newCtx.prev = ctx; - newCtx.next = ctx.next; - ctx.next.prev = newCtx; - ctx.next = newCtx; - - name2ctx.put(name, newCtx); - - callHandlerAdded(newCtx); - } - - @Override - public ChannelPipeline addFirst(ChannelHandler... handlers) { - return addFirst(null, handlers); - } - - @Override - public ChannelPipeline addFirst(EventExecutorGroup executor, ChannelHandler... handlers) { - if (handlers == null) { - throw new NullPointerException("handlers"); - } - if (handlers.length == 0 || handlers[0] == null) { - return this; - } - - int size; - for (size = 1; size < handlers.length; size ++) { - if (handlers[size] == null) { - break; - } - } - - for (int i = size - 1; i >= 0; i --) { - ChannelHandler h = handlers[i]; - addFirst(executor, generateName(h), h); - } - - return this; - } - - @Override - public ChannelPipeline addLast(ChannelHandler... handlers) { - return addLast(null, handlers); - } - - @Override - public ChannelPipeline addLast(EventExecutorGroup executor, ChannelHandler... handlers) { - if (handlers == null) { - throw new NullPointerException("handlers"); - } - - for (ChannelHandler h: handlers) { - if (h == null) { - break; - } - addLast(executor, generateName(h), h); - } - - return this; - } - - private String generateName(ChannelHandler handler) { - WeakHashMap, String> cache = nameCaches[(int) (Thread.currentThread().threadId() % nameCaches.length)]; - Class handlerType = handler.getClass(); - String name; - synchronized (cache) { - name = cache.get(handlerType); - if (name == null) { - name = generateName0(handlerType); - cache.put(handlerType, name); - } - } - - synchronized (this) { - // It's not very likely for a user to put more than one handler of the same type, but make sure to avoid - // any name conflicts. Note that we don't cache the names generated here. - if (name2ctx.containsKey(name)) { - String baseName = name.substring(0, name.length() - 1); // Strip the trailing '0'. - for (int i = 1;; i ++) { - String newName = baseName + i; - if (!name2ctx.containsKey(newName)) { - name = newName; - break; - } - } - } - } - - return name; - } - - private static String generateName0(Class handlerType) { - return StringUtil.simpleClassName(handlerType) + "#0"; - } - - @Override - public ChannelPipeline remove(ChannelHandler handler) { - remove(getContextOrDie(handler)); - return this; - } - - @Override - public ChannelHandler remove(String name) { - return remove(getContextOrDie(name)).handler(); - } - - - @Override - public T remove(Class handlerType) { - return (T) remove(getContextOrDie(handlerType)).handler(); - } - - private AbstractChannelHandlerContext remove(final AbstractChannelHandlerContext ctx) { - assert ctx != head && ctx != tail; - - AbstractChannelHandlerContext context; - Future future; - - synchronized (this) { - if (!ctx.channel().isRegistered() || ctx.executor().inEventLoop()) { - remove0(ctx); - return ctx; - } else { - future = ctx.executor().submit(new Runnable() { - @Override - public void run() { - synchronized (DefaultChannelPipeline.this) { - remove0(ctx); - } - } - }); - context = ctx; - } - } - - // Run the following 'waiting' code outside of the above synchronized block - // in order to avoid deadlock - - waitForFuture(future); - - return context; - } - - void remove0(AbstractChannelHandlerContext ctx) { - AbstractChannelHandlerContext prev = ctx.prev; - AbstractChannelHandlerContext next = ctx.next; - prev.next = next; - next.prev = prev; - name2ctx.remove(ctx.name()); - callHandlerRemoved(ctx); - } - - @Override - public ChannelHandler removeFirst() { - if (head.next == tail) { - throw new NoSuchElementException(); - } - return remove(head.next).handler(); - } - - @Override - public ChannelHandler removeLast() { - if (head.next == tail) { - throw new NoSuchElementException(); - } - return remove(tail.prev).handler(); - } - - @Override - public ChannelPipeline replace(ChannelHandler oldHandler, String newName, ChannelHandler newHandler) { - replace(getContextOrDie(oldHandler), newName, newHandler); - return this; - } - - @Override - public ChannelHandler replace(String oldName, String newName, ChannelHandler newHandler) { - return replace(getContextOrDie(oldName), newName, newHandler); - } - - @Override - - public T replace( - Class oldHandlerType, String newName, ChannelHandler newHandler) { - return (T) replace(getContextOrDie(oldHandlerType), newName, newHandler); - } - - private ChannelHandler replace( - final AbstractChannelHandlerContext ctx, final String newName, - ChannelHandler newHandler) { - - assert ctx != head && ctx != tail; - - Future future; - synchronized (this) { - boolean sameName = ctx.name().equals(newName); - if (!sameName) { - checkDuplicateName(newName); - } - - final AbstractChannelHandlerContext newCtx = - new DefaultChannelHandlerContext(this, ctx.executor, newName, newHandler); - - if (!newCtx.channel().isRegistered() || newCtx.executor().inEventLoop()) { - replace0(ctx, newName, newCtx); - return ctx.handler(); - } else { - future = newCtx.executor().submit(new Runnable() { - @Override - public void run() { - synchronized (DefaultChannelPipeline.this) { - replace0(ctx, newName, newCtx); - } - } - }); - } - } - - // Run the following 'waiting' code outside of the above synchronized block - // in order to avoid deadlock - - waitForFuture(future); - - return ctx.handler(); - } - - private void replace0(AbstractChannelHandlerContext oldCtx, String newName, - AbstractChannelHandlerContext newCtx) { - checkMultiplicity(newCtx); - - AbstractChannelHandlerContext prev = oldCtx.prev; - AbstractChannelHandlerContext next = oldCtx.next; - newCtx.prev = prev; - newCtx.next = next; - - // Finish the replacement of oldCtx with newCtx in the linked list. - // Note that this doesn't mean events will be sent to the new handler immediately - // because we are currently at the event handler thread and no more than one handler methods can be invoked - // at the same time (we ensured that in replace().) - prev.next = newCtx; - next.prev = newCtx; - - if (!oldCtx.name().equals(newName)) { - name2ctx.remove(oldCtx.name()); - } - name2ctx.put(newName, newCtx); - - // update the reference to the replacement so forward of buffered content will work correctly - oldCtx.prev = newCtx; - oldCtx.next = newCtx; - - // Invoke newHandler.handlerAdded() first (i.e. before oldHandler.handlerRemoved() is invoked) - // because callHandlerRemoved() will trigger inboundBufferUpdated() or flush() on newHandler and those - // event handlers must be called after handlerAdded(). - callHandlerAdded(newCtx); - callHandlerRemoved(oldCtx); - } - - private static void checkMultiplicity(ChannelHandlerContext ctx) { - ChannelHandler handler = ctx.handler(); - if (handler instanceof ChannelHandlerAdapter) { - ChannelHandlerAdapter h = (ChannelHandlerAdapter) handler; - if (!h.isSharable() && h.added) { - throw new ChannelPipelineException( - h.getClass().getName() + - " is not a @Sharable handler, so can't be added or removed multiple times."); - } - h.added = true; - } - } - - private void callHandlerAdded(final ChannelHandlerContext ctx) { - if (ctx.channel().isRegistered() && !ctx.executor().inEventLoop()) { - ctx.executor().execute(new Runnable() { - @Override - public void run() { - callHandlerAdded0(ctx); - } - }); - return; - } - callHandlerAdded0(ctx); - } - - private void callHandlerAdded0(final ChannelHandlerContext ctx) { - try { - ctx.handler().handlerAdded(ctx); - } catch (Throwable t) { - boolean removed = false; - try { - remove((AbstractChannelHandlerContext) ctx); - removed = true; - } catch (Throwable t2) { - if (logger.isWarnEnabled()) { - logger.warn("Failed to remove a handler: " + ctx.name(), t2); - } - } - - if (removed) { - fireExceptionCaught(new ChannelPipelineException( - ctx.handler().getClass().getName() + - ".handlerAdded() has thrown an exception; removed.", t)); - } else { - fireExceptionCaught(new ChannelPipelineException( - ctx.handler().getClass().getName() + - ".handlerAdded() has thrown an exception; also failed to remove.", t)); - } - } - } - - private void callHandlerRemoved(final AbstractChannelHandlerContext ctx) { - if (ctx.channel().isRegistered() && !ctx.executor().inEventLoop()) { - ctx.executor().execute(new Runnable() { - @Override - public void run() { - callHandlerRemoved0(ctx); - } - }); - return; - } - callHandlerRemoved0(ctx); - } - - private void callHandlerRemoved0(final AbstractChannelHandlerContext ctx) { - // Notify the complete removal. - try { - ctx.handler().handlerRemoved(ctx); - ctx.setRemoved(); - } catch (Throwable t) { - fireExceptionCaught(new ChannelPipelineException( - ctx.handler().getClass().getName() + ".handlerRemoved() has thrown an exception.", t)); - } - } - - /** - * Waits for a future to finish. If the task is interrupted, then the current thread will be interrupted. - * It is expected that the task performs any appropriate locking. - *

- * If the internal call throws a {@link Throwable}, but it is not an instance of {@link Error} or - * {@link RuntimeException}, then it is wrapped inside a {@link ChannelPipelineException} and that is - * thrown instead.

- * - * @param future wait for this future - * @see Future#get() - * @throws Error if the task threw this. - * @throws RuntimeException if the task threw this. - * @throws ChannelPipelineException with a {@link Throwable} as a cause, if the task threw another type of - * {@link Throwable}. - */ - private static void waitForFuture(Future future) { - try { - future.get(); - } catch (ExecutionException ex) { - // In the arbitrary case, we can throw Error, RuntimeException, and Exception - Util.throwUnchecked(ex.getCause()); - } catch (InterruptedException ex) { - // Interrupt the calling thread (note that this method is not called from the event loop) - Thread.currentThread().interrupt(); - } - } - - @Override - public ChannelHandler first() { - ChannelHandlerContext first = firstContext(); - if (first == null) { - return null; - } - return first.handler(); - } - - @Override - public ChannelHandlerContext firstContext() { - AbstractChannelHandlerContext first = head.next; - if (first == tail) { - return null; - } - return head.next; - } - - @Override - public ChannelHandler last() { - AbstractChannelHandlerContext last = tail.prev; - if (last == head) { - return null; - } - return last.handler(); - } - - @Override - public ChannelHandlerContext lastContext() { - AbstractChannelHandlerContext last = tail.prev; - if (last == head) { - return null; - } - return last; - } - - @Override - public ChannelHandler get(String name) { - ChannelHandlerContext ctx = context(name); - if (ctx == null) { - return null; - } else { - return ctx.handler(); - } - } - - - @Override - public T get(Class handlerType) { - ChannelHandlerContext ctx = context(handlerType); - if (ctx == null) { - return null; - } else { - return (T) ctx.handler(); - } - } - - @Override - public ChannelHandlerContext context(String name) { - if (name == null) { - throw new NullPointerException("name"); - } - - synchronized (this) { - return name2ctx.get(name); - } - } - - @Override - public ChannelHandlerContext context(ChannelHandler handler) { - if (handler == null) { - throw new NullPointerException("handler"); - } - - AbstractChannelHandlerContext ctx = head.next; - for (;;) { - - if (ctx == null) { - return null; - } - - if (ctx.handler() == handler) { - return ctx; - } - - ctx = ctx.next; - } - } - - @Override - public ChannelHandlerContext context(Class handlerType) { - if (handlerType == null) { - throw new NullPointerException("handlerType"); - } - - AbstractChannelHandlerContext ctx = head.next; - for (;;) { - if (ctx == null) { - return null; - } - if (handlerType.isAssignableFrom(ctx.handler().getClass())) { - return ctx; - } - ctx = ctx.next; - } - } - - @Override - public List names() { - List list = new ArrayList(); - AbstractChannelHandlerContext ctx = head.next; - for (;;) { - if (ctx == null) { - return list; - } - list.add(ctx.name()); - ctx = ctx.next; - } - } - - @Override - public Map toMap() { - Map map = new LinkedHashMap(); - AbstractChannelHandlerContext ctx = head.next; - for (;;) { - if (ctx == tail) { - return map; - } - map.put(ctx.name(), ctx.handler()); - ctx = ctx.next; - } - } - - @Override - public Iterator> iterator() { - return toMap().entrySet().iterator(); - } - - /** - * Returns the {@link String} representation of this pipeline. - */ - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append(StringUtil.simpleClassName(this)); - buf.append('{'); - AbstractChannelHandlerContext ctx = head.next; - for (;;) { - if (ctx == tail) { - break; - } - - buf.append('('); - buf.append(ctx.name()); - buf.append(" = "); - buf.append(ctx.handler().getClass().getName()); - buf.append(')'); - - ctx = ctx.next; - if (ctx == tail) { - break; - } - - buf.append(", "); - } - buf.append('}'); - return buf.toString(); - } - - @Override - public ChannelPipeline fireChannelRegistered() { - head.fireChannelRegistered(); - return this; - } - - @Override - public ChannelPipeline fireChannelUnregistered() { - head.fireChannelUnregistered(); - - // Remove all handlers sequentially if channel is closed and unregistered. - if (!channel.isOpen()) { - teardownAll(); - } - return this; - } - - /** - * Removes all handlers from the pipeline one by one from tail (exclusive) to head (inclusive) to trigger - * handlerRemoved(). Note that the tail handler is excluded because it's neither an outbound handler nor it - * does anything in handlerRemoved(). - */ - private void teardownAll() { - tail.prev.teardown(); - } - - @Override - public ChannelPipeline fireChannelActive() { - head.fireChannelActive(); - - if (channel.config().isAutoRead()) { - channel.read(); - } - - return this; - } - - @Override - public ChannelPipeline fireChannelInactive() { - head.fireChannelInactive(); - return this; - } - - @Override - public ChannelPipeline fireExceptionCaught(Throwable cause) { - head.fireExceptionCaught(cause); - return this; - } - - @Override - public ChannelPipeline fireUserEventTriggered(Object event) { - head.fireUserEventTriggered(event); - return this; - } - - @Override - public ChannelPipeline fireChannelRead(Object msg) { - head.fireChannelRead(msg); - return this; - } - - @Override - public ChannelPipeline fireChannelReadComplete() { - head.fireChannelReadComplete(); - if (channel.config().isAutoRead()) { - read(); - } - return this; - } - - @Override - public ChannelPipeline fireChannelWritabilityChanged() { - head.fireChannelWritabilityChanged(); - return this; - } - - @Override - public ChannelFuture bind(SocketAddress localAddress) { - return tail.bind(localAddress); - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress) { - return tail.connect(remoteAddress); - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { - return tail.connect(remoteAddress, localAddress); - } - - @Override - public ChannelFuture disconnect() { - return tail.disconnect(); - } - - @Override - public ChannelFuture close() { - return tail.close(); - } - - @Override - public ChannelFuture deregister() { - return tail.deregister(); - } - - @Override - public ChannelPipeline flush() { - tail.flush(); - return this; - } - - @Override - public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { - return tail.bind(localAddress, promise); - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { - return tail.connect(remoteAddress, promise); - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { - return tail.connect(remoteAddress, localAddress, promise); - } - - @Override - public ChannelFuture disconnect(ChannelPromise promise) { - return tail.disconnect(promise); - } - - @Override - public ChannelFuture close(ChannelPromise promise) { - return tail.close(promise); - } - - @Override - public ChannelFuture deregister(final ChannelPromise promise) { - return tail.deregister(promise); - } - - @Override - public ChannelPipeline read() { - tail.read(); - return this; - } - - @Override - public ChannelFuture write(Object msg) { - return tail.write(msg); - } - - @Override - public ChannelFuture write(Object msg, ChannelPromise promise) { - return tail.write(msg, promise); - } - - @Override - public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { - return tail.writeAndFlush(msg, promise); - } - - @Override - public ChannelFuture writeAndFlush(Object msg) { - return tail.writeAndFlush(msg); - } - - private void checkDuplicateName(String name) { - if (name2ctx.containsKey(name)) { - throw new IllegalArgumentException("Duplicate handler name: " + name); - } - } - - private AbstractChannelHandlerContext getContextOrDie(String name) { - AbstractChannelHandlerContext ctx = (AbstractChannelHandlerContext) context(name); - if (ctx == null) { - throw new NoSuchElementException(name); - } else { - return ctx; - } - } - - private AbstractChannelHandlerContext getContextOrDie(ChannelHandler handler) { - AbstractChannelHandlerContext ctx = (AbstractChannelHandlerContext) context(handler); - if (ctx == null) { - throw new NoSuchElementException(handler.getClass().getName()); - } else { - return ctx; - } - } - - private AbstractChannelHandlerContext getContextOrDie(Class handlerType) { - AbstractChannelHandlerContext ctx = (AbstractChannelHandlerContext) context(handlerType); - if (ctx == null) { - throw new NoSuchElementException(handlerType.getName()); - } else { - return ctx; - } - } - - // A special catch-all handler that handles both bytes and messages. - static final class TailContext extends AbstractChannelHandlerContext implements ChannelInboundHandler { - - private static final String TAIL_NAME = generateName0(TailContext.class); - - TailContext(DefaultChannelPipeline pipeline) { - super(pipeline, null, TAIL_NAME, true, false); - } - - @Override - public ChannelHandler handler() { - return this; - } - - @Override - public void channelRegistered(ChannelHandlerContext ctx) throws Exception { } - - @Override - public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { } - - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { } - - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { } - - @Override - public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { } - - @Override - public void handlerAdded(ChannelHandlerContext ctx) throws Exception { } - - @Override - public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { } - - @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - logger.warn( - "An exceptionCaught() event was fired, and it reached at the tail of the pipeline. " + - "It usually means the last handler in the pipeline did not handle the exception.", cause); - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - try { - logger.debug( - "Discarded inbound message {} that reached at the tail of the pipeline. " + - "Please check your pipeline configuration.", msg); - } finally { - ReferenceCountUtil.release(msg); - } - } - - @Override - public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { } - } - - static final class HeadContext extends AbstractChannelHandlerContext implements ChannelOutboundHandler { - - private static final String HEAD_NAME = generateName0(HeadContext.class); - - protected final Unsafe unsafe; - - HeadContext(DefaultChannelPipeline pipeline) { - super(pipeline, null, HEAD_NAME, false, true); - unsafe = pipeline.channel().unsafe(); - } - - @Override - public ChannelHandler handler() { - return this; - } - - @Override - public void handlerAdded(ChannelHandlerContext ctx) throws Exception { - // NOOP - } - - @Override - public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { - // NOOP - } - - @Override - public void bind( - ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) - throws Exception { - unsafe.bind(localAddress, promise); - } - - @Override - public void connect( - ChannelHandlerContext ctx, - SocketAddress remoteAddress, SocketAddress localAddress, - ChannelPromise promise) throws Exception { - unsafe.connect(remoteAddress, localAddress, promise); - } - - @Override - public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { - unsafe.disconnect(promise); - } - - @Override - public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { - unsafe.close(promise); - } - - @Override - public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { - unsafe.deregister(promise); - } - - @Override - public void read(ChannelHandlerContext ctx) { - unsafe.beginRead(); - } - - @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { - unsafe.write(msg, promise); - } - - @Override - public void flush(ChannelHandlerContext ctx) throws Exception { - unsafe.flush(); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - ctx.fireExceptionCaught(cause); - } - } -} diff --git a/common/src/main/java/common/net/channel/DefaultChannelPromise.java b/common/src/main/java/common/net/channel/DefaultChannelPromise.java deleted file mode 100644 index 02cc235..0000000 --- a/common/src/main/java/common/net/channel/DefaultChannelPromise.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.util.concurrent.DefaultPromise; -import common.net.util.concurrent.EventExecutor; -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; - -/** - * The default {@link ChannelPromise} implementation. It is recommended to use {@link Channel#newPromise()} to create - * a new {@link ChannelPromise} rather than calling the constructor explicitly. - */ -public class DefaultChannelPromise extends DefaultPromise implements ChannelPromise { - - private final Channel channel; -// private long checkpoint; - - /** - * Creates a new instance. - * - * @param channel - * the {@link Channel} associated with this future - */ - public DefaultChannelPromise(Channel channel) { - this.channel = channel; - } - - /** - * Creates a new instance. - * - * @param channel - * the {@link Channel} associated with this future - */ - public DefaultChannelPromise(Channel channel, EventExecutor executor) { - super(executor); - this.channel = channel; - } - - @Override - protected EventExecutor executor() { - EventExecutor e = super.executor(); - if (e == null) { - return channel().eventLoop(); - } else { - return e; - } - } - - @Override - public Channel channel() { - return channel; - } - - @Override - public ChannelPromise setSuccess() { - return setSuccess(null); - } - - @Override - public ChannelPromise setSuccess(Void result) { - super.setSuccess(result); - return this; - } - - @Override - public boolean trySuccess() { - return trySuccess(null); - } - - @Override - public ChannelPromise setFailure(Throwable cause) { - super.setFailure(cause); - return this; - } - - @Override - public ChannelPromise addListener(GenericFutureListener> listener) { - super.addListener(listener); - return this; - } - - @Override - public ChannelPromise addListeners(GenericFutureListener>... listeners) { - super.addListeners(listeners); - return this; - } - - @Override - public ChannelPromise removeListener(GenericFutureListener> listener) { - super.removeListener(listener); - return this; - } - - @Override - public ChannelPromise removeListeners(GenericFutureListener>... listeners) { - super.removeListeners(listeners); - return this; - } - - @Override - public ChannelPromise sync() throws InterruptedException { - super.sync(); - return this; - } - - @Override - public ChannelPromise syncUninterruptibly() { - super.syncUninterruptibly(); - return this; - } - - @Override - public ChannelPromise await() throws InterruptedException { - super.await(); - return this; - } - - @Override - public ChannelPromise awaitUninterruptibly() { - super.awaitUninterruptibly(); - return this; - } - -// @Override -// public long flushCheckpoint() { -// return checkpoint; -// } - -// @Override -// public void flushCheckpoint(long checkpoint) { -// this.checkpoint = checkpoint; -// } - -// @Override -// public ChannelPromise promise() { -// return this; -// } - - @Override - protected void checkDeadLock() { - if (channel().isRegistered()) { - super.checkDeadLock(); - } - } -} diff --git a/common/src/main/java/common/net/channel/DefaultMessageSizeEstimator.java b/common/src/main/java/common/net/channel/DefaultMessageSizeEstimator.java deleted file mode 100644 index 0862e96..0000000 --- a/common/src/main/java/common/net/channel/DefaultMessageSizeEstimator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.buffer.ByteBuf; - -/** - * Default {@link MessageSizeEstimator} implementation which supports the estimation of the size of - * {@link ByteBuf}, {@link ByteBufHolder} and {@link FileRegion}. - */ -public final class DefaultMessageSizeEstimator implements MessageSizeEstimator { - - private static final class HandleImpl implements Handle { - private final int unknownSize; - - private HandleImpl(int unknownSize) { - this.unknownSize = unknownSize; - } - - @Override - public int size(Object msg) { - if (msg instanceof ByteBuf) { - return ((ByteBuf) msg).readableBytes(); - } -// if (msg instanceof ByteBufHolder) { -// return ((ByteBufHolder) msg).content().readableBytes(); -// } -// if (msg instanceof FileRegion) { -// return 0; -// } - return unknownSize; - } - } - - /** - * Return the default implementation which returns {@code -1} for unknown messages. - */ - public static final MessageSizeEstimator DEFAULT = new DefaultMessageSizeEstimator(0); - - private final Handle handle; - - /** - * Create a new instance - * - * @param unknownSize The size which is returned for unknown messages. - */ - public DefaultMessageSizeEstimator(int unknownSize) { - if (unknownSize < 0) { - throw new IllegalArgumentException("unknownSize: " + unknownSize + " (expected: >= 0)"); - } - handle = new HandleImpl(unknownSize); - } - - @Override - public Handle newHandle() { - return handle; - } -} diff --git a/common/src/main/java/common/net/channel/EventLoop.java b/common/src/main/java/common/net/channel/EventLoop.java deleted file mode 100644 index 8daea7a..0000000 --- a/common/src/main/java/common/net/channel/EventLoop.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.util.concurrent.EventExecutor; - -/** - * Will handle all the I/O-Operations for a {@link Channel} once it was registered. - * - * One {@link EventLoop} instance will usually handle more then one {@link Channel} but this may depend on - * implementation details and internals. - * - */ -public interface EventLoop extends EventExecutor, EventLoopGroup { - @Override - EventLoopGroup parent(); -} diff --git a/common/src/main/java/common/net/channel/EventLoopException.java b/common/src/main/java/common/net/channel/EventLoopException.java deleted file mode 100644 index 02f9ffa..0000000 --- a/common/src/main/java/common/net/channel/EventLoopException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -/** - * Special {@link ChannelException} which will be thrown by {@link EventLoop} and {@link EventLoopGroup} - * implementations when an error occurs. - */ -public class EventLoopException extends ChannelException { - - private static final long serialVersionUID = -8969100344583703616L; - - public EventLoopException() { - } - - public EventLoopException(String message, Throwable cause) { - super(message, cause); - } - - public EventLoopException(String message) { - super(message); - } - - public EventLoopException(Throwable cause) { - super(cause); - } - -} diff --git a/common/src/main/java/common/net/channel/EventLoopGroup.java b/common/src/main/java/common/net/channel/EventLoopGroup.java deleted file mode 100644 index e058491..0000000 --- a/common/src/main/java/common/net/channel/EventLoopGroup.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.util.concurrent.EventExecutorGroup; - -/** - * Special {@link EventExecutorGroup} which allows to register {@link Channel}'s that get - * processed for later selection during the event loop. - * - */ -public interface EventLoopGroup extends EventExecutorGroup { - /** - * Return the next {@link EventLoop} to use - */ - @Override - EventLoop next(); - - /** - * Register a {@link Channel} with this {@link EventLoop}. The returned {@link ChannelFuture} - * will get notified once the registration was complete. - */ - ChannelFuture register(Channel channel); - - /** - * Register a {@link Channel} with this {@link EventLoop}. The passed {@link ChannelFuture} - * will get notified once the registration was complete and also will get returned. - */ - ChannelFuture register(Channel channel, ChannelPromise promise); -} diff --git a/common/src/main/java/common/net/channel/FailedChannelFuture.java b/common/src/main/java/common/net/channel/FailedChannelFuture.java deleted file mode 100644 index f357ae5..0000000 --- a/common/src/main/java/common/net/channel/FailedChannelFuture.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.util.concurrent.EventExecutor; -import common.util.Util; - -/** - * The {@link CompleteChannelFuture} which is failed already. It is - * recommended to use {@link Channel#newFailedFuture(Throwable)} - * instead of calling the constructor of this future. - */ -final class FailedChannelFuture extends CompleteChannelFuture { - - private final Throwable cause; - - /** - * Creates a new instance. - * - * @param channel the {@link Channel} associated with this future - * @param cause the cause of failure - */ - FailedChannelFuture(Channel channel, EventExecutor executor, Throwable cause) { - super(channel, executor); - if (cause == null) { - throw new NullPointerException("cause"); - } - this.cause = cause; - } - - @Override - public Throwable cause() { - return cause; - } - - @Override - public boolean isSuccess() { - return false; - } - - @Override - public ChannelFuture sync() { - Util.throwUnchecked(cause); - return this; - } - - @Override - public ChannelFuture syncUninterruptibly() { - Util.throwUnchecked(cause); - return this; - } -} diff --git a/common/src/main/java/common/net/channel/MessageSizeEstimator.java b/common/src/main/java/common/net/channel/MessageSizeEstimator.java deleted file mode 100644 index cdefc87..0000000 --- a/common/src/main/java/common/net/channel/MessageSizeEstimator.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -/** - * Responsible to estimate size of a message. The size represent how much memory the message will ca. reserve in - * memory. - */ -public interface MessageSizeEstimator { - - /** - * Creates a new handle. The handle provides the actual operations. - */ - Handle newHandle(); - - interface Handle { - - /** - * Calculate the size of the given message. - * - * @param msg The message for which the size should be calculated - * @return size The size in bytes. The returned size must be >= 0 - */ - int size(Object msg); - } -} diff --git a/common/src/main/java/common/net/channel/MultithreadEventLoopGroup.java b/common/src/main/java/common/net/channel/MultithreadEventLoopGroup.java deleted file mode 100644 index 0a5f4e1..0000000 --- a/common/src/main/java/common/net/channel/MultithreadEventLoopGroup.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.util.concurrent.ThreadFactory; - -import common.net.util.concurrent.DefaultThreadFactory; -import common.net.util.concurrent.MultithreadEventExecutorGroup; -import common.net.util.internal.SystemPropertyUtil; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * Abstract base class for {@link EventLoopGroup} implementations that handles their tasks with multiple threads at - * the same time. - */ -public abstract class MultithreadEventLoopGroup extends MultithreadEventExecutorGroup implements EventLoopGroup { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(MultithreadEventLoopGroup.class); - - private static final int DEFAULT_EVENT_LOOP_THREADS; - - static { - DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt( - "game.net.eventLoopThreads", Runtime.getRuntime().availableProcessors() * 2)); - - if (logger.isDebugEnabled()) { - logger.debug("-Dgame.net.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS); - } - } - - /** - * @see {@link MultithreadEventExecutorGroup#MultithreadEventExecutorGroup(int, ThreadFactory, Object...)} - */ - protected MultithreadEventLoopGroup(int nThreads, ThreadFactory threadFactory, Object... args) { - super(nThreads == 0? DEFAULT_EVENT_LOOP_THREADS : nThreads, threadFactory, args); - } - - @Override - protected ThreadFactory newDefaultThreadFactory() { - return new DefaultThreadFactory(getClass(), Thread.MAX_PRIORITY); - } - - @Override - public EventLoop next() { - return (EventLoop) super.next(); - } - - @Override - public ChannelFuture register(Channel channel) { - return next().register(channel); - } - - @Override - public ChannelFuture register(Channel channel, ChannelPromise promise) { - return next().register(channel, promise); - } -} diff --git a/common/src/main/java/common/net/channel/RecvByteBufAllocator.java b/common/src/main/java/common/net/channel/RecvByteBufAllocator.java deleted file mode 100644 index f90ff3f..0000000 --- a/common/src/main/java/common/net/channel/RecvByteBufAllocator.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.buffer.ByteBuf; -import common.net.buffer.ByteBufAllocator; - -/** - * Allocates a new receive buffer whose capacity is probably large enough to read all inbound data and small enough - * not to waste its space. - */ -public interface RecvByteBufAllocator { - - /** - * Creates a new handle. The handle provides the actual operations and keeps the internal information which is - * required for predicting an optimal buffer capacity. - */ - Handle newHandle(); - - interface Handle { - /** - * Creates a new receive buffer whose capacity is probably large enough to read all inbound data and small - * enough not to waste its space. - */ - ByteBuf allocate(ByteBufAllocator alloc); - - /** - * Similar to {@link #allocate(ByteBufAllocator)} except that it does not allocate anything but just tells the - * capacity. - */ - int guess(); - - /** - * Records the the actual number of read bytes in the previous read operation so that the allocator allocates - * the buffer with potentially more correct capacity. - * - * @param actualReadBytes the actual number of read bytes in the previous read operation - */ - void record(int actualReadBytes); - } -} diff --git a/common/src/main/java/common/net/channel/ServerChannel.java b/common/src/main/java/common/net/channel/ServerChannel.java deleted file mode 100644 index 7dedcaa..0000000 --- a/common/src/main/java/common/net/channel/ServerChannel.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -/** - * A {@link Channel} that accepts an incoming connection attempt and creates - * its child {@link Channel}s by accepting them. {@link ServerSocketChannel} is - * a good example. - */ -public interface ServerChannel extends Channel { - // This is a tag interface. -} diff --git a/common/src/main/java/common/net/channel/SimpleChannelInboundHandler.java b/common/src/main/java/common/net/channel/SimpleChannelInboundHandler.java deleted file mode 100644 index 68b003e..0000000 --- a/common/src/main/java/common/net/channel/SimpleChannelInboundHandler.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.util.ReferenceCountUtil; -import common.net.util.internal.TypeParameterMatcher; - -/** - * {@link ChannelInboundHandlerAdapter} which allows to explicit only handle a specific type of messages. - * - * For example here is an implementation which only handle {@link String} messages. - * - *
- *     public class StringHandler extends
- *             {@link SimpleChannelInboundHandler}<{@link String}> {
- *
- *         {@code @Override}
- *         protected void channelRead0({@link ChannelHandlerContext} ctx, {@link String} message)
- *                 throws {@link Exception} {
- *             System.out.println(message);
- *         }
- *     }
- * 
- * - * Be aware that depending of the constructor parameters it will release all handled messages by pass them to - * {@link ReferenceCountUtil#release(Object)}. In this case you may need to use - * {@link ReferenceCountUtil#retain(Object)} if you pass the object to the next handler in the {@link ChannelPipeline}. - * - *

Forward compatibility notice

- *

- * Please keep in mind that {@link #channelRead0(ChannelHandlerContext, I)} will be renamed to - * {@code messageReceived(ChannelHandlerContext, I)} in 5.0. - *

- */ -public abstract class SimpleChannelInboundHandler extends ChannelInboundHandlerAdapter { - - private final TypeParameterMatcher matcher; - private final boolean autoRelease; - - /** - * @see {@link #SimpleChannelInboundHandler(boolean)} with {@code true} as boolean parameter. - */ - protected SimpleChannelInboundHandler() { - this(true); - } - - /** - * Create a new instance which will try to detect the types to match out of the type parameter of the class. - * - * @param autoRelease {@code true} if handled messages should be released automatically by pass them to - * {@link ReferenceCountUtil#release(Object)}. - */ - protected SimpleChannelInboundHandler(boolean autoRelease) { - matcher = TypeParameterMatcher.find(this, SimpleChannelInboundHandler.class, "I"); - this.autoRelease = autoRelease; - } - - /** - * @see {@link #SimpleChannelInboundHandler(Class, boolean)} with {@code true} as boolean value. - */ - protected SimpleChannelInboundHandler(Class inboundMessageType) { - this(inboundMessageType, true); - } - - /** - * Create a new instance - * - * @param inboundMessageType The type of messages to match - * @param autoRelease {@code true} if handled messages should be released automatically by pass them to - * {@link ReferenceCountUtil#release(Object)}. - */ - protected SimpleChannelInboundHandler(Class inboundMessageType, boolean autoRelease) { - matcher = TypeParameterMatcher.get(inboundMessageType); - this.autoRelease = autoRelease; - } - - /** - * Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next - * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - */ - public boolean acceptInboundMessage(Object msg) throws Exception { - return matcher.match(msg); - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - boolean release = true; - try { - if (acceptInboundMessage(msg)) { - - I imsg = (I) msg; - channelRead0(ctx, imsg); - } else { - release = false; - ctx.fireChannelRead(msg); - } - } finally { - if (autoRelease && release) { - ReferenceCountUtil.release(msg); - } - } - } - - /** - * Please keep in mind that this method will be renamed to - * {@code messageReceived(ChannelHandlerContext, I)} in 5.0. - * - * Is called for each message of type {@link I}. - * - * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler} - * belongs to - * @param msg the message to handle - * @throws Exception is thrown if an error occurred - */ - protected abstract void channelRead0(ChannelHandlerContext ctx, I msg) throws Exception; -} diff --git a/common/src/main/java/common/net/channel/SingleThreadEventLoop.java b/common/src/main/java/common/net/channel/SingleThreadEventLoop.java deleted file mode 100644 index ed45956..0000000 --- a/common/src/main/java/common/net/channel/SingleThreadEventLoop.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.util.concurrent.ThreadFactory; - -import common.net.util.concurrent.SingleThreadEventExecutor; - -/** - * Abstract base class for {@link EventLoop}'s that execute all its submitted tasks in a single thread. - * - */ -public abstract class SingleThreadEventLoop extends SingleThreadEventExecutor implements EventLoop { - - /** - * @see {@link SingleThreadEventExecutor#SingleThreadEventExecutor(EventExecutorGroup, ThreadFactory, boolean)} - */ - protected SingleThreadEventLoop(EventLoopGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp) { - super(parent, threadFactory, addTaskWakesUp); - } - - @Override - public EventLoopGroup parent() { - return (EventLoopGroup) super.parent(); - } - - @Override - public EventLoop next() { - return (EventLoop) super.next(); - } - - @Override - public ChannelFuture register(Channel channel) { - return register(channel, new DefaultChannelPromise(channel, this)); - } - - @Override - public ChannelFuture register(final Channel channel, final ChannelPromise promise) { - if (channel == null) { - throw new NullPointerException("channel"); - } - if (promise == null) { - throw new NullPointerException("promise"); - } - - channel.unsafe().register(this, promise); - return promise; - } - - @Override - protected boolean wakesUpForTask(Runnable task) { - return !(task instanceof NonWakeupRunnable); - } - - /** - * Marker interface for {@linkRunnable} that will not trigger an {@link #wakeup(boolean)} in all cases. - */ - interface NonWakeupRunnable extends Runnable { } -} diff --git a/common/src/main/java/common/net/channel/SucceededChannelFuture.java b/common/src/main/java/common/net/channel/SucceededChannelFuture.java deleted file mode 100644 index f2fafea..0000000 --- a/common/src/main/java/common/net/channel/SucceededChannelFuture.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import common.net.util.concurrent.EventExecutor; - -/** - * The {@link CompleteChannelFuture} which is succeeded already. It is - * recommended to use {@link Channel#newSucceededFuture()} instead of - * calling the constructor of this future. - */ -final class SucceededChannelFuture extends CompleteChannelFuture { - - /** - * Creates a new instance. - * - * @param channel the {@link Channel} associated with this future - */ - SucceededChannelFuture(Channel channel, EventExecutor executor) { - super(channel, executor); - } - - @Override - public Throwable cause() { - return null; - } - - @Override - public boolean isSuccess() { - return true; - } -} diff --git a/common/src/main/java/common/net/channel/VoidChannelPromise.java b/common/src/main/java/common/net/channel/VoidChannelPromise.java deleted file mode 100644 index 1fcbb12..0000000 --- a/common/src/main/java/common/net/channel/VoidChannelPromise.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel; - -import java.util.concurrent.TimeUnit; - -import common.net.util.concurrent.AbstractFuture; -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; - -final class VoidChannelPromise extends AbstractFuture implements ChannelPromise { - - private final Channel channel; - private final boolean fireException; - - /** - * Creates a new instance. - * - * @param channel the {@link Channel} associated with this future - */ - VoidChannelPromise(Channel channel, boolean fireException) { - if (channel == null) { - throw new NullPointerException("channel"); - } - this.channel = channel; - this.fireException = fireException; - } - - @Override - public VoidChannelPromise addListener(GenericFutureListener> listener) { - fail(); - return this; - } - - @Override - public VoidChannelPromise addListeners(GenericFutureListener>... listeners) { - fail(); - return this; - } - - @Override - public VoidChannelPromise removeListener(GenericFutureListener> listener) { - // NOOP - return this; - } - - @Override - public VoidChannelPromise removeListeners(GenericFutureListener>... listeners) { - // NOOP - return this; - } - - @Override - public VoidChannelPromise await() throws InterruptedException { - if (Thread.interrupted()) { - throw new InterruptedException(); - } - return this; - } - - @Override - public boolean await(long timeout, TimeUnit unit) { - fail(); - return false; - } - - @Override - public boolean await(long timeoutMillis) { - fail(); - return false; - } - - @Override - public VoidChannelPromise awaitUninterruptibly() { - fail(); - return this; - } - - @Override - public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { - fail(); - return false; - } - - @Override - public boolean awaitUninterruptibly(long timeoutMillis) { - fail(); - return false; - } - - @Override - public Channel channel() { - return channel; - } - - @Override - public boolean isDone() { - return false; - } - - @Override - public boolean isSuccess() { - return false; - } - - @Override - public boolean setUncancellable() { - return true; - } - - @Override - public boolean isCancellable() { - return false; - } - - @Override - public boolean isCancelled() { - return false; - } - - @Override - public Throwable cause() { - return null; - } - - @Override - public VoidChannelPromise sync() { - fail(); - return this; - } - - @Override - public VoidChannelPromise syncUninterruptibly() { - fail(); - return this; - } - @Override - public VoidChannelPromise setFailure(Throwable cause) { - fireException(cause); - return this; - } - - @Override - public VoidChannelPromise setSuccess() { - return this; - } - - @Override - public boolean tryFailure(Throwable cause) { - fireException(cause); - return false; - } - - @Override - public boolean cancel(boolean mayInterruptIfRunning) { - return false; - } - - @Override - public boolean trySuccess() { - return false; - } - - private static void fail() { - throw new IllegalStateException("void future"); - } - - @Override - public VoidChannelPromise setSuccess(Void result) { - return this; - } - - @Override - public boolean trySuccess(Void result) { - return false; - } - - @Override - public Void getNow() { - return null; - } - - private void fireException(Throwable cause) { - // Only fire the exception if the channel is open and registered - // if not the pipeline is not setup and so it would hit the tail - // of the pipeline. - // See https://github.com/netty/netty/issues/1517 - if (fireException && channel.isRegistered()) { - channel.pipeline().fireExceptionCaught(cause); - } - } -} diff --git a/common/src/main/java/common/net/channel/local/LocalAddress.java b/common/src/main/java/common/net/channel/local/LocalAddress.java deleted file mode 100644 index 95f6e43..0000000 --- a/common/src/main/java/common/net/channel/local/LocalAddress.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.local; - -import java.net.SocketAddress; - -import common.net.channel.Channel; - -/** - * An endpoint in the local transport. Each endpoint is identified by a unique - * case-insensitive string. - */ -public final class LocalAddress extends SocketAddress implements Comparable { - - private static final long serialVersionUID = 4644331421130916435L; - - public static final LocalAddress ANY = new LocalAddress("ANY"); - - private final String id; - private final String strVal; - - /** - * Creates a new ephemeral port based on the ID of the specified channel. - * Note that we prepend an upper-case character so that it never conflicts with - * the addresses created by a user, which are always lower-cased on construction time. - */ - LocalAddress(Channel channel) { - StringBuilder buf = new StringBuilder(16); - buf.append("local:E"); - buf.append(Long.toHexString(channel.hashCode() & 0xFFFFFFFFL | 0x100000000L)); - buf.setCharAt(7, ':'); - id = buf.substring(6); - strVal = buf.toString(); - } - - /** - * Creates a new instance with the specified ID. - */ - public LocalAddress(String id) { - if (id == null) { - throw new NullPointerException("id"); - } - id = id.trim().toLowerCase(); - if (id.isEmpty()) { - throw new IllegalArgumentException("empty id"); - } - this.id = id; - strVal = "local:" + id; - } - - /** - * Returns the ID of this address. - */ - public String id() { - return id; - } - - @Override - public int hashCode() { - return id.hashCode(); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof LocalAddress)) { - return false; - } - - return id.equals(((LocalAddress) o).id); - } - - @Override - public int compareTo(LocalAddress o) { - return id.compareTo(o.id); - } - - @Override - public String toString() { - return strVal; - } -} diff --git a/common/src/main/java/common/net/channel/local/LocalChannel.java b/common/src/main/java/common/net/channel/local/LocalChannel.java deleted file mode 100644 index c5590c9..0000000 --- a/common/src/main/java/common/net/channel/local/LocalChannel.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.local; - -import java.net.SocketAddress; -import java.nio.channels.AlreadyConnectedException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.ConnectionPendingException; -import java.nio.channels.NotYetConnectedException; -import java.util.ArrayDeque; -import java.util.Collections; -import java.util.Queue; - -import common.net.channel.AbstractChannel; -import common.net.channel.Channel; -import common.net.channel.ChannelConfig; -import common.net.channel.ChannelException; -import common.net.channel.ChannelMetadata; -import common.net.channel.ChannelOutboundBuffer; -import common.net.channel.ChannelPipeline; -import common.net.channel.ChannelPromise; -import common.net.channel.DefaultChannelConfig; -import common.net.channel.EventLoop; -import common.net.channel.SingleThreadEventLoop; -import common.net.util.ReferenceCountUtil; -import common.net.util.concurrent.SingleThreadEventExecutor; -import common.net.util.internal.InternalThreadLocalMap; - -/** - * A {@link Channel} for the local transport. - */ -public class LocalChannel extends AbstractChannel { - - private static final ChannelMetadata METADATA = new ChannelMetadata(false); - - private static final int MAX_READER_STACK_DEPTH = 8; - - private final ChannelConfig config = new DefaultChannelConfig(this); - private final Queue inboundBuffer = new ArrayDeque(); - private final Runnable readTask = new Runnable() { - @Override - public void run() { - ChannelPipeline pipeline = pipeline(); - for (;;) { - Object m = inboundBuffer.poll(); - if (m == null) { - break; - } - pipeline.fireChannelRead(m); - } - pipeline.fireChannelReadComplete(); - } - }; - - private final Runnable shutdownHook = new Runnable() { - @Override - public void run() { - unsafe().close(unsafe().voidPromise()); - } - }; - - private volatile int state; // 0 - open, 1 - bound, 2 - connected, 3 - closed - private volatile LocalChannel peer; - private volatile LocalAddress localAddress; - private volatile LocalAddress remoteAddress; - private volatile ChannelPromise connectPromise; - private volatile boolean readInProgress; - private volatile boolean registerInProgress; - - public LocalChannel() { - super(null); - } - - LocalChannel(LocalServerChannel parent, LocalChannel peer) { - super(parent); - this.peer = peer; - localAddress = parent.localAddress(); - remoteAddress = peer.localAddress(); - } - - @Override - public ChannelMetadata metadata() { - return METADATA; - } - - @Override - public ChannelConfig config() { - return config; - } - - @Override - public LocalServerChannel parent() { - return (LocalServerChannel) super.parent(); - } - - @Override - public LocalAddress localAddress() { - return (LocalAddress) super.localAddress(); - } - - @Override - public LocalAddress remoteAddress() { - return (LocalAddress) super.remoteAddress(); - } - - @Override - public boolean isOpen() { - return state < 3; - } - - @Override - public boolean isActive() { - return state == 2; - } - - @Override - protected AbstractUnsafe newUnsafe() { - return new LocalUnsafe(); - } - - @Override - protected boolean isCompatible(EventLoop loop) { - return loop instanceof SingleThreadEventLoop; - } - - @Override - protected SocketAddress localAddress0() { - return localAddress; - } - - @Override - protected SocketAddress remoteAddress0() { - return remoteAddress; - } - - @Override - protected void doRegister() throws Exception { - // Check if both peer and parent are non-null because this channel was created by a LocalServerChannel. - // This is needed as a peer may not be null also if a LocalChannel was connected before and - // deregistered / registered later again. - // - // See https://github.com/netty/netty/issues/2400 - if (peer != null && parent() != null) { - // Store the peer in a local variable as it may be set to null if doClose() is called. - // Because of this we also set registerInProgress to true as we check for this in doClose() and make sure - // we delay the fireChannelInactive() to be fired after the fireChannelActive() and so keep the correct - // order of events. - // - // See https://github.com/netty/netty/issues/2144 - final LocalChannel peer = this.peer; - registerInProgress = true; - state = 2; - - peer.remoteAddress = parent().localAddress(); - peer.state = 2; - - // Always call peer.eventLoop().execute() even if peer.eventLoop().inEventLoop() is true. - // This ensures that if both channels are on the same event loop, the peer's channelActive - // event is triggered *after* this channel's channelRegistered event, so that this channel's - // pipeline is fully initialized by ChannelInitializer before any channelRead events. - peer.eventLoop().execute(new Runnable() { - @Override - public void run() { - registerInProgress = false; - peer.pipeline().fireChannelActive(); - peer.connectPromise.setSuccess(); - } - }); - } - ((SingleThreadEventExecutor) eventLoop()).addShutdownHook(shutdownHook); - } - - @Override - protected void doBind(SocketAddress localAddress) throws Exception { - this.localAddress = - LocalChannelRegistry.register(this, this.localAddress, - localAddress); - state = 1; - } - - @Override - protected void doDisconnect() throws Exception { - doClose(); - } - - @Override - protected void doClose() throws Exception { - if (state <= 2) { - // Update all internal state before the closeFuture is notified. - if (localAddress != null) { - if (parent() == null) { - LocalChannelRegistry.unregister(localAddress); - } - localAddress = null; - } - state = 3; - } - - final LocalChannel peer = this.peer; - if (peer != null && peer.isActive()) { - // Need to execute the close in the correct EventLoop - // See https://github.com/netty/netty/issues/1777 - EventLoop eventLoop = peer.eventLoop(); - - // Also check if the registration was not done yet. In this case we submit the close to the EventLoop - // to make sure it is run after the registration completes. - // - // See https://github.com/netty/netty/issues/2144 - if (eventLoop.inEventLoop() && !registerInProgress) { - peer.unsafe().close(unsafe().voidPromise()); - } else { - peer.eventLoop().execute(new Runnable() { - @Override - public void run() { - peer.unsafe().close(unsafe().voidPromise()); - } - }); - } - this.peer = null; - } - } - - @Override - protected void doDeregister() throws Exception { - // Just remove the shutdownHook as this Channel may be closed later or registered to another EventLoop - ((SingleThreadEventExecutor) eventLoop()).removeShutdownHook(shutdownHook); - } - - @Override - protected void doBeginRead() throws Exception { - if (readInProgress) { - return; - } - - ChannelPipeline pipeline = pipeline(); - Queue inboundBuffer = this.inboundBuffer; - if (inboundBuffer.isEmpty()) { - readInProgress = true; - return; - } - - final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get(); - final Integer stackDepth = threadLocals.localChannelReaderStackDepth(); - if (stackDepth < MAX_READER_STACK_DEPTH) { - threadLocals.setLocalChannelReaderStackDepth(stackDepth + 1); - try { - for (;;) { - Object received = inboundBuffer.poll(); - if (received == null) { - break; - } - pipeline.fireChannelRead(received); - } - pipeline.fireChannelReadComplete(); - } finally { - threadLocals.setLocalChannelReaderStackDepth(stackDepth); - } - } else { - eventLoop().execute(readTask); - } - } - - @Override - protected void doWrite(ChannelOutboundBuffer in) throws Exception { - if (state < 2) { - throw new NotYetConnectedException(); - } - if (state > 2) { - throw new ClosedChannelException(); - } - - final LocalChannel peer = this.peer; - final ChannelPipeline peerPipeline = peer.pipeline(); - final EventLoop peerLoop = peer.eventLoop(); - - if (peerLoop == eventLoop()) { - for (;;) { - Object msg = in.current(); - if (msg == null) { - break; - } - peer.inboundBuffer.add(msg); - ReferenceCountUtil.retain(msg); - in.remove(); - } - finishPeerRead(peer, peerPipeline); - } else { - // Use a copy because the original msgs will be recycled by AbstractChannel. - final Object[] msgsCopy = new Object[in.size()]; - for (int i = 0; i < msgsCopy.length; i ++) { - msgsCopy[i] = ReferenceCountUtil.retain(in.current()); - in.remove(); - } - - peerLoop.execute(new Runnable() { - @Override - public void run() { - Collections.addAll(peer.inboundBuffer, msgsCopy); - finishPeerRead(peer, peerPipeline); - } - }); - } - } - - private static void finishPeerRead(LocalChannel peer, ChannelPipeline peerPipeline) { - if (peer.readInProgress) { - peer.readInProgress = false; - for (;;) { - Object received = peer.inboundBuffer.poll(); - if (received == null) { - break; - } - peerPipeline.fireChannelRead(received); - } - peerPipeline.fireChannelReadComplete(); - } - } - - private class LocalUnsafe extends AbstractUnsafe { - - @Override - public void connect(final SocketAddress remoteAddress, - SocketAddress localAddress, final ChannelPromise promise) { - if (!promise.setUncancellable() || !ensureOpen(promise)) { - return; - } - - if (state == 2) { - Exception cause = new AlreadyConnectedException(); - safeSetFailure(promise, cause); - pipeline().fireExceptionCaught(cause); - return; - } - - if (connectPromise != null) { - throw new ConnectionPendingException(); - } - - connectPromise = promise; - - if (state != 1) { - // Not bound yet and no localAddress specified - get one. - if (localAddress == null) { - localAddress = new LocalAddress(LocalChannel.this); - } - } - - if (localAddress != null) { - try { - doBind(localAddress); - } catch (Throwable t) { - safeSetFailure(promise, t); - close(voidPromise()); - return; - } - } - - Channel boundChannel = LocalChannelRegistry.get(remoteAddress); - if (!(boundChannel instanceof LocalServerChannel)) { - Exception cause = new ChannelException("connection refused"); - safeSetFailure(promise, cause); - close(voidPromise()); - return; - } - - LocalServerChannel serverChannel = (LocalServerChannel) boundChannel; - peer = serverChannel.serve(LocalChannel.this); - } - } -} diff --git a/common/src/main/java/common/net/channel/local/LocalChannelRegistry.java b/common/src/main/java/common/net/channel/local/LocalChannelRegistry.java deleted file mode 100644 index 4fc5b82..0000000 --- a/common/src/main/java/common/net/channel/local/LocalChannelRegistry.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.local; - -import java.net.SocketAddress; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import common.net.channel.Channel; -import common.net.channel.ChannelException; -import common.net.util.internal.StringUtil; - -final class LocalChannelRegistry { - - private static final ConcurrentMap boundChannels = new ConcurrentHashMap(); - - static LocalAddress register( - Channel channel, LocalAddress oldLocalAddress, SocketAddress localAddress) { - if (oldLocalAddress != null) { - throw new ChannelException("already bound"); - } - if (!(localAddress instanceof LocalAddress)) { - throw new ChannelException("unsupported address type: " + StringUtil.simpleClassName(localAddress)); - } - - LocalAddress addr = (LocalAddress) localAddress; - if (LocalAddress.ANY.equals(addr)) { - addr = new LocalAddress(channel); - } - - Channel boundChannel = boundChannels.putIfAbsent(addr, channel); - if (boundChannel != null) { - throw new ChannelException("address already in use by: " + boundChannel); - } - return addr; - } - - static Channel get(SocketAddress localAddress) { - return boundChannels.get(localAddress); - } - - static void unregister(LocalAddress localAddress) { - boundChannels.remove(localAddress); - } - - private LocalChannelRegistry() { - // Unused - } -} diff --git a/common/src/main/java/common/net/channel/local/LocalEventLoop.java b/common/src/main/java/common/net/channel/local/LocalEventLoop.java deleted file mode 100644 index 4bf1b89..0000000 --- a/common/src/main/java/common/net/channel/local/LocalEventLoop.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.local; - -import java.util.concurrent.ThreadFactory; - -import common.net.channel.SingleThreadEventLoop; - -final class LocalEventLoop extends SingleThreadEventLoop { - - LocalEventLoop(LocalEventLoopGroup parent, ThreadFactory threadFactory) { - super(parent, threadFactory, true); - } - - @Override - protected void run() { - for (;;) { - Runnable task = takeTask(); - if (task != null) { - task.run(); - updateLastExecutionTime(); - } - - if (confirmShutdown()) { - break; - } - } - } -} diff --git a/common/src/main/java/common/net/channel/local/LocalEventLoopGroup.java b/common/src/main/java/common/net/channel/local/LocalEventLoopGroup.java deleted file mode 100644 index 7f58c98..0000000 --- a/common/src/main/java/common/net/channel/local/LocalEventLoopGroup.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.local; - -import java.util.concurrent.ThreadFactory; - -import common.net.channel.MultithreadEventLoopGroup; -import common.net.util.concurrent.EventExecutor; - -/** - * {@link MultithreadEventLoopGroup} which must be used for the local transport. - */ -public class LocalEventLoopGroup extends MultithreadEventLoopGroup { - - /** - * Create a new instance with the default number of threads. - */ - public LocalEventLoopGroup() { - this(0); - } - - /** - * Create a new instance - * - * @param nThreads the number of threads to use - */ - public LocalEventLoopGroup(int nThreads) { - this(nThreads, null); - } - - /** - * Create a new instance - * - * @param nThreads the number of threads to use - * @param threadFactory the {@link ThreadFactory} or {@code null} to use the default - */ - public LocalEventLoopGroup(int nThreads, ThreadFactory threadFactory) { - super(nThreads, threadFactory); - } - - @Override - protected EventExecutor newChild( - ThreadFactory threadFactory, Object... args) throws Exception { - return new LocalEventLoop(this, threadFactory); - } -} diff --git a/common/src/main/java/common/net/channel/local/LocalServerChannel.java b/common/src/main/java/common/net/channel/local/LocalServerChannel.java deleted file mode 100644 index 557f526..0000000 --- a/common/src/main/java/common/net/channel/local/LocalServerChannel.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.local; - -import java.net.SocketAddress; -import java.util.ArrayDeque; -import java.util.Queue; - -import common.net.channel.AbstractServerChannel; -import common.net.channel.ChannelConfig; -import common.net.channel.ChannelPipeline; -import common.net.channel.DefaultChannelConfig; -import common.net.channel.EventLoop; -import common.net.channel.SingleThreadEventLoop; -import common.net.util.concurrent.SingleThreadEventExecutor; - -/** - * A {@link ServerChannel} for the local transport which allows in VM communication. - */ -public class LocalServerChannel extends AbstractServerChannel { - - private final ChannelConfig config = new DefaultChannelConfig(this); - private final Queue inboundBuffer = new ArrayDeque(); - private final Runnable shutdownHook = new Runnable() { - @Override - public void run() { - unsafe().close(unsafe().voidPromise()); - } - }; - - private volatile int state; // 0 - open, 1 - active, 2 - closed - private volatile LocalAddress localAddress; - private volatile boolean acceptInProgress; - - @Override - public ChannelConfig config() { - return config; - } - - @Override - public LocalAddress localAddress() { - return (LocalAddress) super.localAddress(); - } - - @Override - public LocalAddress remoteAddress() { - return (LocalAddress) super.remoteAddress(); - } - - @Override - public boolean isOpen() { - return state < 2; - } - - @Override - public boolean isActive() { - return state == 1; - } - - @Override - protected boolean isCompatible(EventLoop loop) { - return loop instanceof SingleThreadEventLoop; - } - - @Override - protected SocketAddress localAddress0() { - return localAddress; - } - - @Override - protected void doRegister() throws Exception { - ((SingleThreadEventExecutor) eventLoop()).addShutdownHook(shutdownHook); - } - - @Override - protected void doBind(SocketAddress localAddress) throws Exception { - this.localAddress = LocalChannelRegistry.register(this, this.localAddress, localAddress); - state = 1; - } - - @Override - protected void doClose() throws Exception { - if (state <= 1) { - // Update all internal state before the closeFuture is notified. - if (localAddress != null) { - LocalChannelRegistry.unregister(localAddress); - localAddress = null; - } - state = 2; - } - } - - @Override - protected void doDeregister() throws Exception { - ((SingleThreadEventExecutor) eventLoop()).removeShutdownHook(shutdownHook); - } - - @Override - protected void doBeginRead() throws Exception { - if (acceptInProgress) { - return; - } - - Queue inboundBuffer = this.inboundBuffer; - if (inboundBuffer.isEmpty()) { - acceptInProgress = true; - return; - } - - ChannelPipeline pipeline = pipeline(); - for (;;) { - Object m = inboundBuffer.poll(); - if (m == null) { - break; - } - pipeline.fireChannelRead(m); - } - pipeline.fireChannelReadComplete(); - } - - LocalChannel serve(final LocalChannel peer) { - final LocalChannel child = new LocalChannel(this, peer); - if (eventLoop().inEventLoop()) { - serve0(child); - } else { - eventLoop().execute(new Runnable() { - @Override - public void run() { - serve0(child); - } - }); - } - return child; - } - - private void serve0(final LocalChannel child) { - inboundBuffer.add(child); - if (acceptInProgress) { - acceptInProgress = false; - ChannelPipeline pipeline = pipeline(); - for (;;) { - Object m = inboundBuffer.poll(); - if (m == null) { - break; - } - pipeline.fireChannelRead(m); - } - pipeline.fireChannelReadComplete(); - } - } -} diff --git a/common/src/main/java/common/net/channel/nio/AbstractNioByteChannel.java b/common/src/main/java/common/net/channel/nio/AbstractNioByteChannel.java deleted file mode 100644 index ac4cc89..0000000 --- a/common/src/main/java/common/net/channel/nio/AbstractNioByteChannel.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.nio; - -import java.io.IOException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; - -import common.net.buffer.ByteBuf; -import common.net.buffer.ByteBufAllocator; -import common.net.channel.Channel; -import common.net.channel.ChannelConfig; -import common.net.channel.ChannelOption; -import common.net.channel.ChannelOutboundBuffer; -import common.net.channel.ChannelPipeline; -import common.net.channel.RecvByteBufAllocator; -import common.net.channel.socket.ChannelInputShutdownEvent; -import common.net.util.internal.StringUtil; - -/** - * {@link AbstractNioChannel} base class for {@link Channel}s that operate on bytes. - */ -public abstract class AbstractNioByteChannel extends AbstractNioChannel { - - private static final String EXPECTED_TYPES = - " (expected: " + StringUtil.simpleClassName(ByteBuf.class) + ')'; // ", " + -// StringUtil.simpleClassName(FileRegion.class) + ')'; - - private Runnable flushTask; - - /** - * Create a new instance - * - * @param parent the parent {@link Channel} by which this instance was created. May be {@code null} - * @param ch the underlying {@link SelectableChannel} on which it operates - */ - protected AbstractNioByteChannel(Channel parent, SelectableChannel ch) { - super(parent, ch, SelectionKey.OP_READ); - } - - @Override - protected AbstractNioUnsafe newUnsafe() { - return new NioByteUnsafe(); - } - - private final class NioByteUnsafe extends AbstractNioUnsafe { - private RecvByteBufAllocator.Handle allocHandle; - - private void closeOnRead(ChannelPipeline pipeline) { - SelectionKey key = selectionKey(); - setInputShutdown(); - if (isOpen()) { - if (Boolean.TRUE.equals(config().getOption(ChannelOption.ALLOW_HALF_CLOSURE))) { - key.interestOps(key.interestOps() & ~readInterestOp); - pipeline.fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE); - } else { - close(voidPromise()); - } - } - } - - private void handleReadException(ChannelPipeline pipeline, - ByteBuf byteBuf, Throwable cause, boolean close) { - if (byteBuf != null) { - if (byteBuf.isReadable()) { - setReadPending(false); - pipeline.fireChannelRead(byteBuf); - } else { - byteBuf.release(); - } - } - pipeline.fireChannelReadComplete(); - pipeline.fireExceptionCaught(cause); - if (close || cause instanceof IOException) { - closeOnRead(pipeline); - } - } - - @Override - public void read() { - final ChannelConfig config = config(); - if (!config.isAutoRead() && !isReadPending()) { - // ChannelConfig.setAutoRead(false) was called in the meantime - removeReadOp(); - return; - } - - final ChannelPipeline pipeline = pipeline(); - final ByteBufAllocator allocator = config.getAllocator(); - final int maxMessagesPerRead = config.getMaxMessagesPerRead(); - RecvByteBufAllocator.Handle allocHandle = this.allocHandle; - if (allocHandle == null) { - this.allocHandle = allocHandle = config.getRecvByteBufAllocator().newHandle(); - } - - ByteBuf byteBuf = null; - int messages = 0; - boolean close = false; - try { - int totalReadAmount = 0; - boolean readPendingReset = false; - do { - byteBuf = allocHandle.allocate(allocator); - int writable = byteBuf.writableBytes(); - int localReadAmount = doReadBytes(byteBuf); - if (localReadAmount <= 0) { - // not was read release the buffer - byteBuf.release(); - close = localReadAmount < 0; - break; - } - if (!readPendingReset) { - readPendingReset = true; - setReadPending(false); - } - pipeline.fireChannelRead(byteBuf); - byteBuf = null; - - if (totalReadAmount >= Integer.MAX_VALUE - localReadAmount) { - // Avoid overflow. - totalReadAmount = Integer.MAX_VALUE; - break; - } - - totalReadAmount += localReadAmount; - - // stop reading - if (!config.isAutoRead()) { - break; - } - - if (localReadAmount < writable) { - // Read less than what the buffer can hold, - // which might mean we drained the recv buffer completely. - break; - } - } while (++ messages < maxMessagesPerRead); - - pipeline.fireChannelReadComplete(); - allocHandle.record(totalReadAmount); - - if (close) { - closeOnRead(pipeline); - close = false; - } - } catch (Throwable t) { - handleReadException(pipeline, byteBuf, t, close); - } finally { - // Check if there is a readPending which was not processed yet. - // This could be for two reasons: - // * The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method - // * The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method - // - // See https://github.com/netty/netty/issues/2254 - if (!config.isAutoRead() && !isReadPending()) { - removeReadOp(); - } - } - } - } - - @Override - protected void doWrite(ChannelOutboundBuffer in) throws Exception { - int writeSpinCount = -1; - - for (;;) { - Object msg = in.current(); - if (msg == null) { - // Wrote all messages. - clearOpWrite(); - break; - } - - if (msg instanceof ByteBuf) { - ByteBuf buf = (ByteBuf) msg; - int readableBytes = buf.readableBytes(); - if (readableBytes == 0) { - in.remove(); - continue; - } - - boolean setOpWrite = false; - boolean done = false; - long flushedAmount = 0; - if (writeSpinCount == -1) { - writeSpinCount = config().getWriteSpinCount(); - } - for (int i = writeSpinCount - 1; i >= 0; i --) { - int localFlushedAmount = doWriteBytes(buf); - if (localFlushedAmount == 0) { - setOpWrite = true; - break; - } - - flushedAmount += localFlushedAmount; - if (!buf.isReadable()) { - done = true; - break; - } - } - - in.progress(flushedAmount); - - if (done) { - in.remove(); - } else { - incompleteWrite(setOpWrite); - break; - } - } -// else if (msg instanceof FileRegion) { -// FileRegion region = (FileRegion) msg; -// boolean setOpWrite = false; -// boolean done = false; -// long flushedAmount = 0; -// if (writeSpinCount == -1) { -// writeSpinCount = config().getWriteSpinCount(); -// } -// for (int i = writeSpinCount - 1; i >= 0; i --) { -// long localFlushedAmount = doWriteFileRegion(region); -// if (localFlushedAmount == 0) { -// setOpWrite = true; -// break; -// } -// -// flushedAmount += localFlushedAmount; -// if (region.transfered() >= region.count()) { -// done = true; -// break; -// } -// } -// -// in.progress(flushedAmount); -// -// if (done) { -// in.remove(); -// } else { -// incompleteWrite(setOpWrite); -// break; -// } -// } - else { - // Should not reach here. - throw new Error(); - } - } - } - - @Override - protected final Object filterOutboundMessage(Object msg) { - if (msg instanceof ByteBuf) { - ByteBuf buf = (ByteBuf) msg; - if (buf.isDirect()) { - return msg; - } - - return newDirectBuffer(buf); - } - -// if (msg instanceof FileRegion) { -// return msg; -// } - - throw new UnsupportedOperationException( - "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES); - } - - protected final void incompleteWrite(boolean setOpWrite) { - // Did not write completely. - if (setOpWrite) { - setOpWrite(); - } else { - // Schedule flush again later so other tasks can be picked up in the meantime - Runnable flushTask = this.flushTask; - if (flushTask == null) { - flushTask = this.flushTask = new Runnable() { - @Override - public void run() { - flush(); - } - }; - } - eventLoop().execute(flushTask); - } - } - - /** - * Write a {@link FileRegion} - * - * @param region the {@link FileRegion} from which the bytes should be written - * @return amount the amount of written bytes - */ -// protected abstract long doWriteFileRegion(FileRegion region) throws Exception; - - /** - * Read bytes into the given {@link ByteBuf} and return the amount. - */ - protected abstract int doReadBytes(ByteBuf buf) throws Exception; - - /** - * Write bytes form the given {@link ByteBuf} to the underlying {@link java.nio.channels.Channel}. - * @param buf the {@link ByteBuf} from which the bytes should be written - * @return amount the amount of written bytes - */ - protected abstract int doWriteBytes(ByteBuf buf) throws Exception; - - protected final void setOpWrite() { - final SelectionKey key = selectionKey(); - // Check first if the key is still valid as it may be canceled as part of the deregistration - // from the EventLoop - // See https://github.com/netty/netty/issues/2104 - if (!key.isValid()) { - return; - } - final int interestOps = key.interestOps(); - if ((interestOps & SelectionKey.OP_WRITE) == 0) { - key.interestOps(interestOps | SelectionKey.OP_WRITE); - } - } - - protected final void clearOpWrite() { - final SelectionKey key = selectionKey(); - // Check first if the key is still valid as it may be canceled as part of the deregistration - // from the EventLoop - // See https://github.com/netty/netty/issues/2104 - if (!key.isValid()) { - return; - } - final int interestOps = key.interestOps(); - if ((interestOps & SelectionKey.OP_WRITE) != 0) { - key.interestOps(interestOps & ~SelectionKey.OP_WRITE); - } - } -} diff --git a/common/src/main/java/common/net/channel/nio/AbstractNioChannel.java b/common/src/main/java/common/net/channel/nio/AbstractNioChannel.java deleted file mode 100644 index 214f1de..0000000 --- a/common/src/main/java/common/net/channel/nio/AbstractNioChannel.java +++ /dev/null @@ -1,460 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.nio; - -import java.io.IOException; -import java.net.ConnectException; -import java.net.SocketAddress; -import java.nio.channels.CancelledKeyException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -import common.net.buffer.ByteBuf; -import common.net.buffer.ByteBufAllocator; -import common.net.buffer.ByteBufUtil; -import common.net.buffer.Unpooled; -import common.net.channel.AbstractChannel; -import common.net.channel.Channel; -import common.net.channel.ChannelException; -import common.net.channel.ChannelFuture; -import common.net.channel.ChannelFutureListener; -import common.net.channel.ChannelPromise; -import common.net.channel.ConnectTimeoutException; -import common.net.channel.EventLoop; -import common.net.util.ReferenceCountUtil; -import common.net.util.ReferenceCounted; -import common.net.util.internal.OneTimeTask; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * Abstract base class for {@link Channel} implementations which use a Selector based approach. - */ -public abstract class AbstractNioChannel extends AbstractChannel { - - private static final InternalLogger logger = - InternalLoggerFactory.getInstance(AbstractNioChannel.class); - - private final SelectableChannel ch; - protected final int readInterestOp; - volatile SelectionKey selectionKey; - private volatile boolean inputShutdown; - private volatile boolean readPending; - - /** - * The future of the current connection attempt. If not null, subsequent - * connection attempts will fail. - */ - private ChannelPromise connectPromise; - private ScheduledFuture connectTimeoutFuture; - private SocketAddress requestedRemoteAddress; - - /** - * Create a new instance - * - * @param parent the parent {@link Channel} by which this instance was created. May be {@code null} - * @param ch the underlying {@link SelectableChannel} on which it operates - * @param readInterestOp the ops to set to receive data from the {@link SelectableChannel} - */ - protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) { - super(parent); - this.ch = ch; - this.readInterestOp = readInterestOp; - try { - ch.configureBlocking(false); - } catch (IOException e) { - try { - ch.close(); - } catch (IOException e2) { - if (logger.isWarnEnabled()) { - logger.warn( - "Failed to close a partially initialized socket.", e2); - } - } - - throw new ChannelException("Failed to enter non-blocking mode.", e); - } - } - - @Override - public boolean isOpen() { - return ch.isOpen(); - } - - @Override - public NioUnsafe unsafe() { - return (NioUnsafe) super.unsafe(); - } - - protected SelectableChannel javaChannel() { - return ch; - } - - @Override - public NioEventLoop eventLoop() { - return (NioEventLoop) super.eventLoop(); - } - - /** - * Return the current {@link SelectionKey} - */ - protected SelectionKey selectionKey() { - assert selectionKey != null; - return selectionKey; - } - - protected boolean isReadPending() { - return readPending; - } - - protected void setReadPending(boolean readPending) { - this.readPending = readPending; - } - - /** - * Return {@code true} if the input of this {@link Channel} is shutdown - */ - protected boolean isInputShutdown() { - return inputShutdown; - } - - /** - * Shutdown the input of this {@link Channel}. - */ - void setInputShutdown() { - inputShutdown = true; - } - - /** - * Special {@link Unsafe} sub-type which allows to access the underlying {@link SelectableChannel} - */ - public interface NioUnsafe extends Unsafe { - /** - * Return underlying {@link SelectableChannel} - */ - SelectableChannel ch(); - - /** - * Finish connect - */ - void finishConnect(); - - /** - * Read from underlying {@link SelectableChannel} - */ - void read(); - - void forceFlush(); - } - - protected abstract class AbstractNioUnsafe extends AbstractUnsafe implements NioUnsafe { - - protected final void removeReadOp() { - SelectionKey key = selectionKey(); - // Check first if the key is still valid as it may be canceled as part of the deregistration - // from the EventLoop - // See https://github.com/netty/netty/issues/2104 - if (!key.isValid()) { - return; - } - int interestOps = key.interestOps(); - if ((interestOps & readInterestOp) != 0) { - // only remove readInterestOp if needed - key.interestOps(interestOps & ~readInterestOp); - } - } - - @Override - public final SelectableChannel ch() { - return javaChannel(); - } - - @Override - public final void connect( - final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) { - if (!promise.setUncancellable() || !ensureOpen(promise)) { - return; - } - - try { - if (connectPromise != null) { - throw new IllegalStateException("connection attempt already made"); - } - - boolean wasActive = isActive(); - if (doConnect(remoteAddress, localAddress)) { - fulfillConnectPromise(promise, wasActive); - } else { - connectPromise = promise; - requestedRemoteAddress = remoteAddress; - - // Schedule connect timeout. - int connectTimeoutMillis = config().getConnectTimeoutMillis(); - if (connectTimeoutMillis > 0) { - connectTimeoutFuture = eventLoop().schedule(new OneTimeTask() { - @Override - public void run() { - ChannelPromise connectPromise = AbstractNioChannel.this.connectPromise; - ConnectTimeoutException cause = - new ConnectTimeoutException("connection timed out: " + remoteAddress); - if (connectPromise != null && connectPromise.tryFailure(cause)) { - close(voidPromise()); - } - } - }, connectTimeoutMillis, TimeUnit.MILLISECONDS); - } - - promise.addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture future) throws Exception { - if (future.isCancelled()) { - if (connectTimeoutFuture != null) { - connectTimeoutFuture.cancel(false); - } - connectPromise = null; - close(voidPromise()); - } - } - }); - } - } catch (Throwable t) { - if (t instanceof ConnectException) { - Throwable newT = new ConnectException(t.getMessage() + ": " + remoteAddress); - newT.setStackTrace(t.getStackTrace()); - t = newT; - } - promise.tryFailure(t); - closeIfClosed(); - } - } - - private void fulfillConnectPromise(ChannelPromise promise, boolean wasActive) { - if (promise == null) { - // Closed via cancellation and the promise has been notified already. - return; - } - - // trySuccess() will return false if a user cancelled the connection attempt. - boolean promiseSet = promise.trySuccess(); - - // Regardless if the connection attempt was cancelled, channelActive() event should be triggered, - // because what happened is what happened. - if (!wasActive && isActive()) { - pipeline().fireChannelActive(); - } - - // If a user cancelled the connection attempt, close the channel, which is followed by channelInactive(). - if (!promiseSet) { - close(voidPromise()); - } - } - - private void fulfillConnectPromise(ChannelPromise promise, Throwable cause) { - if (promise == null) { - // Closed via cancellation and the promise has been notified already. - return; - } - - // Use tryFailure() instead of setFailure() to avoid the race against cancel(). - promise.tryFailure(cause); - closeIfClosed(); - } - - @Override - public final void finishConnect() { - // Note this method is invoked by the event loop only if the connection attempt was - // neither cancelled nor timed out. - - assert eventLoop().inEventLoop(); - - try { - boolean wasActive = isActive(); - doFinishConnect(); - fulfillConnectPromise(connectPromise, wasActive); - } catch (Throwable t) { - if (t instanceof ConnectException) { - Throwable newT = new ConnectException(t.getMessage() + ": " + requestedRemoteAddress); - newT.setStackTrace(t.getStackTrace()); - t = newT; - } - - fulfillConnectPromise(connectPromise, t); - } finally { - // Check for null as the connectTimeoutFuture is only created if a connectTimeoutMillis > 0 is used - // See https://github.com/netty/netty/issues/1770 - if (connectTimeoutFuture != null) { - connectTimeoutFuture.cancel(false); - } - connectPromise = null; - } - } - - @Override - protected final void flush0() { - // Flush immediately only when there's no pending flush. - // If there's a pending flush operation, event loop will call forceFlush() later, - // and thus there's no need to call it now. - if (isFlushPending()) { - return; - } - super.flush0(); - } - - @Override - public final void forceFlush() { - // directly call super.flush0() to force a flush now - super.flush0(); - } - - private boolean isFlushPending() { - SelectionKey selectionKey = selectionKey(); - return selectionKey.isValid() && (selectionKey.interestOps() & SelectionKey.OP_WRITE) != 0; - } - } - - @Override - protected boolean isCompatible(EventLoop loop) { - return loop instanceof NioEventLoop; - } - - @Override - protected void doRegister() throws Exception { - boolean selected = false; - for (;;) { - try { - selectionKey = javaChannel().register(eventLoop().selector, 0, this); - return; - } catch (CancelledKeyException e) { - if (!selected) { - // Force the Selector to select now as the "canceled" SelectionKey may still be - // cached and not removed because no Select.select(..) operation was called yet. - eventLoop().selectNow(); - selected = true; - } else { - // We forced a select operation on the selector before but the SelectionKey is still cached - // for whatever reason. JDK bug ? - throw e; - } - } - } - } - - @Override - protected void doDeregister() throws Exception { - eventLoop().cancel(selectionKey()); - } - - @Override - protected void doBeginRead() throws Exception { - // Channel.read() or ChannelHandlerContext.read() was called - if (inputShutdown) { - return; - } - - final SelectionKey selectionKey = this.selectionKey; - if (!selectionKey.isValid()) { - return; - } - - readPending = true; - - final int interestOps = selectionKey.interestOps(); - if ((interestOps & readInterestOp) == 0) { - selectionKey.interestOps(interestOps | readInterestOp); - } - } - - /** - * Connect to the remote peer - */ - protected abstract boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception; - - /** - * Finish the connect - */ - protected abstract void doFinishConnect() throws Exception; - - /** - * Returns an off-heap copy of the specified {@link ByteBuf}, and releases the original one. - * Note that this method does not create an off-heap copy if the allocation / deallocation cost is too high, - * but just returns the original {@link ByteBuf}.. - */ - protected final ByteBuf newDirectBuffer(ByteBuf buf) { - final int readableBytes = buf.readableBytes(); - if (readableBytes == 0) { - ReferenceCountUtil.safeRelease(buf); - return Unpooled.EMPTY_BUFFER; - } - - final ByteBufAllocator alloc = alloc(); - if (alloc.isDirectBufferPooled()) { - ByteBuf directBuf = alloc.directBuffer(readableBytes); - directBuf.writeBytes(buf, buf.readerIndex(), readableBytes); - ReferenceCountUtil.safeRelease(buf); - return directBuf; - } - - final ByteBuf directBuf = ByteBufUtil.threadLocalDirectBuffer(); - if (directBuf != null) { - directBuf.writeBytes(buf, buf.readerIndex(), readableBytes); - ReferenceCountUtil.safeRelease(buf); - return directBuf; - } - - // Allocating and deallocating an unpooled direct buffer is very expensive; give up. - return buf; - } - - /** - * Returns an off-heap copy of the specified {@link ByteBuf}, and releases the specified holder. - * The caller must ensure that the holder releases the original {@link ByteBuf} when the holder is released by - * this method. Note that this method does not create an off-heap copy if the allocation / deallocation cost is - * too high, but just returns the original {@link ByteBuf}.. - */ - protected final ByteBuf newDirectBuffer(ReferenceCounted holder, ByteBuf buf) { - final int readableBytes = buf.readableBytes(); - if (readableBytes == 0) { - ReferenceCountUtil.safeRelease(holder); - return Unpooled.EMPTY_BUFFER; - } - - final ByteBufAllocator alloc = alloc(); - if (alloc.isDirectBufferPooled()) { - ByteBuf directBuf = alloc.directBuffer(readableBytes); - directBuf.writeBytes(buf, buf.readerIndex(), readableBytes); - ReferenceCountUtil.safeRelease(holder); - return directBuf; - } - - final ByteBuf directBuf = ByteBufUtil.threadLocalDirectBuffer(); - if (directBuf != null) { - directBuf.writeBytes(buf, buf.readerIndex(), readableBytes); - ReferenceCountUtil.safeRelease(holder); - return directBuf; - } - - // Allocating and deallocating an unpooled direct buffer is very expensive; give up. - if (holder != buf) { - // Ensure to call holder.release() to give the holder a chance to release other resources than its content. - buf.retain(); - ReferenceCountUtil.safeRelease(holder); - } - - return buf; - } -} diff --git a/common/src/main/java/common/net/channel/nio/AbstractNioMessageChannel.java b/common/src/main/java/common/net/channel/nio/AbstractNioMessageChannel.java deleted file mode 100644 index 3153d17..0000000 --- a/common/src/main/java/common/net/channel/nio/AbstractNioMessageChannel.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.nio; - -import java.io.IOException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.util.ArrayList; -import java.util.List; - -import common.net.channel.Channel; -import common.net.channel.ChannelConfig; -import common.net.channel.ChannelOutboundBuffer; -import common.net.channel.ChannelPipeline; -import common.net.channel.ServerChannel; - -/** - * {@link AbstractNioChannel} base class for {@link Channel}s that operate on messages. - */ -public abstract class AbstractNioMessageChannel extends AbstractNioChannel { - - /** - * @see {@link AbstractNioChannel#AbstractNioChannel(Channel, SelectableChannel, int)} - */ - protected AbstractNioMessageChannel(Channel parent, SelectableChannel ch, int readInterestOp) { - super(parent, ch, readInterestOp); - } - - @Override - protected AbstractNioUnsafe newUnsafe() { - return new NioMessageUnsafe(); - } - - private final class NioMessageUnsafe extends AbstractNioUnsafe { - - private final List readBuf = new ArrayList(); - - @Override - public void read() { - assert eventLoop().inEventLoop(); - final ChannelConfig config = config(); - if (!config.isAutoRead() && !isReadPending()) { - // ChannelConfig.setAutoRead(false) was called in the meantime - removeReadOp(); - return; - } - - final int maxMessagesPerRead = config.getMaxMessagesPerRead(); - final ChannelPipeline pipeline = pipeline(); - boolean closed = false; - Throwable exception = null; - try { - try { - for (;;) { - int localRead = doReadMessages(readBuf); - if (localRead == 0) { - break; - } - if (localRead < 0) { - closed = true; - break; - } - - // stop reading and remove op - if (!config.isAutoRead()) { - break; - } - - if (readBuf.size() >= maxMessagesPerRead) { - break; - } - } - } catch (Throwable t) { - exception = t; - } - setReadPending(false); - int size = readBuf.size(); - for (int i = 0; i < size; i ++) { - pipeline.fireChannelRead(readBuf.get(i)); - } - - readBuf.clear(); - pipeline.fireChannelReadComplete(); - - if (exception != null) { - if (exception instanceof IOException) { - // ServerChannel should not be closed even on IOException because it can often continue - // accepting incoming connections. (e.g. too many open files) - closed = !(AbstractNioMessageChannel.this instanceof ServerChannel); - } - - pipeline.fireExceptionCaught(exception); - } - - if (closed) { - if (isOpen()) { - close(voidPromise()); - } - } - } finally { - // Check if there is a readPending which was not processed yet. - // This could be for two reasons: - // * The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method - // * The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method - // - // See https://github.com/netty/netty/issues/2254 - if (!config.isAutoRead() && !isReadPending()) { - removeReadOp(); - } - } - } - } - - @Override - protected void doWrite(ChannelOutboundBuffer in) throws Exception { - final SelectionKey key = selectionKey(); - final int interestOps = key.interestOps(); - - for (;;) { - Object msg = in.current(); - if (msg == null) { - // Wrote all messages. - if ((interestOps & SelectionKey.OP_WRITE) != 0) { - key.interestOps(interestOps & ~SelectionKey.OP_WRITE); - } - break; - } - try { - boolean done = false; - for (int i = config().getWriteSpinCount() - 1; i >= 0; i--) { - if (doWriteMessage(msg, in)) { - done = true; - break; - } - } - - if (done) { - in.remove(); - } else { - // Did not write all messages. - if ((interestOps & SelectionKey.OP_WRITE) == 0) { - key.interestOps(interestOps | SelectionKey.OP_WRITE); - } - break; - } - } catch (IOException e) { - if (continueOnWriteError()) { - in.remove(e); - } else { - throw e; - } - } - } - } - - /** - * Returns {@code true} if we should continue the write loop on a write error. - */ - protected boolean continueOnWriteError() { - return false; - } - - /** - * Read messages into the given array and return the amount which was read. - */ - protected abstract int doReadMessages(List buf) throws Exception; - - /** - * Write a message to the underlying {@link java.nio.channels.Channel}. - * - * @return {@code true} if and only if the message has been written - */ - protected abstract boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception; -} diff --git a/common/src/main/java/common/net/channel/nio/NioEventLoop.java b/common/src/main/java/common/net/channel/nio/NioEventLoop.java deleted file mode 100644 index dcb46d0..0000000 --- a/common/src/main/java/common/net/channel/nio/NioEventLoop.java +++ /dev/null @@ -1,691 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.nio; - - -import java.io.IOException; -import java.lang.reflect.Field; -import java.nio.channels.CancelledKeyException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.spi.SelectorProvider; -import java.util.ArrayList; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import common.net.channel.ChannelException; -import common.net.channel.EventLoopException; -import common.net.channel.SingleThreadEventLoop; -import common.net.channel.nio.AbstractNioChannel.NioUnsafe; -import common.net.util.internal.MpscLinkedQueue; -import common.net.util.internal.SystemPropertyUtil; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * {@link SingleThreadEventLoop} implementation which register the {@link Channel}'s to a - * {@link Selector} and so does the multi-plexing of these in the event loop. - * - */ -public final class NioEventLoop extends SingleThreadEventLoop { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(NioEventLoop.class); - - private static final int CLEANUP_INTERVAL = 256; // XXX Hard-coded value, but won't need customization. - - private static final boolean DISABLE_KEYSET_OPTIMIZATION = - SystemPropertyUtil.getBoolean("game.net.noKeySetOptimization", false); - - private static final int MIN_PREMATURE_SELECTOR_RETURNS = 3; - private static final int SELECTOR_AUTO_REBUILD_THRESHOLD; - - // Workaround for JDK NIO bug. - // - // See: - // - http://bugs.sun.com/view_bug.do?bug_id=6427854 - // - https://github.com/netty/netty/issues/203 - static { - String key = "sun.nio.ch.bugLevel"; - try { - String buglevel = SystemPropertyUtil.get(key); - if (buglevel == null) { - System.setProperty(key, ""); - } - } catch (SecurityException e) { - if (logger.isDebugEnabled()) { - logger.debug("Unable to get/set System Property: {}", key, e); - } - } - - int selectorAutoRebuildThreshold = SystemPropertyUtil.getInt("game.net.selectorAutoRebuildThreshold", 512); - if (selectorAutoRebuildThreshold < MIN_PREMATURE_SELECTOR_RETURNS) { - selectorAutoRebuildThreshold = 0; - } - - SELECTOR_AUTO_REBUILD_THRESHOLD = selectorAutoRebuildThreshold; - - if (logger.isDebugEnabled()) { - logger.debug("-Dgame.net.noKeySetOptimization: {}", DISABLE_KEYSET_OPTIMIZATION); - logger.debug("-Dgame.net.selectorAutoRebuildThreshold: {}", SELECTOR_AUTO_REBUILD_THRESHOLD); - } - } - - /** - * The NIO {@link Selector}. - */ - Selector selector; - private SelectedSelectionKeySet selectedKeys; - - private final SelectorProvider provider; - - /** - * Boolean that controls determines if a blocked Selector.select should - * break out of its selection process. In our case we use a timeout for - * the select method and the select method will block for that time unless - * waken up. - */ - private final AtomicBoolean wakenUp = new AtomicBoolean(); - - private volatile int ioRatio = 50; - private int cancelledKeys; - private boolean needsToSelectAgain; - - NioEventLoop(NioEventLoopGroup parent, ThreadFactory threadFactory, SelectorProvider selectorProvider) { - super(parent, threadFactory, false); - if (selectorProvider == null) { - throw new NullPointerException("selectorProvider"); - } - provider = selectorProvider; - selector = openSelector(); - } - - private Selector openSelector() { - final Selector selector; - try { - selector = provider.openSelector(); - } catch (IOException e) { - throw new ChannelException("failed to open a new selector", e); - } - - if (DISABLE_KEYSET_OPTIMIZATION) { - return selector; - } - - try { - SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet(); - - Class selectorImplClass = - Class.forName("sun.nio.ch.SelectorImpl", false, ClassLoader.getSystemClassLoader()); - - // Ensure the current selector implementation is what we can instrument. - if (!selectorImplClass.isAssignableFrom(selector.getClass())) { - return selector; - } - - Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys"); - Field publicSelectedKeysField = selectorImplClass.getDeclaredField("publicSelectedKeys"); - - selectedKeysField.setAccessible(true); - publicSelectedKeysField.setAccessible(true); - - selectedKeysField.set(selector, selectedKeySet); - publicSelectedKeysField.set(selector, selectedKeySet); - - selectedKeys = selectedKeySet; - logger.trace("Instrumented an optimized java.util.Set into: {}", selector); - } catch (Throwable t) { - selectedKeys = null; - logger.trace("Failed to instrument an optimized java.util.Set into: {}", selector, t); - } - - return selector; - } - - @Override - protected Queue newTaskQueue() { - // This event loop never calls takeTask() - return new MpscLinkedQueue(); - } - - /** - * Registers an arbitrary {@link SelectableChannel}, not necessarily created by Netty, to the {@link Selector} - * of this event loop. Once the specified {@link SelectableChannel} is registered, the specified {@code task} will - * be executed by this event loop when the {@link SelectableChannel} is ready. - */ - public void register(final SelectableChannel ch, final int interestOps, final NioTask task) { - if (ch == null) { - throw new NullPointerException("ch"); - } - if (interestOps == 0) { - throw new IllegalArgumentException("interestOps must be non-zero."); - } - if ((interestOps & ~ch.validOps()) != 0) { - throw new IllegalArgumentException( - "invalid interestOps: " + interestOps + "(validOps: " + ch.validOps() + ')'); - } - if (task == null) { - throw new NullPointerException("task"); - } - - if (isShutdown()) { - throw new IllegalStateException("event loop shut down"); - } - - try { - ch.register(selector, interestOps, task); - } catch (Exception e) { - throw new EventLoopException("failed to register a channel", e); - } - } - - /** - * Returns the percentage of the desired amount of time spent for I/O in the event loop. - */ - public int getIoRatio() { - return ioRatio; - } - - /** - * Sets the percentage of the desired amount of time spent for I/O in the event loop. The default value is - * {@code 50}, which means the event loop will try to spend the same amount of time for I/O as for non-I/O tasks. - */ - public void setIoRatio(int ioRatio) { - if (ioRatio <= 0 || ioRatio > 100) { - throw new IllegalArgumentException("ioRatio: " + ioRatio + " (expected: 0 < ioRatio <= 100)"); - } - this.ioRatio = ioRatio; - } - - /** - * Replaces the current {@link Selector} of this event loop with newly created {@link Selector}s to work - * around the infamous epoll 100% CPU bug. - */ - public void rebuildSelector() { - if (!inEventLoop()) { - execute(new Runnable() { - @Override - public void run() { - rebuildSelector(); - } - }); - return; - } - - final Selector oldSelector = selector; - final Selector newSelector; - - if (oldSelector == null) { - return; - } - - try { - newSelector = openSelector(); - } catch (Exception e) { - logger.warn("Failed to create a new Selector.", e); - return; - } - - // Register all channels to the new Selector. - int nChannels = 0; - for (;;) { - try { - for (SelectionKey key: oldSelector.keys()) { - Object a = key.attachment(); - try { - if (!key.isValid() || key.channel().keyFor(newSelector) != null) { - continue; - } - - int interestOps = key.interestOps(); - key.cancel(); - SelectionKey newKey = key.channel().register(newSelector, interestOps, a); - if (a instanceof AbstractNioChannel) { - // Update SelectionKey - ((AbstractNioChannel) a).selectionKey = newKey; - } - nChannels ++; - } catch (Exception e) { - logger.warn("Failed to re-register a Channel to the new Selector.", e); - if (a instanceof AbstractNioChannel) { - AbstractNioChannel ch = (AbstractNioChannel) a; - ch.unsafe().close(ch.unsafe().voidPromise()); - } else { - - NioTask task = (NioTask) a; - invokeChannelUnregistered(task, key, e); - } - } - } - } catch (ConcurrentModificationException e) { - // Probably due to concurrent modification of the key set. - continue; - } - - break; - } - - selector = newSelector; - - try { - // time to close the old selector as everything else is registered to the new one - oldSelector.close(); - } catch (Throwable t) { - if (logger.isWarnEnabled()) { - logger.warn("Failed to close the old Selector.", t); - } - } - - logger.info("Migrated " + nChannels + " channel(s) to the new Selector."); - } - - @Override - protected void run() { - for (;;) { - boolean oldWakenUp = wakenUp.getAndSet(false); - try { - if (hasTasks()) { - selectNow(); - } else { - select(oldWakenUp); - - // 'wakenUp.compareAndSet(false, true)' is always evaluated - // before calling 'selector.wakeup()' to reduce the wake-up - // overhead. (Selector.wakeup() is an expensive operation.) - // - // However, there is a race condition in this approach. - // The race condition is triggered when 'wakenUp' is set to - // true too early. - // - // 'wakenUp' is set to true too early if: - // 1) Selector is waken up between 'wakenUp.set(false)' and - // 'selector.select(...)'. (BAD) - // 2) Selector is waken up between 'selector.select(...)' and - // 'if (wakenUp.get()) { ... }'. (OK) - // - // In the first case, 'wakenUp' is set to true and the - // following 'selector.select(...)' will wake up immediately. - // Until 'wakenUp' is set to false again in the next round, - // 'wakenUp.compareAndSet(false, true)' will fail, and therefore - // any attempt to wake up the Selector will fail, too, causing - // the following 'selector.select(...)' call to block - // unnecessarily. - // - // To fix this problem, we wake up the selector again if wakenUp - // is true immediately after selector.select(...). - // It is inefficient in that it wakes up the selector for both - // the first case (BAD - wake-up required) and the second case - // (OK - no wake-up required). - - if (wakenUp.get()) { - selector.wakeup(); - } - } - - cancelledKeys = 0; - needsToSelectAgain = false; - final int ioRatio = this.ioRatio; - if (ioRatio == 100) { - processSelectedKeys(); - runAllTasks(); - } else { - final long ioStartTime = System.nanoTime(); - - processSelectedKeys(); - - final long ioTime = System.nanoTime() - ioStartTime; - runAllTasks(ioTime * (100 - ioRatio) / ioRatio); - } - - if (isShuttingDown()) { - closeAll(); - if (confirmShutdown()) { - break; - } - } - } catch (Throwable t) { - logger.warn("Unexpected exception in the selector loop.", t); - - // Prevent possible consecutive immediate failures that lead to - // excessive CPU consumption. - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // Ignore. - } - } - } - } - - private void processSelectedKeys() { - if (selectedKeys != null) { - processSelectedKeysOptimized(selectedKeys.flip()); - } else { - processSelectedKeysPlain(selector.selectedKeys()); - } - } - - @Override - protected void cleanup() { - try { - selector.close(); - } catch (IOException e) { - logger.warn("Failed to close a selector.", e); - } - } - - void cancel(SelectionKey key) { - key.cancel(); - cancelledKeys ++; - if (cancelledKeys >= CLEANUP_INTERVAL) { - cancelledKeys = 0; - needsToSelectAgain = true; - } - } - - @Override - protected Runnable pollTask() { - Runnable task = super.pollTask(); - if (needsToSelectAgain) { - selectAgain(); - } - return task; - } - - private void processSelectedKeysPlain(Set selectedKeys) { - // check if the set is empty and if so just return to not create garbage by - // creating a new Iterator every time even if there is nothing to process. - // See https://github.com/netty/netty/issues/597 - if (selectedKeys.isEmpty()) { - return; - } - - Iterator i = selectedKeys.iterator(); - for (;;) { - final SelectionKey k = i.next(); - final Object a = k.attachment(); - i.remove(); - - if (a instanceof AbstractNioChannel) { - processSelectedKey(k, (AbstractNioChannel) a); - } else { - - NioTask task = (NioTask) a; - processSelectedKey(k, task); - } - - if (!i.hasNext()) { - break; - } - - if (needsToSelectAgain) { - selectAgain(); - selectedKeys = selector.selectedKeys(); - - // Create the iterator again to avoid ConcurrentModificationException - if (selectedKeys.isEmpty()) { - break; - } else { - i = selectedKeys.iterator(); - } - } - } - } - - private void processSelectedKeysOptimized(SelectionKey[] selectedKeys) { - for (int i = 0;; i ++) { - final SelectionKey k = selectedKeys[i]; - if (k == null) { - break; - } - // null out entry in the array to allow to have it GC'ed once the Channel close - // See https://github.com/netty/netty/issues/2363 - selectedKeys[i] = null; - - final Object a = k.attachment(); - - if (a instanceof AbstractNioChannel) { - processSelectedKey(k, (AbstractNioChannel) a); - } else { - - NioTask task = (NioTask) a; - processSelectedKey(k, task); - } - - if (needsToSelectAgain) { - // null out entries in the array to allow to have it GC'ed once the Channel close - // See https://github.com/netty/netty/issues/2363 - for (;;) { - if (selectedKeys[i] == null) { - break; - } - selectedKeys[i] = null; - i++; - } - - selectAgain(); - // Need to flip the optimized selectedKeys to get the right reference to the array - // and reset the index to -1 which will then set to 0 on the for loop - // to start over again. - // - // See https://github.com/netty/netty/issues/1523 - selectedKeys = this.selectedKeys.flip(); - i = -1; - } - } - } - - private static void processSelectedKey(SelectionKey k, AbstractNioChannel ch) { - final NioUnsafe unsafe = ch.unsafe(); - if (!k.isValid()) { - // close the channel if the key is not valid anymore - unsafe.close(unsafe.voidPromise()); - return; - } - - try { - int readyOps = k.readyOps(); - // Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead - // to a spin loop - if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) { - unsafe.read(); - if (!ch.isOpen()) { - // Connection already closed - no need to handle write. - return; - } - } - if ((readyOps & SelectionKey.OP_WRITE) != 0) { - // Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write - ch.unsafe().forceFlush(); - } - if ((readyOps & SelectionKey.OP_CONNECT) != 0) { - // remove OP_CONNECT as otherwise Selector.select(..) will always return without blocking - // See https://github.com/netty/netty/issues/924 - int ops = k.interestOps(); - ops &= ~SelectionKey.OP_CONNECT; - k.interestOps(ops); - - unsafe.finishConnect(); - } - } catch (CancelledKeyException ignored) { - unsafe.close(unsafe.voidPromise()); - } - } - - private static void processSelectedKey(SelectionKey k, NioTask task) { - int state = 0; - try { - task.channelReady(k.channel(), k); - state = 1; - } catch (Exception e) { - k.cancel(); - invokeChannelUnregistered(task, k, e); - state = 2; - } finally { - switch (state) { - case 0: - k.cancel(); - invokeChannelUnregistered(task, k, null); - break; - case 1: - if (!k.isValid()) { // Cancelled by channelReady() - invokeChannelUnregistered(task, k, null); - } - break; - } - } - } - - private void closeAll() { - selectAgain(); - Set keys = selector.keys(); - Collection channels = new ArrayList(keys.size()); - for (SelectionKey k: keys) { - Object a = k.attachment(); - if (a instanceof AbstractNioChannel) { - channels.add((AbstractNioChannel) a); - } else { - k.cancel(); - - NioTask task = (NioTask) a; - invokeChannelUnregistered(task, k, null); - } - } - - for (AbstractNioChannel ch: channels) { - ch.unsafe().close(ch.unsafe().voidPromise()); - } - } - - private static void invokeChannelUnregistered(NioTask task, SelectionKey k, Throwable cause) { - try { - task.channelUnregistered(k.channel(), cause); - } catch (Exception e) { - logger.warn("Unexpected exception while running NioTask.channelUnregistered()", e); - } - } - - @Override - protected void wakeup(boolean inEventLoop) { - if (!inEventLoop && wakenUp.compareAndSet(false, true)) { - selector.wakeup(); - } - } - - void selectNow() throws IOException { - try { - selector.selectNow(); - } finally { - // restore wakup state if needed - if (wakenUp.get()) { - selector.wakeup(); - } - } - } - - private void select(boolean oldWakenUp) throws IOException { - Selector selector = this.selector; - try { - int selectCnt = 0; - long currentTimeNanos = System.nanoTime(); - long selectDeadLineNanos = currentTimeNanos + delayNanos(currentTimeNanos); - for (;;) { - long timeoutMillis = (selectDeadLineNanos - currentTimeNanos + 500000L) / 1000000L; - if (timeoutMillis <= 0) { - if (selectCnt == 0) { - selector.selectNow(); - selectCnt = 1; - } - break; - } - - int selectedKeys = selector.select(timeoutMillis); - selectCnt ++; - - if (selectedKeys != 0 || oldWakenUp || wakenUp.get() || hasTasks() || hasScheduledTasks()) { - // - Selected something, - // - waken up by user, or - // - the task queue has a pending task. - // - a scheduled task is ready for processing - break; - } - if (Thread.interrupted()) { - // Thread was interrupted so reset selected keys and break so we not run into a busy loop. - // As this is most likely a bug in the handler of the user or it's client library we will - // also log it. - // - // See https://github.com/netty/netty/issues/2426 - if (logger.isDebugEnabled()) { - logger.debug("Selector.select() returned prematurely because " + - "Thread.currentThread().interrupt() was called. Use " + - "NioEventLoop.shutdownGracefully() to shutdown the NioEventLoop."); - } - selectCnt = 1; - break; - } - - long time = System.nanoTime(); - if (time - TimeUnit.MILLISECONDS.toNanos(timeoutMillis) >= currentTimeNanos) { - // timeoutMillis elapsed without anything selected. - selectCnt = 1; - } else if (SELECTOR_AUTO_REBUILD_THRESHOLD > 0 && - selectCnt >= SELECTOR_AUTO_REBUILD_THRESHOLD) { - // The selector returned prematurely many times in a row. - // Rebuild the selector to work around the problem. - logger.warn( - "Selector.select() returned prematurely {} times in a row; rebuilding selector.", - selectCnt); - - rebuildSelector(); - selector = this.selector; - - // Select again to populate selectedKeys. - selector.selectNow(); - selectCnt = 1; - break; - } - - currentTimeNanos = time; - } - - if (selectCnt > MIN_PREMATURE_SELECTOR_RETURNS) { - if (logger.isDebugEnabled()) { - logger.debug("Selector.select() returned prematurely {} times in a row.", selectCnt - 1); - } - } - } catch (CancelledKeyException e) { - if (logger.isDebugEnabled()) { - logger.debug(CancelledKeyException.class.getSimpleName() + " raised by a Selector - JDK bug?", e); - } - // Harmless exception - log anyway - } - } - - private void selectAgain() { - needsToSelectAgain = false; - try { - selector.selectNow(); - } catch (Throwable t) { - logger.warn("Failed to update SelectionKeys.", t); - } - } -} diff --git a/common/src/main/java/common/net/channel/nio/NioEventLoopGroup.java b/common/src/main/java/common/net/channel/nio/NioEventLoopGroup.java deleted file mode 100644 index 926efc8..0000000 --- a/common/src/main/java/common/net/channel/nio/NioEventLoopGroup.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.nio; - -import java.nio.channels.spi.SelectorProvider; -import java.util.concurrent.ThreadFactory; - -import common.net.channel.MultithreadEventLoopGroup; -import common.net.util.concurrent.EventExecutor; - -/** - * {@link MultithreadEventLoopGroup} implementations which is used for NIO {@link Selector} based {@link Channel}s. - */ -public class NioEventLoopGroup extends MultithreadEventLoopGroup { - - /** - * Create a new instance using the default number of threads, the default {@link ThreadFactory} and - * the {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}. - */ - public NioEventLoopGroup() { - this(0); - } - - /** - * Create a new instance using the specified number of threads, {@link ThreadFactory} and the - * {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}. - */ - public NioEventLoopGroup(int nThreads) { - this(nThreads, null); - } - - /** - * Create a new instance using the specified number of threads, the given {@link ThreadFactory} and the - * {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}. - */ - public NioEventLoopGroup(int nThreads, ThreadFactory threadFactory) { - this(nThreads, threadFactory, SelectorProvider.provider()); - } - - /** - * Create a new instance using the specified number of threads, the given {@link ThreadFactory} and the given - * {@link SelectorProvider}. - */ - public NioEventLoopGroup( - int nThreads, ThreadFactory threadFactory, final SelectorProvider selectorProvider) { - super(nThreads, threadFactory, selectorProvider); - } - - /** - * Sets the percentage of the desired amount of time spent for I/O in the child event loops. The default value is - * {@code 50}, which means the event loop will try to spend the same amount of time for I/O as for non-I/O tasks. - */ - public void setIoRatio(int ioRatio) { - for (EventExecutor e: children()) { - ((NioEventLoop) e).setIoRatio(ioRatio); - } - } - - /** - * Replaces the current {@link Selector}s of the child event loops with newly created {@link Selector}s to work - * around the infamous epoll 100% CPU bug. - */ - public void rebuildSelectors() { - for (EventExecutor e: children()) { - ((NioEventLoop) e).rebuildSelector(); - } - } - - @Override - protected EventExecutor newChild( - ThreadFactory threadFactory, Object... args) throws Exception { - return new NioEventLoop(this, threadFactory, (SelectorProvider) args[0]); - } -} diff --git a/common/src/main/java/common/net/channel/nio/NioTask.java b/common/src/main/java/common/net/channel/nio/NioTask.java deleted file mode 100644 index 43dea6b..0000000 --- a/common/src/main/java/common/net/channel/nio/NioTask.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.nio; - -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; - -/** - * An arbitrary task that can be executed by {@link NioEventLoop} when a {@link SelectableChannel} becomes ready. - * - * @see NioEventLoop#register(SelectableChannel, int, NioTask) - */ -public interface NioTask { - /** - * Invoked when the {@link SelectableChannel} has been selected by the {@link Selector}. - */ - void channelReady(C ch, SelectionKey key) throws Exception; - - /** - * Invoked when the {@link SelectionKey} of the specified {@link SelectableChannel} has been cancelled and thus - * this {@link NioTask} will not be notified anymore. - * - * @param cause the cause of the unregistration. {@code null} if a user called {@link SelectionKey#cancel()} or - * the event loop has been shut down. - */ - void channelUnregistered(C ch, Throwable cause) throws Exception; -} diff --git a/common/src/main/java/common/net/channel/nio/SelectedSelectionKeySet.java b/common/src/main/java/common/net/channel/nio/SelectedSelectionKeySet.java deleted file mode 100644 index 8d7cfd8..0000000 --- a/common/src/main/java/common/net/channel/nio/SelectedSelectionKeySet.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.channel.nio; - -import java.nio.channels.SelectionKey; -import java.util.AbstractSet; -import java.util.Iterator; - -final class SelectedSelectionKeySet extends AbstractSet { - - private SelectionKey[] keysA; - private int keysASize; - private SelectionKey[] keysB; - private int keysBSize; - private boolean isA = true; - - SelectedSelectionKeySet() { - keysA = new SelectionKey[1024]; - keysB = keysA.clone(); - } - - @Override - public boolean add(SelectionKey o) { - if (o == null) { - return false; - } - - if (isA) { - int size = keysASize; - keysA[size ++] = o; - keysASize = size; - if (size == keysA.length) { - doubleCapacityA(); - } - } else { - int size = keysBSize; - keysB[size ++] = o; - keysBSize = size; - if (size == keysB.length) { - doubleCapacityB(); - } - } - - return true; - } - - private void doubleCapacityA() { - SelectionKey[] newKeysA = new SelectionKey[keysA.length << 1]; - System.arraycopy(keysA, 0, newKeysA, 0, keysASize); - keysA = newKeysA; - } - - private void doubleCapacityB() { - SelectionKey[] newKeysB = new SelectionKey[keysB.length << 1]; - System.arraycopy(keysB, 0, newKeysB, 0, keysBSize); - keysB = newKeysB; - } - - SelectionKey[] flip() { - if (isA) { - isA = false; - keysA[keysASize] = null; - keysBSize = 0; - return keysA; - } else { - isA = true; - keysB[keysBSize] = null; - keysASize = 0; - return keysB; - } - } - - @Override - public int size() { - if (isA) { - return keysASize; - } else { - return keysBSize; - } - } - - @Override - public boolean remove(Object o) { - return false; - } - - @Override - public boolean contains(Object o) { - return false; - } - - @Override - public Iterator iterator() { - throw new UnsupportedOperationException(); - } -} diff --git a/common/src/main/java/common/net/channel/socket/ChannelInputShutdownEvent.java b/common/src/main/java/common/net/channel/socket/ChannelInputShutdownEvent.java deleted file mode 100644 index 3886008..0000000 --- a/common/src/main/java/common/net/channel/socket/ChannelInputShutdownEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.socket; - -/** - * Special event which will be fired and passed to the - * {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)} methods once the input of - * a {@link SocketChannel} was shutdown and the {@link SocketChannelConfig#isAllowHalfClosure()} method returns - * {@code true}. - */ -public final class ChannelInputShutdownEvent { - - /** - * Instance to use - */ - - public static final ChannelInputShutdownEvent INSTANCE = new ChannelInputShutdownEvent(); - - private ChannelInputShutdownEvent() { } -} diff --git a/common/src/main/java/common/net/channel/socket/DefaultServerSocketChannelConfig.java b/common/src/main/java/common/net/channel/socket/DefaultServerSocketChannelConfig.java deleted file mode 100644 index 52db912..0000000 --- a/common/src/main/java/common/net/channel/socket/DefaultServerSocketChannelConfig.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.socket; - -import static common.net.channel.ChannelOption.SO_BACKLOG; -import static common.net.channel.ChannelOption.SO_RCVBUF; -import static common.net.channel.ChannelOption.SO_REUSEADDR; - -import java.net.ServerSocket; -import java.net.SocketException; -import java.util.Map; - -import common.net.buffer.ByteBufAllocator; -import common.net.channel.ChannelException; -import common.net.channel.ChannelOption; -import common.net.channel.DefaultChannelConfig; -import common.net.channel.MessageSizeEstimator; -import common.net.channel.RecvByteBufAllocator; -import common.net.util.NetUtil; - -/** - * The default {@link ServerSocketChannelConfig} implementation. - */ -public class DefaultServerSocketChannelConfig extends DefaultChannelConfig - implements ServerSocketChannelConfig { - - protected final ServerSocket javaSocket; - private volatile int backlog = NetUtil.SOMAXCONN; - - /** - * Creates a new instance. - */ - public DefaultServerSocketChannelConfig(ServerSocketChannel channel, ServerSocket javaSocket) { - super(channel); - if (javaSocket == null) { - throw new NullPointerException("javaSocket"); - } - this.javaSocket = javaSocket; - } - - @Override - public Map, Object> getOptions() { - return getOptions(super.getOptions(), SO_RCVBUF, SO_REUSEADDR, SO_BACKLOG); - } - - - @Override - public T getOption(ChannelOption option) { - if (option == SO_RCVBUF) { - return (T) Integer.valueOf(getReceiveBufferSize()); - } - if (option == SO_REUSEADDR) { - return (T) Boolean.valueOf(isReuseAddress()); - } - if (option == SO_BACKLOG) { - return (T) Integer.valueOf(getBacklog()); - } - - return super.getOption(option); - } - - @Override - public boolean setOption(ChannelOption option, T value) { - validate(option, value); - - if (option == SO_RCVBUF) { - setReceiveBufferSize((Integer) value); - } else if (option == SO_REUSEADDR) { - setReuseAddress((Boolean) value); - } else if (option == SO_BACKLOG) { - setBacklog((Integer) value); - } else { - return super.setOption(option, value); - } - - return true; - } - - @Override - public boolean isReuseAddress() { - try { - return javaSocket.getReuseAddress(); - } catch (SocketException e) { - throw new ChannelException(e); - } - } - - @Override - public ServerSocketChannelConfig setReuseAddress(boolean reuseAddress) { - try { - javaSocket.setReuseAddress(reuseAddress); - } catch (SocketException e) { - throw new ChannelException(e); - } - return this; - } - - @Override - public int getReceiveBufferSize() { - try { - return javaSocket.getReceiveBufferSize(); - } catch (SocketException e) { - throw new ChannelException(e); - } - } - - @Override - public ServerSocketChannelConfig setReceiveBufferSize(int receiveBufferSize) { - try { - javaSocket.setReceiveBufferSize(receiveBufferSize); - } catch (SocketException e) { - throw new ChannelException(e); - } - return this; - } - - @Override - public ServerSocketChannelConfig setPerformancePreferences(int connectionTime, int latency, int bandwidth) { - javaSocket.setPerformancePreferences(connectionTime, latency, bandwidth); - return this; - } - - @Override - public int getBacklog() { - return backlog; - } - - @Override - public ServerSocketChannelConfig setBacklog(int backlog) { - if (backlog < 0) { - throw new IllegalArgumentException("backlog: " + backlog); - } - this.backlog = backlog; - return this; - } - - @Override - public ServerSocketChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) { - super.setConnectTimeoutMillis(connectTimeoutMillis); - return this; - } - - @Override - public ServerSocketChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) { - super.setMaxMessagesPerRead(maxMessagesPerRead); - return this; - } - - @Override - public ServerSocketChannelConfig setWriteSpinCount(int writeSpinCount) { - super.setWriteSpinCount(writeSpinCount); - return this; - } - - @Override - public ServerSocketChannelConfig setAllocator(ByteBufAllocator allocator) { - super.setAllocator(allocator); - return this; - } - - @Override - public ServerSocketChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) { - super.setRecvByteBufAllocator(allocator); - return this; - } - - @Override - public ServerSocketChannelConfig setAutoRead(boolean autoRead) { - super.setAutoRead(autoRead); - return this; - } - - @Override - public ServerSocketChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark) { - super.setWriteBufferHighWaterMark(writeBufferHighWaterMark); - return this; - } - - @Override - public ServerSocketChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark) { - super.setWriteBufferLowWaterMark(writeBufferLowWaterMark); - return this; - } - - @Override - public ServerSocketChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) { - super.setMessageSizeEstimator(estimator); - return this; - } -} diff --git a/common/src/main/java/common/net/channel/socket/DefaultSocketChannelConfig.java b/common/src/main/java/common/net/channel/socket/DefaultSocketChannelConfig.java deleted file mode 100644 index 32bb532..0000000 --- a/common/src/main/java/common/net/channel/socket/DefaultSocketChannelConfig.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.socket; - -import static common.net.channel.ChannelOption.ALLOW_HALF_CLOSURE; -import static common.net.channel.ChannelOption.IP_TOS; -import static common.net.channel.ChannelOption.SO_KEEPALIVE; -import static common.net.channel.ChannelOption.SO_LINGER; -import static common.net.channel.ChannelOption.SO_RCVBUF; -import static common.net.channel.ChannelOption.SO_REUSEADDR; -import static common.net.channel.ChannelOption.SO_SNDBUF; -import static common.net.channel.ChannelOption.TCP_NODELAY; - -import java.net.Socket; -import java.net.SocketException; -import java.util.Map; - -import common.net.buffer.ByteBufAllocator; -import common.net.channel.ChannelException; -import common.net.channel.ChannelOption; -import common.net.channel.DefaultChannelConfig; -import common.net.channel.MessageSizeEstimator; -import common.net.channel.RecvByteBufAllocator; - -/** - * The default {@link SocketChannelConfig} implementation. - */ -public class DefaultSocketChannelConfig extends DefaultChannelConfig - implements SocketChannelConfig { - - protected final Socket javaSocket; - private volatile boolean allowHalfClosure; - - /** - * Creates a new instance. - */ - public DefaultSocketChannelConfig(SocketChannel channel, Socket javaSocket) { - super(channel); - if (javaSocket == null) { - throw new NullPointerException("javaSocket"); - } - this.javaSocket = javaSocket; - - // Enable TCP_NODELAY by default. - try { - setTcpNoDelay(true); - } catch (Exception e) { - // Ignore. - } - } - - @Override - public Map, Object> getOptions() { - return getOptions( - super.getOptions(), - SO_RCVBUF, SO_SNDBUF, TCP_NODELAY, SO_KEEPALIVE, SO_REUSEADDR, SO_LINGER, IP_TOS, - ALLOW_HALF_CLOSURE); - } - - - @Override - public T getOption(ChannelOption option) { - if (option == SO_RCVBUF) { - return (T) Integer.valueOf(getReceiveBufferSize()); - } - if (option == SO_SNDBUF) { - return (T) Integer.valueOf(getSendBufferSize()); - } - if (option == TCP_NODELAY) { - return (T) Boolean.valueOf(isTcpNoDelay()); - } - if (option == SO_KEEPALIVE) { - return (T) Boolean.valueOf(isKeepAlive()); - } - if (option == SO_REUSEADDR) { - return (T) Boolean.valueOf(isReuseAddress()); - } - if (option == SO_LINGER) { - return (T) Integer.valueOf(getSoLinger()); - } - if (option == IP_TOS) { - return (T) Integer.valueOf(getTrafficClass()); - } - if (option == ALLOW_HALF_CLOSURE) { - return (T) Boolean.valueOf(isAllowHalfClosure()); - } - - return super.getOption(option); - } - - @Override - public boolean setOption(ChannelOption option, T value) { - validate(option, value); - - if (option == SO_RCVBUF) { - setReceiveBufferSize((Integer) value); - } else if (option == SO_SNDBUF) { - setSendBufferSize((Integer) value); - } else if (option == TCP_NODELAY) { - setTcpNoDelay((Boolean) value); - } else if (option == SO_KEEPALIVE) { - setKeepAlive((Boolean) value); - } else if (option == SO_REUSEADDR) { - setReuseAddress((Boolean) value); - } else if (option == SO_LINGER) { - setSoLinger((Integer) value); - } else if (option == IP_TOS) { - setTrafficClass((Integer) value); - } else if (option == ALLOW_HALF_CLOSURE) { - setAllowHalfClosure((Boolean) value); - } else { - return super.setOption(option, value); - } - - return true; - } - - @Override - public int getReceiveBufferSize() { - try { - return javaSocket.getReceiveBufferSize(); - } catch (SocketException e) { - throw new ChannelException(e); - } - } - - @Override - public int getSendBufferSize() { - try { - return javaSocket.getSendBufferSize(); - } catch (SocketException e) { - throw new ChannelException(e); - } - } - - @Override - public int getSoLinger() { - try { - return javaSocket.getSoLinger(); - } catch (SocketException e) { - throw new ChannelException(e); - } - } - - @Override - public int getTrafficClass() { - try { - return javaSocket.getTrafficClass(); - } catch (SocketException e) { - throw new ChannelException(e); - } - } - - @Override - public boolean isKeepAlive() { - try { - return javaSocket.getKeepAlive(); - } catch (SocketException e) { - throw new ChannelException(e); - } - } - - @Override - public boolean isReuseAddress() { - try { - return javaSocket.getReuseAddress(); - } catch (SocketException e) { - throw new ChannelException(e); - } - } - - @Override - public boolean isTcpNoDelay() { - try { - return javaSocket.getTcpNoDelay(); - } catch (SocketException e) { - throw new ChannelException(e); - } - } - - @Override - public SocketChannelConfig setKeepAlive(boolean keepAlive) { - try { - javaSocket.setKeepAlive(keepAlive); - } catch (SocketException e) { - throw new ChannelException(e); - } - return this; - } - - @Override - public SocketChannelConfig setPerformancePreferences( - int connectionTime, int latency, int bandwidth) { - javaSocket.setPerformancePreferences(connectionTime, latency, bandwidth); - return this; - } - - @Override - public SocketChannelConfig setReceiveBufferSize(int receiveBufferSize) { - try { - javaSocket.setReceiveBufferSize(receiveBufferSize); - } catch (SocketException e) { - throw new ChannelException(e); - } - return this; - } - - @Override - public SocketChannelConfig setReuseAddress(boolean reuseAddress) { - try { - javaSocket.setReuseAddress(reuseAddress); - } catch (SocketException e) { - throw new ChannelException(e); - } - return this; - } - - @Override - public SocketChannelConfig setSendBufferSize(int sendBufferSize) { - try { - javaSocket.setSendBufferSize(sendBufferSize); - } catch (SocketException e) { - throw new ChannelException(e); - } - return this; - } - - @Override - public SocketChannelConfig setSoLinger(int soLinger) { - try { - if (soLinger < 0) { - javaSocket.setSoLinger(false, 0); - } else { - javaSocket.setSoLinger(true, soLinger); - } - } catch (SocketException e) { - throw new ChannelException(e); - } - return this; - } - - @Override - public SocketChannelConfig setTcpNoDelay(boolean tcpNoDelay) { - try { - javaSocket.setTcpNoDelay(tcpNoDelay); - } catch (SocketException e) { - throw new ChannelException(e); - } - return this; - } - - @Override - public SocketChannelConfig setTrafficClass(int trafficClass) { - try { - javaSocket.setTrafficClass(trafficClass); - } catch (SocketException e) { - throw new ChannelException(e); - } - return this; - } - - @Override - public boolean isAllowHalfClosure() { - return allowHalfClosure; - } - - @Override - public SocketChannelConfig setAllowHalfClosure(boolean allowHalfClosure) { - this.allowHalfClosure = allowHalfClosure; - return this; - } - - @Override - public SocketChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) { - super.setConnectTimeoutMillis(connectTimeoutMillis); - return this; - } - - @Override - public SocketChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) { - super.setMaxMessagesPerRead(maxMessagesPerRead); - return this; - } - - @Override - public SocketChannelConfig setWriteSpinCount(int writeSpinCount) { - super.setWriteSpinCount(writeSpinCount); - return this; - } - - @Override - public SocketChannelConfig setAllocator(ByteBufAllocator allocator) { - super.setAllocator(allocator); - return this; - } - - @Override - public SocketChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) { - super.setRecvByteBufAllocator(allocator); - return this; - } - - @Override - public SocketChannelConfig setAutoRead(boolean autoRead) { - super.setAutoRead(autoRead); - return this; - } - - @Override - public SocketChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark) { - super.setWriteBufferHighWaterMark(writeBufferHighWaterMark); - return this; - } - - @Override - public SocketChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark) { - super.setWriteBufferLowWaterMark(writeBufferLowWaterMark); - return this; - } - - @Override - public SocketChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) { - super.setMessageSizeEstimator(estimator); - return this; - } -} diff --git a/common/src/main/java/common/net/channel/socket/ServerSocketChannel.java b/common/src/main/java/common/net/channel/socket/ServerSocketChannel.java deleted file mode 100644 index 8808778..0000000 --- a/common/src/main/java/common/net/channel/socket/ServerSocketChannel.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.socket; - -import java.net.InetSocketAddress; - -import common.net.channel.ServerChannel; - -/** - * A TCP/IP {@link ServerChannel} which accepts incoming TCP/IP connections. - */ -public interface ServerSocketChannel extends ServerChannel { - @Override - ServerSocketChannelConfig config(); - @Override - InetSocketAddress localAddress(); - @Override - InetSocketAddress remoteAddress(); -} diff --git a/common/src/main/java/common/net/channel/socket/ServerSocketChannelConfig.java b/common/src/main/java/common/net/channel/socket/ServerSocketChannelConfig.java deleted file mode 100644 index 56138d6..0000000 --- a/common/src/main/java/common/net/channel/socket/ServerSocketChannelConfig.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.socket; - -import common.net.buffer.ByteBufAllocator; -import common.net.channel.ChannelConfig; -import common.net.channel.MessageSizeEstimator; -import common.net.channel.RecvByteBufAllocator; - -/** - * A {@link ChannelConfig} for a {@link ServerSocketChannel}. - * - *

Available options

- * - * In addition to the options provided by {@link ChannelConfig}, - * {@link ServerSocketChannelConfig} allows the following options in the - * option map: - * - * - * - * - * - * - * - * - * - * - * - *
NameAssociated setter method
{@code "backlog"}{@link #setBacklog(int)}
{@code "reuseAddress"}{@link #setReuseAddress(boolean)}
{@code "receiveBufferSize"}{@link #setReceiveBufferSize(int)}
- */ -public interface ServerSocketChannelConfig extends ChannelConfig { - - /** - * Gets the backlog value to specify when the channel binds to a local - * address. - */ - int getBacklog(); - - /** - * Sets the backlog value to specify when the channel binds to a local - * address. - */ - ServerSocketChannelConfig setBacklog(int backlog); - - /** - * Gets the {@link StandardSocketOptions#SO_REUSEADDR} option. - */ - boolean isReuseAddress(); - - /** - * Sets the {@link StandardSocketOptions#SO_REUSEADDR} option. - */ - ServerSocketChannelConfig setReuseAddress(boolean reuseAddress); - - /** - * Gets the {@link StandardSocketOptions#SO_RCVBUF} option. - */ - int getReceiveBufferSize(); - - /** - * Gets the {@link StandardSocketOptions#SO_SNDBUF} option. - */ - ServerSocketChannelConfig setReceiveBufferSize(int receiveBufferSize); - - /** - * Sets the performance preferences as specified in - * {@link ServerSocket#setPerformancePreferences(int, int, int)}. - */ - ServerSocketChannelConfig setPerformancePreferences(int connectionTime, int latency, int bandwidth); - - @Override - ServerSocketChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis); - - @Override - ServerSocketChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead); - - @Override - ServerSocketChannelConfig setWriteSpinCount(int writeSpinCount); - - @Override - ServerSocketChannelConfig setAllocator(ByteBufAllocator allocator); - - @Override - ServerSocketChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator); - - @Override - ServerSocketChannelConfig setAutoRead(boolean autoRead); - - @Override - ServerSocketChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator); -} diff --git a/common/src/main/java/common/net/channel/socket/SocketChannel.java b/common/src/main/java/common/net/channel/socket/SocketChannel.java deleted file mode 100644 index f2b3006..0000000 --- a/common/src/main/java/common/net/channel/socket/SocketChannel.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.socket; - -import java.net.InetSocketAddress; - -import common.net.channel.Channel; -import common.net.channel.ChannelFuture; -import common.net.channel.ChannelPromise; - -/** - * A TCP/IP socket {@link Channel}. - */ -public interface SocketChannel extends Channel { - @Override - ServerSocketChannel parent(); - - @Override - SocketChannelConfig config(); - @Override - InetSocketAddress localAddress(); - @Override - InetSocketAddress remoteAddress(); - - /** - * Returns {@code true} if and only if the remote peer shut down its output so that no more - * data is received from this channel. Note that the semantic of this method is different from - * that of {@link Socket#shutdownInput()} and {@link Socket#isInputShutdown()}. - */ - boolean isInputShutdown(); - - /** - * @see Socket#isOutputShutdown() - */ - boolean isOutputShutdown(); - - /** - * @see Socket#shutdownOutput() - */ - ChannelFuture shutdownOutput(); - - /** - * @see Socket#shutdownOutput() - * - * Will notify the given {@link ChannelPromise} - */ - ChannelFuture shutdownOutput(ChannelPromise future); -} diff --git a/common/src/main/java/common/net/channel/socket/SocketChannelConfig.java b/common/src/main/java/common/net/channel/socket/SocketChannelConfig.java deleted file mode 100644 index 395bb63..0000000 --- a/common/src/main/java/common/net/channel/socket/SocketChannelConfig.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.socket; - -import common.net.buffer.ByteBufAllocator; -import common.net.channel.ChannelConfig; -import common.net.channel.MessageSizeEstimator; -import common.net.channel.RecvByteBufAllocator; - -/** - * A {@link ChannelConfig} for a {@link SocketChannel}. - * - *

Available options

- * - * In addition to the options provided by {@link ChannelConfig}, - * {@link SocketChannelConfig} allows the following options in the option map: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
NameAssociated setter method
{@link ChannelOption#SO_KEEPALIVE}{@link #setKeepAlive(boolean)}
{@link ChannelOption#SO_REUSEADDR}{@link #setReuseAddress(boolean)}
{@link ChannelOption#SO_LINGER}{@link #setSoLinger(int)}
{@link ChannelOption#TCP_NODELAY}{@link #setTcpNoDelay(boolean)}
{@link ChannelOption#SO_RCVBUF}{@link #setReceiveBufferSize(int)}
{@link ChannelOption#SO_SNDBUF}{@link #setSendBufferSize(int)}
{@link ChannelOption#IP_TOS}{@link #setTrafficClass(int)}
{@link ChannelOption#ALLOW_HALF_CLOSURE}{@link #setAllowHalfClosure(boolean)}
- */ -public interface SocketChannelConfig extends ChannelConfig { - - /** - * Gets the {@link StandardSocketOptions#TCP_NODELAY} option. Please note that the default value of this option - * is {@code true} unlike the operating system default ({@code false}). However, for some buggy platforms, such as - * Android, that shows erratic behavior with Nagle's algorithm disabled, the default value remains to be - * {@code false}. - */ - boolean isTcpNoDelay(); - - /** - * Sets the {@link StandardSocketOptions#TCP_NODELAY} option. Please note that the default value of this option - * is {@code true} unlike the operating system default ({@code false}). However, for some buggy platforms, such as - * Android, that shows erratic behavior with Nagle's algorithm disabled, the default value remains to be - * {@code false}. - */ - SocketChannelConfig setTcpNoDelay(boolean tcpNoDelay); - - /** - * Gets the {@link StandardSocketOptions#SO_LINGER} option. - */ - int getSoLinger(); - - /** - * Sets the {@link StandardSocketOptions#SO_LINGER} option. - */ - SocketChannelConfig setSoLinger(int soLinger); - - /** - * Gets the {@link StandardSocketOptions#SO_SNDBUF} option. - */ - int getSendBufferSize(); - - /** - * Sets the {@link StandardSocketOptions#SO_SNDBUF} option. - */ - SocketChannelConfig setSendBufferSize(int sendBufferSize); - - /** - * Gets the {@link StandardSocketOptions#SO_RCVBUF} option. - */ - int getReceiveBufferSize(); - - /** - * Sets the {@link StandardSocketOptions#SO_RCVBUF} option. - */ - SocketChannelConfig setReceiveBufferSize(int receiveBufferSize); - - /** - * Gets the {@link StandardSocketOptions#SO_KEEPALIVE} option. - */ - boolean isKeepAlive(); - - /** - * Sets the {@link StandardSocketOptions#SO_KEEPALIVE} option. - */ - SocketChannelConfig setKeepAlive(boolean keepAlive); - - /** - * Gets the {@link StandardSocketOptions#IP_TOS} option. - */ - int getTrafficClass(); - - /** - * Sets the {@link StandardSocketOptions#IP_TOS} option. - */ - SocketChannelConfig setTrafficClass(int trafficClass); - - /** - * Gets the {@link StandardSocketOptions#SO_REUSEADDR} option. - */ - boolean isReuseAddress(); - - /** - * Sets the {@link StandardSocketOptions#SO_REUSEADDR} option. - */ - SocketChannelConfig setReuseAddress(boolean reuseAddress); - - /** - * Sets the performance preferences as specified in - * {@link Socket#setPerformancePreferences(int, int, int)}. - */ - SocketChannelConfig setPerformancePreferences(int connectionTime, int latency, int bandwidth); - - /** - * Returns {@code true} if and only if the channel should not close itself when its remote - * peer shuts down output to make the connection half-closed. If {@code false}, the connection - * is closed automatically when the remote peer shuts down output. - */ - boolean isAllowHalfClosure(); - - /** - * Sets whether the channel should not close itself when its remote peer shuts down output to - * make the connection half-closed. If {@code true} the connection is not closed when the - * remote peer shuts down output. Instead, - * {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)} - * is invoked with a {@link ChannelInputShutdownEvent} object. If {@code false}, the connection - * is closed automatically. - */ - SocketChannelConfig setAllowHalfClosure(boolean allowHalfClosure); - - @Override - SocketChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis); - - @Override - SocketChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead); - - @Override - SocketChannelConfig setWriteSpinCount(int writeSpinCount); - - @Override - SocketChannelConfig setAllocator(ByteBufAllocator allocator); - - @Override - SocketChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator); - - @Override - SocketChannelConfig setAutoRead(boolean autoRead); - - @Override - SocketChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator); -} diff --git a/common/src/main/java/common/net/channel/socket/nio/NioServerSocketChannel.java b/common/src/main/java/common/net/channel/socket/nio/NioServerSocketChannel.java deleted file mode 100644 index b006e1f..0000000 --- a/common/src/main/java/common/net/channel/socket/nio/NioServerSocketChannel.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.socket.nio; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.SocketAddress; -import java.nio.channels.SelectionKey; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.nio.channels.spi.SelectorProvider; -import java.util.List; - -import common.net.channel.ChannelException; -import common.net.channel.ChannelMetadata; -import common.net.channel.ChannelOutboundBuffer; -import common.net.channel.nio.AbstractNioMessageChannel; -import common.net.channel.socket.DefaultServerSocketChannelConfig; -import common.net.channel.socket.ServerSocketChannelConfig; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * A {@link game.net.channel.socket.ServerSocketChannel} implementation which uses - * NIO selector based implementation to accept new connections. - */ -public class NioServerSocketChannel extends AbstractNioMessageChannel - implements common.net.channel.socket.ServerSocketChannel { - - private static final ChannelMetadata METADATA = new ChannelMetadata(false); - private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider(); - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(NioServerSocketChannel.class); - - private static ServerSocketChannel newSocket(SelectorProvider provider) { - try { - /** - * Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in - * {@link SelectorProvider#provider()} which is called by each ServerSocketChannel.open() otherwise. - * - * See #2308. - */ - return provider.openServerSocketChannel(); - } catch (IOException e) { - throw new ChannelException( - "Failed to open a server socket.", e); - } - } - - private final ServerSocketChannelConfig config; - - /** - * Create a new instance - */ - public NioServerSocketChannel() { - this(newSocket(DEFAULT_SELECTOR_PROVIDER)); - } - - /** - * Create a new instance using the given {@link SelectorProvider}. - */ - public NioServerSocketChannel(SelectorProvider provider) { - this(newSocket(provider)); - } - - /** - * Create a new instance using the given {@link ServerSocketChannel}. - */ - public NioServerSocketChannel(ServerSocketChannel channel) { - super(null, channel, SelectionKey.OP_ACCEPT); - config = new NioServerSocketChannelConfig(this, javaChannel().socket()); - } - - @Override - public InetSocketAddress localAddress() { - return (InetSocketAddress) super.localAddress(); - } - - @Override - public ChannelMetadata metadata() { - return METADATA; - } - - @Override - public ServerSocketChannelConfig config() { - return config; - } - - @Override - public boolean isActive() { - return javaChannel().socket().isBound(); - } - - @Override - public InetSocketAddress remoteAddress() { - return null; - } - - @Override - protected ServerSocketChannel javaChannel() { - return (ServerSocketChannel) super.javaChannel(); - } - - @Override - protected SocketAddress localAddress0() { - return javaChannel().socket().getLocalSocketAddress(); - } - - @Override - protected void doBind(SocketAddress localAddress) throws Exception { - javaChannel().socket().bind(localAddress, config.getBacklog()); - } - - @Override - protected void doClose() throws Exception { - javaChannel().close(); - } - - @Override - protected int doReadMessages(List buf) throws Exception { - SocketChannel ch = javaChannel().accept(); - - try { - if (ch != null) { - buf.add(new NioSocketChannel(this, ch)); - return 1; - } - } catch (Throwable t) { - logger.warn("Failed to create a new channel from an accepted socket.", t); - - try { - ch.close(); - } catch (Throwable t2) { - logger.warn("Failed to close a socket.", t2); - } - } - - return 0; - } - - // Unnecessary stuff - @Override - protected boolean doConnect( - SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - protected void doFinishConnect() throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - protected SocketAddress remoteAddress0() { - return null; - } - - @Override - protected void doDisconnect() throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - protected final Object filterOutboundMessage(Object msg) throws Exception { - throw new UnsupportedOperationException(); - } - - private final class NioServerSocketChannelConfig extends DefaultServerSocketChannelConfig { - private NioServerSocketChannelConfig(NioServerSocketChannel channel, ServerSocket javaSocket) { - super(channel, javaSocket); - } - - @Override - protected void autoReadCleared() { - setReadPending(false); - } - } -} diff --git a/common/src/main/java/common/net/channel/socket/nio/NioSocketChannel.java b/common/src/main/java/common/net/channel/socket/nio/NioSocketChannel.java deleted file mode 100644 index 1ce8c3b..0000000 --- a/common/src/main/java/common/net/channel/socket/nio/NioSocketChannel.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.channel.socket.nio; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; -import java.nio.channels.spi.SelectorProvider; - -import common.net.buffer.ByteBuf; -import common.net.channel.Channel; -import common.net.channel.ChannelException; -import common.net.channel.ChannelFuture; -import common.net.channel.ChannelMetadata; -import common.net.channel.ChannelOutboundBuffer; -import common.net.channel.ChannelPromise; -import common.net.channel.EventLoop; -import common.net.channel.nio.AbstractNioByteChannel; -import common.net.channel.socket.DefaultSocketChannelConfig; -import common.net.channel.socket.ServerSocketChannel; -import common.net.channel.socket.SocketChannelConfig; -import common.net.util.internal.OneTimeTask; - -/** - * {@link game.net.channel.socket.SocketChannel} which uses NIO selector based implementation. - */ -public class NioSocketChannel extends AbstractNioByteChannel implements common.net.channel.socket.SocketChannel { - - private static final ChannelMetadata METADATA = new ChannelMetadata(false); - private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider(); - - private static SocketChannel newSocket(SelectorProvider provider) { - try { - /** - * Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in - * {@link SelectorProvider#provider()} which is called by each SocketChannel.open() otherwise. - * - * See #2308. - */ - return provider.openSocketChannel(); - } catch (IOException e) { - throw new ChannelException("Failed to open a socket.", e); - } - } - - private final SocketChannelConfig config; - - /** - * Create a new instance - */ - public NioSocketChannel() { - this(newSocket(DEFAULT_SELECTOR_PROVIDER)); - } - - /** - * Create a new instance using the given {@link SelectorProvider}. - */ - public NioSocketChannel(SelectorProvider provider) { - this(newSocket(provider)); - } - - /** - * Create a new instance using the given {@link SocketChannel}. - */ - public NioSocketChannel(SocketChannel socket) { - this(null, socket); - } - - /** - * Create a new instance - * - * @param parent the {@link Channel} which created this instance or {@code null} if it was created by the user - * @param socket the {@link SocketChannel} which will be used - */ - public NioSocketChannel(Channel parent, SocketChannel socket) { - super(parent, socket); - config = new NioSocketChannelConfig(this, socket.socket()); - } - - @Override - public ServerSocketChannel parent() { - return (ServerSocketChannel) super.parent(); - } - - @Override - public ChannelMetadata metadata() { - return METADATA; - } - - @Override - public SocketChannelConfig config() { - return config; - } - - @Override - protected SocketChannel javaChannel() { - return (SocketChannel) super.javaChannel(); - } - - @Override - public boolean isActive() { - SocketChannel ch = javaChannel(); - return ch.isOpen() && ch.isConnected(); - } - - @Override - public boolean isInputShutdown() { - return super.isInputShutdown(); - } - - @Override - public InetSocketAddress localAddress() { - return (InetSocketAddress) super.localAddress(); - } - - @Override - public InetSocketAddress remoteAddress() { - return (InetSocketAddress) super.remoteAddress(); - } - - @Override - public boolean isOutputShutdown() { - return javaChannel().socket().isOutputShutdown() || !isActive(); - } - - @Override - public ChannelFuture shutdownOutput() { - return shutdownOutput(newPromise()); - } - - @Override - public ChannelFuture shutdownOutput(final ChannelPromise promise) { - EventLoop loop = eventLoop(); - if (loop.inEventLoop()) { - try { - javaChannel().socket().shutdownOutput(); - promise.setSuccess(); - } catch (Throwable t) { - promise.setFailure(t); - } - } else { - loop.execute(new OneTimeTask() { - @Override - public void run() { - shutdownOutput(promise); - } - }); - } - return promise; - } - - @Override - protected SocketAddress localAddress0() { - return javaChannel().socket().getLocalSocketAddress(); - } - - @Override - protected SocketAddress remoteAddress0() { - return javaChannel().socket().getRemoteSocketAddress(); - } - - @Override - protected void doBind(SocketAddress localAddress) throws Exception { - javaChannel().socket().bind(localAddress); - } - - @Override - protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { - if (localAddress != null) { - javaChannel().socket().bind(localAddress); - } - - boolean success = false; - try { - boolean connected = javaChannel().connect(remoteAddress); - if (!connected) { - selectionKey().interestOps(SelectionKey.OP_CONNECT); - } - success = true; - return connected; - } finally { - if (!success) { - doClose(); - } - } - } - - @Override - protected void doFinishConnect() throws Exception { - if (!javaChannel().finishConnect()) { - throw new Error(); - } - } - - @Override - protected void doDisconnect() throws Exception { - doClose(); - } - - @Override - protected void doClose() throws Exception { - javaChannel().close(); - } - - @Override - protected int doReadBytes(ByteBuf byteBuf) throws Exception { - return byteBuf.writeBytes(javaChannel(), byteBuf.writableBytes()); - } - - @Override - protected int doWriteBytes(ByteBuf buf) throws Exception { - final int expectedWrittenBytes = buf.readableBytes(); - return buf.readBytes(javaChannel(), expectedWrittenBytes); - } - -// @Override -// protected long doWriteFileRegion(FileRegion region) throws Exception { -// final long position = region.transfered(); -// return region.transferTo(javaChannel(), position); -// } - - @Override - protected void doWrite(ChannelOutboundBuffer in) throws Exception { - for (;;) { - int size = in.size(); - if (size == 0) { - // All written so clear OP_WRITE - clearOpWrite(); - break; - } - long writtenBytes = 0; - boolean done = false; - boolean setOpWrite = false; - - // Ensure the pending writes are made of ByteBufs only. - ByteBuffer[] nioBuffers = in.nioBuffers(); - int nioBufferCnt = in.nioBufferCount(); - long expectedWrittenBytes = in.nioBufferSize(); - SocketChannel ch = javaChannel(); - - // Always us nioBuffers() to workaround data-corruption. - // See https://github.com/netty/netty/issues/2761 - switch (nioBufferCnt) { - case 0: - // We have something else beside ByteBuffers to write so fallback to normal writes. - super.doWrite(in); - return; - case 1: - // Only one ByteBuf so use non-gathering write - ByteBuffer nioBuffer = nioBuffers[0]; - for (int i = config().getWriteSpinCount() - 1; i >= 0; i --) { - final int localWrittenBytes = ch.write(nioBuffer); - if (localWrittenBytes == 0) { - setOpWrite = true; - break; - } - expectedWrittenBytes -= localWrittenBytes; - writtenBytes += localWrittenBytes; - if (expectedWrittenBytes == 0) { - done = true; - break; - } - } - break; - default: - for (int i = config().getWriteSpinCount() - 1; i >= 0; i --) { - final long localWrittenBytes = ch.write(nioBuffers, 0, nioBufferCnt); - if (localWrittenBytes == 0) { - setOpWrite = true; - break; - } - expectedWrittenBytes -= localWrittenBytes; - writtenBytes += localWrittenBytes; - if (expectedWrittenBytes == 0) { - done = true; - break; - } - } - break; - } - - // Release the fully written buffers, and update the indexes of the partially written buffer. - in.removeBytes(writtenBytes); - - if (!done) { - // Did not write all buffers completely. - incompleteWrite(setOpWrite); - break; - } - } - } - - private final class NioSocketChannelConfig extends DefaultSocketChannelConfig { - private NioSocketChannelConfig(NioSocketChannel channel, Socket javaSocket) { - super(channel, javaSocket); - } - - @Override - protected void autoReadCleared() { - setReadPending(false); - } - } -} diff --git a/common/src/main/java/common/net/handler/codec/ByteToMessageDecoder.java b/common/src/main/java/common/net/handler/codec/ByteToMessageDecoder.java deleted file mode 100644 index 9957e17..0000000 --- a/common/src/main/java/common/net/handler/codec/ByteToMessageDecoder.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.handler.codec; - -import java.util.List; - -import common.net.buffer.ByteBuf; -import common.net.buffer.Unpooled; -import common.net.channel.ChannelHandlerContext; -import common.net.channel.ChannelInboundHandlerAdapter; -import common.net.util.internal.RecyclableArrayList; -import common.net.util.internal.StringUtil; - -/** - * {@link ChannelInboundHandlerAdapter} which decodes bytes in a stream-like fashion from one {@link ByteBuf} to an - * other Message type. - * - * For example here is an implementation which reads all readable bytes from - * the input {@link ByteBuf} and create a new {@link ByteBuf}. - * - *
- *     public class SquareDecoder extends {@link ByteToMessageDecoder} {
- *         {@code @Override}
- *         public void decode({@link ChannelHandlerContext} ctx, {@link ByteBuf} in, List<Object> out)
- *                 throws {@link Exception} {
- *             out.add(in.readBytes(in.readableBytes()));
- *         }
- *     }
- * 
- * - * Be aware that sub-classes of {@link ByteToMessageDecoder} MUST NOT - * annotated with {@link @Sharable}. - */ -public abstract class ByteToMessageDecoder extends ChannelInboundHandlerAdapter { - - ByteBuf cumulation; - private boolean singleDecode; - private boolean decodeWasNull; - private boolean first; - - protected ByteToMessageDecoder() { - if (isSharable()) { - throw new IllegalStateException("@Sharable annotation is not allowed"); - } - } - - /** - * If set then only one message is decoded on each {@link #channelRead(ChannelHandlerContext, Object)} - * call. This may be useful if you need to do some protocol upgrade and want to make sure nothing is mixed up. - * - * Default is {@code false} as this has performance impacts. - */ - public void setSingleDecode(boolean singleDecode) { - this.singleDecode = singleDecode; - } - - /** - * If {@code true} then only one message is decoded on each - * {@link #channelRead(ChannelHandlerContext, Object)} call. - * - * Default is {@code false} as this has performance impacts. - */ - public boolean isSingleDecode() { - return singleDecode; - } - - /** - * Returns the actual number of readable bytes in the internal cumulative - * buffer of this decoder. You usually do not need to rely on this value - * to write a decoder. Use it only when you must use it at your own risk. - * This method is a shortcut to {@link #internalBuffer() internalBuffer().readableBytes()}. - */ - protected int actualReadableBytes() { - return internalBuffer().readableBytes(); - } - - /** - * Returns the internal cumulative buffer of this decoder. You usually - * do not need to access the internal buffer directly to write a decoder. - * Use it only when you must use it at your own risk. - */ - protected ByteBuf internalBuffer() { - if (cumulation != null) { - return cumulation; - } else { - return Unpooled.EMPTY_BUFFER; - } - } - - @Override - public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception { - ByteBuf buf = internalBuffer(); - int readable = buf.readableBytes(); - if (buf.isReadable()) { - ByteBuf bytes = buf.readBytes(readable); - buf.release(); - ctx.fireChannelRead(bytes); - } else { - buf.release(); - } - cumulation = null; - ctx.fireChannelReadComplete(); - handlerRemoved0(ctx); - } - - /** - * Gets called after the {@link ByteToMessageDecoder} was removed from the actual context and it doesn't handle - * events anymore. - */ - protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception { } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - if (msg instanceof ByteBuf) { - RecyclableArrayList out = RecyclableArrayList.newInstance(); - try { - ByteBuf data = (ByteBuf) msg; - first = cumulation == null; - if (first) { - cumulation = data; - } else { - if (cumulation.writerIndex() > cumulation.maxCapacity() - data.readableBytes() - || cumulation.refCnt() > 1) { - // Expand cumulation (by replace it) when either there is not more room in the buffer - // or if the refCnt is greater then 1 which may happen when the user use slice().retain() or - // duplicate().retain(). - // - // See: - // - https://github.com/netty/netty/issues/2327 - // - https://github.com/netty/netty/issues/1764 - expandCumulation(ctx, data.readableBytes()); - } - cumulation.writeBytes(data); - data.release(); - } - callDecode(ctx, cumulation, out); - } catch (DecoderException e) { - throw e; - } catch (Throwable t) { - throw new DecoderException(t); - } finally { - if (cumulation != null && !cumulation.isReadable()) { - cumulation.release(); - cumulation = null; - } - int size = out.size(); - decodeWasNull = size == 0; - - for (int i = 0; i < size; i ++) { - ctx.fireChannelRead(out.get(i)); - } - out.recycle(); - } - } else { - ctx.fireChannelRead(msg); - } - } - - private void expandCumulation(ChannelHandlerContext ctx, int readable) { - ByteBuf oldCumulation = cumulation; - cumulation = ctx.alloc().buffer(oldCumulation.readableBytes() + readable); - cumulation.writeBytes(oldCumulation); - oldCumulation.release(); - } - - @Override - public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { - if (cumulation != null && !first && cumulation.refCnt() == 1) { - // discard some bytes if possible to make more room in the - // buffer but only if the refCnt == 1 as otherwise the user may have - // used slice().retain() or duplicate().retain(). - // - // See: - // - https://github.com/netty/netty/issues/2327 - // - https://github.com/netty/netty/issues/1764 - cumulation.discardSomeReadBytes(); - } - if (decodeWasNull) { - decodeWasNull = false; - if (!ctx.channel().config().isAutoRead()) { - ctx.read(); - } - } - ctx.fireChannelReadComplete(); - } - - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { - RecyclableArrayList out = RecyclableArrayList.newInstance(); - try { - if (cumulation != null) { - callDecode(ctx, cumulation, out); - decodeLast(ctx, cumulation, out); - } else { - decodeLast(ctx, Unpooled.EMPTY_BUFFER, out); - } - } catch (DecoderException e) { - throw e; - } catch (Exception e) { - throw new DecoderException(e); - } finally { - try { - if (cumulation != null) { - cumulation.release(); - cumulation = null; - } - int size = out.size(); - for (int i = 0; i < size; i++) { - ctx.fireChannelRead(out.get(i)); - } - if (size > 0) { - // Something was read, call fireChannelReadComplete() - ctx.fireChannelReadComplete(); - } - ctx.fireChannelInactive(); - } finally { - // recycle in all cases - out.recycle(); - } - } - } - - /** - * Called once data should be decoded from the given {@link ByteBuf}. This method will call - * {@link #decode(ChannelHandlerContext, ByteBuf, List)} as long as decoding should take place. - * - * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to - * @param in the {@link ByteBuf} from which to read data - * @param out the {@link List} to which decoded messages should be added - */ - protected void callDecode(ChannelHandlerContext ctx, ByteBuf in, List out) { - try { - while (in.isReadable()) { - int outSize = out.size(); - int oldInputLength = in.readableBytes(); - decode(ctx, in, out); - - // Check if this handler was removed before continuing the loop. - // If it was removed, it is not safe to continue to operate on the buffer. - // - // See https://github.com/netty/netty/issues/1664 - if (ctx.isRemoved()) { - break; - } - - if (outSize == out.size()) { - if (oldInputLength == in.readableBytes()) { - break; - } else { - continue; - } - } - - if (oldInputLength == in.readableBytes()) { - throw new DecoderException( - StringUtil.simpleClassName(getClass()) + - ".decode() did not read anything but decoded a message."); - } - - if (isSingleDecode()) { - break; - } - } - } catch (DecoderException e) { - throw e; - } catch (Throwable cause) { - throw new DecoderException(cause); - } - } - - /** - * Decode the from one {@link ByteBuf} to an other. This method will be called till either the input - * {@link ByteBuf} has nothing to read when return from this method or till nothing was read from the input - * {@link ByteBuf}. - * - * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to - * @param in the {@link ByteBuf} from which to read data - * @param out the {@link List} to which decoded messages should be added - * @throws Exception is thrown if an error accour - */ - protected abstract void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception; - - /** - * Is called one last time when the {@link ChannelHandlerContext} goes in-active. Which means the - * {@link #channelInactive(ChannelHandlerContext)} was triggered. - * - * By default this will just call {@link #decode(ChannelHandlerContext, ByteBuf, List)} but sub-classes may - * override this for some special cleanup operation. - */ - protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { - decode(ctx, in, out); - } -} diff --git a/common/src/main/java/common/net/handler/codec/CodecException.java b/common/src/main/java/common/net/handler/codec/CodecException.java deleted file mode 100644 index e024083..0000000 --- a/common/src/main/java/common/net/handler/codec/CodecException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.handler.codec; - -/** - * An {@link Exception} which is thrown by a codec. - */ -public class CodecException extends RuntimeException { - - private static final long serialVersionUID = -1464830400709348473L; - - /** - * Creates a new instance. - */ - public CodecException() { - } - - /** - * Creates a new instance. - */ - public CodecException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Creates a new instance. - */ - public CodecException(String message) { - super(message); - } - - /** - * Creates a new instance. - */ - public CodecException(Throwable cause) { - super(cause); - } -} diff --git a/common/src/main/java/common/net/handler/codec/CorruptedFrameException.java b/common/src/main/java/common/net/handler/codec/CorruptedFrameException.java deleted file mode 100644 index d62f750..0000000 --- a/common/src/main/java/common/net/handler/codec/CorruptedFrameException.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.handler.codec; - -/** - * An {@link DecoderException} which is thrown when the received frame data could not be decoded by - * an inbound handler. - */ -public class CorruptedFrameException extends DecoderException { - - private static final long serialVersionUID = 3918052232492988408L; - - /** - * Creates a new instance. - */ - public CorruptedFrameException() { - } - - /** - * Creates a new instance. - */ - public CorruptedFrameException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Creates a new instance. - */ - public CorruptedFrameException(String message) { - super(message); - } - - /** - * Creates a new instance. - */ - public CorruptedFrameException(Throwable cause) { - super(cause); - } -} diff --git a/common/src/main/java/common/net/handler/codec/DecoderException.java b/common/src/main/java/common/net/handler/codec/DecoderException.java deleted file mode 100644 index 35f2beb..0000000 --- a/common/src/main/java/common/net/handler/codec/DecoderException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.handler.codec; - -/** - * An {@link CodecException} which is thrown by a dencoder. - */ -public class DecoderException extends CodecException { - - private static final long serialVersionUID = 6926716840699621852L; - - /** - * Creates a new instance. - */ - public DecoderException() { - } - - /** - * Creates a new instance. - */ - public DecoderException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Creates a new instance. - */ - public DecoderException(String message) { - super(message); - } - - /** - * Creates a new instance. - */ - public DecoderException(Throwable cause) { - super(cause); - } -} diff --git a/common/src/main/java/common/net/handler/codec/EncoderException.java b/common/src/main/java/common/net/handler/codec/EncoderException.java deleted file mode 100644 index 549455d..0000000 --- a/common/src/main/java/common/net/handler/codec/EncoderException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.handler.codec; - -/** - * An {@link CodecException} which is thrown by an encoder. - */ -public class EncoderException extends CodecException { - - private static final long serialVersionUID = -5086121160476476774L; - - /** - * Creates a new instance. - */ - public EncoderException() { - } - - /** - * Creates a new instance. - */ - public EncoderException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Creates a new instance. - */ - public EncoderException(String message) { - super(message); - } - - /** - * Creates a new instance. - */ - public EncoderException(Throwable cause) { - super(cause); - } -} diff --git a/common/src/main/java/common/net/handler/codec/MessageToByteEncoder.java b/common/src/main/java/common/net/handler/codec/MessageToByteEncoder.java deleted file mode 100644 index 9cb059d..0000000 --- a/common/src/main/java/common/net/handler/codec/MessageToByteEncoder.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.handler.codec; - -import common.net.buffer.ByteBuf; -import common.net.buffer.Unpooled; -import common.net.channel.ChannelHandlerContext; -import common.net.channel.ChannelOutboundHandlerAdapter; -import common.net.channel.ChannelPromise; -import common.net.util.ReferenceCountUtil; -import common.net.util.internal.TypeParameterMatcher; - - -/** - * {@link ChannelOutboundHandlerAdapter} which encodes message in a stream-like fashion from one message to an - * {@link ByteBuf}. - * - * - * Example implementation which encodes {@link Integer}s to a {@link ByteBuf}. - * - *
- *     public class IntegerEncoder extends {@link MessageToByteEncoder}<{@link Integer}> {
- *         {@code @Override}
- *         public void encode({@link ChannelHandlerContext} ctx, {@link Integer} msg, {@link ByteBuf} out)
- *                 throws {@link Exception} {
- *             out.writeInt(msg);
- *         }
- *     }
- * 
- */ -public abstract class MessageToByteEncoder extends ChannelOutboundHandlerAdapter { - - private final TypeParameterMatcher matcher; - private final boolean preferDirect; - - /** - * @see {@link #MessageToByteEncoder(boolean)} with {@code true} as boolean parameter. - */ - protected MessageToByteEncoder() { - this(true); - } - - /** - * @see {@link #MessageToByteEncoder(Class, boolean)} with {@code true} as boolean value. - */ - protected MessageToByteEncoder(Class outboundMessageType) { - this(outboundMessageType, true); - } - - /** - * Create a new instance which will try to detect the types to match out of the type parameter of the class. - * - * @param preferDirect {@code true} if a direct {@link ByteBuf} should be tried to be used as target for - * the encoded messages. If {@code false} is used it will allocate a heap - * {@link ByteBuf}, which is backed by an byte array. - */ - protected MessageToByteEncoder(boolean preferDirect) { - matcher = TypeParameterMatcher.find(this, MessageToByteEncoder.class, "I"); - this.preferDirect = preferDirect; - } - - /** - * Create a new instance - * - * @param outboundMessageType The tpye of messages to match - * @param preferDirect {@code true} if a direct {@link ByteBuf} should be tried to be used as target for - * the encoded messages. If {@code false} is used it will allocate a heap - * {@link ByteBuf}, which is backed by an byte array. - */ - protected MessageToByteEncoder(Class outboundMessageType, boolean preferDirect) { - matcher = TypeParameterMatcher.get(outboundMessageType); - this.preferDirect = preferDirect; - } - - /** - * Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next - * {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. - */ - public boolean acceptOutboundMessage(Object msg) throws Exception { - return matcher.match(msg); - } - - @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { - ByteBuf buf = null; - try { - if (acceptOutboundMessage(msg)) { - - I cast = (I) msg; - buf = allocateBuffer(ctx, cast, preferDirect); - try { - encode(ctx, cast, buf); - } finally { - ReferenceCountUtil.release(cast); - } - - if (buf.isReadable()) { - ctx.write(buf, promise); - } else { - buf.release(); - ctx.write(Unpooled.EMPTY_BUFFER, promise); - } - buf = null; - } else { - ctx.write(msg, promise); - } - } catch (EncoderException e) { - throw e; - } catch (Throwable e) { - throw new EncoderException(e); - } finally { - if (buf != null) { - buf.release(); - } - } - } - - /** - * Allocate a {@link ByteBuf} which will be used as argument of {@link #encode(ChannelHandlerContext, I, ByteBuf)}. - * Sub-classes may override this method to returna {@link ByteBuf} with a perfect matching {@code initialCapacity}. - */ - protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, I msg, - boolean preferDirect) throws Exception { - if (preferDirect) { - return ctx.alloc().ioBuffer(); - } else { - return ctx.alloc().heapBuffer(); - } - } - - /** - * Encode a message into a {@link ByteBuf}. This method will be called for each written message that can be handled - * by this encoder. - * - * @param ctx the {@link ChannelHandlerContext} which this {@link MessageToByteEncoder} belongs to - * @param msg the message to encode - * @param out the {@link ByteBuf} into which the encoded message will be written - * @throws Exception is thrown if an error accour - */ - protected abstract void encode(ChannelHandlerContext ctx, I msg, ByteBuf out) throws Exception; -} diff --git a/common/src/main/java/common/net/handler/codec/MessageToMessageDecoder.java b/common/src/main/java/common/net/handler/codec/MessageToMessageDecoder.java deleted file mode 100644 index 6b6c2eb..0000000 --- a/common/src/main/java/common/net/handler/codec/MessageToMessageDecoder.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.handler.codec; - -import java.util.List; - -import common.net.channel.ChannelHandlerContext; -import common.net.channel.ChannelInboundHandlerAdapter; -import common.net.util.ReferenceCountUtil; -import common.net.util.internal.RecyclableArrayList; -import common.net.util.internal.TypeParameterMatcher; - -/** - * {@link ChannelInboundHandlerAdapter} which decodes from one message to an other message. - * - * - * For example here is an implementation which decodes a {@link String} to an {@link Integer} which represent - * the length of the {@link String}. - * - *
- *     public class StringToIntegerDecoder extends
- *             {@link MessageToMessageDecoder}<{@link String}> {
- *
- *         {@code @Override}
- *         public void decode({@link ChannelHandlerContext} ctx, {@link String} message,
- *                            List<Object> out) throws {@link Exception} {
- *             out.add(message.length());
- *         }
- *     }
- * 
- * - * Be aware that you need to call {@link ReferenceCounted#retain()} on messages that are just passed through if they - * are of type {@link ReferenceCounted}. This is needed as the {@link MessageToMessageDecoder} will call - * {@link ReferenceCounted#release()} on decoded messages. - * - */ -public abstract class MessageToMessageDecoder extends ChannelInboundHandlerAdapter { - - private final TypeParameterMatcher matcher; - - /** - * Create a new instance which will try to detect the types to match out of the type parameter of the class. - */ - protected MessageToMessageDecoder() { - matcher = TypeParameterMatcher.find(this, MessageToMessageDecoder.class, "I"); - } - - /** - * Create a new instance - * - * @param inboundMessageType The type of messages to match and so decode - */ - protected MessageToMessageDecoder(Class inboundMessageType) { - matcher = TypeParameterMatcher.get(inboundMessageType); - } - - /** - * Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next - * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. - */ - public boolean acceptInboundMessage(Object msg) throws Exception { - return matcher.match(msg); - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - RecyclableArrayList out = RecyclableArrayList.newInstance(); - try { - if (acceptInboundMessage(msg)) { - I cast = (I) msg; - try { - decode(ctx, cast, out); - } finally { - ReferenceCountUtil.release(cast); - } - } else { - out.add(msg); - } - } catch (DecoderException e) { - throw e; - } catch (Exception e) { - throw new DecoderException(e); - } finally { - int size = out.size(); - for (int i = 0; i < size; i ++) { - ctx.fireChannelRead(out.get(i)); - } - out.recycle(); - } - } - - /** - * Decode from one message to an other. This method will be called for each written message that can be handled - * by this encoder. - * - * @param ctx the {@link ChannelHandlerContext} which this {@link MessageToMessageDecoder} belongs to - * @param msg the message to decode to an other one - * @param out the {@link List} to which decoded messages should be added - * @throws Exception is thrown if an error accour - */ - protected abstract void decode(ChannelHandlerContext ctx, I msg, List out) throws Exception; -} diff --git a/common/src/main/java/common/net/handler/timeout/ReadTimeoutException.java b/common/src/main/java/common/net/handler/timeout/ReadTimeoutException.java deleted file mode 100644 index 3216773..0000000 --- a/common/src/main/java/common/net/handler/timeout/ReadTimeoutException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.handler.timeout; - -/** - * A {@link TimeoutException} raised by {@link ReadTimeoutHandler} when no data - * was read within a certain period of time. - */ -public final class ReadTimeoutException extends TimeoutException { - - private static final long serialVersionUID = 169287984113283421L; - - public static final ReadTimeoutException INSTANCE = new ReadTimeoutException(); - - private ReadTimeoutException() { } -} diff --git a/common/src/main/java/common/net/handler/timeout/ReadTimeoutHandler.java b/common/src/main/java/common/net/handler/timeout/ReadTimeoutHandler.java deleted file mode 100644 index d21019c..0000000 --- a/common/src/main/java/common/net/handler/timeout/ReadTimeoutHandler.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.handler.timeout; - -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -import common.net.channel.ChannelHandlerContext; -import common.net.channel.ChannelInboundHandlerAdapter; - -/** - * Raises a {@link ReadTimeoutException} when no data was read within a certain - * period of time. - * - *
- * // The connection is closed when there is no inbound traffic
- * // for 30 seconds.
- *
- * public class MyChannelInitializer extends {@link ChannelInitializer}<{@link Channel}> {
- *     public void initChannel({@link Channel} channel) {
- *         channel.pipeline().addLast("readTimeoutHandler", new {@link ReadTimeoutHandler}(30);
- *         channel.pipeline().addLast("myHandler", new MyHandler());
- *     }
- * }
- *
- * // Handler should handle the {@link ReadTimeoutException}.
- * public class MyHandler extends {@link ChannelDuplexHandler} {
- *     {@code @Override}
- *     public void exceptionCaught({@link ChannelHandlerContext} ctx, {@link Throwable} cause)
- *             throws {@link Exception} {
- *         if (cause instanceof {@link ReadTimeoutException}) {
- *             // do something
- *         } else {
- *             super.exceptionCaught(ctx, cause);
- *         }
- *     }
- * }
- *
- * {@link ServerBootstrap} bootstrap = ...;
- * ...
- * bootstrap.childHandler(new MyChannelInitializer());
- * ...
- * 
- * @see WriteTimeoutHandler - * @see IdleStateHandler - */ -public class ReadTimeoutHandler extends ChannelInboundHandlerAdapter { - private static final long MIN_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(1); - - private final long timeoutNanos; - - private volatile ScheduledFuture timeout; - private volatile long lastReadTime; - - private volatile int state; // 0 - none, 1 - Initialized, 2 - Destroyed; - - private boolean closed; - - /** - * Creates a new instance. - * - * @param timeoutSeconds - * read timeout in seconds - */ - public ReadTimeoutHandler(int timeoutSeconds) { - this(timeoutSeconds, TimeUnit.SECONDS); - } - - /** - * Creates a new instance. - * - * @param timeout - * read timeout - * @param unit - * the {@link TimeUnit} of {@code timeout} - */ - public ReadTimeoutHandler(long timeout, TimeUnit unit) { - if (unit == null) { - throw new NullPointerException("unit"); - } - - if (timeout <= 0) { - timeoutNanos = 0; - } else { - timeoutNanos = Math.max(unit.toNanos(timeout), MIN_TIMEOUT_NANOS); - } - } - - @Override - public void handlerAdded(ChannelHandlerContext ctx) throws Exception { - if (ctx.channel().isActive() && ctx.channel().isRegistered()) { - // channelActvie() event has been fired already, which means this.channelActive() will - // not be invoked. We have to initialize here instead. - initialize(ctx); - } else { - // channelActive() event has not been fired yet. this.channelActive() will be invoked - // and initialization will occur there. - } - } - - @Override - public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { - destroy(); - } - - @Override - public void channelRegistered(ChannelHandlerContext ctx) throws Exception { - // Initialize early if channel is active already. - if (ctx.channel().isActive()) { - initialize(ctx); - } - super.channelRegistered(ctx); - } - - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - // This method will be invoked only if this handler was added - // before channelActive() event is fired. If a user adds this handler - // after the channelActive() event, initialize() will be called by beforeAdd(). - initialize(ctx); - super.channelActive(ctx); - } - - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { - destroy(); - super.channelInactive(ctx); - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - lastReadTime = System.nanoTime(); - ctx.fireChannelRead(msg); - } - - private void initialize(ChannelHandlerContext ctx) { - // Avoid the case where destroy() is called before scheduling timeouts. - // See: https://github.com/netty/netty/issues/143 - switch (state) { - case 1: - case 2: - return; - } - - state = 1; - - lastReadTime = System.nanoTime(); - if (timeoutNanos > 0) { - timeout = ctx.executor().schedule( - new ReadTimeoutTask(ctx), - timeoutNanos, TimeUnit.NANOSECONDS); - } - } - - private void destroy() { - state = 2; - - if (timeout != null) { - timeout.cancel(false); - timeout = null; - } - } - - /** - * Is called when a read timeout was detected. - */ - protected void readTimedOut(ChannelHandlerContext ctx) throws Exception { - if (!closed) { - ctx.fireExceptionCaught(ReadTimeoutException.INSTANCE); - ctx.close(); - closed = true; - } - } - - private final class ReadTimeoutTask implements Runnable { - - private final ChannelHandlerContext ctx; - - ReadTimeoutTask(ChannelHandlerContext ctx) { - this.ctx = ctx; - } - - @Override - public void run() { - if (!ctx.channel().isOpen()) { - return; - } - - long currentTime = System.nanoTime(); - long nextDelay = timeoutNanos - (currentTime - lastReadTime); - if (nextDelay <= 0) { - // Read timed out - set a new timeout and notify the callback. - timeout = ctx.executor().schedule(this, timeoutNanos, TimeUnit.NANOSECONDS); - try { - readTimedOut(ctx); - } catch (Throwable t) { - ctx.fireExceptionCaught(t); - } - } else { - // Read occurred before the timeout - set a new timeout with shorter delay. - timeout = ctx.executor().schedule(this, nextDelay, TimeUnit.NANOSECONDS); - } - } - } -} diff --git a/common/src/main/java/common/net/handler/timeout/TimeoutException.java b/common/src/main/java/common/net/handler/timeout/TimeoutException.java deleted file mode 100644 index 491f161..0000000 --- a/common/src/main/java/common/net/handler/timeout/TimeoutException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.handler.timeout; - -import common.net.channel.ChannelException; - -/** - * A {@link TimeoutException} when no data was either read or written within a - * certain period of time. - */ -public class TimeoutException extends ChannelException { - - private static final long serialVersionUID = 4673641882869672533L; - - TimeoutException() { } - - @Override - public Throwable fillInStackTrace() { - return this; - } -} diff --git a/common/src/main/java/common/net/util/Attribute.java b/common/src/main/java/common/net/util/Attribute.java deleted file mode 100644 index 56075ee..0000000 --- a/common/src/main/java/common/net/util/Attribute.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util; - -/** - * An attribute which allows to store a value reference. It may be updated atomically and so is thread-safe. - * - * @param the type of the value it holds. - */ -public interface Attribute { - - /** - * Returns the key of this attribute. - */ - AttributeKey key(); - - /** - * Returns the current value, which may be {@code null} - */ - T get(); - - /** - * Sets the value - */ - void set(T value); - - /** - * Atomically sets to the given value and returns the old value which may be {@code null} if non was set before. - */ - T getAndSet(T value); - - /** - * Atomically sets to the given value if this {@link Attribute} does not contain a value at the moment. - * If it was not possible to set the value as it contains a value it will just return the current value. - */ - T setIfAbsent(T value); - - /** - * Removes this attribute from the {@link AttributeMap} and returns the old value.. Subsequent {@link #get()} - * calls will return @{code null}. - */ - T getAndRemove(); - - /** - * Atomically sets the value to the given updated value if the current value == the expected value. - * If it the set was successful it returns {@code true} otherwise {@code false}. - */ - boolean compareAndSet(T oldValue, T newValue); - - /** - * Removes this attribute from the {@link AttributeMap}. Subsequent {@link #get()} calls will return @{code null}. - */ - void remove(); -} diff --git a/common/src/main/java/common/net/util/AttributeKey.java b/common/src/main/java/common/net/util/AttributeKey.java deleted file mode 100644 index 30f87f0..0000000 --- a/common/src/main/java/common/net/util/AttributeKey.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * Key which can be used to access {@link Attribute} out of the {@link AttributeMap}. Be aware that it is not be - * possible to have multiple keys with the same name. - * - * - * @param the type of the {@link Attribute} which can be accessed via this {@link AttributeKey}. - */ - // 'T' is used only at compile time -public final class AttributeKey extends UniqueName { - - private static final ConcurrentMap names = new ConcurrentHashMap(); - - /** - * Creates a new {@link AttributeKey} with the specified {@code name}. - */ - - public static AttributeKey valueOf(String name) { - return new AttributeKey(name); - } - - private AttributeKey(String name) { - super(names, name); - } -} diff --git a/common/src/main/java/common/net/util/AttributeMap.java b/common/src/main/java/common/net/util/AttributeMap.java deleted file mode 100644 index 2a1e85a..0000000 --- a/common/src/main/java/common/net/util/AttributeMap.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util; - -/** - * Holds {@link Attribute}s which can be accessed via {@link AttributeKey}. - * - * Implementations must be Thread-safe. - */ -public interface AttributeMap { - /** - * Get the {@link Attribute} for the given {@link AttributeKey}. This method will never return null, but may return - * an {@link Attribute} which does not have a value set yet. - */ - Attribute attr(AttributeKey key); -} diff --git a/common/src/main/java/common/net/util/CharsetUtil.java b/common/src/main/java/common/net/util/CharsetUtil.java deleted file mode 100644 index 5e69ad3..0000000 --- a/common/src/main/java/common/net/util/CharsetUtil.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util; - -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CodingErrorAction; -import java.util.Map; - -import common.net.util.internal.InternalThreadLocalMap; - -/** - * A utility class that provides various common operations and constants - * related with {@link Charset} and its relevant classes. - */ -public final class CharsetUtil { - - /** - * 16-bit UTF (UCS Transformation Format) whose byte order is identified by - * an optional byte-order mark - */ - public static final Charset UTF_16 = Charset.forName("UTF-16"); - - /** - * 16-bit UTF (UCS Transformation Format) whose byte order is big-endian - */ - public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); - - /** - * 16-bit UTF (UCS Transformation Format) whose byte order is little-endian - */ - public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); - - /** - * 8-bit UTF (UCS Transformation Format) - */ - public static final Charset UTF_8 = Charset.forName("UTF-8"); - - /** - * ISO Latin Alphabet No. 1, as known as ISO-LATIN-1 - */ - public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - - /** - * 7-bit ASCII, as known as ISO646-US or the Basic Latin block of the - * Unicode character set - */ - public static final Charset US_ASCII = Charset.forName("US-ASCII"); - - /** - * Returns a cached thread-local {@link CharsetEncoder} for the specified - * charset. - */ - public static CharsetEncoder getEncoder(Charset charset) { - if (charset == null) { - throw new NullPointerException("charset"); - } - - Map map = InternalThreadLocalMap.get().charsetEncoderCache(); - CharsetEncoder e = map.get(charset); - if (e != null) { - e.reset(); - e.onMalformedInput(CodingErrorAction.REPLACE); - e.onUnmappableCharacter(CodingErrorAction.REPLACE); - return e; - } - - e = charset.newEncoder(); - e.onMalformedInput(CodingErrorAction.REPLACE); - e.onUnmappableCharacter(CodingErrorAction.REPLACE); - map.put(charset, e); - return e; - } - - /** - * Returns a cached thread-local {@link CharsetDecoder} for the specified - * charset. - */ - public static CharsetDecoder getDecoder(Charset charset) { - if (charset == null) { - throw new NullPointerException("charset"); - } - - Map map = InternalThreadLocalMap.get().charsetDecoderCache(); - CharsetDecoder d = map.get(charset); - if (d != null) { - d.reset(); - d.onMalformedInput(CodingErrorAction.REPLACE); - d.onUnmappableCharacter(CodingErrorAction.REPLACE); - return d; - } - - d = charset.newDecoder(); - d.onMalformedInput(CodingErrorAction.REPLACE); - d.onUnmappableCharacter(CodingErrorAction.REPLACE); - map.put(charset, d); - return d; - } - - private CharsetUtil() { - // Unused - } -} diff --git a/common/src/main/java/common/net/util/DefaultAttributeMap.java b/common/src/main/java/common/net/util/DefaultAttributeMap.java deleted file mode 100644 index 83c28ab..0000000 --- a/common/src/main/java/common/net/util/DefaultAttributeMap.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util; - -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.atomic.AtomicReferenceArray; -import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; - -/** - * Default {@link AttributeMap} implementation which use simple synchronization per bucket to keep the memory overhead - * as low as possible. - */ -public class DefaultAttributeMap implements AttributeMap { - - - private static final AtomicReferenceFieldUpdater updater; - - static { - - AtomicReferenceFieldUpdater referenceFieldUpdater = - null; - if (referenceFieldUpdater == null) { - referenceFieldUpdater = AtomicReferenceFieldUpdater - .newUpdater(DefaultAttributeMap.class, AtomicReferenceArray.class, "attributes"); - } - updater = referenceFieldUpdater; - } - - private static final int BUCKET_SIZE = 4; - private static final int MASK = BUCKET_SIZE - 1; - - // Initialize lazily to reduce memory consumption; updated by AtomicReferenceFieldUpdater above. - - private volatile AtomicReferenceArray> attributes; - - - @Override - public Attribute attr(AttributeKey key) { - if (key == null) { - throw new NullPointerException("key"); - } - AtomicReferenceArray> attributes = this.attributes; - if (attributes == null) { - // Not using ConcurrentHashMap due to high memory consumption. - attributes = new AtomicReferenceArray>(BUCKET_SIZE); - - if (!updater.compareAndSet(this, null, attributes)) { - attributes = this.attributes; - } - } - - int i = index(key); - DefaultAttribute head = attributes.get(i); - if (head == null) { - // No head exists yet which means we may be able to add the attribute without synchronization and just - // use compare and set. At worst we need to fallback to synchronization - head = new DefaultAttribute(key); - if (attributes.compareAndSet(i, null, head)) { - // we were able to add it so return the head right away - return (Attribute) head; - } else { - head = attributes.get(i); - } - } - - synchronized (head) { - DefaultAttribute curr = head; - for (;;) { - if (!curr.removed && curr.key == key) { - return (Attribute) curr; - } - - DefaultAttribute next = curr.next; - if (next == null) { - DefaultAttribute attr = new DefaultAttribute(head, key); - curr.next = attr; - attr.prev = curr; - return attr; - } else { - curr = next; - } - } - } - } - - private static int index(AttributeKey key) { - return key.id() & MASK; - } - - - private static final class DefaultAttribute extends AtomicReference implements Attribute { - - private static final long serialVersionUID = -2661411462200283011L; - - // The head of the linked-list this attribute belongs to, which may be itself - private final DefaultAttribute head; - private final AttributeKey key; - - // Double-linked list to prev and next node to allow fast removal - private DefaultAttribute prev; - private DefaultAttribute next; - - // Will be set to true one the attribute is removed via getAndRemove() or remove() - private volatile boolean removed; - - DefaultAttribute(DefaultAttribute head, AttributeKey key) { - this.head = head; - this.key = key; - } - - DefaultAttribute(AttributeKey key) { - head = this; - this.key = key; - } - - @Override - public AttributeKey key() { - return key; - } - - @Override - public T setIfAbsent(T value) { - while (!compareAndSet(null, value)) { - T old = get(); - if (old != null) { - return old; - } - } - return null; - } - - @Override - public T getAndRemove() { - removed = true; - T oldValue = getAndSet(null); - remove0(); - return oldValue; - } - - @Override - public void remove() { - removed = true; - set(null); - remove0(); - } - - private void remove0() { - synchronized (head) { - // We only update the linked-list structure if prev != null because if it is null this - // DefaultAttribute acts also as head. The head must never be removed completely and just be - // marked as removed as all synchronization is done on the head itself for each bucket. - // The head itself will be GC'ed once the DefaultAttributeMap is GC'ed. So at most 5 heads will - // be removed lazy as the array size is 5. - if (prev != null) { - prev.next = next; - - if (next != null) { - next.prev = prev; - } - } - } - } - } -} diff --git a/common/src/main/java/common/net/util/IllegalReferenceCountException.java b/common/src/main/java/common/net/util/IllegalReferenceCountException.java deleted file mode 100644 index eed5aa7..0000000 --- a/common/src/main/java/common/net/util/IllegalReferenceCountException.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util; - -/** - * An {@link IllegalStateException} which is raised when a user attempts to access a {@link ReferenceCounted} whose - * reference count has been decreased to 0 (and consequently freed). - */ -public class IllegalReferenceCountException extends IllegalStateException { - - private static final long serialVersionUID = -2507492394288153468L; - - public IllegalReferenceCountException() { } - - public IllegalReferenceCountException(int refCnt) { - this("refCnt: " + refCnt); - } - - public IllegalReferenceCountException(int refCnt, int increment) { - this("refCnt: " + refCnt + ", " + (increment > 0? "increment: " + increment : "decrement: " + -increment)); - } - - public IllegalReferenceCountException(String message) { - super(message); - } - - public IllegalReferenceCountException(String message, Throwable cause) { - super(message, cause); - } - - public IllegalReferenceCountException(Throwable cause) { - super(cause); - } -} diff --git a/common/src/main/java/common/net/util/NetUtil.java b/common/src/main/java/common/net/util/NetUtil.java deleted file mode 100644 index 99e420a..0000000 --- a/common/src/main/java/common/net/util/NetUtil.java +++ /dev/null @@ -1,614 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.StringTokenizer; - -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; -import common.util.Util; - -/** - * A class that holds a number of network-related constants. - *

- * This class borrowed some of its methods from a modified fork of the - * Inet6Util class which was part of Apache Harmony. - */ -public final class NetUtil { - - /** - * The {@link Inet4Address} that represents the IPv4 loopback address '127.0.0.1' - */ - public static final Inet4Address LOCALHOST4; - - /** - * The {@link Inet6Address} that represents the IPv6 loopback address '::1' - */ - public static final Inet6Address LOCALHOST6; - - /** - * The {@link InetAddress} that represents the loopback address. If IPv6 stack is available, it will refer to - * {@link #LOCALHOST6}. Otherwise, {@link #LOCALHOST4}. - */ - public static final InetAddress LOCALHOST; - - /** - * The loopback {@link NetworkInterface} of the current machine - */ - public static final NetworkInterface LOOPBACK_IF; - - /** - * The SOMAXCONN value of the current machine. If failed to get the value, 3072 is used as a - * default value. - */ - public static final int SOMAXCONN; - - /** - * The logger being used by this class - */ - private static final InternalLogger logger = InternalLoggerFactory.getInstance(NetUtil.class); - - static { - byte[] LOCALHOST4_BYTES = {127, 0, 0, 1}; - byte[] LOCALHOST6_BYTES = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; - - // Create IPv4 loopback address. - Inet4Address localhost4 = null; - try { - localhost4 = (Inet4Address) InetAddress.getByAddress(LOCALHOST4_BYTES); - } catch (Exception e) { - // We should not get here as long as the length of the address is correct. - Util.throwUnchecked(e); - } - LOCALHOST4 = localhost4; - - // Create IPv6 loopback address. - Inet6Address localhost6 = null; - try { - localhost6 = (Inet6Address) InetAddress.getByAddress(LOCALHOST6_BYTES); - } catch (Exception e) { - // We should not get here as long as the length of the address is correct. - Util.throwUnchecked(e); - } - LOCALHOST6 = localhost6; - - // Retrieve the list of available network interfaces. - List ifaces = new ArrayList(); - try { - for (Enumeration i = NetworkInterface.getNetworkInterfaces(); i.hasMoreElements();) { - NetworkInterface iface = i.nextElement(); - // Use the interface with proper INET addresses only. - if (iface.getInetAddresses().hasMoreElements()) { - ifaces.add(iface); - } - } - } catch (SocketException e) { - logger.warn("Failed to retrieve the list of available network interfaces", e); - } - - // Find the first loopback interface available from its INET address (127.0.0.1 or ::1) - // Note that we do not use NetworkInterface.isLoopback() in the first place because it takes long time - // on a certain environment. (e.g. Windows with -Djava.net.preferIPv4Stack=true) - NetworkInterface loopbackIface = null; - InetAddress loopbackAddr = null; - loop: for (NetworkInterface iface: ifaces) { - for (Enumeration i = iface.getInetAddresses(); i.hasMoreElements();) { - InetAddress addr = i.nextElement(); - if (addr.isLoopbackAddress()) { - // Found - loopbackIface = iface; - loopbackAddr = addr; - break loop; - } - } - } - - // If failed to find the loopback interface from its INET address, fall back to isLoopback(). - if (loopbackIface == null) { - try { - for (NetworkInterface iface: ifaces) { - if (iface.isLoopback()) { - Enumeration i = iface.getInetAddresses(); - if (i.hasMoreElements()) { - // Found the one with INET address. - loopbackIface = iface; - loopbackAddr = i.nextElement(); - break; - } - } - } - - if (loopbackIface == null) { - logger.warn("Failed to find the loopback interface"); - } - } catch (SocketException e) { - logger.warn("Failed to find the loopback interface", e); - } - } - - if (loopbackIface != null) { - // Found the loopback interface with an INET address. - logger.debug( - "Loopback interface: {} ({}, {})", - loopbackIface.getName(), loopbackIface.getDisplayName(), loopbackAddr.getHostAddress()); - } else { - // Could not find the loopback interface, but we can't leave LOCALHOST as null. - // Use LOCALHOST6 or LOCALHOST4, preferably the IPv6 one. - if (loopbackAddr == null) { - try { - if (NetworkInterface.getByInetAddress(LOCALHOST6) != null) { - logger.debug("Using hard-coded IPv6 localhost address: {}", localhost6); - loopbackAddr = localhost6; - } - } catch (Exception e) { - // Ignore - } finally { - if (loopbackAddr == null) { - logger.debug("Using hard-coded IPv4 localhost address: {}", localhost4); - loopbackAddr = localhost4; - } - } - } - } - - LOOPBACK_IF = loopbackIface; - LOCALHOST = loopbackAddr; - - // Determine the default somaxconn (server socket backlog) value of the platform. - // The known defaults: - // - Windows NT Server 4.0+: 200 - // - Linux and Mac OS X: 128 - int somaxconn = Util.WINDOWS ? 200 : 128; - File file = new File("/proc/sys/net/core/somaxconn"); - if (file.exists()) { - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(file)); - somaxconn = Integer.parseInt(in.readLine()); - if (logger.isDebugEnabled()) { - logger.debug("{}: {}", file, somaxconn); - } - } catch (Exception e) { - logger.debug("Failed to get SOMAXCONN from: {}", file, e); - } finally { - if (in != null) { - try { - in.close(); - } catch (Exception e) { - // Ignored. - } - } - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("{}: {} (non-existent)", file, somaxconn); - } - } - - SOMAXCONN = somaxconn; - } - - /** - * Creates an byte[] based on an ipAddressString. No error handling is - * performed here. - */ - public static byte[] createByteArrayFromIpAddressString(String ipAddressString) { - - if (isValidIpV4Address(ipAddressString)) { - StringTokenizer tokenizer = new StringTokenizer(ipAddressString, "."); - String token; - int tempInt; - byte[] byteAddress = new byte[4]; - for (int i = 0; i < 4; i ++) { - token = tokenizer.nextToken(); - tempInt = Integer.parseInt(token); - byteAddress[i] = (byte) tempInt; - } - - return byteAddress; - } - - if (isValidIpV6Address(ipAddressString)) { - if (ipAddressString.charAt(0) == '[') { - ipAddressString = ipAddressString.substring(1, ipAddressString.length() - 1); - } - - StringTokenizer tokenizer = new StringTokenizer(ipAddressString, ":.", true); - ArrayList hexStrings = new ArrayList(); - ArrayList decStrings = new ArrayList(); - String token = ""; - String prevToken = ""; - int doubleColonIndex = -1; // If a double colon exists, we need to - // insert 0s. - - // Go through the tokens, including the seperators ':' and '.' - // When we hit a : or . the previous token will be added to either - // the hex list or decimal list. In the case where we hit a :: - // we will save the index of the hexStrings so we can add zeros - // in to fill out the string - while (tokenizer.hasMoreTokens()) { - prevToken = token; - token = tokenizer.nextToken(); - - if (":".equals(token)) { - if (":".equals(prevToken)) { - doubleColonIndex = hexStrings.size(); - } else if (!prevToken.isEmpty()) { - hexStrings.add(prevToken); - } - } else if (".".equals(token)) { - decStrings.add(prevToken); - } - } - - if (":".equals(prevToken)) { - if (":".equals(token)) { - doubleColonIndex = hexStrings.size(); - } else { - hexStrings.add(token); - } - } else if (".".equals(prevToken)) { - decStrings.add(token); - } - - // figure out how many hexStrings we should have - // also check if it is a IPv4 address - int hexStringsLength = 8; - - // If we have an IPv4 address tagged on at the end, subtract - // 4 bytes, or 2 hex words from the total - if (!decStrings.isEmpty()) { - hexStringsLength -= 2; - } - - // if we hit a double Colon add the appropriate hex strings - if (doubleColonIndex != -1) { - int numberToInsert = hexStringsLength - hexStrings.size(); - for (int i = 0; i < numberToInsert; i ++) { - hexStrings.add(doubleColonIndex, "0"); - } - } - - byte[] ipByteArray = new byte[16]; - - // Finally convert these strings to bytes... - for (int i = 0; i < hexStrings.size(); i ++) { - convertToBytes(hexStrings.get(i), ipByteArray, i * 2); - } - - // Now if there are any decimal values, we know where they go... - for (int i = 0; i < decStrings.size(); i ++) { - ipByteArray[i + 12] = (byte) (Integer.parseInt(decStrings.get(i)) & 255); - } - return ipByteArray; - } - return null; - } - - /** - * Converts a 4 character hex word into a 2 byte word equivalent - */ - private static void convertToBytes(String hexWord, byte[] ipByteArray, int byteIndex) { - - int hexWordLength = hexWord.length(); - int hexWordIndex = 0; - ipByteArray[byteIndex] = 0; - ipByteArray[byteIndex + 1] = 0; - int charValue; - - // high order 4 bits of first byte - if (hexWordLength > 3) { - charValue = getIntValue(hexWord.charAt(hexWordIndex ++)); - ipByteArray[byteIndex] |= charValue << 4; - } - - // low order 4 bits of the first byte - if (hexWordLength > 2) { - charValue = getIntValue(hexWord.charAt(hexWordIndex ++)); - ipByteArray[byteIndex] |= charValue; - } - - // high order 4 bits of second byte - if (hexWordLength > 1) { - charValue = getIntValue(hexWord.charAt(hexWordIndex ++)); - ipByteArray[byteIndex + 1] |= charValue << 4; - } - - // low order 4 bits of the first byte - charValue = getIntValue(hexWord.charAt(hexWordIndex)); - ipByteArray[byteIndex + 1] |= charValue & 15; - } - - static int getIntValue(char c) { - - switch (c) { - case '0': - return 0; - case '1': - return 1; - case '2': - return 2; - case '3': - return 3; - case '4': - return 4; - case '5': - return 5; - case '6': - return 6; - case '7': - return 7; - case '8': - return 8; - case '9': - return 9; - } - - c = Character.toLowerCase(c); - switch (c) { - case 'a': - return 10; - case 'b': - return 11; - case 'c': - return 12; - case 'd': - return 13; - case 'e': - return 14; - case 'f': - return 15; - } - return 0; - } - - public static boolean isValidIpV6Address(String ipAddress) { - int length = ipAddress.length(); - boolean doubleColon = false; - int numberOfColons = 0; - int numberOfPeriods = 0; - int numberOfPercent = 0; - StringBuilder word = new StringBuilder(); - char c = 0; - char prevChar; - int offset = 0; // offset for [] ip addresses - - if (length < 2) { - return false; - } - - for (int i = 0; i < length; i ++) { - prevChar = c; - c = ipAddress.charAt(i); - switch (c) { - - // case for an open bracket [x:x:x:...x] - case '[': - if (i != 0) { - return false; // must be first character - } - if (ipAddress.charAt(length - 1) != ']') { - return false; // must have a close ] - } - offset = 1; - if (length < 4) { - return false; - } - break; - - // case for a closed bracket at end of IP [x:x:x:...x] - case ']': - if (i != length - 1) { - return false; // must be last charcter - } - if (ipAddress.charAt(0) != '[') { - return false; // must have a open [ - } - break; - - // case for the last 32-bits represented as IPv4 x:x:x:x:x:x:d.d.d.d - case '.': - numberOfPeriods ++; - if (numberOfPeriods > 3) { - return false; - } - if (!isValidIp4Word(word.toString())) { - return false; - } - if (numberOfColons != 6 && !doubleColon) { - return false; - } - // a special case ::1:2:3:4:5:d.d.d.d allows 7 colons with an - // IPv4 ending, otherwise 7 :'s is bad - if (numberOfColons == 7 && ipAddress.charAt(offset) != ':' && - ipAddress.charAt(1 + offset) != ':') { - return false; - } - word.delete(0, word.length()); - break; - - case ':': - // FIX "IP6 mechanism syntax #ip6-bad1" - // An IPV6 address cannot start with a single ":". - // Either it can starti with "::" or with a number. - if (i == offset && (ipAddress.length() <= i || ipAddress.charAt(i + 1) != ':')) { - return false; - } - // END FIX "IP6 mechanism syntax #ip6-bad1" - numberOfColons ++; - if (numberOfColons > 7) { - return false; - } - if (numberOfPeriods > 0) { - return false; - } - if (prevChar == ':') { - if (doubleColon) { - return false; - } - doubleColon = true; - } - word.delete(0, word.length()); - break; - case '%': - if (numberOfColons == 0) { - return false; - } - numberOfPercent ++; - - // validate that the stuff after the % is valid - if (i + 1 >= length) { - // in this case the percent is there but no number is - // available - return false; - } - try { - if (Integer.parseInt(ipAddress.substring(i + 1)) < 0) { - return false; - } - } catch (NumberFormatException e) { - // right now we just support an integer after the % so if - // this is not - // what is there then return - return false; - } - break; - - default: - if (numberOfPercent == 0) { - if (word != null && word.length() > 3) { - return false; - } - if (!isValidHexChar(c)) { - return false; - } - } - word.append(c); - } - } - - // Check if we have an IPv4 ending - if (numberOfPeriods > 0) { - // There is a test case with 7 colons and valid ipv4 this should resolve it - if (numberOfPeriods != 3 || !(isValidIp4Word(word.toString()) && numberOfColons < 7)) { - return false; - } - } else { - // If we're at then end and we haven't had 7 colons then there is a - // problem unless we encountered a doubleColon - if (numberOfColons != 7 && !doubleColon) { - return false; - } - - // If we have an empty word at the end, it means we ended in either - // a : or a . - // If we did not end in :: then this is invalid - if (numberOfPercent == 0) { - if (word.length() == 0 && ipAddress.charAt(length - 1 - offset) == ':' && - ipAddress.charAt(length - 2 - offset) != ':') { - return false; - } - } - } - - return true; - } - - public static boolean isValidIp4Word(String word) { - char c; - if (word.length() < 1 || word.length() > 3) { - return false; - } - for (int i = 0; i < word.length(); i ++) { - c = word.charAt(i); - if (!(c >= '0' && c <= '9')) { - return false; - } - } - return Integer.parseInt(word) <= 255; - } - - static boolean isValidHexChar(char c) { - return c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f'; - } - - /** - * Takes a string and parses it to see if it is a valid IPV4 address. - * - * @return true, if the string represents an IPV4 address in dotted - * notation, false otherwise - */ - public static boolean isValidIpV4Address(String value) { - - int periods = 0; - int i; - int length = value.length(); - - if (length > 15) { - return false; - } - char c; - StringBuilder word = new StringBuilder(); - for (i = 0; i < length; i ++) { - c = value.charAt(i); - if (c == '.') { - periods ++; - if (periods > 3) { - return false; - } - if (word.length() == 0) { - return false; - } - if (Integer.parseInt(word.toString()) > 255) { - return false; - } - word.delete(0, word.length()); - } else if (!Character.isDigit(c)) { - return false; - } else { - if (word.length() > 2) { - return false; - } - word.append(c); - } - } - - if (word.length() == 0 || Integer.parseInt(word.toString()) > 255) { - return false; - } - - return periods == 3; - } - - /** - * A constructor to stop this class being constructed. - */ - private NetUtil() { - // Unused - } -} diff --git a/common/src/main/java/common/net/util/Recycler.java b/common/src/main/java/common/net/util/Recycler.java deleted file mode 100644 index 9fb120d..0000000 --- a/common/src/main/java/common/net/util/Recycler.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util; - -import java.lang.ref.WeakReference; -import java.util.Arrays; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.concurrent.atomic.AtomicInteger; - -import common.net.util.concurrent.FastThreadLocal; -import common.net.util.internal.SystemPropertyUtil; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * Light-weight object pool based on a thread-local stack. - * - * @param the type of the pooled object - */ -public abstract class Recycler { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(Recycler.class); - - private static final AtomicInteger ID_GENERATOR = new AtomicInteger(Integer.MIN_VALUE); - private static final int OWN_THREAD_ID = ID_GENERATOR.getAndIncrement(); - private static final int DEFAULT_MAX_CAPACITY; - private static final int INITIAL_CAPACITY; - - static { - // In the future, we might have different maxCapacity for different object types. - // e.g. game.net.recycler.maxCapacity.writeTask - // game.net.recycler.maxCapacity.outboundBuffer - int maxCapacity = SystemPropertyUtil.getInt("game.net.recycler.maxCapacity.default", 0); - if (maxCapacity <= 0) { - // TODO: Some arbitrary large number - should adjust as we get more production experience. - maxCapacity = 262144; - } - - DEFAULT_MAX_CAPACITY = maxCapacity; - if (logger.isDebugEnabled()) { - logger.debug("-Dgame.net.recycler.maxCapacity.default: {}", DEFAULT_MAX_CAPACITY); - } - - INITIAL_CAPACITY = Math.min(DEFAULT_MAX_CAPACITY, 256); - } - - private final int maxCapacity; - private final FastThreadLocal> threadLocal = new FastThreadLocal>() { - @Override - protected Stack initialValue() { - return new Stack(Recycler.this, Thread.currentThread(), maxCapacity); - } - }; - - protected Recycler() { - this(DEFAULT_MAX_CAPACITY); - } - - protected Recycler(int maxCapacity) { - this.maxCapacity = Math.max(0, maxCapacity); - } - - - public final T get() { - Stack stack = threadLocal.get(); - DefaultHandle handle = stack.pop(); - if (handle == null) { - handle = stack.newHandle(); - handle.value = newObject(handle); - } - return (T) handle.value; - } - - public final boolean recycle(T o, Handle handle) { - DefaultHandle h = (DefaultHandle) handle; - if (h.stack.parent != this) { - return false; - } - if (o != h.value) { - throw new IllegalArgumentException("o does not belong to handle"); - } - h.recycle(); - return true; - } - - protected abstract T newObject(Handle handle); - - public interface Handle { } - - static final class DefaultHandle implements Handle { - private int lastRecycledId; - private int recycleId; - - private Stack stack; - private Object value; - - DefaultHandle(Stack stack) { - this.stack = stack; - } - - public void recycle() { - Thread thread = Thread.currentThread(); - if (thread == stack.thread) { - stack.push(this); - return; - } - // we don't want to have a ref to the queue as the value in our weak map - // so we null it out; to ensure there are no races with restoring it later - // we impose a memory ordering here (no-op on x86) - Map, WeakOrderQueue> delayedRecycled = DELAYED_RECYCLED.get(); - WeakOrderQueue queue = delayedRecycled.get(stack); - if (queue == null) { - delayedRecycled.put(stack, queue = new WeakOrderQueue(stack, thread)); - } - queue.add(this); - } - } - - private static final FastThreadLocal, WeakOrderQueue>> DELAYED_RECYCLED = - new FastThreadLocal, WeakOrderQueue>>() { - @Override - protected Map, WeakOrderQueue> initialValue() { - return new WeakHashMap, WeakOrderQueue>(); - } - }; - - // a queue that makes only moderate guarantees about visibility: items are seen in the correct order, - // but we aren't absolutely guaranteed to ever see anything at all, thereby keeping the queue cheap to maintain - private static final class WeakOrderQueue { - private static final int LINK_CAPACITY = 16; - - // Let Link extend AtomicInteger for intrinsics. The Link itself will be used as writerIndex. - - private static final class Link extends AtomicInteger { - private final DefaultHandle[] elements = new DefaultHandle[LINK_CAPACITY]; - - private int readIndex; - private Link next; - } - - // chain of data items - private Link head, tail; - // pointer to another queue of delayed items for the same stack - private WeakOrderQueue next; - private final WeakReference owner; - private final int id = ID_GENERATOR.getAndIncrement(); - - WeakOrderQueue(Stack stack, Thread thread) { - head = tail = new Link(); - owner = new WeakReference(thread); - synchronized (stack) { - next = stack.head; - stack.head = this; - } - } - - void add(DefaultHandle handle) { - handle.lastRecycledId = id; - - Link tail = this.tail; - int writeIndex; - if ((writeIndex = tail.get()) == LINK_CAPACITY) { - this.tail = tail = tail.next = new Link(); - writeIndex = tail.get(); - } - tail.elements[writeIndex] = handle; - handle.stack = null; - // we lazy set to ensure that setting stack to null appears before we unnull it in the owning thread; - // this also means we guarantee visibility of an element in the queue if we see the index updated - tail.lazySet(writeIndex + 1); - } - - boolean hasFinalData() { - return tail.readIndex != tail.get(); - } - - // transfer as many items as we can from this queue to the stack, returning true if any were transferred - - boolean transfer(Stack to) { - - Link head = this.head; - if (head == null) { - return false; - } - - if (head.readIndex == LINK_CAPACITY) { - if (head.next == null) { - return false; - } - this.head = head = head.next; - } - - int start = head.readIndex; - int end = head.get(); - if (start == end) { - return false; - } - - int count = end - start; - if (to.size + count > to.elements.length) { - to.elements = Arrays.copyOf(to.elements, (to.size + count) * 2); - } - - DefaultHandle[] src = head.elements; - DefaultHandle[] trg = to.elements; - int size = to.size; - while (start < end) { - DefaultHandle element = src[start]; - if (element.recycleId == 0) { - element.recycleId = element.lastRecycledId; - } else if (element.recycleId != element.lastRecycledId) { - throw new IllegalStateException("recycled already"); - } - element.stack = to; - trg[size++] = element; - src[start++] = null; - } - to.size = size; - - if (end == LINK_CAPACITY && head.next != null) { - this.head = head.next; - } - - head.readIndex = end; - return true; - } - } - - static final class Stack { - - // we keep a queue of per-thread queues, which is appended to once only, each time a new thread other - // than the stack owner recycles: when we run out of items in our stack we iterate this collection - // to scavenge those that can be reused. this permits us to incur minimal thread synchronisation whilst - // still recycling all items. - final Recycler parent; - final Thread thread; - private DefaultHandle[] elements; - private final int maxCapacity; - private int size; - - private volatile WeakOrderQueue head; - private WeakOrderQueue cursor, prev; - - Stack(Recycler parent, Thread thread, int maxCapacity) { - this.parent = parent; - this.thread = thread; - this.maxCapacity = maxCapacity; - elements = new DefaultHandle[INITIAL_CAPACITY]; - } - - DefaultHandle pop() { - int size = this.size; - if (size == 0) { - if (!scavenge()) { - return null; - } - size = this.size; - } - size --; - DefaultHandle ret = elements[size]; - if (ret.lastRecycledId != ret.recycleId) { - throw new IllegalStateException("recycled multiple times"); - } - ret.recycleId = 0; - ret.lastRecycledId = 0; - this.size = size; - return ret; - } - - boolean scavenge() { - // continue an existing scavenge, if any - if (scavengeSome()) { - return true; - } - - // reset our scavenge cursor - prev = null; - cursor = head; - return false; - } - - boolean scavengeSome() { - boolean success = false; - WeakOrderQueue cursor = this.cursor, prev = this.prev; - while (cursor != null) { - if (cursor.transfer(this)) { - success = true; - break; - } - WeakOrderQueue next = cursor.next; - if (cursor.owner.get() == null) { - // if the thread associated with the queue is gone, unlink it, after - // performing a volatile read to confirm there is no data left to collect - // we never unlink the first queue, as we don't want to synchronize on updating the head - if (cursor.hasFinalData()) { - for (;;) { - if (!cursor.transfer(this)) { - break; - } - } - } - if (prev != null) { - prev.next = next; - } - } else { - prev = cursor; - } - cursor = next; - } - this.prev = prev; - this.cursor = cursor; - return success; - } - - void push(DefaultHandle item) { - if ((item.recycleId | item.lastRecycledId) != 0) { - throw new IllegalStateException("recycled already"); - } - item.recycleId = item.lastRecycledId = OWN_THREAD_ID; - - int size = this.size; - if (size == elements.length) { - if (size == maxCapacity) { - // Hit the maximum capacity - drop the possibly youngest object. - return; - } - elements = Arrays.copyOf(elements, size << 1); - } - - elements[size] = item; - this.size = size + 1; - } - - DefaultHandle newHandle() { - return new DefaultHandle(this); - } - } -} diff --git a/common/src/main/java/common/net/util/ReferenceCountUtil.java b/common/src/main/java/common/net/util/ReferenceCountUtil.java deleted file mode 100644 index 7c55c48..0000000 --- a/common/src/main/java/common/net/util/ReferenceCountUtil.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util; - -import common.net.util.internal.StringUtil; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * Collection of method to handle objects that may implement {@link ReferenceCounted}. - */ -public final class ReferenceCountUtil { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(ReferenceCountUtil.class); - - /** - * Try to call {@link ReferenceCounted#retain()} if the specified message implements {@link ReferenceCounted}. - * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. - */ - - public static T retain(T msg) { - if (msg instanceof ReferenceCounted) { - return (T) ((ReferenceCounted) msg).retain(); - } - return msg; - } - - /** - * Try to call {@link ReferenceCounted#retain()} if the specified message implements {@link ReferenceCounted}. - * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. - */ - - public static T retain(T msg, int increment) { - if (msg instanceof ReferenceCounted) { - return (T) ((ReferenceCounted) msg).retain(increment); - } - return msg; - } - - /** - * Try to call {@link ReferenceCounted#release()} if the specified message implements {@link ReferenceCounted}. - * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. - */ - public static boolean release(Object msg) { - if (msg instanceof ReferenceCounted) { - return ((ReferenceCounted) msg).release(); - } - return false; - } - - /** - * Try to call {@link ReferenceCounted#release(int)} if the specified message implements {@link ReferenceCounted}. - * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. - */ - public static boolean release(Object msg, int decrement) { - if (msg instanceof ReferenceCounted) { - return ((ReferenceCounted) msg).release(decrement); - } - return false; - } - - /** - * Try to call {@link ReferenceCounted#release()} if the specified message implements {@link ReferenceCounted}. - * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. - * Unlike {@link #release(Object)} this method catches an exception raised by {@link ReferenceCounted#release()} - * and logs it, rather than rethrowing it to the caller. It is usually recommended to use {@link #release(Object)} - * instead, unless you absolutely need to swallow an exception. - */ - public static void safeRelease(Object msg) { - try { - release(msg); - } catch (Throwable t) { - logger.warn("Failed to release a message: {}", msg, t); - } - } - - /** - * Try to call {@link ReferenceCounted#release(int)} if the specified message implements {@link ReferenceCounted}. - * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. - * Unlike {@link #release(Object)} this method catches an exception raised by {@link ReferenceCounted#release(int)} - * and logs it, rather than rethrowing it to the caller. It is usually recommended to use - * {@link #release(Object, int)} instead, unless you absolutely need to swallow an exception. - */ - public static void safeRelease(Object msg, int decrement) { - try { - release(msg, decrement); - } catch (Throwable t) { - if (logger.isWarnEnabled()) { - logger.warn("Failed to release a message: {} (decrement: {})", msg, decrement, t); - } - } - } - - /** - * Schedules the specified object to be released when the caller thread terminates. Note that this operation is - * intended to simplify reference counting of ephemeral objects during unit tests. Do not use it beyond the - * intended use case. - */ - public static T releaseLater(T msg) { - return releaseLater(msg, 1); - } - - /** - * Schedules the specified object to be released when the caller thread terminates. Note that this operation is - * intended to simplify reference counting of ephemeral objects during unit tests. Do not use it beyond the - * intended use case. - */ - public static T releaseLater(T msg, int decrement) { - if (msg instanceof ReferenceCounted) { - ThreadDeathWatcher.watch(Thread.currentThread(), new ReleasingTask((ReferenceCounted) msg, decrement)); - } - return msg; - } - - /** - * Releases the objects when the thread that called {@link #releaseLater(Object)} has been terminated. - */ - private static final class ReleasingTask implements Runnable { - - private final ReferenceCounted obj; - private final int decrement; - - ReleasingTask(ReferenceCounted obj, int decrement) { - this.obj = obj; - this.decrement = decrement; - } - - @Override - public void run() { - try { - if (!obj.release(decrement)) { - logger.warn("Non-zero refCnt: {}", this); - } else { - logger.debug("Released: {}", this); - } - } catch (Exception ex) { - logger.warn("Failed to release an object: {}", obj, ex); - } - } - - @Override - public String toString() { - return StringUtil.simpleClassName(obj) + ".release(" + decrement + ") refCnt: " + obj.refCnt(); - } - } - - private ReferenceCountUtil() { } -} diff --git a/common/src/main/java/common/net/util/ReferenceCounted.java b/common/src/main/java/common/net/util/ReferenceCounted.java deleted file mode 100644 index 33d6097..0000000 --- a/common/src/main/java/common/net/util/ReferenceCounted.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util; - -/** - * A reference-counted object that requires explicit deallocation. - *

- * When a new {@link ReferenceCounted} is instantiated, it starts with the reference count of {@code 1}. - * {@link #retain()} increases the reference count, and {@link #release()} decreases the reference count. - * If the reference count is decreased to {@code 0}, the object will be deallocated explicitly, and accessing - * the deallocated object will usually result in an access violation. - *

- *

- * If an object that implements {@link ReferenceCounted} is a container of other objects that implement - * {@link ReferenceCounted}, the contained objects will also be released via {@link #release()} when the container's - * reference count becomes 0. - *

- */ -public interface ReferenceCounted { - /** - * Returns the reference count of this object. If {@code 0}, it means this object has been deallocated. - */ - int refCnt(); - - /** - * Increases the reference count by {@code 1}. - */ - ReferenceCounted retain(); - - /** - * Increases the reference count by the specified {@code increment}. - */ - ReferenceCounted retain(int increment); - - /** - * Decreases the reference count by {@code 1} and deallocates this object if the reference count reaches at - * {@code 0}. - * - * @return {@code true} if and only if the reference count became {@code 0} and this object has been deallocated - */ - boolean release(); - - /** - * Decreases the reference count by the specified {@code decrement} and deallocates this object if the reference - * count reaches at {@code 0}. - * - * @return {@code true} if and only if the reference count became {@code 0} and this object has been deallocated - */ - boolean release(int decrement); -} diff --git a/common/src/main/java/common/net/util/ResourceLeak.java b/common/src/main/java/common/net/util/ResourceLeak.java deleted file mode 100644 index 00064a7..0000000 --- a/common/src/main/java/common/net/util/ResourceLeak.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util; - -public interface ResourceLeak { - /** - * Records the caller's current stack trace so that the {@link ResourceLeakDetector} can tell where the leaked - * resource was accessed lastly. - */ - void record(); - - /** - * Close the leak so that {@link ResourceLeakDetector} does not warn about leaked resources. - * - * @return {@code true} if called first time, {@code false} if called already - */ - boolean close(); -} diff --git a/common/src/main/java/common/net/util/ResourceLeakDetector.java b/common/src/main/java/common/net/util/ResourceLeakDetector.java deleted file mode 100644 index 0159efd..0000000 --- a/common/src/main/java/common/net/util/ResourceLeakDetector.java +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util; - -import static common.net.util.internal.StringUtil.NEWLINE; -import static common.net.util.internal.StringUtil.simpleClassName; - -import java.lang.ref.PhantomReference; -import java.lang.ref.ReferenceQueue; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.EnumSet; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicBoolean; - -import common.net.util.internal.SystemPropertyUtil; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -public final class ResourceLeakDetector { - - private static final String PROP_LEVEL = "game.net.leakDetectionLevel"; - private static final Level DEFAULT_LEVEL = Level.SIMPLE; - - /** - * Represents the level of resource leak detection. - */ - public enum Level { - /** - * Disables resource leak detection. - */ - DISABLED, - /** - * Enables simplistic sampling resource leak detection which reports there is a leak or not, - * at the cost of small overhead (default). - */ - SIMPLE, - /** - * Enables advanced sampling resource leak detection which reports where the leaked object was accessed - * recently at the cost of high overhead. - */ - ADVANCED, - /** - * Enables paranoid resource leak detection which reports where the leaked object was accessed recently, - * at the cost of the highest possible overhead (for testing purposes only). - */ - PARANOID - } - - private static Level level; - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(ResourceLeakDetector.class); - - static { - final boolean disabled; - if (SystemPropertyUtil.get("game.net.noResourceLeakDetection") != null) { - disabled = SystemPropertyUtil.getBoolean("game.net.noResourceLeakDetection", false); - logger.debug("-Dgame.net.noResourceLeakDetection: {}", disabled); - logger.warn( - "-Dgame.net.noResourceLeakDetection is deprecated. Use '-D{}={}' instead.", - PROP_LEVEL, DEFAULT_LEVEL.name().toLowerCase()); - } else { - disabled = false; - } - - Level defaultLevel = disabled? Level.DISABLED : DEFAULT_LEVEL; - String levelStr = SystemPropertyUtil.get(PROP_LEVEL, defaultLevel.name()).trim().toUpperCase(); - Level level = DEFAULT_LEVEL; - for (Level l: EnumSet.allOf(Level.class)) { - if (levelStr.equals(l.name()) || levelStr.equals(String.valueOf(l.ordinal()))) { - level = l; - } - } - - ResourceLeakDetector.level = level; - if (logger.isDebugEnabled()) { - logger.debug("-D{}: {}", PROP_LEVEL, level.name().toLowerCase()); - } - } - - private static final int DEFAULT_SAMPLING_INTERVAL = 113; - - /** - * Returns {@code true} if resource leak detection is enabled. - */ - public static boolean isEnabled() { - return getLevel().ordinal() > Level.DISABLED.ordinal(); - } - - /** - * Sets the resource leak detection level. - */ - public static void setLevel(Level level) { - if (level == null) { - throw new NullPointerException("level"); - } - ResourceLeakDetector.level = level; - } - - /** - * Returns the current resource leak detection level. - */ - public static Level getLevel() { - return level; - } - - /** the linked list of active resources */ - private final DefaultResourceLeak head = new DefaultResourceLeak(null); - private final DefaultResourceLeak tail = new DefaultResourceLeak(null); - - private final ReferenceQueue refQueue = new ReferenceQueue(); - private final ConcurrentMap reportedLeaks = new ConcurrentHashMap(); - - private final String resourceType; - private final int samplingInterval; - private final long maxActive; - private long active; - private final AtomicBoolean loggedTooManyActive = new AtomicBoolean(); - - private long leakCheckCnt; - - public ResourceLeakDetector(Class resourceType) { - this(simpleClassName(resourceType)); - } - - public ResourceLeakDetector(String resourceType) { - this(resourceType, DEFAULT_SAMPLING_INTERVAL, Long.MAX_VALUE); - } - - public ResourceLeakDetector(Class resourceType, int samplingInterval, long maxActive) { - this(simpleClassName(resourceType), samplingInterval, maxActive); - } - - public ResourceLeakDetector(String resourceType, int samplingInterval, long maxActive) { - if (resourceType == null) { - throw new NullPointerException("resourceType"); - } - if (samplingInterval <= 0) { - throw new IllegalArgumentException("samplingInterval: " + samplingInterval + " (expected: 1+)"); - } - if (maxActive <= 0) { - throw new IllegalArgumentException("maxActive: " + maxActive + " (expected: 1+)"); - } - - this.resourceType = resourceType; - this.samplingInterval = samplingInterval; - this.maxActive = maxActive; - - head.next = tail; - tail.prev = head; - } - - /** - * Creates a new {@link ResourceLeak} which is expected to be closed via {@link ResourceLeak#close()} when the - * related resource is deallocated. - * - * @return the {@link ResourceLeak} or {@code null} - */ - public ResourceLeak open(T obj) { - Level level = ResourceLeakDetector.level; - if (level == Level.DISABLED) { - return null; - } - - if (level.ordinal() < Level.PARANOID.ordinal()) { - if (leakCheckCnt ++ % samplingInterval == 0) { - reportLeak(level); - return new DefaultResourceLeak(obj); - } else { - return null; - } - } else { - reportLeak(level); - return new DefaultResourceLeak(obj); - } - } - - private void reportLeak(Level level) { - if (!logger.isErrorEnabled()) { - for (;;) { - - DefaultResourceLeak ref = (DefaultResourceLeak) refQueue.poll(); - if (ref == null) { - break; - } - ref.close(); - } - return; - } - - // Report too many instances. - int samplingInterval = level == Level.PARANOID? 1 : this.samplingInterval; - if (active * samplingInterval > maxActive && loggedTooManyActive.compareAndSet(false, true)) { - logger.error("LEAK: You are creating too many " + resourceType + " instances. " + - resourceType + " is a shared resource that must be reused across the JVM," + - "so that only a few instances are created."); - } - - // Detect and report previous leaks. - for (;;) { - - DefaultResourceLeak ref = (DefaultResourceLeak) refQueue.poll(); - if (ref == null) { - break; - } - - ref.clear(); - - if (!ref.close()) { - continue; - } - - String records = ref.toString(); - if (reportedLeaks.putIfAbsent(records, Boolean.TRUE) == null) { - if (records.isEmpty()) { - logger.error("LEAK: {}.release() was not called before it's garbage-collected. " + - "Enable advanced leak reporting to find out where the leak occurred. " + - "To enable advanced leak reporting, " + - "specify the JVM option '-D{}={}' or call {}.setLevel()", - resourceType, PROP_LEVEL, Level.ADVANCED.name().toLowerCase(), simpleClassName(this)); - } else { - logger.error( - "LEAK: {}.release() was not called before it's garbage-collected.{}", - resourceType, records); - } - } - } - } - - private final class DefaultResourceLeak extends PhantomReference implements ResourceLeak { - - private static final int MAX_RECORDS = 4; - - private final String creationRecord; - private final Deque lastRecords = new ArrayDeque(); - private final AtomicBoolean freed; - private DefaultResourceLeak prev; - private DefaultResourceLeak next; - - DefaultResourceLeak(Object referent) { - super(referent, referent != null? refQueue : null); - - if (referent != null) { - Level level = getLevel(); - if (level.ordinal() >= Level.ADVANCED.ordinal()) { - creationRecord = newRecord(3); - } else { - creationRecord = null; - } - - // TODO: Use CAS to update the list. - synchronized (head) { - prev = head; - next = head.next; - head.next.prev = this; - head.next = this; - active ++; - } - freed = new AtomicBoolean(); - } else { - creationRecord = null; - freed = new AtomicBoolean(true); - } - } - - @Override - public void record() { - if (creationRecord != null) { - String value = newRecord(2); - - synchronized (lastRecords) { - int size = lastRecords.size(); - if (size == 0 || !lastRecords.getLast().equals(value)) { - lastRecords.add(value); - } - if (size > MAX_RECORDS) { - lastRecords.removeFirst(); - } - } - } - } - - @Override - public boolean close() { - if (freed.compareAndSet(false, true)) { - synchronized (head) { - active --; - prev.next = next; - next.prev = prev; - prev = null; - next = null; - } - return true; - } - return false; - } - - public String toString() { - if (creationRecord == null) { - return ""; - } - - Object[] array; - synchronized (lastRecords) { - array = lastRecords.toArray(); - } - - StringBuilder buf = new StringBuilder(16384); - buf.append(NEWLINE); - buf.append("Recent access records: "); - buf.append(array.length); - buf.append(NEWLINE); - - if (array.length > 0) { - for (int i = array.length - 1; i >= 0; i --) { - buf.append('#'); - buf.append(i + 1); - buf.append(':'); - buf.append(NEWLINE); - buf.append(array[i]); - } - } - - buf.append("Created at:"); - buf.append(NEWLINE); - buf.append(creationRecord); - buf.setLength(buf.length() - NEWLINE.length()); - - return buf.toString(); - } - } - - private static final String[] STACK_TRACE_ELEMENT_EXCLUSIONS = { - "game.net.buffer.AbstractByteBufAllocator.toLeakAwareBuffer(", - }; - - static String newRecord(int recordsToSkip) { - StringBuilder buf = new StringBuilder(4096); - StackTraceElement[] array = new Throwable().getStackTrace(); - for (StackTraceElement e: array) { - if (recordsToSkip > 0) { - recordsToSkip --; - } else { - String estr = e.toString(); - - // Strip the noisy stack trace elements. - boolean excluded = false; - for (String exclusion: STACK_TRACE_ELEMENT_EXCLUSIONS) { - if (estr.startsWith(exclusion)) { - excluded = true; - break; - } - } - - if (!excluded) { - buf.append('\t'); - buf.append(estr); - buf.append(NEWLINE); - } - } - } - - return buf.toString(); - } -} diff --git a/common/src/main/java/common/net/util/Signal.java b/common/src/main/java/common/net/util/Signal.java deleted file mode 100644 index b0f041d..0000000 --- a/common/src/main/java/common/net/util/Signal.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util; - - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * A special {@link Error} which is used to signal some state or request by throwing it. - * {@link Signal} has an empty stack trace and has no cause to save the instantiation overhead. - */ -public final class Signal extends Error { - - private static final long serialVersionUID = -221145131122459977L; - - private static final ConcurrentMap map = new ConcurrentHashMap(); - - - private final UniqueName uname; - - /** - * Creates a new {@link Signal} with the specified {@code name}. - */ - - public static Signal valueOf(String name) { - return new Signal(name); - } - - private Signal(String name) { - super(name); - uname = new UniqueName(map, name); - } - - /** - * Check if the given {@link Signal} is the same as this instance. If not an {@link IllegalStateException} will - * be thrown. - */ - public void expect(Signal signal) { - if (this != signal) { - throw new IllegalStateException("unexpected signal: " + signal); - } - } - - @Override - public Throwable initCause(Throwable cause) { - return this; - } - - @Override - public Throwable fillInStackTrace() { - return this; - } - - @Override - public String toString() { - return uname.name(); - } -} diff --git a/common/src/main/java/common/net/util/ThreadDeathWatcher.java b/common/src/main/java/common/net/util/ThreadDeathWatcher.java deleted file mode 100644 index 1020596..0000000 --- a/common/src/main/java/common/net/util/ThreadDeathWatcher.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import common.net.util.concurrent.DefaultThreadFactory; -import common.net.util.internal.MpscLinkedQueue; -import common.net.util.internal.MpscLinkedQueueNode; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * Checks if a thread is alive periodically and runs a task when a thread dies. - *

- * This thread starts a daemon thread to check the state of the threads being watched and to invoke their - * associated {@link Runnable}s. When there is no thread to watch (i.e. all threads are dead), the daemon thread - * will terminate itself, and a new daemon thread will be started again when a new watch is added. - *

- */ -public final class ThreadDeathWatcher { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(ThreadDeathWatcher.class); - private static final ThreadFactory threadFactory = - new DefaultThreadFactory(ThreadDeathWatcher.class, true, Thread.MIN_PRIORITY); - - private static final Queue pendingEntries = new MpscLinkedQueue(); - private static final Watcher watcher = new Watcher(); - private static final AtomicBoolean started = new AtomicBoolean(); - private static volatile Thread watcherThread; - - /** - * Schedules the specified {@code task} to run when the specified {@code thread} dies. - * - * @param thread the {@link Thread} to watch - * @param task the {@link Runnable} to run when the {@code thread} dies - * - * @throws IllegalArgumentException if the specified {@code thread} is not alive - */ - public static void watch(Thread thread, Runnable task) { - if (thread == null) { - throw new NullPointerException("thread"); - } - if (task == null) { - throw new NullPointerException("task"); - } - if (!thread.isAlive()) { - throw new IllegalArgumentException("thread must be alive."); - } - - schedule(thread, task, true); - } - - /** - * Cancels the task scheduled via {@link #watch(Thread, Runnable)}. - */ - public static void unwatch(Thread thread, Runnable task) { - if (thread == null) { - throw new NullPointerException("thread"); - } - if (task == null) { - throw new NullPointerException("task"); - } - - schedule(thread, task, false); - } - - private static void schedule(Thread thread, Runnable task, boolean isWatch) { - pendingEntries.add(new Entry(thread, task, isWatch)); - - if (started.compareAndSet(false, true)) { - Thread watcherThread = threadFactory.newThread(watcher); - watcherThread.start(); - ThreadDeathWatcher.watcherThread = watcherThread; - } - } - - /** - * Waits until the thread of this watcher has no threads to watch and terminates itself. - * Because a new watcher thread will be started again on {@link #watch(Thread, Runnable)}, - * this operation is only useful when you want to ensure that the watcher thread is terminated - * after your application is shut down and there's no chance of calling - * {@link #watch(Thread, Runnable)} afterwards. - * - * @return {@code true} if and only if the watcher thread has been terminated - */ - public static boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { - if (unit == null) { - throw new NullPointerException("unit"); - } - - Thread watcherThread = ThreadDeathWatcher.watcherThread; - if (watcherThread != null) { - watcherThread.join(unit.toMillis(timeout)); - return !watcherThread.isAlive(); - } else { - return true; - } - } - - private ThreadDeathWatcher() { } - - private static final class Watcher implements Runnable { - - private final List watchees = new ArrayList(); - - @Override - public void run() { - for (;;) { - fetchWatchees(); - notifyWatchees(); - - // Try once again just in case notifyWatchees() triggered watch() or unwatch(). - fetchWatchees(); - notifyWatchees(); - - try { - Thread.sleep(1000); - } catch (InterruptedException ignore) { - // Ignore the interrupt; do not terminate until all tasks are run. - } - - if (watchees.isEmpty() && pendingEntries.isEmpty()) { - - // Mark the current worker thread as stopped. - // The following CAS must always success and must be uncontended, - // because only one watcher thread should be running at the same time. - boolean stopped = started.compareAndSet(true, false); - assert stopped; - - // Check if there are pending entries added by watch() while we do CAS above. - if (pendingEntries.isEmpty()) { - // A) watch() was not invoked and thus there's nothing to handle - // -> safe to terminate because there's nothing left to do - // B) a new watcher thread started and handled them all - // -> safe to terminate the new watcher thread will take care the rest - break; - } - - // There are pending entries again, added by watch() - if (!started.compareAndSet(false, true)) { - // watch() started a new watcher thread and set 'started' to true. - // -> terminate this thread so that the new watcher reads from pendingEntries exclusively. - break; - } - - // watch() added an entry, but this worker was faster to set 'started' to true. - // i.e. a new watcher thread was not started - // -> keep this thread alive to handle the newly added entries. - } - } - } - - private void fetchWatchees() { - for (;;) { - Entry e = pendingEntries.poll(); - if (e == null) { - break; - } - - if (e.isWatch) { - watchees.add(e); - } else { - watchees.remove(e); - } - } - } - - private void notifyWatchees() { - List watchees = this.watchees; - for (int i = 0; i < watchees.size();) { - Entry e = watchees.get(i); - if (!e.thread.isAlive()) { - watchees.remove(i); - try { - e.task.run(); - } catch (Throwable t) { - logger.warn("Thread death watcher task raised an exception:", t); - } - } else { - i ++; - } - } - } - } - - private static final class Entry extends MpscLinkedQueueNode { - final Thread thread; - final Runnable task; - final boolean isWatch; - - Entry(Thread thread, Runnable task, boolean isWatch) { - this.thread = thread; - this.task = task; - this.isWatch = isWatch; - } - - @Override - public Entry value() { - return this; - } - - @Override - public int hashCode() { - return thread.hashCode() ^ task.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof Entry)) { - return false; - } - - Entry that = (Entry) obj; - return thread == that.thread && task == that.task; - } - } -} diff --git a/common/src/main/java/common/net/util/UniqueName.java b/common/src/main/java/common/net/util/UniqueName.java deleted file mode 100644 index 0a20a99..0000000 --- a/common/src/main/java/common/net/util/UniqueName.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util; - -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Defines a name that must be unique in the map that is provided during construction. - */ -public class UniqueName implements Comparable { - - private static final AtomicInteger nextId = new AtomicInteger(); - - private final int id; - private final String name; - - /** - * Constructs a new {@link UniqueName} - * - * @param map the map of names to compare with - * @param name the name of this {@link UniqueName} - */ - public UniqueName(ConcurrentMap map, String name) { - if (map == null) { - throw new NullPointerException("map"); - } - if (name == null) { - throw new NullPointerException("name"); - } - - if (map.putIfAbsent(name, Boolean.TRUE) != null) { - throw new IllegalArgumentException(String.format("'%s' is already in use", name)); - } - - id = nextId.incrementAndGet(); - this.name = name; - } - - /** - * Returns this {@link UniqueName}'s name - * - * @return the name - */ - public final String name() { - return name; - } - - /** - * Returns this {@link UniqueName}'s ID - * - * @return the id - */ - public final int id() { - return id; - } - - @Override - public final int hashCode() { - return super.hashCode(); - } - - @Override - public final boolean equals(Object o) { - return super.equals(o); - } - - @Override - public int compareTo(UniqueName other) { - if (this == other) { - return 0; - } - - int returnCode = name.compareTo(other.name); - if (returnCode != 0) { - return returnCode; - } - - return ((Integer) id).compareTo(other.id); - } - - @Override - public String toString() { - return name(); - } -} diff --git a/common/src/main/java/common/net/util/concurrent/AbstractEventExecutor.java b/common/src/main/java/common/net/util/concurrent/AbstractEventExecutor.java deleted file mode 100644 index 1392ed6..0000000 --- a/common/src/main/java/common/net/util/concurrent/AbstractEventExecutor.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.concurrent.AbstractExecutorService; -import java.util.concurrent.Callable; -import java.util.concurrent.RunnableFuture; -import java.util.concurrent.TimeUnit; - -/** - * Abstract base class for {@link EventExecutor} implementations. - */ -public abstract class AbstractEventExecutor extends AbstractExecutorService implements EventExecutor { - - @Override - public EventExecutor next() { - return this; - } - - @Override - public boolean inEventLoop() { - return inEventLoop(Thread.currentThread()); - } - - @Override - public Iterator iterator() { - return new EventExecutorIterator(); - } - - @Override - public Future shutdownGracefully() { - return shutdownGracefully(2, 15, TimeUnit.SECONDS); - } - - /** - * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. - */ - @Override - @Deprecated - public abstract void shutdown(); - - /** - * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. - */ - @Override - @Deprecated - public List shutdownNow() { - shutdown(); - return Collections.emptyList(); - } - - @Override - public Promise newPromise() { - return new DefaultPromise(this); - } - - @Override - public ProgressivePromise newProgressivePromise() { - return new DefaultProgressivePromise(this); - } - - @Override - public Future newSucceededFuture(V result) { - return new SucceededFuture(this, result); - } - - @Override - public Future newFailedFuture(Throwable cause) { - return new FailedFuture(this, cause); - } - - @Override - public Future submit(Runnable task) { - return (Future) super.submit(task); - } - - @Override - public Future submit(Runnable task, T result) { - return (Future) super.submit(task, result); - } - - @Override - public Future submit(Callable task) { - return (Future) super.submit(task); - } - - @Override - protected final RunnableFuture newTaskFor(Runnable runnable, T value) { - return new PromiseTask(this, runnable, value); - } - - @Override - protected final RunnableFuture newTaskFor(Callable callable) { - return new PromiseTask(this, callable); - } - - @Override - public ScheduledFuture schedule(Runnable command, long delay, - TimeUnit unit) { - throw new UnsupportedOperationException(); - } - - @Override - public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { - throw new UnsupportedOperationException(); - } - - @Override - public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { - throw new UnsupportedOperationException(); - } - - @Override - public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { - throw new UnsupportedOperationException(); - } - - private final class EventExecutorIterator implements Iterator { - private boolean nextCalled; - - @Override - public boolean hasNext() { - return !nextCalled; - } - - @Override - public EventExecutor next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - nextCalled = true; - return AbstractEventExecutor.this; - } - - @Override - public void remove() { - throw new UnsupportedOperationException("read-only"); - } - } -} diff --git a/common/src/main/java/common/net/util/concurrent/AbstractEventExecutorGroup.java b/common/src/main/java/common/net/util/concurrent/AbstractEventExecutorGroup.java deleted file mode 100644 index 8c1b768..0000000 --- a/common/src/main/java/common/net/util/concurrent/AbstractEventExecutorGroup.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - - -/** - * Abstract base class for {@link EventExecutorGroup} implementations. - */ -public abstract class AbstractEventExecutorGroup implements EventExecutorGroup { - - @Override - public Future submit(Runnable task) { - return next().submit(task); - } - - @Override - public Future submit(Runnable task, T result) { - return next().submit(task, result); - } - - @Override - public Future submit(Callable task) { - return next().submit(task); - } - - @Override - public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { - return next().schedule(command, delay, unit); - } - - @Override - public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { - return next().schedule(callable, delay, unit); - } - - @Override - public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { - return next().scheduleAtFixedRate(command, initialDelay, period, unit); - } - - @Override - public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { - return next().scheduleWithFixedDelay(command, initialDelay, delay, unit); - } - - @Override - public Future shutdownGracefully() { - return shutdownGracefully(2, 15, TimeUnit.SECONDS); - } - - /** - * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. - */ - @Override - @Deprecated - public abstract void shutdown(); - - /** - * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. - */ - @Override - @Deprecated - public List shutdownNow() { - shutdown(); - return Collections.emptyList(); - } - - @Override - public List> invokeAll(Collection> tasks) - throws InterruptedException { - return next().invokeAll(tasks); - } - - @Override - public List> invokeAll( - Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { - return next().invokeAll(tasks, timeout, unit); - } - - @Override - public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { - return next().invokeAny(tasks); - } - - @Override - public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - return next().invokeAny(tasks, timeout, unit); - } - - @Override - public void execute(Runnable command) { - next().execute(command); - } -} diff --git a/common/src/main/java/common/net/util/concurrent/AbstractFuture.java b/common/src/main/java/common/net/util/concurrent/AbstractFuture.java deleted file mode 100644 index e288643..0000000 --- a/common/src/main/java/common/net/util/concurrent/AbstractFuture.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * Abstract {@link Future} implementation which does not allow for cancellation. - * - * @param - */ -public abstract class AbstractFuture implements Future { - - @Override - public V get() throws InterruptedException, ExecutionException { - await(); - - Throwable cause = cause(); - if (cause == null) { - return getNow(); - } - throw new ExecutionException(cause); - } - - @Override - public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { - if (await(timeout, unit)) { - Throwable cause = cause(); - if (cause == null) { - return getNow(); - } - throw new ExecutionException(cause); - } - throw new TimeoutException(); - } -} diff --git a/common/src/main/java/common/net/util/concurrent/BlockingOperationException.java b/common/src/main/java/common/net/util/concurrent/BlockingOperationException.java deleted file mode 100644 index 725b524..0000000 --- a/common/src/main/java/common/net/util/concurrent/BlockingOperationException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -/** - * An {@link IllegalStateException} which is raised when a user performed a blocking operation - * when the user is in an event loop thread. If a blocking operation is performed in an event loop - * thread, the blocking operation will most likely enter a dead lock state, hence throwing this - * exception. - */ -public class BlockingOperationException extends IllegalStateException { - - private static final long serialVersionUID = 2462223247762460301L; - - public BlockingOperationException() { } - - public BlockingOperationException(String s) { - super(s); - } - - public BlockingOperationException(Throwable cause) { - super(cause); - } - - public BlockingOperationException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/common/src/main/java/common/net/util/concurrent/CompleteFuture.java b/common/src/main/java/common/net/util/concurrent/CompleteFuture.java deleted file mode 100644 index 2761a6e..0000000 --- a/common/src/main/java/common/net/util/concurrent/CompleteFuture.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.concurrent; - -import java.util.concurrent.TimeUnit; - -/** - * A skeletal {@link Future} implementation which represents a {@link Future} which has been completed already. - */ -public abstract class CompleteFuture extends AbstractFuture { - - private final EventExecutor executor; - - /** - * Creates a new instance. - * - * @param executor the {@link EventExecutor} associated with this future - */ - protected CompleteFuture(EventExecutor executor) { - this.executor = executor; - } - - /** - * Return the {@link EventExecutor} which is used by this {@link CompleteFuture}. - */ - protected EventExecutor executor() { - return executor; - } - - @Override - public Future addListener(GenericFutureListener> listener) { - if (listener == null) { - throw new NullPointerException("listener"); - } - DefaultPromise.notifyListener(executor(), this, listener); - return this; - } - - @Override - public Future addListeners(GenericFutureListener>... listeners) { - if (listeners == null) { - throw new NullPointerException("listeners"); - } - for (GenericFutureListener> l: listeners) { - if (l == null) { - break; - } - DefaultPromise.notifyListener(executor(), this, l); - } - return this; - } - - @Override - public Future removeListener(GenericFutureListener> listener) { - // NOOP - return this; - } - - @Override - public Future removeListeners(GenericFutureListener>... listeners) { - // NOOP - return this; - } - - @Override - public Future await() throws InterruptedException { - if (Thread.interrupted()) { - throw new InterruptedException(); - } - return this; - } - - @Override - public boolean await(long timeout, TimeUnit unit) throws InterruptedException { - if (Thread.interrupted()) { - throw new InterruptedException(); - } - return true; - } - - @Override - public Future sync() throws InterruptedException { - return this; - } - - @Override - public Future syncUninterruptibly() { - return this; - } - - @Override - public boolean await(long timeoutMillis) throws InterruptedException { - if (Thread.interrupted()) { - throw new InterruptedException(); - } - return true; - } - - @Override - public Future awaitUninterruptibly() { - return this; - } - - @Override - public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { - return true; - } - - @Override - public boolean awaitUninterruptibly(long timeoutMillis) { - return true; - } - - @Override - public boolean isDone() { - return true; - } - - @Override - public boolean isCancellable() { - return false; - } - - @Override - public boolean isCancelled() { - return false; - } - - @Override - public boolean cancel(boolean mayInterruptIfRunning) { - return false; - } -} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultEventExecutor.java b/common/src/main/java/common/net/util/concurrent/DefaultEventExecutor.java deleted file mode 100644 index 7f7c611..0000000 --- a/common/src/main/java/common/net/util/concurrent/DefaultEventExecutor.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.concurrent.ThreadFactory; - -/** - * Default {@link SingleThreadEventExecutor} implementation which just execute all submitted task in a - * serial fashion - * - */ -final class DefaultEventExecutor extends SingleThreadEventExecutor { - - DefaultEventExecutor(DefaultEventExecutorGroup parent, ThreadFactory threadFactory) { - super(parent, threadFactory, true); - } - - @Override - protected void run() { - for (;;) { - Runnable task = takeTask(); - if (task != null) { - task.run(); - updateLastExecutionTime(); - } - - if (confirmShutdown()) { - break; - } - } - } -} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultEventExecutorGroup.java b/common/src/main/java/common/net/util/concurrent/DefaultEventExecutorGroup.java deleted file mode 100644 index 10c165a..0000000 --- a/common/src/main/java/common/net/util/concurrent/DefaultEventExecutorGroup.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.concurrent.ThreadFactory; - -/** - * Default implementation of {@link MultithreadEventExecutorGroup} which will use {@link DefaultEventExecutor} instances - * to handle the tasks. - */ -public class DefaultEventExecutorGroup extends MultithreadEventExecutorGroup { - - /** - * @see {@link #DefaultEventExecutorGroup(int, ThreadFactory)} - */ - public DefaultEventExecutorGroup(int nThreads) { - this(nThreads, null); - } - - /** - * Create a new instance. - * - * @param nThreads the number of threads that will be used by this instance. - * @param threadFactory the ThreadFactory to use, or {@code null} if the default should be used. - */ - public DefaultEventExecutorGroup(int nThreads, ThreadFactory threadFactory) { - super(nThreads, threadFactory); - } - - @Override - protected EventExecutor newChild( - ThreadFactory threadFactory, Object... args) throws Exception { - return new DefaultEventExecutor(this, threadFactory); - } -} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultFutureListeners.java b/common/src/main/java/common/net/util/concurrent/DefaultFutureListeners.java deleted file mode 100644 index 37a830e..0000000 --- a/common/src/main/java/common/net/util/concurrent/DefaultFutureListeners.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.Arrays; - -final class DefaultFutureListeners { - - private GenericFutureListener>[] listeners; - private int size; - private int progressiveSize; // the number of progressive listeners - - - DefaultFutureListeners( - GenericFutureListener> first, GenericFutureListener> second) { - listeners = new GenericFutureListener[2]; - listeners[0] = first; - listeners[1] = second; - size = 2; - if (first instanceof GenericProgressiveFutureListener) { - progressiveSize ++; - } - if (second instanceof GenericProgressiveFutureListener) { - progressiveSize ++; - } - } - - public void add(GenericFutureListener> l) { - GenericFutureListener>[] listeners = this.listeners; - final int size = this.size; - if (size == listeners.length) { - this.listeners = listeners = Arrays.copyOf(listeners, size << 1); - } - listeners[size] = l; - this.size = size + 1; - - if (l instanceof GenericProgressiveFutureListener) { - progressiveSize ++; - } - } - - public void remove(GenericFutureListener> l) { - final GenericFutureListener>[] listeners = this.listeners; - int size = this.size; - for (int i = 0; i < size; i ++) { - if (listeners[i] == l) { - int listenersToMove = size - i - 1; - if (listenersToMove > 0) { - System.arraycopy(listeners, i + 1, listeners, i, listenersToMove); - } - listeners[-- size] = null; - this.size = size; - - if (l instanceof GenericProgressiveFutureListener) { - progressiveSize --; - } - return; - } - } - } - - public GenericFutureListener>[] listeners() { - return listeners; - } - - public int size() { - return size; - } - - public int progressiveSize() { - return progressiveSize; - } -} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultProgressivePromise.java b/common/src/main/java/common/net/util/concurrent/DefaultProgressivePromise.java deleted file mode 100644 index 57d908a..0000000 --- a/common/src/main/java/common/net/util/concurrent/DefaultProgressivePromise.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.concurrent; - -public class DefaultProgressivePromise extends DefaultPromise implements ProgressivePromise { - - /** - * Creates a new instance. - * - * It is preferable to use {@link EventExecutor#newProgressivePromise()} to create a new progressive promise - * - * @param executor - * the {@link EventExecutor} which is used to notify the promise when it progresses or it is complete - */ - public DefaultProgressivePromise(EventExecutor executor) { - super(executor); - } - - protected DefaultProgressivePromise() { /* only for subclasses */ } - - @Override - public ProgressivePromise setProgress(long progress, long total) { - if (total < 0) { - // total unknown - total = -1; // normalize - if (progress < 0) { - throw new IllegalArgumentException("progress: " + progress + " (expected: >= 0)"); - } - } else if (progress < 0 || progress > total) { - throw new IllegalArgumentException( - "progress: " + progress + " (expected: 0 <= progress <= total (" + total + "))"); - } - - if (isDone()) { - throw new IllegalStateException("complete already"); - } - - notifyProgressiveListeners(progress, total); - return this; - } - - @Override - public boolean tryProgress(long progress, long total) { - if (total < 0) { - total = -1; - if (progress < 0 || isDone()) { - return false; - } - } else if (progress < 0 || progress > total || isDone()) { - return false; - } - - notifyProgressiveListeners(progress, total); - return true; - } - - @Override - public ProgressivePromise addListener(GenericFutureListener> listener) { - super.addListener(listener); - return this; - } - - @Override - public ProgressivePromise addListeners(GenericFutureListener>... listeners) { - super.addListeners(listeners); - return this; - } - - @Override - public ProgressivePromise removeListener(GenericFutureListener> listener) { - super.removeListener(listener); - return this; - } - - @Override - public ProgressivePromise removeListeners(GenericFutureListener>... listeners) { - super.removeListeners(listeners); - return this; - } - - @Override - public ProgressivePromise sync() throws InterruptedException { - super.sync(); - return this; - } - - @Override - public ProgressivePromise syncUninterruptibly() { - super.syncUninterruptibly(); - return this; - } - - @Override - public ProgressivePromise await() throws InterruptedException { - super.await(); - return this; - } - - @Override - public ProgressivePromise awaitUninterruptibly() { - super.awaitUninterruptibly(); - return this; - } - - @Override - public ProgressivePromise setSuccess(V result) { - super.setSuccess(result); - return this; - } - - @Override - public ProgressivePromise setFailure(Throwable cause) { - super.setFailure(cause); - return this; - } -} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultPromise.java b/common/src/main/java/common/net/util/concurrent/DefaultPromise.java deleted file mode 100644 index f7cad80..0000000 --- a/common/src/main/java/common/net/util/concurrent/DefaultPromise.java +++ /dev/null @@ -1,876 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import static java.util.concurrent.TimeUnit.MILLISECONDS; - -import java.util.ArrayDeque; -import java.util.concurrent.CancellationException; -import java.util.concurrent.TimeUnit; - -import common.net.util.Signal; -import common.net.util.internal.EmptyArrays; -import common.net.util.internal.InternalThreadLocalMap; -import common.net.util.internal.StringUtil; -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; -import common.util.Util; - -public class DefaultPromise extends AbstractFuture implements Promise { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultPromise.class); - private static final InternalLogger rejectedExecutionLogger = - InternalLoggerFactory.getInstance(DefaultPromise.class.getName() + ".rejectedExecution"); - - private static final int MAX_LISTENER_STACK_DEPTH = 8; - private static final Signal SUCCESS = Signal.valueOf(DefaultPromise.class.getName() + ".SUCCESS"); - private static final Signal UNCANCELLABLE = Signal.valueOf(DefaultPromise.class.getName() + ".UNCANCELLABLE"); - private static final CauseHolder CANCELLATION_CAUSE_HOLDER = new CauseHolder(new CancellationException()); - - static { - CANCELLATION_CAUSE_HOLDER.cause.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); - } - - private final EventExecutor executor; - - private volatile Object result; - - /** - * One or more listeners. Can be a {@link GenericFutureListener} or a {@link DefaultFutureListeners}. - * If {@code null}, it means either 1) no listeners were added yet or 2) all listeners were notified. - */ - private Object listeners; - - /** - * The list of the listeners that were added after the promise is done. Initially {@code null} and lazily - * instantiated when the late listener is scheduled to be notified later. Also used as a cached {@link Runnable} - * that performs the notification of the listeners it contains. - */ - private LateListeners lateListeners; - - private short waiters; - - /** - * Creates a new instance. - * - * It is preferable to use {@link EventExecutor#newPromise()} to create a new promise - * - * @param executor - * the {@link EventExecutor} which is used to notify the promise once it is complete - */ - public DefaultPromise(EventExecutor executor) { - if (executor == null) { - throw new NullPointerException("executor"); - } - this.executor = executor; - } - - protected DefaultPromise() { - // only for subclasses - executor = null; - } - - protected EventExecutor executor() { - return executor; - } - - @Override - public boolean isCancelled() { - return isCancelled0(result); - } - - private static boolean isCancelled0(Object result) { - return result instanceof CauseHolder && ((CauseHolder) result).cause instanceof CancellationException; - } - - @Override - public boolean isCancellable() { - return result == null; - } - - @Override - public boolean isDone() { - return isDone0(result); - } - - private static boolean isDone0(Object result) { - return result != null && result != UNCANCELLABLE; - } - - @Override - public boolean isSuccess() { - Object result = this.result; - if (result == null || result == UNCANCELLABLE) { - return false; - } - return !(result instanceof CauseHolder); - } - - @Override - public Throwable cause() { - Object result = this.result; - if (result instanceof CauseHolder) { - return ((CauseHolder) result).cause; - } - return null; - } - - @Override - public Promise addListener(GenericFutureListener> listener) { - if (listener == null) { - throw new NullPointerException("listener"); - } - - if (isDone()) { - notifyLateListener(listener); - return this; - } - - synchronized (this) { - if (!isDone()) { - if (listeners == null) { - listeners = listener; - } else { - if (listeners instanceof DefaultFutureListeners) { - ((DefaultFutureListeners) listeners).add(listener); - } else { - final GenericFutureListener> firstListener = - (GenericFutureListener>) listeners; - listeners = new DefaultFutureListeners(firstListener, listener); - } - } - return this; - } - } - - notifyLateListener(listener); - return this; - } - - @Override - public Promise addListeners(GenericFutureListener>... listeners) { - if (listeners == null) { - throw new NullPointerException("listeners"); - } - - for (GenericFutureListener> l: listeners) { - if (l == null) { - break; - } - addListener(l); - } - return this; - } - - @Override - public Promise removeListener(GenericFutureListener> listener) { - if (listener == null) { - throw new NullPointerException("listener"); - } - - if (isDone()) { - return this; - } - - synchronized (this) { - if (!isDone()) { - if (listeners instanceof DefaultFutureListeners) { - ((DefaultFutureListeners) listeners).remove(listener); - } else if (listeners == listener) { - listeners = null; - } - } - } - - return this; - } - - @Override - public Promise removeListeners(GenericFutureListener>... listeners) { - if (listeners == null) { - throw new NullPointerException("listeners"); - } - - for (GenericFutureListener> l: listeners) { - if (l == null) { - break; - } - removeListener(l); - } - return this; - } - - @Override - public Promise sync() throws InterruptedException { - await(); - rethrowIfFailed(); - return this; - } - - @Override - public Promise syncUninterruptibly() { - awaitUninterruptibly(); - rethrowIfFailed(); - return this; - } - - private void rethrowIfFailed() { - Throwable cause = cause(); - if (cause == null) { - return; - } - - Util.throwUnchecked(cause); - } - - @Override - public Promise await() throws InterruptedException { - if (isDone()) { - return this; - } - - if (Thread.interrupted()) { - throw new InterruptedException(toString()); - } - - synchronized (this) { - while (!isDone()) { - checkDeadLock(); - incWaiters(); - try { - wait(); - } finally { - decWaiters(); - } - } - } - return this; - } - - @Override - public boolean await(long timeout, TimeUnit unit) - throws InterruptedException { - return await0(unit.toNanos(timeout), true); - } - - @Override - public boolean await(long timeoutMillis) throws InterruptedException { - return await0(MILLISECONDS.toNanos(timeoutMillis), true); - } - - @Override - public Promise awaitUninterruptibly() { - if (isDone()) { - return this; - } - - boolean interrupted = false; - synchronized (this) { - while (!isDone()) { - checkDeadLock(); - incWaiters(); - try { - wait(); - } catch (InterruptedException e) { - // Interrupted while waiting. - interrupted = true; - } finally { - decWaiters(); - } - } - } - - if (interrupted) { - Thread.currentThread().interrupt(); - } - - return this; - } - - @Override - public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { - try { - return await0(unit.toNanos(timeout), false); - } catch (InterruptedException e) { - // Should not be raised at all. - throw new InternalError(); - } - } - - @Override - public boolean awaitUninterruptibly(long timeoutMillis) { - try { - return await0(MILLISECONDS.toNanos(timeoutMillis), false); - } catch (InterruptedException e) { - // Should not be raised at all. - throw new InternalError(); - } - } - - private boolean await0(long timeoutNanos, boolean interruptable) throws InterruptedException { - if (isDone()) { - return true; - } - - if (timeoutNanos <= 0) { - return isDone(); - } - - if (interruptable && Thread.interrupted()) { - throw new InterruptedException(toString()); - } - - long startTime = System.nanoTime(); - long waitTime = timeoutNanos; - boolean interrupted = false; - - try { - synchronized (this) { - if (isDone()) { - return true; - } - - if (waitTime <= 0) { - return isDone(); - } - - checkDeadLock(); - incWaiters(); - try { - for (;;) { - try { - wait(waitTime / 1000000, (int) (waitTime % 1000000)); - } catch (InterruptedException e) { - if (interruptable) { - throw e; - } else { - interrupted = true; - } - } - - if (isDone()) { - return true; - } else { - waitTime = timeoutNanos - (System.nanoTime() - startTime); - if (waitTime <= 0) { - return isDone(); - } - } - } - } finally { - decWaiters(); - } - } - } finally { - if (interrupted) { - Thread.currentThread().interrupt(); - } - } - } - - /** - * Do deadlock checks - */ - protected void checkDeadLock() { - EventExecutor e = executor(); - if (e != null && e.inEventLoop()) { - throw new BlockingOperationException(toString()); - } - } - - @Override - public Promise setSuccess(V result) { - if (setSuccess0(result)) { - notifyListeners(); - return this; - } - throw new IllegalStateException("complete already: " + this); - } - - @Override - public boolean trySuccess(V result) { - if (setSuccess0(result)) { - notifyListeners(); - return true; - } - return false; - } - - @Override - public Promise setFailure(Throwable cause) { - if (setFailure0(cause)) { - notifyListeners(); - return this; - } - throw new IllegalStateException("complete already: " + this, cause); - } - - @Override - public boolean tryFailure(Throwable cause) { - if (setFailure0(cause)) { - notifyListeners(); - return true; - } - return false; - } - - @Override - public boolean cancel(boolean mayInterruptIfRunning) { - Object result = this.result; - if (isDone0(result) || result == UNCANCELLABLE) { - return false; - } - - synchronized (this) { - // Allow only once. - result = this.result; - if (isDone0(result) || result == UNCANCELLABLE) { - return false; - } - - this.result = CANCELLATION_CAUSE_HOLDER; - if (hasWaiters()) { - notifyAll(); - } - } - - notifyListeners(); - return true; - } - - @Override - public boolean setUncancellable() { - Object result = this.result; - if (isDone0(result)) { - return !isCancelled0(result); - } - - synchronized (this) { - // Allow only once. - result = this.result; - if (isDone0(result)) { - return !isCancelled0(result); - } - - this.result = UNCANCELLABLE; - } - return true; - } - - private boolean setFailure0(Throwable cause) { - if (cause == null) { - throw new NullPointerException("cause"); - } - - if (isDone()) { - return false; - } - - synchronized (this) { - // Allow only once. - if (isDone()) { - return false; - } - - result = new CauseHolder(cause); - if (hasWaiters()) { - notifyAll(); - } - } - return true; - } - - private boolean setSuccess0(V result) { - if (isDone()) { - return false; - } - - synchronized (this) { - // Allow only once. - if (isDone()) { - return false; - } - if (result == null) { - this.result = SUCCESS; - } else { - this.result = result; - } - if (hasWaiters()) { - notifyAll(); - } - } - return true; - } - - @Override - - public V getNow() { - Object result = this.result; - if (result instanceof CauseHolder || result == SUCCESS) { - return null; - } - return (V) result; - } - - private boolean hasWaiters() { - return waiters > 0; - } - - private void incWaiters() { - if (waiters == Short.MAX_VALUE) { - throw new IllegalStateException("too many waiters: " + this); - } - waiters ++; - } - - private void decWaiters() { - waiters --; - } - - private void notifyListeners() { - // This method doesn't need synchronization because: - // 1) This method is always called after synchronized (this) block. - // Hence any listener list modification happens-before this method. - // 2) This method is called only when 'done' is true. Once 'done' - // becomes true, the listener list is never modified - see add/removeListener() - - Object listeners = this.listeners; - if (listeners == null) { - return; - } - - EventExecutor executor = executor(); - if (executor.inEventLoop()) { - final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get(); - final int stackDepth = threadLocals.futureListenerStackDepth(); - if (stackDepth < MAX_LISTENER_STACK_DEPTH) { - threadLocals.setFutureListenerStackDepth(stackDepth + 1); - try { - if (listeners instanceof DefaultFutureListeners) { - notifyListeners0(this, (DefaultFutureListeners) listeners); - } else { - final GenericFutureListener> l = - (GenericFutureListener>) listeners; - notifyListener0(this, l); - } - } finally { - this.listeners = null; - threadLocals.setFutureListenerStackDepth(stackDepth); - } - return; - } - } - - if (listeners instanceof DefaultFutureListeners) { - final DefaultFutureListeners dfl = (DefaultFutureListeners) listeners; - execute(executor, new Runnable() { - @Override - public void run() { - notifyListeners0(DefaultPromise.this, dfl); - DefaultPromise.this.listeners = null; - } - }); - } else { - final GenericFutureListener> l = - (GenericFutureListener>) listeners; - execute(executor, new Runnable() { - @Override - public void run() { - notifyListener0(DefaultPromise.this, l); - DefaultPromise.this.listeners = null; - } - }); - } - } - - private static void notifyListeners0(Future future, DefaultFutureListeners listeners) { - final GenericFutureListener[] a = listeners.listeners(); - final int size = listeners.size(); - for (int i = 0; i < size; i ++) { - notifyListener0(future, a[i]); - } - } - - /** - * Notifies the specified listener which were added after this promise is already done. - * This method ensures that the specified listener is not notified until {@link #listeners} becomes {@code null} - * to avoid the case where the late listeners are notified even before the early listeners are notified. - */ - private void notifyLateListener(final GenericFutureListener l) { - final EventExecutor executor = executor(); - if (executor.inEventLoop()) { - if (listeners == null && lateListeners == null) { - final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get(); - final int stackDepth = threadLocals.futureListenerStackDepth(); - if (stackDepth < MAX_LISTENER_STACK_DEPTH) { - threadLocals.setFutureListenerStackDepth(stackDepth + 1); - try { - notifyListener0(this, l); - } finally { - threadLocals.setFutureListenerStackDepth(stackDepth); - } - return; - } - } else { - LateListeners lateListeners = this.lateListeners; - if (lateListeners == null) { - this.lateListeners = lateListeners = new LateListeners(); - } - lateListeners.add(l); - execute(executor, lateListeners); - return; - } - } - - // Add the late listener to lateListeners in the executor thread for thread safety. - // We could just make LateListeners extend ConcurrentLinkedQueue, but it's an overkill considering - // that most asynchronous applications won't execute this code path. - execute(executor, new LateListenerNotifier(l)); - } - - protected static void notifyListener( - final EventExecutor eventExecutor, final Future future, final GenericFutureListener l) { - - if (eventExecutor.inEventLoop()) { - final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get(); - final int stackDepth = threadLocals.futureListenerStackDepth(); - if (stackDepth < MAX_LISTENER_STACK_DEPTH) { - threadLocals.setFutureListenerStackDepth(stackDepth + 1); - try { - notifyListener0(future, l); - } finally { - threadLocals.setFutureListenerStackDepth(stackDepth); - } - return; - } - } - - execute(eventExecutor, new Runnable() { - @Override - public void run() { - notifyListener0(future, l); - } - }); - } - - private static void execute(EventExecutor executor, Runnable task) { - try { - executor.execute(task); - } catch (Throwable t) { - rejectedExecutionLogger.error("Failed to submit a listener notification task. Event loop shut down?", t); - } - } - - - static void notifyListener0(Future future, GenericFutureListener l) { - try { - l.operationComplete(future); - } catch (Throwable t) { - if (logger.isWarnEnabled()) { - logger.warn("An exception was thrown by " + l.getClass().getName() + ".operationComplete()", t); - } - } - } - - /** - * Returns a {@link GenericProgressiveFutureListener}, an array of {@link GenericProgressiveFutureListener}, or - * {@code null}. - */ - private synchronized Object progressiveListeners() { - Object listeners = this.listeners; - if (listeners == null) { - // No listeners added - return null; - } - - if (listeners instanceof DefaultFutureListeners) { - // Copy DefaultFutureListeners into an array of listeners. - DefaultFutureListeners dfl = (DefaultFutureListeners) listeners; - int progressiveSize = dfl.progressiveSize(); - switch (progressiveSize) { - case 0: - return null; - case 1: - for (GenericFutureListener l: dfl.listeners()) { - if (l instanceof GenericProgressiveFutureListener) { - return l; - } - } - return null; - } - - GenericFutureListener[] array = dfl.listeners(); - GenericProgressiveFutureListener[] copy = new GenericProgressiveFutureListener[progressiveSize]; - for (int i = 0, j = 0; j < progressiveSize; i ++) { - GenericFutureListener l = array[i]; - if (l instanceof GenericProgressiveFutureListener) { - copy[j ++] = (GenericProgressiveFutureListener) l; - } - } - - return copy; - } else if (listeners instanceof GenericProgressiveFutureListener) { - return listeners; - } else { - // Only one listener was added and it's not a progressive listener. - return null; - } - } - - - void notifyProgressiveListeners(final long progress, final long total) { - final Object listeners = progressiveListeners(); - if (listeners == null) { - return; - } - - final ProgressiveFuture self = (ProgressiveFuture) this; - - EventExecutor executor = executor(); - if (executor.inEventLoop()) { - if (listeners instanceof GenericProgressiveFutureListener[]) { - notifyProgressiveListeners0( - self, (GenericProgressiveFutureListener[]) listeners, progress, total); - } else { - notifyProgressiveListener0( - self, (GenericProgressiveFutureListener>) listeners, progress, total); - } - } else { - if (listeners instanceof GenericProgressiveFutureListener[]) { - final GenericProgressiveFutureListener[] array = - (GenericProgressiveFutureListener[]) listeners; - execute(executor, new Runnable() { - @Override - public void run() { - notifyProgressiveListeners0(self, array, progress, total); - } - }); - } else { - final GenericProgressiveFutureListener> l = - (GenericProgressiveFutureListener>) listeners; - execute(executor, new Runnable() { - @Override - public void run() { - notifyProgressiveListener0(self, l, progress, total); - } - }); - } - } - } - - private static void notifyProgressiveListeners0( - ProgressiveFuture future, GenericProgressiveFutureListener[] listeners, long progress, long total) { - for (GenericProgressiveFutureListener l: listeners) { - if (l == null) { - break; - } - notifyProgressiveListener0(future, l, progress, total); - } - } - - - private static void notifyProgressiveListener0( - ProgressiveFuture future, GenericProgressiveFutureListener l, long progress, long total) { - try { - l.operationProgressed(future, progress, total); - } catch (Throwable t) { - if (logger.isWarnEnabled()) { - logger.warn("An exception was thrown by " + l.getClass().getName() + ".operationProgressed()", t); - } - } - } - - private static final class CauseHolder { - final Throwable cause; - CauseHolder(Throwable cause) { - this.cause = cause; - } - } - - @Override - public String toString() { - return toStringBuilder().toString(); - } - - protected StringBuilder toStringBuilder() { - StringBuilder buf = new StringBuilder(64); - buf.append(StringUtil.simpleClassName(this)); - buf.append('@'); - buf.append(Integer.toHexString(hashCode())); - - Object result = this.result; - if (result == SUCCESS) { - buf.append("(success)"); - } else if (result == UNCANCELLABLE) { - buf.append("(uncancellable)"); - } else if (result instanceof CauseHolder) { - buf.append("(failure("); - buf.append(((CauseHolder) result).cause); - buf.append(')'); - } else { - buf.append("(incomplete)"); - } - return buf; - } - - private final class LateListeners extends ArrayDeque> implements Runnable { - - private static final long serialVersionUID = -687137418080392244L; - - LateListeners() { - super(2); - } - - @Override - public void run() { - if (listeners == null) { - for (;;) { - GenericFutureListener l = poll(); - if (l == null) { - break; - } - notifyListener0(DefaultPromise.this, l); - } - } else { - // Reschedule until the initial notification is done to avoid the race condition - // where the notification is made in an incorrect order. - execute(executor(), this); - } - } - } - - private final class LateListenerNotifier implements Runnable { - private GenericFutureListener l; - - LateListenerNotifier(GenericFutureListener l) { - this.l = l; - } - - @Override - public void run() { - LateListeners lateListeners = DefaultPromise.this.lateListeners; - if (l != null) { - if (lateListeners == null) { - DefaultPromise.this.lateListeners = lateListeners = new LateListeners(); - } - lateListeners.add(l); - l = null; - } - - lateListeners.run(); - } - } -} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultThreadFactory.java b/common/src/main/java/common/net/util/concurrent/DefaultThreadFactory.java deleted file mode 100644 index 8dc939d..0000000 --- a/common/src/main/java/common/net/util/concurrent/DefaultThreadFactory.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.concurrent; - -import java.util.Locale; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; - -import common.net.util.internal.StringUtil; - -/** - * A {@link ThreadFactory} implementation with a simple naming rule. - */ -public class DefaultThreadFactory implements ThreadFactory { - - private static final AtomicInteger poolId = new AtomicInteger(); - - private final AtomicInteger nextId = new AtomicInteger(); - private final String prefix; - private final boolean daemon; - private final int priority; - - public DefaultThreadFactory(Class poolType) { - this(poolType, false, Thread.NORM_PRIORITY); - } - - public DefaultThreadFactory(String poolName) { - this(poolName, false, Thread.NORM_PRIORITY); - } - - public DefaultThreadFactory(Class poolType, boolean daemon) { - this(poolType, daemon, Thread.NORM_PRIORITY); - } - - public DefaultThreadFactory(String poolName, boolean daemon) { - this(poolName, daemon, Thread.NORM_PRIORITY); - } - - public DefaultThreadFactory(Class poolType, int priority) { - this(poolType, false, priority); - } - - public DefaultThreadFactory(String poolName, int priority) { - this(poolName, false, priority); - } - - public DefaultThreadFactory(Class poolType, boolean daemon, int priority) { - this(toPoolName(poolType), daemon, priority); - } - - private static String toPoolName(Class poolType) { - if (poolType == null) { - throw new NullPointerException("poolType"); - } - - String poolName = StringUtil.simpleClassName(poolType); - switch (poolName.length()) { - case 0: - return "unknown"; - case 1: - return poolName.toLowerCase(Locale.US); - default: - if (Character.isUpperCase(poolName.charAt(0)) && Character.isLowerCase(poolName.charAt(1))) { - return Character.toLowerCase(poolName.charAt(0)) + poolName.substring(1); - } else { - return poolName; - } - } - } - - public DefaultThreadFactory(String poolName, boolean daemon, int priority) { - if (poolName == null) { - throw new NullPointerException("poolName"); - } - if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) { - throw new IllegalArgumentException( - "priority: " + priority + " (expected: Thread.MIN_PRIORITY <= priority <= Thread.MAX_PRIORITY)"); - } - - prefix = poolName + '-' + poolId.incrementAndGet() + '-'; - this.daemon = daemon; - this.priority = priority; - } - - @Override - public Thread newThread(Runnable r) { - Thread t = newThread(new DefaultRunnableDecorator(r), prefix + nextId.incrementAndGet()); - try { - if (t.isDaemon()) { - if (!daemon) { - t.setDaemon(false); - } - } else { - if (daemon) { - t.setDaemon(true); - } - } - - if (t.getPriority() != priority) { - t.setPriority(priority); - } - } catch (Exception ignored) { - // Doesn't matter even if failed to set. - } - return t; - } - - protected Thread newThread(Runnable r, String name) { - return new FastThreadLocalThread(r, name); - } - - private static final class DefaultRunnableDecorator implements Runnable { - - private final Runnable r; - - DefaultRunnableDecorator(Runnable r) { - this.r = r; - } - - @Override - public void run() { - try { - r.run(); - } finally { - FastThreadLocal.removeAll(); - } - } - } -} diff --git a/common/src/main/java/common/net/util/concurrent/EventExecutor.java b/common/src/main/java/common/net/util/concurrent/EventExecutor.java deleted file mode 100644 index e145548..0000000 --- a/common/src/main/java/common/net/util/concurrent/EventExecutor.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -/** - * The {@link EventExecutor} is a special {@link EventExecutorGroup} which comes - * with some handy methods to see if a {@link Thread} is executed in a event loop. - * Beside this it also extends the {@link EventExecutorGroup} to allow a generic way to - * access methods. - * - */ -public interface EventExecutor extends EventExecutorGroup { - - /** - * Returns a reference to itself. - */ - @Override - EventExecutor next(); - - /** - * Return the {@link EventExecutorGroup} which is the parent of this {@link EventExecutor}, - */ - EventExecutorGroup parent(); - - /** - * Calls {@link #inEventLoop(Thread)} with {@link Thread#currentThread()} as argument - */ - boolean inEventLoop(); - - /** - * Return {@code true} if the given {@link Thread} is executed in the event loop, - * {@code false} otherwise. - */ - boolean inEventLoop(Thread thread); - - /** - * Return a new {@link Promise}. - */ - Promise newPromise(); - - /** - * Create a new {@link ProgressivePromise}. - */ - ProgressivePromise newProgressivePromise(); - - /** - * Create a new {@link Future} which is marked as successes already. So {@link Future#isSuccess()} - * will return {@code true}. All {@link FutureListener} added to it will be notified directly. Also - * every call of blocking methods will just return without blocking. - */ - Future newSucceededFuture(V result); - - /** - * Create a new {@link Future} which is marked as fakued already. So {@link Future#isSuccess()} - * will return {@code false}. All {@link FutureListener} added to it will be notified directly. Also - * every call of blocking methods will just return without blocking. - */ - Future newFailedFuture(Throwable cause); -} diff --git a/common/src/main/java/common/net/util/concurrent/EventExecutorGroup.java b/common/src/main/java/common/net/util/concurrent/EventExecutorGroup.java deleted file mode 100644 index 16da3f8..0000000 --- a/common/src/main/java/common/net/util/concurrent/EventExecutorGroup.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -/** - * The {@link EventExecutorGroup} is responsible to provide {@link EventExecutor}'s to use via its - * {@link #next()} method. Beside this it also is responsible to handle their live-cycle and allows - * to shut them down in a global fashion. - * - */ -public interface EventExecutorGroup extends ScheduledExecutorService, Iterable { - - /** - * Returns {@code true} if and only if this executor was started to be - * {@linkplain #shutdownGracefully() shut down gracefuclly} or was {@linkplain #isShutdown() shut down}. - */ - boolean isShuttingDown(); - - /** - * Shortcut method for {@link #shutdownGracefully(long, long, TimeUnit)} with sensible default values. - * - * @return the {@link #terminationFuture()} - */ - Future shutdownGracefully(); - - /** - * Signals this executor that the caller wants the executor to be shut down. Once this method is called, - * {@link #isShuttingDown()} starts to return {@code true}, and the executor prepares to shut itself down. - * Unlike {@link #shutdown()}, graceful shutdown ensures that no tasks are submitted for 'the quiet period' - * (usually a couple seconds) before it shuts itself down. If a task is submitted during the quiet period, - * it is guaranteed to be accepted and the quiet period will start over. - * - * @param quietPeriod the quiet period as described in the documentation - * @param timeout the maximum amount of time to wait until the executor is {@linkplain #shutdown()} - * regardless if a task was submitted during the quiet period - * @param unit the unit of {@code quietPeriod} and {@code timeout} - * - * @return the {@link #terminationFuture()} - */ - Future shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit); - - /** - * Returns the {@link Future} which is notified when this executor has been terminated. - */ - Future terminationFuture(); - - /** - * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. - */ - @Override - @Deprecated - void shutdown(); - - /** - * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. - */ - @Override - @Deprecated - List shutdownNow(); - - /** - * Returns one of the {@link EventExecutor}s that belong to this group. - */ - EventExecutor next(); - - /** - * Returns a read-only {@link Iterator} over all {@link EventExecutor}, which are handled by this - * {@link EventExecutorGroup} at the time of invoke this method. - */ - @Override - Iterator iterator(); - - @Override - Future submit(Runnable task); - - @Override - Future submit(Runnable task, T result); - - @Override - Future submit(Callable task); - - @Override - ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit); - - @Override - ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit); - - @Override - ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit); - - @Override - ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit); -} diff --git a/common/src/main/java/common/net/util/concurrent/FailedFuture.java b/common/src/main/java/common/net/util/concurrent/FailedFuture.java deleted file mode 100644 index f0c6ce7..0000000 --- a/common/src/main/java/common/net/util/concurrent/FailedFuture.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import common.util.Util; - -/** - * The {@link CompleteFuture} which is failed already. It is - * recommended to use {@link EventExecutor#newFailedFuture(Throwable)} - * instead of calling the constructor of this future. - */ -public final class FailedFuture extends CompleteFuture { - - private final Throwable cause; - - /** - * Creates a new instance. - * - * @param executor the {@link EventExecutor} associated with this future - * @param cause the cause of failure - */ - public FailedFuture(EventExecutor executor, Throwable cause) { - super(executor); - if (cause == null) { - throw new NullPointerException("cause"); - } - this.cause = cause; - } - - @Override - public Throwable cause() { - return cause; - } - - @Override - public boolean isSuccess() { - return false; - } - - @Override - public Future sync() { - Util.throwUnchecked(cause); - return this; - } - - @Override - public Future syncUninterruptibly() { - Util.throwUnchecked(cause); - return this; - } - - @Override - public V getNow() { - return null; - } -} diff --git a/common/src/main/java/common/net/util/concurrent/FastThreadLocal.java b/common/src/main/java/common/net/util/concurrent/FastThreadLocal.java deleted file mode 100644 index a435abf..0000000 --- a/common/src/main/java/common/net/util/concurrent/FastThreadLocal.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.Set; - -import common.net.util.internal.InternalThreadLocalMap; -import common.util.Util; - -/** - * A special variant of {@link ThreadLocal} that yields higher access performan when accessed from a - * {@link FastThreadLocalThread}. - *

- * Internally, a {@link FastThreadLocal} uses a constant index in an array, instead of using hash code and hash table, - * to look for a variable. Although seemingly very subtle, it yields slight performance advantage over using a hash - * table, and it is useful when accessed frequently. - *

- * To take advantage of this thread-local variable, your thread must be a {@link FastThreadLocalThread} or its subtype. - * By default, all threads created by {@link DefaultThreadFactory} are {@link FastThreadLocalThread} due to this reason. - *

- * Note that the fast path is only possible on threads that extend {@link FastThreadLocalThread}, because it requires - * a special field to store the necessary state. An access by any other kind of thread falls back to a regular - * {@link ThreadLocal}. - *

- * - * @param the type of the thread-local variable - * @see ThreadLocal - */ -public class FastThreadLocal { - - private static final int variablesToRemoveIndex = InternalThreadLocalMap.nextVariableIndex(); - - /** - * Removes all {@link FastThreadLocal} variables bound to the current thread. This operation is useful when you - * are in a container environment, and you don't want to leave the thread local variables in the threads you do not - * manage. - */ - public static void removeAll() { - InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); - if (threadLocalMap == null) { - return; - } - - try { - Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex); - if (v != null && v != InternalThreadLocalMap.UNSET) { - - Set> variablesToRemove = (Set>) v; - FastThreadLocal[] variablesToRemoveArray = - variablesToRemove.toArray(new FastThreadLocal[variablesToRemove.size()]); - for (FastThreadLocal tlv: variablesToRemoveArray) { - tlv.remove(threadLocalMap); - } - } - } finally { - InternalThreadLocalMap.remove(); - } - } - - /** - * Returns the number of thread local variables bound to the current thread. - */ - public static int size() { - InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); - if (threadLocalMap == null) { - return 0; - } else { - return threadLocalMap.size(); - } - } - - /** - * Destroys the data structure that keeps all {@link FastThreadLocal} variables accessed from - * non-{@link FastThreadLocalThread}s. This operation is useful when you are in a container environment, and you - * do not want to leave the thread local variables in the threads you do not manage. Call this method when your - * application is being unloaded from the container. - */ - public static void destroy() { - InternalThreadLocalMap.destroy(); - } - - - private static void addToVariablesToRemove(InternalThreadLocalMap threadLocalMap, FastThreadLocal variable) { - Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex); - Set> variablesToRemove; - if (v == InternalThreadLocalMap.UNSET || v == null) { - variablesToRemove = Collections.newSetFromMap(new IdentityHashMap, Boolean>()); - threadLocalMap.setIndexedVariable(variablesToRemoveIndex, variablesToRemove); - } else { - variablesToRemove = (Set>) v; - } - - variablesToRemove.add(variable); - } - - private static void removeFromVariablesToRemove( - InternalThreadLocalMap threadLocalMap, FastThreadLocal variable) { - - Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex); - - if (v == InternalThreadLocalMap.UNSET || v == null) { - return; - } - - - Set> variablesToRemove = (Set>) v; - variablesToRemove.remove(variable); - } - - private final int index; - - public FastThreadLocal() { - index = InternalThreadLocalMap.nextVariableIndex(); - } - - /** - * Returns the current value for the current thread - */ - public final V get() { - return get(InternalThreadLocalMap.get()); - } - - /** - * Returns the current value for the specified thread local map. - * The specified thread local map must be for the current thread. - */ - - public final V get(InternalThreadLocalMap threadLocalMap) { - Object v = threadLocalMap.indexedVariable(index); - if (v != InternalThreadLocalMap.UNSET) { - return (V) v; - } - - return initialize(threadLocalMap); - } - - private V initialize(InternalThreadLocalMap threadLocalMap) { - V v = null; - try { - v = initialValue(); - } catch (Exception e) { - Util.throwUnchecked(e); - } - - threadLocalMap.setIndexedVariable(index, v); - addToVariablesToRemove(threadLocalMap, this); - return v; - } - - /** - * Set the value for the current thread. - */ - public final void set(V value) { - if (value != InternalThreadLocalMap.UNSET) { - set(InternalThreadLocalMap.get(), value); - } else { - remove(); - } - } - - /** - * Set the value for the specified thread local map. The specified thread local map must be for the current thread. - */ - public final void set(InternalThreadLocalMap threadLocalMap, V value) { - if (value != InternalThreadLocalMap.UNSET) { - if (threadLocalMap.setIndexedVariable(index, value)) { - addToVariablesToRemove(threadLocalMap, this); - } - } else { - remove(threadLocalMap); - } - } - - /** - * Returns {@code true} if and only if this thread-local variable is set. - */ - public final boolean isSet() { - return isSet(InternalThreadLocalMap.getIfSet()); - } - - /** - * Returns {@code true} if and only if this thread-local variable is set. - * The specified thread local map must be for the current thread. - */ - public final boolean isSet(InternalThreadLocalMap threadLocalMap) { - return threadLocalMap != null && threadLocalMap.isIndexedVariableSet(index); - } - /** - * Sets the value to uninitialized; a proceeding call to get() will trigger a call to initialValue(). - */ - public final void remove() { - remove(InternalThreadLocalMap.getIfSet()); - } - - /** - * Sets the value to uninitialized for the specified thread local map; - * a proceeding call to get() will trigger a call to initialValue(). - * The specified thread local map must be for the current thread. - */ - - public final void remove(InternalThreadLocalMap threadLocalMap) { - if (threadLocalMap == null) { - return; - } - - Object v = threadLocalMap.removeIndexedVariable(index); - removeFromVariablesToRemove(threadLocalMap, this); - - if (v != InternalThreadLocalMap.UNSET) { - try { - onRemoval((V) v); - } catch (Exception e) { - Util.throwUnchecked(e); - } - } - } - - /** - * Returns the initial value for this thread-local variable. - */ - protected V initialValue() throws Exception { - return null; - } - - /** - * Invoked when this thread local variable is removed by {@link #remove()}. - */ - protected void onRemoval( V value) throws Exception { } -} diff --git a/common/src/main/java/common/net/util/concurrent/FastThreadLocalThread.java b/common/src/main/java/common/net/util/concurrent/FastThreadLocalThread.java deleted file mode 100644 index e81083f..0000000 --- a/common/src/main/java/common/net/util/concurrent/FastThreadLocalThread.java +++ /dev/null @@ -1,72 +0,0 @@ -/* -* Copyright 2014 The Netty Project -* -* The Netty Project licenses this file to you under the Apache License, -* version 2.0 (the "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at: -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -* License for the specific language governing permissions and limitations -* under the License. -*/ -package common.net.util.concurrent; - -import common.net.util.internal.InternalThreadLocalMap; - -/** - * A special {@link Thread} that provides fast access to {@link FastThreadLocal} variables. - */ -public class FastThreadLocalThread extends Thread { - - private InternalThreadLocalMap threadLocalMap; - - public FastThreadLocalThread() { } - - public FastThreadLocalThread(Runnable target) { - super(target); - } - - public FastThreadLocalThread(ThreadGroup group, Runnable target) { - super(group, target); - } - - public FastThreadLocalThread(String name) { - super(name); - } - - public FastThreadLocalThread(ThreadGroup group, String name) { - super(group, name); - } - - public FastThreadLocalThread(Runnable target, String name) { - super(target, name); - } - - public FastThreadLocalThread(ThreadGroup group, Runnable target, String name) { - super(group, target, name); - } - - public FastThreadLocalThread(ThreadGroup group, Runnable target, String name, long stackSize) { - super(group, target, name, stackSize); - } - - /** - * Returns the internal data structure that keeps the thread-local variables bound to this thread. - * Note that this method is for internal use only, and thus is subject to change at any time. - */ - public final InternalThreadLocalMap threadLocalMap() { - return threadLocalMap; - } - - /** - * Sets the internal data structure that keeps the thread-local variables bound to this thread. - * Note that this method is for internal use only, and thus is subject to change at any time. - */ - public final void setThreadLocalMap(InternalThreadLocalMap threadLocalMap) { - this.threadLocalMap = threadLocalMap; - } -} diff --git a/common/src/main/java/common/net/util/concurrent/Future.java b/common/src/main/java/common/net/util/concurrent/Future.java deleted file mode 100644 index 37748cd..0000000 --- a/common/src/main/java/common/net/util/concurrent/Future.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.concurrent.TimeUnit; - - -/** - * The result of an asynchronous operation. - */ - -public interface Future extends java.util.concurrent.Future { - - /** - * Returns {@code true} if and only if the I/O operation was completed - * successfully. - */ - boolean isSuccess(); - - /** - * returns {@code true} if and only if the operation can be cancelled via {@link #cancel(boolean)}. - */ - boolean isCancellable(); - - /** - * Returns the cause of the failed I/O operation if the I/O operation has - * failed. - * - * @return the cause of the failure. - * {@code null} if succeeded or this future is not - * completed yet. - */ - Throwable cause(); - - /** - * Adds the specified listener to this future. The - * specified listener is notified when this future is - * {@linkplain #isDone() done}. If this future is already - * completed, the specified listener is notified immediately. - */ - Future addListener(GenericFutureListener> listener); - - /** - * Adds the specified listeners to this future. The - * specified listeners are notified when this future is - * {@linkplain #isDone() done}. If this future is already - * completed, the specified listeners are notified immediately. - */ - Future addListeners(GenericFutureListener>... listeners); - - /** - * Removes the specified listener from this future. - * The specified listener is no longer notified when this - * future is {@linkplain #isDone() done}. If the specified - * listener is not associated with this future, this method - * does nothing and returns silently. - */ - Future removeListener(GenericFutureListener> listener); - - /** - * Removes the specified listeners from this future. - * The specified listeners are no longer notified when this - * future is {@linkplain #isDone() done}. If the specified - * listeners are not associated with this future, this method - * does nothing and returns silently. - */ - Future removeListeners(GenericFutureListener>... listeners); - - /** - * Waits for this future until it is done, and rethrows the cause of the failure if this future - * failed. - */ - Future sync() throws InterruptedException; - - /** - * Waits for this future until it is done, and rethrows the cause of the failure if this future - * failed. - */ - Future syncUninterruptibly(); - - /** - * Waits for this future to be completed. - * - * @throws InterruptedException - * if the current thread was interrupted - */ - Future await() throws InterruptedException; - - /** - * Waits for this future to be completed without - * interruption. This method catches an {@link InterruptedException} and - * discards it silently. - */ - Future awaitUninterruptibly(); - - /** - * Waits for this future to be completed within the - * specified time limit. - * - * @return {@code true} if and only if the future was completed within - * the specified time limit - * - * @throws InterruptedException - * if the current thread was interrupted - */ - boolean await(long timeout, TimeUnit unit) throws InterruptedException; - - /** - * Waits for this future to be completed within the - * specified time limit. - * - * @return {@code true} if and only if the future was completed within - * the specified time limit - * - * @throws InterruptedException - * if the current thread was interrupted - */ - boolean await(long timeoutMillis) throws InterruptedException; - - /** - * Waits for this future to be completed within the - * specified time limit without interruption. This method catches an - * {@link InterruptedException} and discards it silently. - * - * @return {@code true} if and only if the future was completed within - * the specified time limit - */ - boolean awaitUninterruptibly(long timeout, TimeUnit unit); - - /** - * Waits for this future to be completed within the - * specified time limit without interruption. This method catches an - * {@link InterruptedException} and discards it silently. - * - * @return {@code true} if and only if the future was completed within - * the specified time limit - */ - boolean awaitUninterruptibly(long timeoutMillis); - - /** - * Return the result without blocking. If the future is not done yet this will return {@code null}. - * - * As it is possible that a {@code null} value is used to mark the future as successful you also need to check - * if the future is really done with {@link #isDone()} and not relay on the returned {@code null} value. - */ - V getNow(); - - /** - * {@inheritDoc} - * - * If the cancellation was successful it will fail the future with an {@link CancellationException}. - */ - @Override - boolean cancel(boolean mayInterruptIfRunning); -} diff --git a/common/src/main/java/common/net/util/concurrent/FutureListener.java b/common/src/main/java/common/net/util/concurrent/FutureListener.java deleted file mode 100644 index 8d5a690..0000000 --- a/common/src/main/java/common/net/util/concurrent/FutureListener.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.concurrent; - -/** - * A subtype of {@link GenericFutureListener} that hides type parameter for convenience. - *
- * Future f = new DefaultPromise(..);
- * f.addListener(new FutureListener() {
- *     public void operationComplete(Future f) { .. }
- * });
- * 
- */ -public interface FutureListener extends GenericFutureListener> { } diff --git a/common/src/main/java/common/net/util/concurrent/GenericFutureListener.java b/common/src/main/java/common/net/util/concurrent/GenericFutureListener.java deleted file mode 100644 index a5d46cc..0000000 --- a/common/src/main/java/common/net/util/concurrent/GenericFutureListener.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.EventListener; - -/** - * Listens to the result of a {@link Future}. The result of the asynchronous operation is notified once this listener - * is added by calling {@link Future#addListener(GenericFutureListener)}. - */ -public interface GenericFutureListener> extends EventListener { - - /** - * Invoked when the operation associated with the {@link Future} has been completed. - * - * @param future the source {@link Future} which called this callback - */ - void operationComplete(F future) throws Exception; -} diff --git a/common/src/main/java/common/net/util/concurrent/GenericProgressiveFutureListener.java b/common/src/main/java/common/net/util/concurrent/GenericProgressiveFutureListener.java deleted file mode 100644 index 8da4cbb..0000000 --- a/common/src/main/java/common/net/util/concurrent/GenericProgressiveFutureListener.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.concurrent; - -public interface GenericProgressiveFutureListener> extends GenericFutureListener { - /** - * Invoked when the operation has progressed. - * - * @param progress the progress of the operation so far (cumulative) - * @param total the number that signifies the end of the operation when {@code progress} reaches at it. - * {@code -1} if the end of operation is unknown. - */ - void operationProgressed(F future, long progress, long total) throws Exception; -} diff --git a/common/src/main/java/common/net/util/concurrent/GlobalEventExecutor.java b/common/src/main/java/common/net/util/concurrent/GlobalEventExecutor.java deleted file mode 100644 index 103143b..0000000 --- a/common/src/main/java/common/net/util/concurrent/GlobalEventExecutor.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.Iterator; -import java.util.PriorityQueue; -import java.util.Queue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * Single-thread singleton {@link EventExecutor}. It starts the thread automatically and stops it when there is no - * task pending in the task queue for 1 second. Please note it is not scalable to schedule large number of tasks to - * this executor; use a dedicated executor. - */ -public final class GlobalEventExecutor extends AbstractEventExecutor { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(GlobalEventExecutor.class); - - private static final long SCHEDULE_PURGE_INTERVAL = TimeUnit.SECONDS.toNanos(1); - - public static final GlobalEventExecutor INSTANCE = new GlobalEventExecutor(); - - final BlockingQueue taskQueue = new LinkedBlockingQueue(); - final Queue> delayedTaskQueue = new PriorityQueue>(); - final ScheduledFutureTask purgeTask = new ScheduledFutureTask( - this, delayedTaskQueue, Executors.callable(new PurgeTask(), null), - ScheduledFutureTask.deadlineNanos(SCHEDULE_PURGE_INTERVAL), -SCHEDULE_PURGE_INTERVAL); - - private final ThreadFactory threadFactory = new DefaultThreadFactory(getClass()); - private final TaskRunner taskRunner = new TaskRunner(); - private final AtomicBoolean started = new AtomicBoolean(); - volatile Thread thread; - - private final Future terminationFuture = new FailedFuture(this, new UnsupportedOperationException()); - - private GlobalEventExecutor() { - delayedTaskQueue.add(purgeTask); - } - - @Override - public EventExecutorGroup parent() { - return null; - } - - /** - * Take the next {@link Runnable} from the task queue and so will block if no task is currently present. - * - * @return {@code null} if the executor thread has been interrupted or waken up. - */ - Runnable takeTask() { - BlockingQueue taskQueue = this.taskQueue; - for (;;) { - ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); - if (delayedTask == null) { - Runnable task = null; - try { - task = taskQueue.take(); - } catch (InterruptedException e) { - // Ignore - } - return task; - } else { - long delayNanos = delayedTask.delayNanos(); - Runnable task; - if (delayNanos > 0) { - try { - task = taskQueue.poll(delayNanos, TimeUnit.NANOSECONDS); - } catch (InterruptedException e) { - return null; - } - } else { - task = taskQueue.poll(); - } - - if (task == null) { - fetchFromDelayedQueue(); - task = taskQueue.poll(); - } - - if (task != null) { - return task; - } - } - } - } - - private void fetchFromDelayedQueue() { - long nanoTime = 0L; - for (;;) { - ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); - if (delayedTask == null) { - break; - } - - if (nanoTime == 0L) { - nanoTime = ScheduledFutureTask.nanoTime(); - } - - if (delayedTask.deadlineNanos() <= nanoTime) { - delayedTaskQueue.remove(); - taskQueue.add(delayedTask); - } else { - break; - } - } - } - - /** - * Return the number of tasks that are pending for processing. - * - * Be aware that this operation may be expensive as it depends on the internal implementation of the - * SingleThreadEventExecutor. So use it was care! - */ - public int pendingTasks() { - return taskQueue.size(); - } - - /** - * Add a task to the task queue, or throws a {@link RejectedExecutionException} if this instance was shutdown - * before. - */ - private void addTask(Runnable task) { - if (task == null) { - throw new NullPointerException("task"); - } - taskQueue.add(task); - } - - @Override - public boolean inEventLoop(Thread thread) { - return thread == this.thread; - } - - @Override - public Future shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { - return terminationFuture(); - } - - @Override - public Future terminationFuture() { - return terminationFuture; - } - - @Override - @Deprecated - public void shutdown() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isShuttingDown() { - return false; - } - - @Override - public boolean isShutdown() { - return false; - } - - @Override - public boolean isTerminated() { - return false; - } - - @Override - public boolean awaitTermination(long timeout, TimeUnit unit) { - return false; - } - - /** - * Waits until the worker thread of this executor has no tasks left in its task queue and terminates itself. - * Because a new worker thread will be started again when a new task is submitted, this operation is only useful - * when you want to ensure that the worker thread is terminated after your application is shut - * down and there's no chance of submitting a new task afterwards. - * - * @return {@code true} if and only if the worker thread has been terminated - */ - public boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { - if (unit == null) { - throw new NullPointerException("unit"); - } - - final Thread thread = this.thread; - if (thread == null) { - throw new IllegalStateException("thread was not started"); - } - thread.join(unit.toMillis(timeout)); - return !thread.isAlive(); - } - - @Override - public void execute(Runnable task) { - if (task == null) { - throw new NullPointerException("task"); - } - - addTask(task); - if (!inEventLoop()) { - startThread(); - } - } - - // ScheduledExecutorService implementation - - @Override - public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { - if (command == null) { - throw new NullPointerException("command"); - } - if (unit == null) { - throw new NullPointerException("unit"); - } - if (delay < 0) { - throw new IllegalArgumentException( - String.format("delay: %d (expected: >= 0)", delay)); - } - return schedule(new ScheduledFutureTask( - this, delayedTaskQueue, command, null, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay)))); - } - - @Override - public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { - if (callable == null) { - throw new NullPointerException("callable"); - } - if (unit == null) { - throw new NullPointerException("unit"); - } - if (delay < 0) { - throw new IllegalArgumentException( - String.format("delay: %d (expected: >= 0)", delay)); - } - return schedule(new ScheduledFutureTask( - this, delayedTaskQueue, callable, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay)))); - } - - @Override - public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { - if (command == null) { - throw new NullPointerException("command"); - } - if (unit == null) { - throw new NullPointerException("unit"); - } - if (initialDelay < 0) { - throw new IllegalArgumentException( - String.format("initialDelay: %d (expected: >= 0)", initialDelay)); - } - if (period <= 0) { - throw new IllegalArgumentException( - String.format("period: %d (expected: > 0)", period)); - } - - return schedule(new ScheduledFutureTask( - this, delayedTaskQueue, Executors.callable(command, null), - ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), unit.toNanos(period))); - } - - @Override - public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { - if (command == null) { - throw new NullPointerException("command"); - } - if (unit == null) { - throw new NullPointerException("unit"); - } - if (initialDelay < 0) { - throw new IllegalArgumentException( - String.format("initialDelay: %d (expected: >= 0)", initialDelay)); - } - if (delay <= 0) { - throw new IllegalArgumentException( - String.format("delay: %d (expected: > 0)", delay)); - } - - return schedule(new ScheduledFutureTask( - this, delayedTaskQueue, Executors.callable(command, null), - ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), -unit.toNanos(delay))); - } - - private ScheduledFuture schedule(final ScheduledFutureTask task) { - if (task == null) { - throw new NullPointerException("task"); - } - - if (inEventLoop()) { - delayedTaskQueue.add(task); - } else { - execute(new Runnable() { - @Override - public void run() { - delayedTaskQueue.add(task); - } - }); - } - - return task; - } - - private void startThread() { - if (started.compareAndSet(false, true)) { - Thread t = threadFactory.newThread(taskRunner); - t.start(); - thread = t; - } - } - - final class TaskRunner implements Runnable { - @Override - public void run() { - for (;;) { - Runnable task = takeTask(); - if (task != null) { - try { - task.run(); - } catch (Throwable t) { - logger.warn("Unexpected exception from the global event executor: ", t); - } - - if (task != purgeTask) { - continue; - } - } - - // Terminate if there is no task in the queue (except the purge task). - if (taskQueue.isEmpty() && delayedTaskQueue.size() == 1) { - // Mark the current thread as stopped. - // The following CAS must always success and must be uncontended, - // because only one thread should be running at the same time. - boolean stopped = started.compareAndSet(true, false); - assert stopped; - - // Check if there are pending entries added by execute() or schedule*() while we do CAS above. - if (taskQueue.isEmpty() && delayedTaskQueue.size() == 1) { - // A) No new task was added and thus there's nothing to handle - // -> safe to terminate because there's nothing left to do - // B) A new thread started and handled all the new tasks. - // -> safe to terminate the new thread will take care the rest - break; - } - - // There are pending tasks added again. - if (!started.compareAndSet(false, true)) { - // startThread() started a new thread and set 'started' to true. - // -> terminate this thread so that the new thread reads from taskQueue exclusively. - break; - } - - // New tasks were added, but this worker was faster to set 'started' to true. - // i.e. a new worker thread was not started by startThread(). - // -> keep this thread alive to handle the newly added entries. - } - } - } - } - - private final class PurgeTask implements Runnable { - @Override - public void run() { - Iterator> i = delayedTaskQueue.iterator(); - while (i.hasNext()) { - ScheduledFutureTask task = i.next(); - if (task.isCancelled()) { - i.remove(); - } - } - } - } -} diff --git a/common/src/main/java/common/net/util/concurrent/ImmediateEventExecutor.java b/common/src/main/java/common/net/util/concurrent/ImmediateEventExecutor.java deleted file mode 100644 index 6b8fddb..0000000 --- a/common/src/main/java/common/net/util/concurrent/ImmediateEventExecutor.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.concurrent.TimeUnit; - -/** - * {@link AbstractEventExecutor} which execute tasks in the callers thread. - */ -public final class ImmediateEventExecutor extends AbstractEventExecutor { - public static final ImmediateEventExecutor INSTANCE = new ImmediateEventExecutor(); - - private final Future terminationFuture = new FailedFuture( - GlobalEventExecutor.INSTANCE, new UnsupportedOperationException()); - - private ImmediateEventExecutor() { - // use static instance - } - - @Override - public EventExecutorGroup parent() { - return null; - } - - @Override - public boolean inEventLoop() { - return true; - } - - @Override - public boolean inEventLoop(Thread thread) { - return true; - } - - @Override - public Future shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { - return terminationFuture(); - } - - @Override - public Future terminationFuture() { - return terminationFuture; - } - - @Override - @Deprecated - public void shutdown() { } - - @Override - public boolean isShuttingDown() { - return false; - } - - @Override - public boolean isShutdown() { - return false; - } - - @Override - public boolean isTerminated() { - return false; - } - - @Override - public boolean awaitTermination(long timeout, TimeUnit unit) { - return false; - } - - @Override - public void execute(Runnable command) { - if (command == null) { - throw new NullPointerException("command"); - } - command.run(); - } - - @Override - public Promise newPromise() { - return new ImmediatePromise(this); - } - - @Override - public ProgressivePromise newProgressivePromise() { - return new ImmediateProgressivePromise(this); - } - - static class ImmediatePromise extends DefaultPromise { - ImmediatePromise(EventExecutor executor) { - super(executor); - } - - @Override - protected void checkDeadLock() { - // No check - } - } - - static class ImmediateProgressivePromise extends DefaultProgressivePromise { - ImmediateProgressivePromise(EventExecutor executor) { - super(executor); - } - - @Override - protected void checkDeadLock() { - // No check - } - } -} diff --git a/common/src/main/java/common/net/util/concurrent/ImmediateExecutor.java b/common/src/main/java/common/net/util/concurrent/ImmediateExecutor.java deleted file mode 100644 index 6660c6d..0000000 --- a/common/src/main/java/common/net/util/concurrent/ImmediateExecutor.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.concurrent.Executor; - -/** - * {@link Executor} which execute tasks in the callers thread. - */ -public final class ImmediateExecutor implements Executor { - public static final ImmediateExecutor INSTANCE = new ImmediateExecutor(); - - private ImmediateExecutor() { - // use static instance - } - - @Override - public void execute(Runnable command) { - if (command == null) { - throw new NullPointerException("command"); - } - command.run(); - } -} diff --git a/common/src/main/java/common/net/util/concurrent/MultithreadEventExecutorGroup.java b/common/src/main/java/common/net/util/concurrent/MultithreadEventExecutorGroup.java deleted file mode 100644 index 39a72c3..0000000 --- a/common/src/main/java/common/net/util/concurrent/MultithreadEventExecutorGroup.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Set; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Abstract base class for {@link EventExecutorGroup} implementations that handles their tasks with multiple threads at - * the same time. - */ -public abstract class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup { - - private final EventExecutor[] children; - private final AtomicInteger childIndex = new AtomicInteger(); - private final AtomicInteger terminatedChildren = new AtomicInteger(); - private final Promise terminationFuture = new DefaultPromise(GlobalEventExecutor.INSTANCE); - private final EventExecutorChooser chooser; - - /** - * Create a new instance. - * - * @param nThreads the number of threads that will be used by this instance. - * @param threadFactory the ThreadFactory to use, or {@code null} if the default should be used. - * @param args arguments which will passed to each {@link #newChild(ThreadFactory, Object...)} call - */ - protected MultithreadEventExecutorGroup(int nThreads, ThreadFactory threadFactory, Object... args) { - if (nThreads <= 0) { - throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads)); - } - - if (threadFactory == null) { - threadFactory = newDefaultThreadFactory(); - } - - children = new SingleThreadEventExecutor[nThreads]; - if (isPowerOfTwo(children.length)) { - chooser = new PowerOfTwoEventExecutorChooser(); - } else { - chooser = new GenericEventExecutorChooser(); - } - - for (int i = 0; i < nThreads; i ++) { - boolean success = false; - try { - children[i] = newChild(threadFactory, args); - success = true; - } catch (Exception e) { - // TODO: Think about if this is a good exception type - throw new IllegalStateException("failed to create a child event loop", e); - } finally { - if (!success) { - for (int j = 0; j < i; j ++) { - children[j].shutdownGracefully(); - } - - for (int j = 0; j < i; j ++) { - EventExecutor e = children[j]; - try { - while (!e.isTerminated()) { - e.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - break; - } - } - } - } - } - - final FutureListener terminationListener = new FutureListener() { - @Override - public void operationComplete(Future future) throws Exception { - if (terminatedChildren.incrementAndGet() == children.length) { - terminationFuture.setSuccess(null); - } - } - }; - - for (EventExecutor e: children) { - e.terminationFuture().addListener(terminationListener); - } - } - - protected ThreadFactory newDefaultThreadFactory() { - return new DefaultThreadFactory(getClass()); - } - - @Override - public EventExecutor next() { - return chooser.next(); - } - - @Override - public Iterator iterator() { - return children().iterator(); - } - - /** - * Return the number of {@link EventExecutor} this implementation uses. This number is the maps - * 1:1 to the threads it use. - */ - public final int executorCount() { - return children.length; - } - - /** - * Return a safe-copy of all of the children of this group. - */ - protected Set children() { - Set children = Collections.newSetFromMap(new LinkedHashMap()); - Collections.addAll(children, this.children); - return children; - } - - /** - * Create a new EventExecutor which will later then accessible via the {@link #next()} method. This method will be - * called for each thread that will serve this {@link MultithreadEventExecutorGroup}. - * - */ - protected abstract EventExecutor newChild( - ThreadFactory threadFactory, Object... args) throws Exception; - - @Override - public Future shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { - for (EventExecutor l: children) { - l.shutdownGracefully(quietPeriod, timeout, unit); - } - return terminationFuture(); - } - - @Override - public Future terminationFuture() { - return terminationFuture; - } - - @Override - @Deprecated - public void shutdown() { - for (EventExecutor l: children) { - l.shutdown(); - } - } - - @Override - public boolean isShuttingDown() { - for (EventExecutor l: children) { - if (!l.isShuttingDown()) { - return false; - } - } - return true; - } - - @Override - public boolean isShutdown() { - for (EventExecutor l: children) { - if (!l.isShutdown()) { - return false; - } - } - return true; - } - - @Override - public boolean isTerminated() { - for (EventExecutor l: children) { - if (!l.isTerminated()) { - return false; - } - } - return true; - } - - @Override - public boolean awaitTermination(long timeout, TimeUnit unit) - throws InterruptedException { - long deadline = System.nanoTime() + unit.toNanos(timeout); - loop: for (EventExecutor l: children) { - for (;;) { - long timeLeft = deadline - System.nanoTime(); - if (timeLeft <= 0) { - break loop; - } - if (l.awaitTermination(timeLeft, TimeUnit.NANOSECONDS)) { - break; - } - } - } - return isTerminated(); - } - - private static boolean isPowerOfTwo(int val) { - return (val & -val) == val; - } - - private interface EventExecutorChooser { - EventExecutor next(); - } - - private final class PowerOfTwoEventExecutorChooser implements EventExecutorChooser { - @Override - public EventExecutor next() { - return children[childIndex.getAndIncrement() & children.length - 1]; - } - } - - private final class GenericEventExecutorChooser implements EventExecutorChooser { - @Override - public EventExecutor next() { - return children[Math.abs(childIndex.getAndIncrement() % children.length)]; - } - } -} diff --git a/common/src/main/java/common/net/util/concurrent/ProgressiveFuture.java b/common/src/main/java/common/net/util/concurrent/ProgressiveFuture.java deleted file mode 100644 index 71c7134..0000000 --- a/common/src/main/java/common/net/util/concurrent/ProgressiveFuture.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.concurrent; - -/** - * A {@link Future} which is used to indicate the progress of an operation. - */ -public interface ProgressiveFuture extends Future { - - @Override - ProgressiveFuture addListener(GenericFutureListener> listener); - - @Override - ProgressiveFuture addListeners(GenericFutureListener>... listeners); - - @Override - ProgressiveFuture removeListener(GenericFutureListener> listener); - - @Override - ProgressiveFuture removeListeners(GenericFutureListener>... listeners); - - @Override - ProgressiveFuture sync() throws InterruptedException; - - @Override - ProgressiveFuture syncUninterruptibly(); - - @Override - ProgressiveFuture await() throws InterruptedException; - - @Override - ProgressiveFuture awaitUninterruptibly(); -} diff --git a/common/src/main/java/common/net/util/concurrent/ProgressivePromise.java b/common/src/main/java/common/net/util/concurrent/ProgressivePromise.java deleted file mode 100644 index e6a2e35..0000000 --- a/common/src/main/java/common/net/util/concurrent/ProgressivePromise.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -/** - * Special {@link ProgressiveFuture} which is writable. - */ -public interface ProgressivePromise extends Promise, ProgressiveFuture { - - /** - * Sets the current progress of the operation and notifies the listeners that implement - * {@link GenericProgressiveFutureListener}. - */ - ProgressivePromise setProgress(long progress, long total); - - /** - * Tries to set the current progress of the operation and notifies the listeners that implement - * {@link GenericProgressiveFutureListener}. If the operation is already complete or the progress is out of range, - * this method does nothing but returning {@code false}. - */ - boolean tryProgress(long progress, long total); - - @Override - ProgressivePromise setSuccess(V result); - - @Override - ProgressivePromise setFailure(Throwable cause); - - @Override - ProgressivePromise addListener(GenericFutureListener> listener); - - @Override - ProgressivePromise addListeners(GenericFutureListener>... listeners); - - @Override - ProgressivePromise removeListener(GenericFutureListener> listener); - - @Override - ProgressivePromise removeListeners(GenericFutureListener>... listeners); - - @Override - ProgressivePromise await() throws InterruptedException; - - @Override - ProgressivePromise awaitUninterruptibly(); - - @Override - ProgressivePromise sync() throws InterruptedException; - - @Override - ProgressivePromise syncUninterruptibly(); -} diff --git a/common/src/main/java/common/net/util/concurrent/Promise.java b/common/src/main/java/common/net/util/concurrent/Promise.java deleted file mode 100644 index 252d895..0000000 --- a/common/src/main/java/common/net/util/concurrent/Promise.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -/** - * Special {@link Future} which is writable. - */ -public interface Promise extends Future { - - /** - * Marks this future as a success and notifies all - * listeners. - * - * If it is success or failed already it will throw an {@link IllegalStateException}. - */ - Promise setSuccess(V result); - - /** - * Marks this future as a success and notifies all - * listeners. - * - * @return {@code true} if and only if successfully marked this future as - * a success. Otherwise {@code false} because this future is - * already marked as either a success or a failure. - */ - boolean trySuccess(V result); - - /** - * Marks this future as a failure and notifies all - * listeners. - * - * If it is success or failed already it will throw an {@link IllegalStateException}. - */ - Promise setFailure(Throwable cause); - - /** - * Marks this future as a failure and notifies all - * listeners. - * - * @return {@code true} if and only if successfully marked this future as - * a failure. Otherwise {@code false} because this future is - * already marked as either a success or a failure. - */ - boolean tryFailure(Throwable cause); - - /** - * Make this future impossible to cancel. - * - * @return {@code true} if and only if successfully marked this future as uncancellable or it is already done - * without being cancelled. {@code false} if this future has been cancelled already. - */ - boolean setUncancellable(); - - @Override - Promise addListener(GenericFutureListener> listener); - - @Override - Promise addListeners(GenericFutureListener>... listeners); - - @Override - Promise removeListener(GenericFutureListener> listener); - - @Override - Promise removeListeners(GenericFutureListener>... listeners); - - @Override - Promise await() throws InterruptedException; - - @Override - Promise awaitUninterruptibly(); - - @Override - Promise sync() throws InterruptedException; - - @Override - Promise syncUninterruptibly(); -} diff --git a/common/src/main/java/common/net/util/concurrent/PromiseTask.java b/common/src/main/java/common/net/util/concurrent/PromiseTask.java deleted file mode 100644 index 8a897ad..0000000 --- a/common/src/main/java/common/net/util/concurrent/PromiseTask.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.concurrent.Callable; -import java.util.concurrent.RunnableFuture; - -class PromiseTask extends DefaultPromise implements RunnableFuture { - - static Callable toCallable(Runnable runnable, T result) { - return new RunnableAdapter(runnable, result); - } - - private static final class RunnableAdapter implements Callable { - final Runnable task; - final T result; - - RunnableAdapter(Runnable task, T result) { - this.task = task; - this.result = result; - } - - @Override - public T call() { - task.run(); - return result; - } - - @Override - public String toString() { - return "Callable(task: " + task + ", result: " + result + ')'; - } - } - - protected final Callable task; - - PromiseTask(EventExecutor executor, Runnable runnable, V result) { - this(executor, toCallable(runnable, result)); - } - - PromiseTask(EventExecutor executor, Callable callable) { - super(executor); - task = callable; - } - - @Override - public final int hashCode() { - return System.identityHashCode(this); - } - - @Override - public final boolean equals(Object obj) { - return this == obj; - } - - @Override - public void run() { - try { - if (setUncancellableInternal()) { - V result = task.call(); - setSuccessInternal(result); - } - } catch (Throwable e) { - setFailureInternal(e); - } - } - - @Override - public final Promise setFailure(Throwable cause) { - throw new IllegalStateException(); - } - - protected final Promise setFailureInternal(Throwable cause) { - super.setFailure(cause); - return this; - } - - @Override - public final boolean tryFailure(Throwable cause) { - return false; - } - - protected final boolean tryFailureInternal(Throwable cause) { - return super.tryFailure(cause); - } - - @Override - public final Promise setSuccess(V result) { - throw new IllegalStateException(); - } - - protected final Promise setSuccessInternal(V result) { - super.setSuccess(result); - return this; - } - - @Override - public final boolean trySuccess(V result) { - return false; - } - - protected final boolean trySuccessInternal(V result) { - return super.trySuccess(result); - } - - @Override - public final boolean setUncancellable() { - throw new IllegalStateException(); - } - - protected final boolean setUncancellableInternal() { - return super.setUncancellable(); - } - - @Override - protected StringBuilder toStringBuilder() { - StringBuilder buf = super.toStringBuilder(); - buf.setCharAt(buf.length() - 1, ','); - buf.append(" task: "); - buf.append(task); - buf.append(')'); - return buf; - } -} diff --git a/common/src/main/java/common/net/util/concurrent/ScheduledFuture.java b/common/src/main/java/common/net/util/concurrent/ScheduledFuture.java deleted file mode 100644 index 3498b13..0000000 --- a/common/src/main/java/common/net/util/concurrent/ScheduledFuture.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -/** - * The result of an scheduled asynchronous operation. - */ - -public interface ScheduledFuture extends Future, java.util.concurrent.ScheduledFuture { -} diff --git a/common/src/main/java/common/net/util/concurrent/ScheduledFutureTask.java b/common/src/main/java/common/net/util/concurrent/ScheduledFutureTask.java deleted file mode 100644 index 83f64b3..0000000 --- a/common/src/main/java/common/net/util/concurrent/ScheduledFutureTask.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.concurrent; - -import java.util.Queue; -import java.util.concurrent.Callable; -import java.util.concurrent.Delayed; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - - -final class ScheduledFutureTask extends PromiseTask implements ScheduledFuture { - private static final AtomicLong nextTaskId = new AtomicLong(); - private static final long START_TIME = System.nanoTime(); - - static long nanoTime() { - return System.nanoTime() - START_TIME; - } - - static long deadlineNanos(long delay) { - return nanoTime() + delay; - } - - private final long id = nextTaskId.getAndIncrement(); - private final Queue> delayedTaskQueue; - private long deadlineNanos; - /* 0 - no repeat, >0 - repeat at fixed rate, <0 - repeat with fixed delay */ - private final long periodNanos; - - ScheduledFutureTask( - EventExecutor executor, Queue> delayedTaskQueue, - Runnable runnable, V result, long nanoTime) { - - this(executor, delayedTaskQueue, toCallable(runnable, result), nanoTime); - } - - ScheduledFutureTask( - EventExecutor executor, Queue> delayedTaskQueue, - Callable callable, long nanoTime, long period) { - - super(executor, callable); - if (period == 0) { - throw new IllegalArgumentException("period: 0 (expected: != 0)"); - } - this.delayedTaskQueue = delayedTaskQueue; - deadlineNanos = nanoTime; - periodNanos = period; - } - - ScheduledFutureTask( - EventExecutor executor, Queue> delayedTaskQueue, - Callable callable, long nanoTime) { - - super(executor, callable); - this.delayedTaskQueue = delayedTaskQueue; - deadlineNanos = nanoTime; - periodNanos = 0; - } - - @Override - protected EventExecutor executor() { - return super.executor(); - } - - public long deadlineNanos() { - return deadlineNanos; - } - - public long delayNanos() { - return Math.max(0, deadlineNanos() - nanoTime()); - } - - public long delayNanos(long currentTimeNanos) { - return Math.max(0, deadlineNanos() - (currentTimeNanos - START_TIME)); - } - - @Override - public long getDelay(TimeUnit unit) { - return unit.convert(delayNanos(), TimeUnit.NANOSECONDS); - } - - @Override - public int compareTo(Delayed o) { - if (this == o) { - return 0; - } - - ScheduledFutureTask that = (ScheduledFutureTask) o; - long d = deadlineNanos() - that.deadlineNanos(); - if (d < 0) { - return -1; - } else if (d > 0) { - return 1; - } else if (id < that.id) { - return -1; - } else if (id == that.id) { - throw new Error(); - } else { - return 1; - } - } - - @Override - public void run() { - assert executor().inEventLoop(); - try { - if (periodNanos == 0) { - if (setUncancellableInternal()) { - V result = task.call(); - setSuccessInternal(result); - } - } else { - // check if is done as it may was cancelled - if (!isCancelled()) { - task.call(); - if (!executor().isShutdown()) { - long p = periodNanos; - if (p > 0) { - deadlineNanos += p; - } else { - deadlineNanos = nanoTime() - p; - } - if (!isCancelled()) { - delayedTaskQueue.add(this); - } - } - } - } - } catch (Throwable cause) { - setFailureInternal(cause); - } - } - - @Override - protected StringBuilder toStringBuilder() { - StringBuilder buf = super.toStringBuilder(); - buf.setCharAt(buf.length() - 1, ','); - buf.append(" id: "); - buf.append(id); - buf.append(", deadline: "); - buf.append(deadlineNanos); - buf.append(", period: "); - buf.append(periodNanos); - buf.append(')'); - return buf; - } -} diff --git a/common/src/main/java/common/net/util/concurrent/SingleThreadEventExecutor.java b/common/src/main/java/common/net/util/concurrent/SingleThreadEventExecutor.java deleted file mode 100644 index 044f794..0000000 --- a/common/src/main/java/common/net/util/concurrent/SingleThreadEventExecutor.java +++ /dev/null @@ -1,869 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.PriorityQueue; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.Semaphore; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; - -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * Abstract base class for {@link EventExecutor}'s that execute all its submitted tasks in a single thread. - * - */ -public abstract class SingleThreadEventExecutor extends AbstractEventExecutor { - - private static final InternalLogger logger = - InternalLoggerFactory.getInstance(SingleThreadEventExecutor.class); - - private static final int ST_NOT_STARTED = 1; - private static final int ST_STARTED = 2; - private static final int ST_SHUTTING_DOWN = 3; - private static final int ST_SHUTDOWN = 4; - private static final int ST_TERMINATED = 5; - - private static final Runnable WAKEUP_TASK = new Runnable() { - @Override - public void run() { - // Do nothing. - } - }; - - private static final AtomicIntegerFieldUpdater STATE_UPDATER; - - static { - AtomicIntegerFieldUpdater updater = - null; - if (updater == null) { - updater = AtomicIntegerFieldUpdater.newUpdater(SingleThreadEventExecutor.class, "state"); - } - STATE_UPDATER = updater; - } - - private final EventExecutorGroup parent; - private final Queue taskQueue; - final Queue> delayedTaskQueue = new PriorityQueue>(); - - private final Thread thread; - private final Semaphore threadLock = new Semaphore(0); - private final Set shutdownHooks = new LinkedHashSet(); - private final boolean addTaskWakesUp; - - private long lastExecutionTime; - - - private volatile int state = ST_NOT_STARTED; - - private volatile long gracefulShutdownQuietPeriod; - private volatile long gracefulShutdownTimeout; - private long gracefulShutdownStartTime; - - private final Promise terminationFuture = new DefaultPromise(GlobalEventExecutor.INSTANCE); - - /** - * Create a new instance - * - * @param parent the {@link EventExecutorGroup} which is the parent of this instance and belongs to it - * @param threadFactory the {@link ThreadFactory} which will be used for the used {@link Thread} - * @param addTaskWakesUp {@code true} if and only if invocation of {@link #addTask(Runnable)} will wake up the - * executor thread - */ - protected SingleThreadEventExecutor( - EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp) { - - if (threadFactory == null) { - throw new NullPointerException("threadFactory"); - } - - this.parent = parent; - this.addTaskWakesUp = addTaskWakesUp; - - thread = threadFactory.newThread(new Runnable() { - @Override - public void run() { - boolean success = false; - updateLastExecutionTime(); - try { - SingleThreadEventExecutor.this.run(); - success = true; - } catch (Throwable t) { - logger.warn("Unexpected exception from an event executor: ", t); - } finally { - for (;;) { - int oldState = STATE_UPDATER.get(SingleThreadEventExecutor.this); - if (oldState >= ST_SHUTTING_DOWN || STATE_UPDATER.compareAndSet( - SingleThreadEventExecutor.this, oldState, ST_SHUTTING_DOWN)) { - break; - } - } - // Check if confirmShutdown() was called at the end of the loop. - if (success && gracefulShutdownStartTime == 0) { - logger.error( - "Buggy " + EventExecutor.class.getSimpleName() + " implementation; " + - SingleThreadEventExecutor.class.getSimpleName() + ".confirmShutdown() must be called " + - "before run() implementation terminates."); - } - - try { - // Run all remaining tasks and shutdown hooks. - for (;;) { - if (confirmShutdown()) { - break; - } - } - } finally { - try { - cleanup(); - } finally { - STATE_UPDATER.set(SingleThreadEventExecutor.this, ST_TERMINATED); - threadLock.release(); - if (!taskQueue.isEmpty()) { - logger.warn( - "An event executor terminated with " + - "non-empty task queue (" + taskQueue.size() + ')'); - } - - terminationFuture.setSuccess(null); - } - } - } - } - }); - - taskQueue = newTaskQueue(); - } - - /** - * Create a new {@link Queue} which will holds the tasks to execute. This default implementation will return a - * {@link LinkedBlockingQueue} but if your sub-class of {@link SingleThreadEventExecutor} will not do any blocking - * calls on the this {@link Queue} it may make sense to {@code @Override} this and return some more performant - * implementation that does not support blocking operations at all. - */ - protected Queue newTaskQueue() { - return new LinkedBlockingQueue(); - } - - @Override - public EventExecutorGroup parent() { - return parent; - } - - /** - * Interrupt the current running {@link Thread}. - */ - protected void interruptThread() { - thread.interrupt(); - } - - /** - * @see {@link Queue#poll()} - */ - protected Runnable pollTask() { - assert inEventLoop(); - for (;;) { - Runnable task = taskQueue.poll(); - if (task == WAKEUP_TASK) { - continue; - } - return task; - } - } - - /** - * Take the next {@link Runnable} from the task queue and so will block if no task is currently present. - *

- * Be aware that this method will throw an {@link UnsupportedOperationException} if the task queue, which was - * created via {@link #newTaskQueue()}, does not implement {@link BlockingQueue}. - *

- * - * @return {@code null} if the executor thread has been interrupted or waken up. - */ - protected Runnable takeTask() { - assert inEventLoop(); - if (!(taskQueue instanceof BlockingQueue)) { - throw new UnsupportedOperationException(); - } - - BlockingQueue taskQueue = (BlockingQueue) this.taskQueue; - for (;;) { - ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); - if (delayedTask == null) { - Runnable task = null; - try { - task = taskQueue.take(); - if (task == WAKEUP_TASK) { - task = null; - } - } catch (InterruptedException e) { - // Ignore - } - return task; - } else { - long delayNanos = delayedTask.delayNanos(); - Runnable task = null; - if (delayNanos > 0) { - try { - task = taskQueue.poll(delayNanos, TimeUnit.NANOSECONDS); - } catch (InterruptedException e) { - return null; - } - } - if (task == null) { - // We need to fetch the delayed tasks now as otherwise there may be a chance that - // delayed tasks are never executed if there is always one task in the taskQueue. - // This is for example true for the read task of OIO Transport - // See https://github.com/netty/netty/issues/1614 - fetchFromDelayedQueue(); - task = taskQueue.poll(); - } - - if (task != null) { - return task; - } - } - } - } - - private void fetchFromDelayedQueue() { - long nanoTime = 0L; - for (;;) { - ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); - if (delayedTask == null) { - break; - } - - if (nanoTime == 0L) { - nanoTime = ScheduledFutureTask.nanoTime(); - } - - if (delayedTask.deadlineNanos() <= nanoTime) { - delayedTaskQueue.remove(); - taskQueue.add(delayedTask); - } else { - break; - } - } - } - - /** - * @see {@link Queue#peek()} - */ - protected Runnable peekTask() { - assert inEventLoop(); - return taskQueue.peek(); - } - - /** - * @see {@link Queue#isEmpty()} - */ - protected boolean hasTasks() { - assert inEventLoop(); - return !taskQueue.isEmpty(); - } - - /** - * Returns {@code true} if a scheduled task is ready for processing by {@link #runAllTasks()} or - * {@link #runAllTasks(long)}. - */ - protected boolean hasScheduledTasks() { - assert inEventLoop(); - ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); - return delayedTask != null && delayedTask.deadlineNanos() <= ScheduledFutureTask.nanoTime(); - } - - /** - * Return the number of tasks that are pending for processing. - * - * Be aware that this operation may be expensive as it depends on the internal implementation of the - * SingleThreadEventExecutor. So use it was care! - */ - public final int pendingTasks() { - return taskQueue.size(); - } - - /** - * Add a task to the task queue, or throws a {@link RejectedExecutionException} if this instance was shutdown - * before. - */ - protected void addTask(Runnable task) { - if (task == null) { - throw new NullPointerException("task"); - } - if (isShutdown()) { - reject(); - } - taskQueue.add(task); - } - - /** - * @see {@link Queue#remove(Object)} - */ - protected boolean removeTask(Runnable task) { - if (task == null) { - throw new NullPointerException("task"); - } - return taskQueue.remove(task); - } - - /** - * Poll all tasks from the task queue and run them via {@link Runnable#run()} method. - * - * @return {@code true} if and only if at least one task was run - */ - protected boolean runAllTasks() { - fetchFromDelayedQueue(); - Runnable task = pollTask(); - if (task == null) { - return false; - } - - for (;;) { - try { - task.run(); - } catch (Throwable t) { - logger.warn("A task raised an exception.", t); - } - - task = pollTask(); - if (task == null) { - lastExecutionTime = ScheduledFutureTask.nanoTime(); - return true; - } - } - } - - /** - * Poll all tasks from the task queue and run them via {@link Runnable#run()} method. This method stops running - * the tasks in the task queue and returns if it ran longer than {@code timeoutNanos}. - */ - protected boolean runAllTasks(long timeoutNanos) { - fetchFromDelayedQueue(); - Runnable task = pollTask(); - if (task == null) { - return false; - } - - final long deadline = ScheduledFutureTask.nanoTime() + timeoutNanos; - long runTasks = 0; - long lastExecutionTime; - for (;;) { - try { - task.run(); - } catch (Throwable t) { - logger.warn("A task raised an exception.", t); - } - - runTasks ++; - - // Check timeout every 64 tasks because nanoTime() is relatively expensive. - // XXX: Hard-coded value - will make it configurable if it is really a problem. - if ((runTasks & 0x3F) == 0) { - lastExecutionTime = ScheduledFutureTask.nanoTime(); - if (lastExecutionTime >= deadline) { - break; - } - } - - task = pollTask(); - if (task == null) { - lastExecutionTime = ScheduledFutureTask.nanoTime(); - break; - } - } - - this.lastExecutionTime = lastExecutionTime; - return true; - } - - /** - * Returns the amount of time left until the scheduled task with the closest dead line is executed. - */ - protected long delayNanos(long currentTimeNanos) { - ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); - if (delayedTask == null) { - return SCHEDULE_PURGE_INTERVAL; - } - - return delayedTask.delayNanos(currentTimeNanos); - } - - /** - * Updates the internal timestamp that tells when a submitted task was executed most recently. - * {@link #runAllTasks()} and {@link #runAllTasks(long)} updates this timestamp automatically, and thus there's - * usually no need to call this method. However, if you take the tasks manually using {@link #takeTask()} or - * {@link #pollTask()}, you have to call this method at the end of task execution loop for accurate quiet period - * checks. - */ - protected void updateLastExecutionTime() { - lastExecutionTime = ScheduledFutureTask.nanoTime(); - } - - /** - * - */ - protected abstract void run(); - - /** - * Do nothing, sub-classes may override - */ - protected void cleanup() { - // NOOP - } - - protected void wakeup(boolean inEventLoop) { - if (!inEventLoop || STATE_UPDATER.get(this) == ST_SHUTTING_DOWN) { - taskQueue.add(WAKEUP_TASK); - } - } - - @Override - public boolean inEventLoop(Thread thread) { - return thread == this.thread; - } - - /** - * Add a {@link Runnable} which will be executed on shutdown of this instance - */ - public void addShutdownHook(final Runnable task) { - if (inEventLoop()) { - shutdownHooks.add(task); - } else { - execute(new Runnable() { - @Override - public void run() { - shutdownHooks.add(task); - } - }); - } - } - - /** - * Remove a previous added {@link Runnable} as a shutdown hook - */ - public void removeShutdownHook(final Runnable task) { - if (inEventLoop()) { - shutdownHooks.remove(task); - } else { - execute(new Runnable() { - @Override - public void run() { - shutdownHooks.remove(task); - } - }); - } - } - - private boolean runShutdownHooks() { - boolean ran = false; - // Note shutdown hooks can add / remove shutdown hooks. - while (!shutdownHooks.isEmpty()) { - List copy = new ArrayList(shutdownHooks); - shutdownHooks.clear(); - for (Runnable task: copy) { - try { - task.run(); - } catch (Throwable t) { - logger.warn("Shutdown hook raised an exception.", t); - } finally { - ran = true; - } - } - } - - if (ran) { - lastExecutionTime = ScheduledFutureTask.nanoTime(); - } - - return ran; - } - - @Override - public Future shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { - if (quietPeriod < 0) { - throw new IllegalArgumentException("quietPeriod: " + quietPeriod + " (expected >= 0)"); - } - if (timeout < quietPeriod) { - throw new IllegalArgumentException( - "timeout: " + timeout + " (expected >= quietPeriod (" + quietPeriod + "))"); - } - if (unit == null) { - throw new NullPointerException("unit"); - } - - if (isShuttingDown()) { - return terminationFuture(); - } - - boolean inEventLoop = inEventLoop(); - boolean wakeup; - int oldState; - for (;;) { - if (isShuttingDown()) { - return terminationFuture(); - } - int newState; - wakeup = true; - oldState = STATE_UPDATER.get(this); - if (inEventLoop) { - newState = ST_SHUTTING_DOWN; - } else { - switch (oldState) { - case ST_NOT_STARTED: - case ST_STARTED: - newState = ST_SHUTTING_DOWN; - break; - default: - newState = oldState; - wakeup = false; - } - } - if (STATE_UPDATER.compareAndSet(this, oldState, newState)) { - break; - } - } - gracefulShutdownQuietPeriod = unit.toNanos(quietPeriod); - gracefulShutdownTimeout = unit.toNanos(timeout); - - if (oldState == ST_NOT_STARTED) { - thread.start(); - } - - if (wakeup) { - wakeup(inEventLoop); - } - - return terminationFuture(); - } - - @Override - public Future terminationFuture() { - return terminationFuture; - } - - @Override - @Deprecated - public void shutdown() { - if (isShutdown()) { - return; - } - - boolean inEventLoop = inEventLoop(); - boolean wakeup; - int oldState; - for (;;) { - if (isShuttingDown()) { - return; - } - int newState; - wakeup = true; - oldState = STATE_UPDATER.get(this); - if (inEventLoop) { - newState = ST_SHUTDOWN; - } else { - switch (oldState) { - case ST_NOT_STARTED: - case ST_STARTED: - case ST_SHUTTING_DOWN: - newState = ST_SHUTDOWN; - break; - default: - newState = oldState; - wakeup = false; - } - } - if (STATE_UPDATER.compareAndSet(this, oldState, newState)) { - break; - } - } - - if (oldState == ST_NOT_STARTED) { - thread.start(); - } - - if (wakeup) { - wakeup(inEventLoop); - } - } - - @Override - public boolean isShuttingDown() { - return STATE_UPDATER.get(this) >= ST_SHUTTING_DOWN; - } - - @Override - public boolean isShutdown() { - return STATE_UPDATER.get(this) >= ST_SHUTDOWN; - } - - @Override - public boolean isTerminated() { - return STATE_UPDATER.get(this) == ST_TERMINATED; - } - - /** - * Confirm that the shutdown if the instance should be done now! - */ - protected boolean confirmShutdown() { - if (!isShuttingDown()) { - return false; - } - - if (!inEventLoop()) { - throw new IllegalStateException("must be invoked from an event loop"); - } - - cancelDelayedTasks(); - - if (gracefulShutdownStartTime == 0) { - gracefulShutdownStartTime = ScheduledFutureTask.nanoTime(); - } - - if (runAllTasks() || runShutdownHooks()) { - if (isShutdown()) { - // Executor shut down - no new tasks anymore. - return true; - } - - // There were tasks in the queue. Wait a little bit more until no tasks are queued for the quiet period. - wakeup(true); - return false; - } - - final long nanoTime = ScheduledFutureTask.nanoTime(); - - if (isShutdown() || nanoTime - gracefulShutdownStartTime > gracefulShutdownTimeout) { - return true; - } - - if (nanoTime - lastExecutionTime <= gracefulShutdownQuietPeriod) { - // Check if any tasks were added to the queue every 100ms. - // TODO: Change the behavior of takeTask() so that it returns on timeout. - wakeup(true); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - // Ignore - } - - return false; - } - - // No tasks were added for last quiet period - hopefully safe to shut down. - // (Hopefully because we really cannot make a guarantee that there will be no execute() calls by a user.) - return true; - } - - private void cancelDelayedTasks() { - if (delayedTaskQueue.isEmpty()) { - return; - } - - final ScheduledFutureTask[] delayedTasks = - delayedTaskQueue.toArray(new ScheduledFutureTask[delayedTaskQueue.size()]); - - for (ScheduledFutureTask task: delayedTasks) { - task.cancel(false); - } - - delayedTaskQueue.clear(); - } - - @Override - public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { - if (unit == null) { - throw new NullPointerException("unit"); - } - - if (inEventLoop()) { - throw new IllegalStateException("cannot await termination of the current thread"); - } - - if (threadLock.tryAcquire(timeout, unit)) { - threadLock.release(); - } - - return isTerminated(); - } - - @Override - public void execute(Runnable task) { - if (task == null) { - throw new NullPointerException("task"); - } - - boolean inEventLoop = inEventLoop(); - if (inEventLoop) { - addTask(task); - } else { - startThread(); - addTask(task); - if (isShutdown() && removeTask(task)) { - reject(); - } - } - - if (!addTaskWakesUp && wakesUpForTask(task)) { - wakeup(inEventLoop); - } - } - - - protected boolean wakesUpForTask(Runnable task) { - return true; - } - - protected static void reject() { - throw new RejectedExecutionException("event executor terminated"); - } - - // ScheduledExecutorService implementation - - private static final long SCHEDULE_PURGE_INTERVAL = TimeUnit.SECONDS.toNanos(1); - - @Override - public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { - if (command == null) { - throw new NullPointerException("command"); - } - if (unit == null) { - throw new NullPointerException("unit"); - } - if (delay < 0) { - throw new IllegalArgumentException( - String.format("delay: %d (expected: >= 0)", delay)); - } - return schedule(new ScheduledFutureTask( - this, delayedTaskQueue, command, null, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay)))); - } - - @Override - public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { - if (callable == null) { - throw new NullPointerException("callable"); - } - if (unit == null) { - throw new NullPointerException("unit"); - } - if (delay < 0) { - throw new IllegalArgumentException( - String.format("delay: %d (expected: >= 0)", delay)); - } - return schedule(new ScheduledFutureTask( - this, delayedTaskQueue, callable, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay)))); - } - - @Override - public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { - if (command == null) { - throw new NullPointerException("command"); - } - if (unit == null) { - throw new NullPointerException("unit"); - } - if (initialDelay < 0) { - throw new IllegalArgumentException( - String.format("initialDelay: %d (expected: >= 0)", initialDelay)); - } - if (period <= 0) { - throw new IllegalArgumentException( - String.format("period: %d (expected: > 0)", period)); - } - - return schedule(new ScheduledFutureTask( - this, delayedTaskQueue, Executors.callable(command, null), - ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), unit.toNanos(period))); - } - - @Override - public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { - if (command == null) { - throw new NullPointerException("command"); - } - if (unit == null) { - throw new NullPointerException("unit"); - } - if (initialDelay < 0) { - throw new IllegalArgumentException( - String.format("initialDelay: %d (expected: >= 0)", initialDelay)); - } - if (delay <= 0) { - throw new IllegalArgumentException( - String.format("delay: %d (expected: > 0)", delay)); - } - - return schedule(new ScheduledFutureTask( - this, delayedTaskQueue, Executors.callable(command, null), - ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), -unit.toNanos(delay))); - } - - private ScheduledFuture schedule(final ScheduledFutureTask task) { - if (task == null) { - throw new NullPointerException("task"); - } - - if (inEventLoop()) { - delayedTaskQueue.add(task); - } else { - execute(new Runnable() { - @Override - public void run() { - delayedTaskQueue.add(task); - } - }); - } - - return task; - } - - private void startThread() { - if (STATE_UPDATER.get(this) == ST_NOT_STARTED) { - if (STATE_UPDATER.compareAndSet(this, ST_NOT_STARTED, ST_STARTED)) { - delayedTaskQueue.add(new ScheduledFutureTask( - this, delayedTaskQueue, Executors.callable(new PurgeTask(), null), - ScheduledFutureTask.deadlineNanos(SCHEDULE_PURGE_INTERVAL), -SCHEDULE_PURGE_INTERVAL)); - thread.start(); - } - } - } - - private final class PurgeTask implements Runnable { - @Override - public void run() { - Iterator> i = delayedTaskQueue.iterator(); - while (i.hasNext()) { - ScheduledFutureTask task = i.next(); - if (task.isCancelled()) { - i.remove(); - } - } - } - } -} diff --git a/common/src/main/java/common/net/util/concurrent/SucceededFuture.java b/common/src/main/java/common/net/util/concurrent/SucceededFuture.java deleted file mode 100644 index ddcd86f..0000000 --- a/common/src/main/java/common/net/util/concurrent/SucceededFuture.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.concurrent; - -/** - * The {@link CompleteFuture} which is succeeded already. It is - * recommended to use {@link EventExecutor#newSucceededFuture(Object)} instead of - * calling the constructor of this future. - */ -public final class SucceededFuture extends CompleteFuture { - private final V result; - - /** - * Creates a new instance. - * - * @param executor the {@link EventExecutor} associated with this future - */ - public SucceededFuture(EventExecutor executor, V result) { - super(executor); - this.result = result; - } - - @Override - public Throwable cause() { - return null; - } - - @Override - public boolean isSuccess() { - return true; - } - - @Override - public V getNow() { - return result; - } -} diff --git a/common/src/main/java/common/net/util/internal/EmptyArrays.java b/common/src/main/java/common/net/util/internal/EmptyArrays.java deleted file mode 100644 index e5fac07..0000000 --- a/common/src/main/java/common/net/util/internal/EmptyArrays.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -import java.nio.ByteBuffer; -import java.security.cert.X509Certificate; - -public final class EmptyArrays { - - public static final byte[] EMPTY_BYTES = new byte[0]; - public static final boolean[] EMPTY_BOOLEANS = new boolean[0]; - public static final double[] EMPTY_DOUBLES = new double[0]; - public static final float[] EMPTY_FLOATS = new float[0]; - public static final int[] EMPTY_INTS = new int[0]; - public static final short[] EMPTY_SHORTS = new short[0]; - public static final long[] EMPTY_LONGS = new long[0]; - public static final Object[] EMPTY_OBJECTS = new Object[0]; - public static final Class[] EMPTY_CLASSES = new Class[0]; - public static final String[] EMPTY_STRINGS = new String[0]; - public static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0]; - public static final ByteBuffer[] EMPTY_BYTE_BUFFERS = new ByteBuffer[0]; - public static final X509Certificate[] EMPTY_X509_CERTIFICATES = new X509Certificate[0]; - - private EmptyArrays() { } -} diff --git a/common/src/main/java/common/net/util/internal/IntegerHolder.java b/common/src/main/java/common/net/util/internal/IntegerHolder.java deleted file mode 100644 index 992a27c..0000000 --- a/common/src/main/java/common/net/util/internal/IntegerHolder.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -public final class IntegerHolder { - public int value; -} diff --git a/common/src/main/java/common/net/util/internal/InternalThreadLocalMap.java b/common/src/main/java/common/net/util/internal/InternalThreadLocalMap.java deleted file mode 100644 index 85565f0..0000000 --- a/common/src/main/java/common/net/util/internal/InternalThreadLocalMap.java +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.util.Arrays; -import java.util.IdentityHashMap; -import java.util.Map; -import java.util.WeakHashMap; - -import common.net.util.concurrent.FastThreadLocalThread; - -/** - * The internal data structure that stores the thread-local variables for Netty and all {@link FastThreadLocal}s. - * Note that this class is for internal use only and is subject to change at any time. Use {@link FastThreadLocal} - * unless you know what you are doing. - */ -public final class InternalThreadLocalMap extends UnpaddedInternalThreadLocalMap { - - public static final Object UNSET = new Object(); - - public static InternalThreadLocalMap getIfSet() { - Thread thread = Thread.currentThread(); - InternalThreadLocalMap threadLocalMap; - if (thread instanceof FastThreadLocalThread) { - threadLocalMap = ((FastThreadLocalThread) thread).threadLocalMap(); - } else { - ThreadLocal slowThreadLocalMap = UnpaddedInternalThreadLocalMap.slowThreadLocalMap; - if (slowThreadLocalMap == null) { - threadLocalMap = null; - } else { - threadLocalMap = slowThreadLocalMap.get(); - } - } - return threadLocalMap; - } - - public static InternalThreadLocalMap get() { - Thread thread = Thread.currentThread(); - if (thread instanceof FastThreadLocalThread) { - return fastGet((FastThreadLocalThread) thread); - } else { - return slowGet(); - } - } - - private static InternalThreadLocalMap fastGet(FastThreadLocalThread thread) { - InternalThreadLocalMap threadLocalMap = thread.threadLocalMap(); - if (threadLocalMap == null) { - thread.setThreadLocalMap(threadLocalMap = new InternalThreadLocalMap()); - } - return threadLocalMap; - } - - private static InternalThreadLocalMap slowGet() { - ThreadLocal slowThreadLocalMap = UnpaddedInternalThreadLocalMap.slowThreadLocalMap; - if (slowThreadLocalMap == null) { - UnpaddedInternalThreadLocalMap.slowThreadLocalMap = - slowThreadLocalMap = new ThreadLocal(); - } - - InternalThreadLocalMap ret = slowThreadLocalMap.get(); - if (ret == null) { - ret = new InternalThreadLocalMap(); - slowThreadLocalMap.set(ret); - } - return ret; - } - - public static void remove() { - Thread thread = Thread.currentThread(); - if (thread instanceof FastThreadLocalThread) { - ((FastThreadLocalThread) thread).setThreadLocalMap(null); - } else { - ThreadLocal slowThreadLocalMap = UnpaddedInternalThreadLocalMap.slowThreadLocalMap; - if (slowThreadLocalMap != null) { - slowThreadLocalMap.remove(); - } - } - } - - public static void destroy() { - slowThreadLocalMap = null; - } - - public static int nextVariableIndex() { - int index = nextIndex.getAndIncrement(); - if (index < 0) { - nextIndex.decrementAndGet(); - throw new IllegalStateException("too many thread-local indexed variables"); - } - return index; - } - - public static int lastVariableIndex() { - return nextIndex.get() - 1; - } - - // Cache line padding (must be public) - // With CompressedOops enabled, an instance of this class should occupy at least 128 bytes. - public long rp1, rp2, rp3, rp4, rp5, rp6, rp7, rp8, rp9; - - private InternalThreadLocalMap() { - super(newIndexedVariableTable()); - } - - private static Object[] newIndexedVariableTable() { - Object[] array = new Object[32]; - Arrays.fill(array, UNSET); - return array; - } - - public int size() { - int count = 0; - - if (futureListenerStackDepth != 0) { - count ++; - } - if (localChannelReaderStackDepth != 0) { - count ++; - } - if (handlerSharableCache != null) { - count ++; - } - if (counterHashCode != null) { - count ++; - } - if (random != null) { - count ++; - } - if (typeParameterMatcherGetCache != null) { - count ++; - } - if (typeParameterMatcherFindCache != null) { - count ++; - } - if (stringBuilder != null) { - count ++; - } - if (charsetEncoderCache != null) { - count ++; - } - if (charsetDecoderCache != null) { - count ++; - } - - for (Object o: indexedVariables) { - if (o != UNSET) { - count ++; - } - } - - // We should subtract 1 from the count because the first element in 'indexedVariables' is reserved - // by 'FastThreadLocal' to keep the list of 'FastThreadLocal's to remove on 'FastThreadLocal.removeAll()'. - return count - 1; - } - - public StringBuilder stringBuilder() { - StringBuilder builder = stringBuilder; - if (builder == null) { - stringBuilder = builder = new StringBuilder(512); - } else { - builder.setLength(0); - } - return builder; - } - - public Map charsetEncoderCache() { - Map cache = charsetEncoderCache; - if (cache == null) { - charsetEncoderCache = cache = new IdentityHashMap(); - } - return cache; - } - - public Map charsetDecoderCache() { - Map cache = charsetDecoderCache; - if (cache == null) { - charsetDecoderCache = cache = new IdentityHashMap(); - } - return cache; - } - - public int futureListenerStackDepth() { - return futureListenerStackDepth; - } - - public void setFutureListenerStackDepth(int futureListenerStackDepth) { - this.futureListenerStackDepth = futureListenerStackDepth; - } - - public ThreadLocalRandom random() { - ThreadLocalRandom r = random; - if (r == null) { - random = r = new ThreadLocalRandom(); - } - return r; - } - - public Map, TypeParameterMatcher> typeParameterMatcherGetCache() { - Map, TypeParameterMatcher> cache = typeParameterMatcherGetCache; - if (cache == null) { - typeParameterMatcherGetCache = cache = new IdentityHashMap, TypeParameterMatcher>(); - } - return cache; - } - - public Map, Map> typeParameterMatcherFindCache() { - Map, Map> cache = typeParameterMatcherFindCache; - if (cache == null) { - typeParameterMatcherFindCache = cache = new IdentityHashMap, Map>(); - } - return cache; - } - - public IntegerHolder counterHashCode() { - return counterHashCode; - } - - public void setCounterHashCode(IntegerHolder counterHashCode) { - this.counterHashCode = counterHashCode; - } - - public Map, Boolean> handlerSharableCache() { - Map, Boolean> cache = handlerSharableCache; - if (cache == null) { - // Start with small capacity to keep memory overhead as low as possible. - handlerSharableCache = cache = new WeakHashMap, Boolean>(4); - } - return cache; - } - - public int localChannelReaderStackDepth() { - return localChannelReaderStackDepth; - } - - public void setLocalChannelReaderStackDepth(int localChannelReaderStackDepth) { - this.localChannelReaderStackDepth = localChannelReaderStackDepth; - } - - public Object indexedVariable(int index) { - Object[] lookup = indexedVariables; - return index < lookup.length? lookup[index] : UNSET; - } - - /** - * @return {@code true} if and only if a new thread-local variable has been created - */ - public boolean setIndexedVariable(int index, Object value) { - Object[] lookup = indexedVariables; - if (index < lookup.length) { - Object oldValue = lookup[index]; - lookup[index] = value; - return oldValue == UNSET; - } else { - expandIndexedVariableTableAndSet(index, value); - return true; - } - } - - private void expandIndexedVariableTableAndSet(int index, Object value) { - Object[] oldArray = indexedVariables; - final int oldCapacity = oldArray.length; - int newCapacity = index; - newCapacity |= newCapacity >>> 1; - newCapacity |= newCapacity >>> 2; - newCapacity |= newCapacity >>> 4; - newCapacity |= newCapacity >>> 8; - newCapacity |= newCapacity >>> 16; - newCapacity ++; - - Object[] newArray = Arrays.copyOf(oldArray, newCapacity); - Arrays.fill(newArray, oldCapacity, newArray.length, UNSET); - newArray[index] = value; - indexedVariables = newArray; - } - - public Object removeIndexedVariable(int index) { - Object[] lookup = indexedVariables; - if (index < lookup.length) { - Object v = lookup[index]; - lookup[index] = UNSET; - return v; - } else { - return UNSET; - } - } - - public boolean isIndexedVariableSet(int index) { - Object[] lookup = indexedVariables; - return index < lookup.length && lookup[index] != UNSET; - } -} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueue.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueue.java deleted file mode 100644 index 0e6f378..0000000 --- a/common/src/main/java/common/net/util/internal/MpscLinkedQueue.java +++ /dev/null @@ -1,397 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/** - * Copyright (C) 2009-2013 Typesafe Inc. - */ -package common.net.util.internal; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Queue; - -/** - * A lock-free concurrent single-consumer multi-producer {@link Queue}. - * It allows multiple producer threads to perform the following operations simultaneously: - *
    - *
  • {@link #offer(Object)}, {@link #add(Object)}, and {@link #addAll(Collection)}
  • - *
  • All other read-only operations: - *
      - *
    • {@link #contains(Object)} and {@link #containsAll(Collection)}
    • - *
    • {@link #element()}, {@link #peek()}
    • - *
    • {@link #size()} and {@link #isEmpty()}
    • - *
    • {@link #iterator()} (except {@link Iterator#remove()}
    • - *
    • {@link #toArray()} and {@link #toArray(Object[])}
    • - *
    - *
  • - *
- * .. while only one consumer thread is allowed to perform the following operations exclusively: - *
    - *
  • {@link #poll()} and {@link #remove()}
  • - *
  • {@link #remove(Object)}, {@link #removeAll(Collection)}, and {@link #retainAll(Collection)}
  • - *
  • {@link #clear()}
  • {@link #} - *
- * - * The behavior of this implementation is undefined if you perform the operations for a consumer thread only - * from multiple threads. - * - * The initial implementation is based on: - * - * and adopted padded head node changes from: - * - * data structure modified to avoid false sharing between head and tail Ref as per implementation of MpscLinkedQueue - * on JCTools project. - */ -public final class MpscLinkedQueue extends MpscLinkedQueueTailRef implements Queue { - - private static final long serialVersionUID = -1878402552271506449L; - - long p00, p01, p02, p03, p04, p05, p06, p07; - long p30, p31, p32, p33, p34, p35, p36, p37; - - // offer() occurs at the tail of the linked list. - // poll() occurs at the head of the linked list. - // - // Resulting layout is: - // - // head --next--> 1st element --next--> 2nd element --next--> ... tail (last element) - // - // where the head is a dummy node whose value is null. - // - // offer() appends a new node next to the tail using AtomicReference.getAndSet() - // poll() removes head from the linked list and promotes the 1st element to the head, - // setting its value to null if possible. - // - // Also note that this class extends AtomicReference for the "tail" slot (which is the one that is appended to) - // since Unsafe does not expose XCHG operation intrinsically. - public MpscLinkedQueue() { - MpscLinkedQueueNode tombstone = new DefaultNode(null); - setHeadRef(tombstone); - setTailRef(tombstone); - } - - /** - * Returns the node right next to the head, which contains the first element of this queue. - */ - private MpscLinkedQueueNode peekNode() { - for (;;) { - final MpscLinkedQueueNode head = headRef(); - final MpscLinkedQueueNode next = head.next(); - if (next != null) { - return next; - } - if (head == tailRef()) { - return null; - } - - // If we are here, it means: - // * offer() is adding the first element, and - // * it's between replaceTail(newTail) and oldTail.setNext(newTail). - // (i.e. next == oldTail and oldTail.next == null and head == oldTail != newTail) - } - } - - @Override - - public boolean offer(E value) { - if (value == null) { - throw new NullPointerException("value"); - } - - final MpscLinkedQueueNode newTail; - if (value instanceof MpscLinkedQueueNode) { - newTail = (MpscLinkedQueueNode) value; - newTail.setNext(null); - } else { - newTail = new DefaultNode(value); - } - - MpscLinkedQueueNode oldTail = getAndSetTailRef(newTail); - oldTail.setNext(newTail); - return true; - } - - @Override - public E poll() { - final MpscLinkedQueueNode next = peekNode(); - if (next == null) { - return null; - } - - // next becomes a new head. - MpscLinkedQueueNode oldHead = headRef(); - // Similar to 'headRef.node = next', but slightly faster (storestore vs loadstore) - // See: http://robsjava.blogspot.com/2013/06/a-faster-volatile.html - // See: http://psy-lob-saw.blogspot.com/2012/12/atomiclazyset-is-performance-win-for.html - lazySetHeadRef(next); - - // Break the linkage between the old head and the new head. - oldHead.unlink(); - - return next.clearMaybe(); - } - - @Override - public E peek() { - final MpscLinkedQueueNode next = peekNode(); - if (next == null) { - return null; - } - return next.value(); - } - - @Override - public int size() { - int count = 0; - MpscLinkedQueueNode n = peekNode(); - for (;;) { - if (n == null) { - break; - } - count ++; - n = n.next(); - } - return count; - } - - @Override - public boolean isEmpty() { - return peekNode() == null; - } - - @Override - public boolean contains(Object o) { - MpscLinkedQueueNode n = peekNode(); - for (;;) { - if (n == null) { - break; - } - if (n.value() == o) { - return true; - } - n = n.next(); - } - return false; - } - - @Override - public Iterator iterator() { - return new Iterator() { - private MpscLinkedQueueNode node = peekNode(); - - @Override - public boolean hasNext() { - return node != null; - } - - @Override - public E next() { - MpscLinkedQueueNode node = this.node; - if (node == null) { - throw new NoSuchElementException(); - } - E value = node.value(); - this.node = node.next(); - return value; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - - @Override - public boolean add(E e) { - if (offer(e)) { - return true; - } - throw new IllegalStateException("queue full"); - } - - @Override - public E remove() { - E e = poll(); - if (e != null) { - return e; - } - throw new NoSuchElementException(); - } - - @Override - public E element() { - E e = peek(); - if (e != null) { - return e; - } - throw new NoSuchElementException(); - } - - @Override - public Object[] toArray() { - final Object[] array = new Object[size()]; - final Iterator it = iterator(); - for (int i = 0; i < array.length; i ++) { - if (it.hasNext()) { - array[i] = it.next(); - } else { - return Arrays.copyOf(array, i); - } - } - return array; - } - - @Override - - public T[] toArray(T[] a) { - final int size = size(); - final T[] array; - if (a.length >= size) { - array = a; - } else { - array = (T[]) Array.newInstance(a.getClass().getComponentType(), size); - } - - final Iterator it = iterator(); - for (int i = 0; i < array.length; i++) { - if (it.hasNext()) { - array[i] = (T) it.next(); - } else { - if (a == array) { - array[i] = null; - return array; - } - - if (a.length < i) { - return Arrays.copyOf(array, i); - } - - System.arraycopy(array, 0, a, 0, i); - if (a.length > i) { - a[i] = null; - } - return a; - } - } - return array; - } - - @Override - public boolean remove(Object o) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean containsAll(Collection c) { - for (Object e: c) { - if (!contains(e)) { - return false; - } - } - return true; - } - - @Override - public boolean addAll(Collection c) { - if (c == null) { - throw new NullPointerException("c"); - } - if (c == this) { - throw new IllegalArgumentException("c == this"); - } - - boolean modified = false; - for (E e: c) { - add(e); - modified = true; - } - return modified; - } - - @Override - public boolean removeAll(Collection c) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean retainAll(Collection c) { - throw new UnsupportedOperationException(); - } - - @Override - public void clear() { - while (poll() != null) { - continue; - } - } - - private void writeObject(ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - for (E e: this) { - out.writeObject(e); - } - out.writeObject(null); - } - - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - - final MpscLinkedQueueNode tombstone = new DefaultNode(null); - setHeadRef(tombstone); - setTailRef(tombstone); - - for (;;) { - - E e = (E) in.readObject(); - if (e == null) { - break; - } - add(e); - } - } - - private static final class DefaultNode extends MpscLinkedQueueNode { - - private T value; - - DefaultNode(T value) { - this.value = value; - } - - @Override - public T value() { - return value; - } - - @Override - protected T clearMaybe() { - T value = this.value; - this.value = null; - return value; - } - } -} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueueHeadRef.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueueHeadRef.java deleted file mode 100644 index fc70e65..0000000 --- a/common/src/main/java/common/net/util/internal/MpscLinkedQueueHeadRef.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -import java.io.Serializable; -import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; - - -abstract class MpscLinkedQueueHeadRef extends MpscLinkedQueuePad0 implements Serializable { - - private static final long serialVersionUID = 8467054865577874285L; - - - private static final AtomicReferenceFieldUpdater UPDATER; - - static { - - AtomicReferenceFieldUpdater updater; - updater = null; - if (updater == null) { - updater = AtomicReferenceFieldUpdater.newUpdater( - MpscLinkedQueueHeadRef.class, MpscLinkedQueueNode.class, "headRef"); - } - UPDATER = updater; - } - - private transient volatile MpscLinkedQueueNode headRef; - - protected final MpscLinkedQueueNode headRef() { - return headRef; - } - - protected final void setHeadRef(MpscLinkedQueueNode headRef) { - this.headRef = headRef; - } - - protected final void lazySetHeadRef(MpscLinkedQueueNode headRef) { - UPDATER.lazySet(this, headRef); - } -} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueueNode.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueueNode.java deleted file mode 100644 index b44975f..0000000 --- a/common/src/main/java/common/net/util/internal/MpscLinkedQueueNode.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; - -public abstract class MpscLinkedQueueNode { - - - private static final AtomicReferenceFieldUpdater nextUpdater; - - static { - - AtomicReferenceFieldUpdater u; - - u = null; - if (u == null) { - u = AtomicReferenceFieldUpdater.newUpdater(MpscLinkedQueueNode.class, MpscLinkedQueueNode.class, "next"); - } - nextUpdater = u; - } - - - private volatile MpscLinkedQueueNode next; - - final MpscLinkedQueueNode next() { - return next; - } - - final void setNext(final MpscLinkedQueueNode newNext) { - // Similar to 'next = newNext', but slightly faster (storestore vs loadstore) - // See: http://robsjava.blogspot.com/2013/06/a-faster-volatile.html - nextUpdater.lazySet(this, newNext); - } - - public abstract T value(); - - /** - * Sets the element this node contains to {@code null} so that the node can be used as a tombstone. - */ - protected T clearMaybe() { - return value(); - } - - /** - * Unlink to allow GC'ed - */ - void unlink() { - setNext(null); - } -} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad0.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad0.java deleted file mode 100644 index 0fe9e45..0000000 --- a/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad0.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -abstract class MpscLinkedQueuePad0 { - long p00, p01, p02, p03, p04, p05, p06, p07; - long p30, p31, p32, p33, p34, p35, p36, p37; -} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad1.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad1.java deleted file mode 100644 index 6cfd53f..0000000 --- a/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad1.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -abstract class MpscLinkedQueuePad1 extends MpscLinkedQueueHeadRef { - - private static final long serialVersionUID = 2886694927079691637L; - - long p00, p01, p02, p03, p04, p05, p06, p07; - long p30, p31, p32, p33, p34, p35, p36, p37; -} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueueTailRef.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueueTailRef.java deleted file mode 100644 index 55f9537..0000000 --- a/common/src/main/java/common/net/util/internal/MpscLinkedQueueTailRef.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; - -abstract class MpscLinkedQueueTailRef extends MpscLinkedQueuePad1 { - - private static final long serialVersionUID = 8717072462993327429L; - - - private static final AtomicReferenceFieldUpdater UPDATER; - - static { - - AtomicReferenceFieldUpdater updater; - updater = null; - if (updater == null) { - updater = AtomicReferenceFieldUpdater.newUpdater( - MpscLinkedQueueTailRef.class, MpscLinkedQueueNode.class, "tailRef"); - } - UPDATER = updater; - } - - private transient volatile MpscLinkedQueueNode tailRef; - - protected final MpscLinkedQueueNode tailRef() { - return tailRef; - } - - protected final void setTailRef(MpscLinkedQueueNode tailRef) { - this.tailRef = tailRef; - } - - - protected final MpscLinkedQueueNode getAndSetTailRef(MpscLinkedQueueNode tailRef) { - // LOCK XCHG in JDK8, a CAS loop in JDK 7/6 - return (MpscLinkedQueueNode) UPDATER.getAndSet(this, tailRef); - } -} diff --git a/common/src/main/java/common/net/util/internal/NoOpTypeParameterMatcher.java b/common/src/main/java/common/net/util/internal/NoOpTypeParameterMatcher.java deleted file mode 100644 index fe4d34f..0000000 --- a/common/src/main/java/common/net/util/internal/NoOpTypeParameterMatcher.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -public final class NoOpTypeParameterMatcher extends TypeParameterMatcher { - @Override - public boolean match(Object msg) { - return true; - } -} diff --git a/common/src/main/java/common/net/util/internal/OneTimeTask.java b/common/src/main/java/common/net/util/internal/OneTimeTask.java deleted file mode 100644 index 7fdb8ae..0000000 --- a/common/src/main/java/common/net/util/internal/OneTimeTask.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.internal; - -/** - * {@link Runnable} which represent a one time task which may allow the {@link EventExecutor} to reduce the amount of - * produced garbage when queue it for execution. - * - * It is important this will not be reused. After submitted it is not allowed to get submitted again! - */ -public abstract class OneTimeTask extends MpscLinkedQueueNode implements Runnable { - - @Override - public Runnable value() { - return this; - } -} diff --git a/common/src/main/java/common/net/util/internal/RecyclableArrayList.java b/common/src/main/java/common/net/util/internal/RecyclableArrayList.java deleted file mode 100644 index 739a077..0000000 --- a/common/src/main/java/common/net/util/internal/RecyclableArrayList.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.RandomAccess; - -import common.net.util.Recycler; -import common.net.util.Recycler.Handle; - -/** - * A simple list which is reyclable. This implementation does not allow {@code null} elements to be added. - */ -public final class RecyclableArrayList extends ArrayList { - - private static final long serialVersionUID = -8605125654176467947L; - - private static final int DEFAULT_INITIAL_CAPACITY = 8; - - private static final Recycler RECYCLER = new Recycler() { - @Override - protected RecyclableArrayList newObject(Handle handle) { - return new RecyclableArrayList(handle); - } - }; - - /** - * Create a new empty {@link RecyclableArrayList} instance - */ - public static RecyclableArrayList newInstance() { - return newInstance(DEFAULT_INITIAL_CAPACITY); - } - - /** - * Create a new empty {@link RecyclableArrayList} instance with the given capacity. - */ - public static RecyclableArrayList newInstance(int minCapacity) { - RecyclableArrayList ret = RECYCLER.get(); - ret.ensureCapacity(minCapacity); - return ret; - } - - private final Handle handle; - - private RecyclableArrayList(Handle handle) { - this(handle, DEFAULT_INITIAL_CAPACITY); - } - - private RecyclableArrayList(Handle handle, int initialCapacity) { - super(initialCapacity); - this.handle = handle; - } - - @Override - public boolean addAll(Collection c) { - checkNullElements(c); - return super.addAll(c); - } - - @Override - public boolean addAll(int index, Collection c) { - checkNullElements(c); - return super.addAll(index, c); - } - - private static void checkNullElements(Collection c) { - if (c instanceof RandomAccess && c instanceof List) { - // produce less garbage - List list = (List) c; - int size = list.size(); - for (int i = 0; i < size; i++) { - if (list.get(i) == null) { - throw new IllegalArgumentException("c contains null values"); - } - } - } else { - for (Object element: c) { - if (element == null) { - throw new IllegalArgumentException("c contains null values"); - } - } - } - } - - @Override - public boolean add(Object element) { - if (element == null) { - throw new NullPointerException("element"); - } - return super.add(element); - } - - @Override - public void add(int index, Object element) { - if (element == null) { - throw new NullPointerException("element"); - } - super.add(index, element); - } - - @Override - public Object set(int index, Object element) { - if (element == null) { - throw new NullPointerException("element"); - } - return super.set(index, element); - } - - /** - * Clear and recycle this instance. - */ - public boolean recycle() { - clear(); - return RECYCLER.recycle(this, handle); - } -} diff --git a/common/src/main/java/common/net/util/internal/RecyclableMpscLinkedQueueNode.java b/common/src/main/java/common/net/util/internal/RecyclableMpscLinkedQueueNode.java deleted file mode 100644 index a037070..0000000 --- a/common/src/main/java/common/net/util/internal/RecyclableMpscLinkedQueueNode.java +++ /dev/null @@ -1,45 +0,0 @@ -/* -* Copyright 2014 The Netty Project -* -* The Netty Project licenses this file to you under the Apache License, -* version 2.0 (the "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at: -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -* License for the specific language governing permissions and limitations -* under the License. -*/ - -package common.net.util.internal; - -import common.net.util.Recycler; - -/** - * {@link MpscLinkedQueueNode} that will automatically call {@link #recycle(Recycler.Handle)} when the node was - * unlinked. - */ -public abstract class RecyclableMpscLinkedQueueNode extends MpscLinkedQueueNode { - private final Recycler.Handle handle; - - protected RecyclableMpscLinkedQueueNode(Recycler.Handle handle) { - if (handle == null) { - throw new NullPointerException("handle"); - } - this.handle = handle; - } - - @Override - final void unlink() { - super.unlink(); - recycle(handle); - } - - /** - * Called once unliked and so ready to recycled. - */ - protected abstract void recycle(Recycler.Handle handle); -} diff --git a/common/src/main/java/common/net/util/internal/StringUtil.java b/common/src/main/java/common/net/util/internal/StringUtil.java deleted file mode 100644 index 1716baa..0000000 --- a/common/src/main/java/common/net/util/internal/StringUtil.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.internal; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Formatter; -import java.util.List; - -import common.util.Util; - -/** - * String utility class. - */ -public final class StringUtil { - - public static final String NEWLINE; - - private static final String[] BYTE2HEX_PAD = new String[256]; - private static final String[] BYTE2HEX_NOPAD = new String[256]; - private static final String EMPTY_STRING = ""; - - static { - // Determine the newline character of the current platform. - String newLine; - Formatter formatter = null; - - try { - formatter = new Formatter(); - newLine = formatter.format("%n").toString(); - } catch (Exception e) { - // Should not reach here, but just in case. - newLine = "\n"; - } - finally { - if(formatter != null) { - try { - formatter.close(); - } - catch(Throwable e) { - } - } - } - - NEWLINE = newLine; - - // Generate the lookup table that converts a byte into a 2-digit hexadecimal integer. - int i; - for (i = 0; i < 10; i ++) { - StringBuilder buf = new StringBuilder(2); - buf.append('0'); - buf.append(i); - BYTE2HEX_PAD[i] = buf.toString(); - BYTE2HEX_NOPAD[i] = String.valueOf(i); - } - for (; i < 16; i ++) { - StringBuilder buf = new StringBuilder(2); - char c = (char) ('a' + i - 10); - buf.append('0'); - buf.append(c); - BYTE2HEX_PAD[i] = buf.toString(); - BYTE2HEX_NOPAD[i] = String.valueOf(c); - } - for (; i < BYTE2HEX_PAD.length; i ++) { - StringBuilder buf = new StringBuilder(2); - buf.append(Integer.toHexString(i)); - String str = buf.toString(); - BYTE2HEX_PAD[i] = str; - BYTE2HEX_NOPAD[i] = str; - } - } - - /** - * Splits the specified {@link String} with the specified delimiter. This operation is a simplified and optimized - * version of {@link String#split(String)}. - */ - public static String[] split(String value, char delim) { - final int end = value.length(); - final List res = new ArrayList(); - - int start = 0; - for (int i = 0; i < end; i ++) { - if (value.charAt(i) == delim) { - if (start == i) { - res.add(EMPTY_STRING); - } else { - res.add(value.substring(start, i)); - } - start = i + 1; - } - } - - if (start == 0) { // If no delimiter was found in the value - res.add(value); - } else { - if (start != end) { - // Add the last element if it's not empty. - res.add(value.substring(start, end)); - } else { - // Truncate trailing empty elements. - for (int i = res.size() - 1; i >= 0; i --) { - if (res.get(i).isEmpty()) { - res.remove(i); - } else { - break; - } - } - } - } - - return res.toArray(new String[res.size()]); - } - - /** - * Converts the specified byte value into a 2-digit hexadecimal integer. - */ - public static String byteToHexStringPadded(int value) { - return BYTE2HEX_PAD[value & 0xff]; - } - - /** - * Converts the specified byte value into a 2-digit hexadecimal integer and appends it to the specified buffer. - */ - public static T byteToHexStringPadded(T buf, int value) { - try { - buf.append(byteToHexStringPadded(value)); - } catch (IOException e) { - Util.throwUnchecked(e); - } - return buf; - } - - /** - * Converts the specified byte array into a hexadecimal value. - */ - public static String toHexStringPadded(byte[] src) { - return toHexStringPadded(src, 0, src.length); - } - - /** - * Converts the specified byte array into a hexadecimal value. - */ - public static String toHexStringPadded(byte[] src, int offset, int length) { - return toHexStringPadded(new StringBuilder(length << 1), src, offset, length).toString(); - } - - /** - * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer. - */ - public static T toHexStringPadded(T dst, byte[] src) { - return toHexStringPadded(dst, src, 0, src.length); - } - - /** - * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer. - */ - public static T toHexStringPadded(T dst, byte[] src, int offset, int length) { - final int end = offset + length; - for (int i = offset; i < end; i ++) { - byteToHexStringPadded(dst, src[i]); - } - return dst; - } - - /** - * Converts the specified byte value into a hexadecimal integer. - */ - public static String byteToHexString(int value) { - return BYTE2HEX_NOPAD[value & 0xff]; - } - - /** - * Converts the specified byte value into a hexadecimal integer and appends it to the specified buffer. - */ - public static T byteToHexString(T buf, int value) { - try { - buf.append(byteToHexString(value)); - } catch (IOException e) { - Util.throwUnchecked(e); - } - return buf; - } - - /** - * Converts the specified byte array into a hexadecimal value. - */ - public static String toHexString(byte[] src) { - return toHexString(src, 0, src.length); - } - - /** - * Converts the specified byte array into a hexadecimal value. - */ - public static String toHexString(byte[] src, int offset, int length) { - return toHexString(new StringBuilder(length << 1), src, offset, length).toString(); - } - - /** - * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer. - */ - public static T toHexString(T dst, byte[] src) { - return toHexString(dst, src, 0, src.length); - } - - /** - * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer. - */ - public static T toHexString(T dst, byte[] src, int offset, int length) { - assert length >= 0; - if (length == 0) { - return dst; - } - - final int end = offset + length; - final int endMinusOne = end - 1; - int i; - - // Skip preceding zeroes. - for (i = offset; i < endMinusOne; i ++) { - if (src[i] != 0) { - break; - } - } - - byteToHexString(dst, src[i ++]); - int remaining = end - i; - toHexStringPadded(dst, src, i, remaining); - - return dst; - } - - /** - * The shortcut to {@link #simpleClassName(Class) simpleClassName(o.getClass())}. - */ - public static String simpleClassName(Object o) { - if (o == null) { - return "null_object"; - } else { - return simpleClassName(o.getClass()); - } - } - - /** - * Generates a simplified name from a {@link Class}. Similar to {@link Class#getSimpleName()}, but it works fine - * with anonymous classes. - */ - public static String simpleClassName(Class clazz) { - if (clazz == null) { - return "null_class"; - } - - Package pkg = clazz.getPackage(); - if (pkg != null) { - return clazz.getName().substring(pkg.getName().length() + 1); - } else { - return clazz.getName(); - } - } - - private StringUtil() { - // Unused. - } -} diff --git a/common/src/main/java/common/net/util/internal/SystemPropertyUtil.java b/common/src/main/java/common/net/util/internal/SystemPropertyUtil.java deleted file mode 100644 index 1788bdb..0000000 --- a/common/src/main/java/common/net/util/internal/SystemPropertyUtil.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.internal; - -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; - -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * A collection of utility methods to retrieve and parse the values of the Java system properties. - */ -public final class SystemPropertyUtil { - - private static boolean initializedLogger; - private static final InternalLogger logger; - private static boolean loggedException; - - static { - initializedLogger = false; - logger = InternalLoggerFactory.getInstance(SystemPropertyUtil.class); - initializedLogger = true; - } - - /** - * Returns {@code true} if and only if the system property with the specified {@code key} - * exists. - */ - public static boolean contains(String key) { - return get(key) != null; - } - - /** - * Returns the value of the Java system property with the specified - * {@code key}, while falling back to {@code null} if the property access fails. - * - * @return the property value or {@code null} - */ - public static String get(String key) { - return get(key, null); - } - - /** - * Returns the value of the Java system property with the specified - * {@code key}, while falling back to the specified default value if - * the property access fails. - * - * @return the property value. - * {@code def} if there's no such property or if an access to the - * specified property is not allowed. - */ - public static String get(final String key, String def) { - if (key == null) { - throw new NullPointerException("key"); - } - if (key.isEmpty()) { - throw new IllegalArgumentException("key must not be empty."); - } - - String value = null; - try { - value = System.getProperty(key); - } catch (Exception e) { - if (!loggedException) { - log("Unable to retrieve a system property '" + key + "'; default values will be used.", e); - loggedException = true; - } - } - - if (value == null) { - return def; - } - - return value; - } - - /** - * Returns the value of the Java system property with the specified - * {@code key}, while falling back to the specified default value if - * the property access fails. - * - * @return the property value. - * {@code def} if there's no such property or if an access to the - * specified property is not allowed. - */ - public static boolean getBoolean(String key, boolean def) { - String value = get(key); - if (value == null) { - return def; - } - - value = value.trim().toLowerCase(); - if (value.isEmpty()) { - return true; - } - - if ("true".equals(value) || "yes".equals(value) || "1".equals(value)) { - return true; - } - - if ("false".equals(value) || "no".equals(value) || "0".equals(value)) { - return false; - } - - log( - "Unable to parse the boolean system property '" + key + "':" + value + " - " + - "using the default value: " + def); - - return def; - } - - private static final Pattern INTEGER_PATTERN = Pattern.compile("-?[0-9]+"); - - /** - * Returns the value of the Java system property with the specified - * {@code key}, while falling back to the specified default value if - * the property access fails. - * - * @return the property value. - * {@code def} if there's no such property or if an access to the - * specified property is not allowed. - */ - public static int getInt(String key, int def) { - String value = get(key); - if (value == null) { - return def; - } - - value = value.trim().toLowerCase(); - if (INTEGER_PATTERN.matcher(value).matches()) { - try { - return Integer.parseInt(value); - } catch (Exception e) { - // Ignore - } - } - - log( - "Unable to parse the integer system property '" + key + "':" + value + " - " + - "using the default value: " + def); - - return def; - } - - /** - * Returns the value of the Java system property with the specified - * {@code key}, while falling back to the specified default value if - * the property access fails. - * - * @return the property value. - * {@code def} if there's no such property or if an access to the - * specified property is not allowed. - */ - public static long getLong(String key, long def) { - String value = get(key); - if (value == null) { - return def; - } - - value = value.trim().toLowerCase(); - if (INTEGER_PATTERN.matcher(value).matches()) { - try { - return Long.parseLong(value); - } catch (Exception e) { - // Ignore - } - } - - log( - "Unable to parse the long integer system property '" + key + "':" + value + " - " + - "using the default value: " + def); - - return def; - } - - private static void log(String msg) { - if (initializedLogger) { - logger.warn(msg); - } else { - // Use JDK logging if logger was not initialized yet. - Logger.getLogger(SystemPropertyUtil.class.getName()).log(Level.WARNING, msg); - } - } - - private static void log(String msg, Exception e) { - if (initializedLogger) { - logger.warn(msg, e); - } else { - // Use JDK logging if logger was not initialized yet. - Logger.getLogger(SystemPropertyUtil.class.getName()).log(Level.WARNING, msg, e); - } - } - - private SystemPropertyUtil() { - // Unused - } -} diff --git a/common/src/main/java/common/net/util/internal/ThreadLocalRandom.java b/common/src/main/java/common/net/util/internal/ThreadLocalRandom.java deleted file mode 100644 index 0ad7360..0000000 --- a/common/src/main/java/common/net/util/internal/ThreadLocalRandom.java +++ /dev/null @@ -1,336 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/* - * Written by Doug Lea with assistance from members of JCP JSR-166 - * Expert Group and released to the public domain, as explained at - * http://creativecommons.org/publicdomain/zero/1.0/ - */ - -package common.net.util.internal; - -import java.lang.Thread.UncaughtExceptionHandler; -import java.security.SecureRandom; -import java.util.Random; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import common.net.util.internal.logging.InternalLogger; -import common.net.util.internal.logging.InternalLoggerFactory; - -/** - * A random number generator isolated to the current thread. Like the - * global {@link java.util.Random} generator used by the {@link - * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized - * with an internally generated seed that may not otherwise be - * modified. When applicable, use of {@code ThreadLocalRandom} rather - * than shared {@code Random} objects in concurrent programs will - * typically encounter much less overhead and contention. Use of - * {@code ThreadLocalRandom} is particularly appropriate when multiple - * tasks (for example, each a {@link game.net.util.internal.chmv8.ForkJoinTask}) use random numbers - * in parallel in thread pools. - * - *

Usages of this class should typically be of the form: - * {@code ThreadLocalRandom.current().nextX(...)} (where - * {@code X} is {@code Int}, {@code Long}, etc). - * When all usages are of this form, it is never possible to - * accidently share a {@code ThreadLocalRandom} across multiple threads. - * - *

This class also provides additional commonly used bounded random - * generation methods. - * - * //since 1.7 - * //author Doug Lea - */ - -public final class ThreadLocalRandom extends Random { - - private static final InternalLogger logger = InternalLoggerFactory.getInstance(ThreadLocalRandom.class); - - private static final AtomicLong seedUniquifier = new AtomicLong(); - - private static volatile long initialSeedUniquifier; - - public static void setInitialSeedUniquifier(long initialSeedUniquifier) { - ThreadLocalRandom.initialSeedUniquifier = initialSeedUniquifier; - } - - public static synchronized long getInitialSeedUniquifier() { - // Use the value set via the setter. - long initialSeedUniquifier = ThreadLocalRandom.initialSeedUniquifier; - if (initialSeedUniquifier == 0) { - // Use the system property value. - ThreadLocalRandom.initialSeedUniquifier = initialSeedUniquifier = - SystemPropertyUtil.getLong("game.net.initialSeedUniquifier", 0); - } - - // Otherwise, generate one. - if (initialSeedUniquifier == 0) { - // Try to generate a real random number from /dev/random. - // Get from a different thread to avoid blocking indefinitely on a machine without much entrophy. - final BlockingQueue queue = new LinkedBlockingQueue(); - Thread generatorThread = new Thread("initialSeedUniquifierGenerator") { - @Override - public void run() { - SecureRandom random = new SecureRandom(); // Get the real random seed from /dev/random - queue.add(random.generateSeed(8)); - } - }; - generatorThread.setDaemon(true); - generatorThread.start(); - generatorThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread t, Throwable e) { - logger.debug("An exception has been raised by {}", t.getName(), e); - } - }); - - // Get the random seed from the thread with timeout. - final long timeoutSeconds = 3; - final long deadLine = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds); - boolean interrupted = false; - for (;;) { - long waitTime = deadLine - System.nanoTime(); - if (waitTime <= 0) { - generatorThread.interrupt(); - logger.warn( - "Failed to generate a seed from SecureRandom within {} seconds. " + - "Not enough entrophy?", timeoutSeconds - ); - break; - } - - try { - byte[] seed = queue.poll(waitTime, TimeUnit.NANOSECONDS); - if (seed != null) { - initialSeedUniquifier = - ((long) seed[0] & 0xff) << 56 | - ((long) seed[1] & 0xff) << 48 | - ((long) seed[2] & 0xff) << 40 | - ((long) seed[3] & 0xff) << 32 | - ((long) seed[4] & 0xff) << 24 | - ((long) seed[5] & 0xff) << 16 | - ((long) seed[6] & 0xff) << 8 | - (long) seed[7] & 0xff; - break; - } - } catch (InterruptedException e) { - interrupted = true; - logger.warn("Failed to generate a seed from SecureRandom due to an InterruptedException."); - break; - } - } - - // Just in case the initialSeedUniquifier is zero or some other constant - initialSeedUniquifier ^= 0x3255ecdc33bae119L; // just a meaningless random number - initialSeedUniquifier ^= Long.reverse(System.nanoTime()); - - ThreadLocalRandom.initialSeedUniquifier = initialSeedUniquifier; - - if (interrupted) { - // Restore the interrupt status because we don't know how to/don't need to handle it here. - Thread.currentThread().interrupt(); - - // Interrupt the generator thread if it's still running, - // in the hope that the SecureRandom provider raises an exception on interruption. - generatorThread.interrupt(); - } - } - - return initialSeedUniquifier; - } - - private static long newSeed() { - final long startTime = System.nanoTime(); - for (;;) { - final long current = seedUniquifier.get(); - final long actualCurrent = current != 0? current : getInitialSeedUniquifier(); - - // L'Ecuyer, "Tables of Linear Congruential Generators of Different Sizes and Good Lattice Structure", 1999 - final long next = actualCurrent * 181783497276652981L; - - if (seedUniquifier.compareAndSet(current, next)) { - if (current == 0 && logger.isDebugEnabled()) { - logger.debug(String.format( - "-Dgame.net.initialSeedUniquifier: 0x%016x (took %d ms)", - actualCurrent, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime))); - } - return next ^ System.nanoTime(); - } - } - } - - // same constants as Random, but must be redeclared because private - private static final long multiplier = 0x5DEECE66DL; - private static final long addend = 0xBL; - private static final long mask = (1L << 48) - 1; - - /** - * The random seed. We can't use super.seed. - */ - private long rnd; - - /** - * Initialization flag to permit calls to setSeed to succeed only - * while executing the Random constructor. We can't allow others - * since it would cause setting seed in one part of a program to - * unintentionally impact other usages by the thread. - */ - boolean initialized; - - // Padding to help avoid memory contention among seed updates in - // different TLRs in the common case that they are located near - // each other. - private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; - - /** - * Constructor called only by localRandom.initialValue. - */ - ThreadLocalRandom() { - super(newSeed()); - initialized = true; - } - - /** - * Returns the current thread's {@code ThreadLocalRandom}. - * - * @return the current thread's {@code ThreadLocalRandom} - */ - public static ThreadLocalRandom current() { - return InternalThreadLocalMap.get().random(); - } - - /** - * Throws {@code UnsupportedOperationException}. Setting seeds in - * this generator is not supported. - * - * @throws UnsupportedOperationException always - */ - public void setSeed(long seed) { - if (initialized) { - throw new UnsupportedOperationException(); - } - rnd = (seed ^ multiplier) & mask; - } - - protected int next(int bits) { - rnd = (rnd * multiplier + addend) & mask; - return (int) (rnd >>> (48 - bits)); - } - - /** - * Returns a pseudorandom, uniformly distributed value between the - * given least value (inclusive) and bound (exclusive). - * - * @param least the least value returned - * @param bound the upper bound (exclusive) - * @throws IllegalArgumentException if least greater than or equal - * to bound - * @return the next value - */ - public int nextInt(int least, int bound) { - if (least >= bound) { - throw new IllegalArgumentException(); - } - return nextInt(bound - least) + least; - } - - /** - * Returns a pseudorandom, uniformly distributed value - * between 0 (inclusive) and the specified value (exclusive). - * - * @param n the bound on the random number to be returned. Must be - * positive. - * @return the next value - * @throws IllegalArgumentException if n is not positive - */ - public long nextLong(long n) { - if (n <= 0) { - throw new IllegalArgumentException("n must be positive"); - } - - // Divide n by two until small enough for nextInt. On each - // iteration (at most 31 of them but usually much less), - // randomly choose both whether to include high bit in result - // (offset) and whether to continue with the lower vs upper - // half (which makes a difference only if odd). - long offset = 0; - while (n >= Integer.MAX_VALUE) { - int bits = next(2); - long half = n >>> 1; - long nextn = ((bits & 2) == 0) ? half : n - half; - if ((bits & 1) == 0) { - offset += n - nextn; - } - n = nextn; - } - return offset + nextInt((int) n); - } - - /** - * Returns a pseudorandom, uniformly distributed value between the - * given least value (inclusive) and bound (exclusive). - * - * @param least the least value returned - * @param bound the upper bound (exclusive) - * @return the next value - * @throws IllegalArgumentException if least greater than or equal - * to bound - */ - public long nextLong(long least, long bound) { - if (least >= bound) { - throw new IllegalArgumentException(); - } - return nextLong(bound - least) + least; - } - - /** - * Returns a pseudorandom, uniformly distributed {@code double} value - * between 0 (inclusive) and the specified value (exclusive). - * - * @param n the bound on the random number to be returned. Must be - * positive. - * @return the next value - * @throws IllegalArgumentException if n is not positive - */ - public double nextDouble(double n) { - if (n <= 0) { - throw new IllegalArgumentException("n must be positive"); - } - return nextDouble() * n; - } - - /** - * Returns a pseudorandom, uniformly distributed value between the - * given least value (inclusive) and bound (exclusive). - * - * @param least the least value returned - * @param bound the upper bound (exclusive) - * @return the next value - * @throws IllegalArgumentException if least greater than or equal - * to bound - */ - public double nextDouble(double least, double bound) { - if (least >= bound) { - throw new IllegalArgumentException(); - } - return nextDouble() * (bound - least) + least; - } - - private static final long serialVersionUID = -5851777807851030925L; -} diff --git a/common/src/main/java/common/net/util/internal/TypeParameterMatcher.java b/common/src/main/java/common/net/util/internal/TypeParameterMatcher.java deleted file mode 100644 index 76ba1b2..0000000 --- a/common/src/main/java/common/net/util/internal/TypeParameterMatcher.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -import java.lang.reflect.Array; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.util.HashMap; -import java.util.Map; - -public abstract class TypeParameterMatcher { - - private static final TypeParameterMatcher NOOP = new NoOpTypeParameterMatcher(); - private static final Object TEST_OBJECT = new Object(); - - public static TypeParameterMatcher get(final Class parameterType) { - final Map, TypeParameterMatcher> getCache = - InternalThreadLocalMap.get().typeParameterMatcherGetCache(); - - TypeParameterMatcher matcher = getCache.get(parameterType); - if (matcher == null) { - if (parameterType == Object.class) { - matcher = NOOP; - } -// else if (PlatformDependent.hasJavassist()) { -// try { -// matcher = JavassistTypeParameterMatcherGenerator.generate(parameterType); -// matcher.match(TEST_OBJECT); -// } catch (IllegalAccessError e) { -// // Happens if parameterType is not public. -// matcher = null; -// } catch (Exception e) { -// // Will not usually happen, but just in case. -// matcher = null; -// } -// } - - if (matcher == null) { - matcher = new ReflectiveMatcher(parameterType); - } - - getCache.put(parameterType, matcher); - } - - return matcher; - } - - public static TypeParameterMatcher find( - final Object object, final Class parameterizedSuperclass, final String typeParamName) { - - final Map, Map> findCache = - InternalThreadLocalMap.get().typeParameterMatcherFindCache(); - final Class thisClass = object.getClass(); - - Map map = findCache.get(thisClass); - if (map == null) { - map = new HashMap(); - findCache.put(thisClass, map); - } - - TypeParameterMatcher matcher = map.get(typeParamName); - if (matcher == null) { - matcher = get(find0(object, parameterizedSuperclass, typeParamName)); - map.put(typeParamName, matcher); - } - - return matcher; - } - - private static Class find0( - final Object object, Class parameterizedSuperclass, String typeParamName) { - - final Class thisClass = object.getClass(); - Class currentClass = thisClass; - for (;;) { - if (currentClass.getSuperclass() == parameterizedSuperclass) { - int typeParamIndex = -1; - TypeVariable[] typeParams = currentClass.getSuperclass().getTypeParameters(); - for (int i = 0; i < typeParams.length; i ++) { - if (typeParamName.equals(typeParams[i].getName())) { - typeParamIndex = i; - break; - } - } - - if (typeParamIndex < 0) { - throw new IllegalStateException( - "unknown type parameter '" + typeParamName + "': " + parameterizedSuperclass); - } - - Type genericSuperType = currentClass.getGenericSuperclass(); - if (!(genericSuperType instanceof ParameterizedType)) { - return Object.class; - } - - Type[] actualTypeParams = ((ParameterizedType) genericSuperType).getActualTypeArguments(); - - Type actualTypeParam = actualTypeParams[typeParamIndex]; - if (actualTypeParam instanceof ParameterizedType) { - actualTypeParam = ((ParameterizedType) actualTypeParam).getRawType(); - } - if (actualTypeParam instanceof Class) { - return (Class) actualTypeParam; - } - if (actualTypeParam instanceof GenericArrayType) { - Type componentType = ((GenericArrayType) actualTypeParam).getGenericComponentType(); - if (componentType instanceof ParameterizedType) { - componentType = ((ParameterizedType) componentType).getRawType(); - } - if (componentType instanceof Class) { - return Array.newInstance((Class) componentType, 0).getClass(); - } - } - if (actualTypeParam instanceof TypeVariable) { - // Resolved type parameter points to another type parameter. - TypeVariable v = (TypeVariable) actualTypeParam; - currentClass = thisClass; - if (!(v.getGenericDeclaration() instanceof Class)) { - return Object.class; - } - - parameterizedSuperclass = (Class) v.getGenericDeclaration(); - typeParamName = v.getName(); - if (parameterizedSuperclass.isAssignableFrom(thisClass)) { - continue; - } else { - return Object.class; - } - } - - return fail(thisClass, typeParamName); - } - currentClass = currentClass.getSuperclass(); - if (currentClass == null) { - return fail(thisClass, typeParamName); - } - } - } - - private static Class fail(Class type, String typeParamName) { - throw new IllegalStateException( - "cannot determine the type of the type parameter '" + typeParamName + "': " + type); - } - - public abstract boolean match(Object msg); - - private static final class ReflectiveMatcher extends TypeParameterMatcher { - private final Class type; - - ReflectiveMatcher(Class type) { - this.type = type; - } - - @Override - public boolean match(Object msg) { - return type.isInstance(msg); - } - } - - protected TypeParameterMatcher() { } -} diff --git a/common/src/main/java/common/net/util/internal/UnpaddedInternalThreadLocalMap.java b/common/src/main/java/common/net/util/internal/UnpaddedInternalThreadLocalMap.java deleted file mode 100644 index 689202d..0000000 --- a/common/src/main/java/common/net/util/internal/UnpaddedInternalThreadLocalMap.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package common.net.util.internal; - -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * The internal data structure that stores the thread-local variables for Netty and all {@link FastThreadLocal}s. - * Note that this class is for internal use only and is subject to change at any time. Use {@link FastThreadLocal} - * unless you know what you are doing. - */ -class UnpaddedInternalThreadLocalMap { - - static ThreadLocal slowThreadLocalMap; - static final AtomicInteger nextIndex = new AtomicInteger(); - - /** Used by {@link FastThreadLocal} */ - Object[] indexedVariables; - - // Core thread-locals - int futureListenerStackDepth; - int localChannelReaderStackDepth; - Map, Boolean> handlerSharableCache; - IntegerHolder counterHashCode; - ThreadLocalRandom random; - Map, TypeParameterMatcher> typeParameterMatcherGetCache; - Map, Map> typeParameterMatcherFindCache; - - // String-related thread-locals - StringBuilder stringBuilder; - Map charsetEncoderCache; - Map charsetDecoderCache; - - UnpaddedInternalThreadLocalMap(Object[] indexedVariables) { - this.indexedVariables = indexedVariables; - } -} diff --git a/common/src/main/java/common/net/util/internal/logging/AbstractInternalLogger.java b/common/src/main/java/common/net/util/internal/logging/AbstractInternalLogger.java deleted file mode 100644 index 2ebbf8a..0000000 --- a/common/src/main/java/common/net/util/internal/logging/AbstractInternalLogger.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.internal.logging; - -import java.io.ObjectStreamException; -import java.io.Serializable; - -import common.net.util.internal.StringUtil; - -/** - * A skeletal implementation of {@link InternalLogger}. This class implements - * all methods that have a {@link InternalLogLevel} parameter by default to call - * specific logger methods such as {@link #info(String)} or {@link #isInfoEnabled()}. - */ -public abstract class AbstractInternalLogger implements InternalLogger, Serializable { - - private static final long serialVersionUID = -6382972526573193470L; - - private final String name; - - /** - * Creates a new instance. - */ - protected AbstractInternalLogger(String name) { - if (name == null) { - throw new NullPointerException("name"); - } - this.name = name; - } - - @Override - public String name() { - return name; - } - - @Override - public boolean isEnabled(InternalLogLevel level) { - switch (level) { - case TRACE: - return isTraceEnabled(); - case DEBUG: - return isDebugEnabled(); - case INFO: - return isInfoEnabled(); - case WARN: - return isWarnEnabled(); - case ERROR: - return isErrorEnabled(); - default: - throw new Error(); - } - } - - @Override - public void log(InternalLogLevel level, String msg, Throwable cause) { - switch (level) { - case TRACE: - trace(msg, cause); - break; - case DEBUG: - debug(msg, cause); - break; - case INFO: - info(msg, cause); - break; - case WARN: - warn(msg, cause); - break; - case ERROR: - error(msg, cause); - break; - default: - throw new Error(); - } - } - - @Override - public void log(InternalLogLevel level, String msg) { - switch (level) { - case TRACE: - trace(msg); - break; - case DEBUG: - debug(msg); - break; - case INFO: - info(msg); - break; - case WARN: - warn(msg); - break; - case ERROR: - error(msg); - break; - default: - throw new Error(); - } - } - - @Override - public void log(InternalLogLevel level, String format, Object arg) { - switch (level) { - case TRACE: - trace(format, arg); - break; - case DEBUG: - debug(format, arg); - break; - case INFO: - info(format, arg); - break; - case WARN: - warn(format, arg); - break; - case ERROR: - error(format, arg); - break; - default: - throw new Error(); - } - } - - @Override - public void log(InternalLogLevel level, String format, Object argA, Object argB) { - switch (level) { - case TRACE: - trace(format, argA, argB); - break; - case DEBUG: - debug(format, argA, argB); - break; - case INFO: - info(format, argA, argB); - break; - case WARN: - warn(format, argA, argB); - break; - case ERROR: - error(format, argA, argB); - break; - default: - throw new Error(); - } - } - - @Override - public void log(InternalLogLevel level, String format, Object... arguments) { - switch (level) { - case TRACE: - trace(format, arguments); - break; - case DEBUG: - debug(format, arguments); - break; - case INFO: - info(format, arguments); - break; - case WARN: - warn(format, arguments); - break; - case ERROR: - error(format, arguments); - break; - default: - throw new Error(); - } - } - - protected Object readResolve() throws ObjectStreamException { - return InternalLoggerFactory.getInstance(name()); - } - - @Override - public String toString() { - return StringUtil.simpleClassName(this) + '(' + name() + ')'; - } -} diff --git a/common/src/main/java/common/net/util/internal/logging/FormattingTuple.java b/common/src/main/java/common/net/util/internal/logging/FormattingTuple.java deleted file mode 100644 index c87a8e7..0000000 --- a/common/src/main/java/common/net/util/internal/logging/FormattingTuple.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package common.net.util.internal.logging; - -/** - * Holds the results of formatting done by {@link MessageFormatter}. - */ -class FormattingTuple { - - static final FormattingTuple NULL = new FormattingTuple(null); - - private final String message; - private final Throwable throwable; - private final Object[] argArray; - - FormattingTuple(String message) { - this(message, null, null); - } - - FormattingTuple(String message, Object[] argArray, Throwable throwable) { - this.message = message; - this.throwable = throwable; - if (throwable == null) { - this.argArray = argArray; - } else { - this.argArray = trimmedCopy(argArray); - } - } - - static Object[] trimmedCopy(Object[] argArray) { - if (argArray == null || argArray.length == 0) { - throw new IllegalStateException("non-sensical empty or null argument array"); - } - final int trimemdLen = argArray.length - 1; - Object[] trimmed = new Object[trimemdLen]; - System.arraycopy(argArray, 0, trimmed, 0, trimemdLen); - return trimmed; - } - - public String getMessage() { - return message; - } - - public Object[] getArgArray() { - return argArray; - } - - public Throwable getThrowable() { - return throwable; - } -} diff --git a/common/src/main/java/common/net/util/internal/logging/InternalLogLevel.java b/common/src/main/java/common/net/util/internal/logging/InternalLogLevel.java deleted file mode 100644 index 108c2f5..0000000 --- a/common/src/main/java/common/net/util/internal/logging/InternalLogLevel.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.internal.logging; - -/** - * The log level that {@link InternalLogger} can log at. - */ -public enum InternalLogLevel { - /** - * 'TRACE' log level. - */ - TRACE, - /** - * 'DEBUG' log level. - */ - DEBUG, - /** - * 'INFO' log level. - */ - INFO, - /** - * 'WARN' log level. - */ - WARN, - /** - * 'ERROR' log level. - */ - ERROR -} diff --git a/common/src/main/java/common/net/util/internal/logging/InternalLogger.java b/common/src/main/java/common/net/util/internal/logging/InternalLogger.java deleted file mode 100644 index 1c2b953..0000000 --- a/common/src/main/java/common/net/util/internal/logging/InternalLogger.java +++ /dev/null @@ -1,444 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package common.net.util.internal.logging; - -/** - * Internal-use-only logger used by Netty. DO NOT - * access this class outside of Netty. - */ -public interface InternalLogger { - - /** - * Return the name of this {@link InternalLogger} instance. - * - * @return name of this logger instance - */ - String name(); - - /** - * Is the logger instance enabled for the TRACE level? - * - * @return True if this Logger is enabled for the TRACE level, - * false otherwise. - */ - boolean isTraceEnabled(); - - /** - * Log a message at the TRACE level. - * - * @param msg the message string to be logged - */ - void trace(String msg); - - /** - * Log a message at the TRACE level according to the specified format - * and argument. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the TRACE level.

- * - * @param format the format string - * @param arg the argument - */ - void trace(String format, Object arg); - - /** - * Log a message at the TRACE level according to the specified format - * and arguments. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the TRACE level.

- * - * @param format the format string - * @param argA the first argument - * @param argB the second argument - */ - void trace(String format, Object argA, Object argB); - - /** - * Log a message at the TRACE level according to the specified format - * and arguments. - *

- *

This form avoids superfluous string concatenation when the logger - * is disabled for the TRACE level. However, this variant incurs the hidden - * (and relatively small) cost of creating an {@code Object[]} before invoking the method, - * even if this logger is disabled for TRACE. The variants taking {@link #trace(String, Object) one} and - * {@link #trace(String, Object, Object) two} arguments exist solely in order to avoid this hidden cost.

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - void trace(String format, Object... arguments); - - /** - * Log an exception (throwable) at the TRACE level with an - * accompanying message. - * - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - void trace(String msg, Throwable t); - - /** - * Is the logger instance enabled for the DEBUG level? - * - * @return True if this Logger is enabled for the DEBUG level, - * false otherwise. - */ - boolean isDebugEnabled(); - - /** - * Log a message at the DEBUG level. - * - * @param msg the message string to be logged - */ - void debug(String msg); - - /** - * Log a message at the DEBUG level according to the specified format - * and argument. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the DEBUG level.

- * - * @param format the format string - * @param arg the argument - */ - void debug(String format, Object arg); - - /** - * Log a message at the DEBUG level according to the specified format - * and arguments. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the DEBUG level.

- * - * @param format the format string - * @param argA the first argument - * @param argB the second argument - */ - void debug(String format, Object argA, Object argB); - - /** - * Log a message at the DEBUG level according to the specified format - * and arguments. - *

- *

This form avoids superfluous string concatenation when the logger - * is disabled for the DEBUG level. However, this variant incurs the hidden - * (and relatively small) cost of creating an {@code Object[]} before invoking the method, - * even if this logger is disabled for DEBUG. The variants taking - * {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two} - * arguments exist solely in order to avoid this hidden cost.

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - void debug(String format, Object... arguments); - - /** - * Log an exception (throwable) at the DEBUG level with an - * accompanying message. - * - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - void debug(String msg, Throwable t); - - /** - * Is the logger instance enabled for the INFO level? - * - * @return True if this Logger is enabled for the INFO level, - * false otherwise. - */ - boolean isInfoEnabled(); - - /** - * Log a message at the INFO level. - * - * @param msg the message string to be logged - */ - void info(String msg); - - /** - * Log a message at the INFO level according to the specified format - * and argument. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the INFO level.

- * - * @param format the format string - * @param arg the argument - */ - void info(String format, Object arg); - - /** - * Log a message at the INFO level according to the specified format - * and arguments. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the INFO level.

- * - * @param format the format string - * @param argA the first argument - * @param argB the second argument - */ - void info(String format, Object argA, Object argB); - - /** - * Log a message at the INFO level according to the specified format - * and arguments. - *

- *

This form avoids superfluous string concatenation when the logger - * is disabled for the INFO level. However, this variant incurs the hidden - * (and relatively small) cost of creating an {@code Object[]} before invoking the method, - * even if this logger is disabled for INFO. The variants taking - * {@link #info(String, Object) one} and {@link #info(String, Object, Object) two} - * arguments exist solely in order to avoid this hidden cost.

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - void info(String format, Object... arguments); - - /** - * Log an exception (throwable) at the INFO level with an - * accompanying message. - * - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - void info(String msg, Throwable t); - - /** - * Is the logger instance enabled for the WARN level? - * - * @return True if this Logger is enabled for the WARN level, - * false otherwise. - */ - boolean isWarnEnabled(); - - /** - * Log a message at the WARN level. - * - * @param msg the message string to be logged - */ - void warn(String msg); - - /** - * Log a message at the WARN level according to the specified format - * and argument. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the WARN level.

- * - * @param format the format string - * @param arg the argument - */ - void warn(String format, Object arg); - - /** - * Log a message at the WARN level according to the specified format - * and arguments. - *

- *

This form avoids superfluous string concatenation when the logger - * is disabled for the WARN level. However, this variant incurs the hidden - * (and relatively small) cost of creating an {@code Object[]} before invoking the method, - * even if this logger is disabled for WARN. The variants taking - * {@link #warn(String, Object) one} and {@link #warn(String, Object, Object) two} - * arguments exist solely in order to avoid this hidden cost.

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - void warn(String format, Object... arguments); - - /** - * Log a message at the WARN level according to the specified format - * and arguments. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the WARN level.

- * - * @param format the format string - * @param argA the first argument - * @param argB the second argument - */ - void warn(String format, Object argA, Object argB); - - /** - * Log an exception (throwable) at the WARN level with an - * accompanying message. - * - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - void warn(String msg, Throwable t); - - /** - * Is the logger instance enabled for the ERROR level? - * - * @return True if this Logger is enabled for the ERROR level, - * false otherwise. - */ - boolean isErrorEnabled(); - - /** - * Log a message at the ERROR level. - * - * @param msg the message string to be logged - */ - void error(String msg); - - /** - * Log a message at the ERROR level according to the specified format - * and argument. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the ERROR level.

- * - * @param format the format string - * @param arg the argument - */ - void error(String format, Object arg); - - /** - * Log a message at the ERROR level according to the specified format - * and arguments. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the ERROR level.

- * - * @param format the format string - * @param argA the first argument - * @param argB the second argument - */ - void error(String format, Object argA, Object argB); - - /** - * Log a message at the ERROR level according to the specified format - * and arguments. - *

- *

This form avoids superfluous string concatenation when the logger - * is disabled for the ERROR level. However, this variant incurs the hidden - * (and relatively small) cost of creating an {@code Object[]} before invoking the method, - * even if this logger is disabled for ERROR. The variants taking - * {@link #error(String, Object) one} and {@link #error(String, Object, Object) two} - * arguments exist solely in order to avoid this hidden cost.

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - void error(String format, Object... arguments); - - /** - * Log an exception (throwable) at the ERROR level with an - * accompanying message. - * - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - void error(String msg, Throwable t); - - /** - * Is the logger instance enabled for the specified {@code level}? - * - * @return True if this Logger is enabled for the specified {@code level}, - * false otherwise. - */ - boolean isEnabled(InternalLogLevel level); - - /** - * Log a message at the specified {@code level}. - * - * @param msg the message string to be logged - */ - void log(InternalLogLevel level, String msg); - - /** - * Log a message at the specified {@code level} according to the specified format - * and argument. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the specified {@code level}.

- * - * @param format the format string - * @param arg the argument - */ - void log(InternalLogLevel level, String format, Object arg); - - /** - * Log a message at the specified {@code level} according to the specified format - * and arguments. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the specified {@code level}.

- * - * @param format the format string - * @param argA the first argument - * @param argB the second argument - */ - void log(InternalLogLevel level, String format, Object argA, Object argB); - - /** - * Log a message at the specified {@code level} according to the specified format - * and arguments. - *

- *

This form avoids superfluous string concatenation when the logger - * is disabled for the specified {@code level}. However, this variant incurs the hidden - * (and relatively small) cost of creating an {@code Object[]} before invoking the method, - * even if this logger is disabled for the specified {@code level}. The variants taking - * {@link #log(InternalLogLevel, String, Object) one} and - * {@link #log(InternalLogLevel, String, Object, Object) two} arguments exist solely - * in order to avoid this hidden cost.

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - void log(InternalLogLevel level, String format, Object... arguments); - - /** - * Log an exception (throwable) at the specified {@code level} with an - * accompanying message. - * - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - void log(InternalLogLevel level, String msg, Throwable t); -} diff --git a/common/src/main/java/common/net/util/internal/logging/InternalLoggerFactory.java b/common/src/main/java/common/net/util/internal/logging/InternalLoggerFactory.java deleted file mode 100644 index e6d10ff..0000000 --- a/common/src/main/java/common/net/util/internal/logging/InternalLoggerFactory.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.internal.logging; - -/** - * Creates an {@link InternalLogger} or changes the default factory - * implementation. This factory allows you to choose what logging framework - * Netty should use. The default factory is {@link Slf4JLoggerFactory}. If SLF4J - * is not available, {@link Log4JLoggerFactory} is used. If Log4J is not available, - * {@link JdkLoggerFactory} is used. You can change it to your preferred - * logging framework before other Netty classes are loaded: - *
- * {@link InternalLoggerFactory}.setDefaultFactory(new {@link Log4JLoggerFactory}());
- * 
- * Please note that the new default factory is effective only for the classes - * which were loaded after the default factory is changed. Therefore, - * {@link #setDefaultFactory(InternalLoggerFactory)} should be called as early - * as possible and shouldn't be called more than once. - */ -public abstract class InternalLoggerFactory { - private static volatile InternalLoggerFactory defaultFactory = - newDefaultFactory(InternalLoggerFactory.class.getName()); - -// - private static InternalLoggerFactory newDefaultFactory(String name) { - InternalLoggerFactory f; -// try { -// f = new Slf4JLoggerFactory(true); -// f.newInstance(name).debug("Using SLF4J as the default logging framework"); -// } catch (Throwable t1) { -// try { -// f = new Log4JLoggerFactory(); -// f.newInstance(name).debug("Using Log4J as the default logging framework"); -// } catch (Throwable t2) { - f = new JdkLoggerFactory(); - f.newInstance(name).debug("Using java.util.logging as the default logging framework"); -// } -// } - return f; - } - - /** - * Returns the default factory. The initial default factory is - * {@link JdkLoggerFactory}. - */ - public static InternalLoggerFactory getDefaultFactory() { - return defaultFactory; - } - - /** - * Changes the default factory. - */ - public static void setDefaultFactory(InternalLoggerFactory defaultFactory) { - if (defaultFactory == null) { - throw new NullPointerException("defaultFactory"); - } - InternalLoggerFactory.defaultFactory = defaultFactory; - } - - /** - * Creates a new logger instance with the name of the specified class. - */ - public static InternalLogger getInstance(Class clazz) { - return getInstance(clazz.getName()); - } - - /** - * Creates a new logger instance with the specified name. - */ - public static InternalLogger getInstance(String name) { - return getDefaultFactory().newInstance(name); - } - - /** - * Creates a new logger instance with the specified name. - */ - protected abstract InternalLogger newInstance(String name); -} diff --git a/common/src/main/java/common/net/util/internal/logging/JdkLogger.java b/common/src/main/java/common/net/util/internal/logging/JdkLogger.java deleted file mode 100644 index a0e69f6..0000000 --- a/common/src/main/java/common/net/util/internal/logging/JdkLogger.java +++ /dev/null @@ -1,647 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package common.net.util.internal.logging; - -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; - -/** - * java.util.logging - * logger. - */ -class JdkLogger extends AbstractInternalLogger { - - private static final long serialVersionUID = -1767272577989225979L; - - final transient Logger logger; - - JdkLogger(Logger logger) { - super(logger.getName()); - this.logger = logger; - } - - /** - * Is this logger instance enabled for the FINEST level? - * - * @return True if this Logger is enabled for level FINEST, false otherwise. - */ - @Override - public boolean isTraceEnabled() { - return logger.isLoggable(Level.FINEST); - } - - /** - * Log a message object at level FINEST. - * - * @param msg - * - the message object to be logged - */ - @Override - public void trace(String msg) { - if (logger.isLoggable(Level.FINEST)) { - log(SELF, Level.FINEST, msg, null); - } - } - - /** - * Log a message at level FINEST according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for level FINEST. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - @Override - public void trace(String format, Object arg) { - if (logger.isLoggable(Level.FINEST)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level FINEST according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the FINEST level. - *

- * - * @param format - * the format string - * @param argA - * the first argument - * @param argB - * the second argument - */ - @Override - public void trace(String format, Object argA, Object argB) { - if (logger.isLoggable(Level.FINEST)) { - FormattingTuple ft = MessageFormatter.format(format, argA, argB); - log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level FINEST according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the FINEST level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - @Override - public void trace(String format, Object... argArray) { - if (logger.isLoggable(Level.FINEST)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at level FINEST with an accompanying message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - @Override - public void trace(String msg, Throwable t) { - if (logger.isLoggable(Level.FINEST)) { - log(SELF, Level.FINEST, msg, t); - } - } - - /** - * Is this logger instance enabled for the FINE level? - * - * @return True if this Logger is enabled for level FINE, false otherwise. - */ - @Override - public boolean isDebugEnabled() { - return logger.isLoggable(Level.FINE); - } - - /** - * Log a message object at level FINE. - * - * @param msg - * - the message object to be logged - */ - @Override - public void debug(String msg) { - if (logger.isLoggable(Level.FINE)) { - log(SELF, Level.FINE, msg, null); - } - } - - /** - * Log a message at level FINE according to the specified format and argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for level FINE. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - @Override - public void debug(String format, Object arg) { - if (logger.isLoggable(Level.FINE)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level FINE according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the FINE level. - *

- * - * @param format - * the format string - * @param argA - * the first argument - * @param argB - * the second argument - */ - @Override - public void debug(String format, Object argA, Object argB) { - if (logger.isLoggable(Level.FINE)) { - FormattingTuple ft = MessageFormatter.format(format, argA, argB); - log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level FINE according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the FINE level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - @Override - public void debug(String format, Object... argArray) { - if (logger.isLoggable(Level.FINE)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at level FINE with an accompanying message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - @Override - public void debug(String msg, Throwable t) { - if (logger.isLoggable(Level.FINE)) { - log(SELF, Level.FINE, msg, t); - } - } - - /** - * Is this logger instance enabled for the INFO level? - * - * @return True if this Logger is enabled for the INFO level, false otherwise. - */ - @Override - public boolean isInfoEnabled() { - return logger.isLoggable(Level.INFO); - } - - /** - * Log a message object at the INFO level. - * - * @param msg - * - the message object to be logged - */ - @Override - public void info(String msg) { - if (logger.isLoggable(Level.INFO)) { - log(SELF, Level.INFO, msg, null); - } - } - - /** - * Log a message at level INFO according to the specified format and argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - @Override - public void info(String format, Object arg) { - if (logger.isLoggable(Level.INFO)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at the INFO level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param argA - * the first argument - * @param argB - * the second argument - */ - @Override - public void info(String format, Object argA, Object argB) { - if (logger.isLoggable(Level.INFO)) { - FormattingTuple ft = MessageFormatter.format(format, argA, argB); - log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level INFO according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - @Override - public void info(String format, Object... argArray) { - if (logger.isLoggable(Level.INFO)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at the INFO level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - @Override - public void info(String msg, Throwable t) { - if (logger.isLoggable(Level.INFO)) { - log(SELF, Level.INFO, msg, t); - } - } - - /** - * Is this logger instance enabled for the WARNING level? - * - * @return True if this Logger is enabled for the WARNING level, false - * otherwise. - */ - @Override - public boolean isWarnEnabled() { - return logger.isLoggable(Level.WARNING); - } - - /** - * Log a message object at the WARNING level. - * - * @param msg - * - the message object to be logged - */ - @Override - public void warn(String msg) { - if (logger.isLoggable(Level.WARNING)) { - log(SELF, Level.WARNING, msg, null); - } - } - - /** - * Log a message at the WARNING level according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARNING level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - @Override - public void warn(String format, Object arg) { - if (logger.isLoggable(Level.WARNING)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at the WARNING level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARNING level. - *

- * - * @param format - * the format string - * @param argA - * the first argument - * @param argB - * the second argument - */ - @Override - public void warn(String format, Object argA, Object argB) { - if (logger.isLoggable(Level.WARNING)) { - FormattingTuple ft = MessageFormatter.format(format, argA, argB); - log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level WARNING according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARNING level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - @Override - public void warn(String format, Object... argArray) { - if (logger.isLoggable(Level.WARNING)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at the WARNING level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - @Override - public void warn(String msg, Throwable t) { - if (logger.isLoggable(Level.WARNING)) { - log(SELF, Level.WARNING, msg, t); - } - } - - /** - * Is this logger instance enabled for level SEVERE? - * - * @return True if this Logger is enabled for level SEVERE, false otherwise. - */ - @Override - public boolean isErrorEnabled() { - return logger.isLoggable(Level.SEVERE); - } - - /** - * Log a message object at the SEVERE level. - * - * @param msg - * - the message object to be logged - */ - @Override - public void error(String msg) { - if (logger.isLoggable(Level.SEVERE)) { - log(SELF, Level.SEVERE, msg, null); - } - } - - /** - * Log a message at the SEVERE level according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the SEVERE level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - @Override - public void error(String format, Object arg) { - if (logger.isLoggable(Level.SEVERE)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at the SEVERE level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the SEVERE level. - *

- * - * @param format - * the format string - * @param argA - * the first argument - * @param argB - * the second argument - */ - @Override - public void error(String format, Object argA, Object argB) { - if (logger.isLoggable(Level.SEVERE)) { - FormattingTuple ft = MessageFormatter.format(format, argA, argB); - log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level SEVERE according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the SEVERE level. - *

- * - * @param format - * the format string - * @param arguments - * an array of arguments - */ - @Override - public void error(String format, Object... arguments) { - if (logger.isLoggable(Level.SEVERE)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); - log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at the SEVERE level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - @Override - public void error(String msg, Throwable t) { - if (logger.isLoggable(Level.SEVERE)) { - log(SELF, Level.SEVERE, msg, t); - } - } - - /** - * Log the message at the specified level with the specified throwable if any. - * This method creates a LogRecord and fills in caller date before calling - * this instance's JDK14 logger. - * - * See bug report #13 for more details. - */ - private void log(String callerFQCN, Level level, String msg, Throwable t) { - // millis and thread are filled by the constructor - LogRecord record = new LogRecord(level, msg); - record.setLoggerName(name()); - record.setThrown(t); - fillCallerData(callerFQCN, record); - logger.log(record); - } - - static final String SELF = JdkLogger.class.getName(); - static final String SUPER = AbstractInternalLogger.class.getName(); - - /** - * Fill in caller data if possible. - * - * @param record - * The record to update - */ - private static void fillCallerData(String callerFQCN, LogRecord record) { - StackTraceElement[] steArray = new Throwable().getStackTrace(); - - int selfIndex = -1; - for (int i = 0; i < steArray.length; i++) { - final String className = steArray[i].getClassName(); - if (className.equals(callerFQCN) || className.equals(SUPER)) { - selfIndex = i; - break; - } - } - - int found = -1; - for (int i = selfIndex + 1; i < steArray.length; i++) { - final String className = steArray[i].getClassName(); - if (!(className.equals(callerFQCN) || className.equals(SUPER))) { - found = i; - break; - } - } - - if (found != -1) { - StackTraceElement ste = steArray[found]; - // setting the class name has the side effect of setting - // the needToInferCaller variable to false. - record.setSourceClassName(ste.getClassName()); - record.setSourceMethodName(ste.getMethodName()); - } - } -} diff --git a/common/src/main/java/common/net/util/internal/logging/JdkLoggerFactory.java b/common/src/main/java/common/net/util/internal/logging/JdkLoggerFactory.java deleted file mode 100644 index a1e88dd..0000000 --- a/common/src/main/java/common/net/util/internal/logging/JdkLoggerFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package common.net.util.internal.logging; - - -import java.util.logging.Logger; - -/** - * Logger factory which creates a - * java.util.logging - * logger. - */ -public class JdkLoggerFactory extends InternalLoggerFactory { - - @Override - public InternalLogger newInstance(String name) { - return new JdkLogger(Logger.getLogger(name)); - } -} diff --git a/common/src/main/java/common/net/util/internal/logging/MessageFormatter.java b/common/src/main/java/common/net/util/internal/logging/MessageFormatter.java deleted file mode 100644 index a1e956a..0000000 --- a/common/src/main/java/common/net/util/internal/logging/MessageFormatter.java +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package common.net.util.internal.logging; - -import java.util.HashMap; -import java.util.Map; - -// contributors: lizongbo: proposed special treatment of array parameter values -// Joern Huxhorn: pointed out double[] omission, suggested deep array copy - -/** - * Formats messages according to very simple substitution rules. Substitutions - * can be made 1, 2 or more arguments. - *

- *

- * For example, - *

- *

- * MessageFormatter.format("Hi {}.", "there")
- * 
- *

- * will return the string "Hi there.". - *

- * The {} pair is called the formatting anchor. It serves to designate - * the location where arguments need to be substituted within the message - * pattern. - *

- * In case your message contains the '{' or the '}' character, you do not have - * to do anything special unless the '}' character immediately follows '{'. For - * example, - *

- *

- * MessageFormatter.format("Set {1,2,3} is not equal to {}.", "1,2");
- * 
- *

- * will return the string "Set {1,2,3} is not equal to 1,2.". - *

- *

- * If for whatever reason you need to place the string "{}" in the message - * without its formatting anchor meaning, then you need to escape the - * '{' character with '\', that is the backslash character. Only the '{' - * character should be escaped. There is no need to escape the '}' character. - * For example, - *

- *

- * MessageFormatter.format("Set \\{} is not equal to {}.", "1,2");
- * 
- *

- * will return the string "Set {} is not equal to 1,2.". - *

- *

- * The escaping behavior just described can be overridden by escaping the escape - * character '\'. Calling - *

- *

- * MessageFormatter.format("File name is C:\\\\{}.", "file.zip");
- * 
- *

- * will return the string "File name is C:\file.zip". - *

- *

- * The formatting conventions are different than those of {@link MessageFormat} - * which ships with the Java platform. This is justified by the fact that - * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}. - * This local performance difference is both measurable and significant in the - * larger context of the complete logging processing chain. - *

- *

- * See also {@link #format(String, Object)}, - * {@link #format(String, Object, Object)} and - * {@link #arrayFormat(String, Object[])} methods for more details. - */ -final class MessageFormatter { - static final char DELIM_START = '{'; - static final char DELIM_STOP = '}'; - static final String DELIM_STR = "{}"; - private static final char ESCAPE_CHAR = '\\'; - - /** - * Performs single argument substitution for the 'messagePattern' passed as - * parameter. - *

- * For example, - *

- *

-     * MessageFormatter.format("Hi {}.", "there");
-     * 
- *

- * will return the string "Hi there.". - *

- * - * @param messagePattern The message pattern which will be parsed and formatted - * @param arg The argument to be substituted in place of the formatting anchor - * @return The formatted message - */ - static FormattingTuple format(String messagePattern, Object arg) { - return arrayFormat(messagePattern, new Object[]{arg}); - } - - /** - * Performs a two argument substitution for the 'messagePattern' passed as - * parameter. - *

- * For example, - *

- *

-     * MessageFormatter.format("Hi {}. My name is {}.", "Alice", "Bob");
-     * 
- *

- * will return the string "Hi Alice. My name is Bob.". - * - * @param messagePattern The message pattern which will be parsed and formatted - * @param argA The argument to be substituted in place of the first formatting - * anchor - * @param argB The argument to be substituted in place of the second formatting - * anchor - * @return The formatted message - */ - static FormattingTuple format(final String messagePattern, - Object argA, Object argB) { - return arrayFormat(messagePattern, new Object[]{argA, argB}); - } - - static Throwable getThrowableCandidate(Object[] argArray) { - if (argArray == null || argArray.length == 0) { - return null; - } - - final Object lastEntry = argArray[argArray.length - 1]; - if (lastEntry instanceof Throwable) { - return (Throwable) lastEntry; - } - return null; - } - - /** - * Same principle as the {@link #format(String, Object)} and - * {@link #format(String, Object, Object)} methods except that any number of - * arguments can be passed in an array. - * - * @param messagePattern The message pattern which will be parsed and formatted - * @param argArray An array of arguments to be substituted in place of formatting - * anchors - * @return The formatted message - */ - static FormattingTuple arrayFormat(final String messagePattern, - final Object[] argArray) { - - Throwable throwableCandidate = getThrowableCandidate(argArray); - - if (messagePattern == null) { - return new FormattingTuple(null, argArray, throwableCandidate); - } - - if (argArray == null) { - return new FormattingTuple(messagePattern); - } - - int i = 0; - int j; - StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50); - - int L; - for (L = 0; L < argArray.length; L++) { - - j = messagePattern.indexOf(DELIM_STR, i); - - if (j == -1) { - // no more variables - if (i == 0) { // this is a simple string - return new FormattingTuple(messagePattern, argArray, - throwableCandidate); - } else { // add the tail string which contains no variables and return - // the result. - sbuf.append(messagePattern.substring(i, messagePattern.length())); - return new FormattingTuple(sbuf.toString(), argArray, - throwableCandidate); - } - } else { - if (isEscapedDelimeter(messagePattern, j)) { - if (!isDoubleEscaped(messagePattern, j)) { - L--; // DELIM_START was escaped, thus should not be incremented - sbuf.append(messagePattern.substring(i, j - 1)); - sbuf.append(DELIM_START); - i = j + 1; - } else { - // The escape character preceding the delimiter start is - // itself escaped: "abc x:\\{}" - // we have to consume one backward slash - sbuf.append(messagePattern.substring(i, j - 1)); - deeplyAppendParameter(sbuf, argArray[L], new HashMap()); - i = j + 2; - } - } else { - // normal case - sbuf.append(messagePattern.substring(i, j)); - deeplyAppendParameter(sbuf, argArray[L], new HashMap()); - i = j + 2; - } - } - } - // append the characters following the last {} pair. - sbuf.append(messagePattern.substring(i, messagePattern.length())); - if (L < argArray.length - 1) { - return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate); - } else { - return new FormattingTuple(sbuf.toString(), argArray, null); - } - } - - static boolean isEscapedDelimeter(String messagePattern, - int delimeterStartIndex) { - - if (delimeterStartIndex == 0) { - return false; - } - return messagePattern.charAt(delimeterStartIndex - 1) == ESCAPE_CHAR; - } - - static boolean isDoubleEscaped(String messagePattern, - int delimeterStartIndex) { - return delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR; - } - - // special treatment of array values was suggested by 'lizongbo' - private static void deeplyAppendParameter(StringBuffer sbuf, Object o, - Map seenMap) { - if (o == null) { - sbuf.append("null"); - return; - } - if (!o.getClass().isArray()) { - safeObjectAppend(sbuf, o); - } else { - // check for primitive array types because they - // unfortunately cannot be cast to Object[] - if (o instanceof boolean[]) { - booleanArrayAppend(sbuf, (boolean[]) o); - } else if (o instanceof byte[]) { - byteArrayAppend(sbuf, (byte[]) o); - } else if (o instanceof char[]) { - charArrayAppend(sbuf, (char[]) o); - } else if (o instanceof short[]) { - shortArrayAppend(sbuf, (short[]) o); - } else if (o instanceof int[]) { - intArrayAppend(sbuf, (int[]) o); - } else if (o instanceof long[]) { - longArrayAppend(sbuf, (long[]) o); - } else if (o instanceof float[]) { - floatArrayAppend(sbuf, (float[]) o); - } else if (o instanceof double[]) { - doubleArrayAppend(sbuf, (double[]) o); - } else { - objectArrayAppend(sbuf, (Object[]) o, seenMap); - } - } - } - - private static void safeObjectAppend(StringBuffer sbuf, Object o) { - try { - String oAsString = o.toString(); - sbuf.append(oAsString); - } catch (Throwable t) { - System.err - .println("SLF4J: Failed toString() invocation on an object of type [" - + o.getClass().getName() + ']'); - t.printStackTrace(); - sbuf.append("[FAILED toString()]"); - } - } - - private static void objectArrayAppend(StringBuffer sbuf, Object[] a, - Map seenMap) { - sbuf.append('['); - if (!seenMap.containsKey(a)) { - seenMap.put(a, null); - final int len = a.length; - for (int i = 0; i < len; i++) { - deeplyAppendParameter(sbuf, a[i], seenMap); - if (i != len - 1) { - sbuf.append(", "); - } - } - // allow repeats in siblings - seenMap.remove(a); - } else { - sbuf.append("..."); - } - sbuf.append(']'); - } - - private static void booleanArrayAppend(StringBuffer sbuf, boolean[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) { - sbuf.append(", "); - } - } - sbuf.append(']'); - } - - private static void byteArrayAppend(StringBuffer sbuf, byte[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) { - sbuf.append(", "); - } - } - sbuf.append(']'); - } - - private static void charArrayAppend(StringBuffer sbuf, char[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) { - sbuf.append(", "); - } - } - sbuf.append(']'); - } - - private static void shortArrayAppend(StringBuffer sbuf, short[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) { - sbuf.append(", "); - } - } - sbuf.append(']'); - } - - private static void intArrayAppend(StringBuffer sbuf, int[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) { - sbuf.append(", "); - } - } - sbuf.append(']'); - } - - private static void longArrayAppend(StringBuffer sbuf, long[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) { - sbuf.append(", "); - } - } - sbuf.append(']'); - } - - private static void floatArrayAppend(StringBuffer sbuf, float[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) { - sbuf.append(", "); - } - } - sbuf.append(']'); - } - - private static void doubleArrayAppend(StringBuffer sbuf, double[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) { - sbuf.append(", "); - } - } - sbuf.append(']'); - } - - private MessageFormatter() { - } -} diff --git a/common/src/main/java/common/network/CompressionDecoder.java b/common/src/main/java/common/network/CompressionDecoder.java deleted file mode 100755 index 702aa11..0000000 --- a/common/src/main/java/common/network/CompressionDecoder.java +++ /dev/null @@ -1,47 +0,0 @@ -package common.network; - -import java.util.List; -import java.util.zip.DataFormatException; -import java.util.zip.Inflater; - -import common.net.buffer.ByteBuf; -import common.net.buffer.Unpooled; -import common.net.channel.ChannelHandlerContext; -import common.net.handler.codec.ByteToMessageDecoder; -import common.net.handler.codec.DecoderException; - -public class CompressionDecoder extends ByteToMessageDecoder { - private final Inflater inflater; - private int treshold; - - public CompressionDecoder(int treshold) { - this.treshold = treshold; - this.inflater = new Inflater(); - } - - protected void decode(ChannelHandlerContext context, ByteBuf buffer, List output) throws DataFormatException, Exception { - if(buffer.readableBytes() == 0) - return; - PacketBuffer pbuf = new PacketBuffer(buffer); - int len = pbuf.readVarInt(); - if(len == 0) { - output.add(pbuf.readBytes(pbuf.readableBytes())); - return; - } - if(len < this.treshold) - throw new DecoderException("Badly compressed packet - size of " + len + " is below server threshold of " + this.treshold); - if(len > 20971520) - throw new DecoderException("Badly compressed packet - size of " + len + " is larger than protocol maximum of " + 20971520); - byte[] comp = new byte[pbuf.readableBytes()]; - pbuf.readBytes(comp); - this.inflater.setInput(comp); - byte[] data = new byte[len]; - this.inflater.inflate(data); - output.add(Unpooled.wrappedBuffer(data)); - this.inflater.reset(); - } - - public void setTreshold(int treshold) { - this.treshold = treshold; - } -} diff --git a/common/src/main/java/common/network/CompressionEncoder.java b/common/src/main/java/common/network/CompressionEncoder.java deleted file mode 100755 index c2cf62f..0000000 --- a/common/src/main/java/common/network/CompressionEncoder.java +++ /dev/null @@ -1,42 +0,0 @@ -package common.network; - -import java.util.zip.Deflater; - -import common.net.buffer.ByteBuf; -import common.net.channel.ChannelHandlerContext; -import common.net.handler.codec.MessageToByteEncoder; - -public class CompressionEncoder extends MessageToByteEncoder { - private final byte[] buffer = new byte[8192]; - private final Deflater deflater; - private int treshold; - - public CompressionEncoder(int treshold) { - this.treshold = treshold; - this.deflater = new Deflater(); - } - - protected void encode(ChannelHandlerContext context, ByteBuf buffer, ByteBuf output) throws Exception { - int len = buffer.readableBytes(); - PacketBuffer pbuf = new PacketBuffer(output); - if(len < this.treshold) { - pbuf.writeVarInt(0); - pbuf.writeBuffer(buffer); - return; - } - byte[] data = new byte[len]; - buffer.readBytes(data); - pbuf.writeVarInt(data.length); - this.deflater.setInput(data, 0, len); - this.deflater.finish(); - while(!this.deflater.finished()) { - int size = this.deflater.deflate(this.buffer); - pbuf.writeBytes(this.buffer, 0, size); - } - this.deflater.reset(); - } - - public void setTreshold(int treshold) { - this.treshold = treshold; - } -} diff --git a/common/src/main/java/common/network/EncryptionDecoder.java b/common/src/main/java/common/network/EncryptionDecoder.java deleted file mode 100644 index 7c4bdb8..0000000 --- a/common/src/main/java/common/network/EncryptionDecoder.java +++ /dev/null @@ -1,21 +0,0 @@ -package common.network; - -import java.util.List; -import javax.crypto.Cipher; -import javax.crypto.ShortBufferException; - -import common.net.buffer.ByteBuf; -import common.net.channel.ChannelHandlerContext; -import common.net.handler.codec.MessageToMessageDecoder; - -public class EncryptionDecoder extends MessageToMessageDecoder { - private final EncryptionCodec codec; - - public EncryptionDecoder(Cipher cipher) { - this.codec = new EncryptionCodec(cipher); - } - - protected void decode(ChannelHandlerContext context, ByteBuf buffer, List output) throws ShortBufferException, Exception { - output.add(this.codec.decipher(context, buffer)); - } -} diff --git a/common/src/main/java/common/network/EncryptionEncoder.java b/common/src/main/java/common/network/EncryptionEncoder.java deleted file mode 100644 index 522c815..0000000 --- a/common/src/main/java/common/network/EncryptionEncoder.java +++ /dev/null @@ -1,20 +0,0 @@ -package common.network; - -import javax.crypto.Cipher; -import javax.crypto.ShortBufferException; - -import common.net.buffer.ByteBuf; -import common.net.channel.ChannelHandlerContext; -import common.net.handler.codec.MessageToByteEncoder; - -public class EncryptionEncoder extends MessageToByteEncoder { - private final EncryptionCodec codec; - - public EncryptionEncoder(Cipher cipher) { - this.codec = new EncryptionCodec(cipher); - } - - protected void encode(ChannelHandlerContext context, ByteBuf buffer, ByteBuf output) throws ShortBufferException, Exception { - this.codec.cipher(buffer, output); - } -} diff --git a/common/src/main/java/common/network/IClientLoginHandler.java b/common/src/main/java/common/network/IClientLoginHandler.java deleted file mode 100644 index 4048077..0000000 --- a/common/src/main/java/common/network/IClientLoginHandler.java +++ /dev/null @@ -1,19 +0,0 @@ -package common.network; - -import common.packet.RPacketChallenge; -import common.packet.RPacketDisconnect; -import common.packet.RPacketEnableCompression; -import common.packet.RPacketLoginSuccess; -import common.packet.RPacketRequestEncrypt; -import common.packet.RPacketResponse; -import common.packet.RPacketServerConfig; - -public interface IClientLoginHandler extends NetHandler { - void handleDisconnect(RPacketDisconnect packet); - void handleLoginSuccess(RPacketLoginSuccess packet); - void handleEnableCompression(RPacketEnableCompression packet); - void handleEncrypt(RPacketRequestEncrypt packet); - void handleConfig(RPacketServerConfig packet); - void handleResponse(RPacketResponse packet); - void handleChallenge(RPacketChallenge packet); -} diff --git a/common/src/main/java/common/network/IClientPlayer.java b/common/src/main/java/common/network/IClientPlayer.java deleted file mode 100644 index da6a2bc..0000000 --- a/common/src/main/java/common/network/IClientPlayer.java +++ /dev/null @@ -1,143 +0,0 @@ -package common.network; - -import common.entity.Entity; -import common.model.ParticleType; -import common.packet.SPacketEntity; -import common.packet.SPacketEntityTeleport; -import common.packet.SPacketEntityHeadLook; -import common.packet.SPacketEntityStatus; -import common.packet.SPacketEntityAttach; -import common.packet.SPacketEntityMetadata; -import common.packet.SPacketEntityEffect; -import common.packet.SPacketRemoveEntityEffect; -import common.packet.SPacketExplosion; -import common.packet.SPacketEffect; -import common.packet.SPacketSoundEffect; -import common.packet.SPacketParticles; -import common.packet.SPacketChangeGameState; -import common.packet.SPacketSpawnGlobalEntity; -import common.packet.SPacketOpenWindow; -import common.packet.SPacketCloseWindow; -import common.packet.SPacketSetSlot; -import common.packet.SPacketWindowItems; -import common.packet.SPacketWindowProperty; -import common.packet.SPacketConfirmTransaction; -import common.packet.SPacketUpdateSign; -import common.packet.SPacketUpdateTileEntity; -import common.packet.SPacketSignEditorOpen; -import common.packet.SPacketPlayerListItem; -import common.packet.SPacketPlayerAbilities; -import common.packet.SPacketTabComplete; -import common.packet.SPacketUpdateEntityTags; -import common.packet.SPacketAnimation; -import common.packet.SPacketBiome; -import common.packet.SPacketBlockAction; -import common.packet.SPacketBlockBreakAnim; -import common.packet.SPacketBlockChange; -import common.packet.SPacketCamera; -import common.packet.SPacketCharacterList; -import common.packet.SPacketChunkData; -import common.packet.SPacketCollectItem; -import common.packet.SPacketDestroyEntities; -import common.packet.SPacketDimensionName; -import common.packet.SPacketDisconnect; -import common.packet.SPacketDisplayForm; -import common.packet.SPacketEntityEquipment; -import common.packet.SPacketEntityVelocity; -import common.packet.SPacketHeldItemChange; -import common.packet.SPacketJoinGame; -import common.packet.SPacketKeepAlive; -import common.packet.SPacketLoading; -import common.packet.SPacketMapChunkBulk; -import common.packet.SPacketMessage; -import common.packet.SPacketMultiBlockChange; -import common.packet.SPacketPlayerPosLook; -import common.packet.SPacketRespawn; -import common.packet.SPacketServerTick; -import common.packet.SPacketSetExperience; -import common.packet.SPacketSkin; -import common.packet.SPacketSpawnMob; -import common.packet.SPacketSpawnObject; -import common.packet.SPacketSpawnPlayer; -import common.packet.SPacketTimeUpdate; -import common.packet.SPacketTrades; -import common.packet.SPacketUpdateHealth; -import common.packet.SPacketWorld; -import common.sound.Sound; - -public interface IClientPlayer extends NetHandler { - void playSound(Sound sound); - boolean isRenderViewEntity(Entity entity); - void updatePlayerMoveState(); - void emitParticleAtEntity(Entity entity, ParticleType particleTypes); - boolean isJumping(); - boolean isSprinting(); - boolean isSneaking(); - float getMoveForward(); - float getMoveStrafe(); - void setMoveForward(float value); - void setMoveStrafe(float value); - void addToSendQueue(Packet packet); - - void handleJoinGame(SPacketJoinGame packet); - void handleSpawnObject(SPacketSpawnObject packet); - void handleSpawnGlobalEntity(SPacketSpawnGlobalEntity packet); - void handleEntityVelocity(SPacketEntityVelocity packet); - void handleEntityMetadata(SPacketEntityMetadata packet); - void handleSpawnPlayer(SPacketSpawnPlayer packet); - void handleEntityTeleport(SPacketEntityTeleport packet); - void handleHeldItemChange(SPacketHeldItemChange packet); - void handleEntityMovement(SPacketEntity packet); - void handleEntityHeadLook(SPacketEntityHeadLook packet); - void handleDestroyEntities(SPacketDestroyEntities packet); - void handlePlayerPosLook(SPacketPlayerPosLook packet); - void handleMultiBlockChange(SPacketMultiBlockChange packet); - void handleChunkData(SPacketChunkData packet); - void handleBiomes(SPacketBiome packet); - void handleBlockChange(SPacketBlockChange packet); - void handleDisconnect(SPacketDisconnect packet); - void handleCollectItem(SPacketCollectItem packet); - void handleMessage(SPacketMessage packet); - void handleLoading(SPacketLoading packet); - void handleAnimation(SPacketAnimation packet); - void handleSpawnMob(SPacketSpawnMob packet); - void handleTimeUpdate(SPacketTimeUpdate packet); - void handleServerTick(SPacketServerTick packet); - void handleEntityAttach(SPacketEntityAttach packet); - void handleEntityStatus(SPacketEntityStatus packet); - void handleUpdateHealth(SPacketUpdateHealth packet); - void handleSetExperience(SPacketSetExperience packet); - void handleRespawn(SPacketRespawn packet); - void handleExplosion(SPacketExplosion packet); - void handleOpenWindow(SPacketOpenWindow packet); - void handleSetSlot(SPacketSetSlot packet); - void handleConfirmTransaction(SPacketConfirmTransaction packet); - void handleWindowItems(SPacketWindowItems packet); - void handleSignEditorOpen(SPacketSignEditorOpen packet); - void handleUpdateSign(SPacketUpdateSign packet); - void handleUpdateTileEntity(SPacketUpdateTileEntity packet); - void handleWindowProperty(SPacketWindowProperty packet); - void handleEntityEquipment(SPacketEntityEquipment packet); - void handleCloseWindow(SPacketCloseWindow packet); - void handleBlockAction(SPacketBlockAction packet); - void handleBlockBreakAnim(SPacketBlockBreakAnim packet); - void handleMapChunkBulk(SPacketMapChunkBulk packet); - void handleChangeGameState(SPacketChangeGameState packet); - void handleEffect(SPacketEffect packet); - void handleEntityEffect(SPacketEntityEffect packet); - void handleCamera(SPacketCamera packet); - void handleRemoveEntityEffect(SPacketRemoveEntityEffect packet); - void handlePlayerListItem(SPacketPlayerListItem packet); - void handleCharacterList(SPacketCharacterList packet); - void handleKeepAlive(SPacketKeepAlive packet); - void handlePlayerAbilities(SPacketPlayerAbilities packet); - void handleTabComplete(SPacketTabComplete packet); - void handleSoundEffect(SPacketSoundEffect packet); - void handleEntityTags(SPacketUpdateEntityTags packet); - void handleParticles(SPacketParticles packet); - void handleSkin(SPacketSkin packet); - void handleTrades(SPacketTrades packet); - void handleWorld(SPacketWorld packet); - void handleDimName(SPacketDimensionName packet); - void handleForm(SPacketDisplayForm packet); -} \ No newline at end of file diff --git a/common/src/main/java/common/network/IHandshakeHandler.java b/common/src/main/java/common/network/IHandshakeHandler.java deleted file mode 100644 index ce6426f..0000000 --- a/common/src/main/java/common/network/IHandshakeHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package common.network; - -import common.packet.HPacketHandshake; - -public interface IHandshakeHandler extends NetHandler { - void processHandshake(HPacketHandshake packet); -} diff --git a/common/src/main/java/common/network/ILoginHandler.java b/common/src/main/java/common/network/ILoginHandler.java deleted file mode 100644 index ff5d881..0000000 --- a/common/src/main/java/common/network/ILoginHandler.java +++ /dev/null @@ -1,15 +0,0 @@ -package common.network; - -import common.packet.LPacketChallenge; -import common.packet.LPacketPassword; -import common.packet.LPacketPubkey; -import common.packet.LPacketResponse; -import common.packet.LPacketStartEncrypt; - -public interface ILoginHandler extends NetHandler { - void processEncryption(LPacketStartEncrypt packet); - void processPassword(LPacketPassword packet); - void processPubkey(LPacketPubkey packet); - void processResponse(LPacketResponse packet); - void processChallenge(LPacketChallenge packet); -} diff --git a/common/src/main/java/common/network/NetConnection.java b/common/src/main/java/common/network/NetConnection.java deleted file mode 100755 index 6a742a1..0000000 --- a/common/src/main/java/common/network/NetConnection.java +++ /dev/null @@ -1,284 +0,0 @@ -package common.network; - -import java.io.IOException; -import java.net.SocketAddress; -import java.nio.channels.ClosedChannelException; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.regex.Pattern; - -import javax.crypto.Cipher; -import javax.crypto.SecretKey; - -import common.log.Log; -import common.net.channel.Channel; -import common.net.channel.ChannelFuture; -import common.net.channel.ChannelFutureListener; -import common.net.channel.ChannelHandlerContext; -import common.net.channel.SimpleChannelInboundHandler; -import common.net.handler.timeout.TimeoutException; -import common.net.util.AttributeKey; -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; -import common.network.NetHandler.ThreadQuickExitException; -import common.util.EncryptUtil; - -public class NetConnection extends SimpleChannelInboundHandler { - private static final boolean DEBUG = System.getProperty("network.debug") != null; - private static final Pattern IP_REPLACER = Pattern.compile("([0-9]*)\\.([0-9]*)\\.[0-9]*\\.[0-9]*"); - public static final AttributeKey ATTR_STATE = AttributeKey.valueOf("protocol"); - - private final Queue queue = new ConcurrentLinkedQueue(); - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - - private Channel channel; - private SocketAddress address; - private NetHandler handler; - private String exitReason; - private boolean disconnected; - - public void channelActive(ChannelHandlerContext context) throws Exception { - super.channelActive(context); - this.channel = context.channel(); - this.address = this.channel.remoteAddress(); - - try { - this.setConnectionState(PacketRegistry.HANDSHAKE); - } - catch(Throwable t) { - Log.NETWORK.error(t, "Fehler beim Aufbauen der Verbindung für Handshake"); - } - } - - public void setConnectionState(PacketRegistry newState) { - this.channel.attr(ATTR_STATE).set(newState); - this.channel.config().setAutoRead(true); - if(DEBUG) - Log.NETWORK.info("Automatisches Lesen eingeschaltet"); - } - - public void channelInactive(ChannelHandlerContext context) throws Exception { - this.closeChannel("Ende der Datenübertragung"); - } - - public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) throws Exception { - String comp; - - if(throwable instanceof TimeoutException) { - comp = "Zeitüberschreitung"; - } - else { - comp = "Interner Fehler: " + throwable; - if(!(throwable instanceof ClosedChannelException || throwable instanceof IOException)) - Log.NETWORK.error(throwable, "Fehler in der Verbindung mit %s", this.getCutAddress()); - } - - this.closeChannel(comp); - } - - protected void channelRead0(ChannelHandlerContext context, Packet packet) throws Exception { - if(DEBUG) - Log.NETWORK.info("EIN: [" + context.channel().attr(NetConnection.ATTR_STATE).get() + "] " + packet.getClass().getName()); - if(this.channel.isOpen()) { - try { - packet.processPacket(this.handler); - } - catch(ThreadQuickExitException e) { - ; - } - } - } - - public void setNetHandler(NetHandler handler) { - if(handler == null) { - throw new NullPointerException("Handler ist Null"); - } -// Log.debug("Setze Handler von " + this + " auf " + handler); - this.handler = handler; - } - - public void sendPacket(Packet packet) { - if(this.isChannelOpen()) { - this.flushOutboundQueue(); - this.dispatchPacket(packet, null); - } - else { - this.lock.writeLock().lock(); - - try { - this.queue.add(new NetConnection.InboundHandlerTuplePacketListener(packet, null)); - } - finally { - this.lock.writeLock().unlock(); - } - } - } - - public void sendPacket(Packet packet, GenericFutureListener> listener) { - if(this.isChannelOpen()) { - this.flushOutboundQueue(); - this.dispatchPacket(packet, new GenericFutureListener[] {listener}); - } - else { - this.lock.writeLock().lock(); - - try { - this.queue.add(new NetConnection.InboundHandlerTuplePacketListener(packet, listener)); - } - finally { - this.lock.writeLock().unlock(); - } - } - } - - private void dispatchPacket(final Packet packet, final GenericFutureListener>[] listeners) { - final PacketRegistry state = PacketRegistry.getType(packet); - final PacketRegistry current = this.channel.attr(ATTR_STATE).get(); - - if(current != state) { - if(DEBUG) - Log.NETWORK.info("Automatisches Lesen ausgeschaltet"); - this.channel.config().setAutoRead(false); - } - - if(this.channel.eventLoop().inEventLoop()) { - if(state != current) { - this.setConnectionState(state); - } - - if(DEBUG) - Log.NETWORK.info("AUS: [" + this.channel.attr(NetConnection.ATTR_STATE).get() + "] " + packet.getClass().getName()); - ChannelFuture future = this.channel.writeAndFlush(packet); - - if(listeners != null) { - future.addListeners(listeners); - } - - future.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); - } - else { - this.channel.eventLoop().execute(new Runnable() { - public void run() { - if(state != current) { - NetConnection.this.setConnectionState(state); - } - - if(DEBUG) - Log.NETWORK.info("AUS: [" + NetConnection.this.channel.attr(NetConnection.ATTR_STATE).get() + "] " + packet.getClass().getName()); - ChannelFuture future = NetConnection.this.channel.writeAndFlush(packet); - - if(listeners != null) { - future.addListeners(listeners); - } - - future.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); - } - }); - } - } - - private void flushOutboundQueue() { - if(this.channel != null && this.channel.isOpen()) { - this.lock.readLock().lock(); - - try { - while(!this.queue.isEmpty()) { - NetConnection.InboundHandlerTuplePacketListener entry = this.queue.poll(); - if(entry != null) // NPE Fix - this.dispatchPacket(entry.packet, entry.listeners); - } - } - finally { - this.lock.readLock().unlock(); - } - } - } - - public void processReceivedPackets() { - this.flushOutboundQueue(); - this.handler.update(); - if(this.channel != null) - this.channel.flush(); - if(DEBUG) - Log.NETWORK.info("Pakete synchronisiert"); - } - - public String getCutAddress() { - return this.address == null ? "?.?.*.*" : IP_REPLACER.matcher(this.address.toString()).replaceAll("$1.$2.*.*"); - } - - public void closeChannel(String message) { - if(this.channel.isOpen()) { - this.channel.close().awaitUninterruptibly(); - this.exitReason = message; - } - } - - public boolean isChannelOpen() { - return this.channel != null && this.channel.isOpen(); - } - - public boolean hasNoChannel() { - return this.channel == null; - } - - public void disableAutoRead() { - this.channel.config().setAutoRead(false); - } - - public void setCompressionTreshold(int treshold) { - if(treshold >= 0) { - if(this.channel.pipeline().get("decompress") instanceof CompressionDecoder) { - ((CompressionDecoder)this.channel.pipeline().get("decompress")).setTreshold(treshold); - } - else { - this.channel.pipeline().addBefore("decoder", "decompress", new CompressionDecoder(treshold)); - } - - if(this.channel.pipeline().get("compress") instanceof CompressionEncoder) { - ((CompressionEncoder)this.channel.pipeline().get("compress")).setTreshold(treshold); - } - else { - this.channel.pipeline().addBefore("encoder", "compress", new CompressionEncoder(treshold)); - } - } - else { - if(this.channel.pipeline().get("decompress") instanceof CompressionDecoder) { - this.channel.pipeline().remove("decompress"); - } - - if(this.channel.pipeline().get("compress") instanceof CompressionEncoder) { - this.channel.pipeline().remove("compress"); - } - } - } - - public void checkDisconnected() { - if(this.channel != null && !this.channel.isOpen()) { - if(!this.disconnected) { - this.disconnected = true; - if(this.handler != null) - this.handler.onDisconnect(this.exitReason != null ? this.exitReason : "Verbindung getrennt"); - } - else { - Log.NETWORK.warn("handleDisconnection() zweifach aufgerufen"); - } - } - } - - public void startEncryption(SecretKey key) { - this.channel.pipeline().addBefore("splitter", "decrypt", new EncryptionDecoder(EncryptUtil.createCipher(Cipher.DECRYPT_MODE, key))); - this.channel.pipeline().addBefore("prepender", "encrypt", new EncryptionEncoder(EncryptUtil.createCipher(Cipher.ENCRYPT_MODE, key))); - } - - private static class InboundHandlerTuplePacketListener { - private final Packet packet; - private final GenericFutureListener>[] listeners; - - public InboundHandlerTuplePacketListener(Packet packet, GenericFutureListener> listener) { - this.packet = packet; - this.listeners = listener == null ? null : new GenericFutureListener[] {listener}; - } - } -} diff --git a/common/src/main/java/common/network/PacketBuffer.java b/common/src/main/java/common/network/PacketBuffer.java deleted file mode 100755 index 5de7b2f..0000000 --- a/common/src/main/java/common/network/PacketBuffer.java +++ /dev/null @@ -1,262 +0,0 @@ -package common.network; - -import java.io.IOException; -import java.nio.charset.Charset; - -import common.init.ItemRegistry; -import common.item.ItemStack; -import common.net.buffer.ByteBuf; -import common.net.buffer.ByteBufInputStream; -import common.net.buffer.ByteBufOutputStream; -import common.net.handler.codec.DecoderException; -import common.net.handler.codec.EncoderException; -import common.tags.TagObject; -import common.util.BlockPos; - -public class PacketBuffer { - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - private final ByteBuf buf; - - public PacketBuffer(ByteBuf wrapped) { - this.buf = wrapped; - } - - public static int getVarIntSize(int input) { - for(int i = 1; i < 5; ++i) { - if((input & -1 << i * 7) == 0) - return i; - } - return 5; - } - - public void writeByteArray(byte[] data) { - this.writeVarInt(data.length); - this.writeBytes(data); - } - - public byte[] readByteArray() { - byte[] data = new byte[this.readVarInt()]; - this.readBytes(data); - return data; - } - - public void writeBlockPos(BlockPos pos) { - this.writeInt(pos.getX()); - this.writeInt(pos.getY()); - this.writeInt(pos.getZ()); - } - - public BlockPos readBlockPos() { - return new BlockPos(this.readInt(), this.readInt(), this.readInt()); - } - - public void writeEnumValue(Enum value) { - this.writeVarInt(value.ordinal()); - } - - public > T readEnumValue(Class clazz) { - return (T)((Enum[])clazz.getEnumConstants())[this.readVarInt()]; - } - - public void writeEnumOrNull(Enum value) { - this.writeVarInt(value == null ? -1 : value.ordinal()); - } - - public > T readEnumOrNull(Class clazz) { - int n = this.readVarInt(); - return n < 0 ? null : (T)((Enum[])clazz.getEnumConstants())[n]; - } - - public void writeVarInt(int value) { - while((value & -128) != 0) { - this.writeByte(value & 127 | 128); - value >>>= 7; - } - this.writeByte(value); - } - - public int readVarInt() { - int v = 0; - int c = 0; - while(true) { - byte b = this.readByte(); - v |= (b & 127) << c++ * 7; - if(c > 5) - throw new RuntimeException("VarInt too big"); - if((b & 128) != 128) - break; - } - return v; - } - - public void writeTag(TagObject tag) { - if(tag == null) { - this.writeByte(0); - return; - } - try { - TagObject.write(tag, new ByteBufOutputStream(this.buf)); - } - catch(IOException e) { - throw new EncoderException(e); - } - } - - public TagObject readTag() throws IOException { - int i = this.buf.readerIndex(); - byte b = this.readByte(); - if(b == 0) - return null; - this.buf.readerIndex(i); - return TagObject.read(new ByteBufInputStream(this.buf), 2097152); - } - - public void writeItemStack(ItemStack stack) { - if(stack == null) { - this.writeShort(-1); - return; - } - this.writeShort(ItemRegistry.getIdFromItem(stack.getItem())); - this.writeVarInt(stack.size); - this.writeShort(stack.getMetadata()); - this.writeTag(stack.getTagCompound()); - } - - public ItemStack readItemStack() throws IOException { - int id = this.readShort(); - if(id < 0) - return null; - int amt = this.readVarInt(); - int meta = this.readShort(); - ItemStack stack = new ItemStack(ItemRegistry.getItemById(id), amt, meta); - stack.setTagCompound(this.readTag()); - return stack; - } - - public void writeString(String str) { - byte[] data = str.getBytes(UTF_8); - if(data.length > 32767) - throw new EncoderException("String too big (was " + str.length() + " bytes encoded, max " + 32767 + ")"); - this.writeVarInt(data.length); - this.writeBytes(data); - } - - public String readString(int limit) { - int len = this.readVarInt(); - if(len > limit * 4) - throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + len + " > " + limit * 4 + ")"); - else if(len < 0) - throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!"); - byte[] data = new byte[len]; - this.readBytes(data); - String str = new String(data, UTF_8); - if(str.length() > limit) - throw new DecoderException("The received string length is longer than maximum allowed (" + len + " > " + limit + ")"); - return str; - } - - public void writeBoolean(boolean value) { - this.buf.writeBoolean(value); - } - - public boolean readBoolean() { - return this.buf.readBoolean(); - } - - public void writeByte(int value) { - this.buf.writeByte(value); - } - - public byte readByte() { - return this.buf.readByte(); - } - - public short readUnsignedByte() { - return this.buf.readUnsignedByte(); - } - - public void writeShort(int value) { - this.buf.writeShort(value); - } - - public short readShort() { - return this.buf.readShort(); - } - - public int readUnsignedShort() { - return this.buf.readUnsignedShort(); - } - - public void writeInt(int value) { - this.buf.writeInt(value); - } - - public int readInt() { - return this.buf.readInt(); - } - - public long readUnsignedInt() { - return this.buf.readUnsignedInt(); - } - - public void writeLong(long value) { - this.buf.writeLong(value); - } - - public long readLong() { - return this.buf.readLong(); - } - - public void writeFloat(float value) { - this.buf.writeFloat(value); - } - - public float readFloat() { - return this.buf.readFloat(); - } - - public void writeDouble(double value) { - this.buf.writeDouble(value); - } - - public double readDouble() { - return this.buf.readDouble(); - } - - public ByteBuf readBytes(int size) { - return this.buf.readBytes(size); - } - - public void writeBytes(byte[] data) { - this.buf.writeBytes(data); - } - - public void readBytes(byte[] buffer) { - this.buf.readBytes(buffer); - } - - public void writeBytes(byte[] data, int offset, int length) { - this.buf.writeBytes(data, offset, length); - } - - public void writeBuffer(ByteBuf buf) { - this.buf.writeBytes(buf); - } - - public void writeBuffer(ByteBuf buf, int offset, int length) { - this.buf.writeBytes(buf, offset, length); - } - - public int readableBytes() { - return this.buf.readableBytes(); - } - - public void ensureWritable(int size) { - this.buf.ensureWritable(size); - } - - public void release() { - this.buf.release(); - } -} diff --git a/common/src/main/java/common/network/PacketDecoder.java b/common/src/main/java/common/network/PacketDecoder.java deleted file mode 100755 index 121e34d..0000000 --- a/common/src/main/java/common/network/PacketDecoder.java +++ /dev/null @@ -1,31 +0,0 @@ -package common.network; - -import java.io.IOException; -import java.util.List; - -import common.net.buffer.ByteBuf; -import common.net.channel.ChannelHandlerContext; -import common.net.handler.codec.ByteToMessageDecoder; - -public class PacketDecoder extends ByteToMessageDecoder { - private final boolean client; - - public PacketDecoder(boolean client) { - this.client = client; - } - - protected void decode(ChannelHandlerContext context, ByteBuf buffer, List output) throws IOException, InstantiationException, IllegalAccessException, Exception { - if(buffer.readableBytes() == 0) - return; - PacketBuffer pbuf = new PacketBuffer(buffer); - int id = pbuf.readVarInt(); - Packet packet = context.channel().attr(NetConnection.ATTR_STATE).get().getPacket(this.client, id); - if(packet == null) - throw new IOException("Ungültige Paket-ID " + id); - packet.readPacketData(pbuf); - if(pbuf.readableBytes() > 0) - throw new IOException("Paket " + ((PacketRegistry)context.channel().attr(NetConnection.ATTR_STATE).get()).ordinal() + "/" + id + " (" - + packet.getClass() + ") war größer als erwartet, " + pbuf.readableBytes() + " weitere Bytes wurden beim Lesen von Paket " + id + " gefunden"); - output.add(packet); - } -} diff --git a/common/src/main/java/common/network/PacketEncoder.java b/common/src/main/java/common/network/PacketEncoder.java deleted file mode 100755 index 0f123ef..0000000 --- a/common/src/main/java/common/network/PacketEncoder.java +++ /dev/null @@ -1,29 +0,0 @@ -package common.network; - -import java.io.IOException; - -import common.net.buffer.ByteBuf; -import common.net.channel.ChannelHandlerContext; -import common.net.handler.codec.MessageToByteEncoder; - -public class PacketEncoder extends MessageToByteEncoder { - private final boolean client; - - public PacketEncoder(boolean client) { - this.client = client; - } - - protected void encode(ChannelHandlerContext context, Packet packet, ByteBuf output) throws IOException, Exception { - Integer id = context.channel().attr(NetConnection.ATTR_STATE).get().getId(this.client, packet); - if(id == null) - throw new IOException("Kann nicht registriertes Paket nicht serialisieren"); - PacketBuffer pbuf = new PacketBuffer(output); - pbuf.writeVarInt(id); - try { - packet.writePacketData(pbuf); - } - catch(Throwable t) { - throw new IOException("Fehler beim Schreiben der Paketdaten", t); - } - } -} diff --git a/common/src/main/java/common/network/PacketPrepender.java b/common/src/main/java/common/network/PacketPrepender.java deleted file mode 100755 index 943257c..0000000 --- a/common/src/main/java/common/network/PacketPrepender.java +++ /dev/null @@ -1,18 +0,0 @@ -package common.network; - -import common.net.buffer.ByteBuf; -import common.net.channel.ChannelHandlerContext; -import common.net.handler.codec.MessageToByteEncoder; - -public class PacketPrepender extends MessageToByteEncoder { - protected void encode(ChannelHandlerContext context, ByteBuf buffer, ByteBuf output) throws Exception { - int len = buffer.readableBytes(); - int vs = PacketBuffer.getVarIntSize(len); - if(vs > 3) - throw new IllegalArgumentException("unable to fit " + len + " into " + 3); - PacketBuffer pbuf = new PacketBuffer(output); - pbuf.ensureWritable(vs + len); - pbuf.writeVarInt(len); - pbuf.writeBuffer(buffer, buffer.readerIndex(), len); - } -} diff --git a/common/src/main/java/common/network/PacketRegistry.java b/common/src/main/java/common/network/PacketRegistry.java deleted file mode 100755 index 7467719..0000000 --- a/common/src/main/java/common/network/PacketRegistry.java +++ /dev/null @@ -1,253 +0,0 @@ -package common.network; - -import java.lang.reflect.InvocationTargetException; -import java.util.Map; - -import common.collect.BiMap; -import common.collect.HashBiMap; -import common.collect.Maps; -import common.packet.CPacketPlayerPosition; -import common.packet.CPacketPlayerLook; -import common.packet.CPacketPlayerPosLook; -import common.packet.CPacketAction; -import common.packet.CPacketBreak; -import common.packet.CPacketCheat; -import common.packet.CPacketClick; -import common.packet.CPacketComplete; -import common.packet.CPacketForm; -import common.packet.CPacketInput; -import common.packet.CPacketKeepAlive; -import common.packet.CPacketMessage; -import common.packet.CPacketPlace; -import common.packet.CPacketPlayer; -import common.packet.CPacketSign; -import common.packet.CPacketSkin; -import common.packet.HPacketHandshake; -import common.packet.LPacketChallenge; -import common.packet.LPacketPassword; -import common.packet.LPacketPubkey; -import common.packet.LPacketResponse; -import common.packet.LPacketStartEncrypt; -import common.packet.RPacketChallenge; -import common.packet.RPacketDisconnect; -import common.packet.RPacketEnableCompression; -import common.packet.RPacketLoginSuccess; -import common.packet.RPacketRequestEncrypt; -import common.packet.RPacketResponse; -import common.packet.RPacketServerConfig; -import common.packet.SPacketEntityRelMove; -import common.packet.SPacketEntityLook; -import common.packet.SPacketEntityLookMove; -import common.packet.SPacketEntity; -import common.packet.SPacketEntityTeleport; -import common.packet.SPacketEntityHeadLook; -import common.packet.SPacketEntityStatus; -import common.packet.SPacketEntityAttach; -import common.packet.SPacketEntityMetadata; -import common.packet.SPacketEntityEffect; -import common.packet.SPacketRemoveEntityEffect; -import common.packet.SPacketExplosion; -import common.packet.SPacketEffect; -import common.packet.SPacketSoundEffect; -import common.packet.SPacketParticles; -import common.packet.SPacketChangeGameState; -import common.packet.SPacketSpawnGlobalEntity; -import common.packet.SPacketOpenWindow; -import common.packet.SPacketCloseWindow; -import common.packet.SPacketSetSlot; -import common.packet.SPacketWindowItems; -import common.packet.SPacketWindowProperty; -import common.packet.SPacketConfirmTransaction; -import common.packet.SPacketUpdateSign; -import common.packet.SPacketUpdateTileEntity; -import common.packet.SPacketSignEditorOpen; -import common.packet.SPacketPlayerListItem; -import common.packet.SPacketPlayerAbilities; -import common.packet.SPacketTabComplete; -import common.packet.SPacketUpdateEntityTags; -import common.packet.SPacketAnimation; -import common.packet.SPacketBiome; -import common.packet.SPacketBlockAction; -import common.packet.SPacketBlockBreakAnim; -import common.packet.SPacketBlockChange; -import common.packet.SPacketCamera; -import common.packet.SPacketCharacterList; -import common.packet.SPacketChunkData; -import common.packet.SPacketCollectItem; -import common.packet.SPacketDestroyEntities; -import common.packet.SPacketDimensionName; -import common.packet.SPacketDisconnect; -import common.packet.SPacketDisplayForm; -import common.packet.SPacketEntityEquipment; -import common.packet.SPacketEntityVelocity; -import common.packet.SPacketHeldItemChange; -import common.packet.SPacketJoinGame; -import common.packet.SPacketKeepAlive; -import common.packet.SPacketLoading; -import common.packet.SPacketMapChunkBulk; -import common.packet.SPacketMessage; -import common.packet.SPacketMultiBlockChange; -import common.packet.SPacketPlayerPosLook; -import common.packet.SPacketRespawn; -import common.packet.SPacketServerTick; -import common.packet.SPacketSetExperience; -import common.packet.SPacketSkin; -import common.packet.SPacketSpawnMob; -import common.packet.SPacketSpawnObject; -import common.packet.SPacketSpawnPlayer; -import common.packet.SPacketTimeUpdate; -import common.packet.SPacketTrades; -import common.packet.SPacketUpdateHealth; -import common.packet.SPacketWorld; - -public enum PacketRegistry { - HANDSHAKE {{ - this.client(HPacketHandshake.class); - }}, - LOGIN {{ - this.server(RPacketDisconnect.class); - this.server(RPacketRequestEncrypt.class); - this.server(RPacketResponse.class); - this.server(RPacketChallenge.class); - this.server(RPacketServerConfig.class); - this.server(RPacketLoginSuccess.class); - this.server(RPacketEnableCompression.class); - - this.client(LPacketStartEncrypt.class); - this.client(LPacketPassword.class); - this.client(LPacketChallenge.class); - this.client(LPacketPubkey.class); - this.client(LPacketResponse.class); - }}, - PLAY {{ - this.server(SPacketKeepAlive.class); - this.server(SPacketJoinGame.class); - this.server(SPacketMessage.class); - this.server(SPacketTimeUpdate.class); - this.server(SPacketEntityEquipment.class); - this.server(SPacketUpdateHealth.class); - this.server(SPacketRespawn.class); - this.server(SPacketPlayerPosLook.class); - this.server(SPacketHeldItemChange.class); - this.server(SPacketAnimation.class); - this.server(SPacketSpawnPlayer.class); - this.server(SPacketCollectItem.class); - this.server(SPacketSpawnObject.class); - this.server(SPacketSpawnMob.class); - this.server(SPacketEntityVelocity.class); - this.server(SPacketDestroyEntities.class); - this.server(SPacketEntity.class); - this.server(SPacketEntityRelMove.class); - this.server(SPacketEntityLook.class); - this.server(SPacketEntityLookMove.class); - this.server(SPacketEntityTeleport.class); - this.server(SPacketEntityHeadLook.class); - this.server(SPacketEntityStatus.class); - this.server(SPacketEntityAttach.class); - this.server(SPacketEntityMetadata.class); - this.server(SPacketEntityEffect.class); - this.server(SPacketRemoveEntityEffect.class); - this.server(SPacketSetExperience.class); - this.server(SPacketChunkData.class); - this.server(SPacketMultiBlockChange.class); - this.server(SPacketBlockChange.class); - this.server(SPacketBlockAction.class); - this.server(SPacketBlockBreakAnim.class); - this.server(SPacketMapChunkBulk.class); - this.server(SPacketExplosion.class); - this.server(SPacketEffect.class); - this.server(SPacketSoundEffect.class); - this.server(SPacketParticles.class); - this.server(SPacketChangeGameState.class); - this.server(SPacketSpawnGlobalEntity.class); - this.server(SPacketOpenWindow.class); - this.server(SPacketCloseWindow.class); - this.server(SPacketSetSlot.class); - this.server(SPacketWindowItems.class); - this.server(SPacketWindowProperty.class); - this.server(SPacketConfirmTransaction.class); - this.server(SPacketUpdateSign.class); - this.server(SPacketUpdateTileEntity.class); - this.server(SPacketSignEditorOpen.class); - this.server(SPacketPlayerListItem.class); - this.server(SPacketPlayerAbilities.class); - this.server(SPacketTabComplete.class); - this.server(SPacketSkin.class); - this.server(SPacketDisconnect.class); - this.server(SPacketWorld.class); - this.server(SPacketCamera.class); - this.server(SPacketBiome.class); - this.server(SPacketUpdateEntityTags.class); - this.server(SPacketTrades.class); - this.server(SPacketDimensionName.class); - this.server(SPacketCharacterList.class); - this.server(SPacketServerTick.class); - this.server(SPacketLoading.class); - this.server(SPacketDisplayForm.class); - - this.client(CPacketKeepAlive.class); - this.client(CPacketMessage.class); - this.client(CPacketAction.class); - this.client(CPacketPlayer.class); - this.client(CPacketPlayerPosition.class); - this.client(CPacketPlayerLook.class); - this.client(CPacketPlayerPosLook.class); - this.client(CPacketBreak.class); - this.client(CPacketPlace.class); - this.client(CPacketInput.class); - this.client(CPacketClick.class); - this.client(CPacketCheat.class); - this.client(CPacketComplete.class); - this.client(CPacketSkin.class); - this.client(CPacketSign.class); - this.client(CPacketForm.class); - }}; - - private static final Map, PacketRegistry> STATES = Maps., PacketRegistry>newHashMap(); - - private final BiMap> server = HashBiMap.>create(); - private final BiMap> client = HashBiMap.>create(); - - protected void server(Class clazz) { - if(this.server.containsValue(clazz)) - throw new IllegalArgumentException("S-Paket " + clazz + " ist bereits bekannt unter ID " + this.server.inverse().get(clazz)); - this.server.put(Integer.valueOf(this.server.size()), clazz); - } - - protected void client(Class clazz) { - if(this.client.containsValue(clazz)) - throw new IllegalArgumentException("C-Paket " + clazz + " ist bereits bekannt unter ID " + this.client.inverse().get(clazz)); - this.client.put(Integer.valueOf(this.client.size()), clazz); - } - - public Integer getId(boolean client, Packet packet) { - return (client ? this.client : this.server).inverse().get(packet.getClass()); - } - - public Packet getPacket(boolean client, int id) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { - Class oclass = (client ? this.client : this.server).get(id); - return oclass == null ? null : oclass.getConstructor().newInstance(); - } - - public static PacketRegistry getType(Packet packet) { - return STATES.get(packet.getClass()); - } - - static { - for(PacketRegistry reg : values()) { - for(BiMap> map : new BiMap[] {reg.server, reg.client}) { - for(Class clazz : map.values()) { - if(STATES.containsKey(clazz) && STATES.get(clazz) != reg) - throw new Error("Paket " + clazz + " ist bereits zu ID " + STATES.get(clazz) + " zugewiesen - kann nicht auf " + reg + " neu zuweisen"); - try { - clazz.getConstructor().newInstance(); - } - catch(Throwable e) { - throw new Error("Paket " + clazz + " kann nicht instanziert werden!"); - } - STATES.put(clazz, reg); - } - } - } - } -} diff --git a/common/src/main/java/common/network/PacketSplitter.java b/common/src/main/java/common/network/PacketSplitter.java deleted file mode 100755 index 3874408..0000000 --- a/common/src/main/java/common/network/PacketSplitter.java +++ /dev/null @@ -1,39 +0,0 @@ -package common.network; - -import java.util.List; - -import common.net.buffer.ByteBuf; -import common.net.buffer.Unpooled; -import common.net.channel.ChannelHandlerContext; -import common.net.handler.codec.ByteToMessageDecoder; -import common.net.handler.codec.CorruptedFrameException; - -public class PacketSplitter extends ByteToMessageDecoder { - protected void decode(ChannelHandlerContext context, ByteBuf buffer, List output) throws Exception { - buffer.markReaderIndex(); - byte[] data = new byte[3]; - for(int z = 0; z < data.length; z++) { - if(!buffer.isReadable()) { - buffer.resetReaderIndex(); - return; - } - data[z] = buffer.readByte(); - if(data[z] < 0) - continue; - PacketBuffer pbuf = new PacketBuffer(Unpooled.wrappedBuffer(data)); - try { - int len = pbuf.readVarInt(); - if(buffer.readableBytes() >= len) { - output.add(buffer.readBytes(len)); - return; - } - buffer.resetReaderIndex(); - } - finally { - pbuf.release(); - } - return; - } - throw new CorruptedFrameException("length wider than 21-bit"); - } -} diff --git a/common/src/main/java/common/packet/CPacketPlayer.java b/common/src/main/java/common/packet/CPacketPlayer.java deleted file mode 100755 index ccafdc3..0000000 --- a/common/src/main/java/common/packet/CPacketPlayer.java +++ /dev/null @@ -1,88 +0,0 @@ -package common.packet; - -import java.io.IOException; - -import common.network.IPlayer; -import common.network.Packet; -import common.network.PacketBuffer; - -public class CPacketPlayer implements Packet -{ - protected double x; - protected double y; - protected double z; - protected float yaw; - protected float pitch; - protected boolean onGround; - protected boolean moving; - protected boolean rotating; - - public CPacketPlayer() - { - } - - public CPacketPlayer(boolean isOnGround) - { - this.onGround = isOnGround; - } - - public void processPacket(IPlayer handler) - { - handler.processPlayer(this); - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - this.onGround = buf.readUnsignedByte() != 0; - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeByte(this.onGround ? 1 : 0); - } - - public double getPositionX() - { - return this.x; - } - - public double getPositionY() - { - return this.y; - } - - public double getPositionZ() - { - return this.z; - } - - public float getYaw() - { - return this.yaw; - } - - public float getPitch() - { - return this.pitch; - } - - public boolean isOnGround() - { - return this.onGround; - } - - public boolean isMoving() - { - return this.moving; - } - - public boolean getRotating() - { - return this.rotating; - } - - public void setMoving(boolean isMoving) - { - this.moving = isMoving; - } -} diff --git a/common/src/main/java/common/packet/CPacketPlayerLook.java b/common/src/main/java/common/packet/CPacketPlayerLook.java deleted file mode 100644 index 47237f7..0000000 --- a/common/src/main/java/common/packet/CPacketPlayerLook.java +++ /dev/null @@ -1,35 +0,0 @@ -package common.packet; - -import java.io.IOException; - -import common.network.PacketBuffer; - -public class CPacketPlayerLook extends CPacketPlayer -{ - public CPacketPlayerLook() - { - this.rotating = true; - } - - public CPacketPlayerLook(float playerYaw, float playerPitch, boolean isOnGround) - { - this.yaw = playerYaw; - this.pitch = playerPitch; - this.onGround = isOnGround; - this.rotating = true; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - this.yaw = buf.readFloat(); - this.pitch = buf.readFloat(); - super.readPacketData(buf); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeFloat(this.yaw); - buf.writeFloat(this.pitch); - super.writePacketData(buf); - } -} \ No newline at end of file diff --git a/common/src/main/java/common/packet/CPacketPlayerPosLook.java b/common/src/main/java/common/packet/CPacketPlayerPosLook.java deleted file mode 100644 index 9b02b82..0000000 --- a/common/src/main/java/common/packet/CPacketPlayerPosLook.java +++ /dev/null @@ -1,46 +0,0 @@ -package common.packet; - -import java.io.IOException; - -import common.network.PacketBuffer; - -public class CPacketPlayerPosLook extends CPacketPlayer -{ - public CPacketPlayerPosLook() - { - this.moving = true; - this.rotating = true; - } - - public CPacketPlayerPosLook(double playerX, double playerY, double playerZ, float playerYaw, float playerPitch, boolean playerIsOnGround) - { - this.x = playerX; - this.y = playerY; - this.z = playerZ; - this.yaw = playerYaw; - this.pitch = playerPitch; - this.onGround = playerIsOnGround; - this.rotating = true; - this.moving = true; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - this.x = buf.readDouble(); - this.y = buf.readDouble(); - this.z = buf.readDouble(); - this.yaw = buf.readFloat(); - this.pitch = buf.readFloat(); - super.readPacketData(buf); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeDouble(this.x); - buf.writeDouble(this.y); - buf.writeDouble(this.z); - buf.writeFloat(this.yaw); - buf.writeFloat(this.pitch); - super.writePacketData(buf); - } -} \ No newline at end of file diff --git a/common/src/main/java/common/packet/CPacketPlayerPosition.java b/common/src/main/java/common/packet/CPacketPlayerPosition.java deleted file mode 100644 index a82ad3e..0000000 --- a/common/src/main/java/common/packet/CPacketPlayerPosition.java +++ /dev/null @@ -1,38 +0,0 @@ -package common.packet; - -import java.io.IOException; - -import common.network.PacketBuffer; - -public class CPacketPlayerPosition extends CPacketPlayer -{ - public CPacketPlayerPosition() - { - this.moving = true; - } - - public CPacketPlayerPosition(double posX, double posY, double posZ, boolean isOnGround) - { - this.x = posX; - this.y = posY; - this.z = posZ; - this.onGround = isOnGround; - this.moving = true; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - this.x = buf.readDouble(); - this.y = buf.readDouble(); - this.z = buf.readDouble(); - super.readPacketData(buf); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeDouble(this.x); - buf.writeDouble(this.y); - buf.writeDouble(this.z); - super.writePacketData(buf); - } -} \ No newline at end of file diff --git a/common/src/main/java/common/packet/LPacketChallenge.java b/common/src/main/java/common/packet/LPacketChallenge.java deleted file mode 100644 index 11fceec..0000000 --- a/common/src/main/java/common/packet/LPacketChallenge.java +++ /dev/null @@ -1,33 +0,0 @@ -package common.packet; - -import java.io.IOException; -import common.network.ILoginHandler; -import common.network.Packet; -import common.network.PacketBuffer; - -public class LPacketChallenge implements Packet { - private byte[] token; - - public LPacketChallenge() { - } - - public LPacketChallenge(byte[] token) { - this.token = token; - } - - public final void readPacketData(PacketBuffer buf) throws IOException { - this.token = buf.readByteArray(); - } - - public final void writePacketData(PacketBuffer buf) throws IOException { - buf.writeByteArray(this.token); - } - - public void processPacket(ILoginHandler handler) { - handler.processChallenge(this); - } - - public byte[] getToken() { - return this.token; - } -} diff --git a/common/src/main/java/common/packet/LPacketPubkey.java b/common/src/main/java/common/packet/LPacketPubkey.java deleted file mode 100644 index 873a247..0000000 --- a/common/src/main/java/common/packet/LPacketPubkey.java +++ /dev/null @@ -1,53 +0,0 @@ -package common.packet; - -import java.io.IOException; -import java.security.PublicKey; - -import common.network.ILoginHandler; -import common.network.IPlayer; -import common.network.Packet; -import common.network.PacketBuffer; -import common.util.EncryptUtil; - -public class LPacketPubkey implements Packet { - private String user; - private String access; - private PublicKey key; - - public LPacketPubkey() { - } - - public LPacketPubkey(String user, String access, PublicKey key) { - this.user = user; - this.access = access; - this.key = key; - } - - public final void readPacketData(PacketBuffer buf) throws IOException { - this.user = buf.readString(IPlayer.MAX_USER_LENGTH); - this.access = buf.readString(IPlayer.MAX_PASS_LENGTH); - this.key = EncryptUtil.decodePublicKey(buf.readByteArray()); - } - - public final void writePacketData(PacketBuffer buf) throws IOException { - buf.writeString(this.user); - buf.writeString(this.access); - buf.writeByteArray(this.key.getEncoded()); - } - - public void processPacket(ILoginHandler handler) { - handler.processPubkey(this); - } - - public String getUser() { - return this.user; - } - - public String getAccess() { - return this.access; - } - - public PublicKey getKey() { - return this.key; - } -} diff --git a/common/src/main/java/common/packet/LPacketResponse.java b/common/src/main/java/common/packet/LPacketResponse.java deleted file mode 100644 index 554bc1e..0000000 --- a/common/src/main/java/common/packet/LPacketResponse.java +++ /dev/null @@ -1,37 +0,0 @@ -package common.packet; - -import java.io.IOException; -import java.security.PrivateKey; -import java.security.PublicKey; - -import common.network.ILoginHandler; -import common.network.Packet; -import common.network.PacketBuffer; -import common.util.EncryptUtil; - -public class LPacketResponse implements Packet { - private byte[] token = new byte[0]; - - public LPacketResponse() { - } - - public LPacketResponse(PrivateKey key, byte[] token) { - this.token = EncryptUtil.createSignature(key, token); - } - - public void readPacketData(PacketBuffer buf) throws IOException { - this.token = buf.readByteArray(); - } - - public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeByteArray(this.token); - } - - public void processPacket(ILoginHandler handler) { - handler.processResponse(this); - } - - public boolean verifyToken(PublicKey key, byte[] token) { - return EncryptUtil.verifySignature(key, token, this.token); - } -} diff --git a/common/src/main/java/common/packet/LPacketStartEncrypt.java b/common/src/main/java/common/packet/LPacketStartEncrypt.java deleted file mode 100644 index b6d4995..0000000 --- a/common/src/main/java/common/packet/LPacketStartEncrypt.java +++ /dev/null @@ -1,36 +0,0 @@ -package common.packet; - -import java.io.IOException; -import java.security.PublicKey; - -import common.network.ILoginHandler; -import common.network.Packet; -import common.network.PacketBuffer; -import common.util.EncryptUtil; - -public class LPacketStartEncrypt implements Packet { - private PublicKey key; - - public LPacketStartEncrypt() { - } - - public LPacketStartEncrypt(PublicKey pubkey) { - this.key = pubkey; - } - - public void readPacketData(PacketBuffer buf) throws IOException { - this.key = EncryptUtil.decodeDHPublicKey(buf.readByteArray()); - } - - public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeByteArray(this.key.getEncoded()); - } - - public void processPacket(ILoginHandler handler) { - handler.processEncryption(this); - } - - public PublicKey getKey() { - return this.key; - } -} diff --git a/common/src/main/java/common/packet/RPacketChallenge.java b/common/src/main/java/common/packet/RPacketChallenge.java deleted file mode 100644 index 9ae9012..0000000 --- a/common/src/main/java/common/packet/RPacketChallenge.java +++ /dev/null @@ -1,33 +0,0 @@ -package common.packet; - -import java.io.IOException; -import common.network.IClientLoginHandler; -import common.network.Packet; -import common.network.PacketBuffer; - -public class RPacketChallenge implements Packet { - private byte[] token; - - public RPacketChallenge() { - } - - public RPacketChallenge(byte[] token) { - this.token = token; - } - - public final void readPacketData(PacketBuffer buf) throws IOException { - this.token = buf.readByteArray(); - } - - public final void writePacketData(PacketBuffer buf) throws IOException { - buf.writeByteArray(this.token); - } - - public void processPacket(IClientLoginHandler handler) { - handler.handleChallenge(this); - } - - public byte[] getToken() { - return this.token; - } -} diff --git a/common/src/main/java/common/packet/RPacketResponse.java b/common/src/main/java/common/packet/RPacketResponse.java deleted file mode 100644 index aa3e490..0000000 --- a/common/src/main/java/common/packet/RPacketResponse.java +++ /dev/null @@ -1,37 +0,0 @@ -package common.packet; - -import java.io.IOException; -import java.security.PrivateKey; -import java.security.PublicKey; - -import common.network.IClientLoginHandler; -import common.network.Packet; -import common.network.PacketBuffer; -import common.util.EncryptUtil; - -public class RPacketResponse implements Packet { - private byte[] token = new byte[0]; - - public RPacketResponse() { - } - - public RPacketResponse(PrivateKey key, byte[] token) { - this.token = EncryptUtil.createSignature(key, token); - } - - public void readPacketData(PacketBuffer buf) throws IOException { - this.token = buf.readByteArray(); - } - - public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeByteArray(this.token); - } - - public void processPacket(IClientLoginHandler handler) { - handler.handleResponse(this); - } - - public boolean verifyToken(PublicKey key, byte[] token) { - return EncryptUtil.verifySignature(key, token, this.token); - } -} diff --git a/common/src/main/java/common/packet/RPacketServerConfig.java b/common/src/main/java/common/packet/RPacketServerConfig.java deleted file mode 100644 index 5c5a2e9..0000000 --- a/common/src/main/java/common/packet/RPacketServerConfig.java +++ /dev/null @@ -1,60 +0,0 @@ -package common.packet; - -import java.io.IOException; -import common.network.IClientLoginHandler; -import common.network.Packet; -import common.network.PacketBuffer; - -public class RPacketServerConfig implements Packet { - private boolean requiresAccess; - private boolean requiresAuth; - private boolean passwordAuth; - private boolean pubkeyAuth; - - public RPacketServerConfig() { - } - - public RPacketServerConfig(boolean requiresAccess, boolean requiresAuth, boolean passwordAuth, boolean pubkeyAuth) { - this.requiresAccess = requiresAccess; - this.requiresAuth = requiresAuth; - this.passwordAuth = passwordAuth; - this.pubkeyAuth = pubkeyAuth; - } - - public final void readPacketData(PacketBuffer buf) throws IOException { - byte flags = buf.readByte(); - this.requiresAccess = (flags & 1) != 0; - this.requiresAuth = (flags & 2) != 0; - this.passwordAuth = (flags & 4) != 0; - this.pubkeyAuth = (flags & 8) != 0; - } - - public final void writePacketData(PacketBuffer buf) throws IOException { - byte flags = 0; - flags |= this.requiresAccess ? 1 : 0; - flags |= this.requiresAuth ? 2 : 0; - flags |= this.passwordAuth ? 4 : 0; - flags |= this.pubkeyAuth ? 8 : 0; - buf.writeByte(flags); - } - - public void processPacket(IClientLoginHandler handler) { - handler.handleConfig(this); - } - - public boolean hasAccessPassword() { - return this.requiresAccess; - } - - public boolean isAuthenticating() { - return this.requiresAuth; - } - - public boolean canUsePassword() { - return this.passwordAuth; - } - - public boolean canUsePubkey() { - return this.pubkeyAuth; - } -} diff --git a/common/src/main/java/common/packet/SPacketBiome.java b/common/src/main/java/common/packet/SPacketBiome.java deleted file mode 100755 index 9991545..0000000 --- a/common/src/main/java/common/packet/SPacketBiome.java +++ /dev/null @@ -1,56 +0,0 @@ -package common.packet; - -import java.io.IOException; - -import common.biome.Biome; -import common.network.IClientPlayer; -import common.network.Packet; -import common.network.PacketBuffer; -import common.util.BlockPos; - -public class SPacketBiome implements Packet { - private int posX; - private int posZ; - private Biome biome; - - public SPacketBiome() { - } - - public SPacketBiome(BlockPos pos, Biome biome) { - this.posX = pos.getX(); - this.posZ = pos.getZ(); - this.biome = biome; - } - - public void readPacketData(PacketBuffer buf) throws IOException { - this.posX = buf.readInt(); - this.posZ = buf.readInt(); - this.biome = buf.readEnumValue(Biome.class); - } - - public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeInt(this.posX); - buf.writeInt(this.posZ); - buf.writeEnumValue(this.biome); - } - - public void processPacket(IClientPlayer handler) { - handler.handleBiomes(this); - } - - public int getChunkX() { - return this.posX >> 4; - } - - public int getChunkZ() { - return this.posZ >> 4; - } - - public BlockPos getPos() { - return new BlockPos(this.posX, 0, this.posZ); - } - - public Biome getBiome() { - return this.biome; - } -} diff --git a/common/src/main/java/common/packet/SPacketChunkData.java b/common/src/main/java/common/packet/SPacketChunkData.java deleted file mode 100755 index 3aac135..0000000 --- a/common/src/main/java/common/packet/SPacketChunkData.java +++ /dev/null @@ -1,105 +0,0 @@ -package common.packet; - -import java.io.IOException; -import common.network.IClientPlayer; -import common.network.Packet; -import common.network.PacketBuffer; - -public class SPacketChunkData implements Packet -{ - private int chunkX; - private int chunkZ; - private SPacketChunkData.Extracted extractedData; - private boolean biomes; - - public SPacketChunkData() - { - } - - public SPacketChunkData(int x, int z, boolean biomes, SPacketChunkData.Extracted data) - { - this.chunkX = x; - this.chunkZ = z; - this.biomes = biomes; - this.extractedData = data; - } - - /** - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer buf) throws IOException - { - this.chunkX = buf.readInt(); - this.chunkZ = buf.readInt(); - this.biomes = buf.readBoolean(); - this.extractedData = new SPacketChunkData.Extracted(); - this.extractedData.data = buf.readByteArray(); - this.extractedData.extend = new int[buf.readVarInt()]; - for(int z = 0; z < this.extractedData.extend.length; z++) { - this.extractedData.extend[z] = buf.readVarInt(); - } - } - - /** - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeInt(this.chunkX); - buf.writeInt(this.chunkZ); - buf.writeBoolean(this.biomes); - buf.writeByteArray(this.extractedData.data); - buf.writeVarInt(this.extractedData.extend.length); - for(int z = 0; z < this.extractedData.extend.length; z++) { - buf.writeVarInt(this.extractedData.extend[z]); - } - } - - /** - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(IClientPlayer handler) - { - handler.handleChunkData(this); - } - - public byte[] getExtractedDataBytes() - { - return this.extractedData.data; - } - - public static int getSize(int segments, boolean overworld, boolean biomes) - { - int i = segments * 2 * 16 * 16 * 16; - int j = segments * 16 * 16 * 16 / 2; - int k = overworld ? segments * 16 * 16 * 16 / 2 : 0; - int l = biomes ? 256 : 0; - return i + j + k + l; - } - - public int getChunkX() - { - return this.chunkX; - } - - public int getChunkZ() - { - return this.chunkZ; - } - - public int[] getExtractedExtend() - { - return this.extractedData.extend; - } - - public boolean hasBiomes() - { - return this.biomes; - } - - public static class Extracted - { - public byte[] data; - public int[] extend; - } -} diff --git a/common/src/main/java/common/packet/SPacketEntity.java b/common/src/main/java/common/packet/SPacketEntity.java deleted file mode 100755 index 7b05088..0000000 --- a/common/src/main/java/common/packet/SPacketEntity.java +++ /dev/null @@ -1,99 +0,0 @@ -package common.packet; - -import java.io.IOException; - -import common.entity.Entity; -import common.network.IClientPlayer; -import common.network.Packet; -import common.network.PacketBuffer; -import common.world.World; - -public class SPacketEntity implements Packet -{ - protected int entityId; - protected byte posX; - protected byte posY; - protected byte posZ; - protected byte yaw; - protected byte pitch; - protected boolean onGround; - protected boolean rotation; - - public SPacketEntity() - { - } - - public SPacketEntity(int entityIdIn) - { - this.entityId = entityIdIn; - } - - /** - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer buf) throws IOException - { - this.entityId = buf.readVarInt(); - } - - /** - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeVarInt(this.entityId); - } - - /** - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(IClientPlayer handler) - { - handler.handleEntityMovement(this); - } - - public String toString() - { - return "Entity_" + super.toString(); - } - - public Entity getEntity(World worldIn) - { - return worldIn.getEntityByID(this.entityId); - } - - public byte getPosX() - { - return this.posX; - } - - public byte getPosY() - { - return this.posY; - } - - public byte getPosZ() - { - return this.posZ; - } - - public byte getYaw() - { - return this.yaw; - } - - public byte getPitch() - { - return this.pitch; - } - - public boolean hasRotations() - { - return this.rotation; - } - - public boolean getOnGround() - { - return this.onGround; - } -} diff --git a/common/src/main/java/common/packet/SPacketEntityLook.java b/common/src/main/java/common/packet/SPacketEntityLook.java deleted file mode 100644 index e9ffbb0..0000000 --- a/common/src/main/java/common/packet/SPacketEntityLook.java +++ /dev/null @@ -1,38 +0,0 @@ -package common.packet; - -import java.io.IOException; - -import common.network.PacketBuffer; - -public class SPacketEntityLook extends SPacketEntity -{ - public SPacketEntityLook() - { - this.rotation = true; - } - - public SPacketEntityLook(int entityIdIn, byte yawIn, byte pitchIn, boolean onGroundIn) - { - super(entityIdIn); - this.yaw = yawIn; - this.pitch = pitchIn; - this.rotation = true; - this.onGround = onGroundIn; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - super.readPacketData(buf); - this.yaw = buf.readByte(); - this.pitch = buf.readByte(); - this.onGround = buf.readBoolean(); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - super.writePacketData(buf); - buf.writeByte(this.yaw); - buf.writeByte(this.pitch); - buf.writeBoolean(this.onGround); - } -} \ No newline at end of file diff --git a/common/src/main/java/common/packet/SPacketEntityLookMove.java b/common/src/main/java/common/packet/SPacketEntityLookMove.java deleted file mode 100644 index 878aa46..0000000 --- a/common/src/main/java/common/packet/SPacketEntityLookMove.java +++ /dev/null @@ -1,47 +0,0 @@ -package common.packet; - -import java.io.IOException; - -import common.network.PacketBuffer; - -public class SPacketEntityLookMove extends SPacketEntity -{ - public SPacketEntityLookMove() - { - this.rotation = true; - } - - public SPacketEntityLookMove(int p_i45973_1_, byte p_i45973_2_, byte p_i45973_3_, byte p_i45973_4_, byte p_i45973_5_, byte p_i45973_6_, boolean p_i45973_7_) - { - super(p_i45973_1_); - this.posX = p_i45973_2_; - this.posY = p_i45973_3_; - this.posZ = p_i45973_4_; - this.yaw = p_i45973_5_; - this.pitch = p_i45973_6_; - this.onGround = p_i45973_7_; - this.rotation = true; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - super.readPacketData(buf); - this.posX = buf.readByte(); - this.posY = buf.readByte(); - this.posZ = buf.readByte(); - this.yaw = buf.readByte(); - this.pitch = buf.readByte(); - this.onGround = buf.readBoolean(); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - super.writePacketData(buf); - buf.writeByte(this.posX); - buf.writeByte(this.posY); - buf.writeByte(this.posZ); - buf.writeByte(this.yaw); - buf.writeByte(this.pitch); - buf.writeBoolean(this.onGround); - } -} \ No newline at end of file diff --git a/common/src/main/java/common/packet/SPacketEntityRelMove.java b/common/src/main/java/common/packet/SPacketEntityRelMove.java deleted file mode 100644 index 4c5a9fa..0000000 --- a/common/src/main/java/common/packet/SPacketEntityRelMove.java +++ /dev/null @@ -1,39 +0,0 @@ -package common.packet; - -import java.io.IOException; - -import common.network.PacketBuffer; - -public class SPacketEntityRelMove extends SPacketEntity -{ - public SPacketEntityRelMove() - { - } - - public SPacketEntityRelMove(int entityIdIn, byte x, byte y, byte z, boolean onGroundIn) - { - super(entityIdIn); - this.posX = x; - this.posY = y; - this.posZ = z; - this.onGround = onGroundIn; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - super.readPacketData(buf); - this.posX = buf.readByte(); - this.posY = buf.readByte(); - this.posZ = buf.readByte(); - this.onGround = buf.readBoolean(); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - super.writePacketData(buf); - buf.writeByte(this.posX); - buf.writeByte(this.posY); - buf.writeByte(this.posZ); - buf.writeBoolean(this.onGround); - } -} \ No newline at end of file diff --git a/common/src/main/java/common/pathfinding/PathCache.java b/common/src/main/java/common/pathfinding/PathCache.java deleted file mode 100755 index b33d97b..0000000 --- a/common/src/main/java/common/pathfinding/PathCache.java +++ /dev/null @@ -1,52 +0,0 @@ -package common.pathfinding; - -import common.init.Blocks; -import common.util.BlockPos; -import common.world.Chunk; -import common.world.IBlockAccess; -import common.world.State; -import common.world.World; - -public class PathCache implements IBlockAccess -{ - protected final int chunkX; - protected final int chunkZ; - protected final Chunk[][] data; - - public PathCache(World world, BlockPos pos1, BlockPos pos2) - { - this.chunkX = pos1.getX() >> 4; - this.chunkZ = pos1.getZ() >> 4; - int cx2 = pos2.getX() >> 4; - int cz2 = pos2.getZ() >> 4; - this.data = new Chunk[cx2 - this.chunkX + 1][cz2 - this.chunkZ + 1]; - for (int x = this.chunkX; x <= cx2; ++x) - { - for (int z = this.chunkZ; z <= cz2; ++z) - { - this.data[x - this.chunkX][z - this.chunkZ] = world.getChunk(x, z); - } - } - } - - public State getState(BlockPos pos) - { - if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) - { - int i = (pos.getX() >> 4) - this.chunkX; - int j = (pos.getZ() >> 4) - this.chunkZ; - - if (i >= 0 && i < this.data.length && j >= 0 && j < this.data[i].length) - { - Chunk chunk = this.data[i][j]; - - if (chunk != null) - { - return chunk.getState(pos); - } - } - } - - return Blocks.air.getState(); - } -} diff --git a/common/src/main/java/common/tags/SizeTracker.java b/common/src/main/java/common/tags/SizeTracker.java deleted file mode 100755 index 26040d3..0000000 --- a/common/src/main/java/common/tags/SizeTracker.java +++ /dev/null @@ -1,22 +0,0 @@ -package common.tags; - -class SizeTracker { - public static final SizeTracker INFINITE = new SizeTracker(0) { - public void read(int bytes) { - } - }; - - private final int max; - - private int read; - - public SizeTracker(int max) { - this.max = max; - } - - public void read(int bytes) { - this.read += bytes; - if(this.read > this.max) - throw new RuntimeException("Versuchte einen Tag zu lesen, der zu groß war: Habe " + this.read + " Bytes, " + this.max + " Bytes maximal erlaubt"); - } -} diff --git a/common/src/main/java/common/tags/Tag.java b/common/src/main/java/common/tags/Tag.java deleted file mode 100755 index fffc364..0000000 --- a/common/src/main/java/common/tags/Tag.java +++ /dev/null @@ -1,25 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -abstract class Tag { - abstract void write(DataOutput output) throws IOException; - abstract void read(DataInput input, int depth, SizeTracker tracker) throws IOException; - public abstract String toString(); - abstract TagType getType(); - public abstract Tag copy(); - - String toString(int indent, int depth) { - return this.toString(); - } - - public boolean equals(Object other) { - return other instanceof Tag && this.getType() == ((Tag)other).getType(); - } - - public int hashCode() { - return this.getType().getId(); - } -} diff --git a/common/src/main/java/common/tags/TagBool.java b/common/src/main/java/common/tags/TagBool.java deleted file mode 100644 index 2ee2a80..0000000 --- a/common/src/main/java/common/tags/TagBool.java +++ /dev/null @@ -1,49 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -class TagBool extends Tag { - private boolean data; - - TagBool() { - } - - public TagBool(boolean data) { - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeBoolean(this.data); - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(9); - this.data = input.readBoolean(); - } - - TagType getType() { - return TagType.BOOLEAN; - } - - public String toString() { - return "" + this.data; - } - - public Tag copy() { - return new TagBool(this.data); - } - - public boolean equals(Object other) { - return super.equals(other) && this.data == ((TagBool)other).data; - } - - public int hashCode() { - return super.hashCode() ^ (this.data ? 1 : 0); - } - - public boolean getBool() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagByte.java b/common/src/main/java/common/tags/TagByte.java deleted file mode 100755 index 12f86ec..0000000 --- a/common/src/main/java/common/tags/TagByte.java +++ /dev/null @@ -1,49 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -class TagByte extends Tag { - private byte data; - - TagByte() { - } - - public TagByte(byte data) { - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeByte(this.data); - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(9); - this.data = input.readByte(); - } - - TagType getType() { - return TagType.BYTE; - } - - public String toString() { - return "" + this.data + "b"; - } - - public Tag copy() { - return new TagByte(this.data); - } - - public boolean equals(Object other) { - return super.equals(other) && this.data == ((TagByte)other).data; - } - - public int hashCode() { - return super.hashCode() ^ this.data; - } - - public byte getByte() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagByteArray.java b/common/src/main/java/common/tags/TagByteArray.java deleted file mode 100755 index e619211..0000000 --- a/common/src/main/java/common/tags/TagByteArray.java +++ /dev/null @@ -1,60 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Arrays; - -class TagByteArray extends Tag { - private byte[] data; - - TagByteArray() { - } - - public TagByteArray(byte[] data) { - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeInt(this.data.length); - output.write(this.data); - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(24); - int len = input.readInt(); - tracker.read(len); - this.data = new byte[len]; - input.readFully(this.data); - } - - TagType getType() { - return TagType.BYTE_ARRAY; - } - - public String toString() { - StringBuilder sb = new StringBuilder("[0x"); - for(int z = 0; z < this.data.length; z++) { - sb.append(String.format("%02x", this.data[z])); - } - return sb.append("]").toString(); - } - - public Tag copy() { - byte[] data = new byte[this.data.length]; - System.arraycopy(this.data, 0, data, 0, this.data.length); - return new TagByteArray(data); - } - - public boolean equals(Object other) { - return super.equals(other) && Arrays.equals(this.data, ((TagByteArray)other).data); - } - - public int hashCode() { - return super.hashCode() ^ Arrays.hashCode(this.data); - } - - public byte[] getByteArray() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagChar.java b/common/src/main/java/common/tags/TagChar.java deleted file mode 100644 index ec281f8..0000000 --- a/common/src/main/java/common/tags/TagChar.java +++ /dev/null @@ -1,49 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -class TagChar extends Tag { - private char data; - - TagChar() { - } - - public TagChar(char data) { - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeChar(this.data); - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(10); - this.data = input.readChar(); - } - - TagType getType() { - return TagType.CHAR; - } - - public String toString() { - return String.format(Character.isLetterOrDigit(this.data) ? "'%c'" : (this.data >= 256 ? "'\\u%04x'" : "'\\x%02x'"), this.data); - } - - public Tag copy() { - return new TagChar(this.data); - } - - public boolean equals(Object other) { - return super.equals(other) && this.data == ((TagChar)other).data; - } - - public int hashCode() { - return super.hashCode() ^ this.data; - } - - public char getChar() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagDouble.java b/common/src/main/java/common/tags/TagDouble.java deleted file mode 100755 index a4b3ed1..0000000 --- a/common/src/main/java/common/tags/TagDouble.java +++ /dev/null @@ -1,50 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -class TagDouble extends Tag { - private double data; - - TagDouble() { - } - - public TagDouble(double data) { - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeDouble(this.data); - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(16); - this.data = input.readDouble(); - } - - TagType getType() { - return TagType.DOUBLE; - } - - public String toString() { - return "" + this.data + "d"; - } - - public Tag copy() { - return new TagDouble(this.data); - } - - public boolean equals(Object other) { - return super.equals(other) && this.data == ((TagDouble)other).data; - } - - public int hashCode() { - long l = Double.doubleToLongBits(this.data); - return super.hashCode() ^ (int)(l ^ l >>> 32); - } - - public double getDouble() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagException.java b/common/src/main/java/common/tags/TagException.java deleted file mode 100755 index 1b11ebc..0000000 --- a/common/src/main/java/common/tags/TagException.java +++ /dev/null @@ -1,7 +0,0 @@ -package common.tags; - -class TagException extends IllegalArgumentException { - public TagException(String message) { - super(message); - } -} diff --git a/common/src/main/java/common/tags/TagFloat.java b/common/src/main/java/common/tags/TagFloat.java deleted file mode 100755 index 0aae9f3..0000000 --- a/common/src/main/java/common/tags/TagFloat.java +++ /dev/null @@ -1,49 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -class TagFloat extends Tag { - private float data; - - TagFloat() { - } - - public TagFloat(float data) { - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeFloat(this.data); - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(12); - this.data = input.readFloat(); - } - - TagType getType() { - return TagType.FLOAT; - } - - public String toString() { - return "" + this.data + "f"; - } - - public Tag copy() { - return new TagFloat(this.data); - } - - public boolean equals(Object other) { - return super.equals(other) && this.data == ((TagFloat)other).data; - } - - public int hashCode() { - return super.hashCode() ^ Float.floatToIntBits(this.data); - } - - public float getFloat() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagInt.java b/common/src/main/java/common/tags/TagInt.java deleted file mode 100755 index 0d3a6b3..0000000 --- a/common/src/main/java/common/tags/TagInt.java +++ /dev/null @@ -1,49 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -class TagInt extends Tag { - private int data; - - TagInt() { - } - - public TagInt(int data) { - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeInt(this.data); - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(12); - this.data = input.readInt(); - } - - TagType getType() { - return TagType.INT; - } - - public String toString() { - return "" + this.data; - } - - public Tag copy() { - return new TagInt(this.data); - } - - public boolean equals(Object other) { - return super.equals(other) && this.data == ((TagInt)other).data; - } - - public int hashCode() { - return super.hashCode() ^ this.data; - } - - public int getInt() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagIntArray.java b/common/src/main/java/common/tags/TagIntArray.java deleted file mode 100755 index 6259e5d..0000000 --- a/common/src/main/java/common/tags/TagIntArray.java +++ /dev/null @@ -1,66 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Arrays; - -class TagIntArray extends Tag { - private int[] data; - - TagIntArray() { - } - - public TagIntArray(int[] data) { - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeInt(this.data.length); - for(int z = 0; z < this.data.length; z++) { - output.writeInt(this.data[z]); - } - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(24); - int len = input.readInt(); - tracker.read(4 * len); - this.data = new int[len]; - for(int z = 0; z < len; z++) { - this.data[z] = input.readInt(); - } - } - - TagType getType() { - return TagType.INT_ARRAY; - } - - public String toString() { - StringBuilder sb = new StringBuilder("["); - for(int z = 0; z < this.data.length; z++) { - if(z != 0) - sb.append(','); - sb.append(this.data[z]); - } - return sb.append("]").toString(); - } - - public Tag copy() { - int[] data = new int[this.data.length]; - System.arraycopy(this.data, 0, data, 0, this.data.length); - return new TagIntArray(data); - } - - public boolean equals(Object other) { - return super.equals(other) && Arrays.equals(this.data, ((TagIntArray)other).data); - } - - public int hashCode() { - return super.hashCode() ^ Arrays.hashCode(this.data); - } - - public int[] getIntArray() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagInterpreter.java b/common/src/main/java/common/tags/TagInterpreter.java deleted file mode 100755 index c364287..0000000 --- a/common/src/main/java/common/tags/TagInterpreter.java +++ /dev/null @@ -1,593 +0,0 @@ -package common.tags; - -import java.util.ArrayList; -import java.util.Stack; -import java.util.regex.Pattern; - -import common.collect.Lists; - -class TagInterpreter -{ - private static final Pattern INT_BYTE_ARRAY = Pattern.compile("\\[[-+\\d|,\\s]+\\]"); - private static final Pattern BYTE_ARRAY = Pattern.compile("\\[0x[a-fA-F\\d]*\\]"); - - static TagObject parseTag(String tag) throws TagException - { - if (!tag.startsWith("{")) - { - throw new TagException("Invalid tag encountered, expected \'{\' as first char."); - } - else if (countTags(tag) != 1) - { - throw new TagException("Encountered multiple top tags, only one expected"); - } - else - { - return (TagObject)parseSection("tag", tag).parse(); - } - } - - static int countTags(String str) throws TagException - { - int count = 0; - boolean quote = false; - Stack stack = new Stack(); - - for (int z = 0; z < str.length(); z++) - { - char ch = str.charAt(z); - - if (ch == '"') - { - if (isEscaped(str, z)) - { - if (!quote) - { - throw new TagException("Illegal use of \\\": " + str); - } - } - else - { - quote = !quote; - } - } - else if (!quote) - { - if (ch != '{' && ch != '[') - { - if (ch == '}' && (stack.isEmpty() || ((Character)stack.pop()).charValue() != '{')) - { - throw new TagException("Unbalanced curly brackets {}: " + str); - } - - if (ch == ']' && (stack.isEmpty() || ((Character)stack.pop()).charValue() != '[')) - { - throw new TagException("Unbalanced square brackets []: " + str); - } - } - else - { - if (stack.isEmpty()) - { - ++count; - } - - stack.push(Character.valueOf(ch)); - } - } - } - - if (quote) - { - throw new TagException("Unbalanced quotation: " + str); - } - else if (!stack.isEmpty()) - { - throw new TagException("Unbalanced brackets: " + str); - } - else - { - if (count == 0 && !str.isEmpty()) - { - count = 1; - } - - return count; - } - } - - static TagInterpreter.Parser parseSection(String id, String str) throws TagException - { - str = str.trim(); - - if (str.startsWith("{")) - { - str = str.substring(1, str.length() - 1); - TagInterpreter.Compound tag; - String section; - - for (tag = new TagInterpreter.Compound(id); str.length() > 0; str = str.substring(section.length() + 1)) - { - section = splitSection(str, true); - - if (section.length() > 0) - { - tag.parsers.add(parseSubsection(section, false)); - } - - if (str.length() < section.length() + 1) - { - break; - } - - char ch = str.charAt(section.length()); - - if (ch != ',' && ch != '{' && ch != '}' && ch != '[' && ch != ']') - { - throw new TagException("Unexpected token \'" + ch + "\' at: " + str.substring(section.length())); - } - } - - return tag; - } - else if (str.startsWith("[") && !INT_BYTE_ARRAY.matcher(str).matches() && !BYTE_ARRAY.matcher(str).matches()) - { - str = str.substring(1, str.length() - 1); - TagInterpreter.List list; - String section; - - for (list = new TagInterpreter.List(id); str.length() > 0; str = str.substring(section.length() + 1)) - { - section = splitSection(str, false); - - if (section.length() > 0) - { - list.parsers.add(parseSubsection(section, true)); - } - - if (str.length() < section.length() + 1) - { - break; - } - - char ch = str.charAt(section.length()); - - if (ch != ',' && ch != '{' && ch != '}' && ch != '[' && ch != ']') - { - throw new TagException("Unexpected token \'" + ch + "\' at: " + str.substring(section.length())); - } - } - - return list; - } - else - { - return new TagInterpreter.Primitive(id, str); - } - } - - private static TagInterpreter.Parser parseSubsection(String str, boolean list) throws TagException - { - String key = getKey(str, list); - String value = getValue(str, list); - return parseSection(key, value); - } - - private static String splitSection(String str, boolean noList) throws TagException - { - int colon = findSeparator(str, ':'); - int comma = findSeparator(str, ','); - - if (noList) - { - if (colon == -1) - { - throw new TagException("Unable to locate name/value separator for string: " + str); - } - - if (comma != -1 && comma < colon) - { - throw new TagException("Name error at: " + str); - } - } - else if (colon == -1 || colon > comma) - { - colon = -1; - } - - return split(str, colon); - } - - private static String split(String str, int index) throws TagException - { - Stack stack = new Stack(); - int idx = index + 1; - boolean quote = false; - boolean quoteFirst = false; - boolean printable = false; - - for (int quoteEnd = 0; idx < str.length(); ++idx) - { - char ch = str.charAt(idx); - - if (ch == '"') - { - if (isEscaped(str, idx)) - { - if (!quote) - { - throw new TagException("Illegal use of \\\": " + str); - } - } - else - { - quote = !quote; - - if (quote && !printable) - { - quoteFirst = true; - } - - if (!quote) - { - quoteEnd = idx; - } - } - } - else if (!quote) - { - if (ch != '{' && ch != '[') - { - if (ch == '}' && (stack.isEmpty() || ((Character)stack.pop()).charValue() != '{')) - { - throw new TagException("Unbalanced curly brackets {}: " + str); - } - - if (ch == ']' && (stack.isEmpty() || ((Character)stack.pop()).charValue() != '[')) - { - throw new TagException("Unbalanced square brackets []: " + str); - } - - if (ch == ',' && stack.isEmpty()) - { - return str.substring(0, idx); - } - } - else - { - stack.push(Character.valueOf(ch)); - } - } - - if (!Character.isWhitespace(ch)) - { - if (!quote && quoteFirst && quoteEnd != idx) - { - return str.substring(0, quoteEnd + 1); - } - - printable = true; - } - } - - return str.substring(0, idx); - } - - private static String getKey(String str, boolean list) throws TagException - { - if (list) - { - str = str.trim(); - - if (str.startsWith("{") || str.startsWith("[")) - { - return ""; - } - } - - int colon = findSeparator(str, ':'); - - if (colon == -1) - { - if (list) - { - return ""; - } - else - { - throw new TagException("Unable to locate name/value separator for string: " + str); - } - } - else - { - return str.substring(0, colon).trim(); - } - } - - private static String getValue(String str, boolean list) throws TagException - { - if (list) - { - str = str.trim(); - - if (str.startsWith("{") || str.startsWith("[")) - { - return str; - } - } - - int colon = findSeparator(str, ':'); - - if (colon == -1) - { - if (list) - { - return str; - } - else - { - throw new TagException("Unable to locate name/value separator for string: " + str); - } - } - else - { - return str.substring(colon + 1).trim(); - } - } - - private static int findSeparator(String str, char separator) - { - int idx = 0; - - for (boolean noQuote = true; idx < str.length(); idx++) - { - char ch = str.charAt(idx); - - if (ch == '"') - { - if (!isEscaped(str, idx)) - { - noQuote = !noQuote; - } - } - else if (noQuote) - { - if (ch == separator) - { - return idx; - } - - if (ch == '{' || ch == '[') - { - return -1; - } - } - } - - return -1; - } - - private static boolean isEscaped(String str, int index) - { - return index > 0 && str.charAt(index - 1) == '\\' && !isEscaped(str, index - 1); - } - - abstract static class Parser - { - protected String section; - - public abstract Tag parse() throws TagException; - } - - static class Compound extends TagInterpreter.Parser - { - protected java.util.List parsers = Lists.newArrayList(); - - public Compound(String section) - { - this.section = section; - } - - public Tag parse() throws TagException - { - TagObject tag = new TagObject(); - - for (TagInterpreter.Parser any : this.parsers) - { - tag.set(any.section, any.parse()); - } - - return tag; - } - } - - static class List extends TagInterpreter.Parser - { - protected java.util.List parsers = Lists.newArrayList(); - - public List(String section) - { - this.section = section; - } - - public Tag parse() throws TagException - { - TagList list = null; - java.util.List strs = null; - - for (TagInterpreter.Parser any : this.parsers) - { - Tag tag = any.parse(); - if(tag.getType() == TagType.STRING) { - if(list != null) - throw new TagException("Cannot use mixed types for list: " + any.section); - if(strs == null) - strs = new ArrayList(this.parsers.size()); - strs.add(((TagString)tag).getString()); - } - else if(tag.getType() == TagType.OBJECT) { - if(strs != null) - throw new TagException("Cannot use mixed types for list: " + any.section); - if(list == null) - list = new TagList(new ArrayList(this.parsers.size())); - list.getList().add(((TagObject)tag)); - } - else { - throw new TagException("Type cannot be put in a list: " + any.section); - } - } - - return strs != null ? new TagStringArray(strs.toArray(new String[strs.size()])) : (list != null ? list : new TagList(Lists.newArrayList())); - } - } - - static class Primitive extends TagInterpreter.Parser - { - private static final Pattern DOUBLE = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[d|D]"); - private static final Pattern FLOAT = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[f|F]"); - private static final Pattern BYTE = Pattern.compile("[-+]?[0-9]+[b|B]"); - private static final Pattern LONG = Pattern.compile("[-+]?[0-9]+[l|L]"); - private static final Pattern SHORT = Pattern.compile("[-+]?[0-9]+[s|S]"); - private static final Pattern INTEGER = Pattern.compile("[-+]?[0-9]+"); - private static final Pattern DOUBLE_UNTYPED = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+"); - - protected String value; - - public Primitive(String section, String value) - { - this.section = section; - this.value = value; - } - - public Tag parse() throws TagException - { - try - { - if (DOUBLE.matcher(this.value).matches()) - { - return new TagDouble(Double.parseDouble(this.value.substring(0, this.value.length() - 1))); - } - - if (FLOAT.matcher(this.value).matches()) - { - return new TagFloat(Float.parseFloat(this.value.substring(0, this.value.length() - 1))); - } - - if (BYTE.matcher(this.value).matches()) - { - return new TagByte(Byte.parseByte(this.value.substring(0, this.value.length() - 1))); - } - - if (LONG.matcher(this.value).matches()) - { - return new TagLong(Long.parseLong(this.value.substring(0, this.value.length() - 1))); - } - - if (SHORT.matcher(this.value).matches()) - { - return new TagShort(Short.parseShort(this.value.substring(0, this.value.length() - 1))); - } - - if (INTEGER.matcher(this.value).matches()) - { - return new TagInt(Integer.parseInt(this.value)); - } - - if (DOUBLE_UNTYPED.matcher(this.value).matches()) - { - return new TagDouble(Double.parseDouble(this.value)); - } - - if (this.value.equalsIgnoreCase("true") || this.value.equalsIgnoreCase("false")) - { - return new TagBool(Boolean.parseBoolean(this.value)); - } - } - catch (NumberFormatException e) - { - this.value = this.value.replaceAll("\\\\\"", "\""); - return new TagString(this.value); - } - - if (this.value.startsWith("[") && this.value.endsWith("]")) - { - String str = this.value.substring(1, this.value.length() - 1); - try - { - if(str.startsWith("0x")) { - str = str.substring(2); - if((str.length() & 1) == 1) - str = "0" + str; - byte[] bytes = new byte[str.length() / 2]; - for (int z = 0; z < bytes.length; z++) - { - bytes[z] = (byte)Integer.parseUnsignedInt(str.substring(z * 2, (z + 1) * 2), 16); - } - return new TagByteArray(bytes); - } - else { - String[] elems = str.split(","); - int[] ints = new int[elems.length]; - for (int z = 0; z < elems.length; z++) - { - ints[z] = Integer.parseInt(elems[z].trim()); - } - return new TagIntArray(ints); - } - } - catch (NumberFormatException e) - { - return new TagString(this.value); - } - } - else - { - if (this.value.startsWith("'") && this.value.endsWith("'")) - { - String str = this.value.substring(1, this.value.length() - 1); - if(str.length() == 1 && str.charAt(0) != '\\') { - return new TagChar(str.charAt(0)); - } - else if(str.length() == 2 && str.charAt(0) == '\\') { - switch(str.charAt(1)) { - case '\\': - return new TagChar('\\'); - case 'n': - return new TagChar('\n'); - } - } - else if((str.length() == 4 && str.startsWith("\\x")) || (str.length() == 6 && str.startsWith("\\u"))) { - try { - return new TagChar((char)Integer.parseUnsignedInt(str.substring(2), 16)); - } - catch(NumberFormatException e) { - } - } - } - - if (this.value.startsWith("\"") && this.value.endsWith("\"")) - { - this.value = this.value.substring(1, this.value.length() - 1); - } - - this.value = this.value.replaceAll("\\\\\"", "\""); - StringBuilder sb = new StringBuilder(); - - for (int z = 0; z < this.value.length(); z++) - { - if (z < this.value.length() - 1 && this.value.charAt(z) == '\\' && this.value.charAt(z + 1) == '\\') - { - sb.append('\\'); - ++z; - } - else - { - sb.append(this.value.charAt(z)); - } - } - - return new TagString(sb.toString()); - } - } - } -} diff --git a/common/src/main/java/common/tags/TagList.java b/common/src/main/java/common/tags/TagList.java deleted file mode 100644 index 67fa035..0000000 --- a/common/src/main/java/common/tags/TagList.java +++ /dev/null @@ -1,85 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import common.util.Util; - -class TagList extends Tag { - private List list; - - TagList() { - } - - public TagList(List list) { - this.list = list; - } - - void write(DataOutput output) throws IOException { - output.writeInt(this.list.size()); - for(int z = 0; z < this.list.size(); z++) { - this.list.get(z).write(output); - } - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(36); - if(depth > 256) - throw new IOException("Objekt ist zu komplex, die Tiefe ist größer als 256"); - int len = input.readInt(); - tracker.read(4 * len); - this.list = new ArrayList(len); - for(int z = 0; z < len; z++) { - TagObject tag = new TagObject(); - tag.read(input, depth + 1, tracker); - this.list.add(tag); - } - } - - TagType getType() { - return TagType.LIST; - } - - public String toString() { - StringBuilder sb = new StringBuilder("["); - for(int z = 0; z < this.list.size(); z++) { - if(z != 0) - sb.append(','); - sb.append(this.list.get(z).toString()); - } - return sb.append(']').toString(); - } - - String toString(int indent, int depth) { - StringBuilder sb = new StringBuilder("["); - String prefix = Util.repeatString(' ', indent * (depth + 1)); - for(int z = 0; z < this.list.size(); z++) { - if(z != 0) - sb.append(','); - sb.append('\n').append(prefix).append(this.list.get(z).toString(indent, depth + 1)); - } - return sb.append('\n').append(Util.repeatString(' ', indent * depth)).append(']').toString(); - } - - public Tag copy() { - TagList list = new TagList(new ArrayList(this.list.size())); - for(TagObject tag : this.list) { - list.list.add(tag.copy()); - } - return list; - } - - public boolean equals(Object other) { - return super.equals(other) && this.list.equals(((TagList)other).list); - } - - public int hashCode() { - return super.hashCode() ^ this.list.hashCode(); - } - - public List getList() { - return this.list; - } -} diff --git a/common/src/main/java/common/tags/TagLong.java b/common/src/main/java/common/tags/TagLong.java deleted file mode 100755 index ac2d2b3..0000000 --- a/common/src/main/java/common/tags/TagLong.java +++ /dev/null @@ -1,49 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -class TagLong extends Tag { - private long data; - - TagLong() { - } - - public TagLong(long data) { - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeLong(this.data); - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(16); - this.data = input.readLong(); - } - - TagType getType() { - return TagType.LONG; - } - - public String toString() { - return "" + this.data + "L"; - } - - public Tag copy() { - return new TagLong(this.data); - } - - public boolean equals(Object other) { - return super.equals(other) && this.data == ((TagLong)other).data; - } - - public int hashCode() { - return super.hashCode() ^ (int)(this.data ^ this.data >>> 32); - } - - public long getLong() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagObject.java b/common/src/main/java/common/tags/TagObject.java deleted file mode 100755 index dd80354..0000000 --- a/common/src/main/java/common/tags/TagObject.java +++ /dev/null @@ -1,398 +0,0 @@ -package common.tags; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import common.collect.Lists; -import common.collect.Maps; -import common.util.Util; - -import java.util.Set; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -/** - * compressed data tree / CDT - * (ids 0..15) - */ -public class TagObject extends Tag { - private Map tags = Maps.newHashMap(); - - void write(DataOutput output) throws IOException { - for(String key : this.tags.keySet()) { - Tag tag = this.tags.get(key); - output.writeByte(tag.getType().getId()); - if(tag.getType() != TagType.NULL) { - output.writeUTF(key); - tag.write(output); - } - } - output.writeByte(0); - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(48); - if(depth > 256) - throw new IOException("Objekt ist zu komplex, die Tiefe ist größer als 256"); - this.tags.clear(); - byte id; - while((id = input.readByte()) != 0) { - String key = input.readUTF(); - tracker.read(28 + 2 * key.length()); - Tag tag = TagType.create(id); - tag.read(input, depth + 1, tracker); - if(this.tags.put(key, tag) != null) - throw new IOException("Objekt ist ungültig, Tag '" + key + "' ist mehrfach vorhanden"); - } - } - - public Set keySet() { - return this.tags.keySet(); - } - - TagType getType() { - return TagType.OBJECT; - } - - void set(String key, Tag value) { - this.tags.put(key, value); - } - - public void setObject(String key, TagObject value) { - this.tags.put(key, value); - } - - public void setStringArray(String key, String[] value) { - this.tags.put(key, new TagStringArray(value)); - } - - public void setList(String key, List value) { - this.tags.put(key, new TagList(value)); - } - - public void setBool(String key, boolean value) { - this.tags.put(key, new TagBool(value)); - } - - public void setByte(String key, byte value) { - this.tags.put(key, new TagByte(value)); - } - - public void setShort(String key, short value) { - this.tags.put(key, new TagShort(value)); - } - - public void setChar(String key, char value) { - this.tags.put(key, new TagChar(value)); - } - - public void setInt(String key, int value) { - this.tags.put(key, new TagInt(value)); - } - - public void setLong(String key, long value) { - this.tags.put(key, new TagLong(value)); - } - - public void setFloat(String key, float value) { - this.tags.put(key, new TagFloat(value)); - } - - public void setDouble(String key, double value) { - this.tags.put(key, new TagDouble(value)); - } - - public void setString(String key, String value) { - this.tags.put(key, new TagString(value)); - } - - public void setByteArray(String key, byte[] value) { - this.tags.put(key, new TagByteArray(value)); - } - - public void setIntArray(String key, int[] value) { - this.tags.put(key, new TagIntArray(value)); - } - - Tag get(String key) { - return this.tags.get(key); - } - - private boolean has(String key, TagType type) { - Tag tag = this.tags.get(key); - return tag != null && tag.getType() == type; - } - - public boolean hasBool(String key) { - return this.has(key, TagType.BOOLEAN); - } - - public boolean hasByte(String key) { - return this.has(key, TagType.BYTE); - } - - public boolean hasShort(String key) { - return this.has(key, TagType.SHORT); - } - - public boolean hasChar(String key) { - return this.has(key, TagType.CHAR); - } - - public boolean hasInt(String key) { - return this.has(key, TagType.INT); - } - - public boolean hasLong(String key) { - return this.has(key, TagType.LONG); - } - - public boolean hasFloat(String key) { - return this.has(key, TagType.FLOAT); - } - - public boolean hasDouble(String key) { - return this.has(key, TagType.DOUBLE); - } - - public boolean hasString(String key) { - return this.has(key, TagType.STRING); - } - - public boolean hasByteArray(String key) { - return this.has(key, TagType.BYTE_ARRAY); - } - - public boolean hasIntArray(String key) { - return this.has(key, TagType.INT_ARRAY); - } - - public boolean hasObject(String key) { - return this.has(key, TagType.OBJECT); - } - - public boolean hasStringArray(String key) { - return this.has(key, TagType.STRING_ARRAY); - } - - public boolean hasList(String key) { - return this.has(key, TagType.LIST); - } - - public boolean getBool(String key) { - return !this.has(key, TagType.BOOLEAN) ? false : ((TagBool)this.tags.get(key)).getBool(); - } - - public byte getByte(String key) { - return !this.has(key, TagType.BYTE) ? 0 : ((TagByte)this.tags.get(key)).getByte(); - } - - public short getShort(String key) { - return !this.has(key, TagType.SHORT) ? 0 : ((TagShort)this.tags.get(key)).getShort(); - } - - public char getChar(String key) { - return !this.has(key, TagType.CHAR) ? 0 : ((TagChar)this.tags.get(key)).getChar(); - } - - public int getInt(String key) { - return !this.has(key, TagType.INT) ? 0 : ((TagInt)this.tags.get(key)).getInt(); - } - - public long getLong(String key) { - return !this.has(key, TagType.LONG) ? 0L : ((TagLong)this.tags.get(key)).getLong(); - } - - public float getFloat(String key) { - return !this.has(key, TagType.FLOAT) ? 0.0f : ((TagFloat)this.tags.get(key)).getFloat(); - } - - public double getDouble(String key) { - return !this.has(key, TagType.DOUBLE) ? 0.0 : ((TagDouble)this.tags.get(key)).getDouble(); - } - - public String getString(String key) { - return !this.has(key, TagType.STRING) ? "" : ((TagString)this.tags.get(key)).getString(); - } - - public byte[] getByteArray(String key) { - return !this.has(key, TagType.BYTE_ARRAY) ? new byte[0] : ((TagByteArray)this.tags.get(key)).getByteArray(); - } - - public int[] getIntArray(String key) { - return !this.has(key, TagType.INT_ARRAY) ? new int[0] : ((TagIntArray)this.tags.get(key)).getIntArray(); - } - - public TagObject getObject(String key) { - return !this.has(key, TagType.OBJECT) ? new TagObject() : (TagObject)this.tags.get(key); - } - - public String[] getStringArray(String key) { - return !this.has(key, TagType.STRING_ARRAY) ? new String[0] : ((TagStringArray)this.tags.get(key)).getStringArray(); - } - - public List getList(String key) { - return !this.has(key, TagType.LIST) ? Lists.newArrayList() : ((TagList)this.tags.get(key)).getList(); - } - - public void remove(String key) { - this.tags.remove(key); - } - - private List> getSortedEntries() { - List> list = Lists.newArrayList(this.tags.entrySet()); - Collections.sort(list, (e1, e2) -> e1.getValue().getType() == TagType.OBJECT && e2.getValue().getType() != TagType.OBJECT ? 1 : ( - e2.getValue().getType() == TagType.OBJECT && e1.getValue().getType() != TagType.OBJECT ? -1 : ( - (e1.getValue().getType() == TagType.LIST || e1.getValue().getType() == TagType.STRING_ARRAY) && - e2.getValue().getType() != TagType.LIST && e2.getValue().getType() != TagType.STRING_ARRAY ? 1 : ( - (e2.getValue().getType() == TagType.LIST || e2.getValue().getType() == TagType.STRING_ARRAY) && - e1.getValue().getType() != TagType.LIST && e1.getValue().getType() != TagType.STRING_ARRAY ? -1 : e1.getKey().compareTo(e2.getKey()))))); - return list; - } - - public String toString() { - StringBuilder sb = new StringBuilder("{"); - for(Entry entry : this.getSortedEntries()) { - if(sb.length() != 1) - sb.append(','); - sb.append(entry.getKey()).append(':').append(entry.getValue().toString()); - } - return sb.append('}').toString(); - } - - String toString(int indent, int depth) { - StringBuilder sb = new StringBuilder("{"); - String prefix = Util.repeatString(' ', indent * (depth + 1)); - for(Entry entry : this.getSortedEntries()) { - if(sb.length() != 1) - sb.append(','); - sb.append('\n').append(prefix).append(entry.getKey()).append(": ").append(entry.getValue().toString(indent, depth + 1)); - } - return sb.append('\n').append(Util.repeatString(' ', indent * depth)).append('}').toString(); - } - - public boolean isEmpty() { - return this.tags.isEmpty(); - } - - public TagObject copy() { - TagObject tag = new TagObject(); - for(String s : this.tags.keySet()) { - tag.set(s, this.tags.get(s).copy()); - } - return tag; - } - - public boolean equals(Object other) { - return super.equals(other) && this.tags.entrySet().equals(((TagObject)other).tags.entrySet()); - } - - public int hashCode() { - return super.hashCode() ^ this.tags.hashCode(); - } - - /** - * Merges this tag with the given compound. Any sub-compounds are - * merged using the same methods, other types of tags are overwritten from the - * given compound. - */ - public void merge(TagObject other) { - for(String key : other.tags.keySet()) { - Tag tag = other.tags.get(key); - if(tag.getType() == TagType.OBJECT) { - if(this.has(key, TagType.OBJECT)) { - TagObject comp = this.getObject(key); - comp.merge((TagObject)tag); - } - else { - this.set(key, tag.copy()); - } - } - else { - this.set(key, tag.copy()); - } - } - } - - public String format(int indent) { - return indent == 0 ? this.toString() : this.toString(indent, 0); - } - - public static void write(TagObject tag, DataOutput out) throws IOException { - tag.write(out); - } - - public static TagObject read(DataInput in) throws IOException { - return read(in, SizeTracker.INFINITE); - } - - public static TagObject read(DataInput in, int limit) throws IOException { - return read(in, new SizeTracker(limit)); - } - - private static TagObject read(DataInput in, SizeTracker tracker) throws IOException { - TagObject tag = new TagObject(); - tag.read(in, 0, tracker); - return tag; - } - - public static void writeGZip(TagObject tag, File file) throws IOException { - DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(file)))); - try { - TagObject.write(tag, out); - } - finally { - out.close(); - } - } - - public static TagObject readGZip(File file) throws IOException { - DataInputStream in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)))); - TagObject tag; - try { - tag = TagObject.read(in, SizeTracker.INFINITE); - } - finally { - in.close(); - } - return tag; - } - - public static boolean compare(TagObject tag1, TagObject tag2) { - return compareTags(tag1, tag2); - } - - private static boolean compareTags(Tag tag1, Tag tag2) { - if(tag1 == tag2 || tag1 == null) - return true; - else if(tag2 == null || !tag1.getClass().equals(tag2.getClass())) - return false; - else if(tag1 instanceof TagObject) { - TagObject comp1 = (TagObject)tag1; - TagObject comp2 = (TagObject)tag2; - for(String key : comp1.keySet()) { - Tag tag = comp1.get(key); - if(!compareTags(tag, comp2.get(key))) - return false; - } - return true; - } - return tag1.equals(tag2); - } - - public static TagObject parse(String tag) throws IllegalArgumentException { - return TagInterpreter.parseTag(tag.trim()); - } -} diff --git a/common/src/main/java/common/tags/TagShort.java b/common/src/main/java/common/tags/TagShort.java deleted file mode 100755 index 15ed3e2..0000000 --- a/common/src/main/java/common/tags/TagShort.java +++ /dev/null @@ -1,49 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -class TagShort extends Tag { - private short data; - - TagShort() { - } - - public TagShort(short data) { - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeShort(this.data); - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(10); - this.data = input.readShort(); - } - - TagType getType() { - return TagType.SHORT; - } - - public String toString() { - return "" + this.data + "s"; - } - - public Tag copy() { - return new TagShort(this.data); - } - - public boolean equals(Object other) { - return super.equals(other) && this.data == ((TagShort)other).data; - } - - public int hashCode() { - return super.hashCode() ^ this.data; - } - - public short getShort() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagString.java b/common/src/main/java/common/tags/TagString.java deleted file mode 100755 index bb0b814..0000000 --- a/common/src/main/java/common/tags/TagString.java +++ /dev/null @@ -1,56 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -class TagString extends Tag { - private String data; - - TagString() { - this.data = ""; - } - - public TagString(String data) { - if(data == null) - throw new IllegalArgumentException("Eine Zeichenkette aus null ist nicht erlaubt"); - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeUTF(this.data); - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(36); - this.data = input.readUTF(); - tracker.read(2 * this.data.length()); - } - - TagType getType() { - return TagType.STRING; - } - - public String toString() { - return "\"" + this.data.replace("\"", "\\\"") + "\""; - } - - public Tag copy() { - return new TagString(this.data); - } - - public boolean equals(Object other) { - if(!super.equals(other)) - return false; - TagString tag = (TagString)other; - return this.data == null && tag.data == null || this.data != null && this.data.equals(tag.data); - } - - public int hashCode() { - return super.hashCode() ^ this.data.hashCode(); - } - - public String getString() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagStringArray.java b/common/src/main/java/common/tags/TagStringArray.java deleted file mode 100644 index eefd2b2..0000000 --- a/common/src/main/java/common/tags/TagStringArray.java +++ /dev/null @@ -1,79 +0,0 @@ -package common.tags; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Arrays; - -import common.util.Util; - -class TagStringArray extends Tag { - private String[] data; - - TagStringArray() { - } - - public TagStringArray(String[] data) { - this.data = data; - } - - void write(DataOutput output) throws IOException { - output.writeInt(this.data.length); - for(int z = 0; z < this.data.length; z++) { - output.writeUTF(this.data[z]); - } - } - - void read(DataInput input, int depth, SizeTracker tracker) throws IOException { - tracker.read(24); - int len = input.readInt(); - this.data = new String[len]; - for(int z = 0; z < len; z++) { - this.data[z] = input.readUTF(); - tracker.read(2 * this.data[z].length()); - } - } - - TagType getType() { - return TagType.STRING_ARRAY; - } - - public String toString() { - StringBuilder sb = new StringBuilder("["); - for(int z = 0; z < this.data.length; z++) { - if(z != 0) - sb.append(','); - sb.append("\"" + this.data[z].replace("\"", "\\\"") + "\""); - } - return sb.append("]").toString(); - } - - String toString(int indent, int depth) { - StringBuilder sb = new StringBuilder("["); - String prefix = Util.repeatString(' ', indent * (depth + 1)); - for(int z = 0; z < this.data.length; z++) { - if(z != 0) - sb.append(','); - sb.append('\n').append(prefix).append("\"" + this.data[z].replace("\"", "\\\"") + "\""); - } - return sb.append('\n').append(Util.repeatString(' ', indent * depth)).append("]").toString(); - } - - public Tag copy() { - String[] data = new String[this.data.length]; - System.arraycopy(this.data, 0, data, 0, this.data.length); - return new TagStringArray(data); - } - - public boolean equals(Object other) { - return super.equals(other) && Arrays.equals(this.data, ((TagStringArray)other).data); - } - - public int hashCode() { - return super.hashCode() ^ Arrays.hashCode(this.data); - } - - public String[] getStringArray() { - return this.data; - } -} diff --git a/common/src/main/java/common/tags/TagType.java b/common/src/main/java/common/tags/TagType.java deleted file mode 100644 index c29db1d..0000000 --- a/common/src/main/java/common/tags/TagType.java +++ /dev/null @@ -1,105 +0,0 @@ -package common.tags; - -import java.io.IOException; - -enum TagType { - NULL { // 0 - protected Tag createTag() { - return null; - } - }, - OBJECT { // 1 - protected Tag createTag() { - return new TagObject(); - } - }, - BOOLEAN { // 2 - protected Tag createTag() { - return new TagBool(); - } - }, - BYTE { // 3 - protected Tag createTag() { - return new TagByte(); - } - }, - SHORT { // 4 - protected Tag createTag() { - return new TagShort(); - } - }, - CHAR { // 5 - protected Tag createTag() { - return new TagChar(); - } - }, - INT { // 6 - protected Tag createTag() { - return new TagInt(); - } - }, - LONG { // 7 - protected Tag createTag() { - return new TagLong(); - } - }, - FLOAT { // 8 - protected Tag createTag() { - return new TagFloat(); - } - }, - DOUBLE { // 9 - protected Tag createTag() { - return new TagDouble(); - } - }, - STRING { // 10 - protected Tag createTag() { - return new TagString(); - } - }, - LIST { // 11 - protected Tag createTag() { - return new TagList(); - } - }, - BYTE_ARRAY { // 12 - protected Tag createTag() { - return new TagByteArray(); - } - }, - INT_ARRAY { // 13 - protected Tag createTag() { - return new TagIntArray(); - } - }, - STRING_ARRAY { // 14 - protected Tag createTag() { - return new TagStringArray(); - } - }; - - private static final TagType[] TYPES; - - private final byte id; - - static { - TYPES = values(); - } - - static Tag create(byte id) throws IOException { - if(id <= 0 || id >= TYPES.length) - throw new IOException("Kann keinen gültigen Tag mit ID #" + id + " lesen"); - return TYPES[id].createTag(); - } - - private TagType() { - this.id = (byte)this.ordinal(); - } - - protected abstract Tag createTag(); - - public byte getId() { - return this.id; - } -} diff --git a/common/src/main/java/common/tileentity/Passcode.java b/common/src/main/java/common/tileentity/Passcode.java deleted file mode 100755 index 1b3b45e..0000000 --- a/common/src/main/java/common/tileentity/Passcode.java +++ /dev/null @@ -1,19 +0,0 @@ -package common.tileentity; - -import common.tags.TagObject; - -public record Passcode(String code) { - public static final Passcode EMPTY_CODE = new Passcode(""); - - public boolean empty() { - return this.code == null || this.code.isEmpty(); - } - - public void toNBT(TagObject tag) { - tag.setString("Lock", this.code); - } - - public static Passcode fromNBT(TagObject tag) { - return tag.hasString("Lock") ? new Passcode(tag.getString("Lock")) : EMPTY_CODE; - } -} diff --git a/common/src/main/java/common/tileentity/TileEntityMobSpawner.java b/common/src/main/java/common/tileentity/TileEntityMobSpawner.java deleted file mode 100755 index 89ff3d4..0000000 --- a/common/src/main/java/common/tileentity/TileEntityMobSpawner.java +++ /dev/null @@ -1,108 +0,0 @@ -package common.tileentity; - -import common.entity.types.EntityLiving; -import common.init.EntityRegistry; -import common.inventory.ContainerTile; -import common.item.ItemMonsterPlacer; -import common.item.ItemNpcSpawner; -import common.item.ItemStack; -import common.tags.TagObject; -import common.vars.Vars; - -public class TileEntityMobSpawner extends TileEntityDevice implements ITickable -{ - public TileEntityMobSpawner() { - super(1); - } - - private int spawnDelay = 20; - private int minSpawnDelay = 200; - private int maxSpawnDelay = 800; - private int spawnRange = 4; - - public boolean isItemValidForSlot(int index, ItemStack stack) { - return index == 0 ? stack.getItem() instanceof ItemMonsterPlacer || stack.getItem() instanceof ItemNpcSpawner : false; - } - - public String getName() { - return "Mob-Spawner"; - } - - public String getGuiID() { - return "mob_spawner"; - } - - public String formatDisplay(ContainerTile inv) { - ItemStack stack = inv.getSlot(0).getStack(); - if(stack == null) - return "Kein Spawner vorhanden"; - return String.format("Erschaffe: %s", stack.getItem() instanceof ItemMonsterPlacer egg ? EntityRegistry.getEntityName(egg.getSpawnedId()) : ((stack.getItem() instanceof ItemNpcSpawner egg ? egg.getCharName() : ""))); - } - - protected boolean executeFunction() { - if(!Vars.mobs || !Vars.spawners || !this.hasAmount(0, 1)) - return false; - if (this.spawnDelay == -1) - this.resetTimer(); - if (this.spawnDelay > 0) { - --this.spawnDelay; - return true; - } - ItemStack stack = this.getStackInSlot(0); - if(stack == null) - return true; - double x = (double)this.pos.getX() + (this.worldObj.rand.doublev() - this.worldObj.rand.doublev()) * (double)this.spawnRange + 0.5D; - double y = (double)(this.pos.getY() + this.worldObj.rand.zrange(3) - 1); - double z = (double)this.pos.getZ() + (this.worldObj.rand.doublev() - this.worldObj.rand.doublev()) * (double)this.spawnRange + 0.5D; - EntityLiving entity = null; - if(stack.getItem() instanceof ItemMonsterPlacer egg) - entity = ItemMonsterPlacer.spawnCreature(this.worldObj, egg.getSpawnedId(), x, y, z, true); - else if(stack.getItem() instanceof ItemNpcSpawner egg) - entity = ItemNpcSpawner.spawnNpc(this.worldObj, egg.getSpawnedChar(), x, y, z, true); - if (entity == null) - return true; - this.decrStackSize(0, 1); - entity.spawnExplosionParticle(); - this.resetTimer(); - return true; - } - - private void resetTimer() - { - if (this.maxSpawnDelay <= this.minSpawnDelay) - { - this.spawnDelay = this.minSpawnDelay; - } - else - { - int i = this.maxSpawnDelay - this.minSpawnDelay; - this.spawnDelay = this.minSpawnDelay + this.worldObj.rand.zrange(i); - } - } - - public void readTags(TagObject nbt) - { - super.readTags(nbt); - this.spawnDelay = nbt.getShort("Delay"); - - if (nbt.hasShort("MinSpawnDelay")) - { - this.minSpawnDelay = nbt.getShort("MinSpawnDelay"); - this.maxSpawnDelay = nbt.getShort("MaxSpawnDelay"); - } - - if (nbt.hasShort("SpawnRange")) - { - this.spawnRange = nbt.getShort("SpawnRange"); - } - } - - public void writeTags(TagObject nbt) - { - super.writeTags(nbt); - nbt.setShort("Delay", (short)this.spawnDelay); - nbt.setShort("MinSpawnDelay", (short)this.minSpawnDelay); - nbt.setShort("MaxSpawnDelay", (short)this.maxSpawnDelay); - nbt.setShort("SpawnRange", (short)this.spawnRange); - } -} diff --git a/common/src/main/java/common/util/EncryptUtil.java b/common/src/main/java/common/util/EncryptUtil.java deleted file mode 100644 index 278bc65..0000000 --- a/common/src/main/java/common/util/EncryptUtil.java +++ /dev/null @@ -1,280 +0,0 @@ -package common.util; - -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.EncodedKeySpec; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; -import java.util.Arrays; -import java.util.Base64; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.KeyAgreement; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.SecretKeySpec; - -import common.log.Log; - -public class EncryptUtil { - public static final String KEY_ALGO_NAME = "tcr-ed25519"; - public static final String KEY_ALGO_DISPLAY = "Ed25519"; - - private static final long CRC24_INIT = 0xB704CEL; - private static final long CRC24_POLY = 0x1864CFBL; - - public static SecretKey makeKeyAgreement(PrivateKey key, PublicKey pubkey) { - try { - KeyAgreement agreement = KeyAgreement.getInstance("X25519"); - agreement.init(key); - agreement.doPhase(pubkey, true); - return new SecretKeySpec(agreement.generateSecret(), 0, 16, "AES"); - } - catch(NoSuchAlgorithmException | InvalidKeyException e) { - Log.SYSTEM.error(e, "Konnte Diffie-Hellman-Schlüsselaushandlung nicht absolvieren"); - return null; - } - } - - public static KeyPair createDHKeypair() { - try { - KeyPairGenerator pairgen = KeyPairGenerator.getInstance("X25519"); - return pairgen.generateKeyPair(); - } - catch(NoSuchAlgorithmException e) { - Log.SYSTEM.error(e, "Konnte Schlüsselpaar für Diffie-Hellman nicht generieren"); - return null; - } - } - - public static KeyPair createKeypair() { - try { - KeyPairGenerator pairgen = KeyPairGenerator.getInstance("Ed25519"); - return pairgen.generateKeyPair(); - } - catch(NoSuchAlgorithmException e) { - Log.SYSTEM.error(e, "Konnte Schlüsselpaar nicht generieren"); - return null; - } - } - - public static byte[] createSignature(PrivateKey key, byte[] token) { - try { - Signature sig = Signature.getInstance("Ed25519"); - sig.initSign(key); - sig.update(token); - return sig.sign(); - } - catch(SignatureException | InvalidKeyException | NoSuchAlgorithmException e) { - Log.SYSTEM.error(e, "Konnte Signatur nicht generieren"); - return null; - } - } - - public static boolean verifySignature(PublicKey key, byte[] token, byte[] signature) { - try { - Signature sig = Signature.getInstance("Ed25519"); - sig.initVerify(key); - sig.update(token); - return sig.verify(signature); - } - catch(SignatureException | InvalidKeyException | NoSuchAlgorithmException e) { - Log.SYSTEM.error(e, "Konnte Signatur nicht verifizieren"); - return false; - } - } - - public static PublicKey decodeDHPublicKey(byte[] encoded) { - try { - EncodedKeySpec spec = new X509EncodedKeySpec(encoded); - KeyFactory factory = KeyFactory.getInstance("X25519"); - return factory.generatePublic(spec); - } - catch(NoSuchAlgorithmException | InvalidKeySpecException e) { - Log.SYSTEM.error(e, "Öffentlicher Schlüssel für Diffie-Hellman konnte nicht dekodiert werden"); - return null; - } - } - - public static PublicKey decodePublicKey(byte[] encoded) { - try { - EncodedKeySpec spec = new X509EncodedKeySpec(encoded); - KeyFactory factory = KeyFactory.getInstance("Ed25519"); - return factory.generatePublic(spec); - } - catch(NoSuchAlgorithmException | InvalidKeySpecException e) { - Log.SYSTEM.error(e, "Öffentlicher Schlüssel konnte nicht dekodiert werden"); - return null; - } - } - - public static PrivateKey decodePrivateKey(byte[] encoded) { - try { - EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded); - KeyFactory factory = KeyFactory.getInstance("Ed25519"); - return factory.generatePrivate(spec); - } - catch(NoSuchAlgorithmException | InvalidKeySpecException e) { - Log.SYSTEM.error(e, "Privater Schlüssel konnte nicht dekodiert werden"); - return null; - } - } - - public static byte[] encryptData(Key key, byte[] data) { - return cipher(Cipher.ENCRYPT_MODE, key, data); - } - - public static byte[] decryptData(Key key, byte[] data) { - return cipher(Cipher.DECRYPT_MODE, key, data); - } - - private static byte[] cipher(int mode, Key key, byte[] data) { - try { - return createCipher(mode, key.getAlgorithm(), key).doFinal(data); - } - catch(IllegalBlockSizeException | BadPaddingException e) { - Log.SYSTEM.error(e, "Konnte Daten nicht ver- oder entschlüsseln"); - return null; - } - } - - private static Cipher createCipher(int mode, String transformation, Key key) { - try { - Cipher cipher = Cipher.getInstance(transformation); - cipher.init(mode, key); - return cipher; - } - catch(InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) { - Log.SYSTEM.error(e, "Konnte Verschlüsselungsverfahren nicht initialisieren"); - return null; - } - } - - public static Cipher createCipher(int mode, Key key) { - try { - Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding"); - cipher.init(mode, (Key)key, (AlgorithmParameterSpec)(new IvParameterSpec(key.getEncoded()))); - return cipher; - } - catch(GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - public static String getXorSha512Hash(byte[] data) { - byte[] hash; - try { - MessageDigest digest = MessageDigest.getInstance("SHA-512"); - hash = digest.digest(data); - } - catch(NoSuchAlgorithmException e) { - Log.SYSTEM.error(e, "Konnte Schlüssel-Prüfwert nicht berechnen"); - return ""; - } - byte[] xor = new byte[8]; - for(int z = 0; z < hash.length / xor.length; z++) { - for(int n = 0; n < xor.length; n++) { - xor[n] ^= hash[z * xor.length + n]; - } - } - return Util.getHexString(xor); - } - - public static String getArmoredPubkey(PublicKey pubkey, String cn) { - StringBuilder sb = new StringBuilder(EncryptUtil.KEY_ALGO_NAME + " "); - sb.append(Base64.getEncoder().encodeToString(pubkey.getEncoded())); - sb.append(' ').append(Base64.getEncoder().encodeToString(crc24(pubkey.getEncoded()))); - return cn == null || cn.isEmpty() ? sb.toString() : sb.append(' ').append(Util.sanitizeCommonName(cn)).toString(); - } - - public static Pair parseArmoredPubkey(String armor) throws IllegalArgumentException { - String[] tok = armor.trim().split(" "); - if(tok.length != 3 && tok.length != 4) - throw new IllegalArgumentException("Key muss aus 3 oder 4 Segmenten bestehen"); - if(!tok[0].equals(EncryptUtil.KEY_ALGO_NAME)) - throw new IllegalArgumentException("Algorithmus '" + tok[0] + "' ist nicht unterstützt, es wird derzeit nur " + EncryptUtil.KEY_ALGO_NAME + " verwendet"); - byte[] key; - try { - key = Base64.getDecoder().decode(tok[1]); - } - catch(IllegalArgumentException e) { - throw new IllegalArgumentException("Schlüssel ist nicht im Base64-Format", e); - } - byte[] hash; - try { - hash = Base64.getDecoder().decode(tok[2]); - } - catch(IllegalArgumentException e) { - throw new IllegalArgumentException("Prüfwert ist nicht im Base64-Format", e); - } - if(hash.length != 3) - throw new IllegalArgumentException("Prüfwert hat die falsche Länge, erwarte 3 Bytes, habe " + hash.length + " Bytes"); - byte[] keyHash = crc24(key); - if(!Arrays.equals(hash, keyHash)) - throw new IllegalArgumentException("Prüfwert ist falsch, erwarte " + Util.getHexString(hash) + ", habe " + Util.getHexString(keyHash)); - PublicKey pubkey; - try { - EncodedKeySpec spec = new X509EncodedKeySpec(key); - KeyFactory factory = KeyFactory.getInstance("Ed25519"); - pubkey = factory.generatePublic(spec); - } - catch(NoSuchAlgorithmException | InvalidKeySpecException e) { - throw new IllegalArgumentException("Öffentlicher Schlüssel konnte nicht dekodiert werden", e); - } - if(tok.length == 4 && !Util.isValidCommonName(tok[3])) - throw new IllegalArgumentException("Name muss aus 'a-z' '0-9' und '-' bestehen, kann keine aufeinander folgenden Bindestriche haben und darf nicht damit beginnen oder darin enden"); - return new Pair(pubkey, tok.length == 4 ? tok[3] : null); - } - - private static byte[] crc24(byte[] data) { - long crc = CRC24_INIT; - for(byte bt : data) { - crc ^= (long)bt << 16; - for(int z = 0; z < 8; z++) { - crc <<= 1; - if((crc & 0x1000000) != 0) - crc ^= CRC24_POLY; - } - } - int value = (int)(crc & 0xFFFFFFL); - return new byte[] {(byte)((value >> 16) & 0xff), (byte)((value >> 8) & 0xff), (byte)(value & 0xff)}; - } - - public static byte[] hashPassword(String password, byte[] salt) { - try { - KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); - SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); - return factory.generateSecret(spec).getEncoded(); - } - catch(NoSuchAlgorithmException | InvalidKeySpecException e) { - Log.SYSTEM.error(e, "Konnte Passwort-Prüfwert nicht berechnen"); - return null; - } - } - - public static Pair hashPassword(String password) { - SecureRandom rand = new SecureRandom(); - byte[] salt = new byte[64]; - rand.nextBytes(salt); - return new Pair(hashPassword(password, salt), salt); - } -} diff --git a/common/src/main/java/common/util/LongHashMap.java b/common/src/main/java/common/util/LongHashMap.java deleted file mode 100755 index 65faf9b..0000000 --- a/common/src/main/java/common/util/LongHashMap.java +++ /dev/null @@ -1,293 +0,0 @@ -package common.util; - -public class LongHashMap -{ - private transient LongHashMap.Entry[] hashArray = new LongHashMap.Entry[4096]; - private transient int numHashElements; - private int mask; - private int capacity = 3072; - private final float percentUseable = 0.75F; - private transient volatile int modCount; - - public static long packInt(int x, int z) { - return (long)x & 4294967295L | ((long)z & 4294967295L) << 32; - } - - public static int getX(long v) { - return (int)(v & 4294967295L); - } - - public static int getZ(long v) { - return (int)(v >> 32); - } - - public LongHashMap() - { - this.mask = this.hashArray.length - 1; - } - - /** - * returns the hashed key given the original key - */ - private static int getHashedKey(long originalKey) - { - return hash((int)(originalKey ^ originalKey >>> 32)); - } - - /** - * the hash function - */ - private static int hash(int integer) - { - integer = integer ^ integer >>> 20 ^ integer >>> 12; - return integer ^ integer >>> 7 ^ integer >>> 4; - } - - /** - * gets the index in the hash given the array length and the hashed key - */ - private static int getHashIndex(int p_76158_0_, int p_76158_1_) - { - return p_76158_0_ & p_76158_1_; - } - - public int getNumHashElements() - { - return this.numHashElements; - } - - /** - * get the value from the map given the key - */ - public V getValueByKey(long p_76164_1_) - { - int i = getHashedKey(p_76164_1_); - - for (LongHashMap.Entry entry = this.hashArray[getHashIndex(i, this.mask)]; entry != null; entry = entry.nextEntry) - { - if (entry.key == p_76164_1_) - { - return entry.value; - } - } - - return (V)null; - } - - public boolean containsItem(long p_76161_1_) - { - return this.getEntry(p_76161_1_) != null; - } - - final LongHashMap.Entry getEntry(long p_76160_1_) - { - int i = getHashedKey(p_76160_1_); - - for (LongHashMap.Entry entry = this.hashArray[getHashIndex(i, this.mask)]; entry != null; entry = entry.nextEntry) - { - if (entry.key == p_76160_1_) - { - return entry; - } - } - - return null; - } - - /** - * Add a key-value pair. - */ - public void add(long p_76163_1_, V p_76163_3_) - { - int i = getHashedKey(p_76163_1_); - int j = getHashIndex(i, this.mask); - - for (LongHashMap.Entry entry = this.hashArray[j]; entry != null; entry = entry.nextEntry) - { - if (entry.key == p_76163_1_) - { - entry.value = p_76163_3_; - return; - } - } - - ++this.modCount; - this.createKey(i, p_76163_1_, p_76163_3_, j); - } - - /** - * resizes the table - */ - private void resizeTable(int p_76153_1_) - { - LongHashMap.Entry[] entry = this.hashArray; - int i = entry.length; - - if (i == 1073741824) - { - this.capacity = Integer.MAX_VALUE; - } - else - { - LongHashMap.Entry[] entry1 = new LongHashMap.Entry[p_76153_1_]; - this.copyHashTableTo(entry1); - this.hashArray = entry1; - this.mask = this.hashArray.length - 1; - this.capacity = (int)((float)p_76153_1_ * this.percentUseable); - } - } - - /** - * copies the hash table to the specified array - */ - private void copyHashTableTo(LongHashMap.Entry[] p_76154_1_) - { - LongHashMap.Entry[] entry = this.hashArray; - int i = p_76154_1_.length; - - for (int j = 0; j < entry.length; ++j) - { - LongHashMap.Entry entry1 = entry[j]; - - if (entry1 != null) - { - entry[j] = null; - - while (true) - { - LongHashMap.Entry entry2 = entry1.nextEntry; - int k = getHashIndex(entry1.hash, i - 1); - entry1.nextEntry = p_76154_1_[k]; - p_76154_1_[k] = entry1; - entry1 = entry2; - - if (entry2 == null) - { - break; - } - } - } - } - } - - /** - * calls the removeKey method and returns removed object - */ - public V remove(long p_76159_1_) - { - LongHashMap.Entry entry = this.removeKey(p_76159_1_); - return (V)(entry == null ? null : entry.value); - } - - final LongHashMap.Entry removeKey(long p_76152_1_) - { - int i = getHashedKey(p_76152_1_); - int j = getHashIndex(i, this.mask); - LongHashMap.Entry entry = this.hashArray[j]; - LongHashMap.Entry entry1; - LongHashMap.Entry entry2; - - for (entry1 = entry; entry1 != null; entry1 = entry2) - { - entry2 = entry1.nextEntry; - - if (entry1.key == p_76152_1_) - { - ++this.modCount; - --this.numHashElements; - - if (entry == entry1) - { - this.hashArray[j] = entry2; - } - else - { - entry.nextEntry = entry2; - } - - return entry1; - } - - entry = entry1; - } - - return entry1; - } - - /** - * creates the key in the hash table - */ - private void createKey(int p_76156_1_, long p_76156_2_, V p_76156_4_, int p_76156_5_) - { - LongHashMap.Entry entry = this.hashArray[p_76156_5_]; - this.hashArray[p_76156_5_] = new LongHashMap.Entry(p_76156_1_, p_76156_2_, p_76156_4_, entry); - - if (this.numHashElements++ >= this.capacity) - { - this.resizeTable(2 * this.hashArray.length); - } - } - - static class Entry - { - final long key; - V value; - LongHashMap.Entry nextEntry; - final int hash; - - Entry(int p_i1553_1_, long p_i1553_2_, V p_i1553_4_, LongHashMap.Entry p_i1553_5_) - { - this.value = p_i1553_4_; - this.nextEntry = p_i1553_5_; - this.key = p_i1553_2_; - this.hash = p_i1553_1_; - } - - public final long getKey() - { - return this.key; - } - - public final V getValue() - { - return this.value; - } - - public final boolean equals(Object p_equals_1_) - { - if (!(p_equals_1_ instanceof LongHashMap.Entry)) - { - return false; - } - else - { - LongHashMap.Entry entry = (LongHashMap.Entry)p_equals_1_; - Object object = Long.valueOf(this.getKey()); - Object object1 = Long.valueOf(entry.getKey()); - - if (object == object1 || object != null && object.equals(object1)) - { - Object object2 = this.getValue(); - Object object3 = entry.getValue(); - - if (object2 == object3 || object2 != null && object2.equals(object3)) - { - return true; - } - } - - return false; - } - } - - public final int hashCode() - { - return LongHashMap.getHashedKey(this.key); - } - - public final String toString() - { - return this.getKey() + "=" + this.getValue(); - } - } -} diff --git a/common/src/main/java/common/util/Pair.java b/common/src/main/java/common/util/Pair.java deleted file mode 100644 index 3ac253e..0000000 --- a/common/src/main/java/common/util/Pair.java +++ /dev/null @@ -1,4 +0,0 @@ -package common.util; - -public record Pair(A first, B second) { -} diff --git a/common/src/main/java/common/util/Position.java b/common/src/main/java/common/util/Position.java deleted file mode 100755 index ac29267..0000000 --- a/common/src/main/java/common/util/Position.java +++ /dev/null @@ -1,4 +0,0 @@ -package common.util; - -public record Position(double x, double y, double z, float yaw, float pitch, int dim) { -} diff --git a/common/src/main/java/common/util/ReleaseType.java b/common/src/main/java/common/util/ReleaseType.java deleted file mode 100644 index be367f8..0000000 --- a/common/src/main/java/common/util/ReleaseType.java +++ /dev/null @@ -1,24 +0,0 @@ -package common.util; - -public enum ReleaseType { - DEV("dev", 3), - ALPHA("alpha", 2), - BETA("beta", 1), - STABLE(null, 0); - - private final String suffix; - private final int id; - - private ReleaseType(String suffix, int id) { - this.suffix = suffix == null ? "" : "-" + suffix; - this.id = id; - } - - public String toString() { - return this.suffix; - } - - public int getId() { - return this.id; - } -} diff --git a/common/src/main/java/common/util/Triplet.java b/common/src/main/java/common/util/Triplet.java deleted file mode 100644 index ded6065..0000000 --- a/common/src/main/java/common/util/Triplet.java +++ /dev/null @@ -1,4 +0,0 @@ -package common.util; - -public record Triplet(A first, B second, C third) { -} diff --git a/common/src/main/java/common/util/Var.java b/common/src/main/java/common/util/Var.java deleted file mode 100644 index 3951c15..0000000 --- a/common/src/main/java/common/util/Var.java +++ /dev/null @@ -1,16 +0,0 @@ -package common.util; - -import static java.lang.annotation.ElementType.FIELD; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(FIELD) -@Retention(value = RetentionPolicy.RUNTIME) -public @interface Var { - String name(); - float min() default (float)Integer.MIN_VALUE; - float max() default (float)Integer.MAX_VALUE; - boolean nonDefault() default false; -} \ No newline at end of file diff --git a/common/src/main/java/common/village/MerchantRecipe.java b/common/src/main/java/common/village/MerchantRecipe.java deleted file mode 100755 index f21db8e..0000000 --- a/common/src/main/java/common/village/MerchantRecipe.java +++ /dev/null @@ -1,32 +0,0 @@ -package common.village; - -import common.item.Item; -import common.item.ItemStack; -import common.tags.TagObject; - -public record MerchantRecipe(ItemStack first, ItemStack second, ItemStack result) { - public MerchantRecipe(TagObject tag) { - this(ItemStack.readFromTag(tag.getObject("buy")), tag.hasObject("buyB") ? ItemStack.readFromTag(tag.getObject("buyB")) : null, ItemStack.readFromTag(tag.getObject("sell"))); - } - - public MerchantRecipe(ItemStack buy, ItemStack sell) { - this(buy, null, sell); - } - - public MerchantRecipe(ItemStack buy, Item sell) { - this(buy, new ItemStack(sell)); - } - - public boolean both() { - return this.second != null; - } - - public TagObject toTags() { - TagObject tag = new TagObject(); - tag.setObject("buy", this.first.writeTags(new TagObject())); - tag.setObject("sell", this.result.writeTags(new TagObject())); - if(this.second != null) - tag.setObject("buyB", this.second.writeTags(new TagObject())); - return tag; - } -} diff --git a/common/src/main/java/common/village/MerchantRecipeList.java b/common/src/main/java/common/village/MerchantRecipeList.java deleted file mode 100755 index f430552..0000000 --- a/common/src/main/java/common/village/MerchantRecipeList.java +++ /dev/null @@ -1,53 +0,0 @@ -package common.village; - -import java.util.ArrayList; - -import common.collect.Lists; -import common.item.ItemStack; -import common.tags.TagObject; -import java.util.List; - -public class MerchantRecipeList extends ArrayList { - public MerchantRecipe canUse(ItemStack stack1, ItemStack stack2, int index) { - if(index > 0 && index < this.size()) { - MerchantRecipe recipe = this.get(index); - return !areItemsSimilar(stack1, recipe.first()) - || (stack2 != null || recipe.both()) - && (!recipe.both() || !areItemsSimilar(stack2, recipe.second())) - || stack1.size < recipe.first().size - || recipe.both() && stack2.size < recipe.second().size ? null : recipe; - } - else { - for(int z = 0; z < this.size(); z++) { - MerchantRecipe recipe = this.get(z); - if(areItemsSimilar(stack1, recipe.first()) && stack1.size >= recipe.first().size - && (!recipe.both() && stack2 == null - || recipe.both() && areItemsSimilar(stack2, recipe.second()) - && stack2.size >= recipe.second().size)) { - return recipe; - } - } - return null; - } - } - - private static boolean areItemsSimilar(ItemStack stack1, ItemStack stack2) { - return ItemStack.areItemsEqual(stack1, stack2) - && (!stack2.hasTagCompound() || stack1.hasTagCompound() && TagObject.compare(stack2.getTagCompound(), stack1.getTagCompound())); - } - - public void fromTags(List list) { - this.clear(); - for(int z = 0; z < list.size(); z++) { - this.add(new MerchantRecipe(list.get(z))); - } - } - - public List toTags() { - List list = Lists.newArrayList(); - for(int z = 0; z < this.size(); z++) { - list.add(this.get(z).toTags()); - } - return list; - } -} diff --git a/common/src/main/java/common/world/Chunk.java b/common/src/main/java/common/world/Chunk.java deleted file mode 100755 index d86700b..0000000 --- a/common/src/main/java/common/world/Chunk.java +++ /dev/null @@ -1,842 +0,0 @@ -package common.world; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.function.Predicate; - -import common.block.Block; -import common.block.ITileEntityProvider; -import common.block.Material; -import common.collect.Maps; -import common.collect.Sets; -import common.entity.Entity; -import common.init.Blocks; -import common.log.Log; -import common.tileentity.TileEntity; -import common.util.BlockPos; -import common.util.BoundingBox; -import common.util.InheritanceMultiMap; -import common.util.ExtMath; -import common.util.Facing; -import common.util.IntHashMap; - -public abstract class Chunk { - public final int xPos; - public final int zPos; - protected final World world; - protected final State filler; - protected final Block fillerBlock; - protected final IntHashMap blocks = new IntHashMap(); - protected final Set blockList = Sets.newHashSet(); - protected final byte[] biomes = new byte[256]; - protected final int[] precHeight = new int[256]; - protected final boolean[] updateSky = new boolean[256]; - protected final int[] height = new int[256]; - protected final Map tiles = Maps.newHashMap(); - protected final InheritanceMultiMap[] entities = new InheritanceMultiMap[32]; - protected final ConcurrentLinkedQueue tileQueue = new ConcurrentLinkedQueue(); - - protected boolean loaded; - protected boolean gapUpdate; - protected boolean populated; - protected boolean lightInit; - protected boolean updated; - protected boolean modified; - protected boolean hasEntity; - protected int minHeight; - protected int lightChecks = Integer.MAX_VALUE; - protected int bottom = Integer.MAX_VALUE; - protected int top = Integer.MIN_VALUE; - - public Chunk(World world, int x, int z) { - this.world = world; - this.xPos = x; - this.zPos = z; - this.filler = world.dimension.getFiller(); - this.fillerBlock = this.filler.getBlock(); - for(int y = 0; y < this.entities.length; ++y) { - this.entities[y] = new InheritanceMultiMap(Entity.class); - } - Arrays.fill(this.precHeight, -99999999); - Arrays.fill(this.biomes, (byte)-1); - } - - public int getHeight(int x, int z) { - return this.height[z << 4 | x]; - } - - public BlockArray getArray(int y) { - return this.blocks.lookup(y); - } - - protected void setArray(BlockArray array) { - int y = array.getY() >> 4; - this.blocks.addKey(y, array); - this.blockList.add(array); - y <<= 4; - this.bottom = y < this.bottom ? y : this.bottom; - this.top = y > this.top ? y : this.top; - } - - public void genSkyLight() { - int top = this.top; - int bottom = this.bottom; - this.minHeight = Integer.MAX_VALUE; - - for(int x = 0; x < 16; ++x) { - for(int z = 0; z < 16; ++z) { - this.precHeight[x + (z << 4)] = -99999999; - - for(int y = top + 16; y > bottom; --y) { - if(this.getOpacity(x, y - 1, z) != 0) { - this.height[z << 4 | x] = y; - - if(y < this.minHeight) { - this.minHeight = y; - } - - break; - } - } - - if(!this.world.dimension.hasNoLight() && top != Integer.MIN_VALUE) { - int l = 15; - int y = top + 16 - 1; - - while(true) { - int b = this.getOpacity(x, y, z); - - if(b == 0 && l != 15) { - b = 1; - } - - l -= b; - - if(l > 0) { - BlockArray stor = this.getArray(y >> 4); - - if(stor != null) { - stor.setSky(x, y & 15, z, l); - this.world.notifyLightSet(new BlockPos((this.xPos << 4) + x, y, (this.zPos << 4) + z)); - } - } - - --y; - - if(y <= bottom || l <= 0) { - break; - } - } - } - } - } - - this.modified = true; - } - - private void propagateOcclusion(int x, int z) { - this.updateSky[x + z * 16] = true; - this.gapUpdate = true; - } - - private void recheckGaps(boolean single) { - if(this.world.isAreaLoaded(new BlockPos(this.xPos * 16 + 8, 0, this.zPos * 16 + 8), 16)) { - for(int x = 0; x < 16; ++x) { - for(int z = 0; z < 16; ++z) { - if(this.updateSky[x + z * 16]) { - this.updateSky[x + z * 16] = false; - int h = this.getHeight(x, z); - int cx = this.xPos * 16 + x; - int cz = this.zPos * 16 + z; - int max = Integer.MAX_VALUE; - - for(Facing face : Facing.Plane.HORIZONTAL) { - max = Math.min(max, this.world.getChunksLowestHorizon(cx + face.getFrontOffsetX(), - cz + face.getFrontOffsetZ())); - } - - this.checkNeighbor(cx, cz, max); - - for(Facing face : Facing.Plane.HORIZONTAL) { - this.checkNeighbor(cx + face.getFrontOffsetX(), cz + face.getFrontOffsetZ(), h); - } - - if(single) { - return; - } - } - } - } - - this.gapUpdate = false; - } - } - - private void checkNeighbor(int x, int z, int max) { - int h = this.world.getHeight(new BlockPos(x, 0, z)).getY(); - - if(h > max) { - this.updateNeighbor(x, z, max, h + 1); - } - else if(h < max) { - this.updateNeighbor(x, z, h, max + 1); - } - } - - private void updateNeighbor(int x, int z, int bottom, int top) { - if(top > bottom && this.world.isAreaLoaded(new BlockPos(x, 0, z), 16)) { - for(int y = bottom; y < top; ++y) { - this.world.checkLightFor(LightType.SKY, new BlockPos(x, y, z)); - } - - this.modified = true; - } - } - - private void relightBlock(int x, int y, int z) { - int h = this.height[z << 4 | x]; - int min = this.bottom; - int cy = h; - - if(y > h) { - cy = y; - } - - while(cy > min && this.getOpacity(x, cy - 1, z) == 0) { - --cy; - } - - if(cy != h) { - this.world.markBlocksDirtyVertical(x + this.xPos * 16, z + this.zPos * 16, cy, h); - this.height[z << 4 | x] = cy; - int cx = this.xPos * 16 + x; - int cz = this.zPos * 16 + z; - - if(!this.world.dimension.hasNoLight()) { - if(cy < h) { - for(int n = cy; n < h; ++n) { - BlockArray stor = this.getArray(n >> 4); - - if(stor != null) { - stor.setSky(x, n & 15, z, 15); - this.world.notifyLightSet(new BlockPos((this.xPos << 4) + x, n, (this.zPos << 4) + z)); - } - } - } - else { - for(int n = h; n < cy; ++n) { - BlockArray stor = this.getArray(n >> 4); - - if(stor != null) { - stor.setSky(x, n & 15, z, 0); - this.world.notifyLightSet(new BlockPos((this.xPos << 4) + x, n, (this.zPos << 4) + z)); - } - } - } - - int l = 15; - - while(cy > min && l > 0) { - --cy; - int b = this.getOpacity(x, cy, z); - - if(b == 0) { - b = 1; - } - - l -= b; - - if(l < 0) { - l = 0; - } - - BlockArray stor = this.getArray(cy >> 4); - - if(stor != null) { - stor.setSky(x, cy & 15, z, l); - } - } - } - - int sh = this.height[z << 4 | x]; - int sy = h; - int ey = sh; - - if(sh < h) { - sy = sh; - ey = h; - } - - if(sh < this.minHeight) { - this.minHeight = sh; - } - - if(!this.world.dimension.hasNoLight()) { - for(Facing face : Facing.Plane.HORIZONTAL) { - this.updateNeighbor(cx + face.getFrontOffsetX(), cz + face.getFrontOffsetZ(), sy, ey); - } - - this.updateNeighbor(cx, cz, sy, ey); - } - - this.modified = true; - } - } - - private int getOpacity(BlockPos pos) { - return this.getBlock(pos).getLightOpacity(); - } - - private int getOpacity(int x, int y, int z) { - return this.getBlock0(x, y, z).getLightOpacity(); - } - - protected Block getBlock0(int x, int y, int z) { - BlockArray stor = this.getArray(y >> 4); - return stor != null ? stor.getBlock(x, y & 15, z) : (y < 0 ? this.fillerBlock : Blocks.air); - } - - public State getState(BlockPos pos) { - BlockArray stor = this.getArray(pos.getY() >> 4); - return stor != null ? stor.get(pos.getX() & 15, pos.getY() & 15, pos.getZ() & 15) : (pos.getY() < 0 ? this.filler : Blocks.air.getState()); - } - - public Block getBlock(BlockPos pos) { - return this.getBlock0(pos.getX() & 15, pos.getY(), pos.getZ() & 15); - } - - public State setState(BlockPos pos, State state) { - int x = pos.getX() & 15; - int y = pos.getY(); - int z = pos.getZ() & 15; - int o = z << 4 | x; - - if(y >= this.precHeight[o] - 1) { - this.precHeight[o] = -99999999; - } - - int h = this.height[o]; - State old = this.getState(pos); - - if(old == state) { - return null; - } - else { - Block block = state.getBlock(); - Block oldb = old.getBlock(); - BlockArray stor = this.getArray(y >> 4); - boolean up = false; - - if(stor == null) { - if(block == Blocks.air && (y >= 0 || this.fillerBlock == Blocks.air)) { - return null; - } - - stor = new BlockArray(y >> 4 << 4, !this.world.dimension.hasNoLight(), y < 0 ? this.filler : null); - this.setArray(stor); - up = y >= h; - } - - stor.set(x, y & 15, z, state); - - if(oldb != block) { - if(!this.world.client) { - oldb.onBlockRemoved((AWorldServer)this.world, pos, old); - } - else if(oldb instanceof ITileEntityProvider) { - this.world.removeTileEntity(pos); - } - } - - if(stor.getBlock(x, y & 15, z) != block) { - return null; - } - else { - if(up) { - this.genSkyLight(); - } - else { - int b = block.getLightOpacity(); - int ob = oldb.getLightOpacity(); - - if(b > 0) { - if(y >= h) { - this.relightBlock(x, y + 1, z); - } - } - else if(y == h - 1) { - this.relightBlock(x, y, z); - } - - if(b != ob && (b < ob || this.getLight(LightType.SKY, pos) > 0 || this.getLight(LightType.BLOCK, pos) > 0)) { - this.propagateOcclusion(x, z); - } - } - - if(oldb instanceof ITileEntityProvider) { - TileEntity tile = this.getTileEntity(pos, TileEntity.EnumCreateEntityType.CHECK); - - if(tile != null) { - tile.updateContainingBlockInfo(); - } - } - - if(!this.world.client && oldb != block) { - block.onBlockAdded((AWorldServer)this.world, pos, state); - } - - if(block instanceof ITileEntityProvider) { - TileEntity tile = this.getTileEntity(pos, TileEntity.EnumCreateEntityType.CHECK); - - if(tile == null) { - tile = ((ITileEntityProvider)block).createNewTileEntity(this.world); - this.world.setTileEntity(pos, tile); - } - - if(tile != null) { - tile.updateContainingBlockInfo(); - } - } - - this.modified = true; - return old; - } - } - } - - public int getLight(LightType type, BlockPos pos) { - int x = pos.getX() & 15; - int y = pos.getY(); - int z = pos.getZ() & 15; - BlockArray stor = this.getArray(y >> 4); - return stor == null ? (this.canSeeSky(pos) ? type.defValue : 0) - : (type == LightType.SKY ? (this.world.dimension.hasNoLight() ? 0 : stor.getSky(x, y & 15, z)) - : (type == LightType.BLOCK ? stor.getLight(x, y & 15, z) : type.defValue)); - } - - public void setLight(LightType type, BlockPos pos, int value) { - int x = pos.getX() & 15; - int y = pos.getY(); - int z = pos.getZ() & 15; - BlockArray stor = this.getArray(y >> 4); - - if(stor == null) { - stor = new BlockArray(y >> 4 << 4, !this.world.dimension.hasNoLight(), y < 0 ? this.filler : null); - this.setArray(stor); - this.genSkyLight(); - } - - this.modified = true; - - if(type == LightType.SKY) { - if(!this.world.dimension.hasNoLight()) { - stor.setSky(x, y & 15, z, value); - } - } - else if(type == LightType.BLOCK) { - stor.setLight(x, y & 15, z, value); - } - } - - public int getLightSub(BlockPos pos, int amount) { - int x = pos.getX() & 15; - int y = pos.getY(); - int z = pos.getZ() & 15; - BlockArray stor = this.getArray(y >> 4); - - if(stor == null) { - return !this.world.dimension.hasNoLight() && amount < LightType.SKY.defValue - ? LightType.SKY.defValue - amount : 0; - } - else { - int l = this.world.dimension.hasNoLight() ? 0 : stor.getSky(x, y & 15, z); - l = l - amount; - int b = stor.getLight(x, y & 15, z); - - if(b > l) { - l = b; - } - - return l; - } - } - - public void addEntity(Entity entity) { - this.hasEntity = true; - int x = ExtMath.floord(entity.posX / 16.0D); - int z = ExtMath.floord(entity.posZ / 16.0D); - - if(x != this.xPos || z != this.zPos) { - Log.TICK.warn("Falsche Position! (" + x + ", " + z + ") sollte (" + this.xPos + ", " + this.zPos + ") sein, " + entity); - entity.setDead(); - } - - int y = ExtMath.floord(entity.posY / 16.0D); - - entity.addedToChunk = true; - entity.chunkCoordX = this.xPos; - entity.chunkCoordY = y; - entity.chunkCoordZ = this.zPos; - - if(y < 0) { - y = 0; - } - - if(y >= this.entities.length) { - y = this.entities.length - 1; - } - - this.entities[y].add(entity); - } - - public void removeEntity(Entity entity) { - int y = entity.chunkCoordY; - - if(y < 0) { - y = 0; - } - - if(y >= this.entities.length) { - y = this.entities.length - 1; - } - - this.entities[y].remove(entity); - } - - public boolean canSeeSky(BlockPos pos) { - int x = pos.getX() & 15; - int y = pos.getY(); - int z = pos.getZ() & 15; - return y >= this.height[z << 4 | x]; - } - - private TileEntity createNewTileEntity(BlockPos pos) { - Block block = this.getBlock(pos); - return !block.hasTileEntity() ? null : ((ITileEntityProvider)block).createNewTileEntity(this.world); - } - - public TileEntity getTileEntity(BlockPos pos, TileEntity.EnumCreateEntityType type) { - TileEntity tile = this.tiles.get(pos); - - if(tile == null) { - if(type == TileEntity.EnumCreateEntityType.IMMEDIATE) { - tile = this.createNewTileEntity(pos); - this.world.setTileEntity(pos, tile); - } - else if(type == TileEntity.EnumCreateEntityType.QUEUED) { - this.tileQueue.add(pos); - } - } - else if(tile.isInvalid()) { - this.tiles.remove(pos); - return null; - } - - return tile; - } - - public void addTileEntity(BlockPos pos, TileEntity tile) { - tile.setWorldObj(this.world); - tile.setPos(pos); - - if(this.getBlock(pos) instanceof ITileEntityProvider) { - if(this.tiles.containsKey(pos)) { - this.tiles.get(pos).invalidate(); - } - - if(tile.validate()) { - this.modified = true; - } - this.tiles.put(pos, tile); - } - } - - public void removeTileEntity(BlockPos pos) { - if(this.loaded) { - TileEntity tile = this.tiles.remove(pos); - - if(tile != null) { - tile.invalidate(); - } - } - } - - public void onChunkUnload() { - this.loaded = false; - - for(TileEntity tile : this.tiles.values()) { - this.world.markTileEntityForRemoval(tile); - } - - for(int n = 0; n < this.entities.length; ++n) { - this.world.unloadEntities(this.entities[n]); - } - } - - public void getEntities(Entity exclude, BoundingBox bb, List list, Predicate pred) { - int sy = ExtMath.floord((bb.minY - 2.0D) / 16.0D); - int ey = ExtMath.floord((bb.maxY + 2.0D) / 16.0D); - sy = ExtMath.clampi(sy, 0, this.entities.length - 1); - ey = ExtMath.clampi(ey, 0, this.entities.length - 1); - - for(int y = sy; y <= ey; ++y) { - if(!this.entities[y].isEmpty()) { - for(Entity entity : this.entities[y]) { - if(entity.getEntityBoundingBox().intersectsWith(bb) && entity != exclude) { - if(pred == null || pred.test(entity)) { - list.add(entity); - } - - Entity[] parts = entity.getParts(); - - if(parts != null) { - for(int l = 0; l < parts.length; ++l) { - entity = parts[l]; - - if(entity != exclude && entity.getEntityBoundingBox().intersectsWith(bb) - && (pred == null || pred.test(entity))) { - list.add(entity); - } - } - } - } - } - } - } - } - - public void getEntities(Class clazz, BoundingBox bb, List list, Predicate pred) { - int sy = ExtMath.floord((bb.minY - 2.0D) / 16.0D); - int ey = ExtMath.floord((bb.maxY + 2.0D) / 16.0D); - sy = ExtMath.clampi(sy, 0, this.entities.length - 1); - ey = ExtMath.clampi(ey, 0, this.entities.length - 1); - - for(int y = sy; y <= ey; ++y) { - for(T entity : this.entities[y].getByClass(clazz)) { - if(entity.getEntityBoundingBox().intersectsWith(bb) && (pred == null || pred.test(entity))) { - list.add(entity); - } - } - } - } - - public BlockPos getPrecipitation(BlockPos pos) { - int x = pos.getX() & 15; - int z = pos.getZ() & 15; - int o = x | z << 4; - BlockPos loc = new BlockPos(pos.getX(), this.precHeight[o], pos.getZ()); - - if(loc.getY() == -99999999) { - int y = this.top + 15; - int min = this.bottom; - loc = new BlockPos(pos.getX(), y, pos.getZ()); - int h = -1; - - while(loc.getY() > min && h == -1) { - Block block = this.getBlock(loc); - Material mat = block.getMaterial(); - - if((!mat.blocksMovement() && !mat.isLiquid()) - || (mat == Material.LEAVES && ((mat = this.getBlock(loc.up()).getMaterial()) == Material.POWDER) - || mat == Material.LEAVES)) { - loc = loc.down(); - } - else { - h = loc.getY() + 1; - } - } - - this.precHeight[o] = h; - } - - return new BlockPos(pos.getX(), this.precHeight[o], pos.getZ()); - } - - public void update(boolean noGaps) { - if(this.gapUpdate && !this.world.dimension.hasNoLight() && !noGaps) { - this.recheckGaps(this.world.client); - } - - this.updated = true; - - if(!this.lightInit && this.populated) { - this.checkLight(); - } - - while(!this.tileQueue.isEmpty()) { - BlockPos pos = (BlockPos)this.tileQueue.poll(); - - if(this.getTileEntity(pos, TileEntity.EnumCreateEntityType.CHECK) == null && this.getBlock(pos).hasTileEntity()) { - TileEntity tile = this.createNewTileEntity(pos); - this.world.setTileEntity(pos, tile); - this.world.markBlockRangeForRenderUpdate(pos, pos); - } - } - } - - public boolean isPopulated() { - return this.updated && this.populated && this.lightInit; - } - - public void resetRelight() { - this.lightChecks = 0; - } - - /** - * Called once-per-chunk-per-tick, and advances the round-robin relight check - * index by up to 8 blocks at a time. In a worst-case scenario, can potentially - * take up to 51.2 seconds, calculated via (8192/8)/20, to re-check all blocks - * in a chunk, which may explain lagging light updates on initial world - * generation. - */ - public void enqueueRelight() { - BlockPos pos = new BlockPos(this.xPos << 4, 0, this.zPos << 4); - - for(int n = 0; n < 8; ++n) { - if(this.top == Integer.MIN_VALUE) - return; - int h = 1 + (this.top >> 4) - (this.bottom >> 4); - if(this.lightChecks >= 256 * h) - return; - - int s = (this.lightChecks % h) + (this.bottom >> 4); - int x = this.lightChecks / h % 16; - int z = this.lightChecks / 512; - ++this.lightChecks; - - for(int y = 0; y < 16; ++y) { - BlockPos block = pos.add(x, (s << 4) + y, z); - boolean edge = y == 0 || y == 15 || x == 0 || x == 15 || z == 0 || z == 15; - - BlockArray arr = this.getArray(s); - if(arr == null && edge || arr != null - && arr.getBlock(x, y, z) == Blocks.air) { - for(Facing face : Facing.values()) { - BlockPos side = block.offset(face); - - if(this.world.getState(side).getBlock().getLightValue() > 0) { - this.world.checkLight(side); - } - } - - this.world.checkLight(block); - } - } - } - } - - public void checkLight() { - this.populated = true; - this.lightInit = true; - BlockPos pos = new BlockPos(this.xPos << 4, 0, this.zPos << 4); - - if(!this.world.dimension.hasNoLight()) { - if(this.world.isAreaLoaded(pos.add(-1, 0, -1), pos.add(16, this.world.getSeaLevel(), 16))) { - label92: - - for(int x = 0; x < 16; ++x) { - for(int z = 0; z < 16; ++z) { - if(!this.updateColumn(x, z)) { - this.lightInit = false; - break label92; - } - } - } - - if(this.lightInit) { - for(Facing face : Facing.Plane.HORIZONTAL) { - int d = face.getAxisDirection() == Facing.AxisDirection.POSITIVE ? 16 : 1; - this.world.getChunk(pos.offset(face, d)).updateColumns(face.getOpposite()); - } - - this.setSkyDirty(); - } - } - else { - this.lightInit = false; - } - } - } - - private void setSkyDirty() { - for(int n = 0; n < this.updateSky.length; ++n) { - this.updateSky[n] = true; - } - - this.recheckGaps(false); - } - - private void updateColumns(Facing facing) { - if(this.populated) { - if(facing == Facing.EAST) { - for(int z = 0; z < 16; ++z) { - this.updateColumn(15, z); - } - } - else if(facing == Facing.WEST) { - for(int z = 0; z < 16; ++z) { - this.updateColumn(0, z); - } - } - else if(facing == Facing.SOUTH) { - for(int x = 0; x < 16; ++x) { - this.updateColumn(x, 15); - } - } - else if(facing == Facing.NORTH) { - for(int x = 0; x < 16; ++x) { - this.updateColumn(x, 0); - } - } - } - } - - private boolean updateColumn(int x, int z) { - int top = this.top; - int bottom = this.bottom; - boolean opaque = false; - boolean below = false; - BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos((this.xPos << 4) + x, 0, (this.zPos << 4) + z); - - for(int y = top + 16 - 1; y > this.world.getSeaLevel() || y > bottom && !below; --y) { - pos.set(pos.getX(), y, pos.getZ()); - int o = this.getOpacity(pos); - - if(o == 255 && pos.getY() < this.world.getSeaLevel()) { - below = true; - } - - if(!opaque && o > 0) { - opaque = true; - } - else if(opaque && o == 0 && !this.world.checkLight(pos)) { - return false; - } - } - - for(int y = pos.getY(); y > bottom; --y) { - pos.set(pos.getX(), y, pos.getZ()); - - if(this.getBlock(pos).getLightValue() > 0) { - this.world.checkLight(pos); - } - } - - return true; - } - - public boolean isLoaded() { - return this.loaded; - } - - public InheritanceMultiMap[] getEntities() { - return this.entities; - } - - public int getLowest() { - return this.minHeight; - } -} diff --git a/common/src/main/java/common/world/LightType.java b/common/src/main/java/common/world/LightType.java deleted file mode 100755 index e1bfdbb..0000000 --- a/common/src/main/java/common/world/LightType.java +++ /dev/null @@ -1,11 +0,0 @@ -package common.world; - -public enum LightType { - SKY(15), BLOCK(0); - - public final int defValue; - - private LightType(int def) { - this.defValue = def; - } -} diff --git a/glfw_license.txt b/glfw_license.txt new file mode 100644 index 0000000..8a60e1d --- /dev/null +++ b/glfw_license.txt @@ -0,0 +1,21 @@ +Copyright (c) 2002-2006 Marcus Geelnard +Copyright (c) 2006-2010 Camilla Berglund + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would + be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not + be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source + distribution. diff --git a/gradle.properties b/gradle.properties deleted file mode 100644 index 91ec0d3..0000000 --- a/gradle.properties +++ /dev/null @@ -1,4 +0,0 @@ - -org.gradle.configuration-cache=false -org.gradle.parallel=true -org.gradle.caching=true diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml deleted file mode 100644 index 7908d7b..0000000 --- a/gradle/libs.versions.toml +++ /dev/null @@ -1,8 +0,0 @@ -# This file was generated by the Gradle 'init' task. -# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format - -[versions] -guava = "33.4.5-jre" - -[libraries] -guava = { module = "com.google.guava:guava", version.ref = "guava" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 1b33c55..0000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 002b867..0000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew deleted file mode 100755 index 23d15a9..0000000 --- a/gradlew +++ /dev/null @@ -1,251 +0,0 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 the original authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# SPDX-License-Identifier: Apache-2.0 -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -# This is normally unused -# shellcheck disable=SC2034 -APP_BASE_NAME=${0##*/} -# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH="\\\"\\\"" - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - if ! command -v java >/dev/null 2>&1 - then - die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, -# and any embedded shellness will be escaped. -# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be -# treated as '${Hostname}' itself on the command line. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ - "$@" - -# Stop when "xargs" is not available. -if ! command -v xargs >/dev/null 2>&1 -then - die "xargs is not available" -fi - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index db3a6ac..0000000 --- a/gradlew.bat +++ /dev/null @@ -1,94 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem -@rem SPDX-License-Identifier: Apache-2.0 -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH= - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/khronos_license.txt b/khronos_license.txt new file mode 100644 index 0000000..d7e6e9d --- /dev/null +++ b/khronos_license.txt @@ -0,0 +1,22 @@ +/* +** Copyright (c) 2013-2014 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ \ No newline at end of file diff --git a/libffi_license.txt b/libffi_license.txt new file mode 100644 index 0000000..7b64447 --- /dev/null +++ b/libffi_license.txt @@ -0,0 +1,21 @@ +libffi - Copyright (c) 1996-2020 Anthony Green, Red Hat, Inc and others. +See source files for details. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/liburing_license.txt b/liburing_license.txt new file mode 100644 index 0000000..67bc330 --- /dev/null +++ b/liburing_license.txt @@ -0,0 +1,7 @@ +Copyright 2020 Jens Axboe + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/lwjgl_license.txt b/lwjgl_license.txt new file mode 100644 index 0000000..a17ad0a --- /dev/null +++ b/lwjgl_license.txt @@ -0,0 +1,29 @@ +Copyright (c) 2012-present Lightweight Java Game Library +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +- Neither the name Lightweight Java Game Library nor the names of + its contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/server/build.gradle.kts b/server/build.gradle.kts deleted file mode 100644 index 86f419c..0000000 --- a/server/build.gradle.kts +++ /dev/null @@ -1,28 +0,0 @@ - -plugins { - application - id("com.gradleup.shadow") version "8.3.6" -} - -dependencies { - implementation(project(":common")) -} - -java { - toolchain { - languageVersion = JavaLanguageVersion.of(21) - } -} - -application { - mainClass = "server.Server" - tasks.run.get().workingDir = rootProject.file("dev/server") - tasks.run.get().workingDir.mkdirs() - tasks.run.get().systemProperties.put("runtime.devmode", "") - tasks.run.get().standardInput = System.`in` -} - -tasks.shadowJar { - destinationDirectory = rootProject.file("dev") - archiveFileName = "tcr_server.jar" -} diff --git a/server/src/main/java/server/command/Argument.java b/server/src/main/java/server/command/Argument.java deleted file mode 100644 index d933fd0..0000000 --- a/server/src/main/java/server/command/Argument.java +++ /dev/null @@ -1,6 +0,0 @@ -package server.command; - -import java.util.Map; - -public record Argument(Parameter parameter, int position, String[] inputs, Map values) { -} diff --git a/server/src/main/java/server/command/ArgumentSplitter.java b/server/src/main/java/server/command/ArgumentSplitter.java deleted file mode 100644 index b6aaa59..0000000 --- a/server/src/main/java/server/command/ArgumentSplitter.java +++ /dev/null @@ -1,224 +0,0 @@ -package server.command; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import common.collect.Lists; -import common.collect.Maps; -import common.collect.Sets; - -public record ArgumentSplitter(Map arguments, String command, CommandEnvironment env) { - private static String joinArgs(Iterable iter) { - StringBuilder sb = new StringBuilder("'"); - for(T obj : iter) { - if(sb.length() > 1) - sb.append("', '"); - sb.append(String.valueOf(obj)); - } - return sb.append("'").toString(); - } - - public static ArgumentSplitter parseArgs(CommandEnvironment env, String str, String[] argv, CachedExecutable cached) { - boolean lenient = str == null; - Map parameters = cached.parameters(); - List positionals = Lists.newArrayList(cached.positionals()); - // String[] argv = ArgumentParser.splitString(str); - Map args = Maps.newHashMap(); - int ppos = 0; - boolean parse = true; - int length = lenient ? argv.length - 1 : argv.length; - for(int z = 1; z < length; z++) { - String arg = argv[z]; - Parameter param = null; - boolean pos = false; - if(parse && arg.equals("--")) { - parse = false; - continue; - } - else if(parse && (arg.startsWith("--") || (arg.startsWith("-") && arg.length() == 2 && (arg.charAt(1) < '0' || arg.charAt(1) > '9')))) { - param = parameters.get(arg.substring(arg.startsWith("--") ? 2 : 1)); - if(param != null && param.positional() && !args.containsKey(param.name())) { - for(int n = 0; n < positionals.size(); n++) { - if(param == positionals.get(n)) { - positionals.remove(n); - break; - } - } - } - } - else if(ppos < positionals.size()) { - param = positionals.get(ppos++); - pos = true; - } - else { - throw new RunException("Position %d: Parameter '%s' ist überflüssig", z, arg); - } - if(param == null) - throw new RunException("Position %d: Argument '%s' ist unbekannt", z, arg); - if(args.containsKey(param.name())) - throw new RunException("Position %d: Parameter '%s' mehrfach angegeben", z, param.name()); - int nargs = param.parsers().size(); -// if(!pos) -// z += 1; - if(z + (pos ? 0 : 1) + nargs > length) - if(lenient) - return new ArgumentSplitter(args, str, env); - else if(nargs == 1 && param.name().equals(param.parsers().get(0).getName())) - throw new RunException("Position %d: Argument '%s' benötigt einen Parameter", z, param.name()); - else - throw new RunException("Position %d: Argument '%s' benötigt %d Parameter (%s)", z, param.name(), nargs, - joinArgs(param.parsers())); - Map params = Maps.newHashMapWithExpectedSize(nargs); - String[] inputs = new String[nargs + (pos ? 0 : 1)]; - int apos = 0; - for(int n = pos ? 0 : 1; n < nargs + (pos ? 0 : 1); n++) { - String par = inputs[n] = argv[z + n]; - ArgumentParser parser = param.parsers().get(apos); - if(parse && (par.startsWith("--") || (par.startsWith("-") && par.length() == 2 && (par.charAt(1) < '0' || par.charAt(1) > '9')))) - if(nargs == 1 && param.name().equals(parser.getName())) - throw new RunException("Position %d: Argument '%s': '%s' als Parameter verwendet", z + n, param.name(), par); - else - throw new RunException("Position %d: Argument '%s': '%s' als Parameter '%s' (#%d) verwendet", z + n, - param.name(), par, parser.getName(), apos + 1); - try { - params.put(parser.getName(), parser.parse(env, par)); - } - catch(Throwable e) { - if(nargs == 1 && param.name().equals(parser.getName())) - throw new RunException(e, "Position %d: Argument '%s': Parameter konnte nicht interpretiert werden", z + n, - param.name()); - else - throw new RunException(e, "Position %d: Argument '%s': Parameter '%s' (#%d) konnte nicht interpretiert werden", z + n, - param.name(), parser.getName(), apos + 1); - } - apos += 1; - } - if(!pos) - inputs[0] = arg; - args.put(param.name(), new Argument(param, z, inputs, params)); - z += nargs - (pos ? 1 : 0); - } - if(lenient) - return new ArgumentSplitter(args, str, env); - for(Parameter param : parameters.values()) { - if(!args.containsKey(param.name())) { - if(param.neededIn(env)) - throw new RunException("Argument '%s' muss angegeben werden", param.name()); - else if(param.parsers().isEmpty()) - continue; - Map params = Maps.newHashMapWithExpectedSize(param.parsers().size()); - for(ArgumentParser parser : param.parsers()) { - params.put(parser.getName(), parser.getDefault(env)); - } - args.put(param.name(), new Argument(param, -1, null, params)); - } - } - return new ArgumentSplitter(args, str, env); - } - - private static Iterable getParam(CommandEnvironment env, String[] argv, CachedExecutable cached, String last) { - ArgumentSplitter parsed; - try { - parsed = parseArgs(env, null, argv, cached); - } - catch(Throwable t) { - parsed = new ArgumentSplitter(Maps.newHashMap(), null, env); - } - Map parameters = cached.parameters(); - List positionals = Lists.newArrayList(cached.positionals()); - Set args = Sets.newHashSet(); - Executable exec = cached.executable(); - int ppos = 0; - boolean parse = true; - for(int z = 1; z < argv.length; z++) { - String arg = argv[z]; - Parameter param = null; - boolean pos = false; - if(z == argv.length - 1) { - if(ppos < positionals.size()) { - param = positionals.get(ppos); - if(param.parsers().isEmpty()) // np - return null; - Iterable custom = exec.getCustomCompletions(env, env.getExecutor(), parsed, param.name(), param.parsers().get(0).getName(), last); - return custom != null ? custom : param.parsers().get(0).getCompletions(env); - } - else { - return null; - } - } - else if(parse && arg.equals("--")) { - parse = false; - continue; - } - else if(parse && (arg.startsWith("--") || (arg.startsWith("-") && arg.length() == 2 && (arg.charAt(1) < '0' || arg.charAt(1) > '9')))) { - param = parameters.get(arg.substring(arg.startsWith("--") ? 2 : 1)); - if(param != null && param.positional() && !args.contains(param.name())) { - for(int n = 0; n < positionals.size(); n++) { - if(param == positionals.get(n)) { - positionals.remove(n); - break; - } - } - } - } - else if(ppos < positionals.size()) { - param = positionals.get(ppos++); - pos = true; - } - else { - return null; - } - if(param == null || args.contains(param.name())) - return null; - int nargs = param.parsers().size(); -// if(z + (pos ? 0 : 1) + nargs > argv.length - 1) { -// return param.getParsers().get(argv.length - z).getCompletions(env); -// } - int apos = 0; - for(int n = pos ? 0 : 1; n < nargs + (pos ? 0 : 1); n++) { - if(z + n == argv.length - 1) { - Iterable custom = exec.getCustomCompletions(env, env.getExecutor(), parsed, param.name(), param.parsers().get(apos).getName(), last); - return custom != null ? custom : param.parsers().get(apos).getCompletions(env); - } - String par = argv[z + n]; - if(parse && (par.startsWith("--") || (par.startsWith("-") && par.length() == 2 && (par.charAt(1) < '0' || par.charAt(1) > '9')))) - return null; - apos += 1; - } - args.add(param.name()); - z += nargs - (pos ? 1 : 0); - } - return null; - } - - public static Iterable parseComplete(CommandEnvironment env, String[] argv, CachedExecutable cached, String last) { - Iterable comp = getParam(env, argv, cached, last); - if(comp == null /* || comp.length == 0 */ ) { - Set params = Sets.newTreeSet(); - boolean all = last.startsWith("--"); - for(String param : cached.parameters().keySet()) { - if(all || param.length() == 1) - params.add(param.length() == 1 ? "-" + param : ("--" + param)); - } - return params; - } - return comp; - } - - public boolean has(String name) { - return this.arguments.containsKey(name); - } - - public T get(String name, String par) { - Argument arg = this.arguments.get(name); - if(arg == null) - return null; - Object value = arg.values().get(par); - return value == null ? null : (T)value; - } - - public T get(String name) { - return this.get(name, name); - } -} diff --git a/server/src/main/java/server/command/Executor.java b/server/src/main/java/server/command/Executor.java deleted file mode 100644 index e628987..0000000 --- a/server/src/main/java/server/command/Executor.java +++ /dev/null @@ -1,31 +0,0 @@ -package server.command; - -import common.entity.Entity; -import common.util.BlockPos; -import common.util.Position; - -public interface Executor { - void log(String msg); - Position getExecPos(); - void setExecPos(Position pos); - - default Entity getPointedEntity() { - return null; - } - - default BlockPos getPointedPosition() { - return null; - } - - default boolean isConsole() { - return false; - } - - default boolean isPlayer() { - return false; - } - - default void log(String fmt, Object ... args) { - this.log(String.format(fmt, args)); - } -} diff --git a/server/src/main/java/server/command/IntParser.java b/server/src/main/java/server/command/IntParser.java deleted file mode 100644 index 6db6b7e..0000000 --- a/server/src/main/java/server/command/IntParser.java +++ /dev/null @@ -1,97 +0,0 @@ -package server.command; - -import java.util.Collection; - -import common.collect.Lists; -import common.util.BlockPos; -import common.util.ExtMath; -import common.util.Position; - -public class IntParser extends DefaultingParser { - public static enum CoordType { - X, Y, Z; - } - - private final CoordType defType; - private final Integer min; - private final Integer max; - private final boolean hex; - - public IntParser(String name, boolean hex, Integer def, Integer min, Integer max, Object ... completions) { - super(name, def, completions); - this.defType = null; - this.min = min; - this.max = max; - this.hex = hex; - } - - public IntParser(String name, CoordType type, Integer min, Integer max) { - super(name, null); - this.defType = type; - this.min = min; - this.max = max; - this.hex = false; - } - - public Integer parse(CommandEnvironment env, String input) { - Integer pre = this.defType != null && input.startsWith("~") ? this.getDefault(env) : null; - input = pre != null ? input.substring(1) : input; - int value; - if(pre != null && input.isEmpty()) { - value = pre; - } - else { - try { - value = Integer.parseInt(input, this.hex ? 16 : 10); - } - catch(NumberFormatException e) { - throw new RunException("Ungültige " + (this.hex ? "Hexadezimalzahl" : "Ganzzahl") + " '%s'", input); - } - if(pre != null) - value = pre + value; - } - if(this.min != null && value < this.min) - if(this.max != null) - throw new RunException("Die Zahl muss im Bereich %d .. %d liegen, habe %d", this.min, this.max, value); - else - throw new RunException("Die Zahl muss mindestens %d betragen, habe %d", this.min, value); - if(this.max != null && value > this.max) - if(this.min != null) - throw new RunException("Die Zahl muss im Bereich %d .. %d liegen, habe %d", this.min, this.max, value); - else - throw new RunException("Die Zahl darf höchstens %d betragen, habe %d", this.max, value); - return value; - } - - public Integer getDefault(CommandEnvironment env) { - Position pos = this.defType == null ? null : env.getExecutor().getExecPos(); - if(this.defType != null) - switch(this.defType) { - case X: - return pos == null ? null : ExtMath.floord(pos.x()); - case Y: - return pos == null ? null : ExtMath.floord(pos.y()); - case Z: - return pos == null ? null : ExtMath.floord(pos.z()); - } - return (Integer)super.getDefault(env); - } - - public Class getTypeClass(boolean required) { - return this.hasDefault() || required ? int.class : Integer.class; - } - - public Collection getCompletions(CommandEnvironment env) { - BlockPos pos = this.defType == null ? null : env.getExecutor().getPointedPosition(); - if(this.defType != null) - switch(this.defType) { - case X: - return pos == null ? null : Lists.newArrayList("" + pos.getX()); - case Y: - return pos == null ? null : Lists.newArrayList("" + pos.getY()); - case Z: - return pos == null ? null : Lists.newArrayList("" + pos.getZ()); - } - return super.getCompletions(env); - } -} diff --git a/server/src/main/java/server/command/Parameter.java b/server/src/main/java/server/command/Parameter.java deleted file mode 100644 index 9c525ce..0000000 --- a/server/src/main/java/server/command/Parameter.java +++ /dev/null @@ -1,23 +0,0 @@ -package server.command; - -import java.util.List; - -public record Parameter(String name, char shortName, int position, boolean required, List parsers, ArgCombiner combiner) { - public boolean positional() { - return this.position >= 0; - } - - public boolean shorthand() { - return this.shortName != 0; - } - - public boolean neededIn(CommandEnvironment env) { - if(!this.required) - return false; - for(ArgumentParser parser : this.parsers) { - if(parser.getDefault(env) == null) - return true; - } - return false; - } -} diff --git a/server/src/main/java/server/command/PatternReplacer.java b/server/src/main/java/server/command/PatternReplacer.java deleted file mode 100644 index d209177..0000000 --- a/server/src/main/java/server/command/PatternReplacer.java +++ /dev/null @@ -1,21 +0,0 @@ -package server.command; - -import java.util.function.Function; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public record PatternReplacer(Pattern pattern, Function function) { - public void replace(StringBuffer sb) { - String str = sb.toString(); - sb.delete(0, sb.length()); - Matcher matcher = this.pattern.matcher(str); - while(matcher.find()) { - String orig = matcher.group(1); - String rep = this.function.apply(orig); - if(rep == null) - throw new RunException("Variable '%s' konnte in diesem Kontext nicht ersetzt werden", orig); - matcher.appendReplacement(sb, rep); - } - matcher.appendTail(sb); - } -} diff --git a/server/src/main/java/server/command/PlayerItemParser.java b/server/src/main/java/server/command/PlayerItemParser.java deleted file mode 100644 index 6c77aa0..0000000 --- a/server/src/main/java/server/command/PlayerItemParser.java +++ /dev/null @@ -1,27 +0,0 @@ -package server.command; - -import common.entity.npc.EntityNPC; -import common.item.ItemStack; - -public class PlayerItemParser extends PlayerEntityParser { - public PlayerItemParser(String name, boolean useSender, UserPolicy policy) { - super(name, useSender, policy); - } - - public Object parse(CommandEnvironment env, String input) { - EntityNPC entity = (EntityNPC)super.parse(env, input); - ItemStack stack = entity.getHeldItem(); - if(stack == null) - throw new RunException("%s hält keinen Gegenstand in der Hand", entity.getCommandName()); - return stack; - } - - public Object getDefault(CommandEnvironment env) { - EntityNPC entity = (EntityNPC)super.getDefault(env); - return entity == null ? null : entity.getHeldItem(); - } - - public Class getTypeClass(boolean required) { - return ItemStack.class; - } -} diff --git a/server/src/main/java/server/command/TagParser.java b/server/src/main/java/server/command/TagParser.java deleted file mode 100644 index c24522f..0000000 --- a/server/src/main/java/server/command/TagParser.java +++ /dev/null @@ -1,24 +0,0 @@ -package server.command; - -import common.tags.TagObject; - -public class TagParser extends DefaultingParser { - public TagParser(String name, TagObject def, Object ... completions) { - super(name, def, completions); - } - - public TagObject parse(CommandEnvironment env, String input) { - TagObject value; - try { - value = TagObject.parse(input); - } - catch(IllegalArgumentException e) { - throw new RunException(e, "Ungültiger Tag '%s'", input); - } - return value; - } - - public Class getTypeClass(boolean required) { - return TagObject.class; - } -} diff --git a/server/src/main/java/server/command/UserParser.java b/server/src/main/java/server/command/UserParser.java deleted file mode 100644 index da291e9..0000000 --- a/server/src/main/java/server/command/UserParser.java +++ /dev/null @@ -1,39 +0,0 @@ -package server.command; - -import java.util.Collection; - -import common.collect.Filter; -import server.network.Player; -import server.network.User; - -public class UserParser extends CompletingParser { - protected final boolean useSender; - protected final UserPolicy policy; - - public UserParser(String name, boolean useSender, UserPolicy policy) { - super(name); - this.useSender = useSender; - this.policy = policy; - } - - public Object parse(CommandEnvironment env, String input) { - User user = env.getServer().getUser(input); - if(user == null) - throw new RunException("Nutzer '%s' wurde nicht gefunden", input); - if(!this.policy.applies(env, env.getExecutor(), user)) - throw new RunException(this.policy.getDenyMessage(user)); - return user; - } - - public Object getDefault(CommandEnvironment env) { - return this.useSender && env.getExecutor().isPlayer() && this.policy.applies(env, env.getExecutor(), (Player)env.getExecutor()) ? (Player)env.getExecutor() : null; - } - - public Collection getCompletions(CommandEnvironment env) { - return Filter.filter(env.getServer().getAllUserNames(), user -> this.policy.applies(env, env.getExecutor(), env.getServer().getUser(user))); // add Lists.newArrayList if modifying! - } - - public Class getTypeClass(boolean required) { - return User.class; - } -} diff --git a/server/src/main/java/server/command/UserPolicy.java b/server/src/main/java/server/command/UserPolicy.java deleted file mode 100644 index d43890b..0000000 --- a/server/src/main/java/server/command/UserPolicy.java +++ /dev/null @@ -1,58 +0,0 @@ -package server.command; - -import server.network.User; - -public enum UserPolicy { - EVERYONE("Wie haste denn das nu geschafft??!") { - public boolean applies(CommandEnvironment env, Executor exec, User user) { - return true; - } - }, - NO_PLAYERS("Objekt ist ein Spieler") { - public boolean applies(CommandEnvironment env, Executor exec, User user) { - return false; - } - }, - NON_ADMINS("Spieler ist ein Admin") { - public boolean applies(CommandEnvironment env, Executor exec, User user) { - return !user.isAdmin() || exec.isConsole(); - } - }, - NON_ADMINS_STRICT("Spieler ist ein Admin") { - public boolean applies(CommandEnvironment env, Executor exec, User user) { - return !user.isAdmin(); - } - }, - ADMINS("Spieler ist kein Admin") { - public boolean applies(CommandEnvironment env, Executor exec, User user) { - return user.isAdmin(); - } - }, - NOT_SELF("Diese Aktion kann nur an anderen Spielern ausgeführt werden") { - public boolean applies(CommandEnvironment env, Executor exec, User user) { - return user != exec; - } - }, - NON_ADMINS_NOT_SELF("Diese Aktion kann nur an anderen Spielern ohne Admin-Status ausgeführt werden") { - public boolean applies(CommandEnvironment env, Executor exec, User user) { - return (!user.isAdmin() || exec.isConsole()) && user != exec; - } - }, - NON_ADMINS_OR_SELF("Spieler ist ein Admin") { - public boolean applies(CommandEnvironment env, Executor exec, User user) { - return !user.isAdmin() || user == exec || exec.isConsole(); - } - }; - - private final String denyMessage; - - private UserPolicy(String denyMessage) { - this.denyMessage = denyMessage; - } - - public String getDenyMessage(User user) { - return String.format("%s: %s", user.getUser(), this.denyMessage); - } - - public abstract boolean applies(CommandEnvironment env, Executor exec, User user); -} diff --git a/server/src/main/java/server/command/commands/CommandAdmin.java b/server/src/main/java/server/command/commands/CommandAdmin.java deleted file mode 100644 index a5587c4..0000000 --- a/server/src/main/java/server/command/commands/CommandAdmin.java +++ /dev/null @@ -1,23 +0,0 @@ -package server.command.commands; - -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; -import server.network.Player; -import server.network.User; - -public class CommandAdmin extends Command { - public CommandAdmin() { - super("admin"); - - this.addUser("user", false, UserPolicy.NON_ADMINS_STRICT); - } - - public void exec(CommandEnvironment env, Executor exec, User user) { - user.setAdmin(true); - if(user.isOnline()) - ((Player)user).log("Du hast Administatorrechte von %s bekommen", exec.isPlayer() ? ((Player)exec).getUser() : "der Konsole"); - exec.log("%s ist jetzt ein Admin", user.getUser()); - } -} diff --git a/server/src/main/java/server/command/commands/CommandBlock.java b/server/src/main/java/server/command/commands/CommandBlock.java deleted file mode 100644 index d0d3530..0000000 --- a/server/src/main/java/server/command/commands/CommandBlock.java +++ /dev/null @@ -1,61 +0,0 @@ -package server.command.commands; - -import java.util.Collection; -import common.init.BlockRegistry; -import common.tags.TagObject; -import common.tileentity.TileEntity; -import common.util.BlockPos; -import common.world.State; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.RunException; -import server.command.StringCompleter; -import server.world.WorldServer; - -public class CommandBlock extends Command { - public CommandBlock() { - super("block"); - - this.addString("block", false, new StringCompleter() { - public Collection complete(CommandEnvironment env) { - return BlockRegistry.REGISTRY.getKeys(); - } - }); - this.addBlockPos("position", true); - this.addWorld("dim", true); - - this.setParamsOptional(); - this.addTag("tag", 't'); - } - - public Object exec(CommandEnvironment env, Executor exec, String block, BlockPos position, WorldServer world, TagObject tag) { - State state = BlockRegistry.getFromIdName(block, null); - if(state == null) - throw new RunException("Block '%s' existiert nicht", block); - boolean success = world.setState(position, state); - if(tag != null) { - TileEntity tile = world.getTileEntity(position); - if(tile != null) { - TagObject te = new TagObject(); - tile.writeTags(te); - tag.setString("id", te.getString("id")); - tag.setInt("x", position.getX()); - tag.setInt("y", position.getY()); - tag.setInt("z", position.getZ()); - te.merge(tag); - TileEntity newTile = TileEntity.createAndLoadEntity(te); - if(newTile != null) { - world.removeTileEntity(position); - world.setTileEntity(position, newTile); - success = true; - } - } - } - if(success) - exec.log("%s bei %d, %d, %d in %s gesetzt", state.getBlock().getDisplay(), position.getX(), position.getY(), position.getZ(), world.dimension.getFormattedName(false)); - else - exec.log("Block wurde nicht verändert"); - return success; - } -} diff --git a/server/src/main/java/server/command/commands/CommandClear.java b/server/src/main/java/server/command/commands/CommandClear.java deleted file mode 100644 index b221069..0000000 --- a/server/src/main/java/server/command/commands/CommandClear.java +++ /dev/null @@ -1,40 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.entity.npc.EntityNPC; -import common.entity.types.EntityLiving; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; - -public class CommandClear extends Command { - public CommandClear() { - super("clear"); - - this.addLivingEntityList("entities", true, UserPolicy.NON_ADMINS_OR_SELF); - } - - public Object exec(CommandEnvironment env, Executor exec, List entities) { - int done = 0; - for(EntityLiving entity : entities) { - if(entity instanceof EntityNPC) { - if(entity.isPlayer()) { - ((EntityNPC)entity).inventory.clearItems(); - } - else { - ((EntityNPC)entity).getExtendedInventory().clear(); - for(int z = 0; z < 5; z++) { - ((EntityNPC)entity).setItem(z, null); - } - } - exec.log("Inventar von %s gelöscht", entity.getCommandName()); - done++; - } - } - if(done > 1) - exec.log("Inventar von %d Objekten gelöscht", done); - return done; - } -} diff --git a/server/src/main/java/server/command/commands/CommandDeathspot.java b/server/src/main/java/server/command/commands/CommandDeathspot.java deleted file mode 100644 index dcdff13..0000000 --- a/server/src/main/java/server/command/commands/CommandDeathspot.java +++ /dev/null @@ -1,35 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.entity.Entity; -import common.entity.npc.EntityNPC; -import common.init.UniverseRegistry; -import common.util.Position; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.RunException; -import server.command.UserPolicy; -import server.network.Player; - -public class CommandDeathspot extends Command { - public CommandDeathspot() { - super("deathspot"); - - this.addPlayerEntity("player", true, UserPolicy.NON_ADMINS_OR_SELF); - - this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); - } - - public Object exec(CommandEnvironment env, Executor exec, EntityNPC player, List entities) { - Position pos = ((Player)player.connection).getLastDeath(); - if(pos == null) - throw new RunException("%s hat keinen letzten Todespunkt", player.getCommandName()); - for(Entity entity : entities) { - entity.teleport(pos); - exec.log("%s zum Todespunkt von %s (%d, %d, %d in %s) teleportiert", entity.getCommandName(), player.getCommandName(), (int)pos.x(), (int)pos.y(), (int)pos.z(), UniverseRegistry.getDimension(pos.dim()).getFormattedName(false)); - } - return entities.size(); - } -} diff --git a/server/src/main/java/server/command/commands/CommandEntity.java b/server/src/main/java/server/command/commands/CommandEntity.java deleted file mode 100644 index 377c5aa..0000000 --- a/server/src/main/java/server/command/commands/CommandEntity.java +++ /dev/null @@ -1,46 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.entity.Entity; -import common.tags.TagObject; -import common.util.BlockPos; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; - -public class CommandEntity extends Command { - public CommandEntity() { - super("entity"); - - this.addEntityList("entities", false, UserPolicy.NO_PLAYERS); - this.setParamsOptional(); - this.addTag("tag"); - } - - public Object exec(CommandEnvironment env, Executor exec, List entities, TagObject tag) { - int done = 0; - for(Entity entity : entities) { - if(entity.isEntityAlive()) { - BlockPos pos = entity.getPosition(); - TagObject etag = new TagObject(); - entity.writeTags(etag); - if(tag == null) { - exec.log("************************************************************"); - exec.log("Daten von %s bei %d, %d, %d in %s:", entity.getCommandName(), pos.getX(), pos.getY(), pos.getZ(), entity.worldObj.dimension.getFormattedName(false)); - exec.log(etag.format(4)); - } - else { - etag.merge(tag); - entity.readTags(etag); - exec.log("Daten von %s bei %d, %d, %d in %s geändert", entity.getCommandName(), pos.getX(), pos.getY(), pos.getZ(), entity.worldObj.dimension.getFormattedName(false)); - } - done++; - } - } - if(tag != null && done > 1) - exec.log("Daten von %d Objekten geändert", done); - return done; - } -} diff --git a/server/src/main/java/server/command/commands/CommandExp.java b/server/src/main/java/server/command/commands/CommandExp.java deleted file mode 100644 index 359ce85..0000000 --- a/server/src/main/java/server/command/commands/CommandExp.java +++ /dev/null @@ -1,44 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.entity.npc.EntityNPC; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; - -public class CommandExp extends Command { - public CommandExp() { - super("exp"); - - this.setParamsOptional(); - this.addInt("points", 1, Integer.MAX_VALUE); - this.addFlag("reset", 'r'); - this.setParamsRequired(); - this.addPlayerEntityList("players", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); - } - - public void exec(CommandEnvironment env, Executor exec, Integer points, boolean reset, List players) { - for(EntityNPC player : players) { - if(points == null && !reset) { - exec.log("Erfahrung von %s: Level %d, %d/%d (%d Punkte)", player.getCommandName(), player.experienceLevel, (int)((float)player.xpBarCap() * player.experience), player.xpBarCap(), player.experienceTotal); - } - else if(reset) { - player.setExperience(points == null ? 0 : points); - exec.log("Erfahrung von %s " + (points == null ? "zurückgesetzt" : "auf %d Punkte gesetzt (Level %d)"), player.getCommandName(), player.experienceTotal, player.experienceLevel); - } - else { - int level = player.experienceLevel; - player.addExperience(points); - exec.log("%d Erfahrungspunkte an %s gegeben" + (player.experienceLevel != level ? ", ist jetzt Level %d" : ""), points, player.getCommandName(), player.experienceLevel); - } - } - if(players.size() > 1) { - if(reset) - exec.log("Erfahrung von %d Spielern " + (points == null ? "zurückgesetzt" : "auf %d Punkte gesetzt"), players.size(), points); - else if(points != null) - exec.log("%d Erfahrungspunkte an %d Spieler gegeben", points * players.size(), players.size()); - } - } -} diff --git a/server/src/main/java/server/command/commands/CommandFind.java b/server/src/main/java/server/command/commands/CommandFind.java deleted file mode 100644 index 99e8d27..0000000 --- a/server/src/main/java/server/command/commands/CommandFind.java +++ /dev/null @@ -1,32 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.entity.Entity; -import common.util.BlockPos; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; - -public class CommandFind extends Command { - public CommandFind() { - super("find"); - - this.addEntityList("entities", false, UserPolicy.EVERYONE); - } - - public Object exec(CommandEnvironment env, Executor exec, List entities) { - int done = 0; - for(Entity entity : entities) { - if(entity.isEntityAlive()) { - BlockPos pos = entity.getPosition(); - exec.log("%s bei %d, %d, %d in %s gefunden", entity.getCommandName(), pos.getX(), pos.getY(), pos.getZ(), entity.worldObj.dimension.getFormattedName(false)); - done++; - } - } - if(done > 1) - exec.log("%d Objekte gefunden", done); - return done; - } -} diff --git a/server/src/main/java/server/command/commands/CommandGod.java b/server/src/main/java/server/command/commands/CommandGod.java deleted file mode 100644 index ef5c51f..0000000 --- a/server/src/main/java/server/command/commands/CommandGod.java +++ /dev/null @@ -1,35 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.color.TextColor; -import common.entity.npc.EntityNPC; -import common.potion.Potion; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; - -public class CommandGod extends Command { - public CommandGod() { - super("god"); - - this.addPlayerEntityList("players", true, UserPolicy.NON_ADMINS_OR_SELF); - this.setParamsOptional(); - this.addFlag("remove", 'r'); - this.addFlag("quiet", 'q'); - } - - public void exec(CommandEnvironment env, Executor exec, List players, boolean remove, boolean quiet) { - remove = !remove && exec.isPlayer() && players.size() == 1 && players.get(0).connection == exec ? players.get(0).hasEffect(Potion.HASTE) && players.get(0).getEffect(Potion.HASTE).getAmplifier() == 255 : remove; - for(EntityNPC player : players) { - player.setGodMode(!remove); - if(!quiet) - player.connection.addFeed(!remove ? (TextColor.GREEN + "Statuseffekte wurden hinzugefügt") : (TextColor.RED + "Statuseffekte wurden entfernt")); - if(quiet || player.connection != exec) - exec.log("Statuseffekte " + (!remove ? "an %s gegeben" : "von %s entfernt"), player.getCommandName()); - } - if(players.size() > 1) - exec.log("Statuseffekte " + (!remove ? "an %d Spieler gegeben" : "von %d Spielern entfernt"), players.size()); - } -} diff --git a/server/src/main/java/server/command/commands/CommandHelp.java b/server/src/main/java/server/command/commands/CommandHelp.java deleted file mode 100644 index 8f21e7f..0000000 --- a/server/src/main/java/server/command/commands/CommandHelp.java +++ /dev/null @@ -1,71 +0,0 @@ -package server.command.commands; - -import java.util.Collection; -import java.util.List; -import java.util.Map.Entry; -import java.util.function.Function; - -import common.collect.Lists; -import common.util.Util; -import server.command.ArgumentParser; -import server.command.CachedExecutable; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.Parameter; -import server.command.RunException; -import server.command.StringCompleter; - -public class CommandHelp extends Command { - public CommandHelp() { - super("help"); - - this.setParamsOptional(); - this.addString("command", false, new StringCompleter() { - public Collection complete(CommandEnvironment env) { - return env.getExecutables().keySet(); - } - }); - } - - private void formatCommand(CommandEnvironment env, Executor exec, CachedExecutable cmd) { - List list = Lists.newArrayList(); - for(Entry entry : cmd.parameters().entrySet()) { - Parameter param = entry.getValue(); - boolean required = param.neededIn(env); - if(entry.getKey().length() == 1 && !param.positional() && param.shorthand()) { - list.add((required ? "<" : "[") + "-" + param.shortName() + (param.parsers().isEmpty() ? " (" + param.name() + ")" : (param.parsers().size() == 1 && - param.parsers().get(0).getName().equals(param.name()) ? " <" + param.name() + ">" : - " (" + param.name() + ")" + Util.buildLines(" ", new Function() { - public String apply(ArgumentParser parser) { - return "<" + parser.getName() + ">"; - } - }, param.parsers()))) + (required ? ">" : "]")); - } - } - for(Parameter param : cmd.positionals()) { - boolean required = param.neededIn(env); - list.add((required ? "<" : "[") + (param.parsers().size() == 1 && - param.parsers().get(0).getName().equals(param.name()) ? param.name() : - "(" + param.name() + ") " + Util.buildLines(" ", new Function() { - public String apply(ArgumentParser parser) { - return "<" + parser.getName() + ">"; - } - }, param.parsers())) + (required ? ">" : "]")); - } - exec.log("%s %s", cmd.name(), Util.buildLines(" ", list)); - } - - public void exec(CommandEnvironment env, Executor exec, String command) { - if(command == null) { - for(CachedExecutable cmd : env.getExecutables().values()) { - this.formatCommand(env, exec, cmd); - } - return; - } - CachedExecutable cmd = env.getExecutables().get(command); - if(cmd == null) - throw new RunException("Befehl '%s' ist nicht bekannt", command); - this.formatCommand(env, exec, cmd); - } -} diff --git a/server/src/main/java/server/command/commands/CommandItem.java b/server/src/main/java/server/command/commands/CommandItem.java deleted file mode 100644 index 00797d0..0000000 --- a/server/src/main/java/server/command/commands/CommandItem.java +++ /dev/null @@ -1,63 +0,0 @@ -package server.command.commands; - -import java.util.Collection; -import java.util.List; - -import common.entity.npc.EntityNPC; -import common.init.ItemRegistry; -import common.item.ItemStack; -import common.tags.TagObject; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.RunException; -import server.command.StringCompleter; -import server.command.UserPolicy; - -public class CommandItem extends Command { - public CommandItem() { - super("item"); - - this.addString("item", false, new StringCompleter() { - public Collection complete(CommandEnvironment env) { - return ItemRegistry.REGISTRY.getKeys(); - } - }); - this.setParamsOptional(); - this.addInt("amount", 1, ItemStack.MAX_SIZE, 1); - this.addTag("tag", 't'); - this.setParamsRequired(); - this.addPlayerEntityList("players", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); - } - - public Object exec(CommandEnvironment env, Executor exec, String item, int amount, TagObject tag, List players) { - ItemStack stack = ItemRegistry.getFromIdName(item, null); - if(stack == null) - throw new RunException("Gegenstand '%s' existiert nicht", item); - stack.setTagCompound(tag); - int done = 0; - int given = 0; - for(EntityNPC player : players) { - int total = amount; - while(total > 0) { - int added = Math.min(total, stack.getMaxStackSize()); - ItemStack st = stack.copy(); - st.size = added; - player.inventory.addItemStackToInventory(st); - added -= st.size; - if(added <= 0) - break; - total -= added; - } - total = amount - total; - if(total <= 0) - continue; - exec.log("%d * %s zum Inventar von %s hinzugefügt", total, stack.getDisplayName(), player.getCommandName()); - done++; - given += total; - } - if(done > 1) - exec.log("%d * %s an %d Spieler verteilt", given, stack.getDisplayName(), done); - return given; - } -} diff --git a/server/src/main/java/server/command/commands/CommandKick.java b/server/src/main/java/server/command/commands/CommandKick.java deleted file mode 100644 index 1b88406..0000000 --- a/server/src/main/java/server/command/commands/CommandKick.java +++ /dev/null @@ -1,26 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; -import server.network.Player; - -public class CommandKick extends Command { - public CommandKick() { - super("kick"); - - this.addPlayerList("player", false, UserPolicy.NON_ADMINS_NOT_SELF); - this.setParamsOptional(); - this.addString("message", "Du wurdest vom Server geworfen", false); - } - - public void exec(CommandEnvironment env, Executor exec, List players, String message) { - for(Player player : players) { - player.disconnect(message); - exec.log("%s wurde vom Server geworfen", player.getUser()); - } - } -} diff --git a/server/src/main/java/server/command/commands/CommandMagic.java b/server/src/main/java/server/command/commands/CommandMagic.java deleted file mode 100644 index 6c1df47..0000000 --- a/server/src/main/java/server/command/commands/CommandMagic.java +++ /dev/null @@ -1,51 +0,0 @@ -package server.command.commands; - -import java.util.Map.Entry; - -import common.enchantment.Enchantment; -import common.enchantment.EnchantmentHelper; -import common.item.ItemStack; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.RunException; -import server.command.UserPolicy; - -public class CommandMagic extends Command { - public CommandMagic() { - super("magic"); - - this.addEnum("enchantment", Enchantment.class, Enchantment.values()); - this.setParamsOptional(); - this.addInt("level", 1, 32767); - this.addFlag("remove", 'r'); - this.addFlag("force", 'f'); - this.setParamsRequired(); - this.addPlayerItem("player", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); - } - - public void exec(CommandEnvironment env, Executor exec, Enchantment ench, Integer level, boolean remove, boolean force, ItemStack stack) { - if(remove) { - int current = EnchantmentHelper.getEnchantmentLevel(ench, stack); - if(current == 0) - throw new RunException("%s hat die Verzauberung %s nicht", stack.getDisplayName(), ench.getDisplay()); - stack.removeEnchantment(ench); - exec.log("Verzauberung %s wurde von %s entfernt", ench.getFormattedName(current), stack.getDisplayName()); - return; - } - level = level == null ? ench.getMaxLevel() : level; - if(!force) { - if(level > ench.getMaxLevel()) - throw new RunException("Level %d ist zu hoch für %s, maximal %d erlaubt", level, ench.getDisplay(), ench.getMaxLevel()); - if(!ench.canApply(stack)) - throw new RunException("Verzauberung %s kann nicht auf %s verwendet werden", ench.getDisplay(), stack.getDisplayName()); - for(Entry id : EnchantmentHelper.getEnchantments(stack).entrySet()) { - if(id.getKey() != ench && !ench.canApplyTogether(id.getKey())) - throw new RunException("Verzauberung %s kann nicht zusammen mit %s verwendet werden", ench.getDisplay(), id.getKey().getFormattedName(id.getValue())); - } - } - stack.removeEnchantment(ench); - stack.addEnchantment(ench, level); - exec.log("Verzauberung %s wurde zu %s hinzugefügt", ench.getFormattedName(level), stack.getDisplayName()); - } -} diff --git a/server/src/main/java/server/command/commands/CommandMore.java b/server/src/main/java/server/command/commands/CommandMore.java deleted file mode 100644 index 05c72b1..0000000 --- a/server/src/main/java/server/command/commands/CommandMore.java +++ /dev/null @@ -1,55 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.entity.npc.EntityNPC; -import common.item.ItemStack; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; - -public class CommandMore extends Command { - public CommandMore() { - super("more"); - - this.setParamsOptional(); - this.addFlag("all", 'a'); - this.setParamsRequired(); - this.addPlayerEntityList("players", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); - } - - private int addItems(ItemStack stack) { - int diff = stack.getMaxStackSize() - stack.size; - stack.size = stack.getMaxStackSize(); - return diff; - } - - public void exec(CommandEnvironment env, Executor exec, boolean all, List players) { - int done = 0; - int added = 0; - for(EntityNPC player : players) { - int add = 0; - if(all) { - for(ItemStack item : player.inventory.mainInventory) { - if(item != null) - add += this.addItems(item); - } - for(ItemStack item : player.inventory.armorInventory) { - if(item != null) - add += this.addItems(item); - } - } - else if(player.getHeldItem() != null) { - add += this.addItems(player.getHeldItem()); - } - if(add > 0) { - exec.log("%d " + (add == 1 ? "Gegenstand" : "Gegenstände") + " wurde" + (add == 1 ? "" : "n") + " dem Inventar von %s hinzugefügt", add, player.getCommandName()); - done++; - } - added += add; - } - if(done > 1) - exec.log("%d Gegenstände wurden dem Inventar von %d Spielern hinzugefügt", added, done); - } -} diff --git a/server/src/main/java/server/command/commands/CommandNoclip.java b/server/src/main/java/server/command/commands/CommandNoclip.java deleted file mode 100644 index 46edf72..0000000 --- a/server/src/main/java/server/command/commands/CommandNoclip.java +++ /dev/null @@ -1,38 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.color.TextColor; -import common.entity.npc.EntityNPC; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; - -public class CommandNoclip extends Command { - public CommandNoclip() { - super("noclip"); - - this.addPlayerEntityList("players", true, UserPolicy.NON_ADMINS_OR_SELF); - this.setParamsOptional(); - this.addFlag("remove", 'r'); - this.addFlag("quiet", 'q'); - } - - public void exec(CommandEnvironment env, Executor exec, List players, boolean remove, boolean quiet) { - int done = 0; - remove = !remove && exec.isPlayer() && players.size() == 1 && players.get(0).connection == exec ? players.get(0).noclip : remove; - for(EntityNPC player : players) { - if(player.noclip == !remove) - continue; - player.setNoclip(!remove); - if(!quiet) - player.connection.addFeed((!remove ? TextColor.GREEN : TextColor.RED) + "NoClip wurde " + (!remove ? "eingeschaltet" : "ausgeschaltet")); - if(quiet || player.connection != exec) - exec.log("NoClip für %s " + (!remove ? "eingeschaltet" : "ausgeschaltet"), player.getCommandName()); - done++; - } - if(done > 1) - exec.log("NoClip von %d Spielern " + (!remove ? "eingeschaltet" : "ausgeschaltet"), done); - } -} diff --git a/server/src/main/java/server/command/commands/CommandPasswd.java b/server/src/main/java/server/command/commands/CommandPasswd.java deleted file mode 100644 index 6b3085b..0000000 --- a/server/src/main/java/server/command/commands/CommandPasswd.java +++ /dev/null @@ -1,80 +0,0 @@ -package server.command.commands; - -import java.security.MessageDigest; - -import common.color.TextColor; -import common.network.IPlayer; -import common.util.EncryptUtil; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.RunException; -import server.command.UserPolicy; -import server.network.Player; -import server.network.User; -import server.util.Form; -import server.vars.SVars; - -public class CommandPasswd extends Command { - public CommandPasswd() { - super("passwd"); - - this.addUser("user", true, UserPolicy.NON_ADMINS_OR_SELF); - this.setParamsOptional(); - this.addString("password", false); - } - - public void exec(CommandEnvironment env, Executor exec, User user, String password) { - if(exec.isPlayer()) { - if(password != null) - throw new RunException("Bei Verwendung als Spieler darf kein Passwort angegeben werden"); - if(user.getPubkey() != null && user == exec) - throw new RunException("Es darf kein Pubkey vorhanden sein, um diesen Befehl an sich selbst anzuwenden"); - if(user.getPasswordHash() == null && user == exec) - throw new RunException("Es muss ein Passwort vorhanden sein, um diesen Befehl an sich selbst anzuwenden"); - ((Player)exec).displayForm(new Form() { - private Field checkField; - private Field passwordField; - private Field confirmField; - - protected void init() { - this.checkField = user != exec ? null : this.addPassword("Aktuelles Passwort", 0, IPlayer.MAX_PASS_LENGTH, ""); - this.passwordField = this.addPassword("Neues Passwort", SVars.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); - this.confirmField = this.addPassword("Passwort bestätigen", SVars.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); - } - - public String getTitle() { - return "Passwort für " + user.getUser() + " ändern"; - } - - protected void accept() { - User plr = env.getServer().getUser(user.getUser()); - if(!((Player)exec).isAdmin() || plr == null || (plr.isAdmin() && plr != exec) || (plr.getPasswordHash() == null && plr == exec) || (plr.getPubkey() != null && plr == exec)) { - exec.log(TextColor.DRED + "Ein Fehler ist aufgetreten"); - return; - } - if(this.checkField != null && !MessageDigest.isEqual(EncryptUtil.hashPassword(this.checkField.get(), plr.getPasswordHash().second()), plr.getPasswordHash().first())) { - exec.log(TextColor.RED + "Falsches Passwort eingegeben"); - return; - } - if(!this.passwordField.get().equals(this.confirmField.get())) { - exec.log(TextColor.RED + "Passwörter stimmen nicht überein"); - return; - } - plr.setPasswordHash(EncryptUtil.hashPassword(this.passwordField.get())); - plr.setPubkey(null); - exec.log(TextColor.GREEN + "Passwort" + (plr != exec ? " für %s" : "") + " gesetzt", plr.getUser()); - } - }); - } - else if(exec.isConsole()) { - if(password == null) - throw new RunException("Bei Verwendung in der Konsole muss ein Passwort angegeben werden"); - if(password.length() < 8) - throw new RunException("Das Passwort ist zu kurz, mindestens 8 Zeichen sind erforderlich"); - user.setPasswordHash(EncryptUtil.hashPassword(password)); - user.setPubkey(null); - exec.log(TextColor.GREEN + "Passwort für %s gesetzt", user.getUser()); - } - } -} diff --git a/server/src/main/java/server/command/commands/CommandPlayers.java b/server/src/main/java/server/command/commands/CommandPlayers.java deleted file mode 100644 index fe2bcb9..0000000 --- a/server/src/main/java/server/command/commands/CommandPlayers.java +++ /dev/null @@ -1,33 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.color.TextColor; -import common.entity.npc.EntityNPC; -import common.util.ExtMath; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.network.Player; - -public class CommandPlayers extends Command { - public CommandPlayers() { - super("players"); - - this.setParamsOptional(); - this.addFlag("coords", 'c'); - } - - public void exec(CommandEnvironment env, Executor exec, boolean coords) { - List players = env.getServer().getPlayers(); - if(players.isEmpty()) { - exec.log(TextColor.DGRAY + "Es sind keine Spieler online"); - return; - } - exec.log(TextColor.GREEN + "Es " + (players.size() == 1 ? "ist" : "sind") + " " + TextColor.YELLOW + "%d" + TextColor.GREEN + " Spieler online", players.size()); - for(Player player : players) { - EntityNPC entity = player.getPresentEntity(); - exec.log("%s%s" + TextColor.GRAY + ": '%s" + TextColor.GRAY + "'" + (coords ? " [" + TextColor.ORANGE + "%s @ %d, %d, %d" + TextColor.GRAY + "]" : ""), player.isAdmin() ? TextColor.RED : TextColor.NEON, player.getUser(), entity == null ? TextColor.DGRAY + "<->" : TextColor.ACID + entity.getCommandName(), entity == null ? null : entity.worldObj.dimension.getFormattedName(false), entity == null ? null : ExtMath.floord(entity.posX), entity == null ? null : ExtMath.floord(entity.posY), entity == null ? null : ExtMath.floord(entity.posZ)); - } - } -} diff --git a/server/src/main/java/server/command/commands/CommandPubkey.java b/server/src/main/java/server/command/commands/CommandPubkey.java deleted file mode 100644 index 74384ab..0000000 --- a/server/src/main/java/server/command/commands/CommandPubkey.java +++ /dev/null @@ -1,87 +0,0 @@ -package server.command.commands; - -import java.security.MessageDigest; -import java.security.PublicKey; - -import common.color.TextColor; -import common.network.IPlayer; -import common.util.EncryptUtil; -import common.util.Pair; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.RunException; -import server.command.UserPolicy; -import server.network.Player; -import server.network.User; -import server.util.Form; - -public class CommandPubkey extends Command { - public CommandPubkey() { - super("pubkey"); - - this.addUser("user", true, UserPolicy.NON_ADMINS_OR_SELF); - this.setParamsOptional(); - this.addString("keySpec", false); - this.addString("keyData", false); - this.addString("keyHash", false); - this.addString("keyName", false); - } - - public void exec(CommandEnvironment env, Executor exec, User user, String keySpec, String keyData, String keyHash, String keyName) { - if(exec.isPlayer()) { - if(keySpec != null || keyData != null || keyHash != null || keyName != null) - throw new RunException("Bei Verwendung als Spieler darf kein Schlüssel angegeben werden"); - ((Player)exec).displayForm(new Form() { - private Field checkField; - private Field keyField; - - protected void init() { - this.checkField = user.getPasswordHash() == null || user != exec ? null : this.addPassword("Aktuelles Passwort", 0, IPlayer.MAX_PASS_LENGTH, ""); - this.keyField = this.addField("Neuer Pubkey", 1, 960, ""); - } - - public String getTitle() { - return "Schlüssel für " + user.getUser() + " ändern"; - } - - protected void accept() { - User plr = env.getServer().getUser(user.getUser()); - if(!((Player)exec).isAdmin() || plr == null || (plr.isAdmin() && plr != exec)) { - exec.log(TextColor.DRED + "Ein Fehler ist aufgetreten"); - return; - } - if(this.checkField != null && plr.getPasswordHash() != null && !MessageDigest.isEqual(EncryptUtil.hashPassword(this.checkField.get(), plr.getPasswordHash().second()), plr.getPasswordHash().first())) { - exec.log(TextColor.RED + "Falsches Passwort eingegeben"); - return; - } - Pair key; - try { - key = EncryptUtil.parseArmoredPubkey(this.keyField.get()); - } - catch(IllegalArgumentException e) { - exec.log(TextColor.RED + "Ungültiger Schlüssel"); - return; - } - plr.setPasswordHash(null); - plr.setPubkey(key.first()); - exec.log(TextColor.GREEN + "Schlüssel" + (plr != exec ? " für %s" : "") + " gesetzt", plr.getUser()); - } - }); - } - else if(exec.isConsole()) { - if(keySpec == null || keyData == null || keyHash == null) - throw new RunException("Bei Verwendung in der Konsole muss ein Schlüssel angegeben werden"); - Pair key; - try { - key = EncryptUtil.parseArmoredPubkey(keySpec + " " + keyData + " " + keyHash + (keyName == null ? null : " " + keyName)); - } - catch(IllegalArgumentException e) { - throw new RunException(e, "Ungültiger Schlüssel"); - } - user.setPasswordHash(null); - user.setPubkey(key.first()); - exec.log(TextColor.GREEN + "Schlüssel für %s gesetzt", user.getUser()); - } - } -} diff --git a/server/src/main/java/server/command/commands/CommandRegkey.java b/server/src/main/java/server/command/commands/CommandRegkey.java deleted file mode 100644 index 451c0b3..0000000 --- a/server/src/main/java/server/command/commands/CommandRegkey.java +++ /dev/null @@ -1,87 +0,0 @@ -package server.command.commands; - -import java.security.PublicKey; - -import common.color.TextColor; -import common.network.IPlayer; -import common.util.EncryptUtil; -import common.util.Pair; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.RunException; -import server.network.Player; -import server.network.User; -import server.util.Form; - -public class CommandRegkey extends Command { - public CommandRegkey() { - super("regkey"); - - this.addString("username", false, null, IPlayer.MAX_USER_LENGTH, IPlayer.VALID_USER); - this.setParamsOptional(); - this.addString("keySpec", false); - this.addString("keyData", false); - this.addString("keyHash", false); - this.addString("keyName", false); - this.addFlag("admin", 'a'); - } - - public void exec(CommandEnvironment env, Executor exec, String username, String keySpec, String keyData, String keyHash, String keyName, boolean admin) { - if(env.getServer().getUser(username) != null) - throw new RunException("Ein Spieler mit diesem Nutzernamen ist bereits registriert"); - if(env.getServer().loadPlayerData(username) != null) - throw new RunException("Ein Spieler mit diesem Nutzernamen hat bereits Spielerdaten, ist aber nicht registriert"); - if(exec.isPlayer()) { - if(keySpec != null || keyData != null || keyHash != null || keyName != null) - throw new RunException("Bei Verwendung als Spieler darf kein Schlüssel angegeben werden"); - ((Player)exec).displayForm(new Form() { - private Field keyField; - - protected void init() { - this.keyField = this.addField("Pubkey", 1, 960, ""); - } - - public String getTitle() { - return "Spieler " + username + " registrieren"; - } - - protected void accept() { - if(!((Player)exec).isAdmin() || env.getServer().getUser(username) != null || env.getServer().loadPlayerData(username) != null) { - exec.log(TextColor.DRED + "Ein Fehler ist aufgetreten"); - return; - } - Pair key; - try { - key = EncryptUtil.parseArmoredPubkey(this.keyField.get()); - } - catch(IllegalArgumentException e) { - exec.log(TextColor.RED + "Ungültiger Schlüssel"); - return; - } - User user = new User(username); - user.setPubkey(key.first()); - user.setAdmin(admin); - env.getServer().addUser(user); - exec.log(TextColor.GREEN + "Spieler %s registriert", username); - } - }); - } - else if(exec.isConsole()) { - if(keySpec == null || keyData == null || keyHash == null) - throw new RunException("Bei Verwendung in der Konsole muss ein Schlüssel angegeben werden"); - Pair key; - try { - key = EncryptUtil.parseArmoredPubkey(keySpec + " " + keyData + " " + keyHash + (keyName == null ? null : " " + keyName)); - } - catch(IllegalArgumentException e) { - throw new RunException(e, "Ungültiger Schlüssel"); - } - User user = new User(username); - user.setPubkey(key.first()); - user.setAdmin(admin); - env.getServer().addUser(user); - exec.log(TextColor.GREEN + "Spieler %s registriert", username); - } - } -} diff --git a/server/src/main/java/server/command/commands/CommandRename.java b/server/src/main/java/server/command/commands/CommandRename.java deleted file mode 100644 index e4c38cc..0000000 --- a/server/src/main/java/server/command/commands/CommandRename.java +++ /dev/null @@ -1,28 +0,0 @@ -package server.command.commands; - -import common.item.ItemStack; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; - -public class CommandRename extends Command { - public CommandRename() { - super("rename"); - - this.setParamsOptional(); - this.addString("name", false, 1, 30, null); - this.setParamsRequired(); - this.addPlayerItem("player", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); - } - - public void exec(CommandEnvironment env, Executor exec, String name, ItemStack stack) { - String prev = stack.getDisplayName(); - if(name == null) - stack.clearCustomName(); - else - stack.setStackDisplayName(name); - if(!prev.equals(stack.getDisplayName())) - exec.log("Gegenstand '%s' wurde zu '%s' umbenannt", prev, stack.getDisplayName()); - } -} diff --git a/server/src/main/java/server/command/commands/CommandRepair.java b/server/src/main/java/server/command/commands/CommandRepair.java deleted file mode 100644 index 23abc7b..0000000 --- a/server/src/main/java/server/command/commands/CommandRepair.java +++ /dev/null @@ -1,62 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.entity.npc.EntityNPC; -import common.item.ItemStack; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; - -public class CommandRepair extends Command { - public CommandRepair() { - super("repair"); - - this.setParamsOptional(); - this.addFlag("all", 'a'); - this.setParamsRequired(); - this.addPlayerEntityList("players", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); - } - - private boolean fixItem(ItemStack stack) { - boolean flag = false; - if(stack.getRepairCost() != 0) { - stack.setRepairCost(0); - flag = true; - } - if(stack.getItem().getMaxDamage() > 0 && stack.getItemDamage() != 0) { - stack.setItemDamage(0); - flag = true; - } - return flag; - } - - public void exec(CommandEnvironment env, Executor exec, boolean all, List players) { - int done = 0; - int repaired = 0; - for(EntityNPC player : players) { - int rep = 0; - if(all) { - for(ItemStack item : player.inventory.mainInventory) { - if(item != null && this.fixItem(item)) - rep++; - } - for(ItemStack item : player.inventory.armorInventory) { - if(item != null && this.fixItem(item)) - rep++; - } - } - else if(player.getHeldItem() != null && this.fixItem(player.getHeldItem())) { - rep++; - } - if(rep > 0) { - exec.log("%d " + (rep == 1 ? "Gegenstand" : "Gegenstände") + " im Inventar von %s wurde" + (rep == 1 ? "" : "n") + " repariert", rep, player.getCommandName()); - done++; - } - repaired += rep; - } - if(done > 1) - exec.log("%d Gegenstände im Inventar von %d Spielern wurden repariert", repaired, done); - } -} diff --git a/server/src/main/java/server/command/commands/CommandReturn.java b/server/src/main/java/server/command/commands/CommandReturn.java deleted file mode 100644 index 4f99203..0000000 --- a/server/src/main/java/server/command/commands/CommandReturn.java +++ /dev/null @@ -1,33 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.entity.npc.EntityNPC; -import common.init.UniverseRegistry; -import common.util.Position; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; -import server.network.Player; - -public class CommandReturn extends Command { - public CommandReturn() { - super("return"); - - this.addPlayerEntityList("players", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); - } - - public Object exec(CommandEnvironment env, Executor exec, List players) { - int done = 0; - for(EntityNPC player : players) { - Position pos = ((Player)player.connection).getLastTeleport(); - if(pos != null) { - player.teleport(pos); - exec.log("%s zum letzten Punkt (%d, %d, %d in %s) teleportiert", player.getCommandName(), (int)pos.x(), (int)pos.y(), (int)pos.z(), UniverseRegistry.getDimension(pos.dim()).getFormattedName(false)); - done++; - } - } - return done; - } -} diff --git a/server/src/main/java/server/command/commands/CommandRevoke.java b/server/src/main/java/server/command/commands/CommandRevoke.java deleted file mode 100644 index cea782a..0000000 --- a/server/src/main/java/server/command/commands/CommandRevoke.java +++ /dev/null @@ -1,26 +0,0 @@ -package server.command.commands; - -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.RunException; -import server.command.UserPolicy; -import server.network.Player; -import server.network.User; - -public class CommandRevoke extends Command { - public CommandRevoke() { - super("revoke"); - - this.addUser("user", false, UserPolicy.ADMINS); - } - - public void exec(CommandEnvironment env, Executor exec, User user) { - if(!exec.isConsole()) - throw new RunException("Dieser Befehl kann nur der Konsole ausgeführt werden"); - user.setAdmin(false); - if(user.isOnline()) - ((Player)user).log("Der Host hat deine Administatorrechte entfernt"); - exec.log("%s ist jetzt kein Admin mehr", user.getUser()); - } -} diff --git a/server/src/main/java/server/command/commands/CommandRunas.java b/server/src/main/java/server/command/commands/CommandRunas.java deleted file mode 100644 index caae85b..0000000 --- a/server/src/main/java/server/command/commands/CommandRunas.java +++ /dev/null @@ -1,26 +0,0 @@ -package server.command.commands; - -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; -import server.network.Player; - -public class CommandRunas extends Command { - public CommandRunas() { - super("~"); - - this.addPlayer("player", false, UserPolicy.NON_ADMINS_NOT_SELF); - this.addString("command", false); - } - - public void exec(CommandEnvironment env, Executor exec, Player player, String command) { - try { - player.setForcedExec(exec); - env.execute(command, player); - } - finally { - player.setForcedExec(null); - } - } -} diff --git a/server/src/main/java/server/command/commands/CommandRunat.java b/server/src/main/java/server/command/commands/CommandRunat.java deleted file mode 100644 index 0acbeb9..0000000 --- a/server/src/main/java/server/command/commands/CommandRunat.java +++ /dev/null @@ -1,37 +0,0 @@ -package server.command.commands; - -import java.util.List; - -import common.entity.Entity; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.UserPolicy; - -public class CommandRunat extends Command { - public CommandRunat() { - super("@"); - - this.addEntityList("entities", false, UserPolicy.NON_ADMINS_NOT_SELF); - this.addString("command", false); - } - - public Object exec(CommandEnvironment env, Executor exec, List entities, String command) { - int done = 0; - for(Entity entity : entities) { - if(entity.isEntityAlive()) { - try { - exec.setExecPos(entity.getPos()); - env.execute(command, exec); - } - finally { - exec.setExecPos(null); - } - done++; - } - } - if(done > 1) - exec.log("Befehl bei %d Objekten ausgeführt", done); - return done; - } -} diff --git a/server/src/main/java/server/command/commands/CommandSeed.java b/server/src/main/java/server/command/commands/CommandSeed.java deleted file mode 100644 index 1879edc..0000000 --- a/server/src/main/java/server/command/commands/CommandSeed.java +++ /dev/null @@ -1,24 +0,0 @@ -package server.command.commands; - -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.world.WorldServer; - -public class CommandSeed extends Command { - public CommandSeed() { - super("seed"); - - this.addWorld("dim", true); - - this.setParamsOptional(); - this.addFlag("dump", 'd'); - } - - public Object exec(CommandEnvironment env, Executor exec, WorldServer world, boolean dump) { - if(dump) - exec.log("Daten: %s", world.dimension.dumpTags().format(4)); - exec.log("Startwert von %s: %d", world.dimension.getFormattedName(false), world.dimension.getSeed()); - return world.dimension.getSeed(); - } -} diff --git a/server/src/main/java/server/command/commands/CommandSv.java b/server/src/main/java/server/command/commands/CommandSv.java deleted file mode 100644 index a6acbbf..0000000 --- a/server/src/main/java/server/command/commands/CommandSv.java +++ /dev/null @@ -1,100 +0,0 @@ -package server.command.commands; - -import java.util.Collection; -import java.util.Map.Entry; - -import common.collect.Lists; -import common.color.TextColor; -import server.command.ArgumentSplitter; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.command.RunException; -import server.command.StringCompleter; -import server.vars.SVar; -import server.vars.ValueType; - -public class CommandSv extends Command { - public CommandSv() { - super("sv"); - - this.setParamsOptional(); - this.addString("variable", false, new StringCompleter() { - public Collection complete(CommandEnvironment env) { - return env.getServer().getVariables().keySet(); - } - }); - this.addString("value", true); - } - - public Iterable getCustomCompletions(CommandEnvironment env, Executor exec, ArgumentSplitter parsed, String param, String parser, String arg) { - if(param.equals("value") && parsed.has("variable")) { - SVar sv = env.getServer().getVariables().get(parsed.get("variable")); - if(sv != null && sv.type == ValueType.BOOLEAN) - return Boolean.parseBoolean(sv.get()) ? Lists.newArrayList("false", "true") : Lists.newArrayList("true", "false"); - else if(sv != null && !sv.noDef && (sv.type == ValueType.INTEGER || sv.type == ValueType.FLOAT)) - return Lists.newArrayList(sv.def); - } - return null; - } - - private String formatVariable(String name, SVar sv, String separator, boolean censor) { - String value = sv.get(); - StringBuilder sb = new StringBuilder(TextColor.YELLOW + name + TextColor.GRAY + " " + separator + " "); - if(sv.noDef && sv.def.equals(value)) - sb.append(TextColor.DGRAY + "[ - ]"); - else if(censor && name.equals("password") && !value.isEmpty()) - sb.append(TextColor.NEON + "'****'"); - else if(sv.type == ValueType.STRING) - sb.append(TextColor.NEON + "'" + value + "'"); - else - sb.append(((sv.type == ValueType.BOOLEAN ? (value.equals("true") ? TextColor.GREEN : TextColor.RED) : TextColor.BLUE)) + value); - if(!sv.def.equals(value)) - sb.append(TextColor.GRAY + " (" + (sv.noDef ? TextColor.DGRAY + "[ - ]" : TextColor.BROWN + sv.def) + TextColor.GRAY + ")"); - return sb.toString(); - } - - public Object exec(CommandEnvironment env, Executor exec, String variable, String value) { - if(variable == null) { - if(value != null) - throw new RunException("Kann keinen Wert ohne eine Variable angeben"); - for(Entry entry : env.getServer().getVariables().entrySet()) { - exec.log(this.formatVariable(entry.getKey(), entry.getValue(), "=", true)); - } - exec.log(TextColor.GREEN + "SVARs insgesamt registriert: %d", env.getServer().getVariables().size()); - return null; - } - SVar sv = env.getServer().getVariables().get(variable); - if(sv == null) - throw new RunException("Variable '%s' existiert nicht", variable); - if(value != null) { - if(sv.type == ValueType.BOOLEAN && !"true".equals(value) && !"false".equals(value)) { - if(value.equals("0") || value.equals("1")) - value = "" + value.equals("1"); - else if(value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) - value = value.toLowerCase(); - else - throw new RunException("'%s' ist nicht 'true' (1) oder 'false' (0)", value); - } - else if(sv.type == ValueType.INTEGER) { - try { - Integer.parseInt(value); - } - catch(NumberFormatException e) { - throw new RunException(TextColor.DRED + "'%s' ist keine gültige Zahl", value); - } - } - else if(sv.type == ValueType.FLOAT) { - try { - Float.parseFloat(value); - } - catch(NumberFormatException e) { - throw new RunException(TextColor.DRED + "'%s' ist keine gültige Zahl", value); - } - } - sv.set(value, false, true); - } - exec.log(this.formatVariable(variable, sv, value == null ? "=" : "->", false)); - return sv.noDef && sv.def.equals(sv.get()) ? null : sv.get(); - } -} diff --git a/server/src/main/java/server/command/commands/CommandUsers.java b/server/src/main/java/server/command/commands/CommandUsers.java deleted file mode 100644 index 74da5a0..0000000 --- a/server/src/main/java/server/command/commands/CommandUsers.java +++ /dev/null @@ -1,26 +0,0 @@ -package server.command.commands; - -import java.util.Collection; -import common.color.TextColor; -import server.command.Command; -import server.command.CommandEnvironment; -import server.command.Executor; -import server.network.User; - -public class CommandUsers extends Command { - public CommandUsers() { - super("users"); - } - - public void exec(CommandEnvironment env, Executor exec) { - Collection users = env.getServer().getUsers(); - if(users.isEmpty()) { - exec.log(TextColor.DGRAY + "Es sind keine Spieler registriert"); - return; - } - exec.log(TextColor.GREEN + "Es " + (users.size() == 1 ? "ist" : "sind") + " " + TextColor.YELLOW + "%d" + TextColor.GREEN + " Spieler registriert", users.size()); - for(User user : users) { - exec.log("%s%s" + TextColor.GRAY + ": %s" + TextColor.GRAY + ", %s", user.isAdmin() ? TextColor.RED : TextColor.NEON, user.getUser(), user.isOnline() ? TextColor.DGREEN + "Online" : TextColor.DGRAY + "Offline", user.getPubkey() != null ? TextColor.YELLOW + "Pubkey" : (user.getPasswordHash() != null ? TextColor.MAGENTA + "Passwort" : TextColor.BLACK + "Kein Login")); - } - } -} diff --git a/server/src/main/java/server/network/LoginHandler.java b/server/src/main/java/server/network/LoginHandler.java deleted file mode 100755 index 10653ff..0000000 --- a/server/src/main/java/server/network/LoginHandler.java +++ /dev/null @@ -1,229 +0,0 @@ -package server.network; - -import java.security.KeyPair; -import java.security.MessageDigest; -import java.security.PublicKey; -import java.security.SecureRandom; -import common.color.TextColor; -import common.log.Log; -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; -import common.network.ILoginHandler; -import common.network.IPlayer; -import common.network.NetConnection; -import common.packet.LPacketChallenge; -import common.packet.LPacketPassword; -import common.packet.LPacketPubkey; -import common.packet.LPacketResponse; -import common.packet.LPacketStartEncrypt; -import common.packet.RPacketChallenge; -import common.packet.RPacketDisconnect; -import common.packet.RPacketRequestEncrypt; -import common.packet.RPacketResponse; -import common.packet.RPacketServerConfig; -import common.util.EncryptUtil; -import server.Server; -import server.vars.SVars; - -public class LoginHandler implements ILoginHandler -{ - private static enum LoginState { - INIT, ENCRYPT, PROOF, PASSWORD, CHALLENGE, AUTHENTICATED, ACCEPTED; - } - - private static final SecureRandom TOKEN_RNG = new SecureRandom(); - - private final Server server; - public final NetConnection netManager; - private final KeyPair tempKeys; - - private LoginState state = LoginState.INIT; - private int timer; - private String loginUser; - private String loginPass; - private byte[] loginToken; - private PublicKey loginKey; - - public LoginHandler(Server server, NetConnection netManager) - { - this.netManager = netManager; - this.server = server; - this.tempKeys = EncryptUtil.createDHKeypair(); - } - - public void closeConnection(String reason) - { - try - { - Log.NETWORK.info("Trenne " + this.getConnectionInfo()); - this.netManager.sendPacket(new RPacketDisconnect(reason)); - this.netManager.closeChannel(reason); - } - catch (Exception exception) - { - Log.NETWORK.error(exception, "Fehler beim Trennen des Spielers beim Login"); - } - } - - public void onDisconnect(String reason) - { - Log.NETWORK.info(this.getConnectionInfo() + " wurde beim Login getrennt: " + TextColor.stripCodes(reason)); - } - - public String getConnectionInfo() - { - return this.loginUser != null ? (this.loginUser + " (" + this.netManager.getCutAddress() - + ")") : this.netManager.getCutAddress(); - } - - public void update() - { - if(this.state == LoginState.AUTHENTICATED) - this.tryAdvance(); - if(this.timer++ == 600) - this.closeConnection("Anmeldung dauerte zu lange"); - } - - private void tryAdvance() { - String kick = this.checkPlayer(); - if(kick != null) { - this.closeConnection(kick); - return; - } - this.server.addPlayer(this.netManager, this.loginUser); - this.state = LoginState.ACCEPTED; - } - - private String checkPlayer() { - if(this.server.getPlayer(this.loginUser) != null) - return "Nutzername '" + this.loginUser + "' ist bereits vergeben"; - User user = this.server.getUser(this.loginUser); - if(SVars.authenticate) { - if(user == null) { - if(!SVars.register) - return "Anmeldung neuer Accounts ist auf diesem Server deaktiviert (Whitelisted)"; - if(SVars.playerLimit > 0 && this.server.getPlayers().size() >= SVars.playerLimit) - return String.format("Der Server ist voll (%d/%d)!", this.server.getPlayers().size(), SVars.playerLimit); - if(this.loginKey != null) { - this.server.addUser(user = new User(this.loginUser)); - user.setPubkey(this.loginKey); - Log.NETWORK.info(this.loginUser + " registrierte sich mit Pubkey"); - } - else { - if(this.loginPass == null || this.loginPass.length() == 0) - return "Ein neues Passwort ist erforderlich um diesen Server zu betreten (mindestens " + SVars.minPassLength + " Zeichen)"; - if(this.loginPass.length() < SVars.minPassLength) - return "Passwort ist zu kurz, mindestens " + SVars.minPassLength + " Zeichen"; - this.server.addUser(user = new User(this.loginUser)); - user.setPasswordHash(EncryptUtil.hashPassword(this.loginPass)); - Log.NETWORK.info(this.loginUser + " registrierte sich mit Passwort"); - } - } - else if((user.getPasswordHash() == null && user.getPubkey() == null) || (user.getPubkey() != null ? !user.getPubkey().equals(this.loginKey) : - (this.loginPass == null || !MessageDigest.isEqual(EncryptUtil.hashPassword(this.loginPass, user.getPasswordHash().second()), user.getPasswordHash().first())))) { - return this.loginKey != null ? "Falscher Pubkey" : "Falsches Passwort"; - } - else { - Log.NETWORK.info(this.loginUser + " loggte sich mit " + (this.loginKey != null ? "Pubkey" : "Passwort") + " ein"); - } - } - if(SVars.playerLimit > 0 && this.server.getPlayers().size() >= SVars.playerLimit && (user == null || !user.isAdmin())) - return String.format("Der Server ist voll (%d/%d)!", this.server.getPlayers().size(), SVars.playerLimit); - return null; - } - - public void sendLoginPacket() { - if(this.state != LoginState.INIT) - throw new IllegalStateException("Unerwartetes Handshake-Paket"); - if(SVars.encrypt) { - this.state = LoginState.ENCRYPT; - this.netManager.sendPacket(new RPacketRequestEncrypt(this.server.getPublicKey(), this.tempKeys.getPublic())); - } - else { - this.state = LoginState.PASSWORD; - this.netManager.sendPacket(new RPacketServerConfig(SVars.accessRequired, SVars.authenticate, SVars.authenticate && SVars.passwordAuth, false)); - } - } - - public void processEncryption(LPacketStartEncrypt packet) { - if(this.state != LoginState.ENCRYPT) - throw new IllegalStateException("Unerwartetes Verschlüsselungs-Paket"); - this.netManager.startEncryption(EncryptUtil.makeKeyAgreement(this.tempKeys.getPrivate(), packet.getKey())); - this.state = LoginState.PROOF; - } - - public void processChallenge(LPacketChallenge packet) { - if(this.state != LoginState.PROOF) - throw new IllegalStateException("Unerwartetes Anforderungs-Paket"); - this.state = LoginState.PASSWORD; - this.netManager.sendPacket(new RPacketResponse(this.server.getPrivateKey(), packet.getToken()), new GenericFutureListener < Future > () { - public void operationComplete(Future u) throws Exception { - LoginHandler.this.netManager.sendPacket(new RPacketServerConfig(SVars.accessRequired, SVars.authenticate, SVars.authenticate && SVars.passwordAuth, - SVars.authenticate && SVars.pubkeyAuth)); - } - }); - } - - private boolean checkAccess(String access) { - if(SVars.accessRequired) { - if(SVars.password.length() < 8) { - this.closeConnection("Es ist kein Zugangspasswort für diesen Server konfiguriert"); - return false; - } - if(!SVars.password.equals(access)) { - this.closeConnection("Falsches Zugangspasswort"); - return false; - } - } - return true; - } - - public void processPassword(LPacketPassword packet) { - if(this.state != LoginState.PASSWORD) - throw new IllegalStateException("Unerwartetes Passwort-Paket"); - this.loginUser = packet.getUser(); - if(this.loginUser.isEmpty() || !IPlayer.isValidUser(this.loginUser)) - throw new IllegalStateException("Ungültiger Nutzername!"); - if(!SVars.passwordAuth && SVars.authenticate) { - this.closeConnection("Dieser Server " + (SVars.pubkeyAuth && SVars.encrypt ? "benötigt einen öffentlichen Schlüssel zur Authentifizierung" : "hat keine Authentifizierungsmethode konfiguriert")); - return; - } - if(!this.checkAccess(packet.getAccess())) - return; - if(SVars.authenticate) - this.loginPass = packet.getPassword(); - this.state = LoginState.AUTHENTICATED; - } - - public void processPubkey(LPacketPubkey packet) { - if(this.state != LoginState.PASSWORD) - throw new IllegalStateException("Unerwartetes Pubkey-Paket"); - this.loginUser = packet.getUser(); - if(this.loginUser.isEmpty() || !IPlayer.isValidUser(this.loginUser)) - throw new IllegalStateException("Ungültiger Nutzername!"); - if((!SVars.pubkeyAuth || !SVars.encrypt) && SVars.authenticate) { - this.closeConnection("Dieser Server " + (SVars.passwordAuth ? "benötigt ein Passwort zur Authentifizierung" : "hat keine Authentifizierungsmethode konfiguriert")); - return; - } - if(!this.checkAccess(packet.getAccess())) - return; - if(SVars.authenticate) { - this.loginKey = packet.getKey(); - this.loginToken = new byte[32]; - TOKEN_RNG.nextBytes(this.loginToken); - this.netManager.sendPacket(new RPacketChallenge(this.loginToken)); - this.state = LoginState.CHALLENGE; - } - else { - this.state = LoginState.AUTHENTICATED; - } - } - - public void processResponse(LPacketResponse packet) { - if(this.state != LoginState.CHALLENGE) - throw new IllegalStateException("Unerwartetes Beweis-Paket"); - if(!packet.verifyToken(this.loginKey, this.loginToken)) - throw new IllegalStateException("Fehlerhaftes Beweis-Token"); - this.state = LoginState.AUTHENTICATED; - } -} diff --git a/server/src/main/java/server/network/User.java b/server/src/main/java/server/network/User.java deleted file mode 100644 index 6b52716..0000000 --- a/server/src/main/java/server/network/User.java +++ /dev/null @@ -1,121 +0,0 @@ -package server.network; - -import java.io.File; -import java.security.PublicKey; -import java.util.Map; - -import common.log.Log; -import common.network.IPlayer; -import common.tags.TagObject; -import common.util.EncryptUtil; -import common.util.Pair; - -public class User { - private final String user; - private boolean admin; - private Pair password; - private PublicKey pubkey; - - public User(String user) { - this.user = user; - } - - public boolean isOnline() { - return false; - } - - public String getUser() { - return this.user; - } - - public void setAdmin(boolean admin) { - this.admin = admin; - } - - public boolean isAdmin() { - return this.admin; - } - - public void setPasswordHash(Pair hash) { - this.password = hash; - } - - public Pair getPasswordHash() { - return this.password; - } - - public void setPubkey(PublicKey key) { - this.pubkey = key; - } - - public PublicKey getPubkey() { - return this.pubkey; - } - - public void copyFrom(User user) { - this.admin = user.admin; - this.password = user.password; - this.pubkey = user.pubkey; - } - - public void readUserTags(TagObject tag) { - this.admin = tag.getBool("admin"); - if(tag.hasByteArray("passwordHash") && tag.hasByteArray("passwordSalt")) - this.password = new Pair(tag.getByteArray("passwordHash"), tag.getByteArray("passwordSalt")); - if(tag.hasByteArray("pubkey")) - this.pubkey = EncryptUtil.decodePublicKey(tag.getByteArray("pubkey")); - } - - public void writeUserTags(TagObject tag) { - if(this.admin) - tag.setBool("admin", this.admin); - if(this.password != null) { - tag.setByteArray("passwordHash", this.password.first()); - tag.setByteArray("passwordSalt", this.password.second()); - } - if(this.pubkey != null) - tag.setByteArray("pubkey", this.pubkey.getEncoded()); - } - - public static void saveDatabase(Map map) { - TagObject tag = new TagObject(); - for(User user : map.values()) { - TagObject data = new TagObject(); - user.writeUserTags(data); - tag.setObject(user.getUser(), data); - } - File nfile = new File("users.cdt.tmp"); - File lfile = new File("users.cdt"); - try { - TagObject.writeGZip(tag, nfile); - if(lfile.exists()) - lfile.delete(); - nfile.renameTo(lfile); - } - catch(Exception e) { - Log.IO.error(e, "Fehler beim Schreiben von " + nfile); - } - } - - public static void loadDatabase(Map map) { - File file = new File("users.cdt"); - if(!file.exists()) - file = new File("users.cdt.tmp"); - if(file.exists()) { - try { - TagObject tag = TagObject.readGZip(file); - for(String key : tag.keySet()) { - if(IPlayer.isValidUser(key) && tag.hasObject(key)) { - User user = new User(key); - user.readUserTags(tag.getObject(key)); - map.put(key, user); - } - } - } - catch(Exception e) { - Log.IO.error(e, "Fehler beim Lesen von " + file); - map.clear(); - } - } - } -} diff --git a/server/src/main/java/server/vars/SVar.java b/server/src/main/java/server/vars/SVar.java deleted file mode 100644 index deaa95a..0000000 --- a/server/src/main/java/server/vars/SVar.java +++ /dev/null @@ -1,84 +0,0 @@ -package server.vars; - -import java.lang.reflect.Field; - -import common.util.ExtMath; -import common.util.Var; - -public class SVar { - public final ValueType type; - public final String def; - public final boolean noDef; - private final Field field; - private final float min; - private final float max; - - private Runnable callback; - - public SVar(Field field, Var value) { - this.type = field.getType() == int.class ? ValueType.INTEGER : (field.getType() == boolean.class ? ValueType.BOOLEAN : - (field.getType() == String.class ? ValueType.STRING : (field.getType() == float.class ? ValueType.FLOAT : null))); - if(this.type == null) - throw new IllegalArgumentException(value.name() + ": Unbekannter Variablen-Typ - " + field.getType()); - this.field = field; - this.def = this.get(); - this.noDef = value.nonDefault(); - this.min = (this.type == ValueType.INTEGER || this.type == ValueType.FLOAT) - ? value.min() : 0; - this.max = (this.type == ValueType.INTEGER || this.type == ValueType.FLOAT) - ? value.max() : (this.type == ValueType.BOOLEAN ? 1 : 0); - this.set(this.def, this.noDef, false); - } - - public String get() { - try { - return "" + this.field.get(null); - } - catch(IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - public void setCallback(Runnable callback) { - this.callback = callback; - } - - public void set(String value, boolean noClamp, boolean update) { - try { - switch(this.type) { - case STRING: - this.field.set(null, value); - break; - case BOOLEAN: - this.field.setBoolean(null, Boolean.parseBoolean(value)); - break; - case INTEGER: - int inum = 0; - try { - inum = Integer.parseInt(value); - } - catch(NumberFormatException e) { - } - this.field.setInt(null, noClamp ? inum : ExtMath.clampi(inum, (int)this.min, (int)this.max)); - break; - case FLOAT: - float fnum = 0.0f; - try { - fnum = Float.parseFloat(value); - } - catch(NumberFormatException e) { - } - if(!noClamp) - fnum = ExtMath.clampf(fnum, this.min, this.max); - int round = (int)(fnum * 1000.0f); - this.field.setFloat(null, (float)round / 1000.0f); - break; - } - } - catch(IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } - if(update && this.callback != null) - this.callback.run(); - } -} \ No newline at end of file diff --git a/server/src/main/java/server/vars/SVars.java b/server/src/main/java/server/vars/SVars.java deleted file mode 100644 index 7d5a0f2..0000000 --- a/server/src/main/java/server/vars/SVars.java +++ /dev/null @@ -1,101 +0,0 @@ -package server.vars; - -import common.util.Var; -import common.vars.Vars; - -public abstract class SVars extends Vars { - @Var(name = "tickSpawning") - public static boolean tickSpawn = true; - @Var(name = "genSpawning") - public static boolean genSpawn = true; - @Var(name = "spawnVillagers") - public static boolean spawnVillager = true; - @Var(name = "spawnCagedVillagers") - public static boolean spawnCageMobs = true; - @Var(name = "spawnBridgeMages") - public static boolean spawnBridgeMobs = true; - @Var(name = "spawnMineshaftArachnoids") - public static boolean spawnMineshaftMobs = true; - @Var(name = "spawnStrongholdHaunters") - public static boolean spawnStrongholdMobs = true; - @Var(name = "spawnHutMages") - public static boolean spawnHutMage = true; - @Var(name = "daylightCycle") - public static boolean dayCycle = true; - @Var(name = "weatherChanges") - public static boolean weather = true; - @Var(name = "dropPlayerSkulls") - public static boolean skullDrop = true; - @Var(name = "checkRespawn") - public static boolean checkBed = true; - @Var(name = "registration") - public static boolean register = true; - @Var(name = "pubkeyAuthentication") - public static boolean pubkeyAuth = true; - @Var(name = "requireAccessPassword") - public static boolean accessRequired = true; - @Var(name = "encryption") - public static boolean encrypt = true; - @Var(name = "requireAuthentication") - public static boolean authenticate = true; - - @Var(name = "snowStacking") - public static boolean snowStack = false; - @Var(name = "passwordAuthentication") - public static boolean passwordAuth = false; - - @Var(name = "randomTickSpeed") - public static int randomTick = 3; - @Var(name = "weatherTickSpeed") - public static int weatherTick = 1; - @Var(name = "lightningChance") - public static int boltChance = 100000; - @Var(name = "igniteChance") - public static int igniteChance = 100; - @Var(name = "spawnRadius") - public static int spawnRadius = 10; - @Var(name = "originRadius", min = 0, max = 262144) - public static int originRadius = 16384; - @Var(name = "respawnTime") - public static int respawnTime = 0; - @Var(name = "spawnGroupCount") - public static int spawnGroups = 3; - @Var(name = "spawnGroupDistance") - public static int spawnGroupDist = 6; - @Var(name = "mobSpawnRadius") - public static int mobSpawnDist = 8; - @Var(name = "mobPlayerDistance") - public static int mobPlayerDist = 24; - @Var(name = "saveInterval") - public static int saveInterval = 900; - @Var(name = "maxPlayers") - public static int playerLimit = 0; - @Var(name = "compressAbove") - public static int compression = 256; - @Var(name = "timeFlow") - public static int timeFlow = 1; - @Var(name = "emptyTicks") - public static int unloadTicks = 1200; - @Var(name = "weatherChance") - public static int weatherChance = 48000; - @Var(name = "viewDistance", min = 2, max = 16) - public static int distance = 8; - @Var(name = "maxSpawns") - public static int maxMobs = 120; - @Var(name = "connectionTimeout", min = 10, max = 300) - public static int timeout = 30; - @Var(name = "passwordMinLength", min = 8, max = 32) - public static int minPassLength = 8; - @Var(name = "port", min = 1024, max = 32767, nonDefault = true) - public static int port = -1; - @Var(name = "spawnDungeonMobs") - public static int spawnDungeonMobs = 4; - - @Var(name = "gravity") - public static float gravity = 1.0f; - - @Var(name = "password", nonDefault = true) - public static String password = ""; - @Var(name = "baseSeed", nonDefault = true) - public static String seed = ""; -} diff --git a/server/src/main/java/server/vars/ValueType.java b/server/src/main/java/server/vars/ValueType.java deleted file mode 100644 index 6ed7cc6..0000000 --- a/server/src/main/java/server/vars/ValueType.java +++ /dev/null @@ -1,5 +0,0 @@ -package server.vars; - -public enum ValueType { - STRING, BOOLEAN, INTEGER, FLOAT; -} \ No newline at end of file diff --git a/server/src/main/java/server/world/ChunkServer.java b/server/src/main/java/server/world/ChunkServer.java deleted file mode 100644 index f30ccc3..0000000 --- a/server/src/main/java/server/world/ChunkServer.java +++ /dev/null @@ -1,226 +0,0 @@ -package server.world; - -import java.util.Map; -import java.util.Set; -import common.biome.Biome; -import common.block.Block; -import common.entity.Entity; -import common.init.BlockRegistry; -import common.init.Blocks; -import common.log.Log; -import common.rng.Random; -import common.tileentity.TileEntity; -import common.util.BlockPos; -import common.world.BlockArray; -import common.world.Chunk; -import common.world.State; -import common.world.World; -import server.worldgen.BiomeGenerator; - -public class ChunkServer extends Chunk { - private long lastSave; - private long inhabited; - - public ChunkServer(World world, int x, int z) { - super(world, x, z); - } - - public ChunkServer(World world, short[] data, int height, boolean base, boolean ceil, Random rand, Biome[] biomes, int x, int z) { - this(world, x, z); - boolean sky = !world.dimension.hasNoLight(); - for(int bx = 0; bx < 16; ++bx) { - for(int bz = 0; bz < 16; ++bz) { - for(int by = 0; by < height; ++by) { - State state = BlockRegistry.STATEMAP.getByValue(data[bx << 4 | bz | by << 8]); - if(state != null && state.getBlock() != Blocks.air) { - int y = by >> 4; - BlockArray arr = this.getArray(y); - if(arr == null) { - arr = new BlockArray(y << 4, sky, null); - this.setArray(arr); - } - arr.set(bx, by & 15, bz, state); - } - } - } - } - if(base) { - Block caves = world.dimension.getCaveFiller().getBlock(); - BlockArray arr = this.getArray(0); - if(arr == null) { - arr = new BlockArray(0, sky, null); - this.setArray(arr); - } - for(int bx = 0; bx < 16; ++bx) { - for(int bz = 0; bz < 16; ++bz) { - for(int by = 0; by < 5; ++by) { - if(by <= rand.zrange(5)) { - Block block = arr.get(bx, by, bz).getBlock(); - if(block == Blocks.air || block.getMaterial().isLiquid() || block == caves) - arr.set(bx, by, bz, this.filler); - } - } - } - } - } - if(ceil) { - int y = (height - 1) >> 4; - BlockArray arr = this.getArray(y); - if(arr == null) { - arr = new BlockArray(y << 4, sky, null); - this.setArray(arr); - } - y = (height - 5) >> 4; - arr = this.getArray(y); - if(arr == null) { - arr = new BlockArray(y << 4, sky, null); - this.setArray(arr); - } - for(int bx = 0; bx < 16; ++bx) { - for(int bz = 0; bz < 16; ++bz) { - for(int by = height - 1; by >= height - 5; --by) { - if(by >= (height - 1) - rand.zrange(5)) - this.getArray(by >> 4).set(bx, by & 15, bz, Blocks.air.getState()); - } - } - } - } - for(int n = 0; n < this.biomes.length; ++n) { - this.biomes[n] = (byte)biomes[n].id; - } - if(ceil) - this.resetRelight(); - else - this.genSkyLight(); - } - - public int getTopSegment() { - return this.top; - } - - public int getBottomSegment() { - return this.bottom; - } - - public Set getStorage() { - return this.blockList; - } - - public void addTileEntity(TileEntity tile) { - this.addTileEntity(tile.getPos(), tile); - - if(this.loaded) { - this.world.addTileEntity(tile); - } - } - - public void onChunkLoad() { - this.loaded = true; - this.world.addTileEntities(this.tiles.values()); - - for(int n = 0; n < this.entities.length; ++n) { - for(Entity entity : this.entities[n]) { - entity.onChunkLoad(); - } - - this.world.loadEntities(this.entities[n]); - } - } - - public boolean isDirty(long time) { - if(this.hasEntity && time != this.lastSave || this.modified) { - return true; - } - return this.modified; - } - - public void setStorage(BlockArray[] data) { - for(BlockArray arr : data) { - this.setArray(arr); - } - } - - public Biome getBiome(BlockPos pos, BiomeGenerator gen) { - int x = pos.getX() & 15; - int z = pos.getZ() & 15; - int o = this.biomes[z << 4 | x] & 255; - - if(o == 255) { - Biome biome = gen == null ? Biome.DEF_BIOME : gen.getBiomeGenerator(pos, Biome.DEF_BIOME); - o = biome.id; - this.biomes[z << 4 | x] = (byte)(o & 255); - } - - return Biome.getBiomeDef(o); - } - - public byte[] getBiomes() { - return this.biomes; - } - - public void setBiomes(byte[] biomes) { - if(this.biomes.length != biomes.length) { - Log.IO.warn("Konnte Biome des Chunks nicht setzen, Länge des Arrays ist " + biomes.length + " statt " + this.biomes.length); - } - else { - for(int n = 0; n < this.biomes.length; ++n) { - this.biomes[n] = biomes[n]; - } - } - } - - public int[] getHeights() { - return this.height; - } - - public void setHeights(int[] map) { - if(this.height.length != map.length) { - Log.IO.warn("Konnte Höhen des Chunks nicht setzen, Länge des Arrays ist " + map.length + " statt " + this.height.length); - } - else { - for(int n = 0; n < this.height.length; ++n) { - this.height[n] = map[n]; - } - } - } - - public Map getTiles() { - return this.tiles; - } - - public boolean isTerrainPopulated() { - return this.populated; - } - - public void setTerrainPopulated(boolean populated) { - this.populated = populated; - } - - public boolean isLightPopulated() { - return this.lightInit; - } - - public void setLightPopulated(boolean populated) { - this.lightInit = populated; - } - - public void setModified(boolean modified) { - this.modified = modified; - } - - public void setHasEntities(boolean entities) { - this.hasEntity = entities; - } - - public void setSaved(long time) { - this.lastSave = time; - } - - public long getInhabited() { - return this.inhabited; - } - - public void setInhabited(long time) { - this.inhabited = time; - } -} diff --git a/server/src/main/java/server/world/TickEvent.java b/server/src/main/java/server/world/TickEvent.java deleted file mode 100755 index 7759f94..0000000 --- a/server/src/main/java/server/world/TickEvent.java +++ /dev/null @@ -1,13 +0,0 @@ -package server.world; - -import common.block.Block; -import common.util.BlockPos; - -public record TickEvent(BlockPos position, Block block, int id, int parameter) { - public boolean equals(Object other) { - if(!(other instanceof TickEvent)) - return false; - TickEvent event = (TickEvent)other; - return this.position.equals(event.position) && this.id == event.id && this.parameter == event.parameter && this.block == event.block; - } -} diff --git a/server/src/main/java/server/Server.java b/server/src/server/Server.java similarity index 60% rename from server/src/main/java/server/Server.java rename to server/src/server/Server.java index 2145dda..b05cff8 100755 --- a/server/src/main/java/server/Server.java +++ b/server/src/server/Server.java @@ -5,8 +5,6 @@ import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; import java.net.InetAddress; import java.security.KeyPair; import java.security.PrivateKey; @@ -14,20 +12,18 @@ import java.security.PublicKey; import java.text.SimpleDateFormat; import java.util.ArrayDeque; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Queue; +import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; -import common.Version; import common.collect.Lists; import common.collect.Maps; import common.color.TextColor; @@ -40,23 +36,15 @@ import common.future.Futures; import common.future.ListenableFuture; import common.future.ListenableFutureTask; import common.future.ThreadFactoryBuilder; +import common.init.Config; import common.init.EntityRegistry; import common.init.Registry; import common.init.UniverseRegistry; +import common.init.Config.ValueType; import common.log.Log; -import common.net.bootstrap.ServerBootstrap; -import common.net.channel.Channel; -import common.net.channel.ChannelException; -import common.net.channel.ChannelFuture; -import common.net.channel.ChannelFutureListener; -import common.net.channel.ChannelHandler; -import common.net.channel.ChannelInitializer; -import common.net.channel.ChannelOption; -import common.net.channel.nio.NioEventLoopGroup; -import common.net.channel.socket.nio.NioServerSocketChannel; -import common.net.handler.timeout.ReadTimeoutHandler; -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; +import common.nbt.NBTLoader; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.network.IPlayer; import common.network.IThreadListener; import common.network.NetConnection; @@ -68,10 +56,10 @@ import common.network.PacketSplitter; import common.network.NetHandler.ThreadQuickExitException; import common.packet.RPacketEnableCompression; import common.packet.RPacketLoginSuccess; -import common.packet.SPacketEntityEffect; -import common.packet.SPacketChangeGameState; -import common.packet.SPacketPlayerListItem; -import common.packet.SPacketPlayerAbilities; +import common.packet.S1DPacketEntityEffect; +import common.packet.S2BPacketChangeGameState; +import common.packet.S38PacketPlayerListItem; +import common.packet.S39PacketPlayerAbilities; import common.packet.SPacketDisconnect; import common.packet.SPacketHeldItemChange; import common.packet.SPacketJoinGame; @@ -81,45 +69,51 @@ import common.packet.SPacketSkin; import common.packet.SPacketTimeUpdate; import common.packet.SPacketWorld; import common.potion.PotionEffect; -import common.tags.TagObject; import common.util.BlockPos; import common.util.EncryptUtil; import common.util.ExtMath; -import common.util.LazyLoader; +import common.util.LazyLoadBase; import common.util.PortalType; import common.util.Position; import common.util.Util; -import common.util.Var; import common.util.WorldPos; -import common.vars.Vars; import common.world.World; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelException; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.timeout.ReadTimeoutHandler; +import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.GenericFutureListener; import server.biome.GenBiome; import server.clipboard.ReorderRegistry; import server.clipboard.RotationRegistry; import server.command.CommandEnvironment; import server.command.Executor; +import server.command.FixedExecutor; import server.network.HandshakeHandler; import server.network.Player; -import server.network.User; -import server.vars.SVar; -import server.vars.SVars; import server.world.Converter; import server.world.Region; import server.world.WorldServer; -public final class Server implements IThreadListener, Executor { - private static final LazyLoader SERVER_NIO_EVENTLOOP = new LazyLoader() { +public final class Server implements IThreadListener { + private static final LazyLoadBase SERVER_NIO_EVENTLOOP = new LazyLoadBase() { protected NioEventLoopGroup load() { return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Server IO #%d").setDaemon(true).build()); } }; private final Thread serverThread = Thread.currentThread(); - private final Map variables = Maps.newTreeMap(); private final List clients = Collections.synchronizedList(Lists.newArrayList()); private final List players = Lists.newArrayList(); - private final Map online = Maps.newHashMap(); - private final Map users = Maps.newTreeMap(); + private final Map usermap = Maps.newHashMap(); private final Queue> queue = new ArrayDeque>(); private final long[] tickTimes = new long[100]; private final Map dimensions = Maps.newTreeMap(); @@ -128,11 +122,11 @@ public final class Server implements IThreadListener, Executor { private final List unload = Lists.newArrayList(); private final Map warps = Maps.newTreeMap(); private final CommandEnvironment scriptEnv = new CommandEnvironment(this); + private final KeyPair keyPair; + private final boolean debug; - private KeyPair keyPair; private WorldServer space; private ChannelFuture endpoint; - private Position execPos; private boolean running = true; private boolean stopped; @@ -157,54 +151,41 @@ public final class Server implements IThreadListener, Executor { public static void main(String[] args) { long time = System.currentTimeMillis(); - Util.checkPlatform(); - Thread.currentThread().setName("Server thread"); - Locale.setDefault(Locale.ROOT); - Util.setupHandlers(); - Log.init(); - Log.SYSTEM.info("Java " + System.getProperty("java.version")); - Log.SYSTEM.info("Starte " + Version.NAME + " Server " + Util.VERSION + " (Protokoll #" + Util.PROTOCOL + ")"); - if(Util.DEVMODE) - Log.SYSTEM.warn("Entwicklungsmodus aktiv - Debugging-Features sind verfügbar"); - Registry.register(); + Util.checkOs(); + Registry.setup("Server thread"); + Log.JNI.info("Starte " + Config.NAME + " Server Version " + Config.VERSION); GenBiome.setAsProvider(); UniverseRegistry.register(); RotationRegistry.register(); ReorderRegistry.register(); - final Server server = new Server(); - Util.addShutdownHook(new Runnable() { + boolean debug = System.getProperty("server.debug", null) != null; + int port = Integer.parseInt(System.getProperty("server.port", "" + Config.PORT)); + final Server server = new Server(debug); + Registry.addShutdownHook(new Runnable() { public void run() { server.stopServer(); - Log.flushLog(); } }); - Log.setSync(server); - server.run(time); + server.run(time, port); Region.killIO(); Log.flushLog(); } - private void saveServerConfig(long time) { - TagObject data = new TagObject(); + public static void saveServerConfig(long time) { + NBTTagCompound data = new NBTTagCompound(); data.setLong("Time", time); data.setLong("LastAccess", System.currentTimeMillis()); - data.setString("Version", Util.VERSION); - TagObject cfg = new TagObject(); - for(String cvar : this.variables.keySet()) { - SVar value = this.variables.get(cvar); - if(!value.noDef || !value.def.equals(value.get())) - cfg.setString(cvar, value.get()); + data.setString("Version", Config.VERSION); + NBTTagCompound cfg = new NBTTagCompound(); + for(String cvar : Config.VARS.keySet()) { + cfg.setString(cvar, Config.VARS.get(cvar).getValue()); } - data.setObject("Config", cfg); - data.setObject("Universe", UniverseRegistry.toTags()); - if(this.keyPair != null) { - data.setByteArray("PrivateKey", this.keyPair.getPrivate().getEncoded()); - data.setByteArray("PublicKey", this.keyPair.getPublic().getEncoded()); - } - File nfile = new File("server.cdt.tmp"); - File lfile = new File("server.cdt"); + data.setTag("Config", cfg); + data.setTag("Universe", UniverseRegistry.saveNbt()); + File nfile = new File("server.nbt.tmp"); + File lfile = new File("server.nbt"); try { - TagObject.writeGZip(data, nfile); + NBTLoader.writeGZip(data, nfile); if(lfile.exists()) lfile.delete(); nfile.renameTo(lfile); @@ -214,174 +195,140 @@ public final class Server implements IThreadListener, Executor { } } - private long loadServerConfig() { - File file = new File("server.cdt"); + public static long loadServerConfig() { + Config.clear(); + UniverseRegistry.clear(); + File file = new File("server.nbt"); if(!file.exists()) - file = new File("server.cdt.tmp"); + file = new File("server.nbt.tmp"); if(file.exists()) { try { - TagObject tag = TagObject.readGZip(file); - TagObject cfg = tag.getObject("Config"); - for(String key : cfg.keySet()) { - SVar svar = this.variables.get(key); - if(svar != null) - svar.set(cfg.getString(key), false, false); + NBTTagCompound tag = NBTLoader.readGZip(file); + NBTTagCompound cfg = tag.getCompoundTag("Config"); + for(String key : cfg.getKeySet()) { + Config.set(key, cfg.getString(key), false); } - UniverseRegistry.fromTags(tag.getObject("Universe")); + UniverseRegistry.loadNbt(tag.getCompoundTag("Universe")); long lastPlayed = tag.getLong("LastAccess"); - String version = tag.hasString("Version") ? tag.getString("Version") : null; + String version = tag.hasKey("Version", 8) ? tag.getString("Version") : null; version = version != null && version.isEmpty() ? "" : version; - long time = tag.hasLong("Time") ? tag.getLong("Time") : World.START_TIME; - Log.IO.info("Config-Version: %s", version); + long time = tag.hasKey("Time", 4) ? tag.getLong("Time") : World.START_TIME; + Log.IO.info("Version: %s", version); Log.IO.info("Weltzeit: %d Ticks / %d Sekunden", time, time / 20L); Log.IO.info("Zuletzt geladen: %s", new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(new Date(lastPlayed))); - if(System.getProperty("server.regenkey") == null && tag.hasByteArray("PrivateKey") && tag.hasByteArray("PublicKey")) { - PrivateKey key = EncryptUtil.decodePrivateKey(tag.getByteArray("PrivateKey")); - PublicKey pubkey = EncryptUtil.decodePublicKey(tag.getByteArray("PublicKey")); - if(key != null && pubkey != null) - this.keyPair = new KeyPair(pubkey, key); - } return time; } catch(Exception e) { Log.IO.error(e, "Fehler beim Lesen von " + file); - for(SVar svar : this.variables.values()) { - svar.set(svar.def, svar.noDef, false); - } + Config.clear(); UniverseRegistry.clear(); } } Log.IO.info("Erstelle neue Welt und Konfiguration"); return World.START_TIME; } - - private void setCallback(Runnable callback, String ... vars) { - for(String key : vars) { - this.variables.get(key).setCallback(callback); - } - } - - public Map getVariables() { - return this.variables; - } - private Server() { - for(Class clazz : new Class[] {Vars.class, SVars.class}) { - for(Field field : clazz.getDeclaredFields()) { - if(field.isAnnotationPresent(Var.class)) { - if(!Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) - throw new IllegalArgumentException("Feld für Variable " + field + " muss statisch und änderbar sein!"); - Var value = field.getAnnotation(Var.class); - if(value.name().isEmpty()) - throw new IllegalArgumentException("Variablenname von " + field + " kann nicht leer sein!"); - if(this.variables.containsKey(value.name())) - throw new IllegalArgumentException("Variable " + value.name() + " existiert bereits!"); - this.variables.put(value.name(), new SVar(field, value)); - } - } - } - this.setCallback(new Runnable() { + private Server(boolean debug) { + this.debug = debug; + Config.setCallback(new Runnable() { public void run() { for(WorldServer world : Server.this.getWorlds()) { world.updatePhysics(); } - Server.this.sendPacket(new SPacketWorld(WorldServer.clampGravity(), SVars.dayCycle, SVars.timeFlow)); + Server.this.sendPacket(new SPacketWorld(WorldServer.clampGravity(), Config.dayCycle, Config.timeFlow)); } }, "daylightCycle", "timeFlow", "gravity"); - this.setCallback(new Runnable() { + Config.setCallback(new Runnable() { public void run() { for(WorldServer world : Server.this.getWorlds()) { world.updateViewRadius(); } } }, "viewDistance"); - this.setCallback(new Runnable() { - public void run() { - Server.this.bind(SVars.port); - } - }, "port"); - this.setCallback(new Runnable() { - public void run() { - if((!SVars.password.isEmpty() && SVars.password.length() < 8) || SVars.password.length() > IPlayer.MAX_PASS_LENGTH) - Log.IO.warn("Passwort muss aus 8-" + IPlayer.MAX_PASS_LENGTH + " Zeichen bestehen, Login wird nicht möglich sein"); - } - }, "password"); + this.keyPair = EncryptUtil.generateKeyPair(); } public CommandEnvironment getScriptEnvironment() { return this.scriptEnv; } - public List getPlayerFilenames() { - String[] list = new File("players").list(); - if(list == null) - return Lists.newArrayList(); - List names = Lists.newArrayList(); + public String[] getUsers() { + String[] list = this.debug ? null : new File("players").list(); + if(list == null) { + list = new String[0]; + } for(int i = 0; i < list.length; ++i) { - if(list[i].endsWith(".cdt")) { - String name = list[i].substring(0, list[i].length() - 4); - if(IPlayer.isValidUser(name)) - names.add(name); + if(list[i].endsWith(".nbt")) { + list[i] = list[i].substring(0, list[i].length() - 4); +// Player player = this.getPlayer(list[i]); +// if(player != null) +// list[i] = player.getUser(); } } - return names; + return list; } public void saveWorldInfo() { - this.saveServerConfig(this.space.getDayTime()); - WorldServer.saveWarps(this.warps); + if(!this.debug) { + saveServerConfig(this.space.getDayTime()); + WorldServer.saveWarps(this.warps); + } } - public TagObject loadPlayerData(String user) { - if(!IPlayer.isValidUser(user)) + public NBTTagCompound loadPlayerData(String user) { + if(this.debug || !IPlayer.isValidUser(user)) return null; - TagObject tag = null; + NBTTagCompound tag = null; try { - File dat = new File(new File("players"), user + ".cdt"); + File dat = new File(new File("players"), user + ".nbt"); if(dat.exists() && dat.isFile()) { - tag = TagObject.readGZip(dat); + tag = NBTLoader.readGZip(dat); } } catch(Exception e) { - Log.IO.error(e, "Konnte Spielerdaten für " + user + " (offline) nicht laden"); + Log.JNI.error(e, "Konnte Spielerdaten für " + user + " (offline) nicht laden"); } return tag; } - public void writePlayerData(String user, TagObject tag) { - if(!IPlayer.isValidUser(user)) + public void writePlayerData(String user, NBTTagCompound tag) { + if(this.debug || !IPlayer.isValidUser(user)) return; try { - File tmp = new File(new File("players"), user + ".cdt.tmp"); - File dat = new File(new File("players"), user + ".cdt"); - TagObject.writeGZip(tag, tmp); + File tmp = new File(new File("players"), user + ".nbt.tmp"); + File dat = new File(new File("players"), user + ".nbt"); + NBTLoader.writeGZip(tag, tmp); if(dat.exists()) { dat.delete(); } tmp.renameTo(dat); } catch(Exception e) { - Log.IO.error(e, "Konnte Spielerdaten für " + user + " (offline) nicht speichern"); + Log.JNI.error(e, "Konnte Spielerdaten für " + user + " (offline) nicht speichern"); } } public Position getOfflinePosition(String user) { - TagObject tag = this.loadPlayerData(user); + NBTTagCompound tag = this.loadPlayerData(user); if(tag == null) return null; - double posX = tag.getDouble("PosX"); - double posY = tag.getDouble("PosY"); - double posZ = tag.getDouble("PosZ"); - float rotYaw = tag.getFloat("Yaw"); - float rotPitch = tag.getFloat("Pitch"); - int dimension = tag.getInt("Dimension"); + NBTTagList pos = tag.getTagList("Pos", 6); + NBTTagList rot = tag.getTagList("Rotation", 5); + double posX = pos.getDoubleAt(0); + double posY = pos.getDoubleAt(1); + double posZ = pos.getDoubleAt(2); + float rotYaw = rot.getFloatAt(0); + float rotPitch = rot.getFloatAt(1); + int dimension = tag.getInteger("Dimension"); return new Position(posX, posY, posZ, rotYaw, rotPitch, dimension); } public void saveAllWorlds(boolean message) { + if(this.debug) + return; if(message) - Log.TICK.info("Speichere Welt"); + Log.JNI.info("Speichere Welt"); this.saveWorldInfo(); for(WorldServer world : this.worlds) { world.saveAllChunks(); @@ -403,30 +350,147 @@ public final class Server implements IThreadListener, Executor { } } - public void run(long time) { - Converter.convert(this); - long wtime = this.loadServerConfig(); - if(this.keyPair == null) { - Log.SYSTEM.info("Generiere neues Schlüsselpaar"); - this.keyPair = EncryptUtil.createKeypair(); - } - User.loadDatabase(this.users); - this.worlds.add(this.space = new WorldServer(this, wtime, Space.INSTANCE)); - this.dimensions.put(this.space.dimension.getDimensionId(), this.space); - new File("players").mkdirs(); - this.setTpsTarget(20.0f); - for(Dimension dim : UniverseRegistry.getDimensions()) { - if(WorldServer.needsLoading(dim)) { - this.getWorld(dim.getDimensionId()).loadForcedChunks(); + public boolean setVar(Executor exec, String line) { + if(line.length() < 1) { + for(Entry entry : Config.VARS.entrySet()) { + Config.Value cvar = entry.getValue(); + String v = cvar.getValue(); + String comp = TextColor.YELLOW + entry.getKey() + TextColor.GRAY + " = "; + if(entry.getKey().equals("password") && !v.isEmpty()) + comp += TextColor.NEON + "'****'"; + else if(cvar.type == ValueType.STRING) + comp += TextColor.NEON + "'" + v + "'"; + else + comp += ((cvar.type == ValueType.BOOLEAN ? (v.equals("true") ? TextColor.GREEN : TextColor.RED) : TextColor.BLUE)) + v; + if(!cvar.def.equals(v)) { + comp += TextColor.GRAY + " (" + TextColor.BROWN + cvar.def + TextColor.GRAY + ")"; + } + exec.logConsole(comp); } - WorldServer.loadWarps(dim, this.warps); + exec.logConsole(TextColor.GREEN + "SVARs insgesamt registriert: %d", Config.VARS.size()); + return true; } - if(SVars.port >= 0) - this.bind(SVars.port); - else - Log.SYSTEM.warn("Kein Port definiert, verwende 'sv port <1024-32767>' um einen Hosting-Port festzulegen"); - if(SVars.accessRequired && SVars.password.length() < 8) - Log.SYSTEM.warn("Kein Passwort definiert, verwende 'sv password <8-" + IPlayer.MAX_PASS_LENGTH + " Zeichen>' um ein Zugangspasswort festzulegen"); + line = line.trim(); + String[] args = /* line.isEmpty() ? new String[0] : */ line.split(" ", -1); + if(args.length == 1) { +// case 0: +// break; +// case 1: + Config.Value cfg = Config.VARS.get(args[0]); + if(cfg == null) + return false; + String v = cfg.getValue(); + String comp = TextColor.YELLOW + args[0] + TextColor.GRAY + " = "; + if(cfg.type == ValueType.STRING) + comp += TextColor.NEON + "'" + v + "'"; + else + comp += ((cfg.type == ValueType.BOOLEAN ? (v.equals("true") ? TextColor.GREEN : TextColor.RED) : TextColor.BLUE)) + v; + if(!cfg.def.equals(v)) + comp += TextColor.GRAY + " (" + TextColor.BROWN + cfg.def + TextColor.GRAY + ")"; + exec.logConsole(comp); +// break; +// default: + } + else { + Config.Value cv = Config.VARS.get(args[0]); + if(cv == null) + return false; + String value = args[1]; + if(cv.type == ValueType.STRING && "\"\"".equals(value)) { + value = ""; + } +// else if(cv.type == ValueType.BOOLEAN && "toggle".equalsIgnoreCase(value)) { +// value = "" + !Boolean.parseBoolean(cv.getValue()); +// } +// else + if(cv.type == ValueType.BOOLEAN && !"true".equals(value) && !"false".equals(value)) { + if(!value.equalsIgnoreCase("true") && !value.equalsIgnoreCase("false")) { + exec.logConsole(TextColor.DRED + "'%s' ist nicht 'true' oder 'false'", value); + return true; + } + value = value.toLowerCase(); + } + if(cv.type == ValueType.INTEGER) { + try { + Integer.parseInt(value); + } + catch(NumberFormatException e) { + exec.logConsole(TextColor.DRED + "'%s' ist keine gültige Zahl", value); + return true; + } + } + else if(cv.type == ValueType.FLOAT) { + try { + Float.parseFloat(value); + } + catch(NumberFormatException e) { + exec.logConsole(TextColor.DRED + "'%s' ist keine gültige Zahl", value); + return true; + } + } + Config.set(args[0], value, true); + exec.logConsole(TextColor.YELLOW + "%s" + TextColor.GRAY + " -> " + ((cv.type == ValueType.BOOLEAN ? (cv.getValue().equals("true") ? TextColor.GREEN : TextColor.RED) : (cv.type == ValueType.STRING ? TextColor.NEON : TextColor.BLUE))) + "%s", args[0], cv.type == ValueType.STRING ? ("'" + cv.getValue() + "'") : cv.getValue()); + } + return true; + } + + public void run(long time, int port) { + if(!this.debug) { + Converter.convert(); + long wtime = loadServerConfig(); +// if(dtime == -1L) // { +// dtime = World.START_TIME; +//// Config.set("spawnDim", "1", null); +//// } + this.worlds.add(this.space = new WorldServer(this, wtime, + Space.INSTANCE, false)); + this.dimensions.put(this.space.dimension.getDimensionId(), this.space); + new File("players").mkdirs(); +// if(Config.spawnY < 0) { +// WorldServer world = this.getWorld(Config.spawnDim); +// world = world == null ? this.space : world; +// Random rand = new Random(world.getSeed()); +// int x = 0; +// int z = 0; +// int count = 0; +// while(!(world.getGroundAboveSeaLevel(new BlockPos(x, 0, z)) == Blocks.grass)) { +// if(count == 1000) { +// SKC.warn("Konnte keine Spawn-Position finden"); +// break; +// } +// x += rand.zrange(64) - rand.zrange(64); +// z += rand.zrange(64) - rand.zrange(64); +// ++count; +// } +// Config.set("spawnX", "" + x, null); +// Config.set("spawnY", "" + world.getSeaLevel(), null); +// Config.set("spawnZ", "" + z, null); +// Config.set("spawnYaw", "" + (-180.0f + rand.floatv() * 360.0f), null); +// Config.set("spawnPitch", "0.0", null); +// } + } + else { + Config.clear(); + UniverseRegistry.clear(); + Config.set("daylightCycle", "false", false); + Config.set("weatherChanges", "false", false); + Config.set("mobSpawning", "false", false); + Config.set("spawnRadius", "0", false); + this.worlds.add(this.space = new WorldServer(this, World.START_TIME, + Space.INSTANCE, true)); + this.dimensions.put(this.space.dimension.getDimensionId(), this.space); + } + this.setTpsTarget(20.0f); + if(!this.debug) { + for(Dimension dim : UniverseRegistry.getDimensions()) { + if(WorldServer.needsLoading(dim)) { + this.getWorld(dim.getDimensionId()).loadForcedChunks(); + } + WorldServer.loadWarps(dim, this.warps); + } + } + if(port >= 0) + this.bind(port); Thread con = new Thread(new Runnable() { private final BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(System.in))); @@ -444,7 +508,9 @@ public final class Server implements IThreadListener, Executor { final String cmd = line; Server.this.schedule(new Runnable() { public void run() { - Server.this.scriptEnv.execute(cmd, Server.this); + FixedExecutor exec = new FixedExecutor(Server.this, "#con", "KONSOLE", null); + if(!Server.this.setVar(exec, cmd)) + Server.this.scriptEnv.execute(cmd, exec); } }); } @@ -452,18 +518,18 @@ public final class Server implements IThreadListener, Executor { }, "Server console handler"); con.setDaemon(true); con.start(); - Log.SYSTEM.info("Server gestartet in " + String.format("%.1f", (double)(System.currentTimeMillis() - time) / 1000.0) + " Sekunden"); + Log.JNI.info("Server gestartet in " + String.format("%.1f", (double)(System.currentTimeMillis() - time) / 1000.0) + " Sekunden"); while(this.running) { this.currentTime = System.nanoTime() / 1000L; this.timePassed = this.currentTime - this.lastSchedule; this.lastSchedule = this.currentTime; if(this.timePassed < 0L) { - Log.TICK.warn("Zeit lief rückwärts! Hat sich die Systemzeit geändert?"); + Log.JNI.warn("Zeit lief rückwärts! Hat sich die Systemzeit geändert?"); this.timePassed = 0L; this.ticksTodo = 0L; } if(this.timePassed > 2000000L && this.currentTime - this.lastWarning >= 15000000L) { - Log.TICK.warn("Kann Server-Tick nicht aufrecht erhalten! Hat sich die Systemzeit geändert, oder ist der Server überlastet? " + + Log.JNI.warn("Kann Server-Tick nicht aufrecht erhalten! Hat sich die Systemzeit geändert, oder ist der Server überlastet? " + "Liege " + (this.timePassed / 1000L) + " ms zurück, überspringe " + ((this.timePassed * this.tpsTarget) / 1000000000L) + " Tick(s)"); this.timePassed = 0L; this.lastWarning = this.currentTime; @@ -487,27 +553,29 @@ public final class Server implements IThreadListener, Executor { this.stopped = true; } catch(Throwable e) { - Log.SYSTEM.error(e, "Fehler beim Beenden des Servers"); + Log.JNI.error(e, "Fehler beim Beenden des Servers"); } finally { this.stopped = true; - Log.SYSTEM.info("Server wurde beendet"); + Log.JNI.info("Server wurde beendet"); } } public void preload(WorldServer world, int bx, int bz) { int done = 0; - int total = SVars.distance * 2 + 1; + int total = Config.distance * 2 + 1; total *= total; - Log.TICK.info("Generiere und lade Welt"); + Log.JNI.info("Generiere und lade Welt"); +// WorldServer world = this.getWorld(Config.spawnDim); +// world = world == null ? this.space : world; bx = bx >> 4; bz = bz >> 4; long last = System.currentTimeMillis(); - for(int x = -SVars.distance; x <= SVars.distance; x++) { - for(int z = -SVars.distance; z <= SVars.distance; z++) { + for(int x = -Config.distance; x <= Config.distance; x++) { + for(int z = -Config.distance; z <= Config.distance; z++) { long time = System.currentTimeMillis(); if(time - last > 1000L) { - Log.TICK.info("Bereite Spawnbereich vor" + ": " + (done * 100 / total) + "%"); + Log.JNI.info("Bereite Spawnbereich vor" + ": " + (done * 100 / total) + "%"); last = time; } ++done; @@ -515,8 +583,43 @@ public final class Server implements IThreadListener, Executor { } } } + +// public void resetProgress() { +// this.setProgress(-1); +// } +// +// public void setDone() { +// this.setProgress(-2); +// } private void tick() { +// boolean pause = this.paused; +// this.paused = this.pause; +// if(!pause && this.paused) { +// if(!this.debug) +// Log.info("Speichere und pausiere Spiel..."); +// this.saveAllPlayerData(true); +// this.saveAllWorlds(true); +// } +// if(this.paused) { +// synchronized(this.queue) { +// while(!this.queue.isEmpty()) { +// FutureTask task = this.queue.poll(); +// try { +// task.run(); +// task.get(); +// } +// catch(ExecutionException e1) { +// if(!(e1.getCause() instanceof ThreadQuickExitException)) +// Log.error("Fehler beim Ausführen von Pause-Task " + task, e1); +// } +// catch(InterruptedException e2) { +// Log.error("Fehler beim Ausführen von Pause-Task " + task, e2); +// } +// } +// } +// return; +// } long now = System.currentTimeMillis(); synchronized(this.queue) { while(!this.queue.isEmpty()) { @@ -527,10 +630,10 @@ public final class Server implements IThreadListener, Executor { } catch(ExecutionException e1) { if(!(e1.getCause() instanceof ThreadQuickExitException)) - Log.SYSTEM.error(e1, "Fehler beim Ausführen von Server-Task " + task); // throw new RuntimeException(e1); + Log.JNI.error(e1, "Fehler beim Ausführen von Server-Task " + task); // throw new RuntimeException(e1); } catch(InterruptedException e2) { - Log.SYSTEM.error(e2, "Fehler beim Ausführen von Server-Task " + task); + Log.JNI.error(e2, "Fehler beim Ausführen von Server-Task " + task); } } } @@ -552,15 +655,14 @@ public final class Server implements IThreadListener, Executor { } this.networkTick(); if(++this.pingTimer > 600) { - this.sendPacket(new SPacketPlayerListItem((List)this.getPlayers())); + this.sendPacket(new S38PacketPlayerListItem((List)this.getPlayers())); this.pingTimer = 0; } - if(SVars.saveInterval > 0 && ++this.saveTimer >= SVars.saveInterval) { + if(Config.saveInterval > 0 && ++this.saveTimer >= Config.saveInterval) { this.saveAllPlayerData(false); this.saveAllWorlds(false); this.saveTimer = 0; } - Log.flushLog(); this.tickTimes[this.perfTimer++] = System.currentTimeMillis() - now; if(this.perfTimer == 100) { this.perfTimer = 0; @@ -577,7 +679,8 @@ public final class Server implements IThreadListener, Executor { Dimension dim = UniverseRegistry.getDimension(dimension); if(dim == null) return null; - world = new WorldServer(this, this.space.getDayTime(), dim); + world = new WorldServer(this, this.space.getDayTime(), + dim, this.debug); this.worlds.add(world); this.dimensions.put(dimension, world); } @@ -631,7 +734,7 @@ public final class Server implements IThreadListener, Executor { this.timePassed = this.ticksTodo = this.ticksDone = 0L; } - public List getAllPlayerNames() { + public List getAllUsernames() { List list = new ArrayList(this.players.size()); for(int z = 0; z < this.players.size(); z++) { list.add(this.players.get(z).getUser()); @@ -639,24 +742,12 @@ public final class Server implements IThreadListener, Executor { return list; } - public List getAllUserNames() { - return Lists.newArrayList(this.users.keySet()); - } - public List getPlayers() { return this.players; } - public Collection getUsers() { - return this.users.values(); - } - public Player getPlayer(String user) { - return this.online.get(user); - } - - public User getUser(String user) { - return this.users.get(user); + return this.usermap.get(user); } private ListenableFuture callFromMainThread(Callable callable) { @@ -672,7 +763,6 @@ public final class Server implements IThreadListener, Executor { return Futures.immediateFuture(callable.call()); } catch(Exception exception) { - Log.SYSTEM.error(exception, "Fehler beim sofortigen Ausführen von Server-Task " + callable); return Futures.immediateFailedFuture(exception); } } @@ -686,11 +776,27 @@ public final class Server implements IThreadListener, Executor { return Thread.currentThread() == this.serverThread; } +// private void movePlayerToSpawn(EntityNPC player) { +// BlockPos pos = new BlockPos(Config.spawnX, Config.spawnY, Config.spawnZ); +// int radius = Config.spawnRadius; +// if(radius > 0) { +// pos = ((WorldServer)player.worldObj).getTopSolidOrLiquidBlock(pos.add( +// ExtMath.clampi(player.worldObj.rand.excl(-radius, radius), -World.MAX_SIZE + 1, World.MAX_SIZE - 1), 0, +// ExtMath.clampi(player.worldObj.rand.excl(-radius, radius), -World.MAX_SIZE + 1, World.MAX_SIZE - 1))); +// } +// player.moveToBlockPosAndAngles(pos, radius > 0 ? (-180.0f + player.worldObj.rand.floatv() * 360.0f) : Config.spawnYaw, +// radius > 0 ? 0.0f : Config.spawnPitch); +// while(radius >= 0 && !player.worldObj.getCollidingBoundingBoxes(player, player.getEntityBoundingBox()).isEmpty() +// && player.posY < 511.0D) { +// player.setPosition(player.posX, player.posY + 1.0D, player.posZ); +// } +// } + public Position getRandomSpawnPosition(WorldPos origin) { WorldServer world = this.getWorld(origin.getDimension()); world = world == null ? this.space : world; BlockPos pos = origin; - int radius = SVars.spawnRadius; + int radius = Config.spawnRadius; if(radius > 0) { pos = world.getTopSolidOrLiquidBlock(pos.add( ExtMath.clampi(world.rand.excl(-radius, radius), -World.MAX_SIZE + 1, World.MAX_SIZE - 1), 0, @@ -699,71 +805,86 @@ public final class Server implements IThreadListener, Executor { int y = pos.getY(); while(world.getState(new BlockPos(pos.getX(), y, pos.getZ())).getBlock().getMaterial().blocksMovement() && y < 511) y++; - return new Position(pos.getX() + 0.5, (double)y, pos.getZ() + 0.5, -180.0f + world.rand.floatv() * 360.0f, 0.0f, world.dimension.getDimensionId()); - } - - public void addUser(User user) { - this.users.put(user.getUser(), user); + return new Position(pos.getX() + 0.5d, (double)y, pos.getZ() + 0.5d, + radius > 0 ? (-180.0f + world.rand.floatv() * 360.0f) : Config.spawnYaw, + radius > 0 ? 0.0f : Config.spawnPitch, world.dimension.getDimensionId()); } - public void addPlayer(NetConnection connection, String loginUser) { - TagObject tag = this.readPlayer(loginUser); + public String addPlayer(NetConnection connection, String loginUser, String loginPass) { + NBTTagCompound tag = this.readPlayer(loginUser); Player conn = new Player(this, connection, loginUser); if(tag != null) - conn.readTags(tag); - if(SVars.compression >= 0) { - connection.sendPacket(new RPacketEnableCompression(SVars.compression), new ChannelFutureListener() { + conn.readFromNBT(tag); + if(Config.playerLimit > 0 && this.players.size() >= Config.playerLimit && !conn.isAdmin()) + return String.format("Der Server ist voll (%d/%d)!", this.players.size(), Config.playerLimit); + if(conn.getPassword() == null) { + if(!Config.register) + return "Anmeldung neuer Accounts ist auf diesem Server deaktiviert (Whitelisted)"; + if(loginPass.length() == 0) + return "Ein neues Passwort ist erforderlich um diesen Server zu betreten (mindestens " + Config.minPassLength + " Zeichen)"; + if(loginPass.length() < Config.minPassLength) + return "Passwort ist zu kurz, mindestens " + Config.minPassLength + " Zeichen"; + conn.setPassword(loginPass); + Log.JNI.info(loginUser + " registrierte sich mit Passwort"); + } + else if(!conn.getPassword().equals(loginPass)) { + return "Falsches Passwort"; + } + else { + Log.JNI.info(loginUser + " loggte sich mit Passwort ein"); + } + if(Config.compression >= 0) { + connection.sendPacket(new RPacketEnableCompression(Config.compression), new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { - connection.setCompressionTreshold(SVars.compression); + connection.setCompressionTreshold(Config.compression); } }); } - connection.sendPacket(new RPacketLoginSuccess()); + connection.sendPacket(new RPacketLoginSuccess(this.debug)); connection.setNetHandler(conn); this.players.add(conn); - User user = this.users.remove(loginUser); - if(user != null) - conn.copyFrom(user); - this.users.put(loginUser, conn); - this.online.put(loginUser, conn); + this.usermap.put(loginUser, conn); tag = conn.readCharacter(); - WorldServer world = tag == null ? this.space : this.getWorld(tag.getInt("Dimension")); + WorldServer world = tag == null ? this.space : this.getWorld(tag.getInteger("Dimension")); world = world == null ? this.space : world; EntityNPC player = conn.createPlayer(world, tag == null ? EntityRegistry.getEntityString(EntityHuman.class) : tag.getString("id")); if(tag != null) - player.readTags(tag); + player.readFromNBT(tag); else player.onInitialSpawn(null); +// player.setWorld(world); if(tag == null) - player.moveToBlockPosAndAngles(new BlockPos(0, 16384, 0), 0.0f, 0.0f); + /* this.movePlayerToSpawn(player); */ player.moveToBlockPosAndAngles(new BlockPos(0, 16384, 0), 0.0f, 0.0f); - Log.NETWORK.info(loginUser + "[" + connection.getCutAddress() + "] hat sich mit Objekt-ID " + Log.JNI.info(loginUser + "[" + connection.getCutAddress() + "] hat sich mit Objekt-ID " + player.getId() + " auf Level " + world.dimension.getDimensionId() + ": " + String.format("%.2f %.2f %.2f", player.posX, player.posY, player.posZ) + " verbunden (" + (tag == null ? "Charakter-Editor" : "'" + player.getCommandName() + "'") + ")"); conn.sendPacket(new SPacketJoinGame(player.getId(), world.dimension, EntityRegistry.getEntityID(player), tag == null)); conn.sendPacket(new SPacketHeldItemChange(player.inventory.currentItem)); conn.sendPacket(new SPacketWorld(WorldServer.clampGravity(), - SVars.dayCycle, SVars.timeFlow)); - this.sendPacket(new SPacketPlayerListItem(false, conn)); + Config.dayCycle, Config.timeFlow)); +// conn.initializeStats(); + this.sendPacket(new S38PacketPlayerListItem(false, conn)); world.spawnEntityInWorld(player); this.preparePlayer(player, null); for(int i = 0; i < this.players.size(); ++i) { Player other = this.players.get(i); - conn.sendPacket(new SPacketPlayerListItem(false, other)); + conn.sendPacket(new S38PacketPlayerListItem(false, other)); } conn.sendPacket(new SPacketSkin(player.getId(), player.getSkin())); // , player.getModel())); conn.setPlayerLocation(player.posX, player.posY, player.posZ, player.rotYaw, player.rotPitch); this.updateTimeAndWeatherForPlayer(conn, world); for(PotionEffect effect : player.getEffects()) { - conn.sendPacket(new SPacketEntityEffect(player.getId(), effect)); + conn.sendPacket(new S1DPacketEntityEffect(player.getId(), effect)); } - conn.sendPacket(new SPacketPlayerAbilities(player)); + conn.sendPacket(new S39PacketPlayerAbilities(player)); conn.addSelfToInternalCraftingInventory(); conn.onConnect(); + return null; } public void removePlayer(Player conn) { @@ -774,11 +895,8 @@ public final class Server implements IThreadListener, Executor { world.removeEntity(player); world.removePlayer(player); this.players.remove(conn); - this.online.remove(conn.getUser()); - User user = new User(conn.getUser()); - user.copyFrom(conn); - this.users.put(conn.getUser(), user); - this.sendPacket(new SPacketPlayerListItem(true, conn)); + this.usermap.remove(conn.getUser()); + this.sendPacket(new S38PacketPlayerListItem(true, conn)); } private void preparePlayer(EntityNPC player, WorldServer oldWorld) { @@ -790,43 +908,49 @@ public final class Server implements IThreadListener, Executor { newWorld.loadChunk((int)player.posX >> 4, (int)player.posZ >> 4); } - private TagObject readPlayer(String user) { - TagObject tag = null; + private NBTTagCompound readPlayer(String user) { + if(this.debug) + return null; + NBTTagCompound tag = null; try { - File dat = new File(new File("players"), user + ".cdt"); + File dat = new File(new File("players"), user + ".nbt"); if(dat.exists() && dat.isFile()) { - tag = TagObject.readGZip(dat); + tag = NBTLoader.readGZip(dat); } } catch(Exception e) { - Log.IO.error(e, "Konnte Spielerdaten für " + user + " nicht laden"); + Log.JNI.error(e, "Konnte Spielerdaten für " + user + " nicht laden"); } return tag; } private void writePlayer(Player conn) { + if(this.debug) + return; try { - TagObject tag = new TagObject(); + NBTTagCompound tag = new NBTTagCompound(); EntityNPC entity = conn.getPresentEntity(); if(entity != null) { - TagObject etag = new TagObject(); - entity.writeTags(etag); - etag.setInt("Dimension", entity.worldObj.dimension.getDimensionId()); + NBTTagCompound etag = new NBTTagCompound(); + entity.writeToNBT(etag); + etag.setInteger("Dimension", entity.worldObj.dimension.getDimensionId()); etag.setString("id", EntityRegistry.getEntityString(entity)); conn.writeCharacter(etag); } - conn.writeTags(tag); - File tmp = new File(new File("players"), conn.getUser() + ".cdt.tmp"); - File dat = new File(new File("players"), conn.getUser() + ".cdt"); - TagObject.writeGZip(tag, tmp); +// else +// etag = new NBTTagCompound(); + conn.writeToNBT(tag); + File tmp = new File(new File("players"), conn.getUser() + ".nbt.tmp"); + File dat = new File(new File("players"), conn.getUser() + ".nbt"); + NBTLoader.writeGZip(tag, tmp); if(dat.exists()) { dat.delete(); } tmp.renameTo(dat); } catch(Exception e) { - Log.IO.error(e, "Konnte Spielerdaten für " + conn.getUser() + " nicht speichern"); + Log.JNI.error(e, "Konnte Spielerdaten für " + conn.getUser() + " nicht speichern"); } } @@ -871,10 +995,11 @@ public final class Server implements IThreadListener, Executor { } else { Position rpos = this.getRandomSpawnPosition(origin); - nplayer.setLocationAndAngles(rpos.x(), rpos.y(), rpos.z(), rpos.yaw(), rpos.pitch()); + nplayer.setLocationAndAngles(rpos.x, rpos.y, rpos.z, rpos.yaw, rpos.pitch); +// this.movePlayerToSpawn(nplayer); } world.loadChunk((int)nplayer.posX >> 4, (int)nplayer.posZ >> 4); - if(bed != null ? SVars.checkBed : SVars.spawnRadius >= 0) { + if(bed != null ? Config.checkBed : Config.spawnRadius >= 0) { while(!world.getCollidingBoundingBoxes(nplayer, nplayer.getEntityBoundingBox()).isEmpty() && nplayer.posY < 512.0D) { nplayer.setPosition(nplayer.posX, nplayer.posY + 1.0D, nplayer.posZ); } @@ -894,12 +1019,12 @@ public final class Server implements IThreadListener, Executor { old.worldObj.dimension.getFormattedName(false)); } - public TagObject swapPlayer(Player conn, TagObject tag, Class clazz) { + public NBTTagCompound swapPlayer(Player conn, NBTTagCompound tag, Class clazz) { EntityNPC old = conn.getEntity(); old.unmount(); - TagObject oldTag = new TagObject(); - old.writeTags(oldTag); - oldTag.setInt("Dimension", old.worldObj.dimension.getDimensionId()); + NBTTagCompound oldTag = new NBTTagCompound(); + old.writeToNBT(oldTag); + oldTag.setInteger("Dimension", old.worldObj.dimension.getDimensionId()); oldTag.setString("id", EntityRegistry.getEntityString(old)); WorldServer oldWorld = (WorldServer)old.getServerWorld(); @@ -907,17 +1032,20 @@ public final class Server implements IThreadListener, Executor { oldWorld.untrackEntity(old); oldWorld.removePlayer(old); oldWorld.removePlayerEntityDangerously(old); +// old.dead = false; - WorldServer world = tag == null ? this.space : this.getWorld(tag.getInt("Dimension")); + WorldServer world = tag == null ? this.space : this.getWorld(tag.getInteger("Dimension")); world = world == null ? this.space : world; EntityNPC nplayer = conn.createPlayer(world, tag == null ? EntityRegistry.getEntityString(clazz) : tag.getString("id")); +// conn.sendPacket(new SPacketRespawn(world.dimension, EntityRegistry.getEntityID(nplayer))); if(tag != null) - nplayer.readTags(tag); + nplayer.readFromNBT(tag); else nplayer.onInitialSpawn(null); +// nplayer.clonePlayer(old); nplayer.setId(old.getId()); if(tag == null) - nplayer.moveToBlockPosAndAngles(new BlockPos(0, 16384, 0), 0.0f, 0.0f); + /* this.movePlayerToSpawn(nplayer); */ nplayer.moveToBlockPosAndAngles(new BlockPos(0, 16384, 0), 0.0f, 0.0f); world.loadChunk((int)nplayer.posX >> 4, (int)nplayer.posZ >> 4); world.addPlayer(nplayer); world.spawnEntityInWorld(nplayer); @@ -925,12 +1053,13 @@ public final class Server implements IThreadListener, Executor { conn.sendPacket(new SPacketSkin(nplayer.getId(), nplayer.getSkin())); // , nplayer.getModel())); conn.setPlayerLocation(nplayer.posX, nplayer.posY, nplayer.posZ, nplayer.rotYaw, nplayer.rotPitch); conn.sendPacket(new SPacketSetExperience(nplayer.experience, nplayer.experienceTotal, nplayer.experienceLevel)); +// conn.initializeStats(); conn.addSelfToInternalCraftingInventory(); nplayer.setHealth(nplayer.getHealth()); this.updateTimeAndWeatherForPlayer(conn, world); this.syncPlayerInventory(nplayer); for(PotionEffect effect : nplayer.getEffects()) { - conn.sendPacket(new SPacketEntityEffect(nplayer.getId(), effect)); + conn.sendPacket(new S1DPacketEntityEffect(nplayer.getId(), effect)); } conn.sendPlayerAbilities(); return oldTag; @@ -938,6 +1067,7 @@ public final class Server implements IThreadListener, Executor { public void transferToDimension(EntityNPC player, int dimension, BlockPos pos, float yaw, float pitch, PortalType portal) { WorldServer oldWorld = (WorldServer)player.getServerWorld(); // this.getWorld(player.dimension); +// player.dimension = dimension; WorldServer newWorld = this.getWorld(dimension); player.connection.sendPacket(new SPacketRespawn(newWorld.dimension, EntityRegistry.getEntityID(player), player.connection.isInEditor())); oldWorld.removePlayerEntityDangerously(player); @@ -952,10 +1082,11 @@ public final class Server implements IThreadListener, Executor { player.connection.setPlayerLocation(player.posX, player.posY, player.posZ, pos != null ? yaw : player.rotYaw, pos != null ? pitch : player.rotPitch); if(pos != null) player.setRotationYawHead(yaw); +// player.interactManager.setWorld(newWorld); this.updateTimeAndWeatherForPlayer((Player)player.connection, newWorld); this.syncPlayerInventory(player); for(PotionEffect effect : player.getEffects()) { - player.connection.sendPacket(new SPacketEntityEffect(player.getId(), effect)); + player.connection.sendPacket(new S1DPacketEntityEffect(player.getId(), effect)); } player.connection.sendPlayerAbilities(); } @@ -1026,22 +1157,23 @@ public final class Server implements IThreadListener, Executor { } public void saveAllPlayerData(boolean message) { + if(this.debug) + return; if(message) { - Log.TICK.info("Speichere Spielerdaten"); + Log.JNI.info("Speichere Spielerdaten"); } for(Player conn : this.players) { this.writePlayer(conn); } - User.saveDatabase(this.users); +// this.saveUsers(); } private void updateTimeAndWeatherForPlayer(Player conn, WorldServer world) { conn.sendPacket(new SPacketTimeUpdate(world.getDayTime(), this.getInfo())); - conn.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.SET_WEATHER, world.getWeather().getID())); - conn.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.RAIN_STRENGTH, world.getRainStrength())); - conn.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.DARKNESS, world.getDarkness())); - conn.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.FOG_STRENGTH, world.getFogStrength())); - conn.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.TEMPERATURE, world.getTempOffset())); + conn.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.SET_WEATHER, world.getWeather().getID())); + conn.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.RAIN_STRENGTH, world.getRainStrength())); + conn.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.DARKNESS, world.getDarkness())); + conn.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.FOG_STRENGTH, world.getFogStrength())); } public void syncPlayerInventory(EntityNPC player) { @@ -1057,13 +1189,13 @@ public final class Server implements IThreadListener, Executor { } synchronized(this.serverThread) { if(this.endpoint != null) { - Log.NETWORK.info("Schließe Port"); + Log.JNI.info("Schließe Port"); try { this.endpoint.channel().close().sync(); this.endpoint = null; } catch(InterruptedException e) { - Log.NETWORK.warn("Unterbrochen beim Schließen des Kanals"); + Log.JNI.warn("Unterbrochen beim Schließen des Kanals"); } } } @@ -1084,7 +1216,7 @@ public final class Server implements IThreadListener, Executor { manager.processReceivedPackets(); } catch(Exception e) { - Log.NETWORK.error(e, "Konnte Paket von " + manager.getCutAddress() + " nicht verarbeiten"); + Log.JNI.error(e, "Konnte Paket von " + manager.getCutAddress() + " nicht verarbeiten"); manager.sendPacket(new SPacketDisconnect(e.getMessage()), new GenericFutureListener>() { public void operationComplete(Future future) throws Exception { manager.closeChannel("Fehlerhaftes Datenpaket"); @@ -1101,13 +1233,19 @@ public final class Server implements IThreadListener, Executor { public Map getWarps() { return this.warps; } +// +// public void start() { +// this.serverThread.start(); +// } private void stopServer() { if(!this.stopped) { - Log.SYSTEM.info("Beende Server"); + Log.JNI.info("Beende Server"); this.terminateEndpoint(this.endMessage); if(this.started) { + Log.JNI.info("Speichere Spieler"); this.saveAllPlayerData(true); + Log.JNI.info("Speichere Welt"); this.saveAllWorlds(true); Region.finishWrite(); } @@ -1120,7 +1258,8 @@ public final class Server implements IThreadListener, Executor { try { if(this.endpoint != null) this.terminateEndpoint("Wechsele auf Port " + port); - Log.NETWORK.info("Öffne Port %d auf 0.0.0.0 (Timeout %ds)", port, SVars.timeout); + // throw new IllegalStateException("Eingangspunkt bereits gesetzt"); + Log.JNI.info("Öffne Port %d auf 0.0.0.0 (Timeout %ds)", port, Config.timeout); this.endpoint = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(NioServerSocketChannel.class)).childHandler(new ChannelInitializer() { protected void initChannel(Channel channel) throws Exception { try { @@ -1128,7 +1267,7 @@ public final class Server implements IThreadListener, Executor { } catch(ChannelException e) { } - channel.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(SVars.timeout))) + channel.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(Config.timeout))) .addLast((String)"splitter", (ChannelHandler)(new PacketSplitter())) .addLast((String)"decoder", (ChannelHandler)(new PacketDecoder(true))) .addLast((String)"prepender", (ChannelHandler)(new PacketPrepender())) @@ -1141,7 +1280,7 @@ public final class Server implements IThreadListener, Executor { }).group(SERVER_NIO_EVENTLOOP.getValue()).localAddress((InetAddress)null, port)).bind().syncUninterruptibly(); } catch(Throwable e) { - Log.NETWORK.error(e, "**** KONNTE NICHT AN PORT " + port + " ANBINDEN!"); + Log.JNI.error(e, "**** KONNTE NICHT AN PORT " + port + " ANBINDEN!"); } } else { @@ -1161,6 +1300,10 @@ public final class Server implements IThreadListener, Executor { "Geladen: " + this.getWorlds().size() + " Welten, " + WorldServer.getLoadedInfo(this); } + public void logConsole(String message) { + Log.CONSOLE.info(message); + } + public PublicKey getPublicKey() { return this.keyPair.getPublic(); } @@ -1168,20 +1311,4 @@ public final class Server implements IThreadListener, Executor { public PrivateKey getPrivateKey() { return this.keyPair.getPrivate(); } - - public void log(String msg) { - Log.CONSOLE.info(msg); - } - - public Position getExecPos() { - return this.execPos; - } - - public void setExecPos(Position pos) { - this.execPos = pos; - } - - public boolean isConsole() { - return true; - } } diff --git a/server/src/main/java/server/biome/BiomeBeach.java b/server/src/server/biome/BiomeBeach.java similarity index 100% rename from server/src/main/java/server/biome/BiomeBeach.java rename to server/src/server/biome/BiomeBeach.java diff --git a/server/src/main/java/server/biome/BiomeBlackened.java b/server/src/server/biome/BiomeBlackened.java similarity index 96% rename from server/src/main/java/server/biome/BiomeBlackened.java rename to server/src/server/biome/BiomeBlackened.java index 04383c2..f03f41f 100644 --- a/server/src/main/java/server/biome/BiomeBlackened.java +++ b/server/src/server/biome/BiomeBlackened.java @@ -1,7 +1,7 @@ package server.biome; import common.biome.Biome; -import common.block.foliage.BlockFlower; +import common.block.BlockFlower; import common.entity.npc.EntityMetalhead; import common.init.Blocks; import common.rng.Random; diff --git a/server/src/main/java/server/biome/BiomeChaos.java b/server/src/server/biome/BiomeChaos.java similarity index 93% rename from server/src/main/java/server/biome/BiomeChaos.java rename to server/src/server/biome/BiomeChaos.java index 0bd3c45..07444af 100755 --- a/server/src/main/java/server/biome/BiomeChaos.java +++ b/server/src/server/biome/BiomeChaos.java @@ -38,7 +38,7 @@ public class BiomeChaos extends GenBiome { int i8 = rand.chOffset(); int l11 = rand.chOffset(); - BlockPos blockpos2 = worldIn.getHeight(pos.add(i8, 0, l11)); + BlockPos blockpos2 = worldIn.getPrecipitationHeight(pos.add(i8, 0, l11)); this.mushroomBlueGen.generate(worldIn, rand, blockpos2); } } diff --git a/server/src/main/java/server/biome/BiomeDesert.java b/server/src/server/biome/BiomeDesert.java similarity index 92% rename from server/src/main/java/server/biome/BiomeDesert.java rename to server/src/server/biome/BiomeDesert.java index 0171ff5..079692e 100755 --- a/server/src/main/java/server/biome/BiomeDesert.java +++ b/server/src/server/biome/BiomeDesert.java @@ -33,7 +33,7 @@ public class BiomeDesert extends GenBiome { int i = rand.chOffset(); int j = rand.chOffset(); - BlockPos blockpos = worldIn.getHeight(pos.add(i, 0, j)).up(); + BlockPos blockpos = worldIn.getPrecipitationHeight(pos.add(i, 0, j)).up(); (new WorldGenDesertWells()).generate(worldIn, rand, blockpos); } } diff --git a/server/src/main/java/server/biome/BiomeExterminated.java b/server/src/server/biome/BiomeExterminated.java similarity index 100% rename from server/src/main/java/server/biome/BiomeExterminated.java rename to server/src/server/biome/BiomeExterminated.java diff --git a/server/src/main/java/server/biome/BiomeForest.java b/server/src/server/biome/BiomeForest.java similarity index 94% rename from server/src/main/java/server/biome/BiomeForest.java rename to server/src/server/biome/BiomeForest.java index 23709f9..f6a5ecc 100755 --- a/server/src/main/java/server/biome/BiomeForest.java +++ b/server/src/server/biome/BiomeForest.java @@ -1,9 +1,8 @@ package server.biome; import common.biome.Biome; -import common.block.foliage.BlockDoublePlant; -import common.block.foliage.BlockFlower; -import common.entity.animal.EntityFox; +import common.block.BlockDoublePlant; +import common.block.BlockFlower; import common.entity.animal.EntityWolf; import common.entity.npc.EntityElf; import common.entity.npc.EntityWoodElf; @@ -68,14 +67,12 @@ public class BiomeForest extends GenBiome if (this.subType == 0) { - this.mobs.add(new RngSpawn(EntityWolf.class, 5, 2, 4)); - this.mobs.add(new RngSpawn(EntityFox.class, 1, 2, 6)); + this.mobs.add(new RngSpawn(EntityWolf.class, 5, 4, 4)); } if (this.subType == 3) { this.treesPerChunk = -999; - this.mobs.add(new RngSpawn(EntityFox.class, 1, 2, 4)); } if(this.subType != 4) { @@ -84,7 +81,6 @@ public class BiomeForest extends GenBiome else { this.mobs.add(new RngSpawn(EntityWoodElf.class, 100, 4, 16)); this.mobs.add(new RngSpawn(EntityElf.class, 12, 4, 16)); - this.mobs.add(new RngSpawn(EntityFox.class, 3, 2, 5)); } } @@ -138,7 +134,7 @@ public class BiomeForest extends GenBiome { int k = i * 4 + rand.range(9, 11); int l = j * 4 + rand.range(9, 11); - BlockPos blockpos = worldIn.getHeight(pos.add(k, 0, l)); + BlockPos blockpos = worldIn.getPrecipitationHeight(pos.add(k, 0, l)); if (rand.chance(20)) { @@ -187,7 +183,7 @@ public class BiomeForest extends GenBiome { int j2 = rand.chOffset(); int k2 = rand.chOffset(); - int i1 = rand.zrange(worldIn.getHeight(pos.add(j2, 0, k2)).getY() + 32); + int i1 = rand.zrange(worldIn.getPrecipitationHeight(pos.add(j2, 0, k2)).getY() + 32); if (DOUBLE_PLANT_GEN.generate(worldIn, rand, new BlockPos(pos.getX() + j2, i1, pos.getZ() + k2))) { diff --git a/server/src/main/java/server/biome/BiomeHell.java b/server/src/server/biome/BiomeHell.java similarity index 100% rename from server/src/main/java/server/biome/BiomeHell.java rename to server/src/server/biome/BiomeHell.java diff --git a/server/src/main/java/server/biome/BiomeHills.java b/server/src/server/biome/BiomeHills.java similarity index 100% rename from server/src/main/java/server/biome/BiomeHills.java rename to server/src/server/biome/BiomeHills.java diff --git a/server/src/main/java/server/biome/BiomeJungle.java b/server/src/server/biome/BiomeJungle.java similarity index 95% rename from server/src/main/java/server/biome/BiomeJungle.java rename to server/src/server/biome/BiomeJungle.java index 34faff3..8431daa 100755 --- a/server/src/main/java/server/biome/BiomeJungle.java +++ b/server/src/server/biome/BiomeJungle.java @@ -1,7 +1,7 @@ package server.biome; import common.biome.Biome; -import common.block.foliage.BlockTallGrass; +import common.block.BlockTallGrass; import common.entity.animal.EntityChicken; import common.entity.animal.EntityOcelot; import common.init.Blocks; @@ -69,7 +69,7 @@ public class BiomeJungle extends GenBiome super.decorate(worldIn, rand, pos); int i = rand.chOffset(); int j = rand.chOffset(); - int k = rand.zrange(worldIn.getHeight(pos.add(i, 0, j)).getY() * 2); + int k = rand.zrange(worldIn.getPrecipitationHeight(pos.add(i, 0, j)).getY() * 2); (new WorldGenMelon()).generate(worldIn, rand, pos.add(i, k, j)); WorldGenVines worldgenvines = new WorldGenVines(); diff --git a/server/src/main/java/server/biome/BiomeMesa.java b/server/src/server/biome/BiomeMesa.java similarity index 97% rename from server/src/main/java/server/biome/BiomeMesa.java rename to server/src/server/biome/BiomeMesa.java index 19251d3..6651be2 100755 --- a/server/src/main/java/server/biome/BiomeMesa.java +++ b/server/src/server/biome/BiomeMesa.java @@ -5,10 +5,11 @@ import java.util.Arrays; import common.biome.Biome; import common.block.Block; import common.block.BlockColored; -import common.block.natural.BlockDirt; -import common.block.natural.BlockSand; +import common.block.BlockDirt; +import common.block.BlockSand; import common.color.DyeColor; import common.init.Blocks; +import common.material.Material; import common.rng.PerlinGen; import common.rng.Random; import common.rng.WeightedList; @@ -121,7 +122,7 @@ public class BiomeMesa extends GenBiome for (int i1 = chunkPrimerIn.height - 1; i1 >= 0; --i1) { - if (chunkPrimerIn.get(k1, i1, j1).getBlock() == Blocks.air && i1 < (int)d4) + if (chunkPrimerIn.get(k1, i1, j1).getBlock().getMaterial() == Material.air && i1 < (int)d4) { chunkPrimerIn.set(k1, i1, j1, worldState); } @@ -134,7 +135,7 @@ public class BiomeMesa extends GenBiome // { State iblockstate1 = chunkPrimerIn.get(k1, i1, j1); - if (iblockstate1.getBlock() == Blocks.air) + if (iblockstate1.getBlock().getMaterial() == Material.air) { l = -1; } @@ -155,7 +156,7 @@ public class BiomeMesa extends GenBiome iblockstate3 = this.fillerBlock; } - if (i1 < l1 && (iblockstate == null || iblockstate.getBlock() == Blocks.air)) + if (i1 < l1 && (iblockstate == null || iblockstate.getBlock().getMaterial() == Material.air)) { iblockstate = liquid; } diff --git a/server/src/main/java/server/biome/BiomeMoon.java b/server/src/server/biome/BiomeMoon.java similarity index 100% rename from server/src/main/java/server/biome/BiomeMoon.java rename to server/src/server/biome/BiomeMoon.java diff --git a/server/src/main/java/server/biome/BiomeMushroom.java b/server/src/server/biome/BiomeMushroom.java similarity index 100% rename from server/src/main/java/server/biome/BiomeMushroom.java rename to server/src/server/biome/BiomeMushroom.java diff --git a/server/src/main/java/server/biome/BiomeMutated.java b/server/src/server/biome/BiomeMutated.java similarity index 100% rename from server/src/main/java/server/biome/BiomeMutated.java rename to server/src/server/biome/BiomeMutated.java diff --git a/server/src/main/java/server/biome/BiomeNone.java b/server/src/server/biome/BiomeNone.java similarity index 100% rename from server/src/main/java/server/biome/BiomeNone.java rename to server/src/server/biome/BiomeNone.java diff --git a/server/src/main/java/server/biome/BiomePlains.java b/server/src/server/biome/BiomePlains.java similarity index 93% rename from server/src/main/java/server/biome/BiomePlains.java rename to server/src/server/biome/BiomePlains.java index 15a969a..45ce1f0 100755 --- a/server/src/main/java/server/biome/BiomePlains.java +++ b/server/src/server/biome/BiomePlains.java @@ -1,8 +1,8 @@ package server.biome; import common.biome.Biome; -import common.block.foliage.BlockDoublePlant; -import common.block.foliage.BlockFlower; +import common.block.BlockDoublePlant; +import common.block.BlockFlower; import common.entity.animal.EntityHorse; import common.rng.Random; import common.util.BlockPos; @@ -87,7 +87,7 @@ public class BiomePlains extends GenBiome { int j = rand.chOffset(); int k = rand.chOffset(); - int l = rand.zrange(worldIn.getHeight(pos.add(j, 0, k)).getY() + 32); + int l = rand.zrange(worldIn.getPrecipitationHeight(pos.add(j, 0, k)).getY() + 32); DOUBLE_PLANT_GEN.generate(worldIn, rand, pos.add(j, l, k)); } } @@ -101,7 +101,7 @@ public class BiomePlains extends GenBiome // { int j1 = rand.chOffset(); int k1 = rand.chOffset(); - int l1 = rand.zrange(worldIn.getHeight(pos.add(j1, 0, k1)).getY() + 32); + int l1 = rand.zrange(worldIn.getPrecipitationHeight(pos.add(j1, 0, k1)).getY() + 32); DOUBLE_PLANT_GEN.generate(worldIn, rand, pos.add(j1, l1, k1)); // } } diff --git a/server/src/main/java/server/biome/BiomeSavanna.java b/server/src/server/biome/BiomeSavanna.java similarity index 94% rename from server/src/main/java/server/biome/BiomeSavanna.java rename to server/src/server/biome/BiomeSavanna.java index f2124ae..c8b3776 100755 --- a/server/src/main/java/server/biome/BiomeSavanna.java +++ b/server/src/server/biome/BiomeSavanna.java @@ -1,8 +1,8 @@ package server.biome; import common.biome.Biome; -import common.block.foliage.BlockDoublePlant; -import common.block.natural.BlockDirt; +import common.block.BlockDirt; +import common.block.BlockDoublePlant; import common.entity.animal.EntityHorse; import common.init.Blocks; import common.rng.Random; @@ -46,7 +46,7 @@ public class BiomeSavanna extends GenBiome { int j = rand.chOffset(); int k = rand.chOffset(); - int l = rand.zrange(worldIn.getHeight(pos.add(j, 0, k)).getY() + 32); + int l = rand.zrange(worldIn.getPrecipitationHeight(pos.add(j, 0, k)).getY() + 32); DOUBLE_PLANT_GEN.generate(worldIn, rand, pos.add(j, l, k)); } diff --git a/server/src/main/java/server/biome/BiomeSnow.java b/server/src/server/biome/BiomeSnow.java similarity index 95% rename from server/src/main/java/server/biome/BiomeSnow.java rename to server/src/server/biome/BiomeSnow.java index ea236f2..e3e1d94 100755 --- a/server/src/main/java/server/biome/BiomeSnow.java +++ b/server/src/server/biome/BiomeSnow.java @@ -36,14 +36,14 @@ public class BiomeSnow extends GenBiome { int j = rand.chOffset(); int k = rand.chOffset(); - this.spikeGen.generate(worldIn, rand, worldIn.getHeight(pos.add(j, 0, k))); + this.spikeGen.generate(worldIn, rand, worldIn.getPrecipitationHeight(pos.add(j, 0, k))); } for (int l = 0; l < 2; ++l) { int i1 = rand.chOffset(); int j1 = rand.chOffset(); - this.pathGen.generate(worldIn, rand, worldIn.getHeight(pos.add(i1, 0, j1))); + this.pathGen.generate(worldIn, rand, worldIn.getPrecipitationHeight(pos.add(i1, 0, j1))); } } diff --git a/server/src/main/java/server/biome/BiomeSnowLand.java b/server/src/server/biome/BiomeSnowLand.java similarity index 100% rename from server/src/main/java/server/biome/BiomeSnowLand.java rename to server/src/server/biome/BiomeSnowLand.java diff --git a/server/src/main/java/server/biome/BiomeSpace.java b/server/src/server/biome/BiomeSpace.java similarity index 96% rename from server/src/main/java/server/biome/BiomeSpace.java rename to server/src/server/biome/BiomeSpace.java index b83c9de..93f8d1f 100755 --- a/server/src/main/java/server/biome/BiomeSpace.java +++ b/server/src/server/biome/BiomeSpace.java @@ -1,7 +1,7 @@ package server.biome; import common.biome.Biome; -import common.block.natural.BlockDirt; +import common.block.BlockDirt; import common.init.Blocks; import common.rng.Random; import common.rng.WeightedList; diff --git a/server/src/main/java/server/biome/BiomeStoneBeach.java b/server/src/server/biome/BiomeStoneBeach.java similarity index 100% rename from server/src/main/java/server/biome/BiomeStoneBeach.java rename to server/src/server/biome/BiomeStoneBeach.java diff --git a/server/src/main/java/server/biome/BiomeSwamp.java b/server/src/server/biome/BiomeSwamp.java similarity index 93% rename from server/src/main/java/server/biome/BiomeSwamp.java rename to server/src/server/biome/BiomeSwamp.java index 9c3854d..eb5cdd0 100755 --- a/server/src/main/java/server/biome/BiomeSwamp.java +++ b/server/src/server/biome/BiomeSwamp.java @@ -2,9 +2,10 @@ package server.biome; import common.biome.Biome; import common.block.BlockDirectional; -import common.block.foliage.BlockFlower; +import common.block.BlockFlower; import common.entity.npc.EntitySlime; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.util.Facing; @@ -52,7 +53,7 @@ public class BiomeSwamp extends GenBiome for (int k = chunkPrimerIn.height - 1; k >= 0; --k) { - if (chunkPrimerIn.get(j, k, i).getBlock() != Blocks.air) + if (chunkPrimerIn.get(j, k, i).getBlock().getMaterial() != Material.air) { if (k == 62 && chunkPrimerIn.get(j, k, i).getBlock() != Blocks.water) { diff --git a/server/src/main/java/server/biome/BiomeTaiga.java b/server/src/server/biome/BiomeTaiga.java similarity index 93% rename from server/src/main/java/server/biome/BiomeTaiga.java rename to server/src/server/biome/BiomeTaiga.java index 97812ff..4d9fbc6 100755 --- a/server/src/main/java/server/biome/BiomeTaiga.java +++ b/server/src/server/biome/BiomeTaiga.java @@ -1,9 +1,9 @@ package server.biome; import common.biome.Biome; -import common.block.foliage.BlockDoublePlant; -import common.block.foliage.BlockTallGrass; -import common.block.natural.BlockDirt; +import common.block.BlockDirt; +import common.block.BlockDoublePlant; +import common.block.BlockTallGrass; import common.entity.animal.EntityWolf; import common.init.Blocks; import common.rng.Random; @@ -70,7 +70,7 @@ public class BiomeTaiga extends GenBiome { int k = rand.chOffset(); int l = rand.chOffset(); - BlockPos blockpos = worldIn.getHeight(pos.add(k, 0, l)); + BlockPos blockpos = worldIn.getPrecipitationHeight(pos.add(k, 0, l)); field_150643_aG.generate(worldIn, rand, blockpos); } } @@ -81,7 +81,7 @@ public class BiomeTaiga extends GenBiome { int j1 = rand.chOffset(); int k1 = rand.chOffset(); - int l1 = rand.zrange(worldIn.getHeight(pos.add(j1, 0, k1)).getY() + 32); + int l1 = rand.zrange(worldIn.getPrecipitationHeight(pos.add(j1, 0, k1)).getY() + 32); DOUBLE_PLANT_GEN.generate(worldIn, rand, pos.add(j1, l1, k1)); } diff --git a/server/src/main/java/server/biome/BiomeTian.java b/server/src/server/biome/BiomeTian.java similarity index 96% rename from server/src/main/java/server/biome/BiomeTian.java rename to server/src/server/biome/BiomeTian.java index 021a972..5f05ad9 100755 --- a/server/src/main/java/server/biome/BiomeTian.java +++ b/server/src/server/biome/BiomeTian.java @@ -1,7 +1,7 @@ package server.biome; import common.biome.Biome; -import common.block.foliage.BlockFlower; +import common.block.BlockFlower; import common.entity.animal.EntityBat; import common.entity.animal.EntityMouse; import common.entity.animal.EntityRabbit; @@ -68,7 +68,7 @@ public class BiomeTian extends GenBiome { int i8 = rand.chOffset(); int l11 = rand.chOffset(); - BlockPos blockpos2 = worldIn.getHeight(pos.add(i8, 0, l11)); + BlockPos blockpos2 = worldIn.getPrecipitationHeight(pos.add(i8, 0, l11)); this.mushroomBlueGen.generate(worldIn, rand, blockpos2); } } diff --git a/server/src/main/java/server/biome/BiomeWater.java b/server/src/server/biome/BiomeWater.java similarity index 100% rename from server/src/main/java/server/biome/BiomeWater.java rename to server/src/server/biome/BiomeWater.java diff --git a/server/src/main/java/server/biome/GenBiome.java b/server/src/server/biome/GenBiome.java similarity index 94% rename from server/src/main/java/server/biome/GenBiome.java rename to server/src/server/biome/GenBiome.java index cc3c27d..f87a088 100755 --- a/server/src/main/java/server/biome/GenBiome.java +++ b/server/src/server/biome/GenBiome.java @@ -4,11 +4,10 @@ import common.biome.Biome; import common.biome.IBiome; import common.block.Block; import common.block.BlockColored; -import common.block.Material; -import common.block.foliage.BlockFlower; -import common.block.foliage.BlockSapling; -import common.block.foliage.BlockTallGrass; -import common.block.natural.BlockSand; +import common.block.BlockFlower; +import common.block.BlockSand; +import common.block.BlockSapling; +import common.block.BlockTallGrass; import common.color.DyeColor; import common.entity.animal.EntityBat; import common.entity.animal.EntityChicken; @@ -27,6 +26,7 @@ import common.entity.npc.EntityZombie; import common.init.Blocks; import common.init.WoodType; import common.log.Log; +import common.material.Material; import common.rng.PerlinGen; import common.rng.Random; import common.rng.WeightedList; @@ -173,7 +173,7 @@ public abstract class GenBiome implements IBiome { } else { - Log.TICK.warn("Biom-ID ist nicht im Bereich: " + id + ", verwende " + Biome.DEF_BIOME.id + " (" + Biome.DEF_BIOME.name + ")"); + Log.JNI.warn("Biom-ID ist nicht im Bereich: " + id + ", verwende " + Biome.DEF_BIOME.id + " (" + Biome.DEF_BIOME.name + ")"); return BIOMES[Biome.DEF_BIOME.id]; } } @@ -340,7 +340,7 @@ public abstract class GenBiome implements IBiome { int l = rand.chOffset(); WorldGenTree treeGen = this.genBigTreeChance(rand); treeGen.prepare(); - BlockPos blockpos = world.getHeight(pos.add(k6, 0, l)); + BlockPos blockpos = world.getPrecipitationHeight(pos.add(k6, 0, l)); if (treeGen.generate(world, rand, blockpos)) { @@ -352,14 +352,14 @@ public abstract class GenBiome implements IBiome { { int l6 = rand.chOffset(); int k10 = rand.chOffset(); - this.bigMushroomGen.generate(world, rand, world.getHeight(pos.add(l6, 0, k10))); + this.bigMushroomGen.generate(world, rand, world.getPrecipitationHeight(pos.add(l6, 0, k10))); } for (int l2 = 0; l2 < this.flowersPerChunk; ++l2) { int i7 = rand.chOffset(); int l10 = rand.chOffset(); - int j14 = world.getHeight(pos.add(i7, 0, l10)).getY() + 32; + int j14 = world.getPrecipitationHeight(pos.add(i7, 0, l10)).getY() + 32; if (j14 > 0) { @@ -368,8 +368,11 @@ public abstract class GenBiome implements IBiome { BlockFlower.EnumFlowerType blockflower$enumflowertype = this.pickRandomFlower(rand, blockpos1); BlockFlower blockflower = blockflower$enumflowertype.getBlockType().getBlock(); - this.yellowFlowerGen.setGeneratedBlock(blockflower, blockflower$enumflowertype); - this.yellowFlowerGen.generate(world, rand, blockpos1); + if (blockflower.getMaterial() != Material.air) + { + this.yellowFlowerGen.setGeneratedBlock(blockflower, blockflower$enumflowertype); + this.yellowFlowerGen.generate(world, rand, blockpos1); + } } } @@ -377,7 +380,7 @@ public abstract class GenBiome implements IBiome { { int j7 = rand.chOffset(); int i11 = rand.chOffset(); - int k14 = world.getHeight(pos.add(j7, 0, i11)).getY() * 2; + int k14 = world.getPrecipitationHeight(pos.add(j7, 0, i11)).getY() * 2; if (k14 > 0) { @@ -390,7 +393,7 @@ public abstract class GenBiome implements IBiome { { int k7 = rand.chOffset(); int j11 = rand.chOffset(); - int l14 = world.getHeight(pos.add(k7, 0, j11)).getY() * 2; + int l14 = world.getPrecipitationHeight(pos.add(k7, 0, j11)).getY() * 2; if (l14 > 0) { @@ -403,7 +406,7 @@ public abstract class GenBiome implements IBiome { { int l7 = rand.chOffset(); int k11 = rand.chOffset(); - int i15 = world.getHeight(pos.add(l7, 0, k11)).getY() * 2; + int i15 = world.getPrecipitationHeight(pos.add(l7, 0, k11)).getY() * 2; if (i15 > 0) { @@ -431,7 +434,7 @@ public abstract class GenBiome implements IBiome { { int i8 = rand.chOffset(); int l11 = rand.chOffset(); - BlockPos blockpos2 = world.getHeight(pos.add(i8, 0, l11)); + BlockPos blockpos2 = world.getPrecipitationHeight(pos.add(i8, 0, l11)); this.mushroomBrownGen.generate(world, rand, blockpos2); } @@ -439,7 +442,7 @@ public abstract class GenBiome implements IBiome { { int j8 = rand.chOffset(); int i12 = rand.chOffset(); - int j15 = world.getHeight(pos.add(j8, 0, i12)).getY() * 2; + int j15 = world.getPrecipitationHeight(pos.add(j8, 0, i12)).getY() * 2; if (j15 > 0) { @@ -454,7 +457,7 @@ public abstract class GenBiome implements IBiome { { int i4 = rand.chOffset(); int k8 = rand.chOffset(); - int j12 = world.getHeight(pos.add(i4, 0, k8)).getY() * 2; + int j12 = world.getPrecipitationHeight(pos.add(i4, 0, k8)).getY() * 2; if (j12 > 0) { @@ -467,7 +470,7 @@ public abstract class GenBiome implements IBiome { { int j4 = rand.chOffset(); int l8 = rand.chOffset(); - int k12 = world.getHeight(pos.add(j4, 0, l8)).getY() * 2; + int k12 = world.getPrecipitationHeight(pos.add(j4, 0, l8)).getY() * 2; if (k12 > 0) { @@ -480,7 +483,7 @@ public abstract class GenBiome implements IBiome { { int i9 = rand.chOffset(); int l12 = rand.chOffset(); - int i16 = world.getHeight(pos.add(i9, 0, l12)).getY() * 2; + int i16 = world.getPrecipitationHeight(pos.add(i9, 0, l12)).getY() * 2; if (i16 > 0) { @@ -493,7 +496,7 @@ public abstract class GenBiome implements IBiome { { int j9 = rand.chOffset(); int i13 = rand.chOffset(); - int j16 = world.getHeight(pos.add(j9, 0, i13)).getY() * 2; + int j16 = world.getPrecipitationHeight(pos.add(j9, 0, i13)).getY() * 2; if (j16 > 0) { @@ -506,7 +509,7 @@ public abstract class GenBiome implements IBiome { { int i5 = rand.chOffset(); int k9 = rand.chOffset(); - int j13 = world.getHeight(pos.add(i5, 0, k9)).getY() * 2; + int j13 = world.getPrecipitationHeight(pos.add(i5, 0, k9)).getY() * 2; if (j13 > 0) { @@ -519,7 +522,7 @@ public abstract class GenBiome implements IBiome { { int l9 = rand.chOffset(); int k13 = rand.chOffset(); - int l16 = world.getHeight(pos.add(l9, 0, k13)).getY() * 2; + int l16 = world.getPrecipitationHeight(pos.add(l9, 0, k13)).getY() * 2; if (l16 > 0) { @@ -551,7 +554,7 @@ public abstract class GenBiome implements IBiome { Block worldBlock = worldState.getBlock(); State worldAlt = worldIn.dimension.getAltFiller1(); State liquid = worldIn.getSurfaceLiquid(); - boolean freeze = liquid.getBlock().getMaterial() == Material.WATER; + boolean freeze = liquid.getBlock().getMaterial() == Material.water; State iblockstate = this.topBlock; State iblockstate1 = this.fillerBlock; int j = -1; @@ -564,7 +567,7 @@ public abstract class GenBiome implements IBiome { { State iblockstate2 = chunkPrimerIn.get(i1, j1, l); - if (iblockstate2.getBlock() == Blocks.air) + if (iblockstate2.getBlock().getMaterial() == Material.air) { j = -1; } @@ -583,7 +586,7 @@ public abstract class GenBiome implements IBiome { iblockstate1 = this.fillerBlock; } - if (j1 < i && (iblockstate == null || iblockstate.getBlock() == Blocks.air)) + if (j1 < i && (iblockstate == null || iblockstate.getBlock().getMaterial() == Material.air)) { if (freeze && World.ABSOLUTE_ZERO + worldIn.getTempOffset() + this.base.getTemperature(blockpos$mutableblockpos.set(x, j1, z)) <= 0.0F) { @@ -810,7 +813,7 @@ public abstract class GenBiome implements IBiome { { if (j >= i / 16) { - if (worldIn.getState(blockpos1).getBlock() == Blocks.air) + if (worldIn.getState(blockpos1).getBlock().getMaterial() == Material.air) { if (rand.chance(8)) { diff --git a/server/src/main/java/server/biome/RngSpawn.java b/server/src/server/biome/RngSpawn.java similarity index 100% rename from server/src/main/java/server/biome/RngSpawn.java rename to server/src/server/biome/RngSpawn.java diff --git a/server/src/main/java/server/biome/Scaling.java b/server/src/server/biome/Scaling.java similarity index 100% rename from server/src/main/java/server/biome/Scaling.java rename to server/src/server/biome/Scaling.java diff --git a/server/src/main/java/server/biome/Temperature.java b/server/src/server/biome/Temperature.java similarity index 100% rename from server/src/main/java/server/biome/Temperature.java rename to server/src/server/biome/Temperature.java diff --git a/server/src/main/java/server/clipboard/BlockTransform.java b/server/src/server/clipboard/BlockTransform.java similarity index 100% rename from server/src/main/java/server/clipboard/BlockTransform.java rename to server/src/server/clipboard/BlockTransform.java diff --git a/server/src/main/java/server/clipboard/ClipboardBlock.java b/server/src/server/clipboard/ClipboardBlock.java similarity index 66% rename from server/src/main/java/server/clipboard/ClipboardBlock.java rename to server/src/server/clipboard/ClipboardBlock.java index aa73d4d..abb7c34 100755 --- a/server/src/main/java/server/clipboard/ClipboardBlock.java +++ b/server/src/server/clipboard/ClipboardBlock.java @@ -1,12 +1,12 @@ package server.clipboard; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.tileentity.TileEntity; import common.world.State; public class ClipboardBlock { private State state; - private TagObject data; + private NBTTagCompound nbt; public ClipboardBlock(State state) { this.state = state; @@ -14,9 +14,9 @@ public class ClipboardBlock { public ClipboardBlock(State data, TileEntity tile) { this(data); - TagObject tag = new TagObject(); - tile.writeTags(tag); - this.data = tag; + NBTTagCompound tag = new NBTTagCompound(); + tile.writeToNBT(tag); + this.nbt = tag; } public State getState() { @@ -27,7 +27,7 @@ public class ClipboardBlock { this.state = state; } - public TagObject getData() { - return this.data; + public NBTTagCompound getNbtData() { + return this.nbt; } } diff --git a/server/src/main/java/server/clipboard/ClipboardPlacer.java b/server/src/server/clipboard/ClipboardPlacer.java similarity index 97% rename from server/src/main/java/server/clipboard/ClipboardPlacer.java rename to server/src/server/clipboard/ClipboardPlacer.java index f69acfa..24d9db5 100755 --- a/server/src/main/java/server/clipboard/ClipboardPlacer.java +++ b/server/src/server/clipboard/ClipboardPlacer.java @@ -9,9 +9,9 @@ import java.util.Map; import java.util.Set; import common.block.Block; +import common.block.BlockDoor; +import common.block.BlockRailBase; import common.block.ITileEntityProvider; -import common.block.artificial.BlockDoor; -import common.block.tech.BlockRailBase; import common.collect.Lists; import common.init.Blocks; import common.inventory.IInventory; @@ -41,6 +41,8 @@ public class ClipboardPlacer { } public void setBlock(BlockPos location, ClipboardBlock block) { + if(location.getY() < 0 || location.getY() > 511) + return; Block type = block.getState().getBlock(); if (ReorderRegistry.shouldPlaceLast(type)) { // Place torches, etc. last diff --git a/server/src/main/java/server/clipboard/ReorderRegistry.java b/server/src/server/clipboard/ReorderRegistry.java similarity index 98% rename from server/src/main/java/server/clipboard/ReorderRegistry.java rename to server/src/server/clipboard/ReorderRegistry.java index 3040b08..8e872b9 100755 --- a/server/src/main/java/server/clipboard/ReorderRegistry.java +++ b/server/src/server/clipboard/ReorderRegistry.java @@ -6,8 +6,8 @@ import java.util.Map; import java.util.Set; import common.block.Block; -import common.block.artificial.BlockBed; -import common.block.artificial.BlockDoor; +import common.block.BlockBed; +import common.block.BlockDoor; import common.color.DyeColor; import common.init.BlockRegistry; import common.init.Blocks; @@ -54,8 +54,6 @@ public abstract class ReorderRegistry { PLACE_LAST.add(Blocks.red_mushroom_block); PLACE_LAST.add(Blocks.torch); PLACE_LAST.add(Blocks.fire); - PLACE_LAST.add(Blocks.soul_fire); - PLACE_LAST.add(Blocks.black_fire); PLACE_LAST.add(Blocks.redstone); PLACE_LAST.add(Blocks.wheat); PLACE_LAST.add(Blocks.ladder); diff --git a/server/src/main/java/server/clipboard/Rotation.java b/server/src/server/clipboard/Rotation.java similarity index 100% rename from server/src/main/java/server/clipboard/Rotation.java rename to server/src/server/clipboard/Rotation.java diff --git a/server/src/main/java/server/clipboard/RotationRegistry.java b/server/src/server/clipboard/RotationRegistry.java similarity index 89% rename from server/src/main/java/server/clipboard/RotationRegistry.java rename to server/src/server/clipboard/RotationRegistry.java index 6716e84..38bc0c7 100755 --- a/server/src/main/java/server/clipboard/RotationRegistry.java +++ b/server/src/server/clipboard/RotationRegistry.java @@ -6,16 +6,16 @@ import java.util.Map; import java.util.function.Predicate; import common.block.Block; +import common.block.BlockDoor; +import common.block.BlockLever; +import common.block.BlockLog; +import common.block.BlockPortal; +import common.block.BlockQuartz; +import common.block.BlockRail; +import common.block.BlockRailBase; +import common.block.BlockRailDetector; +import common.block.BlockRailPowered; import common.block.BlockRotatedPillar; -import common.block.artificial.BlockDoor; -import common.block.artificial.BlockPortal; -import common.block.artificial.BlockQuartz; -import common.block.foliage.BlockLog; -import common.block.tech.BlockLever; -import common.block.tech.BlockRail; -import common.block.tech.BlockRailBase; -import common.block.tech.BlockRailDetector; -import common.block.tech.BlockRailPowered; import common.collect.Lists; import common.collect.Maps; import common.properties.IProperty; @@ -110,8 +110,9 @@ public abstract class RotationRegistry { } } if(!values.isEmpty()) { + int legacyId = common.init.BlockRegistry.getIdFromBlock(block); Rotation state = new Rotation(values.toArray(new RotationValue[values.size()]), predicate); -// Log.CONFIG.debug("Block " + game.init.BlockRegistry.getNameFromBlock(block) + "/" + legacyId + " mask = " + String.format("0x%x", mask)); +// Log.CONFIG.debug("Block " + game.init.BlockRegistry.REGISTRY.getNameForObject(block) + "/" + legacyId + " mask = " + String.format("0x%x", mask)); // for(RotationValue value : values) { // Log.CONFIG.debug(" meta " + value.data + " -> " + value.direction.toString()); // } diff --git a/server/src/main/java/server/clipboard/RotationValue.java b/server/src/server/clipboard/RotationValue.java similarity index 100% rename from server/src/main/java/server/clipboard/RotationValue.java rename to server/src/server/clipboard/RotationValue.java diff --git a/server/src/main/java/server/clipboard/Vector.java b/server/src/server/clipboard/Vector.java similarity index 100% rename from server/src/main/java/server/clipboard/Vector.java rename to server/src/server/clipboard/Vector.java diff --git a/server/src/main/java/server/command/ArgCombiner.java b/server/src/server/command/ArgCombiner.java similarity index 100% rename from server/src/main/java/server/command/ArgCombiner.java rename to server/src/server/command/ArgCombiner.java diff --git a/server/src/server/command/Argument.java b/server/src/server/command/Argument.java new file mode 100644 index 0000000..9863e7c --- /dev/null +++ b/server/src/server/command/Argument.java @@ -0,0 +1,33 @@ +package server.command; + +import java.util.Map; + +public class Argument { + private final Parameter parameter; + private final int position; + private final String[] inputs; + private final Map values; + + public Argument(Parameter parameter, int position, String[] inputs, Map values) { + this.parameter = parameter; + this.position = position; + this.inputs = inputs; + this.values = values; + } + + public Parameter getParameter() { + return this.parameter; + } + + public int getPosition() { + return this.position; + } + + public String[] getInputs() { + return this.inputs; + } + + public Map getValues() { + return this.values; + } +} diff --git a/server/src/main/java/server/command/ArgumentParser.java b/server/src/server/command/ArgumentParser.java similarity index 100% rename from server/src/main/java/server/command/ArgumentParser.java rename to server/src/server/command/ArgumentParser.java diff --git a/server/src/server/command/ArgumentSplitter.java b/server/src/server/command/ArgumentSplitter.java new file mode 100644 index 0000000..58ba45a --- /dev/null +++ b/server/src/server/command/ArgumentSplitter.java @@ -0,0 +1,411 @@ +package server.command; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import common.collect.Lists; +import common.collect.Maps; +import common.collect.Sets; + +public class ArgumentSplitter { + private final String command; + private final Map arguments; + private final CommandEnvironment env; + + protected ArgumentSplitter(Map arguments, String command, CommandEnvironment env) { + this.arguments = arguments; + this.command = command; + this.env = env; + } + + private static String joinArgs(Iterable iter) { + StringBuilder sb = new StringBuilder("'"); + for(T obj : iter) { + if(sb.length() > 1) + sb.append("', '"); + sb.append(String.valueOf(obj)); + } + return sb.append("'").toString(); + } + + public static ArgumentSplitter parseArgs(CommandEnvironment env, String str, String[] argv, CachedExecutable cached) { + Map parameters = cached.getParameters(); + List positionals = Lists.newArrayList(cached.getPositionals()); + // String[] argv = ArgumentParser.splitString(str); + Map args = Maps.newHashMap(); + int ppos = 0; + boolean parse = true; + for(int z = 1; z < argv.length; z++) { + String arg = argv[z]; + Parameter param = null; + boolean pos = false; + if(parse && arg.equals("--")) { + parse = false; + continue; + } + else if(parse && (arg.startsWith("--") || (arg.startsWith("-") && arg.length() == 2))) { + param = parameters.get(arg.substring(arg.startsWith("--") ? 2 : 1)); + if(param != null && param.isPositional() && !args.containsKey(param.getName())) { + for(int n = 0; n < positionals.size(); n++) { + if(param == positionals.get(n)) { + positionals.remove(n); + break; + } + } + } + } + else if(ppos < positionals.size()) { + param = positionals.get(ppos++); + pos = true; + } + else { + throw new RunException("Position %d: Parameter '%s' ist überflüssig", z, arg); + } + if(param == null) + throw new RunException("Position %d: Argument '%s' ist unbekannt", z, arg); + if(args.containsKey(param.getName())) + throw new RunException("Position %d: Parameter '%s' mehrfach angegeben", z, param.getName()); + int nargs = param.getParsers().size(); +// if(!pos) +// z += 1; + if(z + (pos ? 0 : 1) + nargs > argv.length) + if(nargs == 1 && param.getName().equals(param.getParsers().get(0).getName())) + throw new RunException("Position %d: Argument '%s' benötigt einen Parameter", z, param.getName()); + else + throw new RunException("Position %d: Argument '%s' benötigt %d Parameter (%s)", z, param.getName(), nargs, + joinArgs(param.getParsers())); + Map params = Maps.newHashMapWithExpectedSize(nargs); + String[] inputs = new String[nargs + (pos ? 0 : 1)]; + int apos = 0; + for(int n = pos ? 0 : 1; n < nargs + (pos ? 0 : 1); n++) { + String par = inputs[n] = argv[z + n]; + ArgumentParser parser = param.getParsers().get(apos); + if(parse && (par.startsWith("--") || (par.startsWith("-") && par.length() == 2))) + if(nargs == 1 && param.getName().equals(parser.getName())) + throw new RunException("Position %d: Argument '%s': '%s' als Parameter verwendet", z + n, param.getName(), par); + else + throw new RunException("Position %d: Argument '%s': '%s' als Parameter '%s' (#%d) verwendet", z + n, + param.getName(), par, parser.getName(), apos + 1); + try { + params.put(parser.getName(), parser.parse(env, par)); + } + catch(Throwable e) { + if(nargs == 1 && param.getName().equals(parser.getName())) + throw new RunException(e, "Position %d: Argument '%s': Parameter konnte nicht interpretiert werden", z + n, + param.getName()); + else + throw new RunException(e, "Position %d: Argument '%s': Parameter '%s' (#%d) konnte nicht interpretiert werden", z + n, + param.getName(), parser.getName(), apos + 1); + } + apos += 1; + } + if(!pos) + inputs[0] = arg; + args.put(param.getName(), new Argument(param, z, inputs, params)); + z += nargs - (pos ? 1 : 0); + } + for(Parameter param : parameters.values()) { + if(!args.containsKey(param.getName())) { + if(param.isRequired()) { + for(ArgumentParser parser : param.getParsers()) { + if(parser.getDefault(env) == null) + throw new RunException("Argument '%s' muss angegeben werden", param.getName()); + } + } + else if(param.getParsers().isEmpty()) { + continue; + } + Map params = Maps.newHashMapWithExpectedSize(param.getParsers().size()); + for(ArgumentParser parser : param.getParsers()) { + params.put(parser.getName(), parser.getDefault(env)); + } + args.put(param.getName(), new Argument(param, -1, null, params)); + } + } + return new ArgumentSplitter(args, str, env); + } + + private static Iterable getParam(CommandEnvironment env, String[] argv, CachedExecutable cached) { + Map parameters = cached.getParameters(); + List positionals = Lists.newArrayList(cached.getPositionals()); + Set args = Sets.newHashSet(); + int ppos = 0; + boolean parse = true; + for(int z = 1; z < argv.length; z++) { + String arg = argv[z]; + Parameter param = null; + boolean pos = false; + if(z == argv.length - 1) { + if(ppos < positionals.size()) { + param = positionals.get(ppos); + if(param.getParsers().isEmpty()) // np + return null; + return param.getParsers().get(0).getCompletions(env); + } + else { + return null; + } + } + else if(parse && arg.equals("--")) { + parse = false; + continue; + } + else if(parse && (arg.startsWith("--") || (arg.startsWith("-") && arg.length() == 2))) { + param = parameters.get(arg.substring(arg.startsWith("--") ? 2 : 1)); + if(param != null && param.isPositional() && !args.contains(param.getName())) { + for(int n = 0; n < positionals.size(); n++) { + if(param == positionals.get(n)) { + positionals.remove(n); + break; + } + } + } + } + else if(ppos < positionals.size()) { + param = positionals.get(ppos++); + pos = true; + } + else { + return null; + } + if(param == null || args.contains(param.getName())) + return null; + int nargs = param.getParsers().size(); +// if(z + (pos ? 0 : 1) + nargs > argv.length - 1) { +// return param.getParsers().get(argv.length - z).getCompletions(env); +// } + int apos = 0; + for(int n = pos ? 0 : 1; n < nargs + (pos ? 0 : 1); n++) { + if(z + n == argv.length - 1) + return param.getParsers().get(apos).getCompletions(env); + String par = argv[z + n]; + if(parse && (par.startsWith("--") || (par.startsWith("-") && par.length() == 2))) + return null; + apos += 1; + } + args.add(param.getName()); + z += nargs - (pos ? 1 : 0); + } + return null; + } + + public static Iterable parseComplete(CommandEnvironment env, String[] argv, CachedExecutable cached, String last) { + Iterable comp = getParam(env, argv, cached); + if(comp == null /* || comp.length == 0 */ ) { + Set params = Sets.newTreeSet(); + boolean all = last.startsWith("--"); + for(String param : cached.getParameters().keySet()) { + if(all || param.length() == 1) + params.add(param.length() == 1 ? "-" + param : ("--" + param)); + } + return params; + } + return comp; + } + +// public ScriptArg getArg(String name) { +// return this.arguments.get(name); +// } + + public boolean hasArg(String name) { + return this.arguments.containsKey(name); + } + +// public boolean has(String name, String par) { +// return this.arguments.containsKey(name) && this.arguments.get(name).getValues().containsKey(par); +// } + +// public boolean has(String name) { +// return this.has(name, name); +// } + +// public T getDefault(String name, String par, T def) { +// ScriptArg arg = this.arguments.get(name); +// if(arg == null) +// return def; +// Object value = arg.getValues().get(par); +// return value == null ? def : (T)value; +// } +// +// public T getDefault(String name, T def) { +// return this.getDefault(name, name, def); +// } +// +// public T getUnchecked(String name, String par) { +// return this.getDefault(name, par, null); +// } + + public T getUnchecked(String name, String par) { + Argument arg = this.arguments.get(name); + if(arg == null) + return null; + Object value = arg.getValues().get(par); + return value == null ? null : (T)value; + } + +// public T getUnchecked(String name) { +// return this.getDefault(name, null); +// } +// +// public boolean getBool(String name, boolean def) { +// return this.getDefault(name, def); +// } +// +// public boolean getBool(String name) { +// return this.getUnchecked(name); +// } +// +// public > T getEnum(String name, T def) { +// return this.getDefault(name, def); +// } +// +// public > T getEnum(String name) { +// return this.getUnchecked(name); +// } +// +// public int getInt(String name, int def) { +// return this.getDefault(name, def); +// } +// +// public int getInt(String name) { +// return this.getUnchecked(name); +// } +// +// public long getLong(String name, long def) { +// return this.getDefault(name, def); +// } +// +// public long getLong(String name) { +// return this.getUnchecked(name); +// } +// +// public double getDouble(String name, double def) { +// return this.getDefault(name, def); +// } +// +// public double getDouble(String name) { +// return this.getUnchecked(name); +// } +// +// public String getString(String name, String def) { +// return this.getDefault(name, def); +// } +// +// public String getString(String name) { +// return this.getUnchecked(name); +// } +// +// public String[] getStrings(String name, String[] def) { +// return this.getDefault(name, def); +// } +// +// public String[] getStrings(String name) { +// return this.getUnchecked(name); +// } +// +// public Entity getEntity(String name, Entity def) { +// return this.getDefault(name, def); +// } +// +// public Entity getEntity(String name) { +// return this.getUnchecked(name); +// } +// +// public EntityLiving getLiving(String name, EntityLiving def) { +// return this.getDefault(name, def); +// } +// +// public EntityLiving getLiving(String name) { +// return this.getUnchecked(name); +// } +// +// public EntityNPC getNpc(String name, EntityNPC def) { +// return this.getDefault(name, def); +// } +// +// public EntityNPC getNpc(String name) { +// return this.getUnchecked(name); +// } +// +// public Block getBlock(String name, Block def) { +// return this.getDefault(name, def); +// } +// +// public Block getBlock(String name) { +// return this.getUnchecked(name); +// } +// +// public State getState(String name, State def) { +// return this.getDefault(name, def); +// } +// +// public State getState(String name) { +// return this.getUnchecked(name); +// } +// +// public Item getItem(String name, Item def) { +// return this.getDefault(name, def); +// } +// +// public Item getItem(String name) { +// return this.getUnchecked(name); +// } +// +// public ItemStack getStack(String name, ItemStack def) { +// return this.getDefault(name, def); +// } +// +// public ItemStack getStack(String name) { +// return this.getUnchecked(name); +// } +// +// public BlockPos getColumnPos(String name, BlockPos def) { +// return this.hasArg(name) ? this.getColumnPos(name) : def; +// } +// +// public BlockPos getColumnPos(String name) { +// return new BlockPos(this.getUnchecked(name, "x"), 0, this.getUnchecked(name, "z")); +// } +// +// public BlockPos getBlockPos(String name, BlockPos def) { +// return this.hasArg(name) ? this.getBlockPos(name) : def; +// } +// +// public BlockPos getBlockPos(String name) { +// return new BlockPos(this.getUnchecked(name, "x"), this.getUnchecked(name, "y"), this.getUnchecked(name, "z")); +// } +// +// public WorldPos getWorldPos(String name, WorldPos def) { +// return this.hasArg(name) ? this.getWorldPos(name) : def; +// } +// +// public WorldPos getWorldPos(String name) { +// return new WorldPos(this.getUnchecked(name, "x"), this.getUnchecked(name, "y"), this.getUnchecked(name, "z"), +// this.getUnchecked(name, "dim")); +// } +// +// public Vec3 getVector2D(String name, Vec3 def) { +// return this.hasArg(name) ? this.getVector2D(name) : def; +// } +// +// public Vec3 getVector2D(String name) { +// return new Vec3(this.getUnchecked(name, "x"), 0.0, this.getUnchecked(name, "z")); +// } +// +// public Vec3 getVector(String name, Vec3 def) { +// return this.hasArg(name) ? this.getVector(name) : def; +// } +// +// public Vec3 getVector(String name) { +// return new Vec3(this.getUnchecked(name, "x"), this.getUnchecked(name, "y"), this.getUnchecked(name, "z")); +// } +// +// public WorldServer getWorld(String name) { +// return this.getUnchecked(name); +// } +// +// public NBTTagCompound getTag(String name) { +// return this.getUnchecked(name); +// } +} diff --git a/server/src/main/java/server/command/BooleanParser.java b/server/src/server/command/BooleanParser.java similarity index 100% rename from server/src/main/java/server/command/BooleanParser.java rename to server/src/server/command/BooleanParser.java diff --git a/server/src/main/java/server/command/CachedExecutable.java b/server/src/server/command/CachedExecutable.java similarity index 51% rename from server/src/main/java/server/command/CachedExecutable.java rename to server/src/server/command/CachedExecutable.java index 031ecfe..97344af 100644 --- a/server/src/main/java/server/command/CachedExecutable.java +++ b/server/src/server/command/CachedExecutable.java @@ -7,7 +7,21 @@ import java.util.Map; import common.collect.Lists; import common.collect.Maps; -public record CachedExecutable(Executable executable, Map parameters, List positionals, Method method) { +public class CachedExecutable { + private final Executable executable; + private final String name; + private final Map parameters; + private final List positionals; + private final Method method; + + protected CachedExecutable(Executable executable, Map parameters, List positionals, Method method) { + this.executable = executable; + this.parameters = parameters; + this.positionals = positionals; + this.name = executable.getName(); + this.method = method; + } + public static CachedExecutable cacheExecutable(Executable executable) { Map parameters = Maps.newTreeMap(); Map params = executable.getParameters(); @@ -15,12 +29,12 @@ public record CachedExecutable(Executable executable, Map par Parameter[] positions = new Parameter[parameters.size()]; int pos = -1; for(Parameter param : params.values()) { - if(param.positional()) { - positions[param.position()] = param; - pos = param.position() > pos ? param.position() : pos; + if(param.isPositional()) { + positions[param.getPosition()] = param; + pos = param.getPosition() > pos ? param.getPosition() : pos; } - if(param.shorthand()) - parameters.put("" + param.shortName(), param); + if(param.hasShortName()) + parameters.put("" + param.getShortName(), param); } List positionals = Lists.newArrayList(); for(int z = 0; z <= pos; z++) { @@ -30,17 +44,17 @@ public record CachedExecutable(Executable executable, Map par } List> classes = Lists.newArrayList(CommandEnvironment.class, Executor.class); for(Parameter param : executable.getParamList()) { - ArgCombiner combiner = param.combiner(); + ArgCombiner combiner = param.getCombiner(); if(combiner != null) { classes.add(combiner.getTypeClass()); continue; } - if(param.parsers().isEmpty()) { + if(param.getParsers().isEmpty()) { classes.add(boolean.class); continue; } - for(ArgumentParser parser : param.parsers()) { - classes.add(parser.getTypeClass(param.required())); + for(ArgumentParser parser : param.getParsers()) { + classes.add(parser.getTypeClass(param.isRequired())); } } Method method; @@ -53,11 +67,27 @@ public record CachedExecutable(Executable executable, Map par return new CachedExecutable(executable, parameters, positionals, method); } - public String name() { - return this.executable.getName(); + public Executable getExecutable() { + return this.executable; + } + + public Method getMethod() { + return this.method; + } + + public Map getParameters() { + return this.parameters; + } + + public List getPositionals() { + return this.positionals; + } + + public String getName() { + return this.name; } public String toString() { - return this.executable.getName(); + return this.name; } } diff --git a/server/src/main/java/server/command/ColorParser.java b/server/src/server/command/ColorParser.java similarity index 100% rename from server/src/main/java/server/command/ColorParser.java rename to server/src/server/command/ColorParser.java diff --git a/server/src/main/java/server/command/Command.java b/server/src/server/command/Command.java similarity index 72% rename from server/src/main/java/server/command/Command.java rename to server/src/server/command/Command.java index 25e0cb5..e58b0d7 100644 --- a/server/src/main/java/server/command/Command.java +++ b/server/src/server/command/Command.java @@ -7,12 +7,10 @@ import java.util.Map; import common.collect.Lists; import common.collect.Maps; -import common.util.BlockPos; import common.util.CharValidator; import common.util.Vec3; import common.world.World; import server.command.DoubleParser.DefType; -import server.command.IntParser.CoordType; public abstract class Command implements Executable { private final String name; @@ -31,11 +29,6 @@ public abstract class Command implements Executable { return this; } - protected Command setParamsRequired() { - this.parReq = true; - return this; - } - protected Command addParameter(String name, ArgCombiner combiner, ArgumentParser ... parsers) { Parameter param = new Parameter(name, (char)0, this.parPos++, this.parReq, Lists.newArrayList(parsers), combiner); this.parameters.put(name, param); @@ -44,7 +37,7 @@ public abstract class Command implements Executable { } protected Command addParameter(String name, char shortName, ArgCombiner combiner, ArgumentParser ... parsers) { - Parameter param = new Parameter(name, shortName, -1, this.parReq, Lists.newArrayList(parsers), combiner); + Parameter param = new Parameter(name, shortName, -1, false, Lists.newArrayList(parsers), combiner); this.parameters.put(name, param); this.argList.add(param); return this; @@ -81,29 +74,10 @@ public abstract class Command implements Executable { } }, new DoubleParser("x", defaulted ? DefType.X : null, (double)(-World.MAX_SIZE), (double)World.MAX_SIZE, centered), - new DoubleParser("y", defaulted ? DefType.Y : null, (double)(-World.MAX_SIZE_Y), (double)World.MAX_SIZE_Y, false), + new DoubleParser("y", defaulted ? DefType.Y : null, 0.0, (double)World.HEIGHT, false), new DoubleParser("z", defaulted ? DefType.Z : null, (double)(-World.MAX_SIZE), (double)World.MAX_SIZE, centered)); } - protected Command addBlockPos(String name, boolean defaulted) { - return this.addParameter(name, new ArgCombiner() { - public BlockPos combine(Integer[] values) { - return new BlockPos(values[0], values[1], values[2]); - } - - public Class getTypeClass() { - return BlockPos.class; - } - - public Class getInputClass() { - return Integer.class; - } - }, - new IntParser("x", defaulted ? CoordType.X : null, -World.MAX_SIZE, World.MAX_SIZE), - new IntParser("y", defaulted ? CoordType.Y : null, -World.MAX_SIZE_Y, World.MAX_SIZE_Y), - new IntParser("z", defaulted ? CoordType.Z : null, -World.MAX_SIZE, World.MAX_SIZE)); - } - protected Command addWorld(String name, boolean defaulted) { return this.addParameter(new WorldParser(name, false, defaulted)); } @@ -180,60 +154,36 @@ public abstract class Command implements Executable { return this.addParameter(shortName, new TagParser(name, null)); } - protected Command addUser(String name, boolean defaulted, UserPolicy policy) { - return this.addParameter(new UserParser(name, defaulted, policy)); + protected Command addPlayer(String name, boolean defaulted) { + return this.addParameter(new PlayerParser(name, defaulted)); } - protected Command addPlayer(String name, boolean defaulted, UserPolicy policy) { - return this.addParameter(new PlayerParser(name, defaulted, policy)); + protected Command addPlayerEntity(String name, boolean defaulted) { + return this.addParameter(new PlayerEntityParser(name, defaulted)); } - protected Command addPlayerList(String name, boolean defaulted, UserPolicy policy) { - return this.addParameter(new PlayerListParser(name, defaulted, policy)); + protected Command addEntity(String name, boolean defaulted) { + return this.addParameter(new EntityParser(name, defaulted, false)); } - protected Command addPlayerEntity(String name, boolean defaulted, UserPolicy policy) { - return this.addParameter(new PlayerEntityParser(name, defaulted, policy)); + protected Command addEntity(String name, char shortName, boolean defaulted) { + return this.addParameter(shortName, new EntityParser(name, defaulted, false)); } - protected Command addPlayerItem(String name, boolean defaulted, UserPolicy policy) { - return this.addParameter(new PlayerItemParser(name, defaulted, policy)); + protected Command addEntityList(String name, boolean defaulted) { + return this.addParameter(new EntityListParser(name, defaulted, false)); } - protected Command addPlayerItem(String name, char shortName, boolean defaulted, UserPolicy policy) { - return this.addParameter(shortName, new PlayerItemParser(name, defaulted, policy)); + protected Command addEntityList(String name, char shortName, boolean defaulted) { + return this.addParameter(shortName, new EntityListParser(name, defaulted, false)); } - protected Command addPlayerEntityList(String name, boolean defaulted, UserPolicy policy) { - return this.addParameter(new PlayerEntityListParser(name, defaulted, policy)); + protected Command addLivingEntity(String name, boolean defaulted) { + return this.addParameter(new EntityParser(name, defaulted, true)); } - protected Command addPlayerEntityList(String name, char shortName, boolean defaulted, UserPolicy policy) { - return this.addParameter(shortName, new PlayerEntityListParser(name, defaulted, policy)); - } - - protected Command addEntity(String name, boolean defaulted, UserPolicy policy) { - return this.addParameter(new EntityParser(name, defaulted, false, policy)); - } - - protected Command addEntity(String name, char shortName, boolean defaulted, UserPolicy policy) { - return this.addParameter(shortName, new EntityParser(name, defaulted, false, policy)); - } - - protected Command addEntityList(String name, boolean defaulted, UserPolicy policy) { - return this.addParameter(new EntityListParser(name, defaulted, false, policy)); - } - - protected Command addEntityList(String name, char shortName, boolean defaulted, UserPolicy policy) { - return this.addParameter(shortName, new EntityListParser(name, defaulted, false, policy)); - } - - protected Command addLivingEntity(String name, boolean defaulted, UserPolicy policy) { - return this.addParameter(new EntityParser(name, defaulted, true, policy)); - } - - protected Command addLivingEntityList(String name, boolean defaulted, UserPolicy policy) { - return this.addParameter(new EntityListParser(name, defaulted, true, policy)); + protected Command addLivingEntityList(String name, boolean defaulted) { + return this.addParameter(new EntityListParser(name, defaulted, true)); } protected Command addString(String name, boolean allowEmpty, Object ... completions) { diff --git a/server/src/main/java/server/command/CommandEnvironment.java b/server/src/server/command/CommandEnvironment.java similarity index 66% rename from server/src/main/java/server/command/CommandEnvironment.java rename to server/src/server/command/CommandEnvironment.java index 4fa070c..bb85367 100644 --- a/server/src/main/java/server/command/CommandEnvironment.java +++ b/server/src/server/command/CommandEnvironment.java @@ -6,7 +6,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; -import java.util.regex.Pattern; import common.collect.Lists; import common.collect.Maps; @@ -14,7 +13,28 @@ import common.collect.Sets; import common.color.TextColor; import common.log.Log; import server.Server; -import server.command.commands.*; +import server.command.commands.CommandAdmin; +import server.command.commands.CommandHelp; +import server.command.commands.CommandKick; +import server.command.commands.CommandMessage; +import server.command.commands.CommandMilk; +import server.command.commands.CommandOfflinetp; +import server.command.commands.CommandPasswd; +import server.command.commands.CommandPlayers; +import server.command.commands.CommandPotion; +import server.command.commands.CommandRebind; +import server.command.commands.CommandRegister; +import server.command.commands.CommandRemove; +import server.command.commands.CommandRevoke; +import server.command.commands.CommandSave; +import server.command.commands.CommandShutdown; +import server.command.commands.CommandSpawn; +import server.command.commands.CommandTele; +import server.command.commands.CommandTime; +import server.command.commands.CommandTp; +import server.command.commands.CommandWarp; +import server.command.commands.CommandWeather; +import server.command.commands.CommandWorld; public class CommandEnvironment { private final Server server; @@ -33,10 +53,10 @@ public class CommandEnvironment { public void registerExecutable(Executable executable) { CachedExecutable cached = CachedExecutable.cacheExecutable(executable); - if(this.executables.containsKey(cached.name())) - throw new IllegalStateException("Befehl " + cached.name() + " ist bereits registriert"); - this.executables.put(cached.name(), cached); - this.registerReplacer(cached.name(), new Function() { + if(this.executables.containsKey(cached.getName())) + throw new IllegalStateException("Befehl " + cached.getName() + " ist bereits registriert"); + this.executables.put(cached.getName(), cached); + this.registerReplacer(cached.getName(), new Function() { public String apply(String str) { Object o; try { @@ -55,14 +75,14 @@ public class CommandEnvironment { public void registerReplacer(String var, Function function) { if(this.builtins.contains(var)) throw new IllegalStateException("Variable " + var + " ist bereits registriert"); - this.replacers.add(new PatternReplacer(Pattern.compile("\\$\\((" + Pattern.quote(var) + "[^\\)]*)\\)"), function)); + this.replacers.add(new PatternReplacer(var, true, function)); this.builtins.add(var); } public void registerVariable(String var, Variable variable) { if(this.builtins.contains(var)) throw new IllegalStateException("Variable " + var + " ist bereits registriert"); - this.replacers.add(new PatternReplacer(Pattern.compile("\\$\\((" + Pattern.quote(var) + ")\\)"), new Function() { + this.replacers.add(new PatternReplacer(var, false, new Function() { public String apply(String ign) { return variable.get(); } @@ -85,7 +105,7 @@ public class CommandEnvironment { private String substitute(String str) { StringBuffer sb = new StringBuffer(str); for(PatternReplacer replacer : this.replacers) { - replacer.replace(sb); + replacer.replaceVar(sb); } return sb.toString(); } @@ -115,12 +135,12 @@ public class CommandEnvironment { } ArgumentSplitter args = ArgumentSplitter.parseArgs(this, cmd, argv, cached); List params = Lists.newArrayList(this, this.currentExecutor); - for(Parameter param : cached.executable().getParamList()) { - ArgCombiner combiner = param.combiner(); + for(Parameter param : cached.getExecutable().getParamList()) { + ArgCombiner combiner = param.getCombiner(); if(combiner != null) { - Object[] data = (Object[])Array.newInstance(combiner.getInputClass(), param.parsers().size()); + Object[] data = (Object[])Array.newInstance(combiner.getInputClass(), param.getParsers().size()); for(int z = 0; z < data.length; z++) { - data[z] = args.get(param.name(), param.parsers().get(z).getName()); + data[z] = args.getUnchecked(param.getName(), param.getParsers().get(z).getName()); if(data[z] == null) { data = null; break; @@ -129,16 +149,16 @@ public class CommandEnvironment { params.add(data == null ? null : combiner.combine(data)); continue; } - if(param.parsers().isEmpty()) { - params.add(args.has(param.name())); + if(param.getParsers().isEmpty()) { + params.add(args.hasArg(param.getName())); continue; } - for(ArgumentParser parser : param.parsers()) { - params.add(args.get(param.name(), parser.getName())); + for(ArgumentParser parser : param.getParsers()) { + params.add(args.getUnchecked(param.getName(), parser.getName())); } } try { - o = cached.method().invoke(cached.executable(), params.toArray(new Object[params.size()])); + o = cached.getMethod().invoke(cached.getExecutable(), params.toArray(new Object[params.size()])); } catch(InvocationTargetException e) { if(e.getCause() instanceof RuntimeException) @@ -163,7 +183,6 @@ public class CommandEnvironment { } public void execute(String cmd, Executor exec) { - Executor prev = this.currentExecutor; this.currentExecutor = exec; try { this.execute(cmd, true); @@ -171,17 +190,17 @@ public class CommandEnvironment { catch(RunException e) { Throwable cause = e; do { - exec.log(TextColor.RED + cause.getMessage()); + exec.logConsole(TextColor.RED + cause.getMessage()); cause = cause.getCause(); } while(cause != null); } catch(Throwable t) { - exec.log(TextColor.RED + "Fehler: %s", t.getMessage()); + exec.logConsole(TextColor.RED + "Fehler: %s", t.getMessage()); Log.CONSOLE.error(t, "Fehler beim Ausführen von Befehl '%s'", cmd); } finally { - this.currentExecutor = prev; + this.currentExecutor = null; this.previousOutput = null; this.variables.clear(); } @@ -192,18 +211,22 @@ public class CommandEnvironment { List list = Lists.newArrayList(); try { String[][] cmds = ArgumentParser.splitString(cmd.endsWith(" ") ? cmd + "END" : cmd); - Iterable comp = this.executables.keySet(); - String param = cmd; - if(cmds.length > 0 && cmds[cmds.length - 1].length > 0) { - String[] argv = cmds[cmds.length - 1]; - param = cmd.endsWith(" ") ? "" : argv[argv.length - 1]; - if(argv.length > 1) { - int eq = argv[0].indexOf('='); - CachedExecutable cached = this.executables.get(eq >= 0 ? argv[0].substring(eq + 1) : argv[0]); - if(cached == null) - return list; - comp = ArgumentSplitter.parseComplete(this, argv, cached, param); - } + if(cmds.length == 0) + return list; + String[] argv = cmds[cmds.length - 1]; + if(argv.length == 0) + return list; + String param = cmd.endsWith(" ") ? "" : argv[argv.length - 1]; + Iterable comp; + if(argv.length > 1) { + int eq = argv[0].indexOf('='); + CachedExecutable cached = this.executables.get(eq >= 0 ? argv[0].substring(eq + 1) : argv[0]); + if(cached == null) + return list; + comp = ArgumentSplitter.parseComplete(this, argv, cached, param); + } + else { + comp = this.executables.keySet(); } for(String cmp : comp) { if(cmp.regionMatches(true, 0, param, 0, param.length())) @@ -212,8 +235,7 @@ public class CommandEnvironment { } catch(Throwable t) { list.clear(); - if(!(t instanceof RunException)) - Log.CONSOLE.error(t, "Konnte Befehl '%s' nicht vervollständigen", cmd); + Log.CONSOLE.error(t, "Konnte Befehl '%s' nicht vervollständigen", cmd); } finally { this.currentExecutor = null; @@ -222,13 +244,22 @@ public class CommandEnvironment { } public void registerDefaults() { + this.registerVariable("*", new Variable() { + public String get() { + return CommandEnvironment.this.currentExecutor.getExecId(); + } + }); + this.registerVariable("name", new Variable() { + public String get() { + return CommandEnvironment.this.currentExecutor.getExecName(); + } + }); this.registerVariable("!", new Variable() { public String get() { return CommandEnvironment.this.previousOutput == null ? null : CommandEnvironment.this.previousOutput.toString(); } }); - this.registerExecutable(new CommandHelp()); this.registerExecutable(new CommandSpawn()); this.registerExecutable(new CommandPotion()); this.registerExecutable(new CommandMilk()); @@ -245,30 +276,12 @@ public class CommandEnvironment { this.registerExecutable(new CommandKick()); this.registerExecutable(new CommandMessage()); this.registerExecutable(new CommandShutdown()); + this.registerExecutable(new CommandRebind()); this.registerExecutable(new CommandPasswd()); - this.registerExecutable(new CommandPubkey()); this.registerExecutable(new CommandPlayers()); - this.registerExecutable(new CommandUsers()); this.registerExecutable(new CommandSave()); this.registerExecutable(new CommandRegister()); - this.registerExecutable(new CommandRegkey()); - this.registerExecutable(new CommandFind()); - this.registerExecutable(new CommandBlock()); - this.registerExecutable(new CommandSeed()); - this.registerExecutable(new CommandSv()); - this.registerExecutable(new CommandClear()); - this.registerExecutable(new CommandEntity()); - this.registerExecutable(new CommandItem()); - this.registerExecutable(new CommandRunat()); - this.registerExecutable(new CommandRunas()); - this.registerExecutable(new CommandExp()); - this.registerExecutable(new CommandMagic()); - this.registerExecutable(new CommandGod()); - this.registerExecutable(new CommandNoclip()); - this.registerExecutable(new CommandRename()); - this.registerExecutable(new CommandRepair()); - this.registerExecutable(new CommandMore()); - this.registerExecutable(new CommandReturn()); - this.registerExecutable(new CommandDeathspot()); + + this.registerExecutable(new CommandHelp(this)); } } diff --git a/server/src/main/java/server/command/Completer.java b/server/src/server/command/Completer.java similarity index 100% rename from server/src/main/java/server/command/Completer.java rename to server/src/server/command/Completer.java diff --git a/server/src/main/java/server/command/CompletingParser.java b/server/src/server/command/CompletingParser.java similarity index 79% rename from server/src/main/java/server/command/CompletingParser.java rename to server/src/server/command/CompletingParser.java index 154f7a4..21c7de1 100644 --- a/server/src/main/java/server/command/CompletingParser.java +++ b/server/src/server/command/CompletingParser.java @@ -4,8 +4,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import common.util.Identifyable; - public abstract class CompletingParser extends ArgumentParser { private final List defCompletions; @@ -13,7 +11,7 @@ public abstract class CompletingParser extends ArgumentParser { super(name); this.defCompletions = new ArrayList(completions.length); for(Object comp : completions) { - this.defCompletions.add(comp instanceof Identifyable id ? id.getName() : String.valueOf(comp)); + this.defCompletions.add(String.valueOf(comp)); } } diff --git a/server/src/main/java/server/command/DefaultingParser.java b/server/src/server/command/DefaultingParser.java similarity index 100% rename from server/src/main/java/server/command/DefaultingParser.java rename to server/src/server/command/DefaultingParser.java diff --git a/server/src/main/java/server/command/DimensionParser.java b/server/src/server/command/DimensionParser.java similarity index 99% rename from server/src/main/java/server/command/DimensionParser.java rename to server/src/server/command/DimensionParser.java index f941da9..6263114 100644 --- a/server/src/main/java/server/command/DimensionParser.java +++ b/server/src/server/command/DimensionParser.java @@ -34,7 +34,7 @@ public class DimensionParser extends CompletingParser { if(!this.useSender) return null; Position pos = env.getExecutor().getExecPos(); - return pos == null ? null : UniverseRegistry.getDimension(pos.dim()); + return pos == null ? null : UniverseRegistry.getDimension(pos.dim); // if(dim == null) // throw new ScriptException("Unbekannte Dimension '%s'"); } diff --git a/server/src/main/java/server/command/DoubleParser.java b/server/src/server/command/DoubleParser.java similarity index 81% rename from server/src/main/java/server/command/DoubleParser.java rename to server/src/server/command/DoubleParser.java index 93a5a5c..5b57bdb 100644 --- a/server/src/main/java/server/command/DoubleParser.java +++ b/server/src/server/command/DoubleParser.java @@ -36,21 +36,14 @@ public class DoubleParser extends DefaultingParser { Double pre = this.defType != null && input.startsWith("~") ? this.getDefault(env) : null; input = pre != null ? input.substring(1) : input; double value; - if(pre != null && input.isEmpty()) { - value = pre; + try { + value = Double.parseDouble(input); } - else { - try { - value = Double.parseDouble(input); - } - catch(NumberFormatException e) { - throw new RunException("Ungültige Gleitkommazahl '%s'", input); - } - if(this.center && pre == null && input.indexOf('.') < 0) - value += 0.5; - else if(pre != null) - value = pre + value; + catch(NumberFormatException e) { + throw new RunException("Ungültige Gleitkommazahl '%s'", input); } + if(this.center && pre == null && input.indexOf('.') < 0) + value += 0.5; if(this.min != null && value < this.min) if(this.max != null) throw new RunException("Die Zahl muss im Bereich %f .. %f liegen, habe %f", this.min, this.max, value); @@ -69,15 +62,15 @@ public class DoubleParser extends DefaultingParser { if(this.defType != null) switch(this.defType) { case X: - return pos == null ? null : pos.x(); + return pos == null ? null : pos.x; case Y: - return pos == null ? null : pos.y(); + return pos == null ? null : pos.y; case Z: - return pos == null ? null : pos.z(); + return pos == null ? null : pos.z; case YAW: - return pos == null ? null : (double)pos.yaw(); + return pos == null ? null : (double)pos.yaw; case PITCH: - return pos == null ? null : (double)pos.pitch(); + return pos == null ? null : (double)pos.pitch; } return (Double)super.getDefault(env); } diff --git a/server/src/main/java/server/command/EntityListParser.java b/server/src/server/command/EntityListParser.java similarity index 76% rename from server/src/main/java/server/command/EntityListParser.java rename to server/src/server/command/EntityListParser.java index 1238856..fda515d 100644 --- a/server/src/main/java/server/command/EntityListParser.java +++ b/server/src/server/command/EntityListParser.java @@ -9,46 +9,42 @@ import common.collect.Lists; import common.collect.Sets; import common.entity.Entity; import common.entity.EntityType; -import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.EntityRegistry; import server.network.Player; import server.world.WorldServer; public class EntityListParser extends EntityParser { - public EntityListParser(String name, boolean useSender, boolean livingOnly, UserPolicy policy) { - super(name, useSender, livingOnly, policy); + public EntityListParser(String name, boolean useSender, boolean livingOnly) { + super(name, useSender, livingOnly); } public Object parse(CommandEnvironment env, String input) { if(input.equals("**")) { List list = Lists.newArrayList(); - boolean found = false; for(WorldServer world : env.getServer().getWorlds()) { - for(Entity ent : world.getEntities()) { - if(!this.livingOnly || ent instanceof EntityLiving) { - found = true; - if(!(ent instanceof EntityNPC) || !((EntityNPC)ent).isPlayer() || this.policy.applies(env, env.getExecutor(), (Player)((EntityNPC)ent).connection)) + if(this.livingOnly) { + for(Entity ent : world.getEntities()) { + if(ent instanceof EntityLiving) list.add(ent); } } + else { + list.addAll(world.getEntities()); + } } if(list.isEmpty()) - throw new RunException(this.livingOnly ? "Keine " + (found ? "erlaubten" : "lebendigen") + " Objekte gefunden" : "Keine " + (found ? "erlaubten " : "") + "Objekte gefunden"); + throw new RunException(this.livingOnly ? "Keine lebendigen Objekte gefunden" : "Keine Objekte gefunden"); return list; } else if(input.equals("*")) { List list = Lists.newArrayList(); - boolean found = false; for(Player plr : env.getServer().getPlayers()) { - if(plr.getPresentEntity() != null) { - found = true; - if(this.policy.applies(env, env.getExecutor(), plr)) - list.add(plr.getPresentEntity()); - } + if(plr.getPresentEntity() != null) + list.add(plr.getPresentEntity()); } if(list.isEmpty()) - throw new RunException("Keine " + (found ? "erlaubten " : "") + "Spieler gefunden"); + throw new RunException("Keine Spieler gefunden"); return list; } Set> classes = Sets.newHashSet(); @@ -99,22 +95,18 @@ public class EntityListParser extends EntityParser { } List filtered = Lists.newArrayList(entities); boolean negateOnly = (living == null && player == null && types.isEmpty() && classes.isEmpty() && entities.isEmpty()); - boolean found = false; for(WorldServer world : env.getServer().getWorlds()) { for(Entity ent : world.getEntities()) { if((!this.livingOnly || ent instanceof EntityLiving) && (negateOnly || (living != null && types.isEmpty() && classes.isEmpty() && living == (ent instanceof EntityLiving)) || (player != null && types.isEmpty() && classes.isEmpty() && player == ent.isPlayer()) || types.contains(ent.getType()) || classes.contains(ent.getClass())) && (living == null || living == (ent instanceof EntityLiving)) && (player == null || player == ent.isPlayer()) && - !ntypes.contains(ent.getType()) && !nclasses.contains(ent.getClass()) && !nentities.contains(ent) && !entities.contains(ent)) { - found = true; - if(!(ent instanceof EntityNPC) || !((EntityNPC)ent).isPlayer() || this.policy.applies(env, env.getExecutor(), (Player)((EntityNPC)ent).connection)) - filtered.add(ent); - } + !ntypes.contains(ent.getType()) && !nclasses.contains(ent.getClass()) && !nentities.contains(ent) && !entities.contains(ent)) + filtered.add(ent); } } if(filtered.isEmpty()) - throw new RunException("Keine " + (found ? "erlaubten " : "") + "Objekte gefunden"); + throw new RunException("Keine Objekte gefunden"); return filtered; } @@ -125,8 +117,7 @@ public class EntityListParser extends EntityParser { public Collection getCompletions(CommandEnvironment env) { Collection comp = super.getCompletions(env); - if(this.policy != UserPolicy.NO_PLAYERS) - comp.add("*"); + comp.add("*"); for(Class clazz : EntityRegistry.getAllClasses()) { if(!this.livingOnly || EntityLiving.class.isAssignableFrom(clazz)) comp.add(EntityRegistry.getEntityString(clazz)); @@ -134,9 +125,7 @@ public class EntityListParser extends EntityParser { for(EntityType type : EntityType.values()) { comp.add(type.getName()); } - if(this.policy != UserPolicy.NO_PLAYERS) - comp.add("Player"); - Collections.addAll(comp, "Living", "**"); + Collections.addAll(comp, "Player", "Living", "**"); return comp; } diff --git a/server/src/main/java/server/command/EntityParser.java b/server/src/server/command/EntityParser.java similarity index 72% rename from server/src/main/java/server/command/EntityParser.java rename to server/src/server/command/EntityParser.java index 193c640..e570d98 100644 --- a/server/src/main/java/server/command/EntityParser.java +++ b/server/src/server/command/EntityParser.java @@ -5,16 +5,14 @@ import java.util.List; import common.collect.Lists; import common.entity.Entity; -import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; -import server.network.Player; import server.world.WorldServer; public class EntityParser extends PlayerEntityParser { protected final boolean livingOnly; - public EntityParser(String name, boolean useSender, boolean livingOnly, UserPolicy policy) { - super(name, useSender, policy); + public EntityParser(String name, boolean useSender, boolean livingOnly) { + super(name, useSender); this.livingOnly = livingOnly; } @@ -34,8 +32,6 @@ public class EntityParser extends PlayerEntityParser { break; } } - if(entity instanceof EntityNPC && ((EntityNPC)entity).isPlayer() && !this.policy.applies(env, env.getExecutor(), (Player)((EntityNPC)entity).connection)) - throw new RunException(this.policy.getDenyMessage((Player)((EntityNPC)entity).connection)); } else { entity = (Entity)super.parse(env, input); @@ -53,7 +49,7 @@ public class EntityParser extends PlayerEntityParser { public Collection getCompletions(CommandEnvironment env) { Entity target = env.getExecutor().getPointedEntity(); - List comp = target == null || (this.livingOnly && !(target instanceof EntityLiving)) || (target instanceof EntityNPC && ((EntityNPC)target).isPlayer() && !this.policy.applies(env, env.getExecutor(), (Player)((EntityNPC)target).connection)) ? Lists.newArrayList() : Lists.newArrayList("#" + target.getId()); + List comp = target == null || (this.livingOnly && !(target instanceof EntityLiving)) ? Lists.newArrayList() : Lists.newArrayList("#" + target.getId()); comp.addAll(super.getCompletions(env)); return comp; } diff --git a/server/src/main/java/server/command/EnumParser.java b/server/src/server/command/EnumParser.java similarity index 84% rename from server/src/main/java/server/command/EnumParser.java rename to server/src/server/command/EnumParser.java index 2378fe8..305dd00 100644 --- a/server/src/main/java/server/command/EnumParser.java +++ b/server/src/server/command/EnumParser.java @@ -3,7 +3,6 @@ package server.command; import java.util.Map; import common.collect.Maps; -import common.util.Identifyable; public class EnumParser extends DefaultingParser { private final Class clazz; @@ -15,7 +14,7 @@ public class EnumParser extends DefaultingParser { for(T obj : iter) { if(sb.length() > 1) sb.append("', '"); - sb.append(obj instanceof Identifyable id ? id.getName() : String.valueOf(obj)); + sb.append(String.valueOf(obj)); } return sb.append("'").toString(); } @@ -25,7 +24,7 @@ public class EnumParser extends DefaultingParser { this.clazz = clazz; this.selections = selections; for(T o : selections) { - this.lookup.put(o instanceof Identifyable id ? id.getName() : o.toString().toLowerCase(), o); + this.lookup.put(o.toString().toLowerCase(), o); } } diff --git a/server/src/main/java/server/command/Executable.java b/server/src/server/command/Executable.java similarity index 53% rename from server/src/main/java/server/command/Executable.java rename to server/src/server/command/Executable.java index 13114d9..1912915 100644 --- a/server/src/main/java/server/command/Executable.java +++ b/server/src/server/command/Executable.java @@ -4,10 +4,8 @@ import java.util.List; import java.util.Map; public interface Executable { +// Object exec(ScriptEnvironment env, ScriptArgs args); Map getParameters(); List getParamList(); String getName(); - default Iterable getCustomCompletions(CommandEnvironment env, Executor exec, ArgumentSplitter parsed, String param, String parser, String arg) { - return null; - } } diff --git a/server/src/server/command/Executor.java b/server/src/server/command/Executor.java new file mode 100644 index 0000000..193de3c --- /dev/null +++ b/server/src/server/command/Executor.java @@ -0,0 +1,27 @@ +package server.command; + +import common.entity.Entity; +import common.util.BlockPos; +import common.util.Position; +import server.network.Player; + +public interface Executor { + void logConsole(String msg); + String getExecId(); + String getExecName(); + Position getExecPos(); + Entity getPointedEntity(); + BlockPos getPointedPosition(); + + default boolean isConsole() { + return false; + } + + default boolean isPlayer() { + return this instanceof Player; + } + + default void logConsole(String fmt, Object ... args) { + this.logConsole(String.format(fmt, args)); + } +} diff --git a/server/src/server/command/FixedExecutor.java b/server/src/server/command/FixedExecutor.java new file mode 100644 index 0000000..54d8eb8 --- /dev/null +++ b/server/src/server/command/FixedExecutor.java @@ -0,0 +1,57 @@ +package server.command; + +import common.entity.Entity; +import common.util.BlockPos; +import common.util.Position; +import server.Server; + +public class FixedExecutor implements Executor { + private final Server server; + private final String id; + + private String name; + private Position position; + + public FixedExecutor(Server server, String id, String name, Position pos) { + this.server = server; + this.id = id; + this.name = name; + this.position = pos; + } + + public void setName(String name) { + this.name = name; + } + + public void setPosition(Position pos) { + this.position = pos; + } + + public void logConsole(String msg) { + this.server.logConsole(msg); + } + + public String getExecId() { + return this.id; + } + + public String getExecName() { + return this.name; + } + + public Position getExecPos() { + return this.position; + } + + public Entity getPointedEntity() { + return null; + } + + public BlockPos getPointedPosition() { + return null; + } + + public boolean isConsole() { + return true; + } +} diff --git a/server/src/server/command/IntParser.java b/server/src/server/command/IntParser.java new file mode 100644 index 0000000..4b9bdb4 --- /dev/null +++ b/server/src/server/command/IntParser.java @@ -0,0 +1,39 @@ +package server.command; + +public class IntParser extends DefaultingParser { + private final Integer min; + private final Integer max; + private final boolean hex; + + public IntParser(String name, boolean hex, Integer def, Integer min, Integer max, Object ... completions) { + super(name, def, completions); + this.min = min; + this.max = max; + this.hex = hex; + } + + public Integer parse(CommandEnvironment env, String input) { + int value; + try { + value = Integer.parseInt(input, this.hex ? 16 : 10); + } + catch(NumberFormatException e) { + throw new RunException("Ungültige " + (this.hex ? "Hexadezimalzahl" : "Ganzzahl") + " '%s'", input); + } + if(this.min != null && value < this.min) + if(this.max != null) + throw new RunException("Die Zahl muss im Bereich %d .. %d liegen, habe %d", this.min, this.max, value); + else + throw new RunException("Die Zahl muss mindestens %d betragen, habe %d", this.min, value); + if(this.max != null && value > this.max) + if(this.min != null) + throw new RunException("Die Zahl muss im Bereich %d .. %d liegen, habe %d", this.min, this.max, value); + else + throw new RunException("Die Zahl darf höchstens %d betragen, habe %d", this.max, value); + return value; + } + + public Class getTypeClass(boolean required) { + return this.hasDefault() || required ? int.class : Integer.class; + } +} diff --git a/server/src/main/java/server/command/LongParser.java b/server/src/server/command/LongParser.java similarity index 100% rename from server/src/main/java/server/command/LongParser.java rename to server/src/server/command/LongParser.java diff --git a/server/src/main/java/server/command/NonDefaultingParser.java b/server/src/server/command/NonDefaultingParser.java similarity index 100% rename from server/src/main/java/server/command/NonDefaultingParser.java rename to server/src/server/command/NonDefaultingParser.java diff --git a/server/src/server/command/Parameter.java b/server/src/server/command/Parameter.java new file mode 100644 index 0000000..a61a828 --- /dev/null +++ b/server/src/server/command/Parameter.java @@ -0,0 +1,53 @@ +package server.command; + +import java.util.List; + +public class Parameter { + private final String name; + private final char shortName; + private final boolean required; + private final int position; + private final List parsers; + private final ArgCombiner combiner; + + public Parameter(String name, char shortName, int position, boolean required, List parsers, ArgCombiner combiner) { + this.name = name; + this.shortName = shortName; + this.position = position; + this.required = required; + this.parsers = parsers; + this.combiner = combiner; + } + + public boolean isPositional() { + return this.position >= 0; + } + + public int getPosition() { + return this.position; + } + + public List getParsers() { + return this.parsers; + } + + public ArgCombiner getCombiner() { + return this.combiner; + } + + public boolean isRequired() { + return this.required; + } + + public String getName() { + return this.name; + } + + public boolean hasShortName() { + return this.shortName != 0; + } + + public char getShortName() { + return this.shortName; + } +} diff --git a/server/src/server/command/PatternReplacer.java b/server/src/server/command/PatternReplacer.java new file mode 100644 index 0000000..685c94f --- /dev/null +++ b/server/src/server/command/PatternReplacer.java @@ -0,0 +1,49 @@ +package server.command; + +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class PatternReplacer { + private final String variable; + private final boolean matchAll; + private final Pattern pattern; + private final Function function; + + public PatternReplacer(String variable, boolean matchAll, Function function) { + this.variable = variable; + this.matchAll = matchAll; + this.pattern = Pattern.compile("\\$\\((" + Pattern.quote(variable) + (matchAll ? "[^\\)]*" : "") + ")\\)"); + this.function = function; + } + + public void replaceVar(StringBuffer sb) { + String str = sb.toString(); + sb.delete(0, sb.length()); + Matcher matcher = this.pattern.matcher(str); + while(matcher.find()) { + String orig = matcher.group(1); + String rep = this.function.apply(orig); + if(rep == null) + throw new RunException("Variable '%s' konnte in diesem Kontext nicht ersetzt werden", orig); + matcher.appendReplacement(sb, rep); + } + matcher.appendTail(sb); + } + + public String getVariable() { + return this.variable; + } + + public boolean matchesAll() { + return this.matchAll; + } + + public Pattern getPattern() { + return this.pattern; + } + + public Function getFunction() { + return this.function; + } +} diff --git a/server/src/main/java/server/command/PlayerEntityListParser.java b/server/src/server/command/PlayerEntityListParser.java similarity index 70% rename from server/src/main/java/server/command/PlayerEntityListParser.java rename to server/src/server/command/PlayerEntityListParser.java index cf0c39d..2ab4890 100644 --- a/server/src/main/java/server/command/PlayerEntityListParser.java +++ b/server/src/server/command/PlayerEntityListParser.java @@ -11,23 +11,19 @@ import common.entity.npc.EntityNPC; import server.network.Player; public class PlayerEntityListParser extends PlayerEntityParser { - public PlayerEntityListParser(String name, boolean useSender, UserPolicy policy) { - super(name, useSender, policy); + public PlayerEntityListParser(String name, boolean useSender) { + super(name, useSender); } public Object parse(CommandEnvironment env, String input) { if(input.equals("*")) { List list = Lists.newArrayList(); - boolean found = false; for(Player plr : env.getServer().getPlayers()) { - if(plr.getPresentEntity() != null) { - found = true; - if(this.policy.applies(env, env.getExecutor(), plr)) - list.add(plr.getPresentEntity()); - } + if(plr.getPresentEntity() != null) + list.add(plr.getPresentEntity()); } if(list.isEmpty()) - throw new RunException("Keine " + (found ? "erlaubten " : "") + "Spieler gefunden"); + throw new RunException("Keine Spieler gefunden"); return list; } Set set = Sets.newHashSet(); @@ -45,7 +41,7 @@ public class PlayerEntityListParser extends PlayerEntityParser { } public Collection getCompletions(CommandEnvironment env) { - Collection comp = Lists.newArrayList(super.getCompletions(env)); + Collection comp = super.getCompletions(env); comp.add("*"); return comp; } diff --git a/server/src/main/java/server/command/PlayerEntityParser.java b/server/src/server/command/PlayerEntityParser.java similarity index 85% rename from server/src/main/java/server/command/PlayerEntityParser.java rename to server/src/server/command/PlayerEntityParser.java index 2214ca4..c7fee81 100644 --- a/server/src/main/java/server/command/PlayerEntityParser.java +++ b/server/src/server/command/PlayerEntityParser.java @@ -4,8 +4,8 @@ import common.entity.npc.EntityNPC; import server.network.Player; public class PlayerEntityParser extends PlayerParser { - public PlayerEntityParser(String name, boolean useSender, UserPolicy policy) { - super(name, useSender, policy); + public PlayerEntityParser(String name, boolean useSender) { + super(name, useSender); } public Object parse(CommandEnvironment env, String input) { diff --git a/server/src/main/java/server/command/PlayerListParser.java b/server/src/server/command/PlayerListParser.java similarity index 67% rename from server/src/main/java/server/command/PlayerListParser.java rename to server/src/server/command/PlayerListParser.java index 1b8d6be..d66c94f 100644 --- a/server/src/main/java/server/command/PlayerListParser.java +++ b/server/src/server/command/PlayerListParser.java @@ -4,24 +4,20 @@ import java.util.Collection; import java.util.List; import java.util.Set; -import common.collect.Filter; import common.collect.Lists; import common.collect.Sets; import server.network.Player; public class PlayerListParser extends PlayerParser { - public PlayerListParser(String name, boolean useSender, UserPolicy policy) { - super(name, useSender, policy); + public PlayerListParser(String name, boolean useSender) { + super(name, useSender); } public Object parse(CommandEnvironment env, String input) { if(input.equals("*")) { if(env.getServer().getPlayers().isEmpty()) throw new RunException("Keine Spieler gefunden"); - Collection filtered = Filter.filter(env.getServer().getPlayers(), player -> this.policy.applies(env, env.getExecutor(), player)); - if(filtered.isEmpty()) - throw new RunException("Keine erlaubten Spieler gefunden"); - return Lists.newArrayList(filtered); + return Lists.newArrayList(env.getServer().getPlayers()); } Set set = Sets.newHashSet(); for(String tok : input.split(",", -1)) { @@ -38,7 +34,7 @@ public class PlayerListParser extends PlayerParser { } public Collection getCompletions(CommandEnvironment env) { - Collection comp = Lists.newArrayList(super.getCompletions(env)); + Collection comp = super.getCompletions(env); comp.add("*"); return comp; } diff --git a/server/src/main/java/server/command/PlayerParser.java b/server/src/server/command/PlayerParser.java similarity index 50% rename from server/src/main/java/server/command/PlayerParser.java rename to server/src/server/command/PlayerParser.java index f01f9b6..2ca384a 100644 --- a/server/src/main/java/server/command/PlayerParser.java +++ b/server/src/server/command/PlayerParser.java @@ -2,34 +2,29 @@ package server.command; import java.util.Collection; -import common.collect.Filter; import server.network.Player; public class PlayerParser extends CompletingParser { protected final boolean useSender; - protected final UserPolicy policy; - public PlayerParser(String name, boolean useSender, UserPolicy policy) { + public PlayerParser(String name, boolean useSender) { super(name); this.useSender = useSender; - this.policy = policy; } public Object parse(CommandEnvironment env, String input) { Player net = env.getServer().getPlayer(input); if(net == null) throw new RunException("Spieler '%s' wurde nicht gefunden", input); - if(!this.policy.applies(env, env.getExecutor(), net)) - throw new RunException(this.policy.getDenyMessage(net)); return net; } public Object getDefault(CommandEnvironment env) { - return this.useSender && env.getExecutor().isPlayer() && this.policy.applies(env, env.getExecutor(), (Player)env.getExecutor()) ? (Player)env.getExecutor() : null; + return this.useSender && env.getExecutor().isPlayer() ? (Player)env.getExecutor() : null; } public Collection getCompletions(CommandEnvironment env) { - return Filter.filter(env.getServer().getAllPlayerNames(), user -> this.policy.applies(env, env.getExecutor(), env.getServer().getPlayer(user))); // add Lists.newArrayList if modifying! + return env.getServer().getAllUsernames(); } public Class getTypeClass(boolean required) { diff --git a/server/src/main/java/server/command/RunException.java b/server/src/server/command/RunException.java similarity index 100% rename from server/src/main/java/server/command/RunException.java rename to server/src/server/command/RunException.java diff --git a/server/src/main/java/server/command/StringCompleter.java b/server/src/server/command/StringCompleter.java similarity index 100% rename from server/src/main/java/server/command/StringCompleter.java rename to server/src/server/command/StringCompleter.java diff --git a/server/src/main/java/server/command/StringParser.java b/server/src/server/command/StringParser.java similarity index 100% rename from server/src/main/java/server/command/StringParser.java rename to server/src/server/command/StringParser.java diff --git a/server/src/server/command/TagParser.java b/server/src/server/command/TagParser.java new file mode 100644 index 0000000..ab1fad2 --- /dev/null +++ b/server/src/server/command/TagParser.java @@ -0,0 +1,26 @@ +package server.command; + +import common.nbt.NBTException; +import common.nbt.NBTParser; +import common.nbt.NBTTagCompound; + +public class TagParser extends DefaultingParser { + public TagParser(String name, NBTTagCompound def, Object ... completions) { + super(name, def, completions); + } + + public NBTTagCompound parse(CommandEnvironment env, String input) { + NBTTagCompound value; + try { + value = NBTParser.parseTag(input); + } + catch(NBTException e) { + throw new RunException(e, "Ungültiger NBT-Tag '%s'", input); + } + return value; + } + + public Class getTypeClass(boolean required) { + return NBTTagCompound.class; + } +} diff --git a/server/src/main/java/server/command/Variable.java b/server/src/server/command/Variable.java similarity index 100% rename from server/src/main/java/server/command/Variable.java rename to server/src/server/command/Variable.java diff --git a/server/src/main/java/server/command/WorldParser.java b/server/src/server/command/WorldParser.java similarity index 97% rename from server/src/main/java/server/command/WorldParser.java rename to server/src/server/command/WorldParser.java index 520e2a0..9649e30 100644 --- a/server/src/main/java/server/command/WorldParser.java +++ b/server/src/server/command/WorldParser.java @@ -25,8 +25,6 @@ public class WorldParser extends DimensionParser { public WorldServer getDefault(CommandEnvironment env) { Dimension dim = (Dimension)super.getDefault(env); - if(dim == null) - return null; return this.loadedOnly ? env.getServer().getWorldNoLoad(dim.getDimensionId()) : env.getServer().getWorld(dim.getDimensionId()); // if(world == null) // throw new ScriptException("Dimension '%s' ist nicht geladen", dim.getFormattedName(false)); diff --git a/server/src/server/command/commands/CommandAdmin.java b/server/src/server/command/commands/CommandAdmin.java new file mode 100644 index 0000000..49c155e --- /dev/null +++ b/server/src/server/command/commands/CommandAdmin.java @@ -0,0 +1,25 @@ +package server.command.commands; + +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.network.Player; + +public class CommandAdmin extends Command { + public CommandAdmin() { + super("admin"); + + this.addPlayer("player", false); + } + + public void exec(CommandEnvironment env, Executor exec, Player player) { + if(player == exec) + throw new RunException("Du kannst nicht deinen eigenen Admin-Status erneut setzen"); + else if(player.getAdmin()) + throw new RunException("%s ist bereits ein Admin", player.getUser()); + player.setAdmin(true); + player.logConsole("Du hast Administatorrechte von %s bekommen", exec.getExecId()); + exec.logConsole("%s ist jetzt ein Admin", player.getUser()); + } +} diff --git a/server/src/server/command/commands/CommandHelp.java b/server/src/server/command/commands/CommandHelp.java new file mode 100644 index 0000000..f5df1b8 --- /dev/null +++ b/server/src/server/command/commands/CommandHelp.java @@ -0,0 +1,55 @@ +package server.command.commands; + +import java.util.List; +import java.util.Map.Entry; +import java.util.function.Function; + +import common.collect.Lists; +import common.util.Util; +import server.command.ArgumentParser; +import server.command.CachedExecutable; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.Parameter; + +public class CommandHelp extends Command { + public CommandHelp(CommandEnvironment env) { + super("help"); + + this.setParamsOptional(); + this.addEnum("command", CachedExecutable.class, env.getExecutables().values()); + } + + public void exec(CommandEnvironment env, Executor exec, CachedExecutable command) { + if(command == null) { + for(CachedExecutable cmd : env.getExecutables().values()) { + this.exec(env, exec, cmd); + } + return; + } + List list = Lists.newArrayList(); + for(Entry entry : command.getParameters().entrySet()) { + Parameter param = entry.getValue(); + if(entry.getKey().length() == 1 && !param.isPositional() && param.hasShortName()) { + list.add("-" + param.getShortName() + (param.getParsers().isEmpty() ? " (" + param.getName() + ")" : (param.getParsers().size() == 1 && + param.getParsers().get(0).getName().equals(param.getName()) ? " <" + param.getName() + ">" : + " (" + param.getName() + ")" + Util.buildLines(" ", new Function() { + public String apply(ArgumentParser parser) { + return "<" + parser.getName() + ">"; + } + }, param.getParsers())))); + } + } + for(Parameter param : command.getPositionals()) { + list.add((param.isRequired() ? "<" : "[") + (param.getParsers().size() == 1 && + param.getParsers().get(0).getName().equals(param.getName()) ? param.getName() : + "(" + param.getName() + ") " + Util.buildLines(" ", new Function() { + public String apply(ArgumentParser parser) { + return "<" + parser.getName() + ">"; + } + }, param.getParsers())) + (param.isRequired() ? ">" : "]")); + } + exec.logConsole("%s %s", command.getName(), Util.buildLines(" ", list)); + } +} diff --git a/server/src/server/command/commands/CommandKick.java b/server/src/server/command/commands/CommandKick.java new file mode 100644 index 0000000..80b3b5e --- /dev/null +++ b/server/src/server/command/commands/CommandKick.java @@ -0,0 +1,26 @@ +package server.command.commands; + +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.network.Player; + +public class CommandKick extends Command { + public CommandKick() { + super("kick"); + + this.addPlayer("player", false); + this.setParamsOptional(); + this.addString("message", "Du wurdest vom Server geworfen", false); + } + + public void exec(CommandEnvironment env, Executor exec, Player player, String message) { + if(player == exec) + throw new RunException("Du kannst nicht dich nicht selbst vom Server werfen"); + else if(player.getAdmin()) + throw new RunException("%s ist ein Admin", player.getUser()); + player.disconnect(message); + exec.logConsole("%s wurde vom Server geworfen", player.getUser()); + } +} diff --git a/server/src/main/java/server/command/commands/CommandMessage.java b/server/src/server/command/commands/CommandMessage.java similarity index 95% rename from server/src/main/java/server/command/commands/CommandMessage.java rename to server/src/server/command/commands/CommandMessage.java index 8209267..177ba6c 100644 --- a/server/src/main/java/server/command/commands/CommandMessage.java +++ b/server/src/server/command/commands/CommandMessage.java @@ -11,7 +11,6 @@ public class CommandMessage extends Command { this.addString("message", false); - this.setParamsOptional(); this.addEnum("type", 't', SPacketMessage.Type.CHAT, SPacketMessage.Type.class, SPacketMessage.Type.values()); } diff --git a/server/src/main/java/server/command/commands/CommandMilk.java b/server/src/server/command/commands/CommandMilk.java similarity index 70% rename from server/src/main/java/server/command/commands/CommandMilk.java rename to server/src/server/command/commands/CommandMilk.java index 6cc2883..9ebb7f3 100644 --- a/server/src/main/java/server/command/commands/CommandMilk.java +++ b/server/src/server/command/commands/CommandMilk.java @@ -8,13 +8,12 @@ import common.potion.Potion; import server.command.Command; import server.command.CommandEnvironment; import server.command.Executor; -import server.command.UserPolicy; public class CommandMilk extends Command { public CommandMilk() { super("milk"); - this.addLivingEntityList("entities", true, UserPolicy.NON_ADMINS_OR_SELF); + this.addLivingEntityList("entities", true); this.setParamsOptional(); List potions = Lists.newArrayList(); for(Potion potion : Potion.values()) { @@ -30,19 +29,18 @@ public class CommandMilk extends Command { int done = 0; for(EntityLiving entity : entities) { if(type != null && entity.hasEffect(type)) { - int amplifier = entity.getEffect(type).getAmplifier(); entity.removeEffect(type); - exec.log("%s von %s entfernt", type.getDisplay(amplifier), entity.getCommandName()); + exec.logConsole("%s von %s entfernt", type.getDisplay(), entity.getCommandName()); done++; } else if(type == null && !entity.getEffects().isEmpty()) { entity.clearEffects(negative); - exec.log("Alle Effekte von %s entfernt", entity.getCommandName()); + exec.logConsole("Alle Effekte von %s entfernt", entity.getCommandName()); done++; } } if(done > 1) - exec.log(type == null ? "Alle Effekte von %d Objekten entfernt" : "%d Effekte entfernt", entities.size()); + exec.logConsole(type == null ? "Alle Effekte von %d Objekten entfernt" : "%d Effekte entfernt", entities.size()); return done; } } diff --git a/server/src/main/java/server/command/commands/CommandOfflinetp.java b/server/src/server/command/commands/CommandOfflinetp.java similarity index 76% rename from server/src/main/java/server/command/commands/CommandOfflinetp.java rename to server/src/server/command/commands/CommandOfflinetp.java index 55a3dba..7d3e339 100644 --- a/server/src/main/java/server/command/commands/CommandOfflinetp.java +++ b/server/src/server/command/commands/CommandOfflinetp.java @@ -3,6 +3,7 @@ package server.command.commands; import java.util.Collection; import java.util.List; +import common.collect.Lists; import common.entity.Entity; import common.init.UniverseRegistry; import common.util.Position; @@ -11,7 +12,6 @@ import server.command.CommandEnvironment; import server.command.Executor; import server.command.RunException; import server.command.StringCompleter; -import server.command.UserPolicy; import server.network.Player; public class CommandOfflinetp extends Command { @@ -20,11 +20,11 @@ public class CommandOfflinetp extends Command { this.addString("user", false, new StringCompleter() { public Collection complete(CommandEnvironment env) { - return env.getServer().getPlayerFilenames(); + return Lists.newArrayList(env.getServer().getUsers()); } }); - this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); + this.addEntityList("entities", 'e', true); } public Object exec(CommandEnvironment env, Executor exec, String user, List entities) { @@ -34,7 +34,7 @@ public class CommandOfflinetp extends Command { throw new RunException("Spieler '%s' konnte nicht gefunden werden", user); for(Entity entity : entities) { entity.teleport(pos); - exec.log("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x(), (int)pos.y(), (int)pos.z(), UniverseRegistry.getDimension(pos.dim()).getFormattedName(false)); + exec.logConsole("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x, (int)pos.y, (int)pos.z, UniverseRegistry.getDimension(pos.dim).getFormattedName(false)); } return entities.size(); } diff --git a/server/src/server/command/commands/CommandPasswd.java b/server/src/server/command/commands/CommandPasswd.java new file mode 100644 index 0000000..7cf15ad --- /dev/null +++ b/server/src/server/command/commands/CommandPasswd.java @@ -0,0 +1,69 @@ +package server.command.commands; + +import common.color.TextColor; +import common.init.Config; +import common.network.IPlayer; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.network.Player; +import server.util.Form; + +public class CommandPasswd extends Command { + public CommandPasswd() { + super("passwd"); + + this.addPlayer("player", true); + this.setParamsOptional(); + this.addString("password", false); + } + + public void exec(CommandEnvironment env, Executor exec, Player player, String password) { + if(exec.isPlayer()) { + if(password != null) + throw new RunException("Bei Verwendung als Spieler darf kein Passwort angegeben werden"); + if(player.getAdmin() && player != exec) + throw new RunException("%s ist ein Admin", player.getUser()); + ((Player)exec).displayForm(new Form() { + private Field checkField; + private Field passwordField; + private Field confirmField; + + protected void init() { + this.checkField = player != exec ? null : this.addPassword("Aktuelles Passwort", 0, IPlayer.MAX_PASS_LENGTH, ""); + this.passwordField = this.addPassword("Neues Passwort", Config.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); + this.confirmField = this.addPassword("Passwort bestätigen", Config.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); + } + + public String getTitle() { + return "Passwort für " + player.getUser() + " ändern"; + } + + protected void accept() { + Player plr = env.getServer().getPlayer(player.getUser()); + if(!((Player)exec).isAdmin() || plr == null || (plr.isAdmin() && plr != exec)) { + exec.logConsole(TextColor.DRED + "Ein Fehler ist aufgetreten"); + return; + } + if(this.checkField != null && !this.checkField.get().equals(plr.getPassword())) { + exec.logConsole(TextColor.RED + "Falsches Passwort eingegeben"); + return; + } + if(!this.passwordField.get().equals(this.confirmField.get())) { + exec.logConsole(TextColor.RED + "Passwörter stimmen nicht überein"); + return; + } + plr.setPassword(this.passwordField.get()); + exec.logConsole(TextColor.GREEN + "Passwort" + (plr != exec ? " für %s" : "") + " gesetzt", plr.getUser()); + } + }); + } + else if(exec.isConsole()) { + if(password == null) + throw new RunException("Bei Verwendung in der Konsole muss ein Passwort angegeben werden"); + player.setPassword(password); + exec.logConsole(TextColor.GREEN + "Passwort für %s gesetzt", player.getUser()); + } + } +} diff --git a/server/src/server/command/commands/CommandPlayers.java b/server/src/server/command/commands/CommandPlayers.java new file mode 100644 index 0000000..b665700 --- /dev/null +++ b/server/src/server/command/commands/CommandPlayers.java @@ -0,0 +1,32 @@ +package server.command.commands; + +import java.util.List; + +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.util.ExtMath; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.network.Player; + +public class CommandPlayers extends Command { + public CommandPlayers() { + super("players"); + + this.addFlag("coords", 'c'); + } + + public void exec(CommandEnvironment env, Executor exec, boolean coords) { + List players = env.getServer().getPlayers(); + if(players.isEmpty()) { + exec.logConsole(TextColor.DGRAY + "Es sind keine Spieler online"); + return; + } + exec.logConsole(TextColor.GREEN + "Es " + (players.size() == 1 ? "ist" : "sind") + " " + TextColor.YELLOW + "%d" + TextColor.GREEN + " Spieler online", players.size()); + for(Player player : players) { + EntityNPC entity = player.getPresentEntity(); + exec.logConsole("%s%s" + TextColor.GRAY + ": '%s" + TextColor.GRAY + "'" + (coords ? " [" + TextColor.ORANGE + "%s @ %d, %d, %d" + TextColor.GRAY + "]" : ""), player.isAdmin() ? TextColor.RED : TextColor.NEON, player.getUser(), entity == null ? TextColor.DGRAY + "<->" : TextColor.ACID + entity.getCommandName(), entity == null ? null : entity.worldObj.dimension.getFormattedName(false), entity == null ? null : ExtMath.floord(entity.posX), entity == null ? null : ExtMath.floord(entity.posY), entity == null ? null : ExtMath.floord(entity.posZ)); + } + } +} diff --git a/server/src/main/java/server/command/commands/CommandPotion.java b/server/src/server/command/commands/CommandPotion.java similarity index 76% rename from server/src/main/java/server/command/commands/CommandPotion.java rename to server/src/server/command/commands/CommandPotion.java index 87bf9da..b814346 100644 --- a/server/src/main/java/server/command/commands/CommandPotion.java +++ b/server/src/server/command/commands/CommandPotion.java @@ -8,13 +8,12 @@ import common.potion.PotionEffect; import server.command.Command; import server.command.CommandEnvironment; import server.command.Executor; -import server.command.UserPolicy; public class CommandPotion extends Command { public CommandPotion() { super("potion"); - this.addLivingEntityList("entities", true, UserPolicy.NON_ADMINS_OR_SELF); + this.addLivingEntityList("entities", true); this.addEnum("type", Potion.class, Potion.values()); this.setParamsOptional(); this.addInt("duration", 0, 1000000, 1000000); @@ -28,7 +27,7 @@ public class CommandPotion extends Command { public Object exec(CommandEnvironment env, Executor exec, List entities, Potion type, int duration, int strength, boolean particles, boolean ambient, boolean keep) { int done = 0; for(EntityLiving entity : entities) { - if(entity.isPotionApplicable(type, strength - 1)) { + if(entity.isPotionApplicable(type)) { if(type.isInstant()) { type.onImpact(null, null, entity, strength - 1, 1.0); } @@ -39,14 +38,14 @@ public class CommandPotion extends Command { entity.addEffect(effect); } if(type.isInstant() || duration == 0) - exec.log("%s an %s gegeben", type.getDisplay(strength - 1), entity.getCommandName()); + exec.logConsole("%d * %s an %s gegeben", strength, type.getDisplay(), entity.getCommandName()); else - exec.log("%s für %d Sekunden an %s gegeben", type.getDisplay(strength - 1), duration, entity.getCommandName()); + exec.logConsole("%d * %s für %d Sekunden an %s gegeben", strength, type.getDisplay(), duration, entity.getCommandName()); done++; } } if(done > 1) - exec.log("%d Effekte vergeben", done); + exec.logConsole("%d Effekte vergeben", done); return done; } } diff --git a/server/src/server/command/commands/CommandRebind.java b/server/src/server/command/commands/CommandRebind.java new file mode 100644 index 0000000..ad45c0e --- /dev/null +++ b/server/src/server/command/commands/CommandRebind.java @@ -0,0 +1,17 @@ +package server.command.commands; + +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; + +public class CommandRebind extends Command { + public CommandRebind() { + super("rebind"); + + this.addInt("port", 1024, 65535); + } + + public void exec(CommandEnvironment env, Executor exec, int port) { + env.getServer().bind(port); + } +} diff --git a/server/src/main/java/server/command/commands/CommandRegister.java b/server/src/server/command/commands/CommandRegister.java similarity index 53% rename from server/src/main/java/server/command/commands/CommandRegister.java rename to server/src/server/command/commands/CommandRegister.java index 5e315f5..c8a48e4 100644 --- a/server/src/main/java/server/command/commands/CommandRegister.java +++ b/server/src/server/command/commands/CommandRegister.java @@ -1,16 +1,15 @@ package server.command.commands; import common.color.TextColor; +import common.init.Config; +import common.nbt.NBTTagCompound; import common.network.IPlayer; -import common.util.EncryptUtil; import server.command.Command; import server.command.CommandEnvironment; import server.command.Executor; import server.command.RunException; import server.network.Player; -import server.network.User; import server.util.Form; -import server.vars.SVars; public class CommandRegister extends Command { public CommandRegister() { @@ -23,10 +22,12 @@ public class CommandRegister extends Command { } public void exec(CommandEnvironment env, Executor exec, String username, String password, boolean admin) { - if(env.getServer().getUser(username) != null) + Player player = env.getServer().getPlayer(username); + if(player != null) + throw new RunException("Ein Spieler mit diesem Nutzernamen ist bereits online"); + NBTTagCompound tag = env.getServer().loadPlayerData(username); + if(tag != null) throw new RunException("Ein Spieler mit diesem Nutzernamen ist bereits registriert"); - if(env.getServer().loadPlayerData(username) != null) - throw new RunException("Ein Spieler mit diesem Nutzernamen hat bereits Spielerdaten, ist aber nicht registriert"); if(exec.isPlayer()) { if(password != null) throw new RunException("Bei Verwendung als Spieler darf kein Passwort angegeben werden"); @@ -35,8 +36,8 @@ public class CommandRegister extends Command { private Field confirmField; protected void init() { - this.passwordField = this.addPassword("Passwort", SVars.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); - this.confirmField = this.addPassword("Passwort bestätigen", SVars.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); + this.passwordField = this.addPassword("Passwort", Config.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); + this.confirmField = this.addPassword("Passwort bestätigen", Config.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); } public String getTitle() { @@ -44,32 +45,28 @@ public class CommandRegister extends Command { } protected void accept() { - if(!((Player)exec).isAdmin() || env.getServer().getUser(username) != null || env.getServer().loadPlayerData(username) != null) { - exec.log(TextColor.DRED + "Ein Fehler ist aufgetreten"); + if(!((Player)exec).isAdmin() || env.getServer().getPlayer(username) != null || env.getServer().loadPlayerData(username) != null) { + exec.logConsole(TextColor.DRED + "Ein Fehler ist aufgetreten"); return; } if(!this.passwordField.get().equals(this.confirmField.get())) { - exec.log(TextColor.RED + "Passwörter stimmen nicht überein"); + exec.logConsole(TextColor.RED + "Passwörter stimmen nicht überein"); return; } - User user = new User(username); - user.setPasswordHash(EncryptUtil.hashPassword(this.passwordField.get())); - user.setAdmin(admin); - env.getServer().addUser(user); - exec.log(TextColor.GREEN + "Spieler %s registriert", username); + NBTTagCompound user = new NBTTagCompound(); + user.setString("password", this.passwordField.get()); + env.getServer().writePlayerData(username, user); + exec.logConsole(TextColor.GREEN + "Spieler %s registriert", username); } }); } else if(exec.isConsole()) { if(password == null) throw new RunException("Bei Verwendung in der Konsole muss ein Passwort angegeben werden"); - if(password.length() < 8) - throw new RunException("Das Passwort ist zu kurz, mindestens 8 Zeichen sind erforderlich"); - User user = new User(username); - user.setPasswordHash(EncryptUtil.hashPassword(password)); - user.setAdmin(admin); - env.getServer().addUser(user); - exec.log(TextColor.GREEN + "Spieler %s registriert", username); + NBTTagCompound user = new NBTTagCompound(); + user.setString("password", password); + env.getServer().writePlayerData(username, user); + exec.logConsole(TextColor.GREEN + "Spieler %s registriert", username); } } } diff --git a/server/src/main/java/server/command/commands/CommandRemove.java b/server/src/server/command/commands/CommandRemove.java similarity index 69% rename from server/src/main/java/server/command/commands/CommandRemove.java rename to server/src/server/command/commands/CommandRemove.java index 56044bc..2ecf0b6 100644 --- a/server/src/main/java/server/command/commands/CommandRemove.java +++ b/server/src/server/command/commands/CommandRemove.java @@ -6,15 +6,13 @@ import common.entity.Entity; import server.command.Command; import server.command.CommandEnvironment; import server.command.Executor; -import server.command.UserPolicy; public class CommandRemove extends Command { public CommandRemove() { super("remove"); - this.addEntityList("entities", true, UserPolicy.NON_ADMINS_OR_SELF); - - this.setParamsOptional(); + this.addEntityList("entities", true); + this.addFlag("kill", 'k'); } @@ -26,12 +24,12 @@ public class CommandRemove extends Command { entity.kill(); else entity.setDead(); - exec.log(kill ? "%s getötet" : "%s entfernt", entity.getCommandName()); + exec.logConsole(kill ? "%s getötet" : "%s entfernt", entity.getCommandName()); done++; } } if(done > 1) - exec.log(kill ? "%d Objekte getötet" : "%d Objekte entfernt", done); + exec.logConsole(kill ? "%d Objekte getötet" : "%d Objekte entfernt", done); return done; } } diff --git a/server/src/server/command/commands/CommandRevoke.java b/server/src/server/command/commands/CommandRevoke.java new file mode 100644 index 0000000..075dd3d --- /dev/null +++ b/server/src/server/command/commands/CommandRevoke.java @@ -0,0 +1,27 @@ +package server.command.commands; + +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.network.Player; + +public class CommandRevoke extends Command { + public CommandRevoke() { + super("revoke"); + + this.addPlayer("player", false); + } + + public void exec(CommandEnvironment env, Executor exec, Player player) { + if(!exec.isConsole()) + throw new RunException("Dieser Befehl kann nur der Konsole ausgeführt werden"); +// else if(player == exec) +// throw new RunException("Du kannst nicht deinen eigenen Admin-Status entfernen"); + else if(!player.getAdmin()) + throw new RunException("%s ist kein Admin", player.getUser()); + player.setAdmin(false); + player.logConsole("Der Host hat deine Administatorrechte entfernt"); + exec.logConsole("%s ist jetzt kein Admin mehr", player.getUser()); + } +} diff --git a/server/src/main/java/server/command/commands/CommandSave.java b/server/src/server/command/commands/CommandSave.java similarity index 78% rename from server/src/main/java/server/command/commands/CommandSave.java rename to server/src/server/command/commands/CommandSave.java index 36e9b02..4f80993 100644 --- a/server/src/main/java/server/command/commands/CommandSave.java +++ b/server/src/server/command/commands/CommandSave.java @@ -12,7 +12,6 @@ public class CommandSave extends Command { public CommandSave() { super("save"); - this.setParamsOptional(); this.addFlag("message", 'm'); this.addFlag("flush", 'f'); } @@ -20,16 +19,16 @@ public class CommandSave extends Command { public void exec(CommandEnvironment env, Executor exec, boolean message, boolean flush) { if(message) env.getServer().sendPacket(new SPacketMessage(TextColor.RED + "Speichere Serverdaten, der Server könnte kurz einfrieren", Type.FEED)); - exec.log(TextColor.ORANGE + "Speichere Spielerdaten ..."); + exec.logConsole(TextColor.ORANGE + "Speichere Spielerdaten ..."); env.getServer().saveAllPlayerData(true); - exec.log(TextColor.ORANGE + "Speichere Weltdaten ..."); + exec.logConsole(TextColor.ORANGE + "Speichere Weltdaten ..."); env.getServer().saveAllWorlds(true); env.getServer().resetSaveTimer(); if(flush) { - exec.log(TextColor.ORANGE + "Beende E/A ..."); + exec.logConsole(TextColor.ORANGE + "Beende E/A ..."); Region.finishWrite(); } - exec.log(TextColor.DGREEN + "Alle Serverdaten wurden gespeichert"); + exec.logConsole(TextColor.DGREEN + "Alle Serverdaten wurden gespeichert"); if(message) env.getServer().sendPacket(new SPacketMessage(TextColor.GREEN + "Die Serverdaten wurden gespeichert", Type.FEED)); } diff --git a/server/src/main/java/server/command/commands/CommandShutdown.java b/server/src/server/command/commands/CommandShutdown.java similarity index 100% rename from server/src/main/java/server/command/commands/CommandShutdown.java rename to server/src/server/command/commands/CommandShutdown.java diff --git a/server/src/main/java/server/command/commands/CommandSpawn.java b/server/src/server/command/commands/CommandSpawn.java similarity index 64% rename from server/src/main/java/server/command/commands/CommandSpawn.java rename to server/src/server/command/commands/CommandSpawn.java index dbb77ad..ab5f0a7 100644 --- a/server/src/main/java/server/command/commands/CommandSpawn.java +++ b/server/src/server/command/commands/CommandSpawn.java @@ -8,7 +8,7 @@ import common.collect.Sets; import common.entity.Entity; import common.entity.types.EntityLiving; import common.init.EntityRegistry; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import common.util.Util; import common.util.Vec3; import server.command.Command; @@ -28,9 +28,9 @@ public class CommandSpawn extends Command { } names.add("Lightning"); this.addEnum("type", String.class, names); + this.setParamsOptional(); this.addVector("position", true, true); this.addWorld("dim", true); - this.setParamsOptional(); this.addTag("tag"); this.addFlag("noinit", 'n'); @@ -38,13 +38,13 @@ public class CommandSpawn extends Command { this.addTag("postTag", 'p'); } - public Object exec(CommandEnvironment env, Executor exec, String type, Vec3 pos, WorldServer world, TagObject tag, boolean noinit, int count, TagObject postTag) { + public Object exec(CommandEnvironment env, Executor exec, String type, Vec3 pos, WorldServer world, NBTTagCompound tag, boolean noinit, int count, NBTTagCompound postTag) { if(type.equalsIgnoreCase("Lightning")) { for(int z = 0; z < count; z++) { int color = 0xffffff; - if(tag != null && tag.hasInt("color")) - color = tag.getInt("color"); - else if(tag != null && tag.hasString("color")) { + if(tag != null && tag.hasKey("color", 3)) + color = tag.getInteger("color"); + else if(tag != null && tag.hasKey("color", 8)) { try { color = Integer.parseUnsignedInt(tag.getString("color"), 16); } @@ -52,10 +52,10 @@ public class CommandSpawn extends Command { } } world.strikeLightning(pos.xCoord, pos.yCoord, pos.zCoord, color, - tag != null && tag.hasInt("damage") ? tag.getInt("damage") : 0, tag != null && tag.hasBool("fire") && tag.getBool("fire"), - exec.isPlayer() && tag != null && tag.hasBool("summoned") && tag.getBool("summoned") ? ((Player)exec).getPresentEntity() : null); + tag != null && tag.hasKey("damage", 3) ? tag.getInteger("damage") : 0, tag != null && tag.hasKey("fire", 1) && tag.getBoolean("fire"), + exec.isPlayer() && tag != null && tag.hasKey("summoned", 1) && tag.getBoolean("summoned") ? ((Player)exec).getPresentEntity() : null); } - exec.log("%sBlitz bei %d, %d, %d in %s erschaffen", count == 1 ? "" : (count + "x "), (int)pos.xCoord, (int)pos.yCoord, (int)pos.zCoord, world.dimension.getFormattedName(false)); + exec.logConsole("%sBlitz bei %d, %d, %d in %s erschaffen", count == 1 ? "" : (count + "x "), (int)pos.xCoord, (int)pos.yCoord, (int)pos.zCoord, world.dimension.getFormattedName(false)); return null; } else { @@ -66,23 +66,23 @@ public class CommandSpawn extends Command { throw new RunException("Objekt konnte nicht erzeugt werden"); entity.setLocationAndAngles(pos.xCoord, pos.yCoord, pos.zCoord, world.rand.floatv() * 360.0f, 0.0f); if(tag != null) { - TagObject ent = new TagObject(); - entity.writeTags(ent); + NBTTagCompound ent = new NBTTagCompound(); + entity.writeToNBT(ent); ent.merge(tag); - entity.readTags(ent); + entity.readFromNBT(ent); } if(!noinit && (entity instanceof EntityLiving)) ((EntityLiving)entity).onInitialSpawn(null); world.spawnEntityInWorld(entity); if(postTag != null) { - TagObject ent = new TagObject(); - entity.writeTags(ent); + NBTTagCompound ent = new NBTTagCompound(); + entity.writeToNBT(ent); ent.merge(postTag); - entity.readTags(ent); + entity.readFromNBT(ent); } spawned.add("#" + entity.getId()); } - exec.log("%s%s bei %d, %d, %d in %s erschaffen", count == 1 ? "" : (count + "x "), EntityRegistry.getEntityName(type), (int)pos.xCoord, (int)pos.yCoord, (int)pos.zCoord, world.dimension.getFormattedName(false)); + exec.logConsole("%s%s bei %d, %d, %d in %s erschaffen", count == 1 ? "" : (count + "x "), EntityRegistry.getEntityName(type), (int)pos.xCoord, (int)pos.yCoord, (int)pos.zCoord, world.dimension.getFormattedName(false)); return Util.buildLines(",", spawned); } } diff --git a/server/src/main/java/server/command/commands/CommandTele.java b/server/src/server/command/commands/CommandTele.java similarity index 74% rename from server/src/main/java/server/command/commands/CommandTele.java rename to server/src/server/command/commands/CommandTele.java index 8baf2f2..e2f735a 100644 --- a/server/src/main/java/server/command/commands/CommandTele.java +++ b/server/src/server/command/commands/CommandTele.java @@ -8,26 +8,24 @@ import common.util.Vec3; import server.command.Command; import server.command.CommandEnvironment; import server.command.Executor; -import server.command.UserPolicy; public class CommandTele extends Command { public CommandTele() { super("tele"); this.addVector("position", false, true); - this.addDimension("dim", true); this.setParamsOptional(); + this.addDimension("dim", true); this.addDouble("yaw", -180.0, 180.0); this.addDouble("pitch", -89.0, 89.0); - this.setParamsRequired(); - this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); + this.addEntityList("entities", 'e', true); } public Object exec(CommandEnvironment env, Executor exec, Vec3 position, Dimension dim, Double yaw, Double pitch, List entities) { for(Entity entity : entities) { entity.teleport(position.xCoord, position.yCoord, position.zCoord, yaw == null ? entity.rotYaw : yaw.floatValue(), pitch == null ? entity.rotPitch : pitch.floatValue(), dim.getDimensionId()); - exec.log("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)position.xCoord, (int)position.yCoord, (int)position.zCoord, dim.getFormattedName(false)); + exec.logConsole("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)position.xCoord, (int)position.yCoord, (int)position.zCoord, dim.getFormattedName(false)); } return entities.size(); } diff --git a/server/src/main/java/server/command/commands/CommandTime.java b/server/src/server/command/commands/CommandTime.java similarity index 94% rename from server/src/main/java/server/command/commands/CommandTime.java rename to server/src/server/command/commands/CommandTime.java index bcbbf59..97f59d2 100644 --- a/server/src/main/java/server/command/commands/CommandTime.java +++ b/server/src/server/command/commands/CommandTime.java @@ -14,8 +14,7 @@ public class CommandTime extends Command { super("time"); this.addString("time", false, "day", "night", "noon", "midnight", "sunrise", "sunset"); - - this.setParamsOptional(); + this.addFlag("absolute", 'a'); } @@ -70,7 +69,7 @@ public class CommandTime extends Command { public Object exec(CommandEnvironment env, Executor exec, String timeStr, boolean absolute) { Position pos = exec.getExecPos(); - WorldServer world = pos == null ? env.getServer().getSpace() : env.getServer().getWorld(pos.dim()); + WorldServer world = pos == null ? env.getServer().getSpace() : env.getServer().getWorld(pos.dim); long time = absolute ? 0L : world.getDayTime(); long fwd = parseDayTime(world.dimension, timeStr); if(fwd >= 0L) { @@ -90,7 +89,7 @@ public class CommandTime extends Command { dim.setDayTime(time); dim.resetWeather(); } - exec.log("Zeit auf %s gesetzt", ItemSpaceNavigator.formatImperialTime(world, false)); + exec.logConsole("Zeit auf %s gesetzt", ItemSpaceNavigator.formatImperialTime(world, false)); return time; } } diff --git a/server/src/main/java/server/command/commands/CommandTp.java b/server/src/server/command/commands/CommandTp.java similarity index 61% rename from server/src/main/java/server/command/commands/CommandTp.java rename to server/src/server/command/commands/CommandTp.java index cc4595b..f6a09f6 100644 --- a/server/src/main/java/server/command/commands/CommandTp.java +++ b/server/src/server/command/commands/CommandTp.java @@ -8,22 +8,21 @@ import common.util.Position; import server.command.Command; import server.command.CommandEnvironment; import server.command.Executor; -import server.command.UserPolicy; public class CommandTp extends Command { public CommandTp() { super("tp"); - this.addEntity("target", false, UserPolicy.NOT_SELF); + this.addEntity("target", false); - this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); + this.addEntityList("entities", 'e', true); } public Object exec(CommandEnvironment env, Executor exec, Entity target, List entities) { Position pos = target.getPos(); for(Entity entity : entities) { entity.teleport(pos); - exec.log("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x(), (int)pos.y(), (int)pos.z(), UniverseRegistry.getDimension(pos.dim()).getFormattedName(false)); + exec.logConsole("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x, (int)pos.y, (int)pos.z, UniverseRegistry.getDimension(pos.dim).getFormattedName(false)); } return entities.size(); } diff --git a/server/src/main/java/server/command/commands/CommandWarp.java b/server/src/server/command/commands/CommandWarp.java similarity index 82% rename from server/src/main/java/server/command/commands/CommandWarp.java rename to server/src/server/command/commands/CommandWarp.java index 85bc447..e33dd3b 100644 --- a/server/src/main/java/server/command/commands/CommandWarp.java +++ b/server/src/server/command/commands/CommandWarp.java @@ -11,7 +11,6 @@ import server.command.CommandEnvironment; import server.command.Executor; import server.command.RunException; import server.command.StringCompleter; -import server.command.UserPolicy; public class CommandWarp extends Command { public CommandWarp() { @@ -25,7 +24,7 @@ public class CommandWarp extends Command { } }); - this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); + this.addEntityList("entities", 'e', true); } public Object exec(CommandEnvironment env, Executor exec, String warp, List entities) { @@ -43,12 +42,12 @@ public class CommandWarp extends Command { pos = env.getServer().getWarps().get(warp); if(pos == null) throw new RunException("Warp '%s' existiert nicht", warp); - else if(env.getServer().getWorld(pos.dim()) == null) - throw new RunException("Warp '%s' hat kein Level (%s)", warp, pos.dim()); + else if(env.getServer().getWorld(pos.dim) == null) + throw new RunException("Warp '%s' hat kein Level (%s)", warp, pos.dim); // } for(Entity entity : entities) { entity.teleport(pos); - exec.log("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x(), (int)pos.y(), (int)pos.z(), UniverseRegistry.getDimension(pos.dim()).getFormattedName(false)); + exec.logConsole("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x, (int)pos.y, (int)pos.z, UniverseRegistry.getDimension(pos.dim).getFormattedName(false)); } return entities.size(); } diff --git a/server/src/main/java/server/command/commands/CommandWeather.java b/server/src/server/command/commands/CommandWeather.java similarity index 89% rename from server/src/main/java/server/command/commands/CommandWeather.java rename to server/src/server/command/commands/CommandWeather.java index 25313c6..2a45a62 100644 --- a/server/src/main/java/server/command/commands/CommandWeather.java +++ b/server/src/server/command/commands/CommandWeather.java @@ -12,9 +12,9 @@ public class CommandWeather extends Command { super("weather"); this.addEnum("weather", Weather.class, Weather.values()); - this.addWorld("dim", true); - this.setParamsOptional(); + this.addWorld("dim", true); + this.addFlag("transition", 't'); } @@ -26,6 +26,6 @@ public class CommandWeather extends Command { world.setWeather(weather); if(!transition) world.resetWeather(); - exec.log("Wetter in %s zu %s geändert", world.dimension.getFormattedName(false), weather.getDisplay()); + exec.logConsole("Wetter in %s zu %s geändert", world.dimension.getFormattedName(false), weather.getDisplay()); } } diff --git a/server/src/main/java/server/command/commands/CommandWorld.java b/server/src/server/command/commands/CommandWorld.java similarity index 80% rename from server/src/main/java/server/command/commands/CommandWorld.java rename to server/src/server/command/commands/CommandWorld.java index 316fc18..5ce211c 100644 --- a/server/src/main/java/server/command/commands/CommandWorld.java +++ b/server/src/server/command/commands/CommandWorld.java @@ -7,16 +7,15 @@ import common.util.BlockPos; import server.command.Command; import server.command.CommandEnvironment; import server.command.Executor; -import server.command.UserPolicy; import server.world.WorldServer; public class CommandWorld extends Command { public CommandWorld() { super("world"); - this.addWorld("dim", false); + this.addWorld("dim", true); - this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); + this.addEntityList("entities", 'e', true); } public Object exec(CommandEnvironment env, Executor exec, WorldServer world, List entities) { @@ -33,7 +32,7 @@ public class CommandWorld extends Command { pos = pos.up(); } entity.teleport(pos, world.dimension.getDimensionId()); - exec.log("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), pos.getX(), pos.getY(), pos.getZ(), world.dimension.getFormattedName(false)); + exec.logConsole("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), pos.getX(), pos.getY(), pos.getZ(), world.dimension.getFormattedName(false)); } return entities.size(); } diff --git a/server/src/main/java/server/network/HandshakeHandler.java b/server/src/server/network/HandshakeHandler.java similarity index 65% rename from server/src/main/java/server/network/HandshakeHandler.java rename to server/src/server/network/HandshakeHandler.java index fb42a35..a3fc59e 100755 --- a/server/src/main/java/server/network/HandshakeHandler.java +++ b/server/src/server/network/HandshakeHandler.java @@ -1,14 +1,15 @@ package server.network; +import common.init.Config; import common.network.IHandshakeHandler; import common.network.NetConnection; +import common.network.NetHandler; import common.network.PacketRegistry; import common.packet.HPacketHandshake; import common.packet.RPacketDisconnect; -import common.util.Util; import server.Server; -public class HandshakeHandler implements IHandshakeHandler +public class HandshakeHandler extends NetHandler implements IHandshakeHandler { private final Server server; private final NetConnection networkManager; @@ -30,21 +31,19 @@ public class HandshakeHandler implements IHandshakeHandler return; } this.networkManager.setConnectionState(PacketRegistry.LOGIN); - if (packetIn.getProtocolVersion() != Util.PROTOCOL) + if (packetIn.getProtocolVersion() != Config.PROTOCOL) { String comp; - if(packetIn.getProtocolVersion() < Util.PROTOCOL) - comp = "Der Server nutzt eine neuere Version: " + Util.VERSION; + if(packetIn.getProtocolVersion() < Config.PROTOCOL) + comp = "Der Server nutzt eine neuere Version: " + Config.VERSION; else - comp = "Der Server nutzt eine ältere Version: " + Util.VERSION; + comp = "Der Server nutzt eine ältere Version: " + Config.VERSION; this.networkManager.sendPacket(new RPacketDisconnect(comp)); this.networkManager.closeChannel(comp); } else { - LoginHandler handler = new LoginHandler(this.server, this.networkManager); - this.networkManager.setNetHandler(handler); - handler.sendLoginPacket(); + this.networkManager.setNetHandler(new LoginHandler(this.server, this.networkManager)); } } } diff --git a/server/src/server/network/LoginHandler.java b/server/src/server/network/LoginHandler.java new file mode 100755 index 0000000..d71d102 --- /dev/null +++ b/server/src/server/network/LoginHandler.java @@ -0,0 +1,143 @@ +package server.network; + +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.util.Arrays; + +import javax.crypto.SecretKey; + +import common.color.TextColor; +import common.init.Config; +import common.log.Log; +import common.network.ILoginHandler; +import common.network.IPlayer; +import common.network.NetConnection; +import common.network.NetHandler; +import common.packet.LPacketLogin; +import common.packet.LPacketPasswordResponse; +import common.packet.LPacketStartEncrypt; +import common.packet.RPacketDisconnect; +import common.packet.RPacketRequestEncrypt; +import server.Server; + +public class LoginHandler extends NetHandler implements ILoginHandler +{ + private static enum LoginState { + INIT, ENCRYPT, PASSWORD, AUTHENTICATED, ACCEPTED; + } + + private static final SecureRandom TOKEN_RNG = new SecureRandom(); + + private final Server server; + public final NetConnection netManager; + + private LoginState state = LoginState.INIT; + private int timer; + private String loginUser; + private String loginPass; + private byte[] loginToken; + + public LoginHandler(Server server, NetConnection netManager) + { + this.netManager = netManager; + this.server = server; + } + + public void closeConnection(String reason) + { + try + { + Log.JNI.info("Trenne " + this.getConnectionInfo()); + this.netManager.sendPacket(new RPacketDisconnect(reason)); + this.netManager.closeChannel(reason); + } + catch (Exception exception) + { + Log.JNI.error(exception, "Fehler beim Trennen des Spielers beim Login"); + } + } + + public void onDisconnect(String reason) + { + Log.JNI.info(this.getConnectionInfo() + " wurde beim Login getrennt: " + TextColor.stripCodes(reason)); + } + + public String getConnectionInfo() + { + return this.loginUser != null ? (this.loginUser + " (" + this.netManager.getCutAddress() + + ")") : this.netManager.getCutAddress(); + } + + public void update() + { + if(this.state == LoginState.AUTHENTICATED) + this.tryAcceptPlayer(); +// else if (this.currentLoginState == LoginState.DELAY_ACCEPT) +// { +// if (this.server.getPlayer(this.loginUser) == null) +// { +// this.currentLoginState = LoginState.ACCEPTED; +// this.server.addPlayer(this.networkManager, this.loginUser); +// } +// } + if(this.timer++ == 600) + this.closeConnection("Anmeldung dauerte zu lange"); + } + + private void tryAcceptPlayer() + { + if(this.server.getPlayer(this.loginUser) != null) { + this.closeConnection("Nutzername '" + this.loginUser + "' ist bereits vergeben."); + return; + } +// if (this.server.getPlayer(this.loginUser) != null) +// { +// this.closeConnection("Nutzername '" + this.loginUser + "' ist bereits vergeben."); +// return; +//// this.currentLoginState = LoginState.DELAY_ACCEPT; +//// player.netHandler.kick("Du hast dich von einen anderen Ort verbunden"); +// } +// this.networkManager.sendPacket(new RPacketLoginSuccess()); + String kick = this.server.addPlayer(this.netManager, this.loginUser, this.loginPass); + if(kick != null) + this.closeConnection(kick); + else + this.state = LoginState.ACCEPTED; + } + + public void processLogin(LPacketLogin packet) { + if(this.state != LoginState.INIT) + throw new IllegalStateException("Unerwartetes Login-Paket"); + this.state = LoginState.ENCRYPT; + this.loginToken = new byte[4]; + TOKEN_RNG.nextBytes(this.loginToken); + this.netManager.sendPacket(new RPacketRequestEncrypt(this.server.getPublicKey(), this.loginToken)); + } + + public void processEncryption(LPacketStartEncrypt packet) { + if(this.state != LoginState.ENCRYPT) + throw new IllegalStateException("Unerwartetes Verschlüsselungs-Paket"); + PrivateKey pkey = this.server.getPrivateKey(); + if(!Arrays.equals(this.loginToken, packet.getToken(pkey))) + throw new IllegalStateException("Fehlerhaftes Token"); + SecretKey key = packet.getKey(pkey); + this.netManager.startEncryption(key); + this.state = LoginState.PASSWORD; + } + + public void processPasswordResponse(LPacketPasswordResponse packetIn) { + if(this.state != LoginState.PASSWORD) + throw new IllegalStateException("Unerwartetes Passwort-Paket"); + this.loginUser = packetIn.getUser(); + this.loginPass = packetIn.getPassword(); + if(this.loginUser.isEmpty() || !IPlayer.isValidUser(this.loginUser)) + throw new IllegalStateException("Ungültiger Nutzername!"); +// if(!this.checkConnect(packetIn.getAccess())) +// return; + if(!Config.password.isEmpty() && !Config.password.equals(packetIn.getAccess())) { + this.closeConnection("Falsches Zugangspasswort"); + return; + } + this.state = LoginState.AUTHENTICATED; + } +} diff --git a/server/src/main/java/server/network/Player.java b/server/src/server/network/Player.java similarity index 84% rename from server/src/main/java/server/network/Player.java rename to server/src/server/network/Player.java index 5299582..b5cbd23 100755 --- a/server/src/main/java/server/network/Player.java +++ b/server/src/server/network/Player.java @@ -8,9 +8,9 @@ import java.util.Set; import java.util.function.Predicate; import common.block.Block; -import common.block.artificial.BlockFence; -import common.block.artificial.BlockFenceGate; -import common.block.artificial.BlockWall; +import common.block.BlockFence; +import common.block.BlockFenceGate; +import common.block.BlockWall; import common.collect.Lists; import common.color.TextColor; import common.dimension.Dimension; @@ -26,15 +26,15 @@ import common.entity.projectile.EntityArrow; import common.entity.types.EntityLiving; import common.future.Futures; import common.init.BlockRegistry; -import common.init.Blocks; +import common.init.Config; import common.init.EntityRegistry; import common.init.Items; import common.init.SoundEvent; import common.init.UniverseRegistry; +import common.init.Config.ValueType; import common.inventory.Container; import common.inventory.ContainerChest; -import common.inventory.ContainerEnchantment; -import common.inventory.ContainerEntityInventory; +import common.inventory.ContainerHorseInventory; import common.inventory.ContainerMerchant; import common.inventory.ICrafting; import common.inventory.IInventory; @@ -45,13 +45,16 @@ import common.item.ItemArmor; import common.item.ItemControl; import common.item.ItemStack; import common.log.Log; -import common.net.util.concurrent.Future; -import common.net.util.concurrent.GenericFutureListener; +import common.material.Material; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; +import common.nbt.NBTTagString; import common.network.IPlayer; import common.network.NetConnection; import common.network.NetHandler; import common.network.Packet; import common.packet.CPacketAction; +import common.packet.CPacketBook; import common.packet.CPacketBreak; import common.packet.CPacketCheat; import common.packet.CPacketClick; @@ -64,21 +67,21 @@ import common.packet.CPacketPlace; import common.packet.CPacketPlayer; import common.packet.CPacketSign; import common.packet.CPacketSkin; -import common.packet.SPacketEntityTeleport; -import common.packet.SPacketEntityStatus; -import common.packet.SPacketEntityAttach; -import common.packet.SPacketEntityEffect; -import common.packet.SPacketRemoveEntityEffect; -import common.packet.SPacketSoundEffect; -import common.packet.SPacketOpenWindow; -import common.packet.SPacketCloseWindow; -import common.packet.SPacketSetSlot; -import common.packet.SPacketWindowItems; -import common.packet.SPacketWindowProperty; -import common.packet.SPacketConfirmTransaction; -import common.packet.SPacketSignEditorOpen; -import common.packet.SPacketPlayerAbilities; -import common.packet.SPacketTabComplete; +import common.packet.S18PacketEntityTeleport; +import common.packet.S1APacketEntityStatus; +import common.packet.S1BPacketEntityAttach; +import common.packet.S1DPacketEntityEffect; +import common.packet.S1EPacketRemoveEntityEffect; +import common.packet.S29PacketSoundEffect; +import common.packet.S2DPacketOpenWindow; +import common.packet.S2EPacketCloseWindow; +import common.packet.S2FPacketSetSlot; +import common.packet.S30PacketWindowItems; +import common.packet.S31PacketWindowProperty; +import common.packet.S32PacketConfirmTransaction; +import common.packet.S36PacketSignEditorOpen; +import common.packet.S39PacketPlayerAbilities; +import common.packet.S3APacketTabComplete; import common.packet.SPacketAnimation; import common.packet.SPacketBlockChange; import common.packet.SPacketCharacterList; @@ -100,11 +103,10 @@ import common.packet.CPacketAction.Action; import common.packet.SPacketMessage.Type; import common.potion.Potion; import common.potion.PotionEffect; -import common.tags.TagObject; import common.tileentity.IInteractionObject; import common.tileentity.ILockableContainer; import common.tileentity.TileEntity; -import common.tileentity.TileEntityDevice; +import common.tileentity.TileEntityMachine; import common.tileentity.TileEntitySign; import common.util.BlockPos; import common.util.BoundingBox; @@ -117,9 +119,11 @@ import common.util.Position; import common.util.Vec3i; import common.util.WorldPos; import common.village.MerchantRecipeList; -import common.world.BlockArray; +import common.world.Chunk; import common.world.State; import common.world.World; +import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.GenericFutureListener; import server.Server; import server.clipboard.BlockTransform; import server.clipboard.ClipboardBlock; @@ -130,12 +134,10 @@ import server.clipboard.RotationValue; import server.clipboard.Vector; import server.command.Executor; import server.util.Form; -import server.vars.SVars; -import server.world.ChunkServer; import server.world.Region; import server.world.WorldServer; -public class Player extends User implements ICrafting, Executor, IPlayer +public class Player extends NetHandler implements ICrafting, Executor, IPlayer { private static enum EditAction { SELECT("Auswahlmodus"), COPYPASTE("Kopiermodus"), TRANSFORM("Drehmodus"); @@ -149,8 +151,9 @@ public class Player extends User implements ICrafting, Executor, IPlayer private final NetConnection connection; private final Server server; + private final String user; private final IntHashMap transactions = new IntHashMap(); - private final List characters = Lists.newArrayList(); + private final List characters = Lists.newArrayList(); private EntityNPC entity; private int tickTime; @@ -166,7 +169,10 @@ public class Player extends User implements ICrafting, Executor, IPlayer private boolean charEditor = true; private Form form; + private boolean admin; private int ping; + private boolean deleted; + private String password; private boolean profiling; private int selectionDim = Integer.MIN_VALUE; @@ -204,15 +210,12 @@ public class Player extends User implements ICrafting, Executor, IPlayer private final List loadedChunks = new LinkedList(); private final List destroyedItemsNetCache = new LinkedList(); - - private Position forcedPos; - private Executor forcedExec; - private Position deathPos; - private Position teleportPos; +// private final Set statsQueue = Sets.newHashSet(); +// private final Map stats = Maps.newConcurrentMap(); public Player(Server server, NetConnection connection, String user) { - super(user); + this.user = user; this.server = server; this.connection = connection; // this.local = connection.isLocalChannel(); @@ -250,8 +253,8 @@ public class Player extends User implements ICrafting, Executor, IPlayer this.pingKey = (int)this.lastPingTime; this.sendPacket(new SPacketKeepAlive(this.pingKey)); } - if(this.isAdmin() && this.profiling) - this.sendPacket(new SPacketServerTick((int)this.server.getLastTick())); + if(this.admin && this.profiling) + this.sendPacket(new SPacketServerTick((int)this.server.getLastTick(), this.getTickInfo())); if(this.respawnTimer > 0) { if(--this.respawnTimer == 0) { this.respawnPlayer(); @@ -259,8 +262,16 @@ public class Player extends User implements ICrafting, Executor, IPlayer } } - public boolean isOnline() { - return true; + private String getTickInfo() { + if(this.charEditor || this.entity == null) + return ""; + WorldServer world = this.getEntityWorld(); + BlockPos pos = this.entity.getPosition(); + return String.format("Temperatur: %.2f K / %.2f °C, L: %s%s", + world.getTemperatureK(pos), world.getTemperatureC(pos), + !world.dimension.getType().days ? "*" : "", + world.getLeavesGen(pos).getDisplayName() + ); } public void displayLoading(String message) { @@ -276,14 +287,13 @@ public class Player extends User implements ICrafting, Executor, IPlayer } public void onEntityDeath() { - this.deathPos = this.entity.getPos(); this.entity.sendDeathMessage(); - if (!SVars.keepInventory && SVars.playerDrop) + if (!Config.keepInventory && Config.playerDrop) { this.entity.inventory.dropAllItems(); } - if(SVars.skullDrop) { + if(Config.skullDrop) { ItemStack stack = new ItemStack(Items.skull, 1, 0); this.entity.dropItem(stack, true, false); } @@ -308,8 +318,8 @@ public class Player extends User implements ICrafting, Executor, IPlayer // this.removeStat(StatRegistry.timeSinceDeathStat); this.entity.resetCombat(); - if(SVars.respawnTime > 0) - this.respawnTimer = ExtMath.clampi(SVars.respawnTime, 2, 20); + if(Config.respawnTime > 0) + this.respawnTimer = ExtMath.clampi(Config.respawnTime, 2, 20); } public boolean isInEditor() { @@ -323,6 +333,10 @@ public class Player extends User implements ICrafting, Executor, IPlayer public EntityNPC getEntity() { return this.entity; } + + public String getUser() { + return this.user; + } // public boolean isLocal() { // return this.local; @@ -331,6 +345,22 @@ public class Player extends User implements ICrafting, Executor, IPlayer public int getLatency() { return this.ping; } + + public boolean isAdmin() { + return this.admin; // || this.local; + } + + public boolean getAdmin() { + return this.isAdmin(); + } + + public void setPassword(String pass) { + this.password = pass; + } + + public String getPassword() { + return this.password; + } @@ -378,7 +408,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer BlockPos blockpos = new BlockPos(i, j, k); Block block = this.entity.worldObj.getState(blockpos).getBlock(); - if (block == Blocks.air) + if (block.getMaterial() == Material.air) { Block block1 = this.entity.worldObj.getState(blockpos.down()).getBlock(); @@ -410,7 +440,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer this.entity.openContainer.onCraftGuiOpened(this); IInventory iinventory = ((ContainerMerchant)this.entity.openContainer).getMerchantInventory(); String ichatcomponent = npc.getName(); - this.sendPacket(new SPacketOpenWindow(this.currentWindowId, "trade", ichatcomponent, iinventory.getSizeInventory())); + this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "trade", ichatcomponent, iinventory.getSizeInventory())); MerchantRecipeList merchantrecipelist = npc.getTrades(this.entity); if (merchantrecipelist != null) @@ -426,7 +456,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer { if (!this.isChangingQuantityOnly) { - this.sendPacket(new SPacketSetSlot(-1, -1, this.entity.inventory.getItemStack())); + this.sendPacket(new S2FPacketSetSlot(-1, -1, this.entity.inventory.getItemStack())); } } @@ -462,19 +492,25 @@ public class Player extends User implements ICrafting, Executor, IPlayer public void clonePlayer(EntityNPC oldPlayer) { - this.lastExperience = -1; - this.lastHealth = -1.0F; - if(SVars.keepInventory) + if(Config.keepInventory) this.entity.inventory.copyInventory(oldPlayer.inventory); this.entity.experienceLevel = oldPlayer.experienceLevel; this.entity.experienceTotal = oldPlayer.experienceTotal; this.entity.experience = oldPlayer.experience; - this.entity.setEnchSeed(oldPlayer.getEnchSeed()); + this.entity.setXPSeed(oldPlayer.getXPSeed()); this.entity.setWarpChest(oldPlayer.getWarpChest()); +// this.entity.getDataWatcher().updateObject(10, Integer.valueOf(oldPlayer.getDataWatcher().getWatchableObjectInt(10))); + this.lastExperience = -1; + this.lastHealth = -1.0F; +// this.destroyedItemsNetCache.addAll(oldPlayer.connection.destroyedItemsNetCache); this.entity.setSkin(oldPlayer.getSkin()); - this.entity.setHeight(oldPlayer.getHeight()); - this.entity.setCustomNameTag(oldPlayer.getCustomNameTag()); + this.entity.getDataWatcher().updateObject(29, oldPlayer.getDataWatcher().getWatchableObjectFloat(29)); +// this.entity.getDataWatcher().updateObject(11, oldPlayer.getDataWatcher().getWatchableObjectByte(11)); + this.entity.getDataWatcher().updateObject(1, oldPlayer.getDataWatcher().getWatchableObjectString(1)); + this.entity.getDataWatcher().updateObject(18, oldPlayer.getDataWatcher().getWatchableObjectByte(18)); this.entity.setAlignment(oldPlayer.getAlignment()); +// this.stats.putAll(oldPlayer.stats); +// this.statsQueue.addAll(oldPlayer.statsQueue); } public void removeEntity(Entity p_152339_1_) @@ -528,7 +564,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer { if (this.entity != null) { - this.sendPacket(new SPacketPlayerAbilities(this.entity)); + this.sendPacket(new S39PacketPlayerAbilities(this.entity)); this.entity.updateEffectMeta(); } } @@ -584,34 +620,58 @@ public class Player extends User implements ICrafting, Executor, IPlayer } public void sendThrowMessage(ItemStack stack) { - if(stack.size == 1) + if(stack.stackSize == 1) this.addFeed(TextColor.DRED + "* %s weg geworfen", stack.getColoredName(TextColor.DRED)); else - this.addFeed(TextColor.DRED + "* %d %s weg geworfen", stack.size, + this.addFeed(TextColor.DRED + "* %d %s weg geworfen", stack.stackSize, stack.getColoredName(TextColor.DRED)); } - public void readTags(TagObject tag) { - this.selected = tag.getInt("selected"); - List list = tag.getList("characters"); - for(int z = 0; z < list.size(); z++) { - this.characters.add(list.get(z)); + public void readFromNBT(NBTTagCompound tag) { + this.admin = tag.getBoolean("admin"); + if(tag.hasKey("password", 8)) + this.password = tag.getString("password"); + this.selected = tag.getInteger("selected"); + NBTTagList list = tag.getTagList("characters", 10); + for(int z = 0; z < list.tagCount(); z++) { + this.characters.add(list.getCompoundTagAt(z)); } this.selected = Math.min(this.selected, this.characters.size() - 1); this.charEditor = this.selected < 0; +// this.stats.clear(); +// if(tag.hasKey("Stats", 10)) { +// NBTTagCompound stats = tag.getCompoundTag("Stats"); +// for(String key : stats.getKeySet()) { +// StatBase stat = StatRegistry.getStat(key); +// if(stat == null) { +// Log.warn("Ungültige Statistik: Statistik '" + key + "' ist unbekannt"); +// continue; +// } +// this.stats.put(stat, stats.getInteger(key)); +// } +// } } - public void writeTags(TagObject tag) { + public void writeToNBT(NBTTagCompound tag) { + if(this.admin) + tag.setBoolean("admin", this.admin); + if(this.password != null) + tag.setString("password", this.password); if(!this.characters.isEmpty()) { - tag.setInt("selected", this.selected); - List list = Lists.newArrayList(); - for(TagObject etag : this.characters) { - list.add(etag); + tag.setInteger("selected", this.selected); + NBTTagList list = new NBTTagList(); + for(NBTTagCompound etag : this.characters) { + list.appendTag(etag); } - tag.setList("characters", list); + tag.setTag("characters", list); } +// NBTTagCompound stats = new NBTTagCompound(); +// for(Entry entry : this.stats.entrySet()) { +// stats.setInteger(entry.getKey().statId, entry.getValue()); +// } +// tag.setTag("Stats", stats); } @@ -638,7 +698,6 @@ public class Player extends User implements ICrafting, Executor, IPlayer } public void teleport(double x, double y, double z, float yaw, float pitch, int dimension) { - this.teleportPos = this.entity.getPos(); x = ExtMath.clampd(x, -World.MAX_SIZE + 1, World.MAX_SIZE - 1); z = ExtMath.clampd(z, -World.MAX_SIZE + 1, World.MAX_SIZE - 1); // this.setLastTeleport(this.getLocation()); @@ -659,20 +718,20 @@ public class Player extends User implements ICrafting, Executor, IPlayer public void mountEntity(Entity entityIn) { - this.sendPacket(new SPacketEntityAttach(0, this.entity, this.entity.vehicle)); + this.sendPacket(new S1BPacketEntityAttach(0, this.entity, this.entity.vehicle)); this.setPlayerLocation(this.entity.posX, this.entity.posY, this.entity.posZ, this.entity.rotYaw, this.entity.rotPitch); } public void openEditSign(TileEntitySign signTile) { signTile.setPlayer(this.entity); - this.sendPacket(new SPacketSignEditorOpen(signTile.getPos())); + this.sendPacket(new S36PacketSignEditorOpen(signTile.getPos())); } public void displayGui(IInteractionObject guiOwner) { this.getNextWindowId(); - this.sendPacket(new SPacketOpenWindow(this.currentWindowId, guiOwner.getGuiID(), guiOwner.getCommandName())); + this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, guiOwner.getGuiID(), guiOwner.getCommandName())); this.entity.openContainer = guiOwner.createContainer(this.entity.inventory, this.entity); this.entity.openContainer.windowId = this.currentWindowId; this.entity.openContainer.onCraftGuiOpened(this); @@ -692,27 +751,27 @@ public class Player extends User implements ICrafting, Executor, IPlayer if (ilockablecontainer.isLocked() && !this.entity.canOpen(ilockablecontainer.getLockCode())) // && !this.isSpectator()) { this.addHotbar(TextColor.RED + "%s ist verschlossen!", chestInventory.getCommandName()); - this.sendPacket(new SPacketSoundEffect(SoundEvent.DOOR, this.entity.posX, this.entity.posY, this.entity.posZ, 1.0F)); + this.sendPacket(new S29PacketSoundEffect(SoundEvent.DOOR, this.entity.posX, this.entity.posY, this.entity.posZ, 1.0F)); return; } } this.getNextWindowId(); - if (chestInventory instanceof TileEntityDevice) + if (chestInventory instanceof TileEntityMachine) { - this.sendPacket(new SPacketOpenWindow(this.currentWindowId, "tile", chestInventory.getCommandName(), chestInventory.getSizeInventory(), - ((TileEntityDevice)chestInventory).getPos())); + this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "machine_" + ((IInteractionObject)chestInventory).getGuiID(), chestInventory.getCommandName(), chestInventory.getSizeInventory(), + ((TileEntityMachine)chestInventory).getPos())); this.entity.openContainer = ((IInteractionObject)chestInventory).createContainer(this.entity.inventory, this.entity); } else if (chestInventory instanceof IInteractionObject) { - this.sendPacket(new SPacketOpenWindow(this.currentWindowId, ((IInteractionObject)chestInventory).getGuiID(), chestInventory.getCommandName(), chestInventory.getSizeInventory())); + this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, ((IInteractionObject)chestInventory).getGuiID(), chestInventory.getCommandName(), chestInventory.getSizeInventory())); this.entity.openContainer = ((IInteractionObject)chestInventory).createContainer(this.entity.inventory, this.entity); } else { - this.sendPacket(new SPacketOpenWindow(this.currentWindowId, "container", chestInventory.getCommandName(), chestInventory.getSizeInventory())); + this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "container", chestInventory.getCommandName(), chestInventory.getSizeInventory())); this.entity.openContainer = new ContainerChest(this.entity.inventory, chestInventory, this.entity); } @@ -720,7 +779,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer this.entity.openContainer.onCraftGuiOpened(this); } - public void displayEntityGui(Entity entity, IInventory inventory) + public void displayGUIHorse(EntityHorse horse, IInventory horseInventory) { if (this.entity.openContainer != this.entity.inventoryContainer) { @@ -728,8 +787,8 @@ public class Player extends User implements ICrafting, Executor, IPlayer } this.getNextWindowId(); - this.sendPacket(new SPacketOpenWindow(this.currentWindowId, "entity", inventory.getCommandName(), inventory.getSizeInventory(), entity.getId())); - this.entity.openContainer = new ContainerEntityInventory(this.entity.inventory, inventory, entity, this.entity); + this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "EntityHorse", horseInventory.getCommandName(), horseInventory.getSizeInventory(), horse.getId())); + this.entity.openContainer = new ContainerHorseInventory(this.entity.inventory, horseInventory, horse, this.entity); this.entity.openContainer.windowId = this.currentWindowId; this.entity.openContainer.onCraftGuiOpened(this); } @@ -746,7 +805,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer public void closeScreen() { - this.sendPacket(new SPacketCloseWindow(this.entity.openContainer.windowId)); + this.sendPacket(new S2EPacketCloseWindow(this.entity.openContainer.windowId)); this.closeContainer(); } @@ -765,7 +824,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer public void onItemUseFinish() { - this.sendPacket(new SPacketEntityStatus(this.entity, (byte)9)); + this.sendPacket(new S1APacketEntityStatus(this.entity, (byte)9)); } // /** @@ -783,17 +842,17 @@ public class Player extends User implements ICrafting, Executor, IPlayer public void onNewEffect(PotionEffect id) { - this.sendPacket(new SPacketEntityEffect(this.entity.getId(), id)); + this.sendPacket(new S1DPacketEntityEffect(this.entity.getId(), id)); } public void onChangedEffect(PotionEffect id, boolean added) { - this.sendPacket(new SPacketEntityEffect(this.entity.getId(), id)); + this.sendPacket(new S1DPacketEntityEffect(this.entity.getId(), id)); } public void onFinishedEffect(PotionEffect effect) { - this.sendPacket(new SPacketRemoveEntityEffect(this.entity.getId(), effect)); + this.sendPacket(new S1EPacketRemoveEntityEffect(this.entity.getId(), effect)); } public void setPositionAndUpdate(double x, double y, double z) @@ -818,7 +877,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer public void playSound(SoundEvent name, float volume) { - this.server.sendNearExcept(this.entity, this.entity.posX, this.entity.posY, this.entity.posZ, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.entity.worldObj.dimension.getDimensionId(), new SPacketSoundEffect(name, this.entity.posX, this.entity.posY, this.entity.posZ, volume)); + this.server.sendNearExcept(this.entity, this.entity.posX, this.entity.posY, this.entity.posZ, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.entity.worldObj.dimension.getDimensionId(), new S29PacketSoundEffect(name, this.entity.posX, this.entity.posY, this.entity.posZ, volume)); } @@ -838,7 +897,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer { if (!this.isChangingQuantityOnly) { - this.sendPacket(new SPacketSetSlot(containerToSend.windowId, slotInd, stack)); + this.sendPacket(new S2FPacketSetSlot(containerToSend.windowId, slotInd, stack)); } } } @@ -850,115 +909,24 @@ public class Player extends User implements ICrafting, Executor, IPlayer public void updateCraftingInventory(Container containerToSend, List itemsList) { - this.sendPacket(new SPacketWindowItems(containerToSend.windowId, itemsList)); - this.sendPacket(new SPacketSetSlot(-1, -1, this.entity.inventory.getItemStack())); + this.sendPacket(new S30PacketWindowItems(containerToSend.windowId, itemsList)); + this.sendPacket(new S2FPacketSetSlot(-1, -1, this.entity.inventory.getItemStack())); } public void sendProgressBarUpdate(Container containerIn, int varToUpdate, int newValue) { - this.sendPacket(new SPacketWindowProperty(containerIn.windowId, varToUpdate, newValue)); + this.sendPacket(new S31PacketWindowProperty(containerIn.windowId, varToUpdate, newValue)); } public void sendAllWindowProperties(Container p_175173_1_, IInventory p_175173_2_) { for (int i = 0; i < p_175173_2_.getFieldCount(); ++i) { - this.sendPacket(new SPacketWindowProperty(p_175173_1_.windowId, i, p_175173_2_.getField(i))); + this.sendPacket(new S31PacketWindowProperty(p_175173_1_.windowId, i, p_175173_2_.getField(i))); } } - - public static SPacketChunkData.Extracted getExtractedData(ChunkServer chunk, boolean biomes, boolean overworld, int[] extend) - { - Set aextendedblockstorage = chunk.getStorage(); - SPacketChunkData.Extracted s21packetchunkdata$extracted = new SPacketChunkData.Extracted(); - List list = Lists.newArrayList(); - - if(extend == null) { - for(BlockArray arr : aextendedblockstorage) { - if(arr != null && (!biomes || !arr.isEmpty())) - list.add(arr); - } - } - else { - for(int cy : extend) { - BlockArray arr = chunk.getArray(cy); - if(arr != null && (!biomes || !arr.isEmpty())) - list.add(arr); - } - } - extend = new int[list.size()]; - for(int z = 0; z < extend.length; z++) { - extend[z] = list.get(z).getY() >> 4; - } - - s21packetchunkdata$extracted.extend = extend; - s21packetchunkdata$extracted.data = new byte[SPacketChunkData.getSize(extend.length, overworld, biomes)]; - int j = 0; - - for (BlockArray extendedblockstorage1 : list) - { - char[] achar = extendedblockstorage1.getData(); - - for (char c0 : achar) - { - s21packetchunkdata$extracted.data[j++] = (byte)(c0 & 255); - s21packetchunkdata$extracted.data[j++] = (byte)(c0 >> 8 & 255); - } - } - - for (BlockArray extendedblockstorage2 : list) - { - j = copyTo(extendedblockstorage2.getBlocklight().getData(), s21packetchunkdata$extracted.data, j); - } - - if (overworld) - { - for (BlockArray extendedblockstorage3 : list) - { - j = copyTo(extendedblockstorage3.getSkylight().getData(), s21packetchunkdata$extracted.data, j); - } - } - - if (biomes) - { - copyTo(chunk.getBiomes(), s21packetchunkdata$extracted.data, j); - } - - return s21packetchunkdata$extracted; - } - - private static int copyTo(byte[] src, byte[] dest, int offset) - { - System.arraycopy(src, 0, dest, offset, src.length); - return offset + src.length; - } - - public static SPacketChunkData getPacket(ChunkServer chunkIn, boolean biomes, int[] extend, boolean sky) - { - return new SPacketChunkData(chunkIn.xPos, chunkIn.zPos, biomes, getExtractedData(chunkIn, biomes, sky, extend)); - } - - private static SPacketMapChunkBulk getPacket(List chunks, boolean sky) - { - int i = chunks.size(); - int[] xPositions = new int[i]; - int[] zPositions = new int[i]; - SPacketChunkData.Extracted[] chunksData = new SPacketChunkData.Extracted[i]; - - for (int j = 0; j < i; ++j) - { - ChunkServer chunk = chunks.get(j); - SPacketChunkData.Extracted s21packetchunkdata$extracted = getExtractedData(chunk, true, sky, null); - xPositions[j] = chunk.xPos; - zPositions[j] = chunk.zPos; - chunksData[j] = s21packetchunkdata$extracted; - } - - return new SPacketMapChunkBulk(xPositions, zPositions, chunksData, sky); - } - public void updateEntity() { @@ -995,7 +963,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer if (!this.loadedChunks.isEmpty()) { - List list = Lists.newArrayList(); + List list = Lists.newArrayList(); Iterator iterator1 = this.loadedChunks.iterator(); List list1 = Lists.newArrayList(); @@ -1009,12 +977,12 @@ public class Player extends User implements ICrafting, Executor, IPlayer { if (this.entity.worldObj.isBlockLoaded(new BlockPos(chunkcoordintpair.x << 4, 0, chunkcoordintpair.z << 4))) { - ChunkServer chunk = this.getEntityWorld().getChunk(chunkcoordintpair.x, chunkcoordintpair.z); + Chunk chunk = this.entity.worldObj.getChunk(chunkcoordintpair.x, chunkcoordintpair.z); if (chunk.isPopulated()) { list.add(chunk); - list1.addAll(((WorldServer)this.entity.worldObj).getTileEntitiesIn(chunkcoordintpair.x * 16, -World.MAX_SIZE_Y, chunkcoordintpair.z * 16, chunkcoordintpair.x * 16 + 16, World.MAX_SIZE_Y, chunkcoordintpair.z * 16 + 16)); + list1.addAll(((WorldServer)this.entity.worldObj).getTileEntitiesIn(chunkcoordintpair.x * 16, 0, chunkcoordintpair.z * 16, chunkcoordintpair.x * 16 + 16, 512, chunkcoordintpair.z * 16 + 16)); iterator1.remove(); } } @@ -1029,11 +997,11 @@ public class Player extends User implements ICrafting, Executor, IPlayer { if (list.size() == 1) { - this.sendPacket(getPacket(list.get(0), true, null, !this.entity.worldObj.dimension.hasNoLight())); + this.sendPacket(new SPacketChunkData((Chunk)list.get(0), true, 0xffffffff)); } else { - this.sendPacket(getPacket(list, !this.entity.worldObj.dimension.hasNoLight())); + this.sendPacket(new SPacketMapChunkBulk(list)); } for (TileEntity tileentity : list1) @@ -1041,7 +1009,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer this.sendTileEntityUpdate(tileentity); } - for (ChunkServer chunk1 : list) + for (Chunk chunk1 : list) { this.getEntityWorld().updateChunksForPlayer(this.entity, chunk1); } @@ -1060,7 +1028,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer int i = this.curblockDamage - this.initialBlockDamage; Block block = this.entity.worldObj.getState(this.removingPos).getBlock(); - if (block == Blocks.air) + if (block.getMaterial() == Material.air) { this.receivedFinishDiggingPacket = false; } @@ -1086,7 +1054,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer { Block block1 = this.entity.worldObj.getState(this.startPos).getBlock(); - if (block1 == Blocks.air) + if (block1.getMaterial() == Material.air) { this.entity.worldObj.sendBlockBreakProgress(this.entity.getId(), this.startPos, -1); this.durabilityRemainingOnBlock = -1; @@ -1129,13 +1097,13 @@ public class Player extends User implements ICrafting, Executor, IPlayer this.initialDamage = this.curblockDamage; float f = 1.0F; - if (block != Blocks.air) + if (block.getMaterial() != Material.air) { block.onBlockClicked(this.entity.worldObj, pos, this.entity); f = block.getPlayerRelativeBlockHardness(this.entity, this.entity.worldObj, pos); } - if (block != Blocks.air && f >= 1.0F) + if (block.getMaterial() != Material.air && f >= 1.0F) { this.tryHarvestBlock(pos); } @@ -1157,7 +1125,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer int i = this.curblockDamage - this.initialDamage; Block block = this.entity.worldObj.getState(pos).getBlock(); - if (block != Blocks.air) + if (block.getMaterial() != Material.air) { float f = block.getPlayerRelativeBlockHardness(this.entity, this.entity.worldObj, pos) * (float)(i + 1); @@ -1225,7 +1193,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer { itemstack1.onBlockDestroyed(this.entity.worldObj, iblockstate.getBlock(), pos, this.entity); - if (itemstack1.size == 0) + if (itemstack1.stackSize == 0) { this.entity.destroyCurrentEquippedItem(); } @@ -1246,11 +1214,11 @@ public class Player extends User implements ICrafting, Executor, IPlayer // if(this.onPlayerInteract(false, null)) { // return true; // } - int i = stack.size; + int i = stack.stackSize; int j = stack.getMetadata(); ItemStack itemstack = stack.useItemRightClick(this.entity.worldObj, this.entity); - if (itemstack != stack || itemstack != null && (itemstack.size != i || itemstack.getMaxItemUseDuration() > 0 || itemstack.getMetadata() != j)) + if (itemstack != stack || itemstack != null && (itemstack.stackSize != i || itemstack.getMaxItemUseDuration() > 0 || itemstack.getMetadata() != j)) { this.entity.inventory.mainInventory[this.entity.inventory.currentItem] = itemstack; @@ -1264,7 +1232,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer // } // } - if (itemstack.size == 0) + if (itemstack.stackSize == 0) { this.entity.inventory.mainInventory[this.entity.inventory.currentItem] = null; } @@ -1564,18 +1532,18 @@ public class Player extends User implements ICrafting, Executor, IPlayer this.addHotbar(TextColor.YELLOW + (info.isEmpty() ? "Keine Drehung" : info)); } - public TagObject readCharacter() { + public NBTTagCompound readCharacter() { return this.characters.isEmpty() || this.selected < 0 ? null : this.characters.get(this.selected); } - public void writeCharacter(TagObject tag) { + public void writeCharacter(NBTTagCompound tag) { if(!this.characters.isEmpty() && this.selected >= 0) this.characters.set(this.selected, tag); } public void disconnect(String message) { - Log.NETWORK.info("Trenne %s: %s", this.getUser(), message); + Log.JNI.info("Trenne %s: %s", this.user, message); this.connection.sendPacket(new SPacketDisconnect(message), new GenericFutureListener < Future > () { public void operationComplete(Future p_operationComplete_1_) throws Exception @@ -1595,32 +1563,33 @@ public class Player extends User implements ICrafting, Executor, IPlayer public void onDisconnect(String reason) { - Log.NETWORK.info(this.getUser() + " wurde getrennt: " + TextColor.stripCodes(reason)); - this.server.sendPacket(new SPacketMessage(String.format("%s hat das Spiel verlassen", this.getUser()), Type.FEED)); + Log.JNI.info(this.user + " wurde getrennt: " + TextColor.stripCodes(reason)); + this.server.sendPacket(new SPacketMessage(String.format("%s hat das Spiel verlassen", this.user), Type.FEED)); this.server.removePlayer(this); } - public PlayerCharacter getCharacterInfo(TagObject tag) { + public PlayerCharacter getCharacterInfo(NBTTagCompound tag) { String name = tag.getString("CustomName"); String info = tag.getString("Description"); if(info != null && info.isEmpty()) info = null; Alignment align = Alignment.getByName(tag.getString("Align")); - Dimension dimension = UniverseRegistry.getDimension(tag.getInt("Dimension")); + NBTTagList position = tag.getTagList("Pos", 6); + Dimension dimension = UniverseRegistry.getDimension(tag.getInteger("Dimension")); String dim = dimension == null ? "???" : dimension.getFormattedName(false); - BlockPos pos = new BlockPos(tag.getDouble("PosX"), tag.getDouble("PosY"), tag.getDouble("PosZ")); + BlockPos pos = new BlockPos(position.getDoubleAt(0), position.getDoubleAt(1), position.getDoubleAt(2)); String type = EntityRegistry.getEntityName(tag.getString("id")); - int level = tag.getInt("XpLevel"); + int level = tag.getInteger("XpLevel"); return new PlayerCharacter(name, info, align, dim, pos, type, level); } public void onConnect() { List chars = Lists.newArrayList(); - for(TagObject tag : this.characters) { + for(NBTTagCompound tag : this.characters) { chars.add(this.getCharacterInfo(tag)); } this.sendPacket(new SPacketCharacterList(this.selected, chars)); - this.server.sendPacket(new SPacketMessage(String.format("%s hat das Spiel betreten", this.getUser()), Type.FEED)); + this.server.sendPacket(new SPacketMessage(String.format("%s hat das Spiel betreten", this.user), Type.FEED)); } public void sendPacket(final Packet packet) @@ -1726,8 +1695,14 @@ public class Player extends User implements ICrafting, Executor, IPlayer return true; } + private boolean setVar(String line) { + if(!this.isAdmin()) + return false; + return this.server.setVar(this, line); + } + public void setAdmin(boolean admin) { - super.setAdmin(admin); + this.admin = admin; if(!this.isAdmin() && this.entity != null && this.entity.noclip) { this.entity.noclip = false; this.entity.flying &= this.entity.hasEffect(Potion.FLYING) || this.entity.canNaturallyFly(); @@ -1899,35 +1874,20 @@ public class Player extends User implements ICrafting, Executor, IPlayer // return Lists.newArrayList(); } - public void setForcedExec(Executor forced) { - this.forcedExec = forced; + public void logConsole(String msg) { + this.addConsole(msg); } - public void setExecPos(Position pos) { - this.forcedPos = pos; + public String getExecId() { + return this.user; } - public void log(String msg) { - if(this.forcedExec != null) - this.forcedExec.log(TextColor.ACID + "Als " + TextColor.GREEN + "%s" + TextColor.DGRAY + ": " + TextColor.RESET + "%s", this.getUser(), msg); - else - this.addConsole(msg); + public String getExecName() { + return this.entity != null ? this.entity.getCommandName() : this.user; } public Position getExecPos() { - return this.forcedPos != null ? this.forcedPos : (this.entity != null ? this.entity.getPos() : null); - } - - public Entity getPointedEntity() { - return this.pointedEntity != -1 && this.entity != null ? this.entity.worldObj.getEntityByID(this.pointedEntity) : null; - } - - public BlockPos getPointedPosition() { - return this.pointedPosition; - } - - public boolean isPlayer() { - return true; + return this.entity != null ? this.entity.getPos() : null; } public void processMessage(CPacketMessage packetIn) @@ -1947,7 +1907,8 @@ public class Player extends User implements ICrafting, Executor, IPlayer switch(type) { case COMMAND: - this.runCommand(msg); // this.addFeed(TextColor.RED + "Befehl wurde nicht gefunden"); + if(!this.setVar(msg)) + this.runCommand(msg); // this.addFeed(TextColor.RED + "Befehl wurde nicht gefunden"); break; case CHAT: @@ -1977,21 +1938,63 @@ public class Player extends User implements ICrafting, Executor, IPlayer } } +// private Iterable getWarpList(char pre) { +// switch(pre) { +// case '+': +// return Lists.newArrayList(this.server.getUsers()); +// case '@': +// List warps = Lists.newArrayList("spawn"); +// for(String warp : this.server.getWarps().keySet()) { +// warps.add(warp); +// } +// return warps; +// case '*': +// return UniverseRegistry.getWorldNames(); +// } +// return Lists.newArrayList(); +// } + +// private static List getVarList() { +// List list = ; +// list.add("time"); +// return list; +// } + + private List getVarCompletion(String var) { + Config.Value v = Config.VARS.get(var); + if(v == null) + return Lists.newArrayList(); + if(v.type == ValueType.BOOLEAN) + return Boolean.parseBoolean(v.getValue()) ? Lists.newArrayList("false", "true") : Lists.newArrayList("true", "false"); + else if(v.type == ValueType.INTEGER || v.type == ValueType.FLOAT) + return Lists.newArrayList(v.def); + return Lists.newArrayList(); + } + public void processComplete(CPacketComplete packetIn) { NetHandler.checkThread(packetIn, this, this.server); if(this.charEditor || !this.isAdmin()) { - this.entity.connection.sendPacket(new SPacketTabComplete(new String[0])); + this.entity.connection.sendPacket(new S3APacketTabComplete(new String[0])); return; } this.pointedEntity = packetIn.getEntityId(); this.pointedPosition = packetIn.getPosition(); if(packetIn.getMessage().startsWith(" ")) { - this.entity.connection.sendPacket(new SPacketTabComplete(new String[0])); + this.entity.connection.sendPacket(new S3APacketTabComplete(new String[0])); return; } - List list = this.completeCommand(packetIn.getMessage()); - this.entity.connection.sendPacket(new SPacketTabComplete(list.toArray(new String[list.size()]))); + List list = Lists.newArrayList(); + String s = packetIn.getMessage(); + String[] argv = s.split(" ", -1); + s = argv[argv.length - 1]; + Iterable res = argv.length == 1 ? Lists.newArrayList(Config.VARS.keySet()) : (argv.length == 2 ? getVarCompletion(argv[0]) : Lists.newArrayList()); + for(String s1 : res) { + if(s1.regionMatches(true, 0, s, 0, s.length())) + list.add(s1); + } + list.addAll(this.completeCommand(packetIn.getMessage())); + this.entity.connection.sendPacket(new S3APacketTabComplete(list.toArray(new String[list.size()]))); } private static boolean isFinite(double value) { @@ -2071,7 +2074,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer if (d3 > 4.0D) { Entity entity = this.entity.vehicle; - this.entity.connection.sendPacket(new SPacketEntityTeleport(entity)); + this.entity.connection.sendPacket(new S18PacketEntityTeleport(entity)); this.setPlayerLocation(this.entity.posX, this.entity.posY, this.entity.posZ, this.entity.rotYaw, this.entity.rotPitch); } @@ -2107,7 +2110,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer float f1 = this.entity.rotYaw; float f2 = this.entity.rotPitch; - if (packetIn.isMoving() && packetIn.getPositionY() == -99999999.0D) + if (packetIn.isMoving() && packetIn.getPositionY() == -999.0D) { packetIn.setMoving(false); } @@ -2182,7 +2185,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer } this.entity.setPositionAndRotation(d8, d9, d10, f1, f2); - this.entity.addMovement(this.entity.posX - d0, this.entity.posY - d1, this.entity.posZ - d2); + this.entity.addMovementStat(this.entity.posX - d0, this.entity.posY - d1, this.entity.posZ - d2); if (!this.entity.noClip) { @@ -2290,7 +2293,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer { return; } - else if (blockpos.getY() >= World.MAX_SIZE_Y) + else if (blockpos.getY() >= World.HEIGHT) { return; } @@ -2318,7 +2321,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer this.cancelDestroyingBlock(); } - if (worldserver.getState(blockpos).getBlock() != Blocks.air) + if (worldserver.getState(blockpos).getBlock().getMaterial() != Material.air) { this.sendPacket(new SPacketBlockChange(worldserver, blockpos)); } @@ -2354,7 +2357,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer this.tryUseItem(itemstack); // } } - else if (blockpos.getY() < World.MAX_SIZE_Y - 1 || enumfacing != Facing.UP && blockpos.getY() < World.MAX_SIZE_Y) + else if (blockpos.getY() < World.HEIGHT - 1 || enumfacing != Facing.UP && blockpos.getY() < World.HEIGHT) { double max = this.entity.getReachDistance() + 3.0D; max *= max; @@ -2381,7 +2384,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer itemstack = this.entity.inventory.getCurrentItem(); - if (itemstack != null && itemstack.size == 0) + if (itemstack != null && itemstack.stackSize == 0) { this.entity.inventory.mainInventory[this.entity.inventory.currentItem] = null; itemstack = null; @@ -2397,7 +2400,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer if (!ItemStack.areItemStacksEqual(this.entity.inventory.getCurrentItem(), packetIn.getStack())) { - this.sendPacket(new SPacketSetSlot(this.entity.openContainer.windowId, slot.slotNumber, this.entity.inventory.getCurrentItem())); + this.sendPacket(new S2FPacketSetSlot(this.entity.openContainer.windowId, slot.slotNumber, this.entity.inventory.getCurrentItem())); } } } @@ -2441,7 +2444,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer NetHandler.checkThread(packetIn, this, this.server); CPacketAction.Action action = packetIn.getAction(); - if(this.charEditor != (action == Action.SET_ALIGN || action == Action.SET_SPECIES || action == Action.SET_CLASS || action == Action.SET_HEIGHT || action == Action.CLOSE_EDITOR || action == Action.CANCEL_EDITOR)) // { + if(this.charEditor != (action == Action.SET_ALIGN || action == Action.SET_SPECIES || action == Action.SET_CLASS || action == Action.SET_HEIGHT || action == Action.CLOSE_EDITOR)) // { // if(this.local && action == Action.CLOSE_EDITOR) // this.server.setDone(); return; @@ -2453,12 +2456,11 @@ public class Player extends User implements ICrafting, Executor, IPlayer this.charEditor = true; // if(this.local) // this.server.resetProgress(); - TagObject tag = this.server.swapPlayer(this, null, EntityHuman.class); + NBTTagCompound tag = this.server.swapPlayer(this, null, EntityHuman.class); if(!this.characters.isEmpty() && this.selected >= 0) this.characters.set(this.selected, tag); int last = this.selected; this.selected = -1; - this.teleportPos = this.deathPos = null; this.sendPacket(!this.characters.isEmpty() && last >= 0 ? new SPacketCharacterList(this.selected, last, this.getCharacterInfo(tag)) : new SPacketCharacterList(this.selected)); break; } @@ -2466,43 +2468,29 @@ public class Player extends User implements ICrafting, Executor, IPlayer case CLOSE_EDITOR: { this.charEditor = false; this.selected = this.characters.size(); - this.characters.add(new TagObject()); + this.characters.add(new NBTTagCompound()); WorldServer world = this.server.getWorld(packetIn.getAuxData()); world = world == null ? this.server.getSpace() : world; - WorldPos origin = new WorldPos(world.rand.range(-SVars.originRadius, SVars.originRadius), 64, world.rand.range(-SVars.originRadius, SVars.originRadius), + WorldPos origin = new WorldPos(world.rand.range(-Config.originRadius, Config.originRadius), 64, world.rand.range(-Config.originRadius, Config.originRadius), world.dimension.getDimensionId()); this.entity.setOrigin(origin); Position pos = this.server.getRandomSpawnPosition(origin); this.entity.teleport(pos); - this.teleportPos = this.deathPos = null; this.sendPacket(new SPacketCharacterList(this.selected, this.selected, new PlayerCharacter(this.entity.getCustomNameTag(), this.entity.getDescription(), this.entity.getAlignment(), this.entity.worldObj.dimension.getFormattedName(false), this.entity.getPosition(), EntityRegistry.getEntityName(EntityRegistry.getEntityString(this.entity)), this.entity.experienceLevel))); // if(this.local) // this.server.setDone(); break; } - - case CANCEL_EDITOR: { - int index = packetIn.getAuxData(); - if(index >= this.characters.size() || index < 0) - return; - this.charEditor = false; - this.server.swapPlayer(this, this.characters.get(index), null); - this.selected = index; - this.teleportPos = this.deathPos = null; - this.sendPacket(new SPacketCharacterList(this.selected)); - break; - } case SELECT_CHARACTER: { int index = packetIn.getAuxData(); if(index == this.selected || index >= this.characters.size() || index < 0) return; - TagObject etag = this.server.swapPlayer(this, this.characters.get(index), null); + NBTTagCompound etag = this.server.swapPlayer(this, this.characters.get(index), null); if(!this.characters.isEmpty() && this.selected >= 0) this.characters.set(this.selected, etag); int last = this.selected; this.selected = index; - this.teleportPos = this.deathPos = null; this.sendPacket(!this.characters.isEmpty() && last >= 0 ? new SPacketCharacterList(this.selected, last, this.getCharacterInfo(etag)) : new SPacketCharacterList(this.selected)); break; } @@ -2598,7 +2586,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer } catch (Exception e) { - Log.TICK.error(e, "Konnte Handel nicht wählen"); + Log.JNI.error(e, "Konnte Handel nicht wählen"); } break; @@ -2661,9 +2649,10 @@ public class Player extends User implements ICrafting, Executor, IPlayer break; case ENCHANT_ITEM: - if(this.entity.openContainer instanceof ContainerEnchantment ench && ench.windowId == (packetIn.getAuxData() & 255) && ench.getCanCraft(this.entity)) { - ench.enchantItem(this.entity, (packetIn.getAuxData() >> 8) % 3); - ench.detectAndSendChanges(); + if(this.entity.openContainer.windowId == (packetIn.getAuxData() & 255) && this.entity.openContainer.getCanCraft(this.entity)) // && !this.playerEntity.isSpectator()) + { + this.entity.openContainer.enchantItem(this.entity, (packetIn.getAuxData() >> 8) % 3); + this.entity.openContainer.detectAndSendChanges(); } break; @@ -2682,15 +2671,39 @@ public class Player extends User implements ICrafting, Executor, IPlayer case GOD: if(this.isAdmin()) { - boolean god = !this.entity.hasEffect(Potion.HASTE) || this.entity.getEffect(Potion.HASTE).getAmplifier() != 255; - this.entity.setGodMode(god); - this.addFeed(god ? (TextColor.GREEN + "Statuseffekte wurden hinzugefügt") : (TextColor.RED + "Statuseffekte wurden entfernt")); +// this.playerEntity.setCheat(!this.playerEntity.godmode); + this.entity.fallDistance = 0.0F; + if(this.entity.hasEffect(Potion.HASTE) && this.entity.getEffect(Potion.HASTE).getAmplifier() == 255) { + this.entity.removeEffect(Potion.HASTE); + this.entity.removeEffect(Potion.RESISTANCE); + this.entity.removeEffect(Potion.FIRE_RESISTANCE); + this.entity.removeEffect(Potion.FLYING); + this.entity.removeEffect(Potion.MANA); + this.addFeed(TextColor.RED + "Statuseffekte wurden entfernt"); + } + else { + this.entity.extinguish(); + this.entity.setHealth(this.entity.getMaxHealth()); + this.entity.setManaPoints(this.entity.getMaxMana()); + this.entity.clearEffects(false); + this.entity.addEffect(new PotionEffect(Potion.HASTE, Integer.MAX_VALUE, 255, false, false)); + this.entity.addEffect(new PotionEffect(Potion.RESISTANCE, Integer.MAX_VALUE, 255, false, false)); + this.entity.addEffect(new PotionEffect(Potion.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, false, false)); + this.entity.addEffect(new PotionEffect(Potion.FLYING, Integer.MAX_VALUE, 0, false, false)); + this.entity.addEffect(new PotionEffect(Potion.MANA, Integer.MAX_VALUE, 255, false, false)); + this.addFeed(TextColor.GREEN + "Statuseffekte wurden hinzugefügt"); + } } break; case NOCLIP: if(this.isAdmin()) { - this.entity.setNoclip(!this.entity.noclip); + if(!this.entity.noclip) + this.entity.mountEntity(null); + this.entity.noclip ^= true; + this.entity.flying &= this.entity.hasEffect(Potion.FLYING) || this.entity.noclip || this.entity.canNaturallyFly(); + this.entity.fallDistance = 0.0F; + this.sendPlayerAbilities(); this.addFeed((this.entity.noclip ? TextColor.GREEN : TextColor.RED) + "NoClip ist jetzt " + (this.entity.noclip ? "eingeschaltet" : "ausgeschaltet")); } break; @@ -2722,8 +2735,8 @@ public class Player extends User implements ICrafting, Executor, IPlayer case REPAIR: if(this.isAdmin() && this.entity.getCurrentEquippedItem() != null) { ItemStack itemstack = this.entity.getCurrentEquippedItem(); - int diff = itemstack.getMaxStackSize() - itemstack.size; - itemstack.size = itemstack.getMaxStackSize(); + int diff = itemstack.getMaxStackSize() - itemstack.stackSize; + itemstack.stackSize = itemstack.getMaxStackSize(); itemstack.setRepairCost(0); if(itemstack.getItem().getMaxDamage() > 0) itemstack.setItemDamage(0); @@ -2803,12 +2816,12 @@ public class Player extends User implements ICrafting, Executor, IPlayer break; case START_PROFILING: - if(this.isAdmin()) + if(this.admin) this.profiling = true; break; case STOP_PROFILING: - if(this.isAdmin()) + if(this.admin) this.profiling = false; break; @@ -2850,7 +2863,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer if (ItemStack.areItemStacksEqual(packetIn.getClickedItem(), itemstack)) { - this.entity.connection.sendPacket(new SPacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true)); + this.entity.connection.sendPacket(new S32PacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true)); this.isChangingQuantityOnly = true; this.entity.openContainer.detectAndSendChanges(); this.updateHeldItem(); @@ -2859,7 +2872,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer else { this.transactions.addKey(this.entity.openContainer.windowId, Short.valueOf(packetIn.getActionNumber())); - this.entity.connection.sendPacket(new SPacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), false)); + this.entity.connection.sendPacket(new S32PacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), false)); this.entity.openContainer.setCanCraft(this.entity, false); List list1 = Lists.newArrayList(); @@ -2874,9 +2887,9 @@ public class Player extends User implements ICrafting, Executor, IPlayer } } - public void processCheat(CPacketCheat packet) + public void processCheat(CPacketCheat packetIn) { - NetHandler.checkThread(packet, this, this.server); + NetHandler.checkThread(packetIn, this, this.server); if(this.charEditor) return; @@ -2887,7 +2900,7 @@ public class Player extends User implements ICrafting, Executor, IPlayer // { // boolean drop = packetIn.getSlotId() < 0; // boolean changed = false; - ItemStack itemstack = packet.getStack(); + ItemStack itemstack = packetIn.getStack(); // if(itemstack != null && itemstack.getItem() == Items.barrier && !this.playerEntity.canUse(Permissions.BARRIER)) { // changed = true; // itemstack = null; @@ -2896,28 +2909,28 @@ public class Player extends User implements ICrafting, Executor, IPlayer // changed = true; // } - if (itemstack.hasTagCompound() && itemstack.getTagCompound().hasObject("BlockEntityTag")) + if (itemstack.hasTagCompound() && itemstack.getTagCompound().hasKey("BlockEntityTag")) { -// if(!itemstack.getTagCompound().hasTag("BlockEntityTag")) { +// if(!itemstack.getTagCompound().hasKey("BlockEntityTag", 10)) { // changed = true; // itemstack.setTagCompound(null); // } // else { - TagObject tag = itemstack.getTagCompound().getObject("BlockEntityTag"); + NBTTagCompound nbttagcompound = itemstack.getTagCompound().getCompoundTag("BlockEntityTag"); - if (tag.hasInt("x") && tag.hasInt("y") && tag.hasInt("z")) + if (nbttagcompound.hasKey("x") && nbttagcompound.hasKey("y") && nbttagcompound.hasKey("z")) { - BlockPos pos = new BlockPos(tag.getInt("x"), tag.getInt("y"), tag.getInt("z")); - TileEntity te = this.entity.worldObj.getTileEntity(pos); + BlockPos blockpos = new BlockPos(nbttagcompound.getInteger("x"), nbttagcompound.getInteger("y"), nbttagcompound.getInteger("z")); + TileEntity tileentity = this.entity.worldObj.getTileEntity(blockpos); - if (te != null) + if (tileentity != null) { - TagObject tile = new TagObject(); - te.writeTags(tile); - tile.remove("x"); - tile.remove("y"); - tile.remove("z"); - itemstack.setTagInfo("BlockEntityTag", tile); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + tileentity.writeToNBT(nbttagcompound1); + nbttagcompound1.removeTag("x"); + nbttagcompound1.removeTag("y"); + nbttagcompound1.removeTag("z"); + itemstack.setTagInfo("BlockEntityTag", nbttagcompound1); } } // } @@ -2925,30 +2938,30 @@ public class Player extends User implements ICrafting, Executor, IPlayer // boolean validSlot = packetIn.getSlotId() >= 1 && packetIn.getSlotId() < 36 + InventoryPlayer.getHotbarSize(); boolean validItem = itemstack.getItem() != null; - boolean validData = itemstack.getMetadata() >= 0 && itemstack.size <= itemstack.getMaxStackSize() && itemstack.size > 0; // TODO: max + boolean validData = itemstack.getMetadata() >= 0 && itemstack.stackSize <= itemstack.getMaxStackSize() && itemstack.stackSize > 0; // TODO: max if (validItem && validData) { - int amount = itemstack.size; - if(packet.getSlot() == -1) { + int amount = itemstack.stackSize; + if(packetIn.getSlot() == -1) { this.entity.inventory.addItemStackToInventory(itemstack); - amount -= itemstack.size; + amount -= itemstack.stackSize; } - else if(packet.getSlot() >= 0 && packet.getSlot() < this.entity.inventory.getSizeInventory() && (packet.getSlot() < this.entity.inventory.mainInventory.length || (itemstack.getItem() instanceof ItemArmor && ((ItemArmor)itemstack.getItem()).armorType.getArmorSlot() == packet.getSlot() - this.entity.inventory.mainInventory.length))) { - ItemStack old = this.entity.inventory.getStackInSlot(packet.getSlot()); + else if(packetIn.getSlot() >= 0 && packetIn.getSlot() < this.entity.inventory.getSizeInventory() && (packetIn.getSlot() < this.entity.inventory.mainInventory.length || (itemstack.getItem() instanceof ItemArmor && ((ItemArmor)itemstack.getItem()).armorType == packetIn.getSlot() - this.entity.inventory.mainInventory.length))) { + ItemStack old = this.entity.inventory.getStackInSlot(packetIn.getSlot()); if(old != null) { if(ItemStack.areItemsEqual(itemstack, old) && ItemStack.areItemStackTagsEqual(itemstack, old)) { - itemstack.size = Math.min(itemstack.getMaxStackSize(), old.size + itemstack.size); - amount = itemstack.size - old.size; + itemstack.stackSize = Math.min(itemstack.getMaxStackSize(), old.stackSize + itemstack.stackSize); + amount = itemstack.stackSize - old.stackSize; } - else if(old.size == 1) + else if(old.stackSize == 1) this.addFeed(TextColor.DRED + "* %s zerstört", old.getColoredName(TextColor.DRED)); else - this.addFeed(TextColor.DRED + "* %d %s zerstört", old.size, + this.addFeed(TextColor.DRED + "* %d %s zerstört", old.stackSize, old.getColoredName(TextColor.DRED)); } - this.entity.inventory.setInventorySlotContents(packet.getSlot(), itemstack); + this.entity.inventory.setInventorySlotContents(packetIn.getSlot(), itemstack); } else { return; @@ -3048,6 +3061,34 @@ public class Player extends User implements ICrafting, Executor, IPlayer // this.lastSkinUpdate = System.currentTimeMillis(); } + public void processBook(CPacketBook packetIn) { + NetHandler.checkThread(packetIn, this, this.server); + if(this.charEditor) + return; + + String[] pages = packetIn.getPages(); +// if (!ItemWritableBook.isNBTValid(itemstack1.getTagCompound())) +// throw new IOException("Fehlerhafter Buch-Tag!"); + ItemStack itemstack = this.entity.inventory.getCurrentItem(); + if (itemstack != null && itemstack.getItem() == Items.writable_book) + { + if(pages.length == 0) { + if(itemstack.hasTagCompound()) { + itemstack.getTagCompound().removeTag("pages"); + if(itemstack.getTagCompound().hasNoTags()) + itemstack.setTagCompound(null); + } + } + else { + NBTTagList list = new NBTTagList(); + for(String page : pages) { + list.appendTag(new NBTTagString(page)); + } + itemstack.setTagInfo("pages", list); + } + } + } + public void processForm(CPacketForm packet) { NetHandler.checkThread(packet, this, this.server); if(this.charEditor || this.form == null || packet.getId() != this.currentFormId) @@ -3061,6 +3102,14 @@ public class Player extends User implements ICrafting, Executor, IPlayer this.getNextFormId(); this.sendPacket(new SPacketDisplayForm(this.currentFormId, form.getTitle(), form.getInputList())); } + + public Entity getPointedEntity() { + return this.pointedEntity != -1 && this.entity != null ? this.entity.worldObj.getEntityByID(this.pointedEntity) : null; + } + + public BlockPos getPointedPosition() { + return this.pointedPosition; + } public List getLoadedChunkList() { return this.loadedChunks; @@ -3078,18 +3127,6 @@ public class Player extends User implements ICrafting, Executor, IPlayer this.managedPosX = x; this.managedPosZ = z; } - - public Position getLastTeleport() { - return this.teleportPos; - } - - public Position getLastDeath() { - return this.deathPos; - } - - public String getEntityName() { - return this.getPresentEntity() == null ? this.getUser() : this.getPresentEntity().getCommandName(); - } // public void processCmdBlock(CPacketCmdBlock packetIn) { // NetHandler.checkThread(packetIn, this, this.serverController); diff --git a/server/src/main/java/server/util/Form.java b/server/src/server/util/Form.java similarity index 100% rename from server/src/main/java/server/util/Form.java rename to server/src/server/util/Form.java diff --git a/server/src/main/java/server/village/VillageCollection.java b/server/src/server/village/VillageCollection.java similarity index 83% rename from server/src/main/java/server/village/VillageCollection.java rename to server/src/server/village/VillageCollection.java index be459ab..4730732 100755 --- a/server/src/main/java/server/village/VillageCollection.java +++ b/server/src/server/village/VillageCollection.java @@ -4,10 +4,11 @@ import java.util.Iterator; import java.util.List; import common.block.Block; -import common.block.Material; -import common.block.artificial.BlockDoor; +import common.block.BlockDoor; import common.collect.Lists; -import common.tags.TagObject; +import common.material.Material; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.util.BlockPos; import common.util.Facing; import common.village.Village; @@ -22,16 +23,16 @@ public class VillageCollection private int tickCounter; private boolean dirty; - public VillageCollection(TagObject tag) { - if(tag != null) { - this.tickCounter = tag.getInt("Tick"); - List list = tag.getList("Villages"); + public VillageCollection(NBTTagCompound nbt) { + if(nbt != null) { + this.tickCounter = nbt.getInteger("Tick"); + NBTTagList nbttaglist = nbt.getTagList("Villages", 10); - for (int i = 0; i < list.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - TagObject obj = list.get(i); + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); Village village = new Village(); - village.readTags(obj); + village.readVillageDataFromNBT(nbttagcompound); this.villageList.add(village); } } @@ -214,15 +215,16 @@ public class VillageCollection for (int j = 1; j <= 5; ++j) { - if (world.canSeeSky(centerPos.offset(direction, j))) - { - ++i; - - if (i >= limitation) - { - return i; + BlockPos pos = centerPos.offset(direction, j); + for(int z = 0; z < 5; z++) { + if(!world.isAirBlock(pos.up(z))) + break; + if(z == 4) { + ++i; + if(i >= limitation) + return i; } - } + } } return i; @@ -244,25 +246,25 @@ public class VillageCollection private boolean isWoodDoor(WorldServer world, BlockPos doorPos) { Block block = world.getState(doorPos).getBlock(); - return block instanceof BlockDoor ? block.getMaterial() == Material.WOOD : false; + return block instanceof BlockDoor ? block.getMaterial() == Material.wood : false; } - public TagObject toTags() + public NBTTagCompound writeToNBT() { - TagObject tag = new TagObject(); - tag.setInt("Tick", this.tickCounter); - List list = Lists.newArrayList(); + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setInteger("Tick", this.tickCounter); + NBTTagList nbttaglist = new NBTTagList(); for (Village village : this.villageList) { - TagObject obj = new TagObject(); - village.writeTags(obj); - list.add(obj); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + village.writeVillageDataToNBT(nbttagcompound); + nbttaglist.appendTag(nbttagcompound); } - tag.setList("Villages", list); + nbt.setTag("Villages", nbttaglist); this.dirty = false; - return tag; + return nbt; } public boolean isDirty() diff --git a/server/src/main/java/server/world/Converter.java b/server/src/server/world/Converter.java similarity index 82% rename from server/src/main/java/server/world/Converter.java rename to server/src/server/world/Converter.java index 7b7bc10..7564a9e 100644 --- a/server/src/main/java/server/world/Converter.java +++ b/server/src/server/world/Converter.java @@ -2,16 +2,14 @@ package server.world; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; -import java.io.DataInput; import java.io.DataInputStream; import java.io.File; -import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.RandomAccessFile; -import java.util.ArrayList; +import java.text.SimpleDateFormat; import java.util.Arrays; -import java.util.List; +import java.util.Date; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; @@ -19,31 +17,30 @@ import java.util.zip.InflaterInputStream; import common.biome.Biome; import common.block.Block; +import common.block.BlockCactus; +import common.block.BlockCarpet; import common.block.BlockColored; -import common.block.artificial.BlockCarpet; -import common.block.artificial.BlockFlowerPot; -import common.block.artificial.BlockQuartz; -import common.block.artificial.BlockSlab; -import common.block.artificial.BlockStainedGlass; -import common.block.artificial.BlockStainedGlassPane; -import common.block.artificial.BlockStoneBrick; -import common.block.artificial.BlockWall; -import common.block.foliage.BlockCactus; -import common.block.foliage.BlockFlower; -import common.block.foliage.BlockLeaves; -import common.block.foliage.BlockLog; -import common.block.foliage.BlockTallGrass; -import common.block.foliage.LeavesType; -import common.block.liquid.BlockLiquid; -import common.block.natural.BlockDirt; -import common.block.natural.BlockFire; -import common.block.natural.BlockRock; -import common.block.natural.BlockSand; -import common.block.natural.BlockSandStone; -import common.block.tech.BlockPistonBase; -import common.block.tech.BlockPistonHead; -import common.block.tech.BlockTNT; -import common.collect.Lists; +import common.block.BlockDirt; +import common.block.BlockFire; +import common.block.BlockFlower; +import common.block.BlockFlowerPot; +import common.block.BlockLeaves; +import common.block.BlockLiquid; +import common.block.BlockLog; +import common.block.BlockPistonBase; +import common.block.BlockPistonHead; +import common.block.BlockQuartz; +import common.block.BlockRock; +import common.block.BlockSand; +import common.block.BlockSandStone; +import common.block.BlockSlab; +import common.block.BlockStainedGlass; +import common.block.BlockStainedGlassPane; +import common.block.BlockStoneBrick; +import common.block.BlockTNT; +import common.block.BlockTallGrass; +import common.block.BlockWall; +import common.block.LeavesType; import common.collect.Maps; import common.color.DyeColor; import common.entity.Entity; @@ -62,11 +59,15 @@ import common.entity.item.EntityBoat; import common.entity.item.EntityMinecart; import common.init.BlockRegistry; import common.init.Blocks; +import common.init.Config; import common.init.EntityRegistry; import common.init.TileRegistry; +import common.init.UniverseRegistry; import common.log.Log; +import common.nbt.NBTLoader; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.rng.Random; -import common.tags.TagObject; import common.tileentity.TileEntity; import common.tileentity.TileEntityBanner; import common.tileentity.TileEntityBeacon; @@ -78,82 +79,19 @@ import common.tileentity.TileEntityDropper; import common.tileentity.TileEntityEnchantmentTable; import common.tileentity.TileEntityFurnace; import common.tileentity.TileEntityHopper; +import common.tileentity.TileEntityMobSpawner; +import common.tileentity.TileEntityNote; +import common.tileentity.TileEntityPiston; import common.tileentity.TileEntitySign; +import common.tileentity.TileEntitySkull; import common.util.Facing; import common.util.NibbleArray; import common.world.State; import common.world.Weather; +import common.world.World; import server.Server; public abstract class Converter { - private static class NbtTag { - private final Map map = Maps.newHashMap(); - - private boolean has(String key, Class type) { - Object tag = this.map.get(key); - return tag != null && tag.getClass() == type; - } - - private List getList(String key, Class type) { - Object tag = this.map.get(key); - if(!(tag instanceof List)) - return Lists.newArrayList(); - List list = (List)tag; - return !list.isEmpty() && list.get(0).getClass() != type ? Lists.newArrayList() : list; - } - - public byte getByte(String key) { - return !this.has(key, Byte.class) ? 0 : (Byte)this.map.get(key); - } - - public int getInt(String key) { - return this.has(key, Integer.class) ? (Integer)this.map.get(key) : (this.has(key, Short.class) ? (Short)this.map.get(key) : this.getByte(key)); - } - - public String getString(String key) { - return !this.has(key, String.class) ? "" : (String)this.map.get(key); - } - - public byte[] getByteArray(String key) { - return !this.has(key, byte[].class) ? new byte[0] : (byte[])this.map.get(key); - } - - public int[] getIntArray(String key) { - return !this.has(key, int[].class) ? new int[0] : (int[])this.map.get(key); - } - - public NbtTag getTag(String key) { - return !this.has(key, NbtTag.class) ? new NbtTag() : (NbtTag)this.map.get(key); - } - - public float[] getFloatList(String key) { - List list = this.getList(key, Float.class); - float[] values = new float[list.size()]; - for(int z = 0; z < values.length; z++) { - values[z] = (Float)list.get(z); - } - return values; - } - - public double[] getDoubleList(String key) { - List list = this.getList(key, Double.class); - double[] values = new double[list.size()]; - for(int z = 0; z < values.length; z++) { - values[z] = (Double)list.get(z); - } - return values; - } - - public NbtTag[] getTagList(String key) { - List list = this.getList(key, NbtTag.class); - NbtTag[] values = new NbtTag[list.size()]; - for(int z = 0; z < values.length; z++) { - values[z] = (NbtTag)list.get(z); - } - return values; - } - } - private static enum SaveVersion { ALPHA_1_0("Alpha 1.0 - Beta 1.2"), BETA_1_3("Beta 1.3 - Release 1.8.9"), @@ -255,7 +193,7 @@ public abstract class Converter { private static long postProgress(long start, int progress) { if(System.currentTimeMillis() - start >= 500L) { start = System.currentTimeMillis(); - Log.IO.info("... " + progress + "%"); + Log.JNI.info("... " + progress + "%"); } return start; } @@ -342,9 +280,12 @@ public abstract class Converter { mapTile(TileEntityDispenser.class, "Trap", "dispenser"); mapTile(TileEntityDropper.class, "Dropper", "dropper"); mapTile(TileEntitySign.class, "Sign", "sign"); - // mapTile(TileEntityPiston.class, "Piston", "piston"); + mapTile(TileEntityMobSpawner.class, "MobSpawner", "mob_spawner"); + mapTile(TileEntityNote.class, "Music", "noteblock"); + mapTile(TileEntityPiston.class, "Piston", "piston"); mapTile(TileEntityEnchantmentTable.class, "EnchantTable", "enchanting_table"); mapTile(TileEntityBeacon.class, "Beacon", "beacon"); + mapTile(TileEntitySkull.class, "Skull", "skull"); mapTile(TileEntityDaylightDetector.class, "DLDetector", "daylight_detector"); mapTile(TileEntityHopper.class, "Hopper", "hopper"); mapTile(TileEntityComparator.class, "Comparator", "comparator"); @@ -486,7 +427,7 @@ public abstract class Converter { return Blocks.wool.getState().withProperty(BlockColored.COLOR, DyeColor.byMetadata(data)); } }, 35); - mapBlock(Blocks.stone, 36); // mapBlockData(Blocks.piston_extension, 36); + mapBlockData(Blocks.piston_extension, 36); mapBlock(Blocks.flower.getState().withProperty(Blocks.flower.getTypeProperty(), BlockFlower.EnumFlowerType.DANDELION), 37); mapBlock(Blocks.flower.getState().withProperty(Blocks.flower.getTypeProperty(), BlockFlower.EnumFlowerType.POPPY), 38); @@ -574,13 +515,13 @@ public abstract class Converter { return Blocks.fire.getState().withProperty(BlockFire.AGE, data); } }, 51); - mapBlock(Blocks.iron_bars, 52); + mapBlock(Blocks.mob_spawner, 52); mapBlockData(Blocks.oak_stairs, 53); mapBlockData(Blocks.chest, 54); mapBlockData(Blocks.redstone, 55); mapBlock(Blocks.diamond_ore, 56); mapBlock(Blocks.diamond_block, 57); - mapBlock(Blocks.workbench, 58); + mapBlock(Blocks.crafting_table, 58); mapBlockData(Blocks.wheat, 59); mapBlockData(Blocks.farmland, 60); mapBlockData(Blocks.furnace, 61); @@ -860,74 +801,11 @@ public abstract class Converter { }, 252); mapBlock(Blocks.obsidian, 255); } - - private static Object read(DataInput input, byte id) throws IOException { - switch(id) { - case 0: - return null; - case 1: - return input.readByte(); - case 2: - return input.readShort(); - case 3: - return input.readInt(); - case 4: - return input.readLong(); - case 5: - return input.readFloat(); - case 6: - return input.readDouble(); - case 7: { - int len = input.readInt(); - byte[] data = new byte[len]; - input.readFully(data); - return data; - } - case 8: - return input.readUTF(); - case 9: { - byte type = input.readByte(); - int len = input.readInt(); - if(type == 0 && len > 0) - throw new RuntimeException("Liste hat keinen Typ"); - List list = new ArrayList(len); - for(int z = 0; z < len; z++) { - list.add(read(input, type)); - } - return list; - } - case 10: { - NbtTag tag = new NbtTag(); - byte type; - while((type = input.readByte()) != 0) { - String key = input.readUTF(); - tag.map.put(key, read(input, type)); - } - return tag; - } - case 11: { - int len = input.readInt(); - int[] data = new int[len]; - for(int z = 0; z < len; z++) { - data[z] = input.readInt(); - } - return data; - } - default: - return null; - } - } - - private static NbtTag readTag(DataInputStream in) throws IOException { - if(in.readByte() != 10) - throw new IOException("Tag hat den falschen Typ"); - in.readUTF(); - return (NbtTag)read(in, (byte)10); - } - private static TagObject convertTile(NbtTag ent, String id) { - TagObject nent = new TagObject(); - if("Sign".equals(id)) { + private static void convertTile(NBTTagCompound ent) { + if("Sign".equals(ent.getString("id"))) { +// Log.debug("Konvertiere Schild bei " +// + ent.getInteger("x") + "," + ent.getInteger("y") + "," + ent.getInteger("z") + " ..."); String[] signText = new String[4]; for(int i = 0; i < 4; ++i) { signText[i] = ent.getString("Text" + (i + 1)); @@ -937,12 +815,15 @@ public abstract class Converter { String[] old = new String[4]; for(int i = 0; i < 4; ++i) { old[i] = signText[i]; - signText[i] = signText[i].indexOf('\u00A7') != -1 ? - signText[i].replaceAll("\u00A7[0-9a-fA-Fk-oK-O]", "") : +// if(ChatFormat.hasLegacy(this.signText[i])) { + signText[i] = signText[i].indexOf('\u00A7') != -1 ? /* TextColor.replaceCodes( */ + signText[i].replaceAll("\u00A7[0-9a-fA-Fk-oK-O]", "") /* .replace("\u00A7", "$$")) */ : signText[i]; +// } if(signText[i].startsWith("{") && signText[i].endsWith("}")) { try { - signText[i] = ""; +// TextComponent comp = TextSerializer.toComponent(signText[i]); + signText[i] = ""; // comp.getFormattedText(); newComp++; } catch(Throwable e) { @@ -957,15 +838,14 @@ public abstract class Converter { if(newComp == 4 && (quotes & (1 << i)) != 0) { signText[i] = signText[i].substring(1, signText[i].length() - 1); } +// if(old[i] != signText[i]) { +// Log.debug("Zeile " + (i + 1) + ": '" + TextColor.stripCodes(signText[i]) + "'"); +// } } for(int i = 0; i < 4; ++i) { - nent.setString("Text" + (i + 1), signText[i]); + ent.setString("Text" + (i + 1), signText[i]); } } - else if("Comparator".equals(id)) { - nent.setInt("OutputSignal", ent.getInt("OutputSignal")); - } - return nent; } private static int getNibble(byte[] data, int x, int y, int z) { @@ -977,22 +857,23 @@ public abstract class Converter { int idx = name.indexOf(':'); return idx >= 0 ? name.substring(idx + 1) : name; // save compat } - - private static TagObject convertChunkData(NbtTag tag, boolean legacy) { - TagObject ntag = new TagObject(); - tag = tag.getTag("Level"); + + private static NBTTagCompound convertChunkData(NBTTagCompound tag, boolean legacy) { + tag = tag.getCompoundTag("Level"); if(legacy) { + if(tag.hasKey("LastUpdate", 3)) + tag.setLong("LastUpdate", (long)tag.getInteger("LastUpdate")); byte[] oldheight = tag.getByteArray("HeightMap"); int[] height = new int[oldheight.length]; for(int i = 0; i < oldheight.length; ++i) { height[i] = oldheight[i]; } - ntag.setIntArray("HeightMap", height); + tag.setIntArray("HeightMap", height); byte[] oldblks = tag.getByteArray("Blocks"); byte[] olddata = tag.getByteArray("Data"); byte[] oldsky = tag.getByteArray("SkyLight"); byte[] oldlight = tag.getByteArray("BlockLight"); - List sections = Lists.newArrayList(); + NBTTagList sections = new NBTTagList(); for(int n = 0; n < 8; ++n) { boolean empty = true; for(int x = 0; x < 16 && empty; ++x) { @@ -1024,80 +905,63 @@ public abstract class Converter { } } } - TagObject section = new TagObject(); + NBTTagCompound section = new NBTTagCompound(); section.setByte("Y", (byte)(n & 255)); section.setByteArray("Blocks", blocks); section.setByteArray("Data", data.getData()); section.setByteArray("SkyLight", sky.getData()); section.setByteArray("BlockLight", light.getData()); - sections.add(section); + sections.appendTag(section); } } - ntag.setList("Sections", sections); + tag.setTag("Sections", sections); byte[] biomes = new byte[256]; Arrays.fill(biomes, (byte)(Biome.DEF_BIOME.id & 255)); - ntag.setByteArray("Biomes", biomes); + tag.setByteArray("Biomes", biomes); } - else { - ntag.setIntArray("HeightMap", tag.getIntArray("HeightMap")); - } - - ntag.setBool("TerrainPopulated", true); - ntag.setBool("LightPopulated", tag.getByte("LightPopulated") != 0); - - NbtTag[] ents = tag.getTagList("Entities"); - List entities = Lists.newArrayList(); - for(NbtTag ent : ents) { - TagObject nent = new TagObject(); + NBTTagList ents = tag.getTagList("Entities", 10); + NBTTagList entities = new NBTTagList(); + for(int z = 0; z < ents.tagCount(); z++) { + NBTTagCompound ent = ents.getCompoundTagAt(z); String mapped = ENTITY_MAP.get(trimColon(ent.getString("id"))); if(mapped != null) { - double[] pos = ent.getDoubleList("Pos"); - double[] motion = ent.getDoubleList("Motion"); - float[] rotation = ent.getFloatList("Rotation"); - if(pos.length != 3 || motion.length != 3 || rotation.length != 2) - continue; - boolean ground = ent.getByte("OnGround") != 0; - nent.setDouble("PosX", pos[0]); - nent.setDouble("PosY", pos[1]); - nent.setDouble("PosZ", pos[2]); - nent.setDouble("MotionX", motion[0]); - nent.setDouble("MotionY", motion[1]); - nent.setDouble("MotionZ", motion[2]); - nent.setFloat("Yaw", rotation[0]); - nent.setFloat("Pitch", rotation[1]); - nent.setBool("OnGround", ground); - nent.setInt("Dimension", 1); - nent.setString("id", mapped); - entities.add(nent); + NBTTagList pos = ent.getTagList("Pos", 6); + NBTTagList motion = ent.getTagList("Motion", 6); + NBTTagList rotation = ent.getTagList("Rotation", 5); + boolean ground = ent.getBoolean("OnGround"); + ent.getKeySet().clear(); + ent.setTag("Pos", pos); + ent.setTag("Motion", motion); + ent.setTag("Rotation", rotation); + ent.setBoolean("OnGround", ground); + ent.setInteger("Dimension", 1); + ent.setString("id", mapped); + entities.appendTag(ent); } } - ntag.setList("Entities", entities); + tag.setTag("Entities", entities); - ents = tag.getTagList("TileEntities"); - entities = Lists.newArrayList(); - for(NbtTag ent : ents) { - TagObject nent = new TagObject(); + ents = tag.getTagList("TileEntities", 10); + entities = new NBTTagList(); + for(int z = 0; z < ents.tagCount(); z++) { + NBTTagCompound ent = ents.getCompoundTagAt(z); String mapped = TILE_MAP.get(trimColon(ent.getString("id"))); if(mapped != null) { - nent = convertTile(ent, mapped); - nent.setString("id", mapped); - nent.setInt("x", ent.getInt("x")); - nent.setInt("y", ent.getInt("y")); - nent.setInt("z", ent.getInt("z")); - entities.add(nent); + ent.setString("id", mapped); + convertTile(ent); + entities.appendTag(ent); } } - ntag.setList("TileEntities", entities); + tag.setTag("TileEntities", entities); - NbtTag[] sects = tag.getTagList("Sections"); - entities = Lists.newArrayList(); - for(NbtTag sect : sects) { - TagObject nsect = new TagObject(); - nsect.setInt("Y", sect.getByte("Y")); + tag.removeTag("TileTicks"); + + NBTTagList sects = tag.getTagList("Sections", 10); + for(int n = 0; n < sects.tagCount(); ++n) { + NBTTagCompound sect = sects.getCompoundTagAt(n); byte[] blocks = sect.getByteArray("Blocks"); NibbleArray data = new NibbleArray(sect.getByteArray("Data")); - byte[] add = sect.getByteArray("Add"); - NibbleArray adddata = add.length > 0 ? new NibbleArray(add) : null; + NibbleArray adddata = sect.hasKey("Add", 7) ? new NibbleArray(sect.getByteArray("Add")) : null; for(int c = 0; c < blocks.length; ++c) { int cx = c & 15; int cy = c >> 8 & 15; @@ -1128,14 +992,12 @@ public abstract class Converter { data.set(cx, cy, cz, cd & 15); } } - nsect.setByteArray("Blocks", blocks); - nsect.setByteArray("Data", data.getData()); + sect.setByteArray("Blocks", blocks); + sect.setByteArray("Data", data.getData()); if(adddata != null) - nsect.setByteArray("Add", adddata.getData()); - entities.add(nsect); + sect.setByteArray("Add", adddata.getData()); } - ntag.setList("Sections", entities); - return ntag; + return tag; } private static long convertChunks(File dir, File file, long start, int progress, int total) { @@ -1144,7 +1006,7 @@ public abstract class Converter { int rx, rz; String[] reg = name.split("\\."); if(reg.length != 4) { - Log.IO.warn("Unbekannte Region " + file); + Log.JNI.warn("Unbekannte Region " + file); return start; } try { @@ -1152,7 +1014,7 @@ public abstract class Converter { rz = Integer.parseInt(reg[2]); } catch(NumberFormatException e) { - Log.IO.warn("Unbekannte Region " + file); + Log.JNI.warn("Unbekannte Region " + file); return start; } try { @@ -1169,7 +1031,7 @@ public abstract class Converter { } areas++; newreg = new Region(dir, rx * 4 + bx, rz * 4 + bz); - Log.IO.info("Konvertiere " + file + " zu " + newreg.getFile() + " ..."); + Log.JNI.info("Konvertiere " + file + " zu " + newreg.getFile() + " ..."); for(int nx = 0; nx < 8; nx++) { for(int nz = 0; nz < 8; nz++) { int x = bx << 3 | nx; @@ -1178,16 +1040,16 @@ public abstract class Converter { chunks++; DataInputStream in = oldreg.getInputStream(x, z); if(in == null) { - Log.IO.warn("Konnte " + file.getPath() + "@" + x + "," + z + " nicht lesen"); + Log.JNI.warn("Konnte " + file.getPath() + "@" + x + "," + z + " nicht lesen"); continue; } - NbtTag tag = readTag(in); + NBTTagCompound tag = NBTLoader.read(in); in.close(); - TagObject ntag = convertChunkData(tag, legacy); + tag = convertChunkData(tag, legacy); // DataOutputStream out = newreg.getOutputStream(nx, nz); // CompressedStreamTools.write(tag, out); // out.close(); - newreg.writeTag(nx, nz, ntag); + newreg.writeTag(nx, nz, tag); } } } @@ -1201,106 +1063,106 @@ public abstract class Converter { } } oldreg.close(); - Log.IO.info(file + ": " + areas + " Regionen, " + chunks + " Chunks"); + Log.JNI.info(file + ": " + areas + " Regionen, " + chunks + " Chunks"); } catch(IOException e) { e.printStackTrace(); } return start; } - - public static boolean convert(Server server) { + + public static boolean convert() { long cur = System.currentTimeMillis(); - if(new File("server.cdt").exists()) + if(new File("server.nbt").exists()) return false; File ldat = new File("level.dat"); if(!ldat.exists()) ldat = new File("level.dat_old"); if(!ldat.exists()) return false; - Log.IO.info("Welt wird konvertiert"); - NbtTag tag; - DataInputStream in = null; + Log.JNI.info("Welt wird konvertiert"); + NBTTagCompound nbt; try { - in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream(ldat)))); - tag = readTag(in); + nbt = NBTLoader.readGZip(ldat); } catch(Exception e) { - Log.IO.error(e, "Fehler beim Lesen von level.dat"); + Log.JNI.error(e, "Fehler beim Lesen von level.dat"); return false; } - finally { - try { - if(in != null) - in.close(); - } - catch(IOException e) { - } - } - tag = tag.getTag("Data"); - int version = tag.getInt("version"); - int data = tag.getInt("DataVersion"); + nbt = nbt.getCompoundTag("Data"); + int version = nbt.getInteger("version"); + int data = nbt.getInteger("DataVersion"); +// nbt.setBoolean("incompatible", data >= 1400); SaveVersion ver = data >= 1400 ? SaveVersion.RELEASE_1_13 : (data >= 100 ? SaveVersion.RELEASE_1_9 : (version == 19132 || version == 19133 ? SaveVersion.BETA_1_3 : (version == 0 ? SaveVersion.ALPHA_1_0 : null))); if(ver == null) { Log.IO.error("Version %d ist unbekannt", version); return false; } + long wtime = nbt.getLong(nbt.hasKey("DayTime", 99) ? "DayTime" : "Time") + World.START_TIME; Log.IO.info("Version: %s", ver); + Log.IO.info("Weltzeit: %d Ticks / %d Sekunden", wtime, wtime / 20L); + Log.IO.info("Zuletzt geladen: %s", new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(new Date(nbt.getLong("LastPlayed")))); if(ver != SaveVersion.RELEASE_1_13) { - Log.IO.info("Konvertiere Chunk-Daten von region/*.mca,*.mcr"); + Log.JNI.info("Konvertiere Chunk-Daten von region/*.mca,*.mcr"); File regionDir = new File("region"); if(regionDir.exists()) { File chunkDir = new File(new File("chunk"), "terra"); - Log.IO.info("Konvertiere Welt nach '" + chunkDir + "' ..."); - Log.IO.info("Durchsuche Ordner unter '" + regionDir + "' nach .mca- und .mcr-Dateien ..."); + Log.JNI.info("Konvertiere Welt nach '" + chunkDir + "' ..."); + Log.JNI.info("Durchsuche Ordner unter '" + regionDir + "' nach .mca- und .mcr-Dateien ..."); File[] files = regionDir.listFiles(new FilenameFilter() { public boolean accept(File file, String name) { return name.endsWith(".mca") || name.endsWith(".mcr"); } }); if(files.length == 0) { - Log.IO.info("Keine .mca- oder .mcr-Dateien gefunden."); + Log.JNI.info("Keine .mca- oder .mcr-Dateien gefunden."); } else { - Log.IO.info("Ingesamt wurden " + files.length + " .mca-Dateien und .mcr-Dateien gefunden, konvertiere ..."); + Log.JNI.info("Ingesamt wurden " + files.length + " .mca-Dateien und .mcr-Dateien gefunden, konvertiere ..."); if(ver == SaveVersion.RELEASE_1_9) - Log.IO.info("Konvertiere von neuerer Version, dies wird Blöcke entfernen ..."); + Log.JNI.info("Konvertiere von neuerer Version, dies wird Blöcke entfernen ..."); chunkDir.mkdirs(); int progress = 0; long time = System.currentTimeMillis(); long start = postProgress(time, 0); for(File file : files) { int percent = (int)Math.round(100.0D * (double)progress / (double)files.length); - Log.IO.info("Konvertiere Chunk-Daten: " + file.getName() + " (" + progress + "/" + files.length + ")"); + Log.JNI.info("Konvertiere Chunk-Daten: " + file.getName() + " (" + progress + "/" + files.length + ")"); start = convertChunks(chunkDir, file, start, progress, files.length); ++progress; start = postProgress(start, percent); } time = System.currentTimeMillis() - time; - Log.IO.info("Fertig. Konversion dauerte " + ((time / 60000L) > 0 ? ((time / 60000L) + " Minuten und ") : "") + ((time / 1000L) % 60L) + " Sekunden."); + Log.JNI.info("Fertig. Konversion dauerte " + ((time / 60000L) > 0 ? ((time / 60000L) + " Minuten und ") : "") + ((time / 1000L) % 60L) + " Sekunden."); } } } else { - Log.IO.warn("Konvertiere keine Chunk-Daten, da Version zu neu"); + Log.JNI.warn("Konvertiere keine Chunk-Daten, da Version zu neu"); } - Log.IO.info("Konvertiere Daten von level.dat"); - NbtTag rules = tag.getTag("GameRules"); - for(Entry rule : OLD_GAMERULES.entrySet()) { - if(!rules.getString(rule.getKey()).isEmpty()) - server.getVariables().get(rule.getValue()).set(rules.getString(rule.getKey()), false, false); + Log.JNI.info("Konvertiere Daten von level.dat"); + Config.clear(); + UniverseRegistry.clear(); + if(nbt.hasKey("GameRules", 10)) { + NBTTagCompound rules = nbt.getCompoundTag("GameRules"); + for(Entry rule : OLD_GAMERULES.entrySet()) { + if(rules.hasKey(rule.getKey(), 8)) + Config.set(rule.getValue(), rules.getString(rule.getKey()), false); + } } - Weather weather = tag.getByte("thundering") != 0 ? Weather.THUNDER : (tag.getByte("raining") != 0 ? Weather.RAIN : Weather.CLEAR); + Log.JNI.info("Speichere neue server.nbt ..."); + Server.saveServerConfig(wtime); + Weather weather = nbt.getBoolean("thundering") ? Weather.THUNDER : (nbt.getBoolean("raining") ? Weather.RAIN : Weather.CLEAR); if(weather != Weather.CLEAR) { - TagObject dataTag = new TagObject(); + NBTTagCompound dataTag = new NBTTagCompound(); dataTag.setString("Weather", weather.getName()); - Log.IO.info("Speichere neue data.cdt ..."); - File dataFile = new File(new File(new File("chunk"), "terra"), "data.cdt"); + Log.JNI.info("Speichere neue data.nbt ..."); + File dataFile = new File(new File(new File("chunk"), "terra"), "data.nbt"); try { - TagObject.writeGZip(dataTag, dataFile); + NBTLoader.writeGZip(dataTag, dataFile); } catch(Exception e) { - Log.IO.error(e, "Konnte Weltdaten nicht speichern"); + Log.JNI.error(e, "Konnte Weltdaten nicht speichern"); } } Log.IO.info("Welt wurde in %d Sekunden konvertiert", (System.currentTimeMillis() - cur) / 1000L); diff --git a/server/src/main/java/server/world/Region.java b/server/src/server/world/Region.java similarity index 72% rename from server/src/main/java/server/world/Region.java rename to server/src/server/world/Region.java index 114c963..573f860 100755 --- a/server/src/main/java/server/world/Region.java +++ b/server/src/server/world/Region.java @@ -14,7 +14,6 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; @@ -23,15 +22,18 @@ import common.collect.Lists; import common.collect.Maps; import common.entity.Entity; import common.init.BlockRegistry; -import common.init.Blocks; import common.init.EntityRegistry; import common.log.Log; -import common.tags.TagObject; +import common.nbt.NBTLoader; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.tileentity.TileEntity; import common.util.BlockPos; +import common.util.NextTickListEntry; import common.util.NibbleArray; import common.util.Util; import common.world.BlockArray; +import common.world.Chunk; public class Region { private static class ChunkBuffer extends ByteArrayOutputStream { @@ -151,14 +153,14 @@ public class Region { // this.file.seek((long)(512 + (x + z * 8) * 8192)); int size = this.sizes[x + z * 8]; // this.file.readShort(); if(size > 8192 /* - 2 */ || size < 0) { - Log.IO.warn("Chunk-Region-Datei " + this.regFile + " hat eine ungültige Größe bei " + x + ", " + z + ", überspringe"); + Log.JNI.warn("Chunk-Region-Datei " + this.regFile + " hat eine ungültige Größe bei " + x + ", " + z + ", überspringe"); return null; } byte[] data; if(size == 0) { File expand = getExpansionFile(this.folder, this.xPos * 8 + x, this.zPos * 8 + z); if(!expand.exists()) { - Log.IO.warn("Chunk-Erweiterungs-Datei " + expand + " ist nicht vorhanden oder nicht lesbar, überspringe"); + Log.JNI.warn("Chunk-Erweiterungs-Datei " + expand + " ist nicht vorhanden oder nicht lesbar, überspringe"); return null; } in = new FileInputStream(expand); @@ -181,7 +183,7 @@ public class Region { else { int pos = this.positions[x + z * 8] << 8; if(pos + size > this.file.length() - 512L || pos < 0) { - Log.IO.warn("Chunk-Region-Datei " + this.regFile + " hat eine ungültige Position bei " + x + ", " + z + ", überspringe"); + Log.JNI.warn("Chunk-Region-Datei " + this.regFile + " hat eine ungültige Position bei " + x + ", " + z + ", überspringe"); return null; } this.file.seek(512L + (long)pos); @@ -198,7 +200,7 @@ public class Region { } catch(IOException e1) { } - Log.IO.error(e, "Fehler beim lesen von Chunk-Region-Datei " + this.regFile + " bei " + x + ", " + z + ", überspringe"); + Log.JNI.error(e, "Fehler beim lesen von Chunk-Region-Datei " + this.regFile + " bei " + x + ", " + z + ", überspringe"); return null; } } @@ -270,10 +272,10 @@ public class Region { return (long)this.timestamps[x + z * 8] * 10000L; } - public void writeTag(int x, int z, TagObject tag) throws IOException { + public void writeTag(int x, int z, NBTTagCompound tag) throws IOException { ChunkBuffer buf = new ChunkBuffer(); DataOutputStream out = new DataOutputStream(new DeflaterOutputStream(buf)); - TagObject.write(tag, out); + NBTLoader.write(tag, out); out.close(); this.write(x, z, buf.getData(), buf.size()); } @@ -340,49 +342,47 @@ public class Region { clearCache(true); } - public static /* synchronized */ TagObject readChunk(File dir, int x, int z) throws IOException { + public static /* synchronized */ NBTTagCompound readChunk(File dir, int x, int z) throws IOException { // return getRegionFile(dir, x >> 3, z >> 3).readTag(x & 7, z & 7); byte[] data = getRegionFile(dir, x >> 3, z >> 3).read(x & 7, z & 7); if(data == null) return null; - return TagObject.read(new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data))))); + return NBTLoader.read(new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data))))); } - public static /* synchronized */ void writeChunk(File dir, int x, int z, TagObject tag) throws IOException { + public static /* synchronized */ void writeChunk(File dir, int x, int z, NBTTagCompound tag) throws IOException { ChunkBuffer buf = new ChunkBuffer(); DataOutputStream out = new DataOutputStream(new DeflaterOutputStream(buf)); - TagObject.write(tag, out); + NBTLoader.write(tag, out); out.close(); getRegionFile(dir, x >> 3, z >> 3).write(x & 7, z & 7, buf.getData(), buf.size()); // getRegionFile(dir, x >> 3, z >> 3).writeTag(x & 7, z & 7, tag); } - public static ChunkServer readChunk(WorldServer world, int x, int z, TagObject tag) { -// if(!tag.hasTag("Level")) { + public static Chunk readNbt(WorldServer world, int x, int z, NBTTagCompound tag) { +// if(!tag.hasKey("Level", 10)) { // Log.error("Chunk-Datei bei " + x + "," + z + " hat keine Level-Daten, überspringe"); // return null; // } // tag = tag.getCompoundTag("Level"); - if(!tag.hasList("Sections")) { - Log.IO.warn("Chunk-Datei bei " + x + "," + z + " hat keine Block-Daten, überspringe"); + if(!tag.hasKey("Sections", 9)) { + Log.JNI.warn("Chunk-Datei bei " + x + "," + z + " hat keine Block-Daten, überspringe"); return null; } - ChunkServer chunk = new ChunkServer(world, x, z); - chunk.setHeights(tag.getIntArray("HeightMap")); - chunk.setTerrainPopulated(tag.getBool("TerrainPopulated")); - chunk.setLightPopulated(tag.getBool("LightPopulated")); + Chunk chunk = new Chunk(world, x, z); + chunk.setTerrainPopulated(tag.getBoolean("TerrainPopulated")); chunk.setInhabited(tag.getLong("InhabitedTime")); - List sects = tag.getList("Sections"); - BlockArray[] sections = new BlockArray[sects.size()]; - boolean light = !world.dimension.hasNoLight(); - - for(int n = 0; n < sects.size(); ++n) { - TagObject sect = sects.get(n); - int y = sect.getInt("Y"); - BlockArray storage = new BlockArray(y << 4, light, null); + NBTTagList sects = tag.getTagList("Sections", 10); + int stor = 32; + BlockArray[] sections = new BlockArray[stor]; + + for(int n = 0; n < sects.tagCount(); ++n) { + NBTTagCompound sect = sects.getCompoundTagAt(n); + int y = sect.getByte("Y"); + BlockArray storage = new BlockArray(y << 4); byte[] blocks = sect.getByteArray("Blocks"); NibbleArray data = new NibbleArray(sect.getByteArray("Data")); - NibbleArray adddata = sect.hasByteArray("Add") ? new NibbleArray(sect.getByteArray("Add")) : null; + NibbleArray adddata = sect.hasKey("Add", 7) ? new NibbleArray(sect.getByteArray("Add")) : null; char[] seg = new char[blocks.length]; for(int c = 0; c < seg.length; ++c) { @@ -395,35 +395,27 @@ public class Region { storage.setData(seg); storage.setBlocklight(new NibbleArray(sect.getByteArray("BlockLight"))); - - if(light) { - storage.setSkylight(new NibbleArray(sect.getByteArray("SkyLight"))); - } - + storage.update(); - sections[n] = storage; + sections[y] = storage; } chunk.setStorage(sections); - if(tag.hasByteArray("Biomes")) { - chunk.setBiomes(tag.getByteArray("Biomes")); - } - - List entities = tag.getList("Entities"); + NBTTagList entities = tag.getTagList("Entities", 10); if(entities != null) { - for(int n = 0; n < entities.size(); ++n) { - TagObject ent = entities.get(n); - Entity entity = EntityRegistry.createFromTags(ent, world); + for(int n = 0; n < entities.tagCount(); ++n) { + NBTTagCompound ent = entities.getCompoundTagAt(n); + Entity entity = EntityRegistry.createEntityFromNBT(ent, world); chunk.setHasEntities(true); if(entity != null) { chunk.addEntity(entity); Entity rider = entity; - for(TagObject ride = ent; ride.hasObject("Riding"); ride = ride.getObject("Riding")) { - Entity pass = EntityRegistry.createFromTags(ride.getObject("Riding"), world); + for(NBTTagCompound ride = ent; ride.hasKey("Riding", 10); ride = ride.getCompoundTag("Riding")) { + Entity pass = EntityRegistry.createEntityFromNBT(ride.getCompoundTag("Riding"), world); if(pass != null) { chunk.addEntity(pass); @@ -436,11 +428,11 @@ public class Region { } } - List tiles = tag.getList("TileEntities"); + NBTTagList tiles = tag.getTagList("TileEntities", 10); if(tiles != null) { - for(int n = 0; n < tiles.size(); ++n) { - TagObject tile = tiles.get(n); + for(int n = 0; n < tiles.tagCount(); ++n) { + NBTTagCompound tile = tiles.getCompoundTagAt(n); TileEntity tileentity = TileEntity.createAndLoadEntity(tile); if(tileentity != null) { @@ -449,25 +441,33 @@ public class Region { } } - if(tag.hasList("TileTicks")) { - List ticks = tag.getList("TileTicks"); + if(tag.hasKey("TileTicks", 9)) { + NBTTagList ticks = tag.getTagList("TileTicks", 10); if(ticks != null) { int invalid = 0; - for(int n = 0; n < ticks.size(); ++n) { - TagObject tick = ticks.get(n); - Block block = BlockRegistry.getRegisteredBlock(tick.getString("i")); + for(int n = 0; n < ticks.tagCount(); ++n) { + NBTTagCompound tick = ticks.getCompoundTagAt(n); + Block block; - if(block != Blocks.air) { // FIX - world.scheduleBlockUpdate(new BlockPos(tick.getInt("x"), tick.getInt("y"), tick.getInt("z")), block, - tick.getInt("t"), tick.getInt("p")); + if(tick.hasKey("i", 8)) { + block = BlockRegistry.getByIdFallback(tick.getString("i")); + } + else { + block = BlockRegistry.getBlockById(tick.getInteger("i")); + } + + if(block != null) { // FIX + world.scheduleBlockUpdate(new BlockPos(tick.getInteger("x"), tick.getInteger("y"), tick.getInteger("z")), block, + tick.getInteger("t"), tick.getInteger("p")); } else if(invalid++ < 10) { - Log.IO.warn("Unbekannter Block-Tick in Chunk " + x + "," + z + ": '" + tick.getString("i") + "'"); + Log.JNI.warn("Unbekannter Block-Tick in Chunk " + x + "," + z + ": " + + (tick.hasKey("i", 8) ? ("'" + tick.getString("i") + "'") : ("#" + tick.getInteger("i")))); } } if(invalid > 10) { - Log.IO.warn((invalid - 10) + " weitere ..."); + Log.JNI.warn((invalid - 10) + " weitere ..."); } } } @@ -475,22 +475,20 @@ public class Region { return chunk; } - public static TagObject writeChunk(WorldServer world, ChunkServer chunk) { - TagObject tag = new TagObject(); + public static NBTTagCompound writeNbt(WorldServer world, Chunk chunk) { + NBTTagCompound tag = new NBTTagCompound(); // tag.setShort("V", (short)Config.PROTOCOL); tag.setLong("LastUpdate", world.getTime()); - tag.setIntArray("HeightMap", chunk.getHeights()); - tag.setBool("TerrainPopulated", chunk.isTerrainPopulated()); - tag.setBool("LightPopulated", chunk.isLightPopulated()); + tag.setBoolean("TerrainPopulated", chunk.isTerrainPopulated()); tag.setLong("InhabitedTime", chunk.getInhabited()); - Set sections = chunk.getStorage(); - List sects = Lists.newArrayList(); + BlockArray[] sections = chunk.getStorage(); + NBTTagList sects = new NBTTagList(); boolean light = !world.dimension.hasNoLight(); for(BlockArray storage : sections) { if(storage != null) { - TagObject sect = new TagObject(); - sect.setInt("Y", storage.getY() >> 4); + NBTTagCompound sect = new NBTTagCompound(); + sect.setByte("Y", (byte)(storage.getY() >> 4 & 511)); byte[] blocks = new byte[storage.getData().length]; NibbleArray data = new NibbleArray(); NibbleArray adddata = null; @@ -521,65 +519,55 @@ public class Region { } sect.setByteArray("BlockLight", storage.getBlocklight().getData()); - - if(light) { - sect.setByteArray("SkyLight", storage.getSkylight().getData()); - } - else { - sect.setByteArray("SkyLight", new byte[storage.getBlocklight().getData().length]); - } - - sects.add(sect); + + sects.appendTag(sect); } } - tag.setList("Sections", sects); - tag.setByteArray("Biomes", chunk.getBiomes()); + tag.setTag("Sections", sects); chunk.setHasEntities(false); - List entities = Lists.newArrayList(); + NBTTagList entities = new NBTTagList(); for(int n = 0; n < chunk.getEntities().length; ++n) { for(Entity entity : chunk.getEntities()[n]) { - TagObject ent = new TagObject(); + NBTTagCompound ent = new NBTTagCompound(); - if(entity.writeOptional(ent)) { + if(entity.writeToNBTOptional(ent)) { chunk.setHasEntities(true); - entities.add(ent); + entities.appendTag(ent); } } } - tag.setList("Entities", entities); - List tiles = Lists.newArrayList(); + tag.setTag("Entities", entities); + NBTTagList tiles = new NBTTagList(); for(TileEntity tileentity : chunk.getTiles().values()) { - TagObject tile = new TagObject(); - tileentity.writeTags(tile); - tiles.add(tile); + NBTTagCompound tile = new NBTTagCompound(); + tileentity.writeToNBT(tile); + tiles.appendTag(tile); } - tag.setList("TileEntities", tiles); + tag.setTag("TileEntities", tiles); List tics = world.getPendingBlockUpdates(chunk); if(tics != null) { long time = world.getTime(); - List ticks = Lists.newArrayList(); + NBTTagList ticks = new NBTTagList(); for(NextTickListEntry tic : tics) { - if(tic.getBlock() == Blocks.air) - continue; - TagObject tick = new TagObject(); - String res = BlockRegistry.getNameFromBlock(tic.getBlock()); - tick.setString("i", res == null ? "" : res); - tick.setInt("x", tic.position.getX()); - tick.setInt("y", tic.position.getY()); - tick.setInt("z", tic.position.getZ()); - tick.setInt("t", (int)(tic.scheduledTime - time)); - tick.setInt("p", tic.priority); - ticks.add(tick); + NBTTagCompound tick = new NBTTagCompound(); + String res = BlockRegistry.REGISTRY.getNameForObject(tic.getBlock()); + tick.setString("i", res == null ? "" : res.toString()); + tick.setInteger("x", tic.position.getX()); + tick.setInteger("y", tic.position.getY()); + tick.setInteger("z", tic.position.getZ()); + tick.setInteger("t", (int)(tic.scheduledTime - time)); + tick.setInteger("p", tic.priority); + ticks.appendTag(tick); } - tag.setList("TileTicks", ticks); + tag.setTag("TileTicks", ticks); } return tag; diff --git a/server/src/main/java/server/world/Spawner.java b/server/src/server/world/Spawner.java similarity index 92% rename from server/src/main/java/server/world/Spawner.java rename to server/src/server/world/Spawner.java index 06e5da6..02f27ff 100755 --- a/server/src/main/java/server/world/Spawner.java +++ b/server/src/server/world/Spawner.java @@ -8,6 +8,7 @@ import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.entity.types.EntityWaterMob; import common.init.Blocks; +import common.init.Config; import common.rng.Random; import common.rng.WeightedList; import common.util.BlockPos; @@ -16,7 +17,6 @@ import common.util.ExtMath; import common.world.World; import server.biome.GenBiome; import server.biome.RngSpawn; -import server.vars.SVars; public abstract class Spawner { private static final int MOB_COUNT_DIV = (int)Math.pow(17.0D, 2.0D); @@ -53,7 +53,7 @@ public abstract class Spawner { // } CHUNKS.clear(); int locs = 0; - int range = Math.max(SVars.mobSpawnDist, 1); + int range = Math.max(Config.mobSpawnDist, 1); for(EntityNPC player : world.players) { // if(Config.spectatorSpawning || !player.isSpectator()) { int x = ExtMath.floord(player.posX / 16.0D); @@ -75,30 +75,32 @@ public abstract class Spawner { } // boolean animals = (time % Math.max(Config.animalSpawnDelay, 1)) == 0; int spawned = 0; - int mobSpread = Math.max(SVars.spawnGroupDist, 1); + int mobSpread = Math.max(Config.spawnGroupDist, 1); // double spawnDist = (double)Config.mobSpawnDistance; - double playerDist = (double)SVars.mobPlayerDist; + double playerDist = (double)Config.mobPlayerDist; // BlockPos spawn = world.isPrimary() ? Server.getSpawnPoint() : null; // for(EnumCreatureType type : EnumCreatureType.values()) { // if((!type.isPeaceful() || peaceful) && (type.isPeaceful() || hostile) && (!type.isAnimal() || animals)) { int cur = world.countEntities(EntityLiving.class); - int max = SVars.maxMobs * locs / MOB_COUNT_DIV; + int max = Config.maxMobs * locs / MOB_COUNT_DIV; if(cur <= max) { typeLabel: for(ChunkPos coord : CHUNKS) { - ChunkServer chunk = world.getChunk(coord.x, coord.z); int x = coord.x * 16 + world.rand.zrange(16); int z = coord.z * 16 + world.rand.zrange(16); - int h = chunk.getTopSegment(); - if(h == Integer.MIN_VALUE) - continue; - int y = world.rand.range(chunk.getBottomSegment(), h + 16); + int h = world.getPrecipitationHeight(new BlockPos(x, 0, z)).getY() + 1; + if(h > 0) { + int m = h % 16; + h = m == 0 ? h : h + 16 - m; + } + h = h <= 0 ? 16 : h; + int y = world.rand.excl(h <= 8 ? 0 : 8, h); BlockPos pos = new BlockPos(x, y, z); Block block = world.getState(pos).getBlock(); if(!block.isNormalCube()) { int group = 0; Object data = null; - for(int n = 0; n < SVars.spawnGroups; ++n) { + for(int n = 0; n < Config.spawnGroups; ++n) { int mx = x; int my = y; int mz = z; diff --git a/server/src/main/java/server/world/WorldServer.java b/server/src/server/world/WorldServer.java similarity index 73% rename from server/src/main/java/server/world/WorldServer.java rename to server/src/server/world/WorldServer.java index 46db8b6..53461a0 100755 --- a/server/src/main/java/server/world/WorldServer.java +++ b/server/src/server/world/WorldServer.java @@ -15,19 +15,16 @@ import java.util.function.Predicate; import common.biome.Biome; import common.block.Block; +import common.block.BlockDoor; +import common.block.BlockEventData; import common.block.BlockFalling; -import common.block.Material; -import common.block.artificial.BlockDoor; -import common.block.liquid.BlockLiquid; -import common.block.natural.BlockSnow; +import common.block.BlockLiquid; +import common.block.BlockSnow; +import common.block.LeavesType; import common.collect.Lists; import common.collect.Maps; import common.collect.Sets; import common.dimension.Dimension; -import common.dimension.Dimension.GeneratorType; -import common.dimension.Lake; -import common.dimension.Liquid; -import common.dimension.Ore; import common.entity.DamageSource; import common.entity.Entity; import common.entity.EntityTrackerEntry; @@ -35,52 +32,60 @@ import common.entity.effect.EntityLightning; import common.entity.npc.EntityNPC; import common.entity.types.EntityLiving; import common.init.Blocks; +import common.init.Config; import common.init.SoundEvent; import common.init.UniverseRegistry; import common.item.ItemDoor; import common.log.Log; +import common.material.Material; import common.model.ParticleType; +import common.nbt.NBTLoader; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagInt; +import common.nbt.NBTTagList; import common.network.IPlayer; import common.network.Packet; -import common.packet.SPacketEntityStatus; -import common.packet.SPacketExplosion; -import common.packet.SPacketEffect; -import common.packet.SPacketSoundEffect; -import common.packet.SPacketParticles; -import common.packet.SPacketChangeGameState; -import common.packet.SPacketSpawnGlobalEntity; -import common.packet.SPacketBiome; +import common.packet.S1APacketEntityStatus; +import common.packet.S27PacketExplosion; +import common.packet.S28PacketEffect; +import common.packet.S29PacketSoundEffect; +import common.packet.S2APacketParticles; +import common.packet.S2BPacketChangeGameState; +import common.packet.S2CPacketSpawnGlobalEntity; import common.packet.SPacketBlockAction; import common.packet.SPacketBlockBreakAnim; import common.packet.SPacketBlockChange; +import common.packet.SPacketChunkData; import common.packet.SPacketMultiBlockChange; import common.rng.Random; import common.rng.WeightedList; -import common.tags.TagObject; import common.tileentity.TileEntity; import common.util.BlockPos; import common.util.BoundingBox; import common.util.ChunkPos; import common.util.ExtMath; +import common.util.FileUtils; import common.util.IntHashMap; -import common.util.LongHashMap; +import common.util.NextTickListEntry; import common.util.PortalType; import common.util.Position; import common.util.Vec3; import common.village.Village; import common.world.BlockArray; +import common.world.Chunk; import common.world.Explosion; import common.world.AWorldServer; -import common.world.LightType; import common.world.State; import common.world.Weather; import common.world.World; +import common.worldgen.FeatureLake; +import common.worldgen.FeatureLiquid; +import common.worldgen.FeatureOre; import server.Server; import server.biome.GenBiome; import server.biome.RngSpawn; import server.clipboard.ClipboardBlock; import server.network.Player; -import server.vars.SVars; import server.village.VillageCollection; import server.worldgen.BiomeGenLayered; import server.worldgen.BiomeGenPerlin; @@ -94,6 +99,7 @@ import server.worldgen.FeatureLakes; import server.worldgen.FeatureLiquids; import server.worldgen.FeatureOres; import server.worldgen.GeneratorCavern; +import server.worldgen.GeneratorDebug; import server.worldgen.GeneratorDestroyed; import server.worldgen.GeneratorFlat; import server.worldgen.GeneratorIsland; @@ -123,22 +129,21 @@ public final class WorldServer extends AWorldServer { private final TreeSet ticksNext = new TreeSet(); private final EventList[] queue = new EventList[] {new EventList(), new EventList()}; private final List ticksNow = Lists.newArrayList(); - private final Set dropped = Collections.newSetFromMap(new ConcurrentHashMap()); - private final LongHashMap chunks = new LongHashMap(); - private final List loaded = Lists.newArrayList(); - private final Map toRemove = new ConcurrentHashMap(); + private final Set dropped = Collections.newSetFromMap(new ConcurrentHashMap()); + private final Map chunks = Maps.newHashMap(); + private final List loaded = Lists.newArrayList(); + private final Map toRemove = new ConcurrentHashMap(); private final Set pending = Collections.newSetFromMap(new ConcurrentHashMap()); - private final LongHashMap loaders = new LongHashMap(); + private final Map loaders = Maps.newHashMap(); private final Set loaderList = Sets.newHashSet(); private final List managed = Lists.newArrayList(); - private final LongHashMap instances = new LongHashMap(); + private final Map instances = Maps.newHashMap(); private final List toUpdate = Lists.newArrayList(); private final List instList = Lists.newArrayList(); private final Set tracked = Sets.newHashSet(); private final IntHashMap trackMap = new IntHashMap(); private final Map dataMap = Maps.newHashMap(); private final List dataList = Lists.newArrayList(); - private final List toTick = Lists.newArrayList(); private final Biome[] biomes = new Biome[256]; private MapGenCaves caveGen; @@ -155,8 +160,8 @@ public final class WorldServer extends AWorldServer { private BlockReplacer replacer; private FeatureDungeons dungeons; private State liquid; - private boolean base; - private boolean ceil; + private State base; + private State ceil; private FeatureOres[] ores; private FeatureLakes[] lakes; private FeatureLiquids[] liquids; @@ -172,6 +177,7 @@ public final class WorldServer extends AWorldServer { private boolean loadersModified; // private boolean warpsModified; private boolean exterminated; + private float temp; private int emptyTicks; private int blockEvtIdx; private int trackDistance; @@ -181,7 +187,7 @@ public final class WorldServer extends AWorldServer { private long time; public static float clampGravity() { - return ExtMath.clampf(SVars.gravity, -10.0f, 10.0f); + return ExtMath.clampf(Config.gravity, -10.0f, 10.0f); } private BiomeGenerator createBiomeGenerator(Random rand) { @@ -255,8 +261,8 @@ public final class WorldServer extends AWorldServer { return null; FeatureOres[] gens = new FeatureOres[this.dimension.getOres().size()]; for(int z = 0; z < gens.length; z++) { - Ore gen = this.dimension.getOres().get(z); - gens[z] = new FeatureOres(gen.state(), gen.count(), gen.more(), gen.size(), gen.min(), gen.max(), gen.dist()); + FeatureOre gen = this.dimension.getOres().get(z); + gens[z] = new FeatureOres(gen.state, gen.count, gen.more, gen.size, gen.min, gen.max, gen.dist); } return gens; } @@ -266,8 +272,8 @@ public final class WorldServer extends AWorldServer { return null; FeatureLakes[] gens = new FeatureLakes[this.dimension.getLakes().size()]; for(int z = 0; z < gens.length; z++) { - Lake gen = this.dimension.getLakes().get(z); - gens[z] = new FeatureLakes(gen.state(), gen.filler(), gen.top(), gen.chance(), gen.minHeight(), gen.maxHeight(), gen.ratiod()); + FeatureLake gen = this.dimension.getLakes().get(z); + gens[z] = new FeatureLakes(gen.state, gen.filler, gen.top, gen.chance, gen.minHeight, gen.maxHeight, gen.ratiod); } return gens; } @@ -277,58 +283,79 @@ public final class WorldServer extends AWorldServer { return null; FeatureLiquids[] gens = new FeatureLiquids[this.dimension.getLiquids().size()]; for(int z = 0; z < gens.length; z++) { - Liquid gen = this.dimension.getLiquids().get(z); - gens[z] = new FeatureLiquids(gen.state(), gen.chance(), gen.minHeight(), gen.maxHeight(), gen.lower()); + FeatureLiquid gen = this.dimension.getLiquids().get(z); + gens[z] = new FeatureLiquids(gen.state, gen.chance, gen.minHeight, gen.maxHeight, gen.lower); } return gens; } - public WorldServer(Server server, long dtime, Dimension dim) { - super(dim); + public WorldServer(Server server, long dtime, Dimension dim, boolean debug) { + super(dim, debug); this.server = server; // this.time = time; this.daytime = dtime; this.updateViewRadius(); this.chunkDir = new File(new File("chunk"), dim.getDimensionName()); - this.chunkDir.mkdirs(); - if(!SVars.seed.isEmpty()) - this.rand.setSeed((long)SVars.seed.hashCode() ^ ~((long)dim.getDimensionName().hashCode())); - this.seed = this.rand.longv(); - this.dimension.setSeed(this.seed); - TagObject tag = null; - try { - File dat = new File(this.chunkDir, "data.cdt"); - if(dat.exists() && dat.isFile()) - tag = TagObject.readGZip(dat); - } - catch(Exception e) { - Log.IO.error(e, "Konnte Weltdaten nicht laden"); - } - if(tag != null) { - this.exterminated = tag.getBool("Exterminated"); - this.time = tag.getLong("Time"); - if(tag.hasObject("Generator")) { - this.dimension.fromTags(tag.getObject("Generator")); + if(!debug) { + this.chunkDir.mkdirs(); + this.seed = this.rand.longv(); + this.dimension.setSeed(this.seed); + NBTTagCompound tag = null; + try { + File dat = new File(this.chunkDir, "data.nbt"); + if(dat.exists() && dat.isFile()) + tag = NBTLoader.readGZip(dat); + } + catch(Exception e) { + Log.JNI.error(e, "Konnte Weltdaten nicht laden"); + } + if(tag != null) { + this.exterminated = tag.getBoolean("Exterminated"); + this.time = tag.getLong("Time"); + if(tag.hasKey("Generator", 10)) { + this.dimension.fromNbt(tag.getCompoundTag("Generator")); + if(this.dimension.getType().weather && !this.exterminated) + this.weather = this.dimension.getWeather(); + this.seed = this.dimension.getSeed(); + } if(this.dimension.getType().weather && !this.exterminated) + this.weather = Weather.getByName(tag.getString("Weather")); + if(this.weather == null) { this.weather = this.dimension.getWeather(); - this.seed = this.dimension.getSeed(); - } - if(this.dimension.getType().weather && !this.exterminated) - this.weather = Weather.getByName(tag.getString("Weather")); - if(this.weather == null) { - this.weather = this.dimension.getWeather(); // this.dataModified = true; + } + // ... } - // ... + if(this.exterminated) + this.weather = Weather.CLEAR; } - else { - Log.TICK.info("Startwert für %s: %d" + (SVars.seed.isEmpty() ? "" : " von Basiswert '%s'"), this.dimension.getFormattedName(false), this.seed, SVars.seed); - } - if(this.exterminated) - this.weather = Weather.CLEAR; this.grng = new Random(this.seed); // GeneratorSettings settings = !debug && !this.exterminated ? dim.getSettings() : null; - if(this.exterminated) { + if(debug) { + this.liquid = Blocks.air.getState(); + this.biomeGen = new BiomeGenSingle(Biome.NONE); + this.generator = new GeneratorDebug(); + this.replacer = null; + this.populate = false; + this.caveGen = null; + this.bigCaveGen = null; + this.ravineGen = null; + this.base = null; + this.ceil = null; + this.mobs = false; + this.snow = false; + this.strongholdGen = null; + this.villageGen = null; + this.mineshaftGen = null; + this.scatteredGen = null; + this.bridgeGen = null; + this.seaLevel = 0; + this.ores = null; + this.lakes = null; + this.liquids = null; + this.dungeons = null; + } + else if(this.exterminated) { this.setExterminatedGen(); } // else if(settings != null) { @@ -394,8 +421,8 @@ public final class WorldServer extends AWorldServer { this.caveGen = this.createCaveGenerator(); this.bigCaveGen = this.createBigCaveGenerator(); this.ravineGen = this.createRavineGenerator(); - this.base = this.dimension.getFiller().getBlock() != Blocks.air && this.dimension.getGeneratorType() != GeneratorType.FLAT; - this.ceil = this.dimension.hasWorldCeiling(); + this.base = this.dimension.getWorldFloor(); + this.ceil = this.dimension.getWorldCeiling(); this.mobs = this.dimension.hasMobs(); this.snow = this.dimension.hasSnow(); this.strongholdGen = this.dimension.hasStrongholds() ? new MapGenStronghold() : null; @@ -414,34 +441,54 @@ public final class WorldServer extends AWorldServer { this.calculateInitialSkylight(); this.calculateInitialWeather(); this.updatePhysics(); - tag = null; - try { - File dat = new File(this.chunkDir, "loaders.cdt"); - if(dat.exists() && dat.isFile()) - tag = TagObject.readGZip(dat); - } - catch(Exception e) { - Log.IO.error(e, "Konnte Ladeliste nicht laden"); - } - if(tag != null && tag.hasList("Loaders")) { - List list = tag.getList("Loaders"); - for(int z = 0; z < list.size(); z++) { - TagObject pos = list.get(z); - this.addLoader(new BlockPos(pos.getInt("X"), pos.getInt("Y"), pos.getInt("Z"))); - } - this.loadersModified = false; - } - if(this.villageGen != null) { - tag = null; + if(!debug) { + NBTTagCompound tag = null; try { - File dat = new File(this.chunkDir, "villages.cdt"); + File dat = new File(this.chunkDir, "loaders.nbt"); if(dat.exists() && dat.isFile()) - tag = TagObject.readGZip(dat); + tag = NBTLoader.readGZip(dat); } catch(Exception e) { - Log.IO.error(e, "Konnte Dorfliste nicht laden"); + Log.JNI.error(e, "Konnte Ladeliste nicht laden"); + } + if(tag != null && tag.hasKey("Loaders", 9)) { + NBTTagList list = tag.getTagList("Loaders", 10); + for(int z = 0; z < list.tagCount(); z++) { + NBTTagCompound pos = list.getCompoundTagAt(z); + this.addLoader(new BlockPos(pos.getInteger("X"), pos.getInteger("Y"), pos.getInteger("Z"))); + } + this.loadersModified = false; + } +// tag = null; +// try { +// File dat = new File(this.chunkDir, "warps.nbt"); +// if(dat.exists() && dat.isFile()) +// tag = NBTLoader.readGZip(dat); +// } +// catch(Exception e) { +// Log.warn("Konnte Warpliste nicht laden", e); +// } +// if(tag != null && tag.hasKey("Warps", 9)) { +// NBTTagList list = tag.getTagList("Warps", 10); +// for(int z = 0; z < list.tagCount(); z++) { +// NBTTagCompound pos = list.getCompoundTagAt(z); +// server.getWarps().put(pos.getString("Name"), new Position(pos.getDouble("X"), pos.getDouble("Y"), pos.getDouble("Z"), +// pos.getFloat("Yaw"), pos.getFloat("Pitch"), this.dimension.getDimensionId())); +// } +// this.warpsModified = false; +// } + if(this.villageGen != null) { + tag = null; + try { + File dat = new File(this.chunkDir, "villages.nbt"); + if(dat.exists() && dat.isFile()) + tag = NBTLoader.readGZip(dat); + } + catch(Exception e) { + Log.JNI.error(e, "Konnte Dorfliste nicht laden"); + } + this.villageStorage = new VillageCollection(tag); } - this.villageStorage = new VillageCollection(tag); } } @@ -450,7 +497,7 @@ public final class WorldServer extends AWorldServer { } public void updatePhysics() { - this.setTimeFactor(SVars.timeFlow); + this.setTimeFactor(Config.timeFlow); this.setGravity(clampGravity()); } @@ -458,21 +505,23 @@ public final class WorldServer extends AWorldServer { this.updateWeather(false); this.biomeGen.cleanupCache(); // this.profiler.start("mobSpawner"); - if(this.mobs && SVars.mobs && SVars.tickSpawn) { + if(this.mobs && Config.mobs && Config.tickSpawn && !this.debug) { Spawner.spawn(this); } // this.profiler.next("chunkSource"); - for(int i = 0; i < 100; ++i) { - if(!this.dropped.isEmpty()) { - Long v = (Long)this.dropped.iterator().next(); - ChunkServer chunk = this.chunks.getValueByKey(v.longValue()); - if(chunk != null) { - chunk.onChunkUnload(); - this.saveChunkData(chunk); - this.chunks.remove(v.longValue()); - this.loaded.remove(chunk); + if(!this.debug) { + for(int i = 0; i < 100; ++i) { + if(!this.dropped.isEmpty()) { + ChunkPos v = this.dropped.iterator().next(); + Chunk chunk = this.chunks.get(v); + if(chunk != null) { + chunk.onChunkUnload(); + this.saveChunkData(chunk); + this.chunks.remove(v); + this.loaded.remove(chunk); + } + this.dropped.remove(v); } - this.dropped.remove(v); } } int light = this.calculateSkylightSubtracted(true); @@ -482,7 +531,7 @@ public final class WorldServer extends AWorldServer { // this.info.tick(); this.time += 1L; // this.dataModified = true; - if(SVars.dayCycle) // { + if(Config.dayCycle) // { this.daytime += this.timeFactor; // if(this.dimension.getType().dayCycle) // this.season = this.getSeasonByTime(); @@ -521,10 +570,10 @@ public final class WorldServer extends AWorldServer { } public boolean addLoader(BlockPos pos) { - long chunk = LongHashMap.packInt(pos.getX() / 16, pos.getZ() / 16); - if(this.loaders.containsItem(chunk)) + ChunkPos chunk = new ChunkPos(pos.getX() / 16, pos.getZ() / 16); + if(this.loaders.containsKey(chunk)) return false; - this.loaders.add(chunk, pos); + this.loaders.put(chunk, pos); this.loaderList.add(pos); this.loadersModified = true; return true; @@ -535,8 +584,8 @@ public final class WorldServer extends AWorldServer { // } public boolean removeLoader(BlockPos pos) { - long chunk = LongHashMap.packInt(pos.getX() / 16, pos.getZ() / 16); - BlockPos loader = this.loaders.getValueByKey(chunk); + ChunkPos chunk = new ChunkPos(pos.getX() / 16, pos.getZ() / 16); + BlockPos loader = this.loaders.get(chunk); if(!pos.equals(loader)) return false; this.loaders.remove(chunk); @@ -573,123 +622,202 @@ public final class WorldServer extends AWorldServer { return this.biomeGen; } - public Biome getBiomeGenForCoords(final BlockPos pos) { - if(this.isBlockLoaded(pos)) - return this.getChunk(pos).getBiome(pos, this.biomeGen); - else - return this.biomeGen.getBiomeGenerator(pos, Biome.DEF_BIOME); + public Biome getBiomeGenForCoords(BlockPos pos) { + return this.biomeGen.getBiomeGenerator(pos, Biome.DEF_BIOME); + } + + protected void calculateInitialWeather() { + super.calculateInitialWeather(); + this.temp = this.getBaseTemperature() + this.weather.getTemperature(); + } + + public float getTempOffset() { + return this.temp; + } + + protected float getBaseTemperature() { + return this.dimension.getTemperature() + this.dimension.getOrbitOffset() * + ExtMath.sin((((float)(this.daytime % this.dimension.getOrbitalPeriod()) / (float)this.dimension.getOrbitalPeriod()) + -0.125f) * (float)Math.PI * 2.0f); + } + + public LeavesType getLeavesGen(BlockPos pos) { + return this.canFreezeAt(pos) ? LeavesType.SNOWY : ((!this.dimension.getType().days || this.dimension.getOrbitOffset() == 0.0f) ? + this.dimension.getLeavesType() : LeavesType.values()[(int)((this.daytime % + this.dimension.getOrbitalPeriod()) * (long)LeavesType.values().length / this.dimension.getOrbitalPeriod())]); + } + + public float getTemperatureK(BlockPos pos) { + return this.temp + this.getBiomeGenForCoords(pos).getTemperature(pos); + } + + public float getTemperatureC(BlockPos pos) { + return World.ABSOLUTE_ZERO + this.getTemperatureK(pos); + } + + public boolean canFreezeAt(BlockPos pos) { + return this.getTemperatureC(pos) <= 0.0F; + } + + public boolean canBurnAt(BlockPos pos) { + return this.getTemperatureC(pos) >= 194.0f; + } + + public boolean doesWaterVaporize(BlockPos pos) { + return this.getTemperatureC(pos) >= 100.0f; + } + + public boolean isLavaFaster(BlockPos pos) { + return this.getTemperatureC(pos) >= 314.0f; + } + + public boolean canSnowAt(BlockPos pos, boolean checkLight, boolean allowLayers) { + if(!this.canFreezeAt(pos)) { + return false; + } + else if(!checkLight) { + return true; + } + else { + if(pos.getY() >= 0 && pos.getY() < 512 && this.getLightFor(pos) < 10) { + Block block = this.getState(pos).getBlock(); + + if((block.getMaterial() == Material.air || (allowLayers && block == Blocks.snow_layer)) + && Blocks.snow_layer.canPlaceBlockAt(this, pos)) { + return true; + } + } + + return false; + } + } + + public boolean isRainingAt(BlockPos strikePosition, boolean wet) { + if(wet ? !this.isRaining() : !this.hasDownfall()) { + return false; + } + else if(this.getPrecipitationHeight(strikePosition, strikePosition.getY() + 46, 48).getY() > strikePosition.getY()) { + return false; + } + return !this.canSnowAt(strikePosition, false, false); } public void setItemData(String dataID, WorldSavedData worldSavedDataIn) { - this.setData(dataID, worldSavedDataIn); + if(!this.debug) + this.setData(dataID, worldSavedDataIn); } public WorldSavedData loadItemData(String dataID) { - return this.loadData(dataID); + return this.debug ? null : this.loadData(dataID); } protected void updateBlocks() { - this.setActivePlayerChunksAndCheckLight(SVars.distance); + this.setActivePlayerChunksAndCheckLight(Config.distance); - int i = 0; - int j = 0; + if(this.debug) { + for(ChunkPos chunkcoordintpair1 : this.active) { + this.getChunk(chunkcoordintpair1.x, chunkcoordintpair1.z).update(); + } + } + else { + int i = 0; + int j = 0; - for(ChunkPos chunkcoordintpair : this.active) { - int k = chunkcoordintpair.x * 16; - int l = chunkcoordintpair.z * 16; + for(ChunkPos chunkcoordintpair : this.active) { + int k = chunkcoordintpair.x * 16; + int l = chunkcoordintpair.z * 16; // this.profiler.start("getChunk"); - ChunkServer chunk = this.getChunk(chunkcoordintpair.x, chunkcoordintpair.z); + Chunk chunk = this.getChunk(chunkcoordintpair.x, chunkcoordintpair.z); // this.profiler.next("moodSound"); // this.playMoodSound(k, l, chunk); // this.profiler.next("checkLight"); - chunk.enqueueRelight(); + chunk.enqueueRelight(); // this.profiler.next("tickChunk"); - chunk.update(false); + chunk.update(); // this.profiler.next("thunder"); - int l2 = SVars.boltChance; + int l2 = Config.boltChance; - if(l2 > 0 && this.rand.zrange(l2) == 0 && this.isThundering()) { - this.updateLCG = this.updateLCG * 3 + 1013904223; - int i1 = this.updateLCG >> 2; - BlockPos blockpos = this.adjustPosToNearbyEntity(new BlockPos(k + (i1 & 15), 0, l + (i1 >> 8 & 15))); + if(l2 > 0 && this.rand.zrange(l2) == 0 && this.isThundering()) { + this.updateLCG = this.updateLCG * 3 + 1013904223; + int i1 = this.updateLCG >> 2; + BlockPos blockpos = this.adjustPosToNearbyEntity(new BlockPos(k + (i1 & 15), 0, l + (i1 >> 8 & 15))); - if(this.canStrikeAt(blockpos)) { - this.strikeLightning((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ(), 0x737380, 120, true, null); + if(this.canStrikeAt(blockpos)) { + this.strikeLightning((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ(), 0x737380, 120, true, null); + } } - } // this.profiler.next("iceandsnow"); - l2 = SVars.weatherTick; + l2 = Config.weatherTick; - for(int z = 0; z < l2; z++) { - if(this.rand.zrange(16) == 0) { - this.updateLCG = this.updateLCG * 3 + 1013904223; - int k2 = this.updateLCG >> 2; - BlockPos blockpos2 = this.getPrecipitationHeight(new BlockPos(k + (k2 & 15), 0, l + (k2 >> 8 & 15))); - BlockPos blockpos1 = blockpos2.down(); + for(int z = 0; z < l2; z++) { + if(this.rand.zrange(16) == 0) { + this.updateLCG = this.updateLCG * 3 + 1013904223; + int k2 = this.updateLCG >> 2; + BlockPos blockpos2 = this.getPrecipitationHeight(new BlockPos(k + (k2 & 15), 0, l + (k2 >> 8 & 15))); + BlockPos blockpos1 = blockpos2.down(); - if(this.canBlockFreeze(blockpos1, true)) { - this.setState(blockpos1, Blocks.ice.getState()); - } + if(this.canBlockFreeze(blockpos1, true)) { + this.setState(blockpos1, Blocks.ice.getState()); + } - if(this.snow && this.isRaining() && this.canSnowAt(blockpos2, true, SVars.snowStack)) { - State layer = SVars.snowStack ? this.getState(blockpos2) : null; - this.setState(blockpos2, SVars.snowStack && layer.getBlock() == Blocks.snow_layer - ? (Blocks.snow_layer.getState().withProperty(BlockSnow.LAYERS, - Math.min(layer.getValue(BlockSnow.LAYERS) + 1, 2))) : Blocks.snow_layer.getState()); - } + if(this.snow && this.isRaining() && this.canSnowAt(blockpos2, true, Config.snowStack)) { + State layer = Config.snowStack ? this.getState(blockpos2) : null; + this.setState(blockpos2, Config.snowStack && layer.getBlock() == Blocks.snow_layer + ? (Blocks.snow_layer.getState().withProperty(BlockSnow.LAYERS, + Math.min(layer.getValue(BlockSnow.LAYERS) + 1, 2))) : Blocks.snow_layer.getState()); + } - if(this.isRaining()) { // && this.getBiomeGenForCoords(blockpos1).canRain()) { - this.getState(blockpos1).getBlock().fillWithRain(this, blockpos1); - } + if(this.isRaining()) { // && this.getBiomeGenForCoords(blockpos1).canRain()) { + this.getState(blockpos1).getBlock().fillWithRain(this, blockpos1); + } - if(SVars.igniteChance > 0 && SVars.fire && !this.isRaining() && - this.rand.chance(this.hasDownfall() ? Math.max(1, SVars.igniteChance / 3) : SVars.igniteChance) - && this.canPlaceFireAt(blockpos2)) { - this.setState(blockpos2, Blocks.fire.getState()); + if(Config.igniteChance > 0 && Config.fire && !this.isRaining() && + this.rand.chance(this.hasDownfall() ? Math.max(1, Config.igniteChance / 3) : Config.igniteChance) + && this.canPlaceFireAt(blockpos2)) { + this.setState(blockpos2, Blocks.fire.getState()); + } } } - } // this.profiler.next("tickBlocks"); - l2 = SVars.randomTick; + l2 = Config.randomTick; - if(l2 > 0) { - this.toTick.addAll(chunk.getStorage()); - for(BlockArray extendedblockstorage : this.toTick) { - if(extendedblockstorage != null && extendedblockstorage.isTicked()) { - for(int j1 = 0; j1 < l2; ++j1) { - this.updateLCG = this.updateLCG * 3 + 1013904223; - int k1 = this.updateLCG >> 2; - int l1 = k1 & 15; - int i2 = k1 >> 8 & 15; - int j2 = k1 >> 16 & 15; - ++j; - State iblockstate = extendedblockstorage.get(l1, j2, i2); - Block block = iblockstate.getBlock(); + if(l2 > 0) { + for(BlockArray extendedblockstorage : chunk.getStorage()) { + if(extendedblockstorage != null && extendedblockstorage.isTicked()) { + for(int j1 = 0; j1 < l2; ++j1) { + this.updateLCG = this.updateLCG * 3 + 1013904223; + int k1 = this.updateLCG >> 2; + int l1 = k1 & 15; + int i2 = k1 >> 8 & 15; + int j2 = k1 >> 16 & 15; + ++j; + State iblockstate = extendedblockstorage.get(l1, j2, i2); + Block block = iblockstate.getBlock(); - if(block.getTickRandomly()) { - ++i; - block.randomTick(this, new BlockPos(l1 + k, j2 + extendedblockstorage.getY(), i2 + l), iblockstate, - this.rand); + if(block.getTickRandomly()) { + ++i; + block.randomTick(this, new BlockPos(l1 + k, j2 + extendedblockstorage.getY(), i2 + l), iblockstate, + this.rand); + } } } } } - this.toTick.clear(); - } // this.profiler.end(); + } } } private BlockPos adjustPosToNearbyEntity(BlockPos pos) { BlockPos blockpos = this.getPrecipitationHeight(pos); - BoundingBox axisalignedbb = (new BoundingBox(blockpos, new BlockPos(blockpos.getX(), World.MAX_SIZE_Y, blockpos.getZ()))).expand(3.0D, + BoundingBox axisalignedbb = (new BoundingBox(blockpos, new BlockPos(blockpos.getX(), World.HEIGHT, blockpos.getZ()))).expand(3.0D, 3.0D, 3.0D); List list = this.getEntitiesWithinAABB(EntityLiving.class, axisalignedbb, new Predicate() { public boolean test(EntityLiving p_apply_1_) { - return p_apply_1_ != null && p_apply_1_.isEntityAlive() && WorldServer.this.canSeeSky(p_apply_1_.getPosition()); + return p_apply_1_ != null && p_apply_1_.isEntityAlive() && p_apply_1_.getPosition().getY() >= blockpos.getY(); } }); return !list.isEmpty() ? ((EntityLiving)list.get(this.rand.zrange(list.size()))).getPosition() : blockpos; @@ -708,14 +836,14 @@ public final class WorldServer extends AWorldServer { NextTickListEntry nextticklistentry = new NextTickListEntry(pos, blockIn); int i = 0; - if(this.updateForced && blockIn != Blocks.air) { + if(this.updateForced && blockIn.getMaterial() != Material.air) { if(blockIn.requiresUpdates()) { i = 8; if(this.isAreaLoaded(nextticklistentry.position.add(-i, -i, -i), nextticklistentry.position.add(i, i, i))) { State iblockstate = this.getState(nextticklistentry.position); - if(iblockstate.getBlock() != Blocks.air && iblockstate.getBlock() == nextticklistentry.getBlock()) { + if(iblockstate.getBlock().getMaterial() != Material.air && iblockstate.getBlock() == nextticklistentry.getBlock()) { iblockstate.getBlock().updateTick(this, nextticklistentry.position, iblockstate, this.rand); } } @@ -727,7 +855,7 @@ public final class WorldServer extends AWorldServer { } if(this.isAreaLoaded(pos.add(-i, -i, -i), pos.add(i, i, i))) { - if(blockIn != Blocks.air) { + if(blockIn.getMaterial() != Material.air) { nextticklistentry.setScheduledTime((long)delay + this.time); nextticklistentry.setPriority(priority); } @@ -743,7 +871,7 @@ public final class WorldServer extends AWorldServer { NextTickListEntry nextticklistentry = new NextTickListEntry(pos, blockIn); nextticklistentry.setPriority(priority); - if(blockIn != Blocks.air) { + if(blockIn.getMaterial() != Material.air) { nextticklistentry.setScheduledTime((long)delay + this.time); } @@ -755,7 +883,7 @@ public final class WorldServer extends AWorldServer { public void updateEntities() { if(this.players.isEmpty()) { - if(this.emptyTicks++ >= SVars.unloadTicks) { + if(this.emptyTicks++ >= Config.unloadTicks) { return; } } @@ -771,63 +899,68 @@ public final class WorldServer extends AWorldServer { } public boolean shouldUnload() { - return this.emptyTicks >= SVars.unloadTicks && this.loaderList.isEmpty(); + return this.emptyTicks >= Config.unloadTicks && this.loaderList.isEmpty(); } public boolean tickUpdates(boolean p_72955_1_) { - int i = this.ticksNext.size(); - - if(i != this.ticks.size()) { - throw new IllegalStateException("TickNextTick list out of synch"); + if(this.debug) { + return false; } else { - if(i > 1000) { - i = 1000; + int i = this.ticksNext.size(); + + if(i != this.ticks.size()) { + throw new IllegalStateException("TickNextTick list out of synch"); } + else { + if(i > 1000) { + i = 1000; + } // this.profiler.start("cleaning"); - for(int j = 0; j < i; ++j) { - NextTickListEntry nextticklistentry = (NextTickListEntry)this.ticksNext.first(); + for(int j = 0; j < i; ++j) { + NextTickListEntry nextticklistentry = (NextTickListEntry)this.ticksNext.first(); - if(!p_72955_1_ && nextticklistentry.scheduledTime > this.time) { - break; + if(!p_72955_1_ && nextticklistentry.scheduledTime > this.time) { + break; + } + + this.ticksNext.remove(nextticklistentry); + this.ticks.remove(nextticklistentry); + this.ticksNow.add(nextticklistentry); } - this.ticksNext.remove(nextticklistentry); - this.ticks.remove(nextticklistentry); - this.ticksNow.add(nextticklistentry); - } - // this.profiler.end(); // this.profiler.start("ticking"); - Iterator iterator = this.ticksNow.iterator(); + Iterator iterator = this.ticksNow.iterator(); - while(iterator.hasNext()) { - NextTickListEntry nextticklistentry1 = (NextTickListEntry)iterator.next(); - iterator.remove(); - int k = 0; + while(iterator.hasNext()) { + NextTickListEntry nextticklistentry1 = (NextTickListEntry)iterator.next(); + iterator.remove(); + int k = 0; - if(this.isAreaLoaded(nextticklistentry1.position.add(-k, -k, -k), nextticklistentry1.position.add(k, k, k))) { - State iblockstate = this.getState(nextticklistentry1.position); + if(this.isAreaLoaded(nextticklistentry1.position.add(-k, -k, -k), nextticklistentry1.position.add(k, k, k))) { + State iblockstate = this.getState(nextticklistentry1.position); - if(iblockstate.getBlock() != Blocks.air - && Block.isEqualTo(iblockstate.getBlock(), nextticklistentry1.getBlock())) { - iblockstate.getBlock().updateTick(this, nextticklistentry1.position, iblockstate, this.rand); + if(iblockstate.getBlock().getMaterial() != Material.air + && Block.isEqualTo(iblockstate.getBlock(), nextticklistentry1.getBlock())) { + iblockstate.getBlock().updateTick(this, nextticklistentry1.position, iblockstate, this.rand); + } + } + else { + this.scheduleUpdate(nextticklistentry1.position, nextticklistentry1.getBlock(), 0); } } - else { - this.scheduleUpdate(nextticklistentry1.position, nextticklistentry1.getBlock(), 0); - } - } // this.profiler.end(); - this.ticksNow.clear(); - return !this.ticksNext.isEmpty(); + this.ticksNow.clear(); + return !this.ticksNext.isEmpty(); + } } } - public List getPendingBlockUpdates(ChunkServer chunk) { + public List getPendingBlockUpdates(Chunk chunk) { int x1 = (chunk.xPos << 4) - 2; int x2 = x1 + 16 + 2; int z1 = (chunk.zPos << 4) - 2; @@ -869,33 +1002,33 @@ public final class WorldServer extends AWorldServer { } public static boolean needsLoading(Dimension dim) { - TagObject tag = null; + NBTTagCompound tag = null; try { - File dat = new File(new File(new File("chunk"), dim.getDimensionName()), "loaders.cdt"); + File dat = new File(new File(new File("chunk"), dim.getDimensionName()), "loaders.nbt"); if(dat.exists() && dat.isFile()) - tag = TagObject.readGZip(dat); + tag = NBTLoader.readGZip(dat); } catch(Exception e) { return false; } - return tag != null && tag.hasList("Loaders") && !tag.getList("Loaders").isEmpty(); + return tag != null && tag.hasKey("Loaders", 9) && !tag.getTagList("Loaders", 10).hasNoTags(); } public static void loadWarps(Dimension dim, Map warps) { - TagObject tag = null; + NBTTagCompound tag = null; try { - File dat = new File(new File(new File("chunk"), dim.getDimensionName()), "warps.cdt"); + File dat = new File(new File(new File("chunk"), dim.getDimensionName()), "warps.nbt"); if(dat.exists() && dat.isFile()) - tag = TagObject.readGZip(dat); + tag = NBTLoader.readGZip(dat); } catch(Exception e) { - Log.IO.error(e, "Konnte Warpliste nicht laden"); + Log.JNI.error(e, "Konnte Warpliste nicht laden"); return; } - if(tag != null && tag.hasList("Warps")) { - List list = tag.getList("Warps"); - for(int z = 0; z < list.size(); z++) { - TagObject pos = list.get(z); + if(tag != null && tag.hasKey("Warps", 9)) { + NBTTagList list = tag.getTagList("Warps", 10); + for(int z = 0; z < list.tagCount(); z++) { + NBTTagCompound pos = list.getCompoundTagAt(z); warps.put(pos.getString("Name"), new Position(pos.getDouble("X"), pos.getDouble("Y"), pos.getDouble("Z"), pos.getFloat("Yaw"), pos.getFloat("Pitch"), dim.getDimensionId())); } @@ -903,144 +1036,122 @@ public final class WorldServer extends AWorldServer { } public static void saveWarps(Map warps) { - Map> map = Maps.newHashMap(); + Map map = Maps.newHashMap(); for(Entry pos : warps.entrySet()) { - Dimension dim = UniverseRegistry.getDimension(pos.getValue().dim()); + Dimension dim = UniverseRegistry.getDimension(pos.getValue().dim); if(dim != null) { - List list = map.get(pos.getValue().dim()); + NBTTagList list = map.get(pos.getValue().dim); if(list == null) - map.put(pos.getValue().dim(), list = Lists.newArrayList()); - TagObject warp = new TagObject(); + map.put(pos.getValue().dim, list = new NBTTagList()); + NBTTagCompound warp = new NBTTagCompound(); warp.setString("Name", pos.getKey()); - warp.setDouble("X", pos.getValue().x()); - warp.setDouble("Y", pos.getValue().y()); - warp.setDouble("Z", pos.getValue().z()); - warp.setFloat("Yaw", pos.getValue().yaw()); - warp.setFloat("Pitch", pos.getValue().pitch()); - list.add(warp); + warp.setDouble("X", pos.getValue().x); + warp.setDouble("Y", pos.getValue().y); + warp.setDouble("Z", pos.getValue().z); + warp.setFloat("Yaw", pos.getValue().yaw); + warp.setFloat("Pitch", pos.getValue().pitch); + list.appendTag(warp); } } for(Dimension dim : UniverseRegistry.getDimensions()) { - List list = map.get(dim.getDimensionId()); - File file = new File(new File(new File("chunk"), dim.getDimensionName()), "warps.cdt"); + NBTTagList list = map.get(dim.getDimensionId()); + File file = new File(new File(new File("chunk"), dim.getDimensionName()), "warps.nbt"); if(list == null) { file.delete(); } else { - TagObject tag = new TagObject(); - tag.setList("Warps", list); + NBTTagCompound tag = new NBTTagCompound(); + tag.setTag("Warps", list); try { - TagObject.writeGZip(tag, file); + NBTLoader.writeGZip(tag, file); } catch(Exception e) { - Log.IO.error(e, "Konnte Warpliste nicht speichern"); + Log.JNI.error(e, "Konnte Warpliste nicht speichern"); } } } map.clear(); } - private static boolean deleteFiles(File[] files) { - if(files == null) { - Log.IO.warn("Konnte Ordner nicht löschen"); - return false; - } - - for(int i = 0; i < files.length; ++i) { - File file = files[i]; - Log.IO.info("Lösche " + file); - - if(file.isDirectory() && !deleteFiles(file.listFiles())) { - Log.IO.warn("Konnte Ordner " + file + " nicht löschen"); - return false; - } - - if(!file.delete()) { - Log.IO.warn("Konnte Datei " + file + " nicht löschen"); - return false; - } - } - - return true; - } - public void saveAllChunks() { + if(/* (force || !this.disableSaving) && */ !this.debug) { // if(this.primary) { // // } - if(this.loadersModified) { - this.loadersModified = false; - TagObject loaders = new TagObject(); - List list = Lists.newArrayList(); - for(BlockPos pos : this.loaderList) { - TagObject loader = new TagObject(); - loader.setInt("X", pos.getX()); - loader.setInt("Y", pos.getY()); - loader.setInt("Z", pos.getZ()); - list.add(loader); - } - loaders.setList("Loaders", list); - File file = new File(this.chunkDir, "loaders.cdt"); - if(list.isEmpty()) { - file.delete(); - } - else { - try { - TagObject.writeGZip(loaders, file); + if(this.loadersModified) { + this.loadersModified = false; + NBTTagCompound loaders = new NBTTagCompound(); + NBTTagList list = new NBTTagList(); + for(BlockPos pos : this.loaderList) { + NBTTagCompound loader = new NBTTagCompound(); + loader.setInteger("X", pos.getX()); + loader.setInteger("Y", pos.getY()); + loader.setInteger("Z", pos.getZ()); + list.appendTag(loader); } - catch(Exception e) { - Log.IO.error(e, "Konnte Ladeliste nicht speichern"); + loaders.setTag("Loaders", list); + File file = new File(this.chunkDir, "loaders.nbt"); + if(list.hasNoTags()) { + file.delete(); + } + else { + try { + NBTLoader.writeGZip(loaders, file); + } + catch(Exception e) { + Log.JNI.error(e, "Konnte Ladeliste nicht speichern"); + } } } - } // if(this.warpsModified) { // this.warpsModified = false; // } // if(this.dataModified) { // this.dataModified = false; - TagObject data = new TagObject(); + NBTTagCompound data = new NBTTagCompound(); // data.setLong("Seed", this.seed); - data.setObject("Generator", this.dimension.toTags(true)); - data.setLong("Time", this.time); - data.setBool("Exterminated", this.exterminated); - data.setString("Weather", this.weather.getName()); - // ... - File file = new File(this.chunkDir, "data.cdt"); - try { - TagObject.writeGZip(data, file); - } - catch(Exception e) { - Log.IO.error(e, "Konnte Weltdaten nicht speichern"); - } -// } - for(int i = 0; i < this.dataList.size(); ++i) { - WorldSavedData wdata = this.dataList.get(i); - if(wdata.dirty) { - this.saveData(wdata); - wdata.dirty = false; - } - } - if(this.villageStorage != null && this.villageStorage.isDirty()) { - TagObject tag = this.villageStorage.toTags(); - File dat = new File(this.chunkDir, "villages.cdt"); + data.setTag("Generator", this.dimension.toNbt(true)); + data.setLong("Time", this.time); + data.setBoolean("Exterminated", this.exterminated); + data.setString("Weather", this.weather.getName()); + // ... + File file = new File(this.chunkDir, "data.nbt"); try { - TagObject.writeGZip(tag, dat); + NBTLoader.writeGZip(data, file); } catch(Exception e) { - Log.IO.error(e, "Konnte Dorfliste nicht speichern"); + Log.JNI.error(e, "Konnte Weltdaten nicht speichern"); } - } - List list = Lists.newArrayList(this.loaded); - for(int n = 0; n < list.size(); ++n) { - ChunkServer chunk = list.get(n); - if(chunk.isDirty(this.time)) { - this.saveChunkData(chunk); - chunk.setModified(false); +// } + for(int i = 0; i < this.dataList.size(); ++i) { + WorldSavedData wdata = this.dataList.get(i); + if(wdata.dirty) { + this.saveData(wdata); + wdata.dirty = false; + } } - } - for(ChunkServer chunk : Lists.newArrayList(this.loaded)) { - if(chunk != null && !this.hasPlayerInstance(chunk.xPos, chunk.zPos)) { - this.dropChunk(chunk.xPos, chunk.zPos); + if(this.villageStorage != null && this.villageStorage.isDirty()) { + NBTTagCompound tag = this.villageStorage.writeToNBT(); + File dat = new File(this.chunkDir, "villages.nbt"); + try { + NBTLoader.writeGZip(tag, dat); + } + catch(Exception e) { + Log.JNI.error(e, "Konnte Dorfliste nicht speichern"); + } + } + List list = Lists.newArrayList(this.loaded); + for(int n = 0; n < list.size(); ++n) { + Chunk chunk = list.get(n); + if(chunk.isDirty(this.time)) { + this.saveChunkData(chunk); + chunk.setModified(false); + } + } + for(Chunk chunk : Lists.newArrayList(this.loaded)) { + if(chunk != null && !this.hasPlayerInstance(chunk.xPos, chunk.zPos)) { + this.dropChunk(chunk.xPos, chunk.zPos); + } } } } @@ -1073,15 +1184,15 @@ public final class WorldServer extends AWorldServer { EntityLightning entity = new EntityLightning(this, x, y, z, color, damage, fire, summoner); this.effects.add(entity); this.server.sendNear(entity.posX, entity.posY, entity.posZ, 512.0D, this.dimension.getDimensionId(), - new SPacketSpawnGlobalEntity(entity, 1, entity.color)); - if(fire && SVars.fire) { + new S2CPacketSpawnGlobalEntity(entity, 1, entity.color)); + if(fire && Config.fire) { BlockPos pos = new BlockPos(entity); if(this.isAreaLoaded(pos, 10)) { - if(this.getState(pos).getBlock() == Blocks.air && Blocks.fire.canPlaceBlockAt(this, pos)) + if(this.getState(pos).getBlock().getMaterial() == Material.air && Blocks.fire.canPlaceBlockAt(this, pos)) this.setState(pos, Blocks.fire.getState()); for(int n = 0; n < 4; n++) { BlockPos extra = pos.add(this.rand.range(-1, 1), this.rand.range(-1, 1), this.rand.range(-1, 1)); - if(this.getState(extra).getBlock() == Blocks.air && Blocks.fire.canPlaceBlockAt(this, extra)) + if(this.getState(extra).getBlock().getMaterial() == Material.air && Blocks.fire.canPlaceBlockAt(this, extra)) this.setState(extra, Blocks.fire.getState()); } } @@ -1089,7 +1200,7 @@ public final class WorldServer extends AWorldServer { } public void setEntityState(Entity entityIn, byte state) { - this.sendToAllTrackingAndSelf(entityIn, new SPacketEntityStatus(entityIn, state)); + this.sendToAllTrackingAndSelf(entityIn, new S1APacketEntityStatus(entityIn, state)); } public Explosion newExplosion(Entity entityIn, double x, double y, double z, float strength, boolean isFlaming, boolean isSmoking, boolean altSound) { @@ -1103,7 +1214,7 @@ public final class WorldServer extends AWorldServer { for(EntityNPC entityplayer : this.players) { if(entityplayer.getDistanceSq(x, y, z) < 4096.0D) { - entityplayer.connection.sendPacket(new SPacketExplosion(x, y, z, strength, explosion.getAffectedBlockPositions(), + entityplayer.connection.sendPacket(new S27PacketExplosion(x, y, z, strength, explosion.getAffectedBlockPositions(), (Vec3)explosion.getPlayerKnockbackMap().get(entityplayer), altSound)); } } @@ -1112,9 +1223,9 @@ public final class WorldServer extends AWorldServer { } public void addBlockEvent(BlockPos pos, Block blockIn, int eventID, int eventParam) { - TickEvent blockeventdata = new TickEvent(pos, blockIn, eventID, eventParam); + BlockEventData blockeventdata = new BlockEventData(pos, blockIn, eventID, eventParam); - for(TickEvent blockeventdata1 : this.queue[this.blockEvtIdx]) { + for(BlockEventData blockeventdata1 : this.queue[this.blockEvtIdx]) { if(blockeventdata1.equals(blockeventdata)) { return; } @@ -1128,12 +1239,12 @@ public final class WorldServer extends AWorldServer { int i = this.blockEvtIdx; this.blockEvtIdx ^= 1; - for(TickEvent blockeventdata : this.queue[i]) { + for(BlockEventData blockeventdata : this.queue[i]) { if(this.fireBlockEvent(blockeventdata)) { - this.server.sendNear((double)blockeventdata.position().getX(), (double)blockeventdata.position().getY(), - (double)blockeventdata.position().getZ(), 64.0D, this.dimension.getDimensionId(), - new SPacketBlockAction(blockeventdata.position(), blockeventdata.block(), blockeventdata.id(), - blockeventdata.parameter())); + this.server.sendNear((double)blockeventdata.getPosition().getX(), (double)blockeventdata.getPosition().getY(), + (double)blockeventdata.getPosition().getZ(), 64.0D, this.dimension.getDimensionId(), + new SPacketBlockAction(blockeventdata.getPosition(), blockeventdata.getBlock(), blockeventdata.getEventID(), + blockeventdata.getEventParameter())); } } @@ -1141,10 +1252,10 @@ public final class WorldServer extends AWorldServer { } } - private boolean fireBlockEvent(TickEvent event) { - State iblockstate = this.getState(event.position()); - return iblockstate.getBlock() == event.block() - ? iblockstate.getBlock().onBlockEventReceived(this, event.position(), iblockstate, event.id(), event.parameter()) + private boolean fireBlockEvent(BlockEventData event) { + State iblockstate = this.getState(event.getPosition()); + return iblockstate.getBlock() == event.getBlock() + ? iblockstate.getBlock().onBlockEventReceived(this, event.getPosition(), iblockstate, event.getEventID(), event.getEventParameter()) : false; } @@ -1156,7 +1267,7 @@ public final class WorldServer extends AWorldServer { public void setWeather(Weather weather) { this.weather = weather; // this.dataModified = true; - this.server.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.SET_WEATHER, + this.server.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.SET_WEATHER, weather.getID()), this.dimension.getDimensionId()); } @@ -1183,9 +1294,9 @@ public final class WorldServer extends AWorldServer { float prevRain = this.rain; float prevFog = this.fog; - if(SVars.weather && SVars.weatherChance > 0) { + if(Config.weather && Config.weatherChance > 0) { // int time = dim.getWeatherTime(); - if(this.rand.chance(SVars.weatherChance)) { + if(this.rand.chance(Config.weatherChance)) { Weather nweather = Weather.pick(this.getBaseTemperature(), this.rand); if(nweather != this.weather) { // dim.setWeatherTime(this.rand.zrange(Config.weatherFlow) + Config.weatherFlow); @@ -1228,15 +1339,15 @@ public final class WorldServer extends AWorldServer { } if(prevRain != this.rain || force) { - this.server.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.RAIN_STRENGTH, this.rain), this.dimension.getDimensionId()); + this.server.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.RAIN_STRENGTH, this.rain), this.dimension.getDimensionId()); } if(prevDarkness != this.darkness || force) { - this.server.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.DARKNESS, this.darkness), this.dimension.getDimensionId()); + this.server.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.DARKNESS, this.darkness), this.dimension.getDimensionId()); } if(prevFog != this.fog || force) { - this.server.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.FOG_STRENGTH, this.fog), this.dimension.getDimensionId()); + this.server.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.FOG_STRENGTH, this.fog), this.dimension.getDimensionId()); } } @@ -1250,10 +1361,6 @@ public final class WorldServer extends AWorldServer { else if(this.temp > temp) { this.temp = Math.max((float)((double)this.temp - 0.01D), temp); } - - if(prevTemp != this.temp || force) { - this.server.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.TEMPERATURE, this.temp), this.dimension.getDimensionId()); - } } // if(this.resetWeather) @@ -1268,7 +1375,7 @@ public final class WorldServer extends AWorldServer { public void spawnParticle(ParticleType particleType, boolean longDistance, double xCoord, double yCoord, double zCoord, int numberOfParticles, double xOffset, double yOffset, double zOffset, double particleSpeed, int[] particleArguments) { - Packet packet = new SPacketParticles(particleType, longDistance, (float)xCoord, (float)yCoord, (float)zCoord, (float)xOffset, + Packet packet = new S2APacketParticles(particleType, longDistance, (float)xCoord, (float)yCoord, (float)zCoord, (float)xOffset, (float)yOffset, (float)zOffset, (float)particleSpeed, numberOfParticles, particleArguments); for(int i = 0; i < this.players.size(); ++i) { @@ -1283,26 +1390,22 @@ public final class WorldServer extends AWorldServer { } protected boolean isLoaded(int x, int z, boolean allowEmpty) { - return this.chunkExists(x, z); + return this.chunkExists(x, z) && super.isLoaded(x, z, allowEmpty); } - public ChunkServer getChunk(int x, int z) { - ChunkServer chunk = this.chunks.getValueByKey(LongHashMap.packInt(x, z)); + public Chunk getChunk(int x, int z) { + Chunk chunk = this.chunks.get(new ChunkPos(x, z)); return chunk == null ? this.loadChunk(x, z) : chunk; } - public ChunkServer getChunk(BlockPos pos) { - return this.getChunk(pos.getX() >> 4, pos.getZ() >> 4); - } - private boolean chunkExists(int x, int z) { - return this.chunks.containsItem(LongHashMap.packInt(x, z)); + return this.chunks.containsKey(new ChunkPos(x, z)); } public void dropChunk(int x, int z) { - long chunk = LongHashMap.packInt(x, z); - if(!this.loaders.containsItem(chunk)) - this.dropped.add(Long.valueOf(chunk)); + ChunkPos chunk = new ChunkPos(x, z); + if(!this.loaders.containsKey(chunk)) + this.dropped.add(chunk); } public void loadForcedChunks() { @@ -1312,24 +1415,25 @@ public final class WorldServer extends AWorldServer { } public void unloadAllChunks() { - for(ChunkServer chunk : this.loaded) { + for(Chunk chunk : this.loaded) { this.dropChunk(chunk.xPos, chunk.zPos); } } - public ChunkServer loadChunk(int x, int z) { - long id = LongHashMap.packInt(x, z); - this.dropped.remove(Long.valueOf(id)); - ChunkServer chunk = this.chunks.getValueByKey(id); + public Chunk loadChunk(int x, int z) { + ChunkPos id = new ChunkPos(x, z); + this.dropped.remove(id); + Chunk chunk = this.chunks.get(id); if(chunk == null) { - chunk = this.loadChunkFromFile(x, z); + if(!this.debug) + chunk = this.loadChunkFromFile(x, z); if(chunk == null) { chunk = this.generate(x, z); } - this.chunks.add(id, chunk); + this.chunks.put(id, chunk); this.loaded.add(chunk); chunk.onChunkLoad(); this.popChunk(x, z); @@ -1338,10 +1442,10 @@ public final class WorldServer extends AWorldServer { return chunk; } - private ChunkServer loadChunkFromFile(int x, int z) { + private Chunk loadChunkFromFile(int x, int z) { try { ChunkPos coord = new ChunkPos(x, z); - TagObject tag = this.toRemove.get(coord); + NBTTagCompound tag = this.toRemove.get(coord); if(tag == null) { tag = Region.readChunk(this.chunkDir, x, z); // DataInputStream in = ; @@ -1350,7 +1454,7 @@ public final class WorldServer extends AWorldServer { } // tag = CompressedStreamTools.read(in); } - ChunkServer chunk = Region.readChunk(this, x, z, tag); + Chunk chunk = Region.readNbt(this, x, z, tag); if(chunk != null) { chunk.setSaved(this.time); if(this.mineshaftGen != null) { @@ -1372,24 +1476,32 @@ public final class WorldServer extends AWorldServer { return chunk; } catch(Exception e) { - Log.IO.error(e, "Konnte Chunk nicht laden"); + Log.JNI.error(e, "Konnte Chunk nicht laden"); return null; } } - private void saveChunkData(ChunkServer chunk) { + private void saveChunkData(Chunk chunk) { +// try { chunk.setSaved(this.time); +// this.lock.check(); try { - TagObject tag = Region.writeChunk(this, chunk); - ChunkPos coord = new ChunkPos(chunk.xPos, chunk.zPos); +// NBTTagCompound ltag = new NBTTagCompound(); +// tag.setTag("Level", ltag); + NBTTagCompound tag = Region.writeNbt(this, chunk); + ChunkPos coord = chunk.getPos(); if(!this.pending.contains(coord)) { this.toRemove.put(coord, tag); } Region.queueIO(this); } catch(Exception e) { - Log.IO.error(e, "Konnte Chunk nicht speichern"); + Log.JNI.error(e, "Konnte Chunk nicht speichern"); } +// } +// catch(SaveException e) { +// Log.error("Konnte Chunk nicht speichern; bereits von einer anderen Instanz genutzt?", e); +// } } public boolean writeNextIO() { @@ -1404,7 +1516,7 @@ public final class WorldServer extends AWorldServer { boolean flag; try { this.pending.add(coord); - TagObject tag = this.toRemove.remove(coord); + NBTTagCompound tag = this.toRemove.remove(coord); if(tag != null) { try { @@ -1414,7 +1526,7 @@ public final class WorldServer extends AWorldServer { Region.writeChunk(this.chunkDir, coord.x, coord.z, tag); } catch(Exception e) { - Log.IO.error(e, "Konnte Chunk nicht speichern"); + Log.JNI.error(e, "Konnte Chunk nicht speichern"); } } flag = true; @@ -1486,9 +1598,9 @@ public final class WorldServer extends AWorldServer { } private void populate(int x, int z) { - ChunkServer chunk = this.getChunk(x, z); + Chunk chunk = this.getChunk(x, z); if(!chunk.isTerrainPopulated()) { - chunk.checkLight(); + chunk.setTerrainPopulated(true); BlockFalling.fallInstantly = true; int bx = x * 16; int bz = z * 16; @@ -1536,7 +1648,7 @@ public final class WorldServer extends AWorldServer { liquid.generate(this, this.grng, pos); } } - if(this.mobs && SVars.mobs && SVars.genSpawn) { + if(this.mobs && Config.mobs && Config.genSpawn) { Spawner.generate(this, biome, bx + 8, bz + 8, 16, 16, this.grng); } // if(this.snow) { @@ -1555,11 +1667,11 @@ public final class WorldServer extends AWorldServer { } // } BlockFalling.fallInstantly = false; - chunk.setModified(true); + chunk.setModified(); } } - private ChunkServer generate(int x, int z) { + private Chunk generate(int x, int z) { this.grng.setSeed((long)x * 341873128712L + (long)z * 132897987541L); ChunkPrimer primer = new ChunkPrimer(this.height); this.generator.generateChunk(this, x, z, primer); @@ -1591,7 +1703,7 @@ public final class WorldServer extends AWorldServer { if(this.scatteredGen != null) { this.scatteredGen.generate(this, x, z, primer); } - return new ChunkServer(this, primer.getData(), primer.height, this.base, this.ceil, this.grng, this.biomes, x, z); + return new Chunk(this, primer.getData(), primer.height, this.base, this.ceil, this.grng, x, z); } public boolean isExterminated() { @@ -1599,6 +1711,8 @@ public final class WorldServer extends AWorldServer { } public boolean exterminate() { + if(this.debug) + return true; if(this.exterminated) return false; this.setWeather(Weather.CLEAR); @@ -1607,47 +1721,47 @@ public final class WorldServer extends AWorldServer { if(!this.loaderList.isEmpty()) this.loadersModified = true; for(BlockPos pos : this.loaderList) { - this.loaders.remove(LongHashMap.packInt(pos.getX() / 16, pos.getZ() / 16)); + this.loaders.remove(new ChunkPos(pos.getX() / 16, pos.getZ() / 16)); } this.loaderList.clear(); for(Iterator> iter = this.server.getWarps().entrySet().iterator(); iter.hasNext();) { Entry pos = iter.next(); - if(pos.getValue().dim() == this.dimension.getDimensionId()) + if(pos.getValue().dim == this.dimension.getDimensionId()) iter.remove(); } Region.finishWrite(); - deleteFiles(this.chunkDir.listFiles(new FileFilter() { + FileUtils.deleteFiles(this.chunkDir.listFiles(new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } })); this.exterminated = true; // this.dataModified = true; - for(Long v : this.dropped) { - ChunkServer chunk = this.chunks.getValueByKey(v.longValue()); + for(ChunkPos v : this.dropped) { + Chunk chunk = this.chunks.get(v); if(chunk != null) { chunk.onChunkUnload(); - this.chunks.remove(v.longValue()); + this.chunks.remove(v); this.loaded.remove(chunk); } } this.dropped.clear(); - List loaded = Lists.newArrayList(this.loaded); + List loaded = Lists.newArrayList(this.loaded); this.loaded.clear(); this.setExterminatedGen(); - for(ChunkServer chunk : loaded) { - long pos = LongHashMap.packInt(chunk.xPos, chunk.zPos); + for(Chunk chunk : loaded) { + ChunkPos pos = new ChunkPos(chunk.xPos, chunk.zPos); chunk.onChunkUnload(); this.chunks.remove(pos); chunk = this.generate(chunk.xPos, chunk.zPos); - this.chunks.add(pos, chunk); + this.chunks.put(pos, chunk); this.loaded.add(chunk); chunk.onChunkLoad(); - chunk.checkLight(); - chunk.setModified(true); + chunk.setTerrainPopulated(true); + chunk.setModified(); } - for(ChunkServer chunk : this.loaded) { - chunk.update(false); + for(Chunk chunk : this.loaded) { + chunk.update(); } this.entities.removeAll(this.unloaded); for(int l = 0; l < this.unloaded.size(); ++l) { @@ -1668,15 +1782,15 @@ public final class WorldServer extends AWorldServer { } for(EntityNPC player : this.players) { player.attackEntityFrom(DamageSource.causeExterminatusDamage(null), 5000); - Packet packet = new SPacketParticles(ParticleType.EXPLOSION_HUGE, true, + Packet packet = new S2APacketParticles(ParticleType.EXPLOSION_HUGE, true, (float)player.posX, (float)this.getSeaLevel() + 4.0f, (float)player.posZ, (float)128.0, (float)2.0, (float)128.0, (float)0.15, 1000, new int[0]); player.connection.sendPacket(packet); - packet = new SPacketParticles(ParticleType.CLOUD, true, + packet = new S2APacketParticles(ParticleType.CLOUD, true, (float)player.posX, (float)this.getSeaLevel() + 4.0f, (float)player.posZ, (float)128.0, (float)2.0, (float)128.0, (float)0.15, 1000, new int[0]); player.connection.sendPacket(packet); - packet = new SPacketEffect(1025, new BlockPos(player.posX, (double)this.getSeaLevel() + 4.0, player.posZ), 0); + packet = new S28PacketEffect(1025, new BlockPos(player.posX, (double)this.getSeaLevel() + 4.0, player.posZ), 0); player.connection.sendPacket(packet); } return true; @@ -1699,8 +1813,8 @@ public final class WorldServer extends AWorldServer { this.replacer = null; this.populate = false; this.liquid = Blocks.air.getState(); - this.base = false; - this.ceil = false; + this.base = Blocks.air.getState(); + this.ceil = null; this.height = this.generator.getMaximumHeight(); this.seaLevel = this.dimension.getSeaLevel(); this.ores = null; @@ -1719,7 +1833,7 @@ public final class WorldServer extends AWorldServer { Object[] worlds = server.getWorlds().toArray(); for(Object obj : worlds) { WorldServer world = (WorldServer)obj; - chunks += world.chunks.getNumHashElements(); + chunks += world.chunks.size(); entities += world.entities.size(); tiles += world.tiles.size(); ticked += world.tickable.size(); @@ -1752,7 +1866,7 @@ public final class WorldServer extends AWorldServer { public void playSound(SoundEvent sound, double x, double y, double z, float volume) { - this.server.sendNear(x, y, z, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.dimension.getDimensionId(), new SPacketSoundEffect(sound, x, y, z, volume)); + this.server.sendNear(x, y, z, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.dimension.getDimensionId(), new S29PacketSoundEffect(sound, x, y, z, volume)); } public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2) @@ -1765,7 +1879,7 @@ public final class WorldServer extends AWorldServer { public void playAuxSFX(EntityNPC player, int sfxType, BlockPos blockPosIn, int data) { - this.server.sendNearExcept(player, (double)blockPosIn.getX(), (double)blockPosIn.getY(), (double)blockPosIn.getZ(), 64.0D, this.dimension.getDimensionId(), new SPacketEffect(sfxType, blockPosIn, data)); + this.server.sendNearExcept(player, (double)blockPosIn.getX(), (double)blockPosIn.getY(), (double)blockPosIn.getZ(), 64.0D, this.dimension.getDimensionId(), new S28PacketEffect(sfxType, blockPosIn, data)); } // public void broadcastSound(int soundID, BlockPos pos, int data) @@ -1819,31 +1933,17 @@ public final class WorldServer extends AWorldServer { } private boolean hasPlayerInstance(int chunkX, int chunkZ) { - long v = (long)chunkX + 2147483647L | (long)chunkZ + 2147483647L << 32; - return this.instances.getValueByKey(v) != null; - } - - public void setBiome(BlockPos pos, Biome biome) { - ChunkServer chunk = this.getChunk(pos); - if(chunk == null || !chunk.isLoaded()) - return; - chunk.getBiomes()[((pos.getZ() & 0xF) << 4 | pos.getX() & 0xF)] = (byte)biome.id; - chunk.setModified(true); - int chunkX = pos.getX() >> 4; - int chunkZ = pos.getZ() >> 4; - long v = (long)chunkX + 2147483647L | (long)chunkZ + 2147483647L << 32; - PlayerInstance ins = this.instances.getValueByKey(v); - if(ins != null) - ins.sendToAllPlayersWatchingChunk(new SPacketBiome(pos, biome)); + ChunkPos v = new ChunkPos(chunkX, chunkZ); + return this.instances.get(v) != null; } private PlayerInstance getPlayerInstance(int chunkX, int chunkZ, boolean create) { - long v = (long)chunkX + 2147483647L | (long)chunkZ + 2147483647L << 32; - PlayerInstance inst = this.instances.getValueByKey(v); + ChunkPos v = new ChunkPos(chunkX, chunkZ); + PlayerInstance inst = this.instances.get(v); if(inst == null && create) { inst = new PlayerInstance(chunkX, chunkZ); - this.instances.add(v, inst); + this.instances.put(v, inst); this.instList.add(inst); } @@ -1985,7 +2085,7 @@ public final class WorldServer extends AWorldServer { } public void updateViewRadius() { - int radius = ExtMath.clampi(SVars.distance, 3, 128); + int radius = ExtMath.clampi(Config.distance, 3, 128); if(radius != this.viewRadius) { int diff = radius - this.viewRadius; @@ -2019,7 +2119,7 @@ public final class WorldServer extends AWorldServer { this.viewRadius = radius; } - this.trackDistance = SVars.distance * 16 - 16; + this.trackDistance = Config.distance * 16 - 16; } public void trackEntity(Entity entityIn) { @@ -2054,7 +2154,7 @@ public final class WorldServer extends AWorldServer { entitytrackerentry.updatePlayerEntities(this.players); } catch(Throwable throwable) { - Log.TICK.error((Throwable)throwable, (String)"Fange Objekt-Tracking-Fehler \"leise\" auf."); + Log.JNI.error((Throwable)throwable, (String)"Fange Objekt-Tracking-Fehler \"leise\" auf."); } } @@ -2130,7 +2230,7 @@ public final class WorldServer extends AWorldServer { } } - public void updateChunksForPlayer(EntityNPC player, ChunkServer chunk) { + public void updateChunksForPlayer(EntityNPC player, Chunk chunk) { for(EntityTrackerEntry entitytrackerentry : this.tracked) { if(entitytrackerentry.trackedEntity != player && entitytrackerentry.trackedEntity.chunkCoordX == chunk.xPos && entitytrackerentry.trackedEntity.chunkCoordZ == chunk.zPos) { @@ -2143,7 +2243,7 @@ public final class WorldServer extends AWorldServer { // int x = position.getBlockX(); // int y = position.getBlockY(); // int z = position.getBlockZ(); - ChunkServer chunk = this.getChunk(pos.getX() >> 4, pos.getZ() >> 4); + Chunk chunk = this.getChunk(pos.getX() >> 4, pos.getZ() >> 4); // BlockPos pos = new BlockPos(x, y, z); State old = chunk.getState(pos); State newState = block.getState(); @@ -2156,13 +2256,13 @@ public final class WorldServer extends AWorldServer { State successState = chunk.setState(pos, newState); boolean successful = successState != null; if(successful) { - if(block.getData() != null) { + if(block.getNbtData() != null) { this.removeTileEntity(pos); - TagObject tag = block.getData(); + NBTTagCompound tag = block.getNbtData(); tag.setString("id", tag.getString("id")); - tag.setInt("x", pos.getX()); - tag.setInt("y", pos.getY()); - tag.setInt("z", pos.getZ()); + tag.setTag("x", new NBTTagInt(pos.getX())); + tag.setTag("y", new NBTTagInt(pos.getY())); + tag.setTag("z", new NBTTagInt(pos.getZ())); TileEntity tileEntity = TileEntity.createAndLoadEntity(tag); if(tileEntity != null) { this.setTileEntity(pos, tileEntity); @@ -2196,7 +2296,22 @@ public final class WorldServer extends AWorldServer { return new ClipboardBlock(state); } } - + +// public final EditBlock getLazyBlock(Vector position) { +// State state = this.getState(new BlockPos(position.getBlockX(), position.getBlockY(), position.getBlockZ())); +// return new LazyBlock(state, this, position); +// } + +// public final List getEntities(EditRegion region) { +// List entities = Lists.newArrayList(); +// for(Entity entity : this.entities) { +// if(region.contains(new Vector(entity.posX, entity.posY, entity.posZ))) { +// entities.add(entity); +// } +// } +// return entities; +// } + public final List getEntities() { List entities = Lists.newArrayList(); for(Entity entity : this.entities) { @@ -2223,10 +2338,7 @@ public final class WorldServer extends AWorldServer { } public boolean canStrikeAt(BlockPos strikePosition) { - if(!this.canSeeSky(strikePosition)) { - return false; - } - else if(this.getPrecipitationHeight(strikePosition).getY() > strikePosition.getY()) { + if(this.getPrecipitationHeight(strikePosition).getY() > strikePosition.getY()) { return false; } return true; @@ -2283,10 +2395,10 @@ public final class WorldServer extends AWorldServer { if(!this.canBurnAt(pos)) { return false; } - if(pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) { + if(pos.getY() >= 0 && pos.getY() < 512) { Block block = this.getState(pos).getBlock(); - if(block == Blocks.air && Blocks.fire.canPlaceBlockAt(this, pos)) { + if(block.getMaterial() == Material.air && Blocks.fire.canPlaceBlockAt(this, pos)) { return true; } } @@ -2299,7 +2411,7 @@ public final class WorldServer extends AWorldServer { return false; } else { - if(pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y && this.getLightFor(LightType.BLOCK, pos) < 10) { + if(pos.getY() >= 0 && pos.getY() < 512 && this.getLightFor(pos) < 10) { State iblockstate = this.getState(pos); Block block = iblockstate.getBlock(); @@ -2308,10 +2420,10 @@ public final class WorldServer extends AWorldServer { return true; } - boolean flag = this.getState(pos.west()).getBlock().getMaterial() == Material.WATER && - this.getState(pos.east()).getBlock().getMaterial() == Material.WATER && - this.getState(pos.north()).getBlock().getMaterial() == Material.WATER && - this.getState(pos.south()).getBlock().getMaterial() == Material.WATER; + boolean flag = this.getState(pos.west()).getBlock().getMaterial() == Material.water && + this.getState(pos.east()).getBlock().getMaterial() == Material.water && + this.getState(pos.north()).getBlock().getMaterial() == Material.water && + this.getState(pos.south()).getBlock().getMaterial() == Material.water; if(!flag) { return true; @@ -2337,7 +2449,7 @@ public final class WorldServer extends AWorldServer { for(int i2 = i1; i2 <= j1; ++i2) { Block block = this.getState(blockpos$mutableblockpos.set(k1, l1, i2)).getBlock(); - if(block != Blocks.air) { + if(block.getMaterial() != Material.air) { return true; } } @@ -2347,22 +2459,17 @@ public final class WorldServer extends AWorldServer { return false; } - public BlockPos getTopSolidOrLiquidBlock(BlockPos pos) { - ChunkServer chunk = this.getChunk(pos); - int h = chunk.getTopSegment(); - if(h == Integer.MIN_VALUE) - return new BlockPos(pos.getX(), 0, pos.getZ()); - BlockPos blockpos = new BlockPos(pos.getX(), h + 16, pos.getZ()); + public BlockPos getTopSolidOrLiquidBlock(BlockPos pos, int y, int scan) { + scan = y - scan; + Chunk chunk = this.getChunk(pos); + BlockPos blockpos; BlockPos blockpos1; - h = chunk.getBottomSegment(); - if(blockpos.getY() - h > 512) - h = blockpos.getY() - 512; - for(; blockpos.getY() >= h; blockpos = blockpos1) { + for(blockpos = new BlockPos(pos.getX(), y, pos.getZ()); blockpos.getY() >= 0 && blockpos.getY() >= scan; blockpos = blockpos1) { blockpos1 = blockpos.down(); Material material = chunk.getBlock(blockpos1).getMaterial(); - if(material.blocksMovement() && material != Material.LEAVES) { + if(material.blocksMovement() && material != Material.leaves) { break; } } @@ -2370,6 +2477,10 @@ public final class WorldServer extends AWorldServer { return blockpos; } + public BlockPos getTopSolidOrLiquidBlock(BlockPos pos) { + return this.getTopSolidOrLiquidBlock(pos, 256, 256); + } + public void removePlayerEntityDangerously(Entity entityIn) { entityIn.setDead(); @@ -2403,7 +2514,7 @@ public final class WorldServer extends AWorldServer { } private File getSaveFile(String id) { - return new File(this.chunkDir, id.toLowerCase() + ".cdt"); + return new File(this.chunkDir, id.toLowerCase() + ".nbt"); } private WorldSavedData loadData(String id) { @@ -2413,7 +2524,16 @@ public final class WorldServer extends AWorldServer { try { File file = this.getSaveFile(id); if(file.exists()) { - data = new WorldSavedData(id, TagObject.readGZip(file)); +// try { + data = new WorldSavedData(id, NBTLoader.readGZip(file)); +// } +// catch(Exception re) { +// throw new RuntimeException("Konnte " + clazz.toString() + " nicht instanzieren", re); +// } +// FileInputStream in = new FileInputStream(file); +// NBTTagCompound tag = ; +// in.close(); +// data.readFromNBT(tag.getCompoundTag("data")); } } catch(Exception e) { @@ -2437,7 +2557,13 @@ public final class WorldServer extends AWorldServer { private void saveData(WorldSavedData data) { try { File file = this.getSaveFile(data.id); - TagObject.writeGZip(data.tag, file); +// NBTTagCompound tag = new NBTTagCompound(); +// data.writeToNBT(tag); +// NBTTagCompound dtag = new NBTTagCompound(); +// dtag.setTag("data", tag); +// FileOutputStream out = new FileOutputStream(file); + NBTLoader.writeGZip(data.tag, file); +// out.close(); } catch(Exception e) { e.printStackTrace(); @@ -2688,46 +2814,31 @@ public final class WorldServer extends AWorldServer { return this.server.getWorld(dimension); } - public void markChunkDirty(BlockPos pos) { - if(this.isBlockLoaded(pos)) - this.getChunk(pos).setModified(true); - } - - private static class EventList extends ArrayList { + private static class EventList extends ArrayList { private EventList() { } } public static class WorldSavedData { public final String id; - public final TagObject tag; + public final NBTTagCompound tag; public boolean dirty; - public WorldSavedData(String id, TagObject tag) { + public WorldSavedData(String id, NBTTagCompound tag) { this.id = id; this.tag = tag; } } - - private static SPacketMultiBlockChange getPacket(int amount, long[] list, ChunkServer chunk) { - ChunkPos pos = new ChunkPos(chunk.xPos, chunk.zPos); - SPacketMultiBlockChange.BlockUpdateData[] changes = new SPacketMultiBlockChange.BlockUpdateData[amount]; - for(int z = 0; z < changes.length; z++) { - changes[z] = new SPacketMultiBlockChange.BlockUpdateData(list[z], chunk.getState(SPacketMultiBlockChange.getPos(pos, list[z]))); - } - return new SPacketMultiBlockChange(pos, changes); - } private class PlayerInstance { private final List watching = Lists.newArrayList(); - private final Set extend = Sets.newHashSet(); - private final long[] changes = new long[64]; private final ChunkPos position; - + private int[] changes = new int[64]; private int updates; + private int sections; private long prevTime; - private boolean biomes; + private boolean resend; public PlayerInstance(int chunkX, int chunkZ) { this.position = new ChunkPos(chunkX, chunkZ); @@ -2736,7 +2847,7 @@ public final class WorldServer extends AWorldServer { public void addPlayer(EntityNPC player) { if(this.watching.contains(player)) { - Log.TICK.warn("Konnte Spieler nicht hinzufügen. #" + player.getId() + " ist bereits in Chunk " + this.position.x + ", " + Log.JNI.warn("Konnte Spieler nicht hinzufügen. #" + player.getId() + " ist bereits in Chunk " + this.position.x + ", " + this.position.z); } else { @@ -2751,19 +2862,18 @@ public final class WorldServer extends AWorldServer { public void removePlayer(EntityNPC player) { if(this.watching.contains(player)) { - ChunkServer chunk = WorldServer.this.getChunk(this.position.x, this.position.z); + Chunk chunk = WorldServer.this.getChunk(this.position.x, this.position.z); if(chunk.isPopulated()) { - player.connection.sendPacket(Player.getPacket(chunk, true, new int[0], !WorldServer.this.dimension.hasNoLight())); + player.connection.sendPacket(new SPacketChunkData(chunk, true, 0)); } this.watching.remove(player); player.connection.getLoadedChunkList().remove(this.position); if(this.watching.isEmpty()) { - long v = (long)this.position.x + 2147483647L | (long)this.position.z + 2147483647L << 32; this.increaseInhabitedTime(chunk); - WorldServer.this.instances.remove(v); + WorldServer.this.instances.remove(this.position); WorldServer.this.instList.remove(this); if(this.updates > 0) { @@ -2783,10 +2893,11 @@ public final class WorldServer extends AWorldServer { if(this.updates == 0) WorldServer.this.toUpdate.add(this); this.updates = 64; - this.biomes = true; + this.sections = 0xffffffff; + this.resend = true; } - private void increaseInhabitedTime(ChunkServer chunk) { + private void increaseInhabitedTime(Chunk chunk) { chunk.setInhabited(chunk.getInhabited() + WorldServer.this.time - this.prevTime); this.prevTime = WorldServer.this.time; } @@ -2796,10 +2907,10 @@ public final class WorldServer extends AWorldServer { WorldServer.this.toUpdate.add(this); } - this.extend.add(y >> 4); + this.sections |= 1 << (y >> 4); if(this.updates < 64) { - long pos = ((long)x & 4294967295L) << 36 | ((long)z & 4294967295L) << 32 | (y & 4294967295L); + int pos = x << 13 | z << 9 | y; for(int i = 0; i < this.updates; ++i) { if(this.changes[i] == pos) { @@ -2824,9 +2935,9 @@ public final class WorldServer extends AWorldServer { public void onUpdate() { if(this.updates != 0) { if(this.updates == 1) { - int x = (int)(this.changes[0] >> 36 & 15L) + this.position.x * 16; - int y = (int)(this.changes[0] & 4294967295L); - int z = (int)(this.changes[0] >> 32 & 15L) + this.position.z * 16; + int x = (this.changes[0] >> 13 & 15) + this.position.x * 16; + int y = this.changes[0] & 511; + int z = (this.changes[0] >> 9 & 15) + this.position.z * 16; BlockPos pos = new BlockPos(x, y, z); this.sendToAllPlayersWatchingChunk(new SPacketBlockChange(WorldServer.this, pos)); @@ -2837,26 +2948,11 @@ public final class WorldServer extends AWorldServer { else if(this.updates == 64) { int x = this.position.x * 16; int z = this.position.z * 16; - int[] extend = null; - if(!this.biomes) { - extend = new int[this.extend.size()]; - int n = 0; - for(Integer i : this.extend) { - extend[n++] = i; - } - } - this.sendToAllPlayersWatchingChunk(Player.getPacket(WorldServer.this.getChunk(this.position.x, this.position.z), - this.biomes, extend, !WorldServer.this.dimension.hasNoLight())); - - if(this.biomes) { - List list = WorldServer.this.getTileEntitiesIn(x, Integer.MIN_VALUE, z, x + 16, Integer.MAX_VALUE, z + 16); + this.sendToAllPlayersWatchingChunk(new SPacketChunkData(WorldServer.this.getChunk(this.position.x, this.position.z), + this.resend, this.sections)); - for(int n = 0; n < list.size(); ++n) { - this.sendTileToAllPlayersWatchingChunk(list.get(n)); - } - } - else { - for(Integer cy : this.extend) { + for(int cy = 0; cy < 32; ++cy) { + if((this.sections & 1 << cy) != 0) { int y = cy << 4; List list = WorldServer.this.getTileEntitiesIn(x, y, z, x + 16, y + 16, z + 16); @@ -2867,13 +2963,13 @@ public final class WorldServer extends AWorldServer { } } else { - this.sendToAllPlayersWatchingChunk(getPacket(this.updates, this.changes, + this.sendToAllPlayersWatchingChunk(new SPacketMultiBlockChange(this.updates, this.changes, WorldServer.this.getChunk(this.position.x, this.position.z))); for(int n = 0; n < this.updates; ++n) { - int x = (int)(this.changes[n] >> 36 & 15L) + this.position.x * 16; - int y = (int)(this.changes[n] & 4294967295L); - int z = (int)(this.changes[n] >> 32 & 15L) + this.position.z * 16; + int x = (this.changes[n] >> 13 & 15) + this.position.x * 16; + int y = this.changes[n] & 511; + int z = (this.changes[n] >> 9 & 15) + this.position.z * 16; BlockPos pos = new BlockPos(x, y, z); if(WorldServer.this.getState(pos).getBlock().hasTileEntity()) { @@ -2883,8 +2979,8 @@ public final class WorldServer extends AWorldServer { } this.updates = 0; - this.extend.clear(); - this.biomes = false; + this.sections = 0; + this.resend = false; } } diff --git a/server/src/main/java/server/worldgen/BiomeGenLayered.java b/server/src/server/worldgen/BiomeGenLayered.java similarity index 94% rename from server/src/main/java/server/worldgen/BiomeGenLayered.java rename to server/src/server/worldgen/BiomeGenLayered.java index 7c03681..0a790ea 100755 --- a/server/src/main/java/server/worldgen/BiomeGenLayered.java +++ b/server/src/server/worldgen/BiomeGenLayered.java @@ -1,12 +1,14 @@ package server.worldgen; import java.util.List; +import java.util.Map; import java.util.Set; import common.biome.Biome; import common.collect.Lists; +import common.collect.Maps; import common.util.BlockPos; -import common.util.LongHashMap; +import common.util.ChunkPos; import server.worldgen.layer.GenLayer; import server.worldgen.layer.GenLayerAddAreas; import server.worldgen.layer.GenLayerAddExtra; @@ -53,7 +55,7 @@ public class BiomeGenLayered implements BiomeGenerator { private final GenLayer genBiomes; private final GenLayer biomeIndexLayer; - private final LongHashMap cacheMap = new LongHashMap(); + private final Map cacheMap = Maps.newHashMap(); private final List cache = Lists.newArrayList(); private long lastCleanupTime; @@ -124,13 +126,13 @@ public class BiomeGenLayered implements BiomeGenerator { { x = x >> 4; z = z >> 4; - long i = LongHashMap.packInt(x, z); // (long)x & 4294967295L | ((long)z & 4294967295L) << 32; - CacheBlock blk = this.cacheMap.getValueByKey(i); + ChunkPos pos = new ChunkPos(x, z); + CacheBlock blk = this.cacheMap.get(pos); if (blk == null) { blk = new CacheBlock(x, z); - this.cacheMap.add(i, blk); + this.cacheMap.put(pos, blk); this.cache.add(blk); } @@ -155,8 +157,7 @@ public class BiomeGenLayered implements BiomeGenerator { if (l > 30000L || l < 0L) { this.cache.remove(k--); - long i1 = LongHashMap.packInt(blk.xPosition, blk.zPosition) ; // (long)biomecache$block.xPosition & 4294967295L | ((long)biomecache$block.zPosition & 4294967295L) << 32; - this.cacheMap.remove(i1); + this.cacheMap.remove(new ChunkPos(blk.xPosition, blk.zPosition)); } } } diff --git a/server/src/main/java/server/worldgen/BiomeGenPerlin.java b/server/src/server/worldgen/BiomeGenPerlin.java similarity index 100% rename from server/src/main/java/server/worldgen/BiomeGenPerlin.java rename to server/src/server/worldgen/BiomeGenPerlin.java diff --git a/server/src/main/java/server/worldgen/BiomeGenSingle.java b/server/src/server/worldgen/BiomeGenSingle.java similarity index 100% rename from server/src/main/java/server/worldgen/BiomeGenSingle.java rename to server/src/server/worldgen/BiomeGenSingle.java diff --git a/server/src/main/java/server/worldgen/BiomeGenerator.java b/server/src/server/worldgen/BiomeGenerator.java similarity index 100% rename from server/src/main/java/server/worldgen/BiomeGenerator.java rename to server/src/server/worldgen/BiomeGenerator.java diff --git a/server/src/main/java/server/worldgen/BlockReplacer.java b/server/src/server/worldgen/BlockReplacer.java similarity index 100% rename from server/src/main/java/server/worldgen/BlockReplacer.java rename to server/src/server/worldgen/BlockReplacer.java diff --git a/server/src/main/java/server/worldgen/ChunkGenerator.java b/server/src/server/worldgen/ChunkGenerator.java similarity index 100% rename from server/src/main/java/server/worldgen/ChunkGenerator.java rename to server/src/server/worldgen/ChunkGenerator.java diff --git a/server/src/main/java/server/worldgen/ChunkPrimer.java b/server/src/server/worldgen/ChunkPrimer.java similarity index 100% rename from server/src/main/java/server/worldgen/ChunkPrimer.java rename to server/src/server/worldgen/ChunkPrimer.java diff --git a/server/src/main/java/server/worldgen/FeatureDungeons.java b/server/src/server/worldgen/FeatureDungeons.java similarity index 80% rename from server/src/main/java/server/worldgen/FeatureDungeons.java rename to server/src/server/worldgen/FeatureDungeons.java index 719f09b..816c0d8 100755 --- a/server/src/main/java/server/worldgen/FeatureDungeons.java +++ b/server/src/server/worldgen/FeatureDungeons.java @@ -1,28 +1,22 @@ package server.worldgen; -import java.lang.reflect.InvocationTargetException; - -import common.block.Material; -import common.entity.npc.EntityArachnoid; -import common.entity.npc.EntityUndead; -import common.entity.npc.EntityZombie; -import common.entity.types.EntityLiving; import common.init.Blocks; import common.init.Items; import common.item.RngLoot; +import common.log.Log; +import common.material.Material; import common.rng.Random; import common.rng.WeightedList; import common.tileentity.TileEntity; import common.tileentity.TileEntityChest; +import common.tileentity.TileEntityMobSpawner; import common.util.BlockPos; import common.util.Facing; -import common.world.World; -import server.vars.SVars; import server.world.WorldServer; public class FeatureDungeons { - private static final Class[] MOB_TYPES = new Class[] {EntityUndead.class, EntityZombie.class, EntityZombie.class, EntityArachnoid.class}; + private static final String[] SPAWNERTYPES = new String[] {"Undead", "Zombie", "Zombie", "Arachnoid"}; private final int chance; @@ -154,15 +148,16 @@ public class FeatureDungeons } } - if(SVars.mobs && SVars.spawnDungeonMobs > 0) { - for(int z = 0; z < SVars.spawnDungeonMobs; z++) { - EntityLiving entity = this.pickMobSpawner(rand, worldIn); - entity.setLocationAndAngles((double)position.getX() + rand.doublev(), (double)position.getY(), (double)position.getZ() + rand.doublev(), worldIn.rand.floatv() * 360.0F, 0.0F); - entity.onInitialSpawn(null); - worldIn.spawnEntityInWorld(entity); - if(rand.chance(5)) - break; - } + worldIn.setState(position, Blocks.mob_spawner.getState(), 2); + TileEntity tileentity = worldIn.getTileEntity(position); + + if (tileentity instanceof TileEntityMobSpawner) + { + ((TileEntityMobSpawner)tileentity).setEntityName(this.pickMobSpawner(rand)); + } + else + { + Log.JNI.warn("Konnte kein Mob-Spawner-Objekt bei (" + position.getX() + ", " + position.getY() + ", " + position.getZ() + ") erstellen"); } return true; @@ -173,13 +168,11 @@ public class FeatureDungeons } } - private EntityLiving pickMobSpawner(Random rand, WorldServer world) + /** + * Randomly decides which spawner to use in a dungeon + */ + private String pickMobSpawner(Random p_76543_1_) { - try { - return rand.pick(MOB_TYPES).getConstructor(World.class).newInstance(world); - } - catch(InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new RuntimeException(e); - } + return SPAWNERTYPES[p_76543_1_.zrange(SPAWNERTYPES.length)]; } } diff --git a/server/src/main/java/server/worldgen/FeatureGenerator.java b/server/src/server/worldgen/FeatureGenerator.java similarity index 100% rename from server/src/main/java/server/worldgen/FeatureGenerator.java rename to server/src/server/worldgen/FeatureGenerator.java diff --git a/server/src/main/java/server/worldgen/FeatureLakes.java b/server/src/server/worldgen/FeatureLakes.java similarity index 97% rename from server/src/main/java/server/worldgen/FeatureLakes.java rename to server/src/server/worldgen/FeatureLakes.java index 2f6fa82..1f4e2c1 100755 --- a/server/src/main/java/server/worldgen/FeatureLakes.java +++ b/server/src/server/worldgen/FeatureLakes.java @@ -1,11 +1,10 @@ package server.worldgen; import common.block.Block; -import common.block.Material; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; -import common.world.LightType; import common.world.State; import server.biome.GenBiome; import server.world.WorldServer; @@ -161,7 +160,7 @@ public class FeatureLakes { BlockPos blockpos = position.add(i2, j4 - 1, j3); - if (worldIn.getState(blockpos).getBlock() == replace && worldIn.getLightFor(LightType.SKY, position.add(i2, j4, j3)) > 0) + if (worldIn.getState(blockpos).getBlock() == replace && worldIn.isAirBlock(position.add(i2, j4, j3))) { GenBiome biomegenbase = GenBiome.BIOMES[worldIn.getBiomeGenForCoords(blockpos).id]; @@ -199,7 +198,7 @@ public class FeatureLakes } } - if (this.block.getMaterial() == Material.WATER) + if (this.block.getMaterial() == Material.water) { for (int k2 = 0; k2 < 16; ++k2) { diff --git a/server/src/main/java/server/worldgen/FeatureLiquids.java b/server/src/server/worldgen/FeatureLiquids.java similarity index 95% rename from server/src/main/java/server/worldgen/FeatureLiquids.java rename to server/src/server/worldgen/FeatureLiquids.java index 69f5871..ff0a1e8 100755 --- a/server/src/main/java/server/worldgen/FeatureLiquids.java +++ b/server/src/server/worldgen/FeatureLiquids.java @@ -1,7 +1,7 @@ package server.worldgen; import common.block.Block; -import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.world.State; @@ -66,7 +66,7 @@ public class FeatureLiquids { return false; } - else if (worldIn.getState(position).getBlock() != Blocks.air && worldIn.getState(position).getBlock() != replace) + else if (worldIn.getState(position).getBlock().getMaterial() != Material.air && worldIn.getState(position).getBlock() != replace) { return false; } diff --git a/server/src/main/java/server/worldgen/FeatureOres.java b/server/src/server/worldgen/FeatureOres.java similarity index 91% rename from server/src/main/java/server/worldgen/FeatureOres.java rename to server/src/server/worldgen/FeatureOres.java index bd61fc6..abac8a1 100755 --- a/server/src/main/java/server/worldgen/FeatureOres.java +++ b/server/src/server/worldgen/FeatureOres.java @@ -5,7 +5,6 @@ import common.rng.Random; import common.util.BlockPos; import common.util.ExtMath; import common.world.State; -import common.world.World; import server.world.WorldServer; public class FeatureOres @@ -42,18 +41,18 @@ public class FeatureOres this.oreBlock = state; this.distributed = dist; if(this.distributed) { - min = min < -World.MAX_SIZE_Y ? -World.MAX_SIZE_Y : (min > World.MAX_SIZE_Y - 1 ? World.MAX_SIZE_Y - 1 : min); - max = max < -World.MAX_SIZE_Y ? -World.MAX_SIZE_Y : (max > World.MAX_SIZE_Y ? World.MAX_SIZE_Y : max); - if(min + max > World.MAX_SIZE_Y - 1) { - max = World.MAX_SIZE_Y - min; + min = min < 0 ? 0 : (min > 511 ? 511 : min); + max = max < 0 ? 0 : (max > 512 ? 512 : max); + if(min + max > 511) { + max = 512 - min; } if(min - max < 0) { max = min; } } else { - min = min < -World.MAX_SIZE_Y ? -World.MAX_SIZE_Y : (min > World.MAX_SIZE_Y ? World.MAX_SIZE_Y : min); - max = max < -World.MAX_SIZE_Y ? -World.MAX_SIZE_Y : (max > World.MAX_SIZE_Y ? World.MAX_SIZE_Y : max); + min = min < 0 ? 0 : (min > 512 ? 512 : min); + max = max < 0 ? 0 : (max > 512 ? 512 : max); if (max < min) { int i = min; @@ -62,7 +61,7 @@ public class FeatureOres } else if (max == min) { - if (min < World.MAX_SIZE_Y - 1) + if (min < 511) { ++max; } diff --git a/server/src/main/java/server/worldgen/GeneratorCavern.java b/server/src/server/worldgen/GeneratorCavern.java similarity index 100% rename from server/src/main/java/server/worldgen/GeneratorCavern.java rename to server/src/server/worldgen/GeneratorCavern.java diff --git a/server/src/server/worldgen/GeneratorDebug.java b/server/src/server/worldgen/GeneratorDebug.java new file mode 100755 index 0000000..d1eb549 --- /dev/null +++ b/server/src/server/worldgen/GeneratorDebug.java @@ -0,0 +1,27 @@ +package server.worldgen; + +import common.world.State; +import common.worldgen.DebugStates; +import server.world.WorldServer; + +public class GeneratorDebug implements ChunkGenerator +{ + public int getMaximumHeight() { + return 72; + } + + public void generateChunk(WorldServer world, int x, int z, ChunkPrimer primer) + { + for(int bx = 0; bx < 16; ++bx) { + for(int bz = 0; bz < 16; ++bz) { + int sx = x * 16 + bx; + int sz = z * 16 + bz; +// primer.set(bx, 60, bz, Blocks.glass.getDefaultState()); + State state = DebugStates.getState(sx, sz); + if(state != null) { + primer.set(bx, 1, bz, state); + } + } + } + } +} diff --git a/server/src/main/java/server/worldgen/GeneratorDestroyed.java b/server/src/server/worldgen/GeneratorDestroyed.java similarity index 100% rename from server/src/main/java/server/worldgen/GeneratorDestroyed.java rename to server/src/server/worldgen/GeneratorDestroyed.java diff --git a/server/src/main/java/server/worldgen/GeneratorFlat.java b/server/src/server/worldgen/GeneratorFlat.java similarity index 100% rename from server/src/main/java/server/worldgen/GeneratorFlat.java rename to server/src/server/worldgen/GeneratorFlat.java diff --git a/server/src/main/java/server/worldgen/GeneratorIsland.java b/server/src/server/worldgen/GeneratorIsland.java similarity index 100% rename from server/src/main/java/server/worldgen/GeneratorIsland.java rename to server/src/server/worldgen/GeneratorIsland.java diff --git a/server/src/main/java/server/worldgen/GeneratorPerlin.java b/server/src/server/worldgen/GeneratorPerlin.java similarity index 100% rename from server/src/main/java/server/worldgen/GeneratorPerlin.java rename to server/src/server/worldgen/GeneratorPerlin.java diff --git a/server/src/main/java/server/worldgen/GeneratorSimple.java b/server/src/server/worldgen/GeneratorSimple.java similarity index 100% rename from server/src/main/java/server/worldgen/GeneratorSimple.java rename to server/src/server/worldgen/GeneratorSimple.java diff --git a/server/src/main/java/server/worldgen/LootConstants.java b/server/src/server/worldgen/LootConstants.java similarity index 100% rename from server/src/main/java/server/worldgen/LootConstants.java rename to server/src/server/worldgen/LootConstants.java diff --git a/server/src/main/java/server/worldgen/MobConstants.java b/server/src/server/worldgen/MobConstants.java similarity index 100% rename from server/src/main/java/server/worldgen/MobConstants.java rename to server/src/server/worldgen/MobConstants.java diff --git a/server/src/main/java/server/worldgen/ReplacerAltBiome.java b/server/src/server/worldgen/ReplacerAltBiome.java similarity index 100% rename from server/src/main/java/server/worldgen/ReplacerAltBiome.java rename to server/src/server/worldgen/ReplacerAltBiome.java diff --git a/server/src/main/java/server/worldgen/ReplacerAltSurface.java b/server/src/server/worldgen/ReplacerAltSurface.java similarity index 95% rename from server/src/main/java/server/worldgen/ReplacerAltSurface.java rename to server/src/server/worldgen/ReplacerAltSurface.java index e3daac1..23043ac 100755 --- a/server/src/main/java/server/worldgen/ReplacerAltSurface.java +++ b/server/src/server/worldgen/ReplacerAltSurface.java @@ -2,7 +2,7 @@ package server.worldgen; import common.biome.Biome; import common.block.Block; -import common.init.Blocks; +import common.material.Material; import common.rng.OctaveGen; import common.rng.Random; import common.world.State; @@ -63,7 +63,7 @@ public class ReplacerAltSurface implements BlockReplacer // { State iblockstate2 = primer.get(k, j1, j); - if (iblockstate2.getBlock() != Blocks.air) + if (iblockstate2.getBlock() != null && iblockstate2.getBlock().getMaterial() != Material.air) { if (iblockstate2.getBlock() == this.fillerBlock) { @@ -92,7 +92,7 @@ public class ReplacerAltSurface implements BlockReplacer } } - if (j1 < i && (iblockstate == null || iblockstate.getBlock() == Blocks.air)) + if (j1 < i && (iblockstate == null || iblockstate.getBlock().getMaterial() == Material.air)) { iblockstate = this.liquid; } diff --git a/server/src/main/java/server/worldgen/ReplacerBiome.java b/server/src/server/worldgen/ReplacerBiome.java similarity index 100% rename from server/src/main/java/server/worldgen/ReplacerBiome.java rename to server/src/server/worldgen/ReplacerBiome.java diff --git a/server/src/main/java/server/worldgen/ReplacerTopLayer.java b/server/src/server/worldgen/ReplacerTopLayer.java similarity index 95% rename from server/src/main/java/server/worldgen/ReplacerTopLayer.java rename to server/src/server/worldgen/ReplacerTopLayer.java index 5f2a52c..8514527 100755 --- a/server/src/main/java/server/worldgen/ReplacerTopLayer.java +++ b/server/src/server/worldgen/ReplacerTopLayer.java @@ -3,6 +3,7 @@ package server.worldgen; import common.biome.Biome; import common.block.Block; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.world.State; import server.world.WorldServer; @@ -36,7 +37,7 @@ public class ReplacerTopLayer implements BlockReplacer { State iblockstate2 = primer.get(i, i1, j); - if (iblockstate2.getBlock() == Blocks.air) + if (iblockstate2.getBlock().getMaterial() == Material.air) { l = -1; } diff --git a/server/src/main/java/server/worldgen/caves/MapGenBase.java b/server/src/server/worldgen/caves/MapGenBase.java similarity index 100% rename from server/src/main/java/server/worldgen/caves/MapGenBase.java rename to server/src/server/worldgen/caves/MapGenBase.java diff --git a/server/src/main/java/server/worldgen/caves/MapGenBigCaves.java b/server/src/server/worldgen/caves/MapGenBigCaves.java similarity index 100% rename from server/src/main/java/server/worldgen/caves/MapGenBigCaves.java rename to server/src/server/worldgen/caves/MapGenBigCaves.java diff --git a/server/src/main/java/server/worldgen/caves/MapGenCaves.java b/server/src/server/worldgen/caves/MapGenCaves.java similarity index 99% rename from server/src/main/java/server/worldgen/caves/MapGenCaves.java rename to server/src/server/worldgen/caves/MapGenCaves.java index c3c67d4..18346a0 100755 --- a/server/src/main/java/server/worldgen/caves/MapGenCaves.java +++ b/server/src/server/worldgen/caves/MapGenCaves.java @@ -2,7 +2,7 @@ package server.worldgen.caves; import common.block.Block; import common.block.BlockColored; -import common.block.natural.BlockSand; +import common.block.BlockSand; import common.color.DyeColor; import common.init.Blocks; import common.rng.Random; diff --git a/server/src/main/java/server/worldgen/caves/MapGenRavine.java b/server/src/server/worldgen/caves/MapGenRavine.java similarity index 100% rename from server/src/main/java/server/worldgen/caves/MapGenRavine.java rename to server/src/server/worldgen/caves/MapGenRavine.java diff --git a/server/src/main/java/server/worldgen/feature/WorldGenAbandonedChest.java b/server/src/server/worldgen/feature/WorldGenAbandonedChest.java similarity index 90% rename from server/src/main/java/server/worldgen/feature/WorldGenAbandonedChest.java rename to server/src/server/worldgen/feature/WorldGenAbandonedChest.java index 7e12f6b..88b69b0 100755 --- a/server/src/main/java/server/worldgen/feature/WorldGenAbandonedChest.java +++ b/server/src/server/worldgen/feature/WorldGenAbandonedChest.java @@ -1,9 +1,9 @@ package server.worldgen.feature; import common.block.Block; -import common.block.Material; import common.init.Blocks; import common.item.RngLoot; +import common.material.Material; import common.rng.Random; import common.rng.WeightedList; import common.tileentity.TileEntity; @@ -33,7 +33,7 @@ public class WorldGenAbandonedChest extends FeatureGenerator public boolean generate(WorldServer worldIn, Random rand, BlockPos position) { Block block; - while (((block = worldIn.getState(position).getBlock()) == Blocks.air || block.getMaterial() == Material.LEAVES) && position.getY() > 1) + while (((block = worldIn.getState(position).getBlock()).getMaterial() == Material.air || block.getMaterial() == Material.leaves) && position.getY() > 1) { position = position.down(); } diff --git a/server/src/main/java/server/worldgen/feature/WorldGenAsteroid.java b/server/src/server/worldgen/feature/WorldGenAsteroid.java similarity index 100% rename from server/src/main/java/server/worldgen/feature/WorldGenAsteroid.java rename to server/src/server/worldgen/feature/WorldGenAsteroid.java diff --git a/server/src/main/java/server/worldgen/feature/WorldGenBlockBlob.java b/server/src/server/worldgen/feature/WorldGenBlockBlob.java similarity index 100% rename from server/src/main/java/server/worldgen/feature/WorldGenBlockBlob.java rename to server/src/server/worldgen/feature/WorldGenBlockBlob.java diff --git a/server/src/main/java/server/worldgen/feature/WorldGenClay.java b/server/src/server/worldgen/feature/WorldGenClay.java similarity index 100% rename from server/src/main/java/server/worldgen/feature/WorldGenClay.java rename to server/src/server/worldgen/feature/WorldGenClay.java diff --git a/server/src/main/java/server/worldgen/feature/WorldGenClayExt.java b/server/src/server/worldgen/feature/WorldGenClayExt.java similarity index 100% rename from server/src/main/java/server/worldgen/feature/WorldGenClayExt.java rename to server/src/server/worldgen/feature/WorldGenClayExt.java diff --git a/server/src/main/java/server/worldgen/feature/WorldGenDesertWells.java b/server/src/server/worldgen/feature/WorldGenDesertWells.java similarity index 90% rename from server/src/main/java/server/worldgen/feature/WorldGenDesertWells.java rename to server/src/server/worldgen/feature/WorldGenDesertWells.java index 90b0636..f54c1e0 100755 --- a/server/src/main/java/server/worldgen/feature/WorldGenDesertWells.java +++ b/server/src/server/worldgen/feature/WorldGenDesertWells.java @@ -1,17 +1,20 @@ package server.worldgen.feature; -import common.block.artificial.BlockSlab; -import common.block.natural.BlockSand; +import common.block.BlockSand; +import common.block.BlockSlab; import common.init.Blocks; +import common.pattern.BlockStateHelper; import common.rng.Random; import common.util.BlockPos; import common.util.Facing; +import common.util.Predicates; import common.world.State; import server.world.WorldServer; import server.worldgen.FeatureGenerator; public class WorldGenDesertWells extends FeatureGenerator { + private static final BlockStateHelper field_175913_a = BlockStateHelper.forBlock(Blocks.sand).where(BlockSand.VARIANT, Predicates.equalTo(BlockSand.EnumType.SAND)); private final State field_175911_b = Blocks.sandstone_slab.getState().withProperty(BlockSlab.FACING, Facing.DOWN); private final State field_175912_c = Blocks.sandstone.getState(); private final State field_175910_d = Blocks.flowing_water.getState(); @@ -23,8 +26,7 @@ public class WorldGenDesertWells extends FeatureGenerator position = position.down(); } - State state = worldIn.getState(position); - if (state.getBlock() != Blocks.sand || state.getValue(BlockSand.VARIANT) != BlockSand.EnumType.SAND) + if (!field_175913_a.test(worldIn.getState(position))) { return false; } diff --git a/server/src/main/java/server/worldgen/feature/WorldGenFire.java b/server/src/server/worldgen/feature/WorldGenFire.java similarity index 100% rename from server/src/main/java/server/worldgen/feature/WorldGenFire.java rename to server/src/server/worldgen/feature/WorldGenFire.java diff --git a/server/src/main/java/server/worldgen/feature/WorldGenGlowStone.java b/server/src/server/worldgen/feature/WorldGenGlowStone.java similarity index 92% rename from server/src/main/java/server/worldgen/feature/WorldGenGlowStone.java rename to server/src/server/worldgen/feature/WorldGenGlowStone.java index 951ece1..9e99c29 100755 --- a/server/src/main/java/server/worldgen/feature/WorldGenGlowStone.java +++ b/server/src/server/worldgen/feature/WorldGenGlowStone.java @@ -1,6 +1,7 @@ package server.worldgen.feature; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.util.Facing; @@ -27,7 +28,7 @@ public class WorldGenGlowStone extends FeatureGenerator { BlockPos blockpos = position.add(rand.zrange(8) - rand.zrange(8), -rand.zrange(12), rand.zrange(8) - rand.zrange(8)); - if (worldIn.getState(blockpos).getBlock() == Blocks.air) + if (worldIn.getState(blockpos).getBlock().getMaterial() == Material.air) { int j = 0; diff --git a/server/src/main/java/server/worldgen/feature/WorldGenHellLava.java b/server/src/server/worldgen/feature/WorldGenHellLava.java similarity index 92% rename from server/src/main/java/server/worldgen/feature/WorldGenHellLava.java rename to server/src/server/worldgen/feature/WorldGenHellLava.java index 4d536bf..9932d74 100755 --- a/server/src/main/java/server/worldgen/feature/WorldGenHellLava.java +++ b/server/src/server/worldgen/feature/WorldGenHellLava.java @@ -2,6 +2,7 @@ package server.worldgen.feature; import common.block.Block; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import server.world.WorldServer; @@ -24,7 +25,7 @@ public class WorldGenHellLava extends FeatureGenerator { return false; } - else if (worldIn.getState(position).getBlock() != Blocks.air && worldIn.getState(position).getBlock() != Blocks.hellrock) + else if (worldIn.getState(position).getBlock().getMaterial() != Material.air && worldIn.getState(position).getBlock() != Blocks.hellrock) { return false; } diff --git a/server/src/main/java/server/worldgen/feature/WorldGenIcePath.java b/server/src/server/worldgen/feature/WorldGenIcePath.java similarity index 100% rename from server/src/main/java/server/worldgen/feature/WorldGenIcePath.java rename to server/src/server/worldgen/feature/WorldGenIcePath.java diff --git a/server/src/main/java/server/worldgen/feature/WorldGenIceSpike.java b/server/src/server/worldgen/feature/WorldGenIceSpike.java similarity index 88% rename from server/src/main/java/server/worldgen/feature/WorldGenIceSpike.java rename to server/src/server/worldgen/feature/WorldGenIceSpike.java index 97d8efd..886d3d9 100755 --- a/server/src/main/java/server/worldgen/feature/WorldGenIceSpike.java +++ b/server/src/server/worldgen/feature/WorldGenIceSpike.java @@ -2,6 +2,7 @@ package server.worldgen.feature; import common.block.Block; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.util.ExtMath; @@ -49,7 +50,7 @@ public class WorldGenIceSpike extends FeatureGenerator { Block block = worldIn.getState(position.add(i1, k, j1)).getBlock(); - if (block == Blocks.air || block == Blocks.dirt || block == Blocks.snow || block == Blocks.ice) + if (block.getMaterial() == Material.air || block == Blocks.dirt || block == Blocks.snow || block == Blocks.ice) { this.setBlockAndNotifyAdequately(worldIn, position.add(i1, k, j1), Blocks.packed_ice.getState()); } @@ -58,7 +59,7 @@ public class WorldGenIceSpike extends FeatureGenerator { block = worldIn.getState(position.add(i1, -k, j1)).getBlock(); - if (block == Blocks.air || block == Blocks.dirt || block == Blocks.snow || block == Blocks.ice) + if (block.getMaterial() == Material.air || block == Blocks.dirt || block == Blocks.snow || block == Blocks.ice) { this.setBlockAndNotifyAdequately(worldIn, position.add(i1, -k, j1), Blocks.packed_ice.getState()); } @@ -95,7 +96,7 @@ public class WorldGenIceSpike extends FeatureGenerator { Block block1 = worldIn.getState(blockpos).getBlock(); - if (block1 != Blocks.air && block1 != Blocks.dirt && block1 != Blocks.snow && block1 != Blocks.ice && block1 != Blocks.packed_ice) + if (block1.getMaterial() != Material.air && block1 != Blocks.dirt && block1 != Blocks.snow && block1 != Blocks.ice && block1 != Blocks.packed_ice) { break; } diff --git a/server/src/main/java/server/worldgen/feature/WorldGenSand.java b/server/src/server/worldgen/feature/WorldGenSand.java similarity index 100% rename from server/src/main/java/server/worldgen/feature/WorldGenSand.java rename to server/src/server/worldgen/feature/WorldGenSand.java diff --git a/server/src/main/java/server/worldgen/feature/WorldGenSpikes.java b/server/src/server/worldgen/feature/WorldGenSpikes.java similarity index 100% rename from server/src/main/java/server/worldgen/feature/WorldGenSpikes.java rename to server/src/server/worldgen/feature/WorldGenSpikes.java diff --git a/server/src/main/java/server/worldgen/foliage/FeatureDoublePlant.java b/server/src/server/worldgen/foliage/FeatureDoublePlant.java similarity index 95% rename from server/src/main/java/server/worldgen/foliage/FeatureDoublePlant.java rename to server/src/server/worldgen/foliage/FeatureDoublePlant.java index 548e584..8237227 100755 --- a/server/src/main/java/server/worldgen/foliage/FeatureDoublePlant.java +++ b/server/src/server/worldgen/foliage/FeatureDoublePlant.java @@ -1,6 +1,6 @@ package server.worldgen.foliage; -import common.block.foliage.BlockDoublePlant; +import common.block.BlockDoublePlant; import common.init.Blocks; import common.rng.Random; import common.util.BlockPos; diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenBigMushroom.java b/server/src/server/worldgen/foliage/WorldGenBigMushroom.java similarity index 97% rename from server/src/main/java/server/worldgen/foliage/WorldGenBigMushroom.java rename to server/src/server/worldgen/foliage/WorldGenBigMushroom.java index 15c3723..b1bf20f 100755 --- a/server/src/main/java/server/worldgen/foliage/WorldGenBigMushroom.java +++ b/server/src/server/worldgen/foliage/WorldGenBigMushroom.java @@ -1,9 +1,9 @@ package server.worldgen.foliage; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockHugeMushroom; +import common.block.BlockHugeMushroom; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import server.world.WorldServer; @@ -56,7 +56,7 @@ public class WorldGenBigMushroom extends FeatureGenerator { Block block = worldIn.getState(blockpos$mutableblockpos.set(l, j, i1)).getBlock(); - if (block != Blocks.air && block.getMaterial() != Material.LEAVES) + if (block.getMaterial() != Material.air && block.getMaterial() != Material.leaves) { flag = false; } diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenCactus.java b/server/src/server/worldgen/foliage/WorldGenCactus.java similarity index 100% rename from server/src/main/java/server/worldgen/foliage/WorldGenCactus.java rename to server/src/server/worldgen/foliage/WorldGenCactus.java diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenDeadBush.java b/server/src/server/worldgen/foliage/WorldGenDeadBush.java similarity index 82% rename from server/src/main/java/server/worldgen/foliage/WorldGenDeadBush.java rename to server/src/server/worldgen/foliage/WorldGenDeadBush.java index ae5c9f7..05f2ba8 100755 --- a/server/src/main/java/server/worldgen/foliage/WorldGenDeadBush.java +++ b/server/src/server/worldgen/foliage/WorldGenDeadBush.java @@ -1,8 +1,8 @@ package server.worldgen.foliage; import common.block.Block; -import common.block.Material; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import server.world.WorldServer; @@ -14,7 +14,7 @@ public class WorldGenDeadBush extends FeatureGenerator { Block block; - while (((block = worldIn.getState(position).getBlock()) == Blocks.air || block.getMaterial() == Material.LEAVES) && position.getY() > 0) + while (((block = worldIn.getState(position).getBlock()).getMaterial() == Material.air || block.getMaterial() == Material.leaves) && position.getY() > 0) { position = position.down(); } diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenFlowers.java b/server/src/server/worldgen/foliage/WorldGenFlowers.java similarity index 97% rename from server/src/main/java/server/worldgen/foliage/WorldGenFlowers.java rename to server/src/server/worldgen/foliage/WorldGenFlowers.java index 4bc978c..add8180 100755 --- a/server/src/main/java/server/worldgen/foliage/WorldGenFlowers.java +++ b/server/src/server/worldgen/foliage/WorldGenFlowers.java @@ -1,6 +1,6 @@ package server.worldgen.foliage; -import common.block.foliage.BlockFlower; +import common.block.BlockFlower; import common.rng.Random; import common.util.BlockPos; import common.world.State; diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenMelon.java b/server/src/server/worldgen/foliage/WorldGenMelon.java similarity index 100% rename from server/src/main/java/server/worldgen/foliage/WorldGenMelon.java rename to server/src/server/worldgen/foliage/WorldGenMelon.java diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenMushroom.java b/server/src/server/worldgen/foliage/WorldGenMushroom.java similarity index 96% rename from server/src/main/java/server/worldgen/foliage/WorldGenMushroom.java rename to server/src/server/worldgen/foliage/WorldGenMushroom.java index 07b999b..740b3ae 100755 --- a/server/src/main/java/server/worldgen/foliage/WorldGenMushroom.java +++ b/server/src/server/worldgen/foliage/WorldGenMushroom.java @@ -1,6 +1,6 @@ package server.worldgen.foliage; -import common.block.foliage.BlockBush; +import common.block.BlockBush; import common.rng.Random; import common.util.BlockPos; import server.world.WorldServer; diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenPumpkin.java b/server/src/server/worldgen/foliage/WorldGenPumpkin.java similarity index 95% rename from server/src/main/java/server/worldgen/foliage/WorldGenPumpkin.java rename to server/src/server/worldgen/foliage/WorldGenPumpkin.java index 1aa47b3..457db07 100755 --- a/server/src/main/java/server/worldgen/foliage/WorldGenPumpkin.java +++ b/server/src/server/worldgen/foliage/WorldGenPumpkin.java @@ -1,6 +1,6 @@ package server.worldgen.foliage; -import common.block.foliage.BlockPumpkin; +import common.block.BlockPumpkin; import common.init.Blocks; import common.rng.Random; import common.util.BlockPos; diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenReed.java b/server/src/server/worldgen/foliage/WorldGenReed.java similarity index 78% rename from server/src/main/java/server/worldgen/foliage/WorldGenReed.java rename to server/src/server/worldgen/foliage/WorldGenReed.java index 45be4d9..459216e 100755 --- a/server/src/main/java/server/worldgen/foliage/WorldGenReed.java +++ b/server/src/server/worldgen/foliage/WorldGenReed.java @@ -1,7 +1,7 @@ package server.worldgen.foliage; -import common.block.Material; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import server.world.WorldServer; @@ -19,7 +19,7 @@ public class WorldGenReed extends FeatureGenerator { BlockPos blockpos1 = blockpos.down(); - if (worldIn.getState(blockpos1.west()).getBlock().getMaterial() == Material.WATER || worldIn.getState(blockpos1.east()).getBlock().getMaterial() == Material.WATER || worldIn.getState(blockpos1.north()).getBlock().getMaterial() == Material.WATER || worldIn.getState(blockpos1.south()).getBlock().getMaterial() == Material.WATER) + if (worldIn.getState(blockpos1.west()).getBlock().getMaterial() == Material.water || worldIn.getState(blockpos1.east()).getBlock().getMaterial() == Material.water || worldIn.getState(blockpos1.north()).getBlock().getMaterial() == Material.water || worldIn.getState(blockpos1.south()).getBlock().getMaterial() == Material.water) { int j = 2 + rand.zrange(rand.zrange(3) + 1); diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenShrub.java b/server/src/server/worldgen/foliage/WorldGenShrub.java similarity index 90% rename from server/src/main/java/server/worldgen/foliage/WorldGenShrub.java rename to server/src/server/worldgen/foliage/WorldGenShrub.java index 65d9376..410b5c9 100755 --- a/server/src/main/java/server/worldgen/foliage/WorldGenShrub.java +++ b/server/src/server/worldgen/foliage/WorldGenShrub.java @@ -1,9 +1,9 @@ package server.worldgen.foliage; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockLeaves; +import common.block.BlockLeaves; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.world.State; @@ -26,7 +26,7 @@ public class WorldGenShrub extends WorldGenBaseTree { Block block; - while (((block = worldIn.getState(position).getBlock()) == Blocks.air || block.getMaterial() == Material.LEAVES) && position.getY() > 0) + while (((block = worldIn.getState(position).getBlock()).getMaterial() == Material.air || block.getMaterial() == Material.leaves) && position.getY() > 0) { position = position.down(); } diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenTallGrass.java b/server/src/server/worldgen/foliage/WorldGenTallGrass.java similarity index 83% rename from server/src/main/java/server/worldgen/foliage/WorldGenTallGrass.java rename to server/src/server/worldgen/foliage/WorldGenTallGrass.java index 81a1d75..804a853 100755 --- a/server/src/main/java/server/worldgen/foliage/WorldGenTallGrass.java +++ b/server/src/server/worldgen/foliage/WorldGenTallGrass.java @@ -1,9 +1,9 @@ package server.worldgen.foliage; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockTallGrass; +import common.block.BlockTallGrass; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.world.State; @@ -23,7 +23,7 @@ public class WorldGenTallGrass extends FeatureGenerator { Block block; - while (((block = worldIn.getState(position).getBlock()) == Blocks.air || block.getMaterial() == Material.LEAVES) && position.getY() > 0) + while (((block = worldIn.getState(position).getBlock()).getMaterial() == Material.air || block.getMaterial() == Material.leaves) && position.getY() > 0) { position = position.down(); } diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenVines.java b/server/src/server/worldgen/foliage/WorldGenVines.java similarity index 97% rename from server/src/main/java/server/worldgen/foliage/WorldGenVines.java rename to server/src/server/worldgen/foliage/WorldGenVines.java index 86fd327..ff9f427 100755 --- a/server/src/main/java/server/worldgen/foliage/WorldGenVines.java +++ b/server/src/server/worldgen/foliage/WorldGenVines.java @@ -1,6 +1,6 @@ package server.worldgen.foliage; -import common.block.foliage.BlockVine; +import common.block.BlockVine; import common.init.Blocks; import common.rng.Random; import common.util.BlockPos; diff --git a/server/src/main/java/server/worldgen/foliage/WorldGenWaterlily.java b/server/src/server/worldgen/foliage/WorldGenWaterlily.java similarity index 100% rename from server/src/main/java/server/worldgen/foliage/WorldGenWaterlily.java rename to server/src/server/worldgen/foliage/WorldGenWaterlily.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayer.java b/server/src/server/worldgen/layer/GenLayer.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayer.java rename to server/src/server/worldgen/layer/GenLayer.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerAddAreas.java b/server/src/server/worldgen/layer/GenLayerAddAreas.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerAddAreas.java rename to server/src/server/worldgen/layer/GenLayerAddAreas.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerAddExtra.java b/server/src/server/worldgen/layer/GenLayerAddExtra.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerAddExtra.java rename to server/src/server/worldgen/layer/GenLayerAddExtra.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerAddSea.java b/server/src/server/worldgen/layer/GenLayerAddSea.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerAddSea.java rename to server/src/server/worldgen/layer/GenLayerAddSea.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerAddSnow.java b/server/src/server/worldgen/layer/GenLayerAddSnow.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerAddSnow.java rename to server/src/server/worldgen/layer/GenLayerAddSnow.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerBase.java b/server/src/server/worldgen/layer/GenLayerBase.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerBase.java rename to server/src/server/worldgen/layer/GenLayerBase.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerBiome.java b/server/src/server/worldgen/layer/GenLayerBiome.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerBiome.java rename to server/src/server/worldgen/layer/GenLayerBiome.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerBiomeEdge.java b/server/src/server/worldgen/layer/GenLayerBiomeEdge.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerBiomeEdge.java rename to server/src/server/worldgen/layer/GenLayerBiomeEdge.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerEdge.java b/server/src/server/worldgen/layer/GenLayerEdge.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerEdge.java rename to server/src/server/worldgen/layer/GenLayerEdge.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerFuzzyZoom.java b/server/src/server/worldgen/layer/GenLayerFuzzyZoom.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerFuzzyZoom.java rename to server/src/server/worldgen/layer/GenLayerFuzzyZoom.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerHills.java b/server/src/server/worldgen/layer/GenLayerHills.java similarity index 99% rename from server/src/main/java/server/worldgen/layer/GenLayerHills.java rename to server/src/server/worldgen/layer/GenLayerHills.java index c2865ae..c92a1f0 100755 --- a/server/src/main/java/server/worldgen/layer/GenLayerHills.java +++ b/server/src/server/worldgen/layer/GenLayerHills.java @@ -37,7 +37,7 @@ public class GenLayerHills extends GenLayer if (k > 255) { - Log.TICK.warn("Altes Biom (" + k + ")!"); + Log.JNI.warn("Altes Biom (" + k + ")!"); } if (k != 0 && l >= 2 && (l - 2) % 29 == 1 && k < 128) diff --git a/server/src/main/java/server/worldgen/layer/GenLayerRemoveEmpty.java b/server/src/server/worldgen/layer/GenLayerRemoveEmpty.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerRemoveEmpty.java rename to server/src/server/worldgen/layer/GenLayerRemoveEmpty.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerRiver.java b/server/src/server/worldgen/layer/GenLayerRiver.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerRiver.java rename to server/src/server/worldgen/layer/GenLayerRiver.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerRiverInit.java b/server/src/server/worldgen/layer/GenLayerRiverInit.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerRiverInit.java rename to server/src/server/worldgen/layer/GenLayerRiverInit.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerRiverMix.java b/server/src/server/worldgen/layer/GenLayerRiverMix.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerRiverMix.java rename to server/src/server/worldgen/layer/GenLayerRiverMix.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerShore.java b/server/src/server/worldgen/layer/GenLayerShore.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerShore.java rename to server/src/server/worldgen/layer/GenLayerShore.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerSmooth.java b/server/src/server/worldgen/layer/GenLayerSmooth.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerSmooth.java rename to server/src/server/worldgen/layer/GenLayerSmooth.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerVoronoiZoom.java b/server/src/server/worldgen/layer/GenLayerVoronoiZoom.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerVoronoiZoom.java rename to server/src/server/worldgen/layer/GenLayerVoronoiZoom.java diff --git a/server/src/main/java/server/worldgen/layer/GenLayerZoom.java b/server/src/server/worldgen/layer/GenLayerZoom.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/GenLayerZoom.java rename to server/src/server/worldgen/layer/GenLayerZoom.java diff --git a/server/src/main/java/server/worldgen/layer/IntCache.java b/server/src/server/worldgen/layer/IntCache.java similarity index 100% rename from server/src/main/java/server/worldgen/layer/IntCache.java rename to server/src/server/worldgen/layer/IntCache.java diff --git a/server/src/main/java/server/worldgen/structure/MapGenBridge.java b/server/src/server/worldgen/structure/MapGenBridge.java similarity index 100% rename from server/src/main/java/server/worldgen/structure/MapGenBridge.java rename to server/src/server/worldgen/structure/MapGenBridge.java diff --git a/server/src/main/java/server/worldgen/structure/MapGenMineshaft.java b/server/src/server/worldgen/structure/MapGenMineshaft.java similarity index 100% rename from server/src/main/java/server/worldgen/structure/MapGenMineshaft.java rename to server/src/server/worldgen/structure/MapGenMineshaft.java diff --git a/server/src/main/java/server/worldgen/structure/MapGenScatteredFeature.java b/server/src/server/worldgen/structure/MapGenScatteredFeature.java similarity index 100% rename from server/src/main/java/server/worldgen/structure/MapGenScatteredFeature.java rename to server/src/server/worldgen/structure/MapGenScatteredFeature.java diff --git a/server/src/main/java/server/worldgen/structure/MapGenStronghold.java b/server/src/server/worldgen/structure/MapGenStronghold.java similarity index 100% rename from server/src/main/java/server/worldgen/structure/MapGenStronghold.java rename to server/src/server/worldgen/structure/MapGenStronghold.java diff --git a/server/src/main/java/server/worldgen/structure/MapGenStructure.java b/server/src/server/worldgen/structure/MapGenStructure.java similarity index 81% rename from server/src/main/java/server/worldgen/structure/MapGenStructure.java rename to server/src/server/worldgen/structure/MapGenStructure.java index 5f6c0d5..ab8c362 100755 --- a/server/src/main/java/server/worldgen/structure/MapGenStructure.java +++ b/server/src/server/worldgen/structure/MapGenStructure.java @@ -4,11 +4,11 @@ import java.util.Iterator; import java.util.Map; import common.collect.Maps; +import common.nbt.NBTBase; +import common.nbt.NBTTagCompound; import common.rng.Random; -import common.tags.TagObject; import common.util.BlockPos; import common.util.ChunkPos; -import common.util.LongHashMap; import common.world.World; import server.world.WorldServer; import server.world.WorldServer.WorldSavedData; @@ -18,7 +18,7 @@ import server.worldgen.caves.MapGenBase; public abstract class MapGenStructure extends MapGenBase { private WorldSavedData structureData; - protected Map structureMap = Maps.newHashMap(); + protected Map structureMap = Maps.newHashMap(); public abstract String getStructureName(); @@ -33,14 +33,15 @@ public abstract class MapGenStructure extends MapGenBase return; this.initializeStructureData(worldIn); - if (!this.structureMap.containsKey(Long.valueOf(LongHashMap.packInt(chunkX, chunkZ)))) + ChunkPos pos = new ChunkPos(chunkX, chunkZ); + if (!this.structureMap.containsKey(pos)) { this.rand.intv(); if (this.canSpawnStructureAtCoords(chunkX, chunkZ)) { StructureStart structurestart = this.getStructureStart(chunkX, chunkZ); - this.structureMap.put(Long.valueOf(LongHashMap.packInt(chunkX, chunkZ)), structurestart); + this.structureMap.put(pos, structurestart); this.setStructureStart(chunkX, chunkZ, structurestart); } } @@ -189,36 +190,38 @@ public abstract class MapGenStructure extends MapGenBase // return null; // } - private void initializeStructureData(WorldServer world) + private void initializeStructureData(WorldServer worldIn) { if (this.structureData == null) { - this.structureData = world.loadItemData(this.getStructureName()); + this.structureData = worldIn.loadItemData(this.getStructureName()); if (this.structureData == null) { - this.structureData = new WorldSavedData(this.getStructureName(), new TagObject()); - world.setItemData(this.getStructureName(), this.structureData); + this.structureData = new WorldSavedData(this.getStructureName(), new NBTTagCompound()); + worldIn.setItemData(this.getStructureName(), this.structureData); } else { - TagObject tag = this.structureData.tag; + NBTTagCompound tag = this.structureData.tag; - for (String s : tag.keySet()) + for (String s : tag.getKeySet()) { - if (tag.hasObject(s)) + NBTBase nbtbase = tag.getTag(s); + + if (nbtbase.getId() == 10) { - TagObject start = tag.getObject(s); + NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbtbase; - if (start.hasInt("ChunkX") && start.hasInt("ChunkZ")) + if (nbttagcompound1.hasKey("ChunkX") && nbttagcompound1.hasKey("ChunkZ")) { - int i = start.getInt("ChunkX"); - int j = start.getInt("ChunkZ"); - StructureStart structure = MapGenStructureIO.getStructureStart(start, world); + int i = nbttagcompound1.getInteger("ChunkX"); + int j = nbttagcompound1.getInteger("ChunkZ"); + StructureStart structurestart = MapGenStructureIO.getStructureStart(nbttagcompound1, worldIn); - if (structure != null) + if (structurestart != null) { - this.structureMap.put(Long.valueOf(LongHashMap.packInt(i, j)), structure); + this.structureMap.put(new ChunkPos(i, j), structurestart); } } } @@ -229,7 +232,7 @@ public abstract class MapGenStructure extends MapGenBase private void setStructureStart(int chunkX, int chunkZ, StructureStart start) { - this.structureData.tag.setObject("[" + chunkX + "," + chunkZ + "]", start.writeComponents(chunkX, chunkZ)); + this.structureData.tag.setTag("[" + chunkX + "," + chunkZ + "]", start.writeStructureComponentsToNBT(chunkX, chunkZ)); this.structureData.dirty = true; } diff --git a/server/src/main/java/server/worldgen/structure/MapGenStructureIO.java b/server/src/server/worldgen/structure/MapGenStructureIO.java similarity index 80% rename from server/src/main/java/server/worldgen/structure/MapGenStructureIO.java rename to server/src/server/worldgen/structure/MapGenStructureIO.java index 0a74793..7418618 100755 --- a/server/src/main/java/server/worldgen/structure/MapGenStructureIO.java +++ b/server/src/server/worldgen/structure/MapGenStructureIO.java @@ -4,7 +4,7 @@ import java.util.Map; import common.collect.Maps; import common.log.Log; -import common.tags.TagObject; +import common.nbt.NBTTagCompound; import server.world.WorldServer; public class MapGenStructureIO @@ -36,7 +36,7 @@ public class MapGenStructureIO return (String)componentClassToNameMap.get(component.getClass()); } - public static StructureStart getStructureStart(TagObject tagCompound, WorldServer worldIn) + public static StructureStart getStructureStart(NBTTagCompound tagCompound, WorldServer worldIn) { StructureStart structurestart = null; @@ -46,28 +46,28 @@ public class MapGenStructureIO if (oclass != null) { - structurestart = (StructureStart)oclass.getConstructor().newInstance(); + structurestart = (StructureStart)oclass.newInstance(); } } catch (Exception exception) { - Log.TICK.warn("Fehler bei Strukturanfang mit ID " + tagCompound.getString("id")); + Log.JNI.warn("Fehler bei Strukturanfang mit ID " + tagCompound.getString("id")); exception.printStackTrace(); } if (structurestart != null) { - structurestart.readComponents(worldIn, tagCompound); + structurestart.readStructureComponentsFromNBT(worldIn, tagCompound); } else { - Log.TICK.warn("Überspringe Struktur mit ID " + tagCompound.getString("id")); + Log.JNI.warn("Überspringe Struktur mit ID " + tagCompound.getString("id")); } return structurestart; } - public static StructureComponent getStructureComponent(TagObject tagCompound, WorldServer worldIn) + public static StructureComponent getStructureComponent(NBTTagCompound tagCompound, WorldServer worldIn) { StructureComponent structurecomponent = null; @@ -77,22 +77,22 @@ public class MapGenStructureIO if (oclass != null) { - structurecomponent = (StructureComponent)oclass.getConstructor().newInstance(); + structurecomponent = (StructureComponent)oclass.newInstance(); } } catch (Exception exception) { - Log.TICK.warn("Fehler bei Strukturteil mit ID " + tagCompound.getString("id")); + Log.JNI.warn("Fehler bei Strukturteil mit ID " + tagCompound.getString("id")); exception.printStackTrace(); } if (structurecomponent != null) { - structurecomponent.readBase(worldIn, tagCompound); + structurecomponent.readStructureBaseNBT(worldIn, tagCompound); } else { - Log.TICK.warn("Überspringe Strukturteil mit ID " + tagCompound.getString("id")); + Log.JNI.warn("Überspringe Strukturteil mit ID " + tagCompound.getString("id")); } return structurecomponent; diff --git a/server/src/main/java/server/worldgen/structure/MapGenVillage.java b/server/src/server/worldgen/structure/MapGenVillage.java similarity index 92% rename from server/src/main/java/server/worldgen/structure/MapGenVillage.java rename to server/src/server/worldgen/structure/MapGenVillage.java index fb4a1a6..47f89ec 100755 --- a/server/src/main/java/server/worldgen/structure/MapGenVillage.java +++ b/server/src/server/worldgen/structure/MapGenVillage.java @@ -5,8 +5,8 @@ import java.util.Set; import common.biome.Biome; import common.collect.Sets; +import common.nbt.NBTTagCompound; import common.rng.Random; -import common.tags.TagObject; import server.world.WorldServer; public class MapGenVillage extends MapGenStructure @@ -140,16 +140,16 @@ public class MapGenVillage extends MapGenStructure return this.hasMoreThanTwoComponents; } - public void writeTags(TagObject tagCompound) + public void writeToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Valid", this.hasMoreThanTwoComponents); + super.writeToNBT(tagCompound); + tagCompound.setBoolean("Valid", this.hasMoreThanTwoComponents); } - public void readTags(TagObject tagCompound) + public void readFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.hasMoreThanTwoComponents = tagCompound.getBool("Valid"); + super.readFromNBT(tagCompound); + this.hasMoreThanTwoComponents = tagCompound.getBoolean("Valid"); } } } diff --git a/server/src/main/java/server/worldgen/structure/StructureBoundingBox.java b/server/src/server/worldgen/structure/StructureBoundingBox.java similarity index 91% rename from server/src/main/java/server/worldgen/structure/StructureBoundingBox.java rename to server/src/server/worldgen/structure/StructureBoundingBox.java index a4b8110..70ddf56 100755 --- a/server/src/main/java/server/worldgen/structure/StructureBoundingBox.java +++ b/server/src/server/worldgen/structure/StructureBoundingBox.java @@ -1,5 +1,6 @@ package server.worldgen.structure; +import common.nbt.NBTTagIntArray; import common.util.BlockPos; import common.util.Facing; import common.util.Vec3i; @@ -41,16 +42,6 @@ public class StructureBoundingBox } } - public StructureBoundingBox(int[] coords, int offset) - { - this.minX = coords[offset + 0]; - this.minY = coords[offset + 1]; - this.minZ = coords[offset + 2]; - this.maxX = coords[offset + 3]; - this.maxY = coords[offset + 4]; - this.maxZ = coords[offset + 5]; - } - /** * returns a new StructureBoundingBox with MAX values */ @@ -218,18 +209,8 @@ public class StructureBoundingBox // return Objects.toStringHelper(this).add("x0", this.minX).add("y0", this.minY).add("z0", this.minZ).add("x1", this.maxX).add("y1", this.maxY).add("z1", this.maxZ).toString(); // } - public int[] toIntArray() + public NBTTagIntArray toNBTTagIntArray() { - return new int[] {this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ}; - } - - public void toIntArray(int[] data, int offset) - { - data[offset + 0] = this.minX; - data[offset + 1] = this.minY; - data[offset + 2] = this.minZ; - data[offset + 3] = this.maxX; - data[offset + 4] = this.maxY; - data[offset + 5] = this.maxZ; + return new NBTTagIntArray(new int[] {this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ}); } } diff --git a/server/src/main/java/server/worldgen/structure/StructureBridge.java b/server/src/server/worldgen/structure/StructureBridge.java similarity index 97% rename from server/src/main/java/server/worldgen/structure/StructureBridge.java rename to server/src/server/worldgen/structure/StructureBridge.java index 42ccbd3..309a567 100755 --- a/server/src/main/java/server/worldgen/structure/StructureBridge.java +++ b/server/src/server/worldgen/structure/StructureBridge.java @@ -3,13 +3,13 @@ package server.worldgen.structure; import java.util.List; import common.collect.Lists; -import common.entity.npc.EntityDarkMage; import common.init.Blocks; +import common.nbt.NBTTagCompound; import common.rng.Random; -import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityMobSpawner; import common.util.BlockPos; import common.util.Facing; -import server.vars.SVars; import server.world.WorldServer; import server.worldgen.LootConstants; @@ -115,16 +115,16 @@ public class StructureBridge this.field_111021_b = p_i45615_2_.zrange(3) == 0; } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.field_111021_b = tagCompound.getBool("Chest"); + super.readStructureFromNBT(tagCompound); + this.field_111021_b = tagCompound.getBoolean("Chest"); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Chest", this.field_111021_b); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("Chest", this.field_111021_b); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -186,16 +186,16 @@ public class StructureBridge this.field_111020_b = p_i45613_2_.zrange(3) == 0; } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.field_111020_b = tagCompound.getBool("Chest"); + super.readStructureFromNBT(tagCompound); + this.field_111020_b = tagCompound.getBoolean("Chest"); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Chest", this.field_111020_b); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("Chest", this.field_111020_b); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -636,16 +636,16 @@ public class StructureBridge return isAboveGround(structureboundingbox) && StructureComponent.findIntersecting(p_175884_0_, structureboundingbox) == null ? new StructureBridge.End(p_175884_6_, p_175884_1_, structureboundingbox, p_175884_5_) : null; } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.fillSeed = tagCompound.getInt("Seed"); + super.readStructureFromNBT(tagCompound); + this.fillSeed = tagCompound.getInteger("Seed"); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setInt("Seed", this.fillSeed); + super.writeStructureToNBT(tagCompound); + tagCompound.setInteger("Seed", this.fillSeed); } public boolean addComponentParts(WorldServer worldIn, Random randomIn, StructureBoundingBox structureBoundingBoxIn) @@ -951,11 +951,11 @@ public class StructureBridge super(p_i2054_1_); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { } @@ -1243,14 +1243,14 @@ public class StructureBridge } } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); + super.readStructureFromNBT(tagCompound); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); + super.writeStructureToNBT(tagCompound); } } @@ -1325,16 +1325,16 @@ public class StructureBridge this.boundingBox = p_i45611_3_; } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.hasSpawner = tagCompound.getBool("Mob"); + super.readStructureFromNBT(tagCompound); + this.hasSpawner = tagCompound.getBoolean("Mob"); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Mob", this.hasSpawner); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("Mob", this.hasSpawner); } public static StructureBridge.Throne func_175874_a(List p_175874_0_, Random p_175874_1_, int p_175874_2_, int p_175874_3_, int p_175874_4_, int p_175874_5_, Facing p_175874_6_) @@ -1364,17 +1364,20 @@ public class StructureBridge this.fillWithBlocks(worldIn, structureBoundingBoxIn, 1, 6, 8, 5, 7, 8, Blocks.blood_brick_fence.getState(), Blocks.blood_brick_fence.getState(), false); this.fillWithBlocks(worldIn, structureBoundingBoxIn, 2, 8, 8, 4, 8, 8, Blocks.blood_brick_fence.getState(), Blocks.blood_brick_fence.getState(), false); - if (!this.hasSpawner && SVars.mobs && SVars.spawnBridgeMobs) + if (!this.hasSpawner) { BlockPos blockpos = new BlockPos(this.getXWithOffset(3, 5), this.getYWithOffset(5), this.getZWithOffset(3, 5)); if (structureBoundingBoxIn.isVecInside(blockpos)) { this.hasSpawner = true; - EntityDarkMage entity = new EntityDarkMage(worldIn); - entity.setLocationAndAngles((double)blockpos.getX() + 0.5D, (double)blockpos.getY(), (double)blockpos.getZ() + 0.5D, worldIn.rand.floatv() * 360.0F, 0.0F); - entity.onInitialSpawn(null); - worldIn.spawnEntityInWorld(entity); + worldIn.setState(blockpos, Blocks.mob_spawner.getState(), 2); + TileEntity tileentity = worldIn.getTileEntity(blockpos); + + if (tileentity instanceof TileEntityMobSpawner) + { + ((TileEntityMobSpawner)tileentity).setEntityName("DarkMage"); + } } } diff --git a/server/src/main/java/server/worldgen/structure/StructureComponent.java b/server/src/server/worldgen/structure/StructureComponent.java similarity index 94% rename from server/src/main/java/server/worldgen/structure/StructureComponent.java rename to server/src/server/worldgen/structure/StructureComponent.java index bbc96a9..54d9af1 100755 --- a/server/src/main/java/server/worldgen/structure/StructureComponent.java +++ b/server/src/server/worldgen/structure/StructureComponent.java @@ -4,13 +4,14 @@ import java.util.List; import common.block.Block; import common.block.BlockDirectional; -import common.block.artificial.BlockDoor; +import common.block.BlockDoor; import common.init.Blocks; import common.item.ItemDoor; import common.item.RngLoot; +import common.material.Material; +import common.nbt.NBTTagCompound; import common.rng.Random; import common.rng.WeightedList; -import common.tags.TagObject; import common.tileentity.TileEntity; import common.tileentity.TileEntityChest; import common.tileentity.TileEntityDispenser; @@ -41,47 +42,47 @@ public abstract class StructureComponent /** * Writes structure base data (id, boundingbox, {@link * game.worldgen.structure.StructureComponent#coordBaseMode coordBase} and {@link - * game.worldgen.structure.StructureComponent#componentType componentType}) to new tag and + * game.worldgen.structure.StructureComponent#componentType componentType}) to new NBTTagCompound and * returns it. */ - public TagObject writeBase() + public NBTTagCompound createStructureBaseNBT() { - TagObject tag = new TagObject(); - tag.setString("id", MapGenStructureIO.getStructureComponentName(this)); - tag.setIntArray("BB", this.boundingBox.toIntArray()); - tag.setInt("O", this.coordBaseMode == null ? -1 : this.coordBaseMode.getHorizontalIndex()); - tag.setInt("GD", this.componentType); - this.writeTags(tag); - return tag; + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setString("id", MapGenStructureIO.getStructureComponentName(this)); + nbttagcompound.setTag("BB", this.boundingBox.toNBTTagIntArray()); + nbttagcompound.setInteger("O", this.coordBaseMode == null ? -1 : this.coordBaseMode.getHorizontalIndex()); + nbttagcompound.setInteger("GD", this.componentType); + this.writeStructureToNBT(nbttagcompound); + return nbttagcompound; } /** - * (abstract) Helper method to write subclass data to tag + * (abstract) Helper method to write subclass data to NBT */ - protected abstract void writeTags(TagObject tag); + protected abstract void writeStructureToNBT(NBTTagCompound tagCompound); /** * Reads and sets structure base data (boundingbox, {@link * game.worldgen.structure.StructureComponent#coordBaseMode coordBase} and {@link * game.worldgen.structure.StructureComponent#componentType componentType}) */ - public void readBase(WorldServer world, TagObject tag) + public void readStructureBaseNBT(WorldServer worldIn, NBTTagCompound tagCompound) { - if (tag.hasIntArray("BB")) + if (tagCompound.hasKey("BB")) { - this.boundingBox = new StructureBoundingBox(tag.getIntArray("BB")); + this.boundingBox = new StructureBoundingBox(tagCompound.getIntArray("BB")); } - int i = tag.getInt("O"); + int i = tagCompound.getInteger("O"); this.coordBaseMode = i == -1 ? null : Facing.getHorizontal(i); - this.componentType = tag.getInt("GD"); - this.readTags(tag); + this.componentType = tagCompound.getInteger("GD"); + this.readStructureFromNBT(tagCompound); } /** - * (abstract) Helper method to read subclass data from tag + * (abstract) Helper method to read subclass data from NBT */ - protected abstract void readTags(TagObject tag); + protected abstract void readStructureFromNBT(NBTTagCompound tagCompound); /** * Initiates construction of the Structure Component picked, at the current Location of StructGen @@ -637,7 +638,7 @@ public abstract class StructureComponent { for (int k = zMin; k <= zMax; ++k) { - if (!existingOnly || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() != Blocks.air) + if (!existingOnly || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock().getMaterial() != Material.air) { if (i != yMin && i != yMax && j != xMin && j != xMax && k != zMin && k != zMax) { @@ -665,7 +666,7 @@ public abstract class StructureComponent { for (int k = minZ; k <= maxZ; ++k) { - if (!alwaysReplace || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() != Blocks.air) + if (!alwaysReplace || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock().getMaterial() != Material.air) { blockselector.selectBlocks(rand, j, i, k, i == minY || i == maxY || j == minX || j == maxX || k == minZ || k == maxZ); this.setBlockState(worldIn, blockselector.getBlockState(), j, i, k, boundingboxIn); @@ -683,7 +684,7 @@ public abstract class StructureComponent { for (int k = minZ; k <= maxZ; ++k) { - if (rand.floatv() <= chance && (!p_175805_13_ || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() != Blocks.air)) + if (rand.floatv() <= chance && (!p_175805_13_ || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock().getMaterial() != Material.air)) { if (i != minY && i != maxY && j != minX && j != maxX && k != minZ && k != maxZ) { @@ -727,7 +728,7 @@ public abstract class StructureComponent { float f7 = ((float)k - f4) / (f2 * 0.5F); - if (!p_180777_10_ || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() != Blocks.air) + if (!p_180777_10_ || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock().getMaterial() != Material.air) { float f8 = f6 * f6 + f5 * f5 + f7 * f7; diff --git a/server/src/main/java/server/worldgen/structure/StructureMineshaft.java b/server/src/server/worldgen/structure/StructureMineshaft.java similarity index 93% rename from server/src/main/java/server/worldgen/structure/StructureMineshaft.java rename to server/src/server/worldgen/structure/StructureMineshaft.java index 7ede565..d7a0fd9 100755 --- a/server/src/main/java/server/worldgen/structure/StructureMineshaft.java +++ b/server/src/server/worldgen/structure/StructureMineshaft.java @@ -4,17 +4,19 @@ import java.util.LinkedList; import java.util.List; import common.entity.item.EntityChestCart; -import common.entity.npc.EntityArachnoid; import common.init.Blocks; import common.init.Items; import common.item.RngLoot; +import common.material.Material; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.rng.Random; import common.rng.WeightedList; -import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityMobSpawner; import common.util.BlockPos; import common.util.Facing; import common.world.State; -import server.vars.SVars; import server.world.WorldServer; import server.worldgen.LootConstants; @@ -99,20 +101,20 @@ public class StructureMineshaft { } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - tagCompound.setBool("hr", this.hasRails); - tagCompound.setBool("sc", this.hasSpiders); - tagCompound.setBool("hps", this.spawnerPlaced); - tagCompound.setInt("Num", this.sectionCount); + tagCompound.setBoolean("hr", this.hasRails); + tagCompound.setBoolean("sc", this.hasSpiders); + tagCompound.setBoolean("hps", this.spawnerPlaced); + tagCompound.setInteger("Num", this.sectionCount); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - this.hasRails = tagCompound.getBool("hr"); - this.hasSpiders = tagCompound.getBool("sc"); - this.spawnerPlaced = tagCompound.getBool("hps"); - this.sectionCount = tagCompound.getInt("Num"); + this.hasRails = tagCompound.getBoolean("hr"); + this.hasSpiders = tagCompound.getBoolean("sc"); + this.spawnerPlaced = tagCompound.getBoolean("hps"); + this.sectionCount = tagCompound.getInteger("Num"); } public Corridor(int type, Random rand, StructureBoundingBox structurebb, Facing facing) @@ -287,7 +289,7 @@ public class StructureMineshaft { BlockPos blockpos = new BlockPos(this.getXWithOffset(x, z), this.getYWithOffset(y), this.getZWithOffset(x, z)); - if (boundingBoxIn.isVecInside(blockpos) && worldIn.getState(blockpos).getBlock() == Blocks.air) + if (boundingBoxIn.isVecInside(blockpos) && worldIn.getState(blockpos).getBlock().getMaterial() == Material.air) { int i = rand.chance() ? 1 : 0; worldIn.setState(blockpos, Blocks.rail.getStateFromMeta(this.getMetadataWithOffset(Blocks.rail, i)), 2); @@ -360,7 +362,7 @@ public class StructureMineshaft this.generateChestContents(worldIn, structureBoundingBoxIn, randomIn, 0, 0, k1 + 1, RngLoot.addToList(LootConstants.MINESHAFT_CHEST, Items.enchanted_book.getRandom(randomIn)), 3 + randomIn.zrange(4)); } - if (this.hasSpiders && !this.spawnerPlaced && SVars.mobs && SVars.spawnMineshaftMobs) + if (this.hasSpiders && !this.spawnerPlaced) { int l1 = this.getYWithOffset(0); int i2 = k1 - 1 + randomIn.zrange(3); @@ -371,10 +373,13 @@ public class StructureMineshaft if (structureBoundingBoxIn.isVecInside(blockpos)) { this.spawnerPlaced = true; - EntityArachnoid entity = new EntityArachnoid(worldIn); - entity.setLocationAndAngles((double)blockpos.getX() + 0.5D, (double)blockpos.getY(), (double)blockpos.getZ() + 0.5D, worldIn.rand.floatv() * 360.0F, 0.0F); - entity.onInitialSpawn(null); - worldIn.spawnEntityInWorld(entity); + worldIn.setState(blockpos, Blocks.mob_spawner.getState(), 2); + TileEntity tileentity = worldIn.getTileEntity(blockpos); + + if (tileentity instanceof TileEntityMobSpawner) + { + ((TileEntityMobSpawner)tileentity).setEntityName("Arachnoid"); + } } } } @@ -386,7 +391,7 @@ public class StructureMineshaft int j3 = -1; State iblockstate1 = this.getBlockStateFromPos(worldIn, k2, j3, i3, structureBoundingBoxIn); - if (iblockstate1.getBlock() == Blocks.air) + if (iblockstate1.getBlock().getMaterial() == Material.air) { int k3 = -1; this.setBlockState(worldIn, Blocks.oak_planks.getState(), k2, k3, i3, structureBoundingBoxIn); @@ -400,7 +405,7 @@ public class StructureMineshaft { State iblockstate = this.getBlockStateFromPos(worldIn, 1, -1, l2, structureBoundingBoxIn); - if (iblockstate.getBlock() != Blocks.air && iblockstate.getBlock().isFullBlock()) + if (iblockstate.getBlock().getMaterial() != Material.air && iblockstate.getBlock().isFullBlock()) { this.randomlyPlaceBlock(worldIn, structureBoundingBoxIn, randomIn, 0.7F, 1, 0, l2, Blocks.rail.getStateFromMeta(this.getMetadataWithOffset(Blocks.rail, 0))); } @@ -421,16 +426,16 @@ public class StructureMineshaft { } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - tagCompound.setBool("tf", this.isMultipleFloors); - tagCompound.setInt("D", this.corridorDirection.getHorizontalIndex()); + tagCompound.setBoolean("tf", this.isMultipleFloors); + tagCompound.setInteger("D", this.corridorDirection.getHorizontalIndex()); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - this.isMultipleFloors = tagCompound.getBool("tf"); - this.corridorDirection = Facing.getHorizontal(tagCompound.getInt("D")); + this.isMultipleFloors = tagCompound.getBoolean("tf"); + this.corridorDirection = Facing.getHorizontal(tagCompound.getInteger("D")); } public Cross(int type, Random rand, StructureBoundingBox structurebb, Facing facing) @@ -564,7 +569,7 @@ public class StructureMineshaft { for (int j = this.boundingBox.minZ; j <= this.boundingBox.maxZ; ++j) { - if (this.getBlockStateFromPos(worldIn, i, this.boundingBox.minY - 1, j, structureBoundingBoxIn).getBlock() == Blocks.air) + if (this.getBlockStateFromPos(worldIn, i, this.boundingBox.minY - 1, j, structureBoundingBoxIn).getBlock().getMaterial() == Material.air) { this.setBlockState(worldIn, Blocks.oak_planks.getState(), i, this.boundingBox.minY - 1, j, structureBoundingBoxIn); } @@ -706,25 +711,25 @@ public class StructureMineshaft } } - protected void writeTags(TagObject tag) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - int[] rooms = new int[this.roomsLinkedToTheRoom.size() * 6]; + NBTTagList nbttaglist = new NBTTagList(); - for (int z = 0; z < rooms.length / 6; z++) + for (StructureBoundingBox structureboundingbox : this.roomsLinkedToTheRoom) { - this.roomsLinkedToTheRoom.get(z).toIntArray(rooms, z * 6); + nbttaglist.appendTag(structureboundingbox.toNBTTagIntArray()); } - tag.setIntArray("Entrances", rooms); + tagCompound.setTag("Entrances", nbttaglist); } - protected void readTags(TagObject tag) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - int[] rooms = tag.getIntArray("Entrances"); + NBTTagList nbttaglist = tagCompound.getTagList("Entrances", 11); - for (int z = 0; z < rooms.length / 6; z++) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - this.roomsLinkedToTheRoom.add(new StructureBoundingBox(rooms, z * 6)); + this.roomsLinkedToTheRoom.add(new StructureBoundingBox(nbttaglist.getIntArrayAt(i))); } } } @@ -742,11 +747,11 @@ public class StructureMineshaft this.boundingBox = structurebb; } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { } diff --git a/server/src/main/java/server/worldgen/structure/StructureMineshaftStart.java b/server/src/server/worldgen/structure/StructureMineshaftStart.java similarity index 100% rename from server/src/main/java/server/worldgen/structure/StructureMineshaftStart.java rename to server/src/server/worldgen/structure/StructureMineshaftStart.java diff --git a/server/src/main/java/server/worldgen/structure/StructureScattered.java b/server/src/server/worldgen/structure/StructureScattered.java similarity index 94% rename from server/src/main/java/server/worldgen/structure/StructureScattered.java rename to server/src/server/worldgen/structure/StructureScattered.java index 5d2705a..8723035 100755 --- a/server/src/main/java/server/worldgen/structure/StructureScattered.java +++ b/server/src/server/worldgen/structure/StructureScattered.java @@ -1,22 +1,22 @@ package server.worldgen.structure; -import common.block.artificial.BlockFlowerPot; -import common.block.artificial.BlockStoneBrick; -import common.block.foliage.BlockFlower; -import common.block.natural.BlockSandStone; -import common.block.tech.BlockLever; -import common.block.tech.BlockTripWire; -import common.block.tech.BlockTripWireHook; +import common.block.BlockFlower; +import common.block.BlockFlowerPot; +import common.block.BlockLever; +import common.block.BlockSandStone; +import common.block.BlockStoneBrick; +import common.block.BlockTripWire; +import common.block.BlockTripWireHook; import common.color.DyeColor; import common.entity.npc.EntityMage; import common.init.Blocks; +import common.init.Config; import common.init.Items; import common.item.RngLoot; +import common.nbt.NBTTagCompound; import common.rng.Random; -import common.tags.TagObject; import common.util.BlockPos; import common.util.Facing; -import server.vars.SVars; import server.world.WorldServer; import server.worldgen.LootConstants; @@ -41,22 +41,22 @@ public class StructureScattered super(p_i2062_1_, p_i2062_2_, 64, p_i2062_3_, 21, 15, 21); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("hasPlacedChest0", this.hasPlacedChest[0]); - tagCompound.setBool("hasPlacedChest1", this.hasPlacedChest[1]); - tagCompound.setBool("hasPlacedChest2", this.hasPlacedChest[2]); - tagCompound.setBool("hasPlacedChest3", this.hasPlacedChest[3]); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("hasPlacedChest0", this.hasPlacedChest[0]); + tagCompound.setBoolean("hasPlacedChest1", this.hasPlacedChest[1]); + tagCompound.setBoolean("hasPlacedChest2", this.hasPlacedChest[2]); + tagCompound.setBoolean("hasPlacedChest3", this.hasPlacedChest[3]); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.hasPlacedChest[0] = tagCompound.getBool("hasPlacedChest0"); - this.hasPlacedChest[1] = tagCompound.getBool("hasPlacedChest1"); - this.hasPlacedChest[2] = tagCompound.getBool("hasPlacedChest2"); - this.hasPlacedChest[3] = tagCompound.getBool("hasPlacedChest3"); + super.readStructureFromNBT(tagCompound); + this.hasPlacedChest[0] = tagCompound.getBoolean("hasPlacedChest0"); + this.hasPlacedChest[1] = tagCompound.getBoolean("hasPlacedChest1"); + this.hasPlacedChest[2] = tagCompound.getBoolean("hasPlacedChest2"); + this.hasPlacedChest[3] = tagCompound.getBoolean("hasPlacedChest3"); } public boolean addComponentParts(WorldServer worldIn, Random randomIn, StructureBoundingBox structureBoundingBoxIn) @@ -293,20 +293,20 @@ public class StructureScattered } } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - tagCompound.setInt("Width", this.scatteredFeatureSizeX); - tagCompound.setInt("Height", this.scatteredFeatureSizeY); - tagCompound.setInt("Depth", this.scatteredFeatureSizeZ); - tagCompound.setInt("HPos", this.field_74936_d); + tagCompound.setInteger("Width", this.scatteredFeatureSizeX); + tagCompound.setInteger("Height", this.scatteredFeatureSizeY); + tagCompound.setInteger("Depth", this.scatteredFeatureSizeZ); + tagCompound.setInteger("HPos", this.field_74936_d); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - this.scatteredFeatureSizeX = tagCompound.getInt("Width"); - this.scatteredFeatureSizeY = tagCompound.getInt("Height"); - this.scatteredFeatureSizeZ = tagCompound.getInt("Depth"); - this.field_74936_d = tagCompound.getInt("HPos"); + this.scatteredFeatureSizeX = tagCompound.getInteger("Width"); + this.scatteredFeatureSizeY = tagCompound.getInteger("Height"); + this.scatteredFeatureSizeZ = tagCompound.getInteger("Depth"); + this.field_74936_d = tagCompound.getInteger("HPos"); } protected boolean func_74935_a(WorldServer worldIn, StructureBoundingBox p_74935_2_, int p_74935_3_) @@ -366,22 +366,22 @@ public class StructureScattered super(p_i2064_1_, p_i2064_2_, 64, p_i2064_3_, 12, 10, 15); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("placedMainChest", this.placedMainChest); - tagCompound.setBool("placedHiddenChest", this.placedHiddenChest); - tagCompound.setBool("placedTrap1", this.placedTrap1); - tagCompound.setBool("placedTrap2", this.placedTrap2); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("placedMainChest", this.placedMainChest); + tagCompound.setBoolean("placedHiddenChest", this.placedHiddenChest); + tagCompound.setBoolean("placedTrap1", this.placedTrap1); + tagCompound.setBoolean("placedTrap2", this.placedTrap2); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.placedMainChest = tagCompound.getBool("placedMainChest"); - this.placedHiddenChest = tagCompound.getBool("placedHiddenChest"); - this.placedTrap1 = tagCompound.getBool("placedTrap1"); - this.placedTrap2 = tagCompound.getBool("placedTrap2"); + super.readStructureFromNBT(tagCompound); + this.placedMainChest = tagCompound.getBoolean("placedMainChest"); + this.placedHiddenChest = tagCompound.getBoolean("placedHiddenChest"); + this.placedTrap1 = tagCompound.getBoolean("placedTrap1"); + this.placedTrap2 = tagCompound.getBoolean("placedTrap2"); } public boolean addComponentParts(WorldServer worldIn, Random randomIn, StructureBoundingBox structureBoundingBoxIn) @@ -613,16 +613,16 @@ public class StructureScattered super(p_i2066_1_, p_i2066_2_, 64, p_i2066_3_, 7, 7, 9); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Mage", this.hasMage); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("Mage", this.hasMage); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.hasMage = tagCompound.getBool("Mage"); + super.readStructureFromNBT(tagCompound); + this.hasMage = tagCompound.getBoolean("Mage"); } public boolean addComponentParts(WorldServer worldIn, Random randomIn, StructureBoundingBox structureBoundingBoxIn) @@ -650,7 +650,7 @@ public class StructureScattered this.setBlockState(worldIn, Blocks.air.getState(), 5, 3, 4, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.air.getState(), 5, 3, 5, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.flower_pot.getState().withProperty(BlockFlowerPot.CONTENTS, 2 + BlockFlower.EnumFlowerType.BLACK_LOTUS.getMeta()), 1, 3, 5, structureBoundingBoxIn); - this.setBlockState(worldIn, Blocks.workbench.getState(), 3, 2, 6, structureBoundingBoxIn); + this.setBlockState(worldIn, Blocks.crafting_table.getState(), 3, 2, 6, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.cauldron.getState(), 4, 2, 6, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.oak_fence.getState(), 1, 2, 1, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.oak_fence.getState(), 5, 2, 1, structureBoundingBoxIn); @@ -671,7 +671,7 @@ public class StructureScattered } } - if (!this.hasMage && SVars.mobs && SVars.spawnHutMage) + if (!this.hasMage && Config.mobs && Config.spawnHutMage) { int l1 = this.getXWithOffset(2, 5); int i2 = this.getYWithOffset(2); diff --git a/server/src/main/java/server/worldgen/structure/StructureStart.java b/server/src/server/worldgen/structure/StructureStart.java similarity index 71% rename from server/src/main/java/server/worldgen/structure/StructureStart.java rename to server/src/server/worldgen/structure/StructureStart.java index ecb455d..bc06008 100755 --- a/server/src/main/java/server/worldgen/structure/StructureStart.java +++ b/server/src/server/worldgen/structure/StructureStart.java @@ -3,10 +3,9 @@ package server.worldgen.structure; import java.util.Iterator; import java.util.LinkedList; -import common.collect.Lists; +import common.nbt.NBTTagCompound; +import common.nbt.NBTTagList; import common.rng.Random; -import common.tags.TagObject; -import java.util.List; import common.util.ChunkPos; import server.world.WorldServer; @@ -68,50 +67,50 @@ public abstract class StructureStart } } - public TagObject writeComponents(int chunkX, int chunkZ) + public NBTTagCompound writeStructureComponentsToNBT(int chunkX, int chunkZ) { - TagObject tag = new TagObject(); - tag.setString("id", MapGenStructureIO.getStructureStartName(this)); - tag.setInt("ChunkX", chunkX); - tag.setInt("ChunkZ", chunkZ); - tag.setIntArray("BB", this.boundingBox.toIntArray()); - List list = Lists.newArrayList(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setString("id", MapGenStructureIO.getStructureStartName(this)); + nbttagcompound.setInteger("ChunkX", chunkX); + nbttagcompound.setInteger("ChunkZ", chunkZ); + nbttagcompound.setTag("BB", this.boundingBox.toNBTTagIntArray()); + NBTTagList nbttaglist = new NBTTagList(); - for (StructureComponent comp : this.components) + for (StructureComponent structurecomponent : this.components) { - list.add(comp.writeBase()); + nbttaglist.appendTag(structurecomponent.createStructureBaseNBT()); } - tag.setList("Children", list); - this.writeTags(tag); - return tag; + nbttagcompound.setTag("Children", nbttaglist); + this.writeToNBT(nbttagcompound); + return nbttagcompound; } - public void writeTags(TagObject tag) + public void writeToNBT(NBTTagCompound tagCompound) { } - public void readComponents(WorldServer world, TagObject tag) + public void readStructureComponentsFromNBT(WorldServer worldIn, NBTTagCompound tagCompound) { - this.chunkPosX = tag.getInt("ChunkX"); - this.chunkPosZ = tag.getInt("ChunkZ"); + this.chunkPosX = tagCompound.getInteger("ChunkX"); + this.chunkPosZ = tagCompound.getInteger("ChunkZ"); - if (tag.hasIntArray("BB")) + if (tagCompound.hasKey("BB")) { - this.boundingBox = new StructureBoundingBox(tag.getIntArray("BB")); + this.boundingBox = new StructureBoundingBox(tagCompound.getIntArray("BB")); } - List list = tag.getList("Children"); + NBTTagList nbttaglist = tagCompound.getTagList("Children", 10); - for (int i = 0; i < list.size(); ++i) + for (int i = 0; i < nbttaglist.tagCount(); ++i) { - this.components.add(MapGenStructureIO.getStructureComponent(list.get(i), world)); + this.components.add(MapGenStructureIO.getStructureComponent(nbttaglist.getCompoundTagAt(i), worldIn)); } - this.readTags(tag); + this.readFromNBT(tagCompound); } - public void readTags(TagObject tag) + public void readFromNBT(NBTTagCompound tagCompound) { } diff --git a/server/src/main/java/server/worldgen/structure/StructureStronghold.java b/server/src/server/worldgen/structure/StructureStronghold.java similarity index 95% rename from server/src/main/java/server/worldgen/structure/StructureStronghold.java rename to server/src/server/worldgen/structure/StructureStronghold.java index b96c6c4..101d358 100755 --- a/server/src/main/java/server/worldgen/structure/StructureStronghold.java +++ b/server/src/server/worldgen/structure/StructureStronghold.java @@ -3,19 +3,19 @@ package server.worldgen.structure; import java.util.List; import java.util.Map; -import common.block.artificial.BlockSlab; -import common.block.artificial.BlockStoneBrick; +import common.block.BlockSlab; +import common.block.BlockStoneBrick; import common.collect.Lists; import common.collect.Maps; -import common.entity.npc.EntityHaunter; import common.init.Blocks; import common.init.Items; import common.item.RngLoot; +import common.nbt.NBTTagCompound; import common.rng.Random; -import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityMobSpawner; import common.util.BlockPos; import common.util.Facing; -import server.vars.SVars; import server.world.WorldServer; import server.worldgen.LootConstants; @@ -252,16 +252,16 @@ public class StructureStronghold this.boundingBox = p_i45582_3_; } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Chest", this.hasMadeChest); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("Chest", this.hasMadeChest); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.hasMadeChest = tagCompound.getBool("Chest"); + super.readStructureFromNBT(tagCompound); + this.hasMadeChest = tagCompound.getBoolean("Chest"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -324,16 +324,16 @@ public class StructureStronghold this.field_74993_a = p_i45581_4_ != Facing.NORTH && p_i45581_4_ != Facing.SOUTH ? p_i45581_3_.getXSize() : p_i45581_3_.getZSize(); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setInt("Steps", this.field_74993_a); + super.writeStructureToNBT(tagCompound); + tagCompound.setInteger("Steps", this.field_74993_a); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.field_74993_a = tagCompound.getInt("Steps"); + super.readStructureFromNBT(tagCompound); + this.field_74993_a = tagCompound.getInteger("Steps"); } public static StructureBoundingBox func_175869_a(List p_175869_0_, Random p_175869_1_, int p_175869_2_, int p_175869_3_, int p_175869_4_, Facing p_175869_5_) @@ -425,22 +425,22 @@ public class StructureStronghold this.field_74999_h = p_i45580_2_.zrange(3) > 0; } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("leftLow", this.field_74996_b); - tagCompound.setBool("leftHigh", this.field_74997_c); - tagCompound.setBool("rightLow", this.field_74995_d); - tagCompound.setBool("rightHigh", this.field_74999_h); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("leftLow", this.field_74996_b); + tagCompound.setBoolean("leftHigh", this.field_74997_c); + tagCompound.setBoolean("rightLow", this.field_74995_d); + tagCompound.setBoolean("rightHigh", this.field_74999_h); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.field_74996_b = tagCompound.getBool("leftLow"); - this.field_74997_c = tagCompound.getBool("leftHigh"); - this.field_74995_d = tagCompound.getBool("rightLow"); - this.field_74999_h = tagCompound.getBool("rightHigh"); + super.readStructureFromNBT(tagCompound); + this.field_74996_b = tagCompound.getBoolean("leftLow"); + this.field_74997_c = tagCompound.getBoolean("leftHigh"); + this.field_74995_d = tagCompound.getBoolean("rightLow"); + this.field_74999_h = tagCompound.getBoolean("rightHigh"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -608,16 +608,16 @@ public class StructureStronghold this.isLargeRoom = p_i45578_3_.getYSize() > 6; } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Tall", this.isLargeRoom); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("Tall", this.isLargeRoom); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.isLargeRoom = tagCompound.getBool("Tall"); + super.readStructureFromNBT(tagCompound); + this.isLargeRoom = tagCompound.getBoolean("Tall"); } public static StructureStronghold.Library func_175864_a(List p_175864_0_, Random p_175864_1_, int p_175864_2_, int p_175864_3_, int p_175864_4_, Facing p_175864_5_, int p_175864_6_) @@ -792,16 +792,16 @@ public class StructureStronghold this.boundingBox = p_i45577_3_; } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Mob", this.hasSpawner); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("Mob", this.hasSpawner); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.hasSpawner = tagCompound.getBool("Mob"); + super.readStructureFromNBT(tagCompound); + this.hasSpawner = tagCompound.getBoolean("Mob"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -899,7 +899,7 @@ public class StructureStronghold // this.setBlockState(worldIn, Blocks.end_portal_frame.getStateFromMeta(j1).withProperty(BlockPortalFrame.ORB, Boolean.valueOf(randomIn.floatv() > 0.9F)), 7, 3, 10, structureBoundingBoxIn); // this.setBlockState(worldIn, Blocks.end_portal_frame.getStateFromMeta(j1).withProperty(BlockPortalFrame.ORB, Boolean.valueOf(randomIn.floatv() > 0.9F)), 7, 3, 11, structureBoundingBoxIn); - if (!this.hasSpawner && SVars.mobs && SVars.spawnStrongholdMobs) + if (!this.hasSpawner) { i = this.getYWithOffset(3); BlockPos blockpos = new BlockPos(this.getXWithOffset(5, 6), i, this.getZWithOffset(5, 6)); @@ -907,10 +907,13 @@ public class StructureStronghold if (structureBoundingBoxIn.isVecInside(blockpos)) { this.hasSpawner = true; - EntityHaunter entity = new EntityHaunter(worldIn); - entity.setLocationAndAngles((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 1.0D, (double)blockpos.getZ() + 0.5D, worldIn.rand.floatv() * 360.0F, 0.0F); - entity.onInitialSpawn(null); - worldIn.spawnEntityInWorld(entity); + worldIn.setState(blockpos, Blocks.mob_spawner.getState(), 2); + TileEntity tileentity = worldIn.getTileEntity(blockpos); + + if (tileentity instanceof TileEntityMobSpawner) + { + ((TileEntityMobSpawner)tileentity).setEntityName("Haunter"); + } } } @@ -1027,16 +1030,16 @@ public class StructureStronghold this.roomType = p_i45575_2_.zrange(5); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setInt("Type", this.roomType); + super.writeStructureToNBT(tagCompound); + tagCompound.setInteger("Type", this.roomType); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.roomType = tagCompound.getInt("Type"); + super.readStructureFromNBT(tagCompound); + this.roomType = tagCompound.getInteger("Type"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -1196,16 +1199,16 @@ public class StructureStronghold this.boundingBox = p_i45574_3_; } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Source", this.field_75024_a); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("Source", this.field_75024_a); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.field_75024_a = tagCompound.getBool("Source"); + super.readStructureFromNBT(tagCompound); + this.field_75024_a = tagCompound.getBoolean("Source"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -1390,18 +1393,18 @@ public class StructureStronghold this.expandsZ = p_i45573_2_.zrange(2) == 0; } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Left", this.expandsX); - tagCompound.setBool("Right", this.expandsZ); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("Left", this.expandsX); + tagCompound.setBoolean("Right", this.expandsZ); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.expandsX = tagCompound.getBool("Left"); - this.expandsZ = tagCompound.getBool("Right"); + super.readStructureFromNBT(tagCompound); + this.expandsX = tagCompound.getBoolean("Left"); + this.expandsZ = tagCompound.getBoolean("Right"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -1469,12 +1472,12 @@ public class StructureStronghold super(p_i2087_1_); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { tagCompound.setString("EntryDoor", this.field_143013_d.getName()); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { this.field_143013_d = StructureStronghold.Stronghold.Door.getByName(tagCompound.getString("EntryDoor")); } diff --git a/server/src/main/java/server/worldgen/structure/StructureVillage.java b/server/src/server/worldgen/structure/StructureVillage.java similarity index 95% rename from server/src/main/java/server/worldgen/structure/StructureVillage.java rename to server/src/server/worldgen/structure/StructureVillage.java index d88fb76..0fb61ae 100755 --- a/server/src/main/java/server/worldgen/structure/StructureVillage.java +++ b/server/src/server/worldgen/structure/StructureVillage.java @@ -5,22 +5,23 @@ import java.util.List; import common.biome.Biome; import common.block.Block; -import common.block.artificial.BlockSlab; -import common.block.artificial.BlockStairs; -import common.block.foliage.BlockLog; -import common.block.natural.BlockSandStone; -import common.block.tech.BlockTorch; +import common.block.BlockLog; +import common.block.BlockSandStone; +import common.block.BlockSlab; +import common.block.BlockStairs; +import common.block.BlockTorch; import common.collect.Lists; import common.color.DyeColor; import common.entity.npc.EntityHuman; import common.init.BlockRegistry; import common.init.Blocks; +import common.init.Config; +import common.material.Material; +import common.nbt.NBTTagCompound; import common.rng.Random; -import common.tags.TagObject; import common.util.BlockPos; import common.util.Facing; import common.world.State; -import server.vars.SVars; import server.world.WorldServer; import server.worldgen.BiomeGenerator; import server.worldgen.LootConstants; @@ -357,7 +358,7 @@ public class StructureVillage this.setBlockState(worldIn, Blocks.air.getState(), 2, 2, 0, structureBoundingBoxIn); this.placeDoorCurrentPosition(worldIn, structureBoundingBoxIn, randomIn, 2, 1, 0, Facing.getHorizontal(this.getMetadataWithOffset(Blocks.oak_door, 1))); - if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) + if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 2, 0, -1, structureBoundingBoxIn); } @@ -403,22 +404,22 @@ public class StructureVillage this.cropTypeD = this.func_151559_a(rand); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setString("CA", BlockRegistry.getNameFromBlock(this.cropTypeA)); - tagCompound.setString("CB", BlockRegistry.getNameFromBlock(this.cropTypeB)); - tagCompound.setString("CC", BlockRegistry.getNameFromBlock(this.cropTypeC)); - tagCompound.setString("CD", BlockRegistry.getNameFromBlock(this.cropTypeD)); + super.writeStructureToNBT(tagCompound); + tagCompound.setInteger("CA", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeA)); + tagCompound.setInteger("CB", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeB)); + tagCompound.setInteger("CC", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeC)); + tagCompound.setInteger("CD", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeD)); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.cropTypeA = BlockRegistry.getRegisteredBlock(tagCompound.getString("CA")); - this.cropTypeB = BlockRegistry.getRegisteredBlock(tagCompound.getString("CB")); - this.cropTypeC = BlockRegistry.getRegisteredBlock(tagCompound.getString("CC")); - this.cropTypeD = BlockRegistry.getRegisteredBlock(tagCompound.getString("CD")); + super.readStructureFromNBT(tagCompound); + this.cropTypeA = BlockRegistry.getBlockById(tagCompound.getInteger("CA")); + this.cropTypeB = BlockRegistry.getBlockById(tagCompound.getInteger("CB")); + this.cropTypeC = BlockRegistry.getBlockById(tagCompound.getInteger("CC")); + this.cropTypeD = BlockRegistry.getBlockById(tagCompound.getInteger("CD")); } private Block func_151559_a(Random rand) @@ -512,18 +513,18 @@ public class StructureVillage this.cropTypeB = this.func_151560_a(rand); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setString("CA", BlockRegistry.getNameFromBlock(this.cropTypeA)); - tagCompound.setString("CB", BlockRegistry.getNameFromBlock(this.cropTypeB)); + super.writeStructureToNBT(tagCompound); + tagCompound.setInteger("CA", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeA)); + tagCompound.setInteger("CB", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeB)); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.cropTypeA = BlockRegistry.getRegisteredBlock(tagCompound.getString("CA")); - this.cropTypeB = BlockRegistry.getRegisteredBlock(tagCompound.getString("CB")); + super.readStructureFromNBT(tagCompound); + this.cropTypeA = BlockRegistry.getBlockById(tagCompound.getInteger("CA")); + this.cropTypeB = BlockRegistry.getBlockById(tagCompound.getInteger("CB")); } private Block func_151560_a(Random rand) @@ -682,7 +683,7 @@ public class StructureVillage this.setBlockState(worldIn, Blocks.torch.getState().withProperty(BlockTorch.FACING, this.coordBaseMode), 2, 3, 1, structureBoundingBoxIn); this.placeDoorCurrentPosition(worldIn, structureBoundingBoxIn, randomIn, 2, 1, 0, Facing.getHorizontal(this.getMetadataWithOffset(Blocks.oak_door, 1))); - if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) + if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 2, 0, -1, structureBoundingBoxIn); } @@ -805,12 +806,12 @@ public class StructureVillage this.setBlockState(worldIn, Blocks.wooden_pressure_plate.getState(), 6, 2, 3, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.oak_fence.getState(), 4, 1, 3, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.wooden_pressure_plate.getState(), 4, 2, 3, structureBoundingBoxIn); - this.setBlockState(worldIn, Blocks.workbench.getState(), 7, 1, 1, structureBoundingBoxIn); + this.setBlockState(worldIn, Blocks.crafting_table.getState(), 7, 1, 1, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.air.getState(), 1, 1, 0, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.air.getState(), 1, 2, 0, structureBoundingBoxIn); this.placeDoorCurrentPosition(worldIn, structureBoundingBoxIn, randomIn, 1, 1, 0, Facing.getHorizontal(this.getMetadataWithOffset(Blocks.oak_door, 1))); - if (this.getBlockStateFromPos(worldIn, 1, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 1, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) + if (this.getBlockStateFromPos(worldIn, 1, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 1, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 1, 0, -1, structureBoundingBoxIn); } @@ -855,16 +856,16 @@ public class StructureVillage return canVillageGoDeeper(structureboundingbox) && StructureComponent.findIntersecting(p_175855_1_, structureboundingbox) == null ? new StructureVillage.House2(start, p_175855_7_, rand, structureboundingbox, facing) : null; } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Chest", this.hasMadeChest); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("Chest", this.hasMadeChest); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.hasMadeChest = tagCompound.getBool("Chest"); + super.readStructureFromNBT(tagCompound); + this.hasMadeChest = tagCompound.getBoolean("Chest"); } public boolean addComponentParts(WorldServer worldIn, Random randomIn, StructureBoundingBox structureBoundingBoxIn) @@ -925,7 +926,7 @@ public class StructureVillage for (int i = 6; i <= 8; ++i) { - if (this.getBlockStateFromPos(worldIn, i, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, i, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) + if (this.getBlockStateFromPos(worldIn, i, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, i, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), i, 0, -1, structureBoundingBoxIn); } @@ -1079,7 +1080,7 @@ public class StructureVillage this.placeDoorCurrentPosition(worldIn, structureBoundingBoxIn, randomIn, 2, 1, 0, Facing.getHorizontal(this.getMetadataWithOffset(Blocks.oak_door, 1))); this.fillWithBlocks(worldIn, structureBoundingBoxIn, 1, 0, -1, 3, 2, -1, Blocks.air.getState(), Blocks.air.getState(), false); - if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) + if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 2, 0, -1, structureBoundingBoxIn); } @@ -1123,16 +1124,16 @@ public class StructureVillage this.isRoofAccessible = rand.chance(); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("Terrace", this.isRoofAccessible); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("Terrace", this.isRoofAccessible); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.isRoofAccessible = tagCompound.getBool("Terrace"); + super.readStructureFromNBT(tagCompound); + this.isRoofAccessible = tagCompound.getBoolean("Terrace"); } public static StructureVillage.House4Garden func_175858_a(StructureVillage.Start start, List p_175858_1_, Random rand, int p_175858_3_, int p_175858_4_, int p_175858_5_, Facing facing, int p_175858_7_) @@ -1184,7 +1185,7 @@ public class StructureVillage this.setBlockState(worldIn, Blocks.oak_planks.getState(), 3, 2, 0, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.oak_planks.getState(), 3, 1, 0, structureBoundingBoxIn); - if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) + if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 2, 0, -1, structureBoundingBoxIn); } @@ -1252,16 +1253,16 @@ public class StructureVillage this.length = Math.max(p_i45562_4_.getXSize(), p_i45562_4_.getZSize()); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setInt("Length", this.length); + super.writeStructureToNBT(tagCompound); + tagCompound.setInteger("Length", this.length); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.length = tagCompound.getInt("Length"); + super.readStructureFromNBT(tagCompound); + this.length = tagCompound.getInteger("Length"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -1507,18 +1508,18 @@ public class StructureVillage } } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - tagCompound.setInt("HPos", this.field_143015_k); - tagCompound.setInt("VCount", this.villagersSpawned); - tagCompound.setBool("Desert", this.isDesertVillage); + tagCompound.setInteger("HPos", this.field_143015_k); + tagCompound.setInteger("VCount", this.villagersSpawned); + tagCompound.setBoolean("Desert", this.isDesertVillage); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - this.field_143015_k = tagCompound.getInt("HPos"); - this.villagersSpawned = tagCompound.getInt("VCount"); - this.isDesertVillage = tagCompound.getBool("Desert"); + this.field_143015_k = tagCompound.getInteger("HPos"); + this.villagersSpawned = tagCompound.getInteger("VCount"); + this.isDesertVillage = tagCompound.getBoolean("Desert"); } protected StructureComponent getNextComponentNN(StructureVillage.Start start, List p_74891_2_, Random rand, int p_74891_4_, int p_74891_5_) @@ -1604,7 +1605,7 @@ public class StructureVillage protected void spawnVillagers(WorldServer worldIn, StructureBoundingBox p_74893_2_, int p_74893_3_, int p_74893_4_, int p_74893_5_, int p_74893_6_) { - if (this.villagersSpawned < p_74893_6_ && SVars.mobs && SVars.spawnVillager) + if (this.villagersSpawned < p_74893_6_ && Config.mobs && Config.spawnVillager) { for (int i = this.villagersSpawned; i < p_74893_6_; ++i) { @@ -1789,18 +1790,18 @@ public class StructureVillage this.tablePosition = rand.zrange(3); } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setInt("T", this.tablePosition); - tagCompound.setBool("C", this.isTallHouse); + super.writeStructureToNBT(tagCompound); + tagCompound.setInteger("T", this.tablePosition); + tagCompound.setBoolean("C", this.isTallHouse); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.tablePosition = tagCompound.getInt("T"); - this.isTallHouse = tagCompound.getBool("C"); + super.readStructureFromNBT(tagCompound); + this.tablePosition = tagCompound.getInteger("T"); + this.isTallHouse = tagCompound.getBoolean("C"); } public static StructureVillage.WoodHut func_175853_a(StructureVillage.Start start, List p_175853_1_, Random rand, int p_175853_3_, int p_175853_4_, int p_175853_5_, Facing facing, int p_175853_7_) @@ -1867,7 +1868,7 @@ public class StructureVillage this.setBlockState(worldIn, Blocks.air.getState(), 1, 2, 0, structureBoundingBoxIn); this.placeDoorCurrentPosition(worldIn, structureBoundingBoxIn, randomIn, 1, 1, 0, Facing.getHorizontal(this.getMetadataWithOffset(Blocks.oak_door, 1))); - if (this.getBlockStateFromPos(worldIn, 1, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 1, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) + if (this.getBlockStateFromPos(worldIn, 1, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 1, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 1, 0, -1, structureBoundingBoxIn); } @@ -1901,16 +1902,16 @@ public class StructureVillage this.boundingBox = p_i45565_4_; } - protected void writeTags(TagObject tagCompound) + protected void writeStructureToNBT(NBTTagCompound tagCompound) { - super.writeTags(tagCompound); - tagCompound.setBool("VSpawn", this.villagerSpawned); + super.writeStructureToNBT(tagCompound); + tagCompound.setBoolean("VSpawn", this.villagerSpawned); } - protected void readTags(TagObject tagCompound) + protected void readStructureFromNBT(NBTTagCompound tagCompound) { - super.readTags(tagCompound); - this.villagerSpawned = tagCompound.getBool("VSpawn"); + super.readStructureFromNBT(tagCompound); + this.villagerSpawned = tagCompound.getBoolean("VSpawn"); } public static StructureVillage.Cage func_175853_a(StructureVillage.Start start, List p_175853_1_, Random rand, int p_175853_3_, int p_175853_4_, int p_175853_5_, Facing facing, int p_175853_7_) @@ -1921,7 +1922,7 @@ public class StructureVillage protected void spawnVillager(WorldServer worldIn, StructureBoundingBox p_74893_2_, int x, int y, int z) { - if (!this.villagerSpawned && SVars.mobs && SVars.spawnCageMobs) + if (!this.villagerSpawned && Config.mobs && Config.spawnCagedVillager) { int j = this.getXWithOffset(x, z); int k = this.getYWithOffset(y); diff --git a/server/src/main/java/server/worldgen/tree/WorldGenBaseTree.java b/server/src/server/worldgen/tree/WorldGenBaseTree.java similarity index 92% rename from server/src/main/java/server/worldgen/tree/WorldGenBaseTree.java rename to server/src/server/worldgen/tree/WorldGenBaseTree.java index 5858316..c5cacd0 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenBaseTree.java +++ b/server/src/server/worldgen/tree/WorldGenBaseTree.java @@ -1,11 +1,11 @@ package server.worldgen.tree; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockCocoa; -import common.block.foliage.BlockLeaves; -import common.block.foliage.BlockVine; +import common.block.BlockCocoa; +import common.block.BlockLeaves; +import common.block.BlockVine; import common.init.Blocks; +import common.material.Material; import common.properties.PropertyBool; import common.rng.Random; import common.util.BlockPos; @@ -116,7 +116,7 @@ public class WorldGenBaseTree extends WorldGenTree BlockPos blockpos = new BlockPos(k1, i3, i2); Block block = worldIn.getState(blockpos).getBlock(); - if (block == Blocks.air || block.getMaterial() == Material.LEAVES || block.getMaterial() == Material.BUSH) + if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves || block.getMaterial() == Material.vine) { this.setBlockAndNotifyAdequately(worldIn, blockpos, this.metaLeaves.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(blockpos))); } @@ -129,7 +129,7 @@ public class WorldGenBaseTree extends WorldGenTree { Block block2 = worldIn.getState(position.up(j3)).getBlock(); - if (block2 == Blocks.air || block2.getMaterial() == Material.LEAVES || block2.getMaterial() == Material.BUSH) + if (block2.getMaterial() == Material.air || block2.getMaterial() == Material.leaves || block2.getMaterial() == Material.vine) { this.setBlockAndNotifyAdequately(worldIn, position.up(j3), this.metaWood); @@ -172,29 +172,29 @@ public class WorldGenBaseTree extends WorldGenTree { blockpos$mutableblockpos1.set(l4, k3, i5); - if (worldIn.getState(blockpos$mutableblockpos1).getBlock().getMaterial() == Material.LEAVES) + if (worldIn.getState(blockpos$mutableblockpos1).getBlock().getMaterial() == Material.leaves) { BlockPos blockpos2 = blockpos$mutableblockpos1.west(); BlockPos blockpos3 = blockpos$mutableblockpos1.east(); BlockPos blockpos4 = blockpos$mutableblockpos1.north(); BlockPos blockpos1 = blockpos$mutableblockpos1.south(); - if (rand.zrange(4) == 0 && worldIn.getState(blockpos2).getBlock() == Blocks.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos2).getBlock().getMaterial() == Material.air) { this.func_181650_b(worldIn, blockpos2, BlockVine.EAST); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos3).getBlock() == Blocks.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos3).getBlock().getMaterial() == Material.air) { this.func_181650_b(worldIn, blockpos3, BlockVine.WEST); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos4).getBlock() == Blocks.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos4).getBlock().getMaterial() == Material.air) { this.func_181650_b(worldIn, blockpos4, BlockVine.SOUTH); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos1).getBlock() == Blocks.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos1).getBlock().getMaterial() == Material.air) { this.func_181650_b(worldIn, blockpos1, BlockVine.NORTH); } @@ -248,7 +248,7 @@ public class WorldGenBaseTree extends WorldGenTree this.func_181651_a(p_181650_1_, p_181650_2_, p_181650_3_); int i = 4; - for (p_181650_2_ = p_181650_2_.down(); p_181650_1_.getState(p_181650_2_).getBlock() == Blocks.air && i > 0; --i) + for (p_181650_2_ = p_181650_2_.down(); p_181650_1_.getState(p_181650_2_).getBlock().getMaterial() == Material.air && i > 0; --i) { this.func_181651_a(p_181650_1_, p_181650_2_, p_181650_3_); p_181650_2_ = p_181650_2_.down(); diff --git a/server/src/main/java/server/worldgen/tree/WorldGenBigTree.java b/server/src/server/worldgen/tree/WorldGenBigTree.java similarity index 97% rename from server/src/main/java/server/worldgen/tree/WorldGenBigTree.java rename to server/src/server/worldgen/tree/WorldGenBigTree.java index 4daf686..ad648bb 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenBigTree.java +++ b/server/src/server/worldgen/tree/WorldGenBigTree.java @@ -3,11 +3,11 @@ package server.worldgen.tree; import java.util.List; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockLeaves; -import common.block.foliage.BlockLog; +import common.block.BlockLeaves; +import common.block.BlockLog; import common.collect.Lists; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.util.ExtMath; @@ -125,9 +125,9 @@ public class WorldGenBigTree extends WorldGenTree if (Math.pow((double)Math.abs(j) + 0.5D, 2.0D) + Math.pow((double)Math.abs(k) + 0.5D, 2.0D) <= (double)(p_181631_2_ * p_181631_2_)) { BlockPos blockpos = p_181631_1_.add(j, 0, k); - Block block = this.world.getState(blockpos).getBlock(); + Material material = this.world.getState(blockpos).getBlock().getMaterial(); - if (block == Blocks.air || block.getMaterial() == Material.LEAVES) + if (material == Material.air || material == Material.leaves) { this.setBlockAndNotifyAdequately(this.world, blockpos, p_181631_3_); } diff --git a/server/src/main/java/server/worldgen/tree/WorldGenBirch.java b/server/src/server/worldgen/tree/WorldGenBirch.java similarity index 93% rename from server/src/main/java/server/worldgen/tree/WorldGenBirch.java rename to server/src/server/worldgen/tree/WorldGenBirch.java index 58bdda1..0659ee8 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenBirch.java +++ b/server/src/server/worldgen/tree/WorldGenBirch.java @@ -1,9 +1,9 @@ package server.worldgen.tree; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockLeaves; +import common.block.BlockLeaves; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.world.State; @@ -101,7 +101,7 @@ public class WorldGenBirch extends WorldGenTree BlockPos blockpos = new BlockPos(i3, i2, k1); Block block = worldIn.getState(blockpos).getBlock(); - if (block == Blocks.air || block.getMaterial() == Material.LEAVES) + if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves) { this.setBlockAndNotifyAdequately(worldIn, blockpos, leavesBlock.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(blockpos))); } @@ -114,7 +114,7 @@ public class WorldGenBirch extends WorldGenTree { Block block2 = worldIn.getState(position.up(j2)).getBlock(); - if (block2 == Blocks.air || block2.getMaterial() == Material.LEAVES) + if (block2.getMaterial() == Material.air || block2.getMaterial() == Material.leaves) { this.setBlockAndNotifyAdequately(worldIn, position.up(j2), logBlock); } diff --git a/server/src/main/java/server/worldgen/tree/WorldGenDarkOak.java b/server/src/server/worldgen/tree/WorldGenDarkOak.java similarity index 96% rename from server/src/main/java/server/worldgen/tree/WorldGenDarkOak.java rename to server/src/server/worldgen/tree/WorldGenDarkOak.java index 65286b2..09f1126 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenDarkOak.java +++ b/server/src/server/worldgen/tree/WorldGenDarkOak.java @@ -1,9 +1,9 @@ package server.worldgen.tree; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockLeaves; +import common.block.BlockLeaves; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.util.Facing; @@ -66,9 +66,9 @@ public class WorldGenDarkOak extends WorldGenTree int k2 = k + j2; BlockPos blockpos1 = new BlockPos(k1, k2, l1); - Block block1 = worldIn.getState(blockpos1).getBlock(); + Material material = worldIn.getState(blockpos1).getBlock().getMaterial(); - if (block1 == Blocks.air || block1.getMaterial() == Material.LEAVES) + if (material == Material.air || material == Material.leaves) { this.func_181639_b(worldIn, blockpos1); this.func_181639_b(worldIn, blockpos1.east()); @@ -210,7 +210,7 @@ public class WorldGenDarkOak extends WorldGenTree BlockPos blockpos = new BlockPos(p_150526_2_, p_150526_3_, p_150526_4_); Block block = worldIn.getState(blockpos).getBlock(); - if (block == Blocks.air) + if (block.getMaterial() == Material.air) { this.setBlockAndNotifyAdequately(worldIn, blockpos, leavesBlock.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(blockpos))); } diff --git a/server/src/main/java/server/worldgen/tree/WorldGenHugeTree.java b/server/src/server/worldgen/tree/WorldGenHugeTree.java similarity index 91% rename from server/src/main/java/server/worldgen/tree/WorldGenHugeTree.java rename to server/src/server/worldgen/tree/WorldGenHugeTree.java index 05ddd76..c5d50f1 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenHugeTree.java +++ b/server/src/server/worldgen/tree/WorldGenHugeTree.java @@ -1,9 +1,9 @@ package server.worldgen.tree; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockLeaves; +import common.block.BlockLeaves; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.world.State; @@ -119,9 +119,9 @@ public abstract class WorldGenHugeTree extends WorldGenTree if (j * j + k * k <= i || l * l + i1 * i1 <= i || j * j + i1 * i1 <= i || l * l + k * k <= i) { BlockPos blockpos = p_175925_2_.add(j, 0, k); - Block block = worldIn.getState(blockpos).getBlock(); + Material material = worldIn.getState(blockpos).getBlock().getMaterial(); - if (block == Blocks.air || block.getMaterial() == Material.LEAVES) + if (material == Material.air || material == Material.leaves) { this.setBlockAndNotifyAdequately(worldIn, blockpos, this.leavesMetadata.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(blockpos))); } @@ -141,9 +141,9 @@ public abstract class WorldGenHugeTree extends WorldGenTree if (j * j + k * k <= i) { BlockPos blockpos = p_175928_2_.add(j, 0, k); - Block block = worldIn.getState(blockpos).getBlock(); + Material material = worldIn.getState(blockpos).getBlock().getMaterial(); - if (block == Blocks.air || block.getMaterial() == Material.LEAVES) + if (material == Material.air || material == Material.leaves) { this.setBlockAndNotifyAdequately(worldIn, blockpos, this.leavesMetadata.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(blockpos))); } diff --git a/server/src/main/java/server/worldgen/tree/WorldGenJungle.java b/server/src/server/worldgen/tree/WorldGenJungle.java similarity index 99% rename from server/src/main/java/server/worldgen/tree/WorldGenJungle.java rename to server/src/server/worldgen/tree/WorldGenJungle.java index ba30cdb..1edd2d4 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenJungle.java +++ b/server/src/server/worldgen/tree/WorldGenJungle.java @@ -1,6 +1,6 @@ package server.worldgen.tree; -import common.block.foliage.BlockVine; +import common.block.BlockVine; import common.init.Blocks; import common.properties.PropertyBool; import common.rng.Random; diff --git a/server/src/main/java/server/worldgen/tree/WorldGenPine.java b/server/src/server/worldgen/tree/WorldGenPine.java similarity index 89% rename from server/src/main/java/server/worldgen/tree/WorldGenPine.java rename to server/src/server/worldgen/tree/WorldGenPine.java index 26b9820..4c90945 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenPine.java +++ b/server/src/server/worldgen/tree/WorldGenPine.java @@ -1,9 +1,9 @@ package server.worldgen.tree; import common.block.Block; -import common.block.Material; -import common.block.natural.BlockDirt; +import common.block.BlockDirt; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.util.ExtMath; @@ -39,7 +39,7 @@ public class WorldGenPine extends WorldGenHugeTree { Block block = worldIn.getState(position.up(j)).getBlock(); - if (block == Blocks.air || block.getMaterial() == Material.LEAVES) + if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves) { this.setBlockAndNotifyAdequately(worldIn, position.up(j), this.woodMetadata); } @@ -48,21 +48,21 @@ public class WorldGenPine extends WorldGenHugeTree { block = worldIn.getState(position.add(1, j, 0)).getBlock(); - if (block == Blocks.air || block.getMaterial() == Material.LEAVES) + if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves) { this.setBlockAndNotifyAdequately(worldIn, position.add(1, j, 0), this.woodMetadata); } block = worldIn.getState(position.add(1, j, 1)).getBlock(); - if (block == Blocks.air || block.getMaterial() == Material.LEAVES) + if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves) { this.setBlockAndNotifyAdequately(worldIn, position.add(1, j, 1), this.woodMetadata); } block = worldIn.getState(position.add(0, j, 1)).getBlock(); - if (block == Blocks.air || block.getMaterial() == Material.LEAVES) + if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves) { this.setBlockAndNotifyAdequately(worldIn, position.add(0, j, 1), this.woodMetadata); } @@ -134,7 +134,7 @@ public class WorldGenPine extends WorldGenHugeTree break; } - if (block != Blocks.air && i < 0) + if (block.getMaterial() != Material.air && i < 0) { break; } diff --git a/server/src/main/java/server/worldgen/tree/WorldGenSavanna.java b/server/src/server/worldgen/tree/WorldGenSavanna.java similarity index 92% rename from server/src/main/java/server/worldgen/tree/WorldGenSavanna.java rename to server/src/server/worldgen/tree/WorldGenSavanna.java index dfd389b..c348cca 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenSavanna.java +++ b/server/src/server/worldgen/tree/WorldGenSavanna.java @@ -1,9 +1,9 @@ package server.worldgen.tree; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockLeaves; +import common.block.BlockLeaves; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.util.Facing; @@ -95,9 +95,9 @@ public class WorldGenSavanna extends WorldGenTree } BlockPos blockpos = new BlockPos(i3, i2, j1); - Block block1 = worldIn.getState(blockpos).getBlock(); + Material material = worldIn.getState(blockpos).getBlock().getMaterial(); - if (block1 == Blocks.air || block1.getMaterial() == Material.LEAVES) + if (material == Material.air || material == Material.leaves) { this.func_181642_b(worldIn, blockpos); k1 = i2; @@ -149,9 +149,9 @@ public class WorldGenSavanna extends WorldGenTree i3 += enumfacing1.getFrontOffsetX(); j1 += enumfacing1.getFrontOffsetZ(); BlockPos blockpos1 = new BlockPos(i3, j2, j1); - Block block1 = worldIn.getState(blockpos1).getBlock(); + Material material1 = worldIn.getState(blockpos1).getBlock().getMaterial(); - if (block1 == Blocks.air || block1.getMaterial() == Material.LEAVES) + if (material1 == Material.air || material1 == Material.leaves) { this.func_181642_b(worldIn, blockpos1); k1 = j2; @@ -209,9 +209,9 @@ public class WorldGenSavanna extends WorldGenTree private void func_175924_b(WorldServer worldIn, BlockPos p_175924_2_) { - Block block = worldIn.getState(p_175924_2_).getBlock(); + Material material = worldIn.getState(p_175924_2_).getBlock().getMaterial(); - if (block == Blocks.air || block.getMaterial() == Material.LEAVES) + if (material == Material.air || material == Material.leaves) { this.setBlockAndNotifyAdequately(worldIn, p_175924_2_, field_181644_b.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(p_175924_2_))); } diff --git a/server/src/main/java/server/worldgen/tree/WorldGenSwamp.java b/server/src/server/worldgen/tree/WorldGenSwamp.java similarity index 89% rename from server/src/main/java/server/worldgen/tree/WorldGenSwamp.java rename to server/src/server/worldgen/tree/WorldGenSwamp.java index 276ed3c..f8ff143 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenSwamp.java +++ b/server/src/server/worldgen/tree/WorldGenSwamp.java @@ -1,10 +1,10 @@ package server.worldgen.tree; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockLeaves; -import common.block.foliage.BlockVine; +import common.block.BlockLeaves; +import common.block.BlockVine; import common.init.Blocks; +import common.material.Material; import common.properties.PropertyBool; import common.rng.Random; import common.util.BlockPos; @@ -28,7 +28,7 @@ public class WorldGenSwamp extends WorldGenTree { int i; - for (i = rand.zrange(4) + 5; worldIn.getState(position.down()).getBlock().getMaterial() == Material.WATER; position = position.down()) + for (i = rand.zrange(4) + 5; worldIn.getState(position.down()).getBlock().getMaterial() == Material.water; position = position.down()) { ; } @@ -61,7 +61,7 @@ public class WorldGenSwamp extends WorldGenTree { Block block = worldIn.getState(blockpos$mutableblockpos.set(l, j, i1)).getBlock(); - if (block != Blocks.air && block.getMaterial() != Material.LEAVES) + if (block.getMaterial() != Material.air && block.getMaterial() != Material.leaves) { if (block != Blocks.water && block != Blocks.flowing_water) { @@ -123,7 +123,7 @@ public class WorldGenSwamp extends WorldGenTree { Block block2 = worldIn.getState(position.up(i2)).getBlock(); - if (block2 == Blocks.air || block2.getMaterial() == Material.LEAVES || block2 == Blocks.flowing_water || block2 == Blocks.water) + if (block2.getMaterial() == Material.air || block2.getMaterial() == Material.leaves || block2 == Blocks.flowing_water || block2 == Blocks.water) { this.setBlockAndNotifyAdequately(worldIn, position.up(i2), field_181648_a); } @@ -141,29 +141,29 @@ public class WorldGenSwamp extends WorldGenTree { blockpos$mutableblockpos1.set(i4, j2, j4); - if (worldIn.getState(blockpos$mutableblockpos1).getBlock().getMaterial() == Material.LEAVES) + if (worldIn.getState(blockpos$mutableblockpos1).getBlock().getMaterial() == Material.leaves) { BlockPos blockpos3 = blockpos$mutableblockpos1.west(); BlockPos blockpos4 = blockpos$mutableblockpos1.east(); BlockPos blockpos1 = blockpos$mutableblockpos1.north(); BlockPos blockpos2 = blockpos$mutableblockpos1.south(); - if (rand.zrange(4) == 0 && worldIn.getState(blockpos3).getBlock() == Blocks.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos3).getBlock().getMaterial() == Material.air) { this.func_181647_a(worldIn, blockpos3, BlockVine.EAST); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos4).getBlock() == Blocks.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos4).getBlock().getMaterial() == Material.air) { this.func_181647_a(worldIn, blockpos4, BlockVine.WEST); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos1).getBlock() == Blocks.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos1).getBlock().getMaterial() == Material.air) { this.func_181647_a(worldIn, blockpos1, BlockVine.SOUTH); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos2).getBlock() == Blocks.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos2).getBlock().getMaterial() == Material.air) { this.func_181647_a(worldIn, blockpos2, BlockVine.NORTH); } @@ -192,7 +192,7 @@ public class WorldGenSwamp extends WorldGenTree this.setBlockAndNotifyAdequately(p_181647_1_, p_181647_2_, iblockstate); int i = 4; - for (p_181647_2_ = p_181647_2_.down(); p_181647_1_.getState(p_181647_2_).getBlock() == Blocks.air && i > 0; --i) + for (p_181647_2_ = p_181647_2_.down(); p_181647_1_.getState(p_181647_2_).getBlock().getMaterial() == Material.air && i > 0; --i) { this.setBlockAndNotifyAdequately(p_181647_1_, p_181647_2_, iblockstate); p_181647_2_ = p_181647_2_.down(); diff --git a/server/src/main/java/server/worldgen/tree/WorldGenTaiga1.java b/server/src/server/worldgen/tree/WorldGenTaiga1.java similarity index 96% rename from server/src/main/java/server/worldgen/tree/WorldGenTaiga1.java rename to server/src/server/worldgen/tree/WorldGenTaiga1.java index 2ae3859..a3fed91 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenTaiga1.java +++ b/server/src/server/worldgen/tree/WorldGenTaiga1.java @@ -1,9 +1,9 @@ package server.worldgen.tree; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockLeaves; +import common.block.BlockLeaves; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.world.State; @@ -115,7 +115,7 @@ public class WorldGenTaiga1 extends WorldGenTree { Block block1 = worldIn.getState(position.up(i3)).getBlock(); - if (block1 == Blocks.air || block1.getMaterial() == Material.LEAVES) + if (block1.getMaterial() == Material.air || block1.getMaterial() == Material.leaves) { this.setBlockAndNotifyAdequately(worldIn, position.up(i3), field_181636_a); } diff --git a/server/src/main/java/server/worldgen/tree/WorldGenTaiga2.java b/server/src/server/worldgen/tree/WorldGenTaiga2.java similarity index 94% rename from server/src/main/java/server/worldgen/tree/WorldGenTaiga2.java rename to server/src/server/worldgen/tree/WorldGenTaiga2.java index ba017a3..681bd4f 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenTaiga2.java +++ b/server/src/server/worldgen/tree/WorldGenTaiga2.java @@ -1,9 +1,9 @@ package server.worldgen.tree; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockLeaves; +import common.block.BlockLeaves; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import common.world.State; @@ -55,7 +55,7 @@ public class WorldGenTaiga2 extends WorldGenTree { Block block = worldIn.getState(blockpos$mutableblockpos.set(k1, i1, l1)).getBlock(); - if (block != Blocks.air && block.getMaterial() != Material.LEAVES) + if (block.getMaterial() != Material.air && block.getMaterial() != Material.leaves) { flag = false; } @@ -130,7 +130,7 @@ public class WorldGenTaiga2 extends WorldGenTree { Block block2 = worldIn.getState(position.up(k4)).getBlock(); - if (block2 == Blocks.air || block2.getMaterial() == Material.LEAVES) + if (block2.getMaterial() == Material.air || block2.getMaterial() == Material.leaves) { this.setBlockAndNotifyAdequately(worldIn, position.up(k4), field_181645_a); } diff --git a/server/src/main/java/server/worldgen/tree/WorldGenTree.java b/server/src/server/worldgen/tree/WorldGenTree.java similarity index 70% rename from server/src/main/java/server/worldgen/tree/WorldGenTree.java rename to server/src/server/worldgen/tree/WorldGenTree.java index 412f0e6..964385a 100755 --- a/server/src/main/java/server/worldgen/tree/WorldGenTree.java +++ b/server/src/server/worldgen/tree/WorldGenTree.java @@ -1,10 +1,10 @@ package server.worldgen.tree; import common.block.Block; -import common.block.Material; -import common.block.foliage.BlockLog; -import common.block.foliage.BlockSapling; +import common.block.BlockLog; +import common.block.BlockSapling; import common.init.Blocks; +import common.material.Material; import common.rng.Random; import common.util.BlockPos; import server.world.WorldServer; @@ -19,7 +19,8 @@ public abstract class WorldGenTree extends FeatureGenerator protected boolean canBeReplaced(Block block) { - return block == Blocks.air || block.getMaterial() == Material.LEAVES || block == Blocks.grass || block == Blocks.dirt || block instanceof BlockLog || block instanceof BlockSapling || block == Blocks.vine; + Material material = block.getMaterial(); + return material == Material.air || material == Material.leaves || block == Blocks.grass || block == Blocks.dirt || block instanceof BlockLog || block instanceof BlockSapling || block == Blocks.vine; } public void prepare() diff --git a/settings.gradle.kts b/settings.gradle.kts deleted file mode 100644 index 60f7529..0000000 --- a/settings.gradle.kts +++ /dev/null @@ -1,5 +0,0 @@ - -rootProject.name = "TCR" -include("common") -include("client") -include("server")