diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/CoreContainer.java b/src/main/java/mcp/mobius/mobiuscore/asm/CoreContainer.java index 1a03982..917c0fc 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/CoreContainer.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/CoreContainer.java @@ -4,31 +4,27 @@ import com.google.common.eventbus.EventBus; import cpw.mods.fml.common.DummyModContainer; import cpw.mods.fml.common.LoadController; import cpw.mods.fml.common.ModMetadata; - import java.util.Arrays; public class CoreContainer extends DummyModContainer { - public CoreContainer() - { - super(new ModMetadata()); - - ModMetadata md = getMetadata(); - md.modId = "MobiusCore"; - md.name = "MobiusCore"; - md.version = "@MOD_VERSION@"; - md.credits = "ProfMobius"; - md.authorList = Arrays.asList("ProfMobius"); - md.description = ""; - md.url = "profmobius.blogspot.com"; - } + public CoreContainer() { + super(new ModMetadata()); + + ModMetadata md = getMetadata(); + md.modId = "MobiusCore"; + md.name = "MobiusCore"; + md.version = "@MOD_VERSION@"; + md.credits = "ProfMobius"; + md.authorList = Arrays.asList("ProfMobius"); + md.description = ""; + md.url = "profmobius.blogspot.com"; + } @Override - public boolean registerBus(EventBus bus, LoadController controller) - { - //bus.register(this); - // this needs to return true, otherwise the mod will be deactivated by FML + public boolean registerBus(EventBus bus, LoadController controller) { + // bus.register(this); + // this needs to return true, otherwise the mod will be deactivated by FML return true; - } - + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/CoreDescription.java b/src/main/java/mcp/mobius/mobiuscore/asm/CoreDescription.java index 3ac7ce2..0744857 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/CoreDescription.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/CoreDescription.java @@ -1,43 +1,42 @@ package mcp.mobius.mobiuscore.asm; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.io.File; import java.util.Map; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; @IFMLLoadingPlugin.TransformerExclusions("mcp.mobius.mobiuscore.asm") public class CoreDescription implements IFMLLoadingPlugin { public static final Logger log = LogManager.getLogger("MobiusCore"); - @Override - public String[] getASMTransformerClass() { - return new String[] { "mcp.mobius.mobiuscore.asm.CoreTransformer" }; - } + @Override + public String[] getASMTransformerClass() { + return new String[] {"mcp.mobius.mobiuscore.asm.CoreTransformer"}; + } - @Override - public String getModContainerClass() { - return "mcp.mobius.mobiuscore.asm.CoreContainer"; - } + @Override + public String getModContainerClass() { + return "mcp.mobius.mobiuscore.asm.CoreContainer"; + } - @Override - public String getSetupClass() { - return null; - } + @Override + public String getSetupClass() { + return null; + } - @Override - public void injectData(Map data) { - if (data.containsKey("coremodLocation")) { - location = (File) data.get("coremodLocation"); - } - } + @Override + public void injectData(Map data) { + if (data.containsKey("coremodLocation")) { + location = (File) data.get("coremodLocation"); + } + } - public static File location; + public static File location; - @Override - public String getAccessTransformerClass() { - return null; - } + @Override + public String getAccessTransformerClass() { + return null; + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/CoreTransformer.java b/src/main/java/mcp/mobius/mobiuscore/asm/CoreTransformer.java index c02b83c..e9b3d39 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/CoreTransformer.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/CoreTransformer.java @@ -1,5 +1,7 @@ package mcp.mobius.mobiuscore.asm; +import java.io.FileNotFoundException; +import java.io.PrintWriter; import mcp.mobius.mobiuscore.asm.transformers.common.*; import mcp.mobius.mobiuscore.asm.transformers.forge.TransformerWorld; import mcp.mobius.mobiuscore.asm.transformers.kcauldron.TransformerWorldKCauldron; @@ -10,87 +12,82 @@ import org.objectweb.asm.ClassReader; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.util.TraceClassVisitor; -import java.io.FileNotFoundException; -import java.io.PrintWriter; - public class CoreTransformer implements IClassTransformer { - - public CoreTransformer(){ - super(); - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes) { - try{ - - //TransformerBase.dumpChecksum(bytes, name, srgname); - - if (srgname.equals("net.minecraft.world.World")) { - ObfTable.ServerType serverType = ObfTable.getServerType(); - if (serverType == ObfTable.ServerType.Forge) { - bytes = new TransformerWorld().transform(name, srgname, bytes); - } else if (serverType == ObfTable.ServerType.Cauldron) { - bytes = new TransformerWorldCauldron().transform(name, srgname, bytes); - } else if (serverType == ObfTable.ServerType.KCauldron) { - bytes = new TransformerWorldKCauldron().transform(name, srgname, bytes); - } else if (serverType == ObfTable.ServerType.Thermos) { - bytes = new TransformerWorldThermos().transform(name, srgname, bytes); - } - } - - if (srgname.equals("net.minecraft.world.WorldServer")){ - bytes = new TransformerWorldServer().transform(name, srgname, bytes); - } + public CoreTransformer() { + super(); + } - if (srgname.equals("net.minecraft.util.MessageSerializer")){ - bytes = new TransformerMessageSerializer().transform(name, srgname, bytes); - } - - if (srgname.equals("net.minecraft.util.MessageDeserializer")){ - bytes = new TransformerMessageDeserializer().transform(name, srgname, bytes); - } - - if (srgname.equals("net.minecraft.client.renderer.entity.RenderManager")){ - bytes = new TransformerRenderManager().transform(name, srgname, bytes); - } - - if (srgname.equals("net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher")){ - bytes = new TransformerTERenderer().transform(name, srgname, bytes); - } - - if (srgname.equals("cpw.mods.fml.common.FMLCommonHandler")){ - bytes = new TransformerFMLCommonHandler().transform(name, srgname, bytes); - } - - if (srgname.equals("cpw.mods.fml.common.network.FMLOutboundHandler")){ - bytes = new TransformerFMLOutboundHandler().transform(name, srgname, bytes); - } - - //if (srgname.equals("cpw.mods.fml.common.network.internal.FMLProxyPacket")){ - // bytes = new TransformerFMLProxyPacket().transform(name, srgname, bytes); - //} - - if (srgname.equals("cpw.mods.fml.common.eventhandler.ASMEventHandler")){ - bytes = new TransformerASMEventHandler().transform(name, srgname, bytes); - } - - } catch (Exception e){ - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); - try{ - PrintWriter pw = new PrintWriter(String.format("%s.asm", srgname.replaceAll("/", "."))); - TraceClassVisitor cv = new TraceClassVisitor(pw); - classReader.accept(cv, 0); - pw.flush(); - throw new RuntimeException(e); - } catch (FileNotFoundException f){ - throw new RuntimeException("DERP"); - } - } - return bytes; - } + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + try { + // TransformerBase.dumpChecksum(bytes, name, srgname); + if (srgname.equals("net.minecraft.world.World")) { + ObfTable.ServerType serverType = ObfTable.getServerType(); + + if (serverType == ObfTable.ServerType.Forge) { + bytes = new TransformerWorld().transform(name, srgname, bytes); + } else if (serverType == ObfTable.ServerType.Cauldron) { + bytes = new TransformerWorldCauldron().transform(name, srgname, bytes); + } else if (serverType == ObfTable.ServerType.KCauldron) { + bytes = new TransformerWorldKCauldron().transform(name, srgname, bytes); + } else if (serverType == ObfTable.ServerType.Thermos) { + bytes = new TransformerWorldThermos().transform(name, srgname, bytes); + } + } + + if (srgname.equals("net.minecraft.world.WorldServer")) { + bytes = new TransformerWorldServer().transform(name, srgname, bytes); + } + + if (srgname.equals("net.minecraft.util.MessageSerializer")) { + bytes = new TransformerMessageSerializer().transform(name, srgname, bytes); + } + + if (srgname.equals("net.minecraft.util.MessageDeserializer")) { + bytes = new TransformerMessageDeserializer().transform(name, srgname, bytes); + } + + if (srgname.equals("net.minecraft.client.renderer.entity.RenderManager")) { + bytes = new TransformerRenderManager().transform(name, srgname, bytes); + } + + if (srgname.equals("net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher")) { + bytes = new TransformerTERenderer().transform(name, srgname, bytes); + } + + if (srgname.equals("cpw.mods.fml.common.FMLCommonHandler")) { + bytes = new TransformerFMLCommonHandler().transform(name, srgname, bytes); + } + + if (srgname.equals("cpw.mods.fml.common.network.FMLOutboundHandler")) { + bytes = new TransformerFMLOutboundHandler().transform(name, srgname, bytes); + } + + // if (srgname.equals("cpw.mods.fml.common.network.internal.FMLProxyPacket")){ + // bytes = new TransformerFMLProxyPacket().transform(name, srgname, bytes); + // } + + if (srgname.equals("cpw.mods.fml.common.eventhandler.ASMEventHandler")) { + bytes = new TransformerASMEventHandler().transform(name, srgname, bytes); + } + + } catch (Exception e) { + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); + classReader.accept(classNode, 0); + try { + PrintWriter pw = new PrintWriter(String.format("%s.asm", srgname.replaceAll("/", "."))); + TraceClassVisitor cv = new TraceClassVisitor(pw); + classReader.accept(cv, 0); + pw.flush(); + throw new RuntimeException(e); + } catch (FileNotFoundException f) { + throw new RuntimeException("DERP"); + } + } + return bytes; + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/MethodDescriptor.java b/src/main/java/mcp/mobius/mobiuscore/asm/MethodDescriptor.java index 1a130c4..2d8f48b 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/MethodDescriptor.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/MethodDescriptor.java @@ -2,25 +2,30 @@ package mcp.mobius.mobiuscore.asm; public final class MethodDescriptor { - private final String methodName; - private final String descriptor; - //public String vanillaDesc; - //public String coremodDesc; + private final String methodName; + private final String descriptor; + // public String vanillaDesc; + // public String coremodDesc; + + public MethodDescriptor(String name, String desc) { + this.methodName = name; + this.descriptor = desc; + } + + public String getMethodName() { + return this.methodName; + } + + public String getDescriptor() { + return this.descriptor; + } + + /* + public MethodDescriptor(String name, String vdesc, String cdesc){ + this.methodName = name; + this.vanillaDesc = vdesc; + this.coremodDesc = cdesc; + } + */ - public MethodDescriptor(String name, String desc){ - this.methodName = name; - this.descriptor = desc; - } - - public String getMethodName(){ return this.methodName; } - public String getDescriptor(){ return this.descriptor; } - - /* - public MethodDescriptor(String name, String vdesc, String cdesc){ - this.methodName = name; - this.vanillaDesc = vdesc; - this.coremodDesc = cdesc; - } - */ - } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/ObfTable.java b/src/main/java/mcp/mobius/mobiuscore/asm/ObfTable.java index d46a0e4..178467f 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/ObfTable.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/ObfTable.java @@ -1,153 +1,234 @@ package mcp.mobius.mobiuscore.asm; import cpw.mods.fml.common.FMLCommonHandler; +import java.io.IOException; import net.minecraft.launchwrapper.LaunchClassLoader; -import java.io.IOException; - public enum ObfTable { - WORLD_UPDATEENTITIES ("ahb", "h", "()V", "net/minecraft/world/World", "updateEntities", "()V"), - WORLD_UPDATEENTITY ("ahb", "g", "(Lsa;)V", "net/minecraft/world/World", "updateEntity", "(Lnet/minecraft/entity/Entity;)V"), - TILEENTITY_UPDATEENTITY ("aor", "h", "()V", "net/minecraft/tileentity/TileEntity", "updateEntity", "()V"), + WORLD_UPDATEENTITIES("ahb", "h", "()V", "net/minecraft/world/World", "updateEntities", "()V"), + WORLD_UPDATEENTITY( + "ahb", "g", "(Lsa;)V", "net/minecraft/world/World", "updateEntity", "(Lnet/minecraft/entity/Entity;)V"), + TILEENTITY_UPDATEENTITY("aor", "h", "()V", "net/minecraft/tileentity/TileEntity", "updateEntity", "()V"), - WORLDSERVER_TICK ("mt", "b", "()V", "net/minecraft/world/WorldServer", "tick", "()V"), - WORLD_PROVIDER ("mt", "t", "Laqo;", "net/minecraft/world/WorldServer", "provider", "Lnet/minecraft/world/WorldProvider;"), - WORLDPROVIDER_DIMID ("aqo", "i", "I", "net/minecraft/world/WorldProvider", "dimensionId", "I"), - - SERIALIZER_ENCODE ("fa", "a", "(Lio/netty/channel/ChannelHandlerContext;Lft;Lio/netty/buffer/ByteBuf;)V", "net/minecraft/util/MessageSerializer", "encode", "(Lio/netty/channel/ChannelHandlerContext;Lnet/minecraft/network/Packet;Lio/netty/buffer/ByteBuf;)V"), - DESERIALIZER_DECODE ("ez", "decode", "(Lio/netty/channel/ChannelHandlerContext;Lio/netty/buffer/ByteBuf;Ljava/util/List;)V", "net/minecraft/util/MessageDeserializer", "decode", "(Lio/netty/channel/ChannelHandlerContext;Lio/netty/buffer/ByteBuf;Ljava/util/List;)V"), + WORLDSERVER_TICK("mt", "b", "()V", "net/minecraft/world/WorldServer", "tick", "()V"), + WORLD_PROVIDER( + "mt", "t", "Laqo;", "net/minecraft/world/WorldServer", "provider", "Lnet/minecraft/world/WorldProvider;"), + WORLDPROVIDER_DIMID("aqo", "i", "I", "net/minecraft/world/WorldProvider", "dimensionId", "I"), - PACKET_WRITEPACKETDATA ("ft", "b", "(Let;)V", "net/minecraft/network/Packet","writePacketData","(Lnet/minecraft/network/PacketBuffer;)V"), - PACKET_READPACKETDATA ("ft", "a", "(Let;)V", "net/minecraft/network/Packet","readPacketData", "(Lnet/minecraft/network/PacketBuffer;)V"), - PACKET_GENERATEPACKET ("ft", "a", "(Lcom/google/common/collect/BiMap;I)Lpk;", "net/minecraft/network/Packet", "generatePacket", "(Lcom/google/common/collect/BiMap;I)Lnet/minecraft/network/Packet;"), - PACKETBUFFER_READABLE ("et", "readableBytes", "()I", "net/minecraft/network/PacketBuffer", "readableBytes", "()I"), - PACKETBUFFER_CAPACITY ("et", "capacity", "()I", "net/minecraft/network/PacketBuffer", "capacity", "()I"), - - RENDERMANAGER_RENDERENTITY("bnn", "a", "(Lsa;FZ)Z", "net/minecraft/client/renderer/entity/RenderManager", "renderEntityStatic", "(Lnet/minecraft/entity/Entity;FZ)Z"), - RENDERMANAGER_RENDERPOSYAW("bnn", "a", "(Lsa;DDDFF)Z", "net/minecraft/client/renderer/entity/RenderManager", "renderEntityWithPosYaw", "(Lnet/minecraft/entity/Entity;DDDFF)Z"), - RENDERMANAGER_RENDER ("bnn", "a", "(Lsa;DDDFFZ)Z", "net/minecraft/client/renderer/entity/RenderManager", "func_147939_a", "(Lnet/minecraft/entity/Entity;DDDFFZ)Z"), - - TERENDER_RENDERAT ("bml", "a", "(Laor;DDDF)V", "net/minecraft/client/renderer/tileentity/TileEntitySpecialRenderer", "renderTileEntityAt", "(Lnet/minecraft/tileentity/TileEntity;DDDF)V"), - - FMLCH_PREWORLDTICK ("cpw/mods/fml/common/FMLCommonHandler","onPreWorldTick","(Lahb;)V", "cpw/mods/fml/common/FMLCommonHandler","onPreWorldTick","(Lnet/minecraft/world/World;)V"), - FMLCH_POSTWORLDTICK ("cpw/mods/fml/common/FMLCommonHandler","onPostWorldTick","(Lahb;)V", "cpw/mods/fml/common/FMLCommonHandler","onPostWorldTick","(Lnet/minecraft/world/World;)V"), - + SERIALIZER_ENCODE( + "fa", + "a", + "(Lio/netty/channel/ChannelHandlerContext;Lft;Lio/netty/buffer/ByteBuf;)V", + "net/minecraft/util/MessageSerializer", + "encode", + "(Lio/netty/channel/ChannelHandlerContext;Lnet/minecraft/network/Packet;Lio/netty/buffer/ByteBuf;)V"), + DESERIALIZER_DECODE( + "ez", + "decode", + "(Lio/netty/channel/ChannelHandlerContext;Lio/netty/buffer/ByteBuf;Ljava/util/List;)V", + "net/minecraft/util/MessageDeserializer", + "decode", + "(Lio/netty/channel/ChannelHandlerContext;Lio/netty/buffer/ByteBuf;Ljava/util/List;)V"), - FMLPP_PROCESSPACKET ("cpw/mods/fml/common/network/internal/FMLProxyPacket", "a", "(Lfb;)V", "cpw/mods/fml/common/network/internal/FMLProxyPacket", "processPacket", "(Lnet/minecraft/network/INetHandler;)V"), + PACKET_WRITEPACKETDATA( + "ft", + "b", + "(Let;)V", + "net/minecraft/network/Packet", + "writePacketData", + "(Lnet/minecraft/network/PacketBuffer;)V"), + PACKET_READPACKETDATA( + "ft", + "a", + "(Let;)V", + "net/minecraft/network/Packet", + "readPacketData", + "(Lnet/minecraft/network/PacketBuffer;)V"), + PACKET_GENERATEPACKET( + "ft", + "a", + "(Lcom/google/common/collect/BiMap;I)Lpk;", + "net/minecraft/network/Packet", + "generatePacket", + "(Lcom/google/common/collect/BiMap;I)Lnet/minecraft/network/Packet;"), + PACKETBUFFER_READABLE("et", "readableBytes", "()I", "net/minecraft/network/PacketBuffer", "readableBytes", "()I"), + PACKETBUFFER_CAPACITY("et", "capacity", "()I", "net/minecraft/network/PacketBuffer", "capacity", "()I"), - WORLD_INIT ("ahb", "", "(Lazc;Ljava/lang/String;Lahj;Laqo;Lqi;)V", "net/minecraft/world/World", "", "(Lnet/minecraft/world/storage/ISaveHandler;Ljava/lang/String;Lnet/minecraft/world/WorldSettings;Lnet/minecraft/world/WorldProvider;Lnet/minecraft/profiler/Profiler;)V"), - WORLD_LOADEDENTS ("ahb", "e", "Ljava/util/List;", "net/minecraft/world/World", "loadedEntityList", "Ljava/util/List;"), - WORLD_LOADEDTILES ("ahb", "g", "Ljava/util/List;", "net/minecraft/world/World", "loadedTileEntityList", "Ljava/util/List;"), - /* - NETWORKLISTEN_NETWORKTICK ("nc", "c", "()V", "net/minecraft/network/NetworkSystem", "networkTick", "()V"), - TCPCONN_READPACKET ("co", "i", "()Z", "net/minecraft/network/TcpConnection", "readPacket", "()Z"), - TCPCONN_SENDPACKET ("co", "a", "(Z)Ley;", "net/minecraft/network/TcpConnection", "func_74460_a", "(Z)Lnet/minecraft/network/packet/Packet;"), - TCPCONN_NETWORKSOCKET ("co", "j", "Ljava/net/Socket;", "net/minecraft/network/TcpConnection", "networkSocket", "Ljava/net/Socket;"), - MEMCONN_ADDSENDQUEUE ("cn", "a", "(Ley;)V", "net/minecraft/network/MemoryConnection", "addToSendQueue", "(Lnet/minecraft/network/packet/Packet;)V"), - MEMCONN_PROCESSREAD ("cn", "b", "()V", "net/minecraft/network/MemoryConnection", "processReadPackets", "()V"), - MEMCONN_PAIREDCONN ("cn", "d", "Lcn;", "net/minecraft/network/MemoryConnection", "pairedConnection", "Lnet/minecraft/network/MemoryConnection;"), - MEMCONN_PROCESSORCACHE ("cn", "b", "(Ley;)V", "net/minecraft/network/MemoryConnection", "processOrCachePacket", "(Lnet/minecraft/network/packet/Packet;)V"), - MEMCONN_MYNETHANDLER ("cn", "e", "Lez;", "net/minecraft/network/MemoryConnection", "myNetHandler", "Lnet/minecraft/network/packet/NetHandler;"); - */ + RENDERMANAGER_RENDERENTITY( + "bnn", + "a", + "(Lsa;FZ)Z", + "net/minecraft/client/renderer/entity/RenderManager", + "renderEntityStatic", + "(Lnet/minecraft/entity/Entity;FZ)Z"), + RENDERMANAGER_RENDERPOSYAW( + "bnn", + "a", + "(Lsa;DDDFF)Z", + "net/minecraft/client/renderer/entity/RenderManager", + "renderEntityWithPosYaw", + "(Lnet/minecraft/entity/Entity;DDDFF)Z"), + RENDERMANAGER_RENDER( + "bnn", + "a", + "(Lsa;DDDFFZ)Z", + "net/minecraft/client/renderer/entity/RenderManager", + "func_147939_a", + "(Lnet/minecraft/entity/Entity;DDDFFZ)Z"), - //PACKET_PROCESSPACKET ("ey", "a", "(Lez;)V", "net/minecraft/network/packet/Packet", "processPacket", "(Lnet/minecraft/network/packet/NetHandler;)V"), - //PACKET_WRITEPACKET ("ey", "a", "(Llp;Ljava/io/DataInput;ZLjava/net/Socket;)Ley;", "net/minecraft/network/packet/Packet", "writePacket", "(Lnet/minecraft/network/packet/Packet;Ljava/io/DataOutput;)V"), - //PACKET_READPACKET ("ey", "a", "(Llp;Ljava/io/DataInput;ZLjava/net/Socket;)Ley;", "net/minecraft/network/packet/Packet", "readPacket", "(Lnet/minecraft/logging/ILogAgent;Ljava/io/DataInput;ZLjava/net/Socket;)Lnet/minecraft/network/packet/Packet;"), - ; + TERENDER_RENDERAT( + "bml", + "a", + "(Laor;DDDF)V", + "net/minecraft/client/renderer/tileentity/TileEntitySpecialRenderer", + "renderTileEntityAt", + "(Lnet/minecraft/tileentity/TileEntity;DDDF)V"), + FMLCH_PREWORLDTICK( + "cpw/mods/fml/common/FMLCommonHandler", + "onPreWorldTick", + "(Lahb;)V", + "cpw/mods/fml/common/FMLCommonHandler", + "onPreWorldTick", + "(Lnet/minecraft/world/World;)V"), + FMLCH_POSTWORLDTICK( + "cpw/mods/fml/common/FMLCommonHandler", + "onPostWorldTick", + "(Lahb;)V", + "cpw/mods/fml/common/FMLCommonHandler", + "onPostWorldTick", + "(Lnet/minecraft/world/World;)V"), - private static Boolean isObfuscated = null; - private static ServerType serverType; - private String clazzNameN; - private String methodNameN; - private String descriptorN; - private String clazzNameS; - private String methodNameS; - private String descriptorS; - - private ObfTable(String clazzn, String namen, String descn, String clazzs, String names, String descs){ - this.clazzNameN = clazzn; - this.clazzNameS = clazzs; - this.methodNameN = namen; - this.methodNameS = names; - this.descriptorN = descn; - this.descriptorS = descs; - } - - public String getClazz(){ - if (deobfuscatedEnvironment()) - return this.clazzNameS; - else - return this.clazzNameN; - } + FMLPP_PROCESSPACKET( + "cpw/mods/fml/common/network/internal/FMLProxyPacket", + "a", + "(Lfb;)V", + "cpw/mods/fml/common/network/internal/FMLProxyPacket", + "processPacket", + "(Lnet/minecraft/network/INetHandler;)V"), - public String getName(){ - if (deobfuscatedEnvironment()) - return this.methodNameS; - else - return this.methodNameN; - } + WORLD_INIT( + "ahb", + "", + "(Lazc;Ljava/lang/String;Lahj;Laqo;Lqi;)V", + "net/minecraft/world/World", + "", + "(Lnet/minecraft/world/storage/ISaveHandler;Ljava/lang/String;Lnet/minecraft/world/WorldSettings;Lnet/minecraft/world/WorldProvider;Lnet/minecraft/profiler/Profiler;)V"), + WORLD_LOADEDENTS( + "ahb", "e", "Ljava/util/List;", "net/minecraft/world/World", "loadedEntityList", "Ljava/util/List;"), + WORLD_LOADEDTILES( + "ahb", "g", "Ljava/util/List;", "net/minecraft/world/World", "loadedTileEntityList", "Ljava/util/List;"), +/* +NETWORKLISTEN_NETWORKTICK ("nc", "c", "()V", "net/minecraft/network/NetworkSystem", "networkTick", "()V"), +TCPCONN_READPACKET ("co", "i", "()Z", "net/minecraft/network/TcpConnection", "readPacket", "()Z"), +TCPCONN_SENDPACKET ("co", "a", "(Z)Ley;", "net/minecraft/network/TcpConnection", "func_74460_a", "(Z)Lnet/minecraft/network/packet/Packet;"), +TCPCONN_NETWORKSOCKET ("co", "j", "Ljava/net/Socket;", "net/minecraft/network/TcpConnection", "networkSocket", "Ljava/net/Socket;"), +MEMCONN_ADDSENDQUEUE ("cn", "a", "(Ley;)V", "net/minecraft/network/MemoryConnection", "addToSendQueue", "(Lnet/minecraft/network/packet/Packet;)V"), +MEMCONN_PROCESSREAD ("cn", "b", "()V", "net/minecraft/network/MemoryConnection", "processReadPackets", "()V"), +MEMCONN_PAIREDCONN ("cn", "d", "Lcn;", "net/minecraft/network/MemoryConnection", "pairedConnection", "Lnet/minecraft/network/MemoryConnection;"), + MEMCONN_PROCESSORCACHE ("cn", "b", "(Ley;)V", "net/minecraft/network/MemoryConnection", "processOrCachePacket", "(Lnet/minecraft/network/packet/Packet;)V"), + MEMCONN_MYNETHANDLER ("cn", "e", "Lez;", "net/minecraft/network/MemoryConnection", "myNetHandler", "Lnet/minecraft/network/packet/NetHandler;"); +*/ - public String getDescriptor(){ - if (deobfuscatedEnvironment()) - return this.descriptorS; - else - return this.descriptorN; - } - - public String getFullDescriptor(){ - if (deobfuscatedEnvironment()) - return this.methodNameS + " " + this.descriptorS; - else - return this.methodNameN + " " + this.descriptorN; - } - - public static Boolean deobfuscatedEnvironment(){ - if (ObfTable.isObfuscated != null) - return ObfTable.isObfuscated; - - try{ - // Are we in a 'decompiled' environment? - byte[] bs = ((LaunchClassLoader)CoreContainer.class.getClassLoader()).getClassBytes("net.minecraft.world.World"); - if (bs != null){ - CoreDescription.log.info("Current code is UNOBFUSCATED"); - ObfTable.isObfuscated = true; - } else { - CoreDescription.log.info("Current code is OBFUSCATED"); - ObfTable.isObfuscated = false; - } +// PACKET_PROCESSPACKET ("ey", "a", "(Lez;)V", "net/minecraft/network/packet/Packet", "processPacket", +// "(Lnet/minecraft/network/packet/NetHandler;)V"), +// PACKET_WRITEPACKET ("ey", "a", "(Llp;Ljava/io/DataInput;ZLjava/net/Socket;)Ley;", +// "net/minecraft/network/packet/Packet", "writePacket", +// "(Lnet/minecraft/network/packet/Packet;Ljava/io/DataOutput;)V"), +// PACKET_READPACKET ("ey", "a", "(Llp;Ljava/io/DataInput;ZLjava/net/Socket;)Ley;", +// "net/minecraft/network/packet/Packet", "readPacket", +// "(Lnet/minecraft/logging/ILogAgent;Ljava/io/DataInput;ZLjava/net/Socket;)Lnet/minecraft/network/packet/Packet;"), +; - }catch (IOException e1){} - - return ObfTable.isObfuscated; - } - - public static ServerType getServerType() { - if (serverType != null) return serverType; + private static Boolean isObfuscated = null; + private static ServerType serverType; + private String clazzNameN; + private String methodNameN; + private String descriptorN; + private String clazzNameS; + private String methodNameS; + private String descriptorS; - if (FMLCommonHandler.instance().getModName().contains("thermos")) { - serverType = ServerType.Thermos; - CoreDescription.log.info("Switching injection mode to Thermos"); - } else if (FMLCommonHandler.instance().getModName().contains("kcauldron")) { - serverType = ServerType.KCauldron; - CoreDescription.log.info("Switching injection mode to KCAULDRON"); - } else if (FMLCommonHandler.instance().getModName().contains("cauldron") || FMLCommonHandler.instance().getModName().contains("mcpc")) { - serverType = ServerType.Cauldron; - CoreDescription.log.info("Switching injection mode to CAULDRON"); - } else { - serverType = ServerType.Forge; - CoreDescription.log.info("Switching injection mode to FORGE"); - } - return serverType; - } - - public enum ServerType { - Forge, Cauldron, KCauldron, Thermos - } - - /* - public FieldInsnNode getFieldNode(){ - return new FieldInsnNode(Opcodes.GETFIELD, this.getClazz(), this.getName(), this.getDescriptor()); - } - */ + private ObfTable(String clazzn, String namen, String descn, String clazzs, String names, String descs) { + this.clazzNameN = clazzn; + this.clazzNameS = clazzs; + this.methodNameN = namen; + this.methodNameS = names; + this.descriptorN = descn; + this.descriptorS = descs; + } + + public String getClazz() { + if (deobfuscatedEnvironment()) return this.clazzNameS; + else return this.clazzNameN; + } + + public String getName() { + if (deobfuscatedEnvironment()) return this.methodNameS; + else return this.methodNameN; + } + + public String getDescriptor() { + if (deobfuscatedEnvironment()) return this.descriptorS; + else return this.descriptorN; + } + + public String getFullDescriptor() { + if (deobfuscatedEnvironment()) return this.methodNameS + " " + this.descriptorS; + else return this.methodNameN + " " + this.descriptorN; + } + + public static Boolean deobfuscatedEnvironment() { + if (ObfTable.isObfuscated != null) return ObfTable.isObfuscated; + + try { + // Are we in a 'decompiled' environment? + byte[] bs = ((LaunchClassLoader) CoreContainer.class.getClassLoader()) + .getClassBytes("net.minecraft.world.World"); + if (bs != null) { + CoreDescription.log.info("Current code is UNOBFUSCATED"); + ObfTable.isObfuscated = true; + } else { + CoreDescription.log.info("Current code is OBFUSCATED"); + ObfTable.isObfuscated = false; + } + + } catch (IOException e1) { + } + + return ObfTable.isObfuscated; + } + + public static ServerType getServerType() { + if (serverType != null) return serverType; + + if (FMLCommonHandler.instance().getModName().contains("thermos")) { + serverType = ServerType.Thermos; + CoreDescription.log.info("Switching injection mode to Thermos"); + } else if (FMLCommonHandler.instance().getModName().contains("kcauldron")) { + serverType = ServerType.KCauldron; + CoreDescription.log.info("Switching injection mode to KCAULDRON"); + } else if (FMLCommonHandler.instance().getModName().contains("cauldron") + || FMLCommonHandler.instance().getModName().contains("mcpc")) { + serverType = ServerType.Cauldron; + CoreDescription.log.info("Switching injection mode to CAULDRON"); + } else { + serverType = ServerType.Forge; + CoreDescription.log.info("Switching injection mode to FORGE"); + } + return serverType; + } + + public enum ServerType { + Forge, + Cauldron, + KCauldron, + Thermos + } + + /* + public FieldInsnNode getFieldNode(){ + return new FieldInsnNode(Opcodes.GETFIELD, this.getClazz(), this.getName(), this.getDescriptor()); + } + */ } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/Opcode.java b/src/main/java/mcp/mobius/mobiuscore/asm/Opcode.java index afb8866..297b1ec 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/Opcode.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/Opcode.java @@ -1,7 +1,7 @@ package mcp.mobius.mobiuscore.asm; -import java.util.HashMap; - +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.InsnNode; @@ -9,296 +9,292 @@ import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; - public class Opcode { - public static InsnNode DUP(){ - return new InsnNode(Opcodes.DUP); - } - - public static VarInsnNode ALOAD(int val){ - return new VarInsnNode(Opcodes.ALOAD, val); - } - - public static TypeInsnNode NEW(String name){ - return new TypeInsnNode(Opcodes.NEW, name); - } - - public static FieldInsnNode GETFIELD(String name){ - String clazz = name.split("\\.")[0]; - String field = name.split("\\.")[1].split(" ")[0]; - String sig = name.split("\\.")[1].split(" ")[1]; - return new FieldInsnNode(Opcodes.GETFIELD, clazz, field, sig); - } - - public static FieldInsnNode GETFIELD(String clazz, String field, String sig){ - return new FieldInsnNode(Opcodes.GETFIELD, clazz, field, sig); - } - - public static FieldInsnNode PUTFIELD(String name){ - String clazz = name.split("\\.")[0]; - String field = name.split("\\.")[1].split(" ")[0]; - String sig = name.split("\\.")[1].split(" ")[1]; - return new FieldInsnNode(Opcodes.PUTFIELD, clazz, field, sig); - } - - public static FieldInsnNode PUTFIELD(String clazz, String field, String sig){ - return new FieldInsnNode(Opcodes.PUTFIELD, clazz, field, sig); - } - - public static FieldInsnNode GETSTATIC(String name){ - String clazz = name.split("\\.")[0]; - String field = name.split("\\.")[1].split(" ")[0]; - String sig = name.split("\\.")[1].split(" ")[1]; - return new FieldInsnNode(Opcodes.GETSTATIC, clazz, field, sig); - } - - public static FieldInsnNode GETSTATIC(String clazz, String field, String sig){ - return new FieldInsnNode(Opcodes.GETSTATIC, clazz, field, sig); - } - - public static MethodInsnNode INVOKEINTERFACE(String name){ - String clazz = name.split("\\.")[0]; - String field = name.split("\\.")[1].split(" ")[0]; - String sig = name.split("\\.")[1].split(" ")[1]; - return new MethodInsnNode(Opcodes.INVOKEINTERFACE, clazz, field, sig, true); - } - - public static MethodInsnNode INVOKEINTERFACE(String clazz, String field, String sig){ - return new MethodInsnNode(Opcodes.INVOKEINTERFACE, clazz, field, sig, true); - } - - public static MethodInsnNode INVOKEVIRTUAL(String name){ - String clazz = name.split("\\.")[0]; - String field = name.split("\\.")[1].split(" ")[0]; - String sig = name.split("\\.")[1].split(" ")[1]; - return new MethodInsnNode(Opcodes.INVOKEVIRTUAL, clazz, field, sig, false); - } - - public static MethodInsnNode INVOKEVIRTUAL(String clazz, String field, String sig){ - return new MethodInsnNode(Opcodes.INVOKEVIRTUAL, clazz, field, sig, false); - } - - public static MethodInsnNode INVOKESPECIAL(String name){ - String clazz = name.split("\\.")[0]; - String field = name.split("\\.")[1].split(" ")[0]; - String sig = name.split("\\.")[1].split(" ")[1]; - return new MethodInsnNode(Opcodes.INVOKESPECIAL, clazz, field, sig, false); - } - - public static MethodInsnNode INVOKESPECIAL(String clazz, String field, String sig){ - return new MethodInsnNode(Opcodes.INVOKESPECIAL, clazz, field, sig, false); - } - - public static BiMap Instructions; - - static{ - Instructions = HashBiMap.create(); - - Instructions.put("NOP",0); // visitInsn - Instructions.put("ACONST_NULL",1); - Instructions.put("ICONST_M1",2); - Instructions.put("ICONST_0",3); - Instructions.put("ICONST_1",4); - Instructions.put("ICONST_2",5); - Instructions.put("ICONST_3",6); - Instructions.put("ICONST_4",7); - Instructions.put("ICONST_5",8); - Instructions.put("LCONST_0",9); - Instructions.put("LCONST_1",10); - Instructions.put("FCONST_0",11); - Instructions.put("FCONST_1",12); - Instructions.put("FCONST_2",13); - Instructions.put("DCONST_0",14); - Instructions.put("DCONST_1",15); - Instructions.put("BIPUSH",16); - Instructions.put("SIPUSH",17); - Instructions.put("LDC",18); - Instructions.put("LDC_W",19); - Instructions.put("LDC2_W",20); - Instructions.put("ILOAD",21); - Instructions.put("LLOAD",22); - Instructions.put("FLOAD",23); - Instructions.put("DLOAD",24); - Instructions.put("ALOAD",25); - Instructions.put("ILOAD_0",26); - Instructions.put("ILOAD_1",27); - Instructions.put("ILOAD_2",28); - Instructions.put("ILOAD_3",29); - Instructions.put("LLOAD_0",30); - Instructions.put("LLOAD_1",31); - Instructions.put("LLOAD_2",32); - Instructions.put("LLOAD_3",33); - Instructions.put("FLOAD_0",34); - Instructions.put("FLOAD_1",35); - Instructions.put("FLOAD_2",36); - Instructions.put("FLOAD_3",37); - Instructions.put("DLOAD_0",38); - Instructions.put("DLOAD_1",39); - Instructions.put("DLOAD_2",40); - Instructions.put("DLOAD_3",41); - Instructions.put("ALOAD_0",42); - Instructions.put("ALOAD_1",43); - Instructions.put("ALOAD_2",44); - Instructions.put("ALOAD_3",45); - Instructions.put("IALOAD",46); - Instructions.put("LALOAD",47); - Instructions.put("FALOAD",48); - Instructions.put("DALOAD",49); - Instructions.put("AALOAD",50); - Instructions.put("BALOAD",51); - Instructions.put("CALOAD",52); - Instructions.put("SALOAD",53); - Instructions.put("ISTORE",54); - Instructions.put("LSTORE",55); - Instructions.put("FSTORE",56); - Instructions.put("DSTORE",57); - Instructions.put("ASTORE",58); - Instructions.put("ISTORE_0",59); - Instructions.put("ISTORE_1",60); - Instructions.put("ISTORE_2",61); - Instructions.put("ISTORE_3",62); - Instructions.put("LSTORE_0",63); - Instructions.put("LSTORE_1",64); - Instructions.put("LSTORE_2",65); - Instructions.put("LSTORE_3",66); - Instructions.put("FSTORE_0",67); - Instructions.put("FSTORE_1",68); - Instructions.put("FSTORE_2",69); - Instructions.put("FSTORE_3",70); - Instructions.put("DSTORE_0",71); - Instructions.put("DSTORE_1",72); - Instructions.put("DSTORE_2",73); - Instructions.put("DSTORE_3",74); - Instructions.put("ASTORE_0",75); - Instructions.put("ASTORE_1",76); - Instructions.put("ASTORE_2",77); - Instructions.put("ASTORE_3",78); - Instructions.put("IASTORE",79); - Instructions.put("LASTORE",80); - Instructions.put("FASTORE",81); - Instructions.put("DASTORE",82); - Instructions.put("AASTORE",83); - Instructions.put("BASTORE",84); - Instructions.put("CASTORE",85); - Instructions.put("SASTORE",86); - Instructions.put("POP",87); - Instructions.put("POP2",88); - Instructions.put("DUP",89); - Instructions.put("DUP_X1",90); - Instructions.put("DUP_X2",91); - Instructions.put("DUP2",92); - Instructions.put("DUP2_X1",93); - Instructions.put("DUP2_X2",94); - Instructions.put("SWAP",95); - Instructions.put("IADD",96); - Instructions.put("LADD",97); - Instructions.put("FADD",98); - Instructions.put("DADD",99); - Instructions.put("ISUB",100); - Instructions.put("LSUB",101); - Instructions.put("FSUB",102); - Instructions.put("DSUB",103); - Instructions.put("IMUL",104); - Instructions.put("LMUL",105); - Instructions.put("FMUL",106); - Instructions.put("DMUL",107); - Instructions.put("IDIV",108); - Instructions.put("LDIV",109); - Instructions.put("FDIV",110); - Instructions.put("DDIV",111); - Instructions.put("IREM",112); - Instructions.put("LREM",113); - Instructions.put("FREM",114); - Instructions.put("DREM",115); - Instructions.put("INEG",116); - Instructions.put("LNEG",117); - Instructions.put("FNEG",118); - Instructions.put("DNEG",119); - Instructions.put("ISHL",120); - Instructions.put("LSHL",121); - Instructions.put("ISHR",122); - Instructions.put("LSHR",123); - Instructions.put("IUSHR",124); - Instructions.put("LUSHR",125); - Instructions.put("IAND",126); - Instructions.put("LAND",127); - Instructions.put("IOR",128); - Instructions.put("LOR",129); - Instructions.put("IXOR",130); - Instructions.put("LXOR",131); - Instructions.put("IINC",132); - Instructions.put("I2L",133); - Instructions.put("I2F",134); - Instructions.put("I2D",135); - Instructions.put("L2I",136); - Instructions.put("L2F",137); - Instructions.put("L2D",138); - Instructions.put("F2I",139); - Instructions.put("F2L",140); - Instructions.put("F2D",141); - Instructions.put("D2I",142); - Instructions.put("D2L",143); - Instructions.put("D2F",144); - Instructions.put("I2B",145); - Instructions.put("I2C",146); - Instructions.put("I2S",147); - Instructions.put("LCMP",148); - Instructions.put("FCMPL",149); - Instructions.put("FCMPG",150); - Instructions.put("DCMPL",151); - Instructions.put("DCMPG",152); - Instructions.put("IFEQ",153); - Instructions.put("IFNE",154); - Instructions.put("IFLT",155); - Instructions.put("IFGE",156); - Instructions.put("IFGT",157); - Instructions.put("IFLE",158); - Instructions.put("IF_ICMPEQ",159); - Instructions.put("IF_ICMPNE",160); - Instructions.put("IF_ICMPLT",161); - Instructions.put("IF_ICMPGE",162); - Instructions.put("IF_ICMPGT",163); - Instructions.put("IF_ICMPLE",164); - Instructions.put("IF_ACMPEQ",165); - Instructions.put("IF_ACMPNE",166); - Instructions.put("GOTO",167); - Instructions.put("JSR",168); - Instructions.put("RET",169); - Instructions.put("TABLESWITCH",170); - Instructions.put("LOOKUPSWITCH",171); - Instructions.put("IRETURN",172); - Instructions.put("LRETURN",173); - Instructions.put("FRETURN",174); - Instructions.put("DRETURN",175); - Instructions.put("ARETURN",176); - Instructions.put("RETURN",177); - Instructions.put("GETSTATIC",178); - Instructions.put("PUTSTATIC",179); - Instructions.put("GETFIELD",180); - Instructions.put("PUTFIELD",181); - Instructions.put("INVOKEVIRTUAL",182); - Instructions.put("INVOKESPECIAL",183); - Instructions.put("INVOKESTATIC",184); - Instructions.put("INVOKEINTERFACE",185); - Instructions.put("INVOKEDYNAMIC",186); - Instructions.put("NEW",187); - Instructions.put("NEWARRAY",188); - Instructions.put("ANEWARRAY",189); - Instructions.put("ARRAYLENGTH",190); - Instructions.put("ATHROW",191); - Instructions.put("CHECKCAST",192); - Instructions.put("INSTANCEOF",193); - Instructions.put("MONITORENTER",194); - Instructions.put("MONITOREXIT",195); - Instructions.put("WIDE",196); - Instructions.put("MULTIANEWARRAY",197); - Instructions.put("IFNULL",198); - Instructions.put("IFNONNULL",199); - Instructions.put("GOTO_W",200); - Instructions.put("JSR_W",201); - } - + public static InsnNode DUP() { + return new InsnNode(Opcodes.DUP); + } + + public static VarInsnNode ALOAD(int val) { + return new VarInsnNode(Opcodes.ALOAD, val); + } + + public static TypeInsnNode NEW(String name) { + return new TypeInsnNode(Opcodes.NEW, name); + } + + public static FieldInsnNode GETFIELD(String name) { + String clazz = name.split("\\.")[0]; + String field = name.split("\\.")[1].split(" ")[0]; + String sig = name.split("\\.")[1].split(" ")[1]; + return new FieldInsnNode(Opcodes.GETFIELD, clazz, field, sig); + } + + public static FieldInsnNode GETFIELD(String clazz, String field, String sig) { + return new FieldInsnNode(Opcodes.GETFIELD, clazz, field, sig); + } + + public static FieldInsnNode PUTFIELD(String name) { + String clazz = name.split("\\.")[0]; + String field = name.split("\\.")[1].split(" ")[0]; + String sig = name.split("\\.")[1].split(" ")[1]; + return new FieldInsnNode(Opcodes.PUTFIELD, clazz, field, sig); + } + + public static FieldInsnNode PUTFIELD(String clazz, String field, String sig) { + return new FieldInsnNode(Opcodes.PUTFIELD, clazz, field, sig); + } + + public static FieldInsnNode GETSTATIC(String name) { + String clazz = name.split("\\.")[0]; + String field = name.split("\\.")[1].split(" ")[0]; + String sig = name.split("\\.")[1].split(" ")[1]; + return new FieldInsnNode(Opcodes.GETSTATIC, clazz, field, sig); + } + + public static FieldInsnNode GETSTATIC(String clazz, String field, String sig) { + return new FieldInsnNode(Opcodes.GETSTATIC, clazz, field, sig); + } + + public static MethodInsnNode INVOKEINTERFACE(String name) { + String clazz = name.split("\\.")[0]; + String field = name.split("\\.")[1].split(" ")[0]; + String sig = name.split("\\.")[1].split(" ")[1]; + return new MethodInsnNode(Opcodes.INVOKEINTERFACE, clazz, field, sig, true); + } + + public static MethodInsnNode INVOKEINTERFACE(String clazz, String field, String sig) { + return new MethodInsnNode(Opcodes.INVOKEINTERFACE, clazz, field, sig, true); + } + + public static MethodInsnNode INVOKEVIRTUAL(String name) { + String clazz = name.split("\\.")[0]; + String field = name.split("\\.")[1].split(" ")[0]; + String sig = name.split("\\.")[1].split(" ")[1]; + return new MethodInsnNode(Opcodes.INVOKEVIRTUAL, clazz, field, sig, false); + } + + public static MethodInsnNode INVOKEVIRTUAL(String clazz, String field, String sig) { + return new MethodInsnNode(Opcodes.INVOKEVIRTUAL, clazz, field, sig, false); + } + + public static MethodInsnNode INVOKESPECIAL(String name) { + String clazz = name.split("\\.")[0]; + String field = name.split("\\.")[1].split(" ")[0]; + String sig = name.split("\\.")[1].split(" ")[1]; + return new MethodInsnNode(Opcodes.INVOKESPECIAL, clazz, field, sig, false); + } + + public static MethodInsnNode INVOKESPECIAL(String clazz, String field, String sig) { + return new MethodInsnNode(Opcodes.INVOKESPECIAL, clazz, field, sig, false); + } + + public static BiMap Instructions; + + static { + Instructions = HashBiMap.create(); + + Instructions.put("NOP", 0); // visitInsn + Instructions.put("ACONST_NULL", 1); + Instructions.put("ICONST_M1", 2); + Instructions.put("ICONST_0", 3); + Instructions.put("ICONST_1", 4); + Instructions.put("ICONST_2", 5); + Instructions.put("ICONST_3", 6); + Instructions.put("ICONST_4", 7); + Instructions.put("ICONST_5", 8); + Instructions.put("LCONST_0", 9); + Instructions.put("LCONST_1", 10); + Instructions.put("FCONST_0", 11); + Instructions.put("FCONST_1", 12); + Instructions.put("FCONST_2", 13); + Instructions.put("DCONST_0", 14); + Instructions.put("DCONST_1", 15); + Instructions.put("BIPUSH", 16); + Instructions.put("SIPUSH", 17); + Instructions.put("LDC", 18); + Instructions.put("LDC_W", 19); + Instructions.put("LDC2_W", 20); + Instructions.put("ILOAD", 21); + Instructions.put("LLOAD", 22); + Instructions.put("FLOAD", 23); + Instructions.put("DLOAD", 24); + Instructions.put("ALOAD", 25); + Instructions.put("ILOAD_0", 26); + Instructions.put("ILOAD_1", 27); + Instructions.put("ILOAD_2", 28); + Instructions.put("ILOAD_3", 29); + Instructions.put("LLOAD_0", 30); + Instructions.put("LLOAD_1", 31); + Instructions.put("LLOAD_2", 32); + Instructions.put("LLOAD_3", 33); + Instructions.put("FLOAD_0", 34); + Instructions.put("FLOAD_1", 35); + Instructions.put("FLOAD_2", 36); + Instructions.put("FLOAD_3", 37); + Instructions.put("DLOAD_0", 38); + Instructions.put("DLOAD_1", 39); + Instructions.put("DLOAD_2", 40); + Instructions.put("DLOAD_3", 41); + Instructions.put("ALOAD_0", 42); + Instructions.put("ALOAD_1", 43); + Instructions.put("ALOAD_2", 44); + Instructions.put("ALOAD_3", 45); + Instructions.put("IALOAD", 46); + Instructions.put("LALOAD", 47); + Instructions.put("FALOAD", 48); + Instructions.put("DALOAD", 49); + Instructions.put("AALOAD", 50); + Instructions.put("BALOAD", 51); + Instructions.put("CALOAD", 52); + Instructions.put("SALOAD", 53); + Instructions.put("ISTORE", 54); + Instructions.put("LSTORE", 55); + Instructions.put("FSTORE", 56); + Instructions.put("DSTORE", 57); + Instructions.put("ASTORE", 58); + Instructions.put("ISTORE_0", 59); + Instructions.put("ISTORE_1", 60); + Instructions.put("ISTORE_2", 61); + Instructions.put("ISTORE_3", 62); + Instructions.put("LSTORE_0", 63); + Instructions.put("LSTORE_1", 64); + Instructions.put("LSTORE_2", 65); + Instructions.put("LSTORE_3", 66); + Instructions.put("FSTORE_0", 67); + Instructions.put("FSTORE_1", 68); + Instructions.put("FSTORE_2", 69); + Instructions.put("FSTORE_3", 70); + Instructions.put("DSTORE_0", 71); + Instructions.put("DSTORE_1", 72); + Instructions.put("DSTORE_2", 73); + Instructions.put("DSTORE_3", 74); + Instructions.put("ASTORE_0", 75); + Instructions.put("ASTORE_1", 76); + Instructions.put("ASTORE_2", 77); + Instructions.put("ASTORE_3", 78); + Instructions.put("IASTORE", 79); + Instructions.put("LASTORE", 80); + Instructions.put("FASTORE", 81); + Instructions.put("DASTORE", 82); + Instructions.put("AASTORE", 83); + Instructions.put("BASTORE", 84); + Instructions.put("CASTORE", 85); + Instructions.put("SASTORE", 86); + Instructions.put("POP", 87); + Instructions.put("POP2", 88); + Instructions.put("DUP", 89); + Instructions.put("DUP_X1", 90); + Instructions.put("DUP_X2", 91); + Instructions.put("DUP2", 92); + Instructions.put("DUP2_X1", 93); + Instructions.put("DUP2_X2", 94); + Instructions.put("SWAP", 95); + Instructions.put("IADD", 96); + Instructions.put("LADD", 97); + Instructions.put("FADD", 98); + Instructions.put("DADD", 99); + Instructions.put("ISUB", 100); + Instructions.put("LSUB", 101); + Instructions.put("FSUB", 102); + Instructions.put("DSUB", 103); + Instructions.put("IMUL", 104); + Instructions.put("LMUL", 105); + Instructions.put("FMUL", 106); + Instructions.put("DMUL", 107); + Instructions.put("IDIV", 108); + Instructions.put("LDIV", 109); + Instructions.put("FDIV", 110); + Instructions.put("DDIV", 111); + Instructions.put("IREM", 112); + Instructions.put("LREM", 113); + Instructions.put("FREM", 114); + Instructions.put("DREM", 115); + Instructions.put("INEG", 116); + Instructions.put("LNEG", 117); + Instructions.put("FNEG", 118); + Instructions.put("DNEG", 119); + Instructions.put("ISHL", 120); + Instructions.put("LSHL", 121); + Instructions.put("ISHR", 122); + Instructions.put("LSHR", 123); + Instructions.put("IUSHR", 124); + Instructions.put("LUSHR", 125); + Instructions.put("IAND", 126); + Instructions.put("LAND", 127); + Instructions.put("IOR", 128); + Instructions.put("LOR", 129); + Instructions.put("IXOR", 130); + Instructions.put("LXOR", 131); + Instructions.put("IINC", 132); + Instructions.put("I2L", 133); + Instructions.put("I2F", 134); + Instructions.put("I2D", 135); + Instructions.put("L2I", 136); + Instructions.put("L2F", 137); + Instructions.put("L2D", 138); + Instructions.put("F2I", 139); + Instructions.put("F2L", 140); + Instructions.put("F2D", 141); + Instructions.put("D2I", 142); + Instructions.put("D2L", 143); + Instructions.put("D2F", 144); + Instructions.put("I2B", 145); + Instructions.put("I2C", 146); + Instructions.put("I2S", 147); + Instructions.put("LCMP", 148); + Instructions.put("FCMPL", 149); + Instructions.put("FCMPG", 150); + Instructions.put("DCMPL", 151); + Instructions.put("DCMPG", 152); + Instructions.put("IFEQ", 153); + Instructions.put("IFNE", 154); + Instructions.put("IFLT", 155); + Instructions.put("IFGE", 156); + Instructions.put("IFGT", 157); + Instructions.put("IFLE", 158); + Instructions.put("IF_ICMPEQ", 159); + Instructions.put("IF_ICMPNE", 160); + Instructions.put("IF_ICMPLT", 161); + Instructions.put("IF_ICMPGE", 162); + Instructions.put("IF_ICMPGT", 163); + Instructions.put("IF_ICMPLE", 164); + Instructions.put("IF_ACMPEQ", 165); + Instructions.put("IF_ACMPNE", 166); + Instructions.put("GOTO", 167); + Instructions.put("JSR", 168); + Instructions.put("RET", 169); + Instructions.put("TABLESWITCH", 170); + Instructions.put("LOOKUPSWITCH", 171); + Instructions.put("IRETURN", 172); + Instructions.put("LRETURN", 173); + Instructions.put("FRETURN", 174); + Instructions.put("DRETURN", 175); + Instructions.put("ARETURN", 176); + Instructions.put("RETURN", 177); + Instructions.put("GETSTATIC", 178); + Instructions.put("PUTSTATIC", 179); + Instructions.put("GETFIELD", 180); + Instructions.put("PUTFIELD", 181); + Instructions.put("INVOKEVIRTUAL", 182); + Instructions.put("INVOKESPECIAL", 183); + Instructions.put("INVOKESTATIC", 184); + Instructions.put("INVOKEINTERFACE", 185); + Instructions.put("INVOKEDYNAMIC", 186); + Instructions.put("NEW", 187); + Instructions.put("NEWARRAY", 188); + Instructions.put("ANEWARRAY", 189); + Instructions.put("ARRAYLENGTH", 190); + Instructions.put("ATHROW", 191); + Instructions.put("CHECKCAST", 192); + Instructions.put("INSTANCEOF", 193); + Instructions.put("MONITORENTER", 194); + Instructions.put("MONITOREXIT", 195); + Instructions.put("WIDE", 196); + Instructions.put("MULTIANEWARRAY", 197); + Instructions.put("IFNULL", 198); + Instructions.put("IFNONNULL", 199); + Instructions.put("GOTO_W", 200); + Instructions.put("JSR_W", 201); + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/TransformerBase.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/TransformerBase.java index b38d70e..0f1be89 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/TransformerBase.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/TransformerBase.java @@ -1,22 +1,16 @@ package mcp.mobius.mobiuscore.asm.transformers; -import java.io.File; -import java.io.FileNotFoundException; import java.io.InputStream; -import java.io.PrintWriter; import java.math.BigInteger; import java.security.MessageDigest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.ListIterator; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; - import mcp.mobius.mobiuscore.asm.CoreDescription; import mcp.mobius.mobiuscore.asm.MethodDescriptor; import mcp.mobius.mobiuscore.asm.Opcode; - import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; @@ -25,405 +19,423 @@ import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LineNumberNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; -import org.objectweb.asm.util.Printer; -import org.objectweb.asm.util.Textifier; -import org.objectweb.asm.util.TraceClassVisitor; -import org.objectweb.asm.util.TraceMethodVisitor; -import org.objectweb.asm.tree.FieldInsnNode; -import org.objectweb.asm.tree.InsnNode; -import org.objectweb.asm.tree.MethodInsnNode; -import org.objectweb.asm.tree.TypeInsnNode; -import org.objectweb.asm.tree.VarInsnNode; -import org.objectweb.asm.tree.LabelNode; public abstract class TransformerBase { - - HashMap> methodsToOverwrite = new HashMap>(); - HashMap> methodsToInject = new HashMap>(); - - public abstract byte[] transform(String name, String srgname, byte[] bytes); - protected ArrayList> findPattern(MethodNode methodNode, AbstractInsnNode... pattern){ - return findPattern( methodNode, false, pattern); - } - - protected ArrayList> findPattern(MethodNode methodNode, boolean dumpOpcodes, AbstractInsnNode... pattern){ - InsnList instructions = methodNode.instructions; - ArrayList> returnList = new ArrayList>(); - - //We are going to check all the intructions in the method to find pattens - for (int indexFirstInst = 0; indexFirstInst < instructions.size(); indexFirstInst++){ - - AbstractInsnNode currNode = instructions.get(indexFirstInst); - if (dumpOpcodes) - printInsnNode(currNode); - - //We found the first element of the pattern. We are starting matching all the elements - if (this.areInsnEqual(currNode, pattern[0]));{ - boolean match = true; - - //We are forward matching all the instructions to see if they are ok. By the end of this loop, match is false if at least one inst doesn't match - for (int indexPatternInst = 0; indexPatternInst < pattern.length; indexPatternInst++){ - try{ - match = match && this.areInsnEqual(instructions.get(indexFirstInst + indexPatternInst) , pattern[indexPatternInst]); - } catch (ArrayIndexOutOfBoundsException e){ - return returnList; // This can only happen if there is less than the number of pattern elements in the remaining instructions. We can return the current results directly. - } - } + HashMap> methodsToOverwrite = new HashMap>(); + HashMap> methodsToInject = new HashMap>(); - // All the instructions are equal, we create a new ArrayList and add it to the return list - if (match){ - ArrayList matchedPattern = new ArrayList(); - for (int indexPatternInst = 0; indexPatternInst < pattern.length; indexPatternInst++){ - matchedPattern.add(instructions.get(indexFirstInst + indexPatternInst)); - } - returnList.add(matchedPattern); - } - } - } - - return returnList; - } - - protected boolean areInsnEqual(AbstractInsnNode insn1, AbstractInsnNode insn2){ - if (!insn1.getClass().equals(insn2.getClass())) return false; - if (insn1.getOpcode() != insn2.getOpcode()) return false; - - if (insn1 instanceof LineNumberNode){ - if ((((LineNumberNode)insn2).line == -1) || (((LineNumberNode)insn2).line == -1)) return true; - if (((LineNumberNode)insn2).line != ((LineNumberNode)insn2).line) return false; - if (((LineNumberNode)insn2).line == ((LineNumberNode)insn2).line) return true; - } - - if (insn1 instanceof VarInsnNode){ - if ((((VarInsnNode)insn2).var == -1) || (((VarInsnNode)insn2).var == -1)) return true; - if (((VarInsnNode)insn2).var != ((VarInsnNode)insn2).var) return false; - if (((VarInsnNode)insn2).var == ((VarInsnNode)insn2).var) return true; - } + public abstract byte[] transform(String name, String srgname, byte[] bytes); - if (insn1 instanceof MethodInsnNode){ - if ((((MethodInsnNode)insn1).owner.equals(((MethodInsnNode)insn2).owner)) && - (((MethodInsnNode)insn1).name.equals(((MethodInsnNode)insn2).name)) && - (((MethodInsnNode)insn1).desc.equals(((MethodInsnNode)insn2).desc))) - return true; - } - - if (insn1 instanceof FieldInsnNode){ - if ((((FieldInsnNode)insn1).owner.equals(((FieldInsnNode)insn2).owner)) && - (((FieldInsnNode)insn1).name.equals(((FieldInsnNode)insn2).name)) && - (((FieldInsnNode)insn1).desc.equals(((FieldInsnNode)insn2).desc))) - return true; - } - - if (insn1 instanceof InsnNode){ - if (insn1.getOpcode() == insn2.getOpcode()) - return true; - } - - if (insn1 instanceof TypeInsnNode){ - if (((TypeInsnNode)insn1).desc.equals(((TypeInsnNode)insn2).desc)) - return true; - } - - return false; - - } - - protected void printInsnNode (AbstractInsnNode insnNode){ - switch(insnNode.getType()){ - case AbstractInsnNode.LINE: - CoreDescription.log.info(String.format("LINE : %s", ((LineNumberNode)insnNode).line)); - break; - - case AbstractInsnNode.LABEL: - CoreDescription.log.info(String.format("LINE : %s", ((LabelNode)insnNode).getLabel())); - break; - - case AbstractInsnNode.VAR_INSN: - CoreDescription.log.info(String.format("VAR_INSN : %s %s", Opcode.Instructions.inverse().get(insnNode.getOpcode()), ((VarInsnNode)insnNode).var)); - break; + protected ArrayList> findPattern(MethodNode methodNode, AbstractInsnNode... pattern) { + return findPattern(methodNode, false, pattern); + } - case AbstractInsnNode.METHOD_INSN: - CoreDescription.log.info(String.format("METHOD_INSN : %s %s %s %s", Opcode.Instructions.inverse().get(insnNode.getOpcode()), ((MethodInsnNode)insnNode).owner, ((MethodInsnNode)insnNode).name, ((MethodInsnNode)insnNode).desc)); - break; - - case AbstractInsnNode.INSN: - CoreDescription.log.info(String.format("INSN : %s", Opcode.Instructions.inverse().get(insnNode.getOpcode()))); - break; + protected ArrayList> findPattern( + MethodNode methodNode, boolean dumpOpcodes, AbstractInsnNode... pattern) { + InsnList instructions = methodNode.instructions; + ArrayList> returnList = new ArrayList>(); - case AbstractInsnNode.TYPE_INSN: - CoreDescription.log.info(String.format("TYPE_INSN : %s %s", Opcode.Instructions.inverse().get(insnNode.getOpcode()), ((TypeInsnNode)insnNode).desc )); - break; - - case AbstractInsnNode.FIELD_INSN: - CoreDescription.log.info(String.format("FIELD_INSN : %s %s %s %s", Opcode.Instructions.inverse().get(insnNode.getOpcode()), ((FieldInsnNode)insnNode).owner, ((FieldInsnNode)insnNode).name, ((FieldInsnNode)insnNode).desc)); - break; - - default: - CoreDescription.log.info(String.format(" %s %s", Opcode.Instructions.inverse().get(insnNode.getOpcode()), insnNode)); - break; - } - } - - protected void printMethod(MethodNode methodNode){ - InsnList instructions = methodNode.instructions; - for (int indexFirstInst = 0; indexFirstInst < instructions.size(); indexFirstInst++){ - AbstractInsnNode currNode = instructions.get(indexFirstInst); - printInsnNode(currNode); - } - } - - private void applyPayloadAfter(InsnList instructions, ArrayList match, AbstractInsnNode[] payload_pattern){ - InsnList payload = new InsnList(); - for (int i = 0; i < payload_pattern.length; i++) - payload.add(payload_pattern[i]); - - instructions.insert(match.get(match.size() - 1), payload); - } - - private void applyPayloadBefore(InsnList instructions, ArrayList match, AbstractInsnNode[] payload_pattern){ - InsnList payload = new InsnList(); - for (int i = 0; i < payload_pattern.length; i++) - payload.add(payload_pattern[i]); - - instructions.insertBefore(match.get(0), payload); - } - - protected void applyPayloadBefore(MethodNode methodNode, AbstractInsnNode[] pattern, AbstractInsnNode[] payload){ - ArrayList> match; - - match = this.findPattern(methodNode, pattern); - if (match.size() != 0){ - for (ArrayList sublist : match){ - this.applyPayloadBefore(methodNode.instructions, sublist, payload); - } - CoreDescription.log.info(String.format("Successful injection in %s %s", methodNode.name, methodNode.desc)); - return; - } - - throw new RuntimeException(String.format("Pattern not found while trying to inject into %s", methodNode.name)); - } - - protected void applyPayloadAfter(MethodNode methodNode, AbstractInsnNode[] pattern, AbstractInsnNode[] payload){ - ArrayList> match; - - match = this.findPattern(methodNode, pattern); - if (match.size() != 0){ - for (ArrayList sublist : match){ - this.applyPayloadAfter(methodNode.instructions, sublist, payload); - } - CoreDescription.log.info(String.format("Successful injection in %s %s", methodNode.name, methodNode.desc)); - return; - } - this.printMethod(methodNode); - throw new RuntimeException(String.format("Pattern not found while trying to inject into %s", methodNode.name)); - } - - protected void applyPayloadFirst(MethodNode methodNode, AbstractInsnNode[] payload_pattern){ - InsnList instructions = methodNode.instructions; - InsnList payload = new InsnList(); - for (int i = 0; i < payload_pattern.length; i++) - payload.add(payload_pattern[i]); - - instructions.insertBefore(instructions.getFirst(), payload); - - CoreDescription.log.info(String.format("Successful injection in %s %s", methodNode.name, methodNode.desc)); - } - - protected void applyPayloadLast(MethodNode methodNode, AbstractInsnNode[] payload_pattern){ - InsnList instructions = methodNode.instructions; - InsnList payload = new InsnList(); - for (int i = 0; i < payload_pattern.length; i++) - payload.add(payload_pattern[i]); - - for (int i = instructions.size() - 1; i >= 0; i--){ - if ((instructions.get(i).getOpcode() == Opcodes.RETURN) || (instructions.get(i).getOpcode() == Opcodes.IRETURN)){ - instructions.insertBefore(instructions.get(i), payload); - } - } + // We are going to check all the intructions in the method to find pattens + for (int indexFirstInst = 0; indexFirstInst < instructions.size(); indexFirstInst++) { - CoreDescription.log.info(String.format("Successful injection in %s %s", methodNode.name, methodNode.desc)); - } - - /* - * Will return a byte array of the content of the named class in the coremod jar - */ - protected byte[] getJarClass(String transformedName){ - byte[] bytes = null; - - try - { - ZipFile zip = new ZipFile(CoreDescription.location); - ZipEntry entry = zip.getEntry(transformedName.replace('.', '/')+".class"); - //ZipEntry entry = zip.getEntry(name.replace('.', '/')+".class"); - if(entry == null) - CoreDescription.log.error(transformedName + " not found in " + CoreDescription.location.getName()); - else - { - InputStream zin = zip.getInputStream(entry); - bytes = new byte[(int) entry.getSize()]; - zin.read(bytes); - zin.close(); - } - zip.close(); - } - catch(Exception e) - { - throw new RuntimeException("Error overriding "+transformedName+" from "+CoreDescription.location.getName(), e); - } - - return bytes; - } - - /* - * Overwrite method X with signature Y with the method from inside the coremod jar. - */ - protected byte[] overwriteMethod(String className, MethodDescriptor methodDesc, byte[] vanillaBytes){ - - byte[] coremodBytes = this.getJarClass(className); - - ClassNode vanillaNode = new ClassNode(); + AbstractInsnNode currNode = instructions.get(indexFirstInst); + if (dumpOpcodes) printInsnNode(currNode); + + // We found the first element of the pattern. We are starting matching all the elements + if (this.areInsnEqual(currNode, pattern[0])) + ; + { + boolean match = true; + + // We are forward matching all the instructions to see if they are ok. By the end of this loop, match is + // false if at least one inst doesn't match + for (int indexPatternInst = 0; indexPatternInst < pattern.length; indexPatternInst++) { + try { + match = match + && this.areInsnEqual( + instructions.get(indexFirstInst + indexPatternInst), pattern[indexPatternInst]); + } catch (ArrayIndexOutOfBoundsException e) { + return returnList; // This can only happen if there is less than the number of pattern elements + // in the remaining instructions. We can return the current results directly. + } + } + + // All the instructions are equal, we create a new ArrayList and add it to the return list + if (match) { + ArrayList matchedPattern = new ArrayList(); + for (int indexPatternInst = 0; indexPatternInst < pattern.length; indexPatternInst++) { + matchedPattern.add(instructions.get(indexFirstInst + indexPatternInst)); + } + returnList.add(matchedPattern); + } + } + } + + return returnList; + } + + protected boolean areInsnEqual(AbstractInsnNode insn1, AbstractInsnNode insn2) { + if (!insn1.getClass().equals(insn2.getClass())) return false; + if (insn1.getOpcode() != insn2.getOpcode()) return false; + + if (insn1 instanceof LineNumberNode) { + if ((((LineNumberNode) insn2).line == -1) || (((LineNumberNode) insn2).line == -1)) return true; + if (((LineNumberNode) insn2).line != ((LineNumberNode) insn2).line) return false; + if (((LineNumberNode) insn2).line == ((LineNumberNode) insn2).line) return true; + } + + if (insn1 instanceof VarInsnNode) { + if ((((VarInsnNode) insn2).var == -1) || (((VarInsnNode) insn2).var == -1)) return true; + if (((VarInsnNode) insn2).var != ((VarInsnNode) insn2).var) return false; + if (((VarInsnNode) insn2).var == ((VarInsnNode) insn2).var) return true; + } + + if (insn1 instanceof MethodInsnNode) { + if ((((MethodInsnNode) insn1).owner.equals(((MethodInsnNode) insn2).owner)) + && (((MethodInsnNode) insn1).name.equals(((MethodInsnNode) insn2).name)) + && (((MethodInsnNode) insn1).desc.equals(((MethodInsnNode) insn2).desc))) return true; + } + + if (insn1 instanceof FieldInsnNode) { + if ((((FieldInsnNode) insn1).owner.equals(((FieldInsnNode) insn2).owner)) + && (((FieldInsnNode) insn1).name.equals(((FieldInsnNode) insn2).name)) + && (((FieldInsnNode) insn1).desc.equals(((FieldInsnNode) insn2).desc))) return true; + } + + if (insn1 instanceof InsnNode) { + if (insn1.getOpcode() == insn2.getOpcode()) return true; + } + + if (insn1 instanceof TypeInsnNode) { + if (((TypeInsnNode) insn1).desc.equals(((TypeInsnNode) insn2).desc)) return true; + } + + return false; + } + + protected void printInsnNode(AbstractInsnNode insnNode) { + switch (insnNode.getType()) { + case AbstractInsnNode.LINE: + CoreDescription.log.info(String.format("LINE : %s", ((LineNumberNode) insnNode).line)); + break; + + case AbstractInsnNode.LABEL: + CoreDescription.log.info(String.format("LINE : %s", ((LabelNode) insnNode).getLabel())); + break; + + case AbstractInsnNode.VAR_INSN: + CoreDescription.log.info(String.format( + "VAR_INSN : %s %s", + Opcode.Instructions.inverse().get(insnNode.getOpcode()), ((VarInsnNode) insnNode).var)); + break; + + case AbstractInsnNode.METHOD_INSN: + CoreDescription.log.info(String.format( + "METHOD_INSN : %s %s %s %s", + Opcode.Instructions.inverse().get(insnNode.getOpcode()), + ((MethodInsnNode) insnNode).owner, + ((MethodInsnNode) insnNode).name, + ((MethodInsnNode) insnNode).desc)); + break; + + case AbstractInsnNode.INSN: + CoreDescription.log.info(String.format( + "INSN : %s", Opcode.Instructions.inverse().get(insnNode.getOpcode()))); + break; + + case AbstractInsnNode.TYPE_INSN: + CoreDescription.log.info(String.format( + "TYPE_INSN : %s %s", + Opcode.Instructions.inverse().get(insnNode.getOpcode()), ((TypeInsnNode) insnNode).desc)); + break; + + case AbstractInsnNode.FIELD_INSN: + CoreDescription.log.info(String.format( + "FIELD_INSN : %s %s %s %s", + Opcode.Instructions.inverse().get(insnNode.getOpcode()), + ((FieldInsnNode) insnNode).owner, + ((FieldInsnNode) insnNode).name, + ((FieldInsnNode) insnNode).desc)); + break; + + default: + CoreDescription.log.info(String.format( + " %s %s", Opcode.Instructions.inverse().get(insnNode.getOpcode()), insnNode)); + break; + } + } + + protected void printMethod(MethodNode methodNode) { + InsnList instructions = methodNode.instructions; + for (int indexFirstInst = 0; indexFirstInst < instructions.size(); indexFirstInst++) { + AbstractInsnNode currNode = instructions.get(indexFirstInst); + printInsnNode(currNode); + } + } + + private void applyPayloadAfter( + InsnList instructions, ArrayList match, AbstractInsnNode[] payload_pattern) { + InsnList payload = new InsnList(); + for (int i = 0; i < payload_pattern.length; i++) payload.add(payload_pattern[i]); + + instructions.insert(match.get(match.size() - 1), payload); + } + + private void applyPayloadBefore( + InsnList instructions, ArrayList match, AbstractInsnNode[] payload_pattern) { + InsnList payload = new InsnList(); + for (int i = 0; i < payload_pattern.length; i++) payload.add(payload_pattern[i]); + + instructions.insertBefore(match.get(0), payload); + } + + protected void applyPayloadBefore(MethodNode methodNode, AbstractInsnNode[] pattern, AbstractInsnNode[] payload) { + ArrayList> match; + + match = this.findPattern(methodNode, pattern); + if (match.size() != 0) { + for (ArrayList sublist : match) { + this.applyPayloadBefore(methodNode.instructions, sublist, payload); + } + CoreDescription.log.info(String.format("Successful injection in %s %s", methodNode.name, methodNode.desc)); + return; + } + + throw new RuntimeException(String.format("Pattern not found while trying to inject into %s", methodNode.name)); + } + + protected void applyPayloadAfter(MethodNode methodNode, AbstractInsnNode[] pattern, AbstractInsnNode[] payload) { + ArrayList> match; + + match = this.findPattern(methodNode, pattern); + if (match.size() != 0) { + for (ArrayList sublist : match) { + this.applyPayloadAfter(methodNode.instructions, sublist, payload); + } + CoreDescription.log.info(String.format("Successful injection in %s %s", methodNode.name, methodNode.desc)); + return; + } + this.printMethod(methodNode); + throw new RuntimeException(String.format("Pattern not found while trying to inject into %s", methodNode.name)); + } + + protected void applyPayloadFirst(MethodNode methodNode, AbstractInsnNode[] payload_pattern) { + InsnList instructions = methodNode.instructions; + InsnList payload = new InsnList(); + for (int i = 0; i < payload_pattern.length; i++) payload.add(payload_pattern[i]); + + instructions.insertBefore(instructions.getFirst(), payload); + + CoreDescription.log.info(String.format("Successful injection in %s %s", methodNode.name, methodNode.desc)); + } + + protected void applyPayloadLast(MethodNode methodNode, AbstractInsnNode[] payload_pattern) { + InsnList instructions = methodNode.instructions; + InsnList payload = new InsnList(); + for (int i = 0; i < payload_pattern.length; i++) payload.add(payload_pattern[i]); + + for (int i = instructions.size() - 1; i >= 0; i--) { + if ((instructions.get(i).getOpcode() == Opcodes.RETURN) + || (instructions.get(i).getOpcode() == Opcodes.IRETURN)) { + instructions.insertBefore(instructions.get(i), payload); + } + } + + CoreDescription.log.info(String.format("Successful injection in %s %s", methodNode.name, methodNode.desc)); + } + + /* + * Will return a byte array of the content of the named class in the coremod jar + */ + protected byte[] getJarClass(String transformedName) { + byte[] bytes = null; + + try { + ZipFile zip = new ZipFile(CoreDescription.location); + ZipEntry entry = zip.getEntry(transformedName.replace('.', '/') + ".class"); + // ZipEntry entry = zip.getEntry(name.replace('.', '/')+".class"); + if (entry == null) + CoreDescription.log.error(transformedName + " not found in " + CoreDescription.location.getName()); + else { + InputStream zin = zip.getInputStream(entry); + bytes = new byte[(int) entry.getSize()]; + zin.read(bytes); + zin.close(); + } + zip.close(); + } catch (Exception e) { + throw new RuntimeException( + "Error overriding " + transformedName + " from " + CoreDescription.location.getName(), e); + } + + return bytes; + } + + /* + * Overwrite method X with signature Y with the method from inside the coremod jar. + */ + protected byte[] overwriteMethod(String className, MethodDescriptor methodDesc, byte[] vanillaBytes) { + + byte[] coremodBytes = this.getJarClass(className); + + ClassNode vanillaNode = new ClassNode(); ClassReader vanillaReader = new ClassReader(vanillaBytes); - ClassNode coremodNode = new ClassNode(); - ClassReader coremodReader = new ClassReader(coremodBytes); - + ClassNode coremodNode = new ClassNode(); + ClassReader coremodReader = new ClassReader(coremodBytes); + vanillaReader.accept(vanillaNode, 0); coremodReader.accept(coremodNode, 0); - + MethodNode vanillaMethodNode = null; - for (MethodNode node: vanillaNode.methods){ - try{ - if (node != null && node.desc.equals(methodDesc.getDescriptor()) && (node.name.equals(methodDesc.getMethodName()))){ - CoreDescription.log.info(String.format("Found method node %s.%s %s in Vanilla.", className, methodDesc.getMethodName(), methodDesc.getDescriptor())); - vanillaMethodNode = node; - } - } catch (Exception e){ - //System.out.printf("Error while parsing %s %s\n", className, node); - } + for (MethodNode node : vanillaNode.methods) { + try { + if (node != null + && node.desc.equals(methodDesc.getDescriptor()) + && (node.name.equals(methodDesc.getMethodName()))) { + CoreDescription.log.info(String.format( + "Found method node %s.%s %s in Vanilla.", + className, methodDesc.getMethodName(), methodDesc.getDescriptor())); + vanillaMethodNode = node; + } + } catch (Exception e) { + // System.out.printf("Error while parsing %s %s\n", className, node); + } } - + MethodNode coremodMethodNode = null; - for (MethodNode node: coremodNode.methods){ - try{ - if (node != null && node.desc.equals(methodDesc.getDescriptor()) && (node.name.equals(methodDesc.getMethodName()))){ - CoreDescription.log.info(String.format("Found method node %s.%s %s in Coremod.", className, methodDesc.getMethodName(), methodDesc.getDescriptor())); - coremodMethodNode = node; - } - } catch (Exception e){ - //System.out.printf("Error while parsing %s %s\n", className, node); - } + for (MethodNode node : coremodNode.methods) { + try { + if (node != null + && node.desc.equals(methodDesc.getDescriptor()) + && (node.name.equals(methodDesc.getMethodName()))) { + CoreDescription.log.info(String.format( + "Found method node %s.%s %s in Coremod.", + className, methodDesc.getMethodName(), methodDesc.getDescriptor())); + coremodMethodNode = node; + } + } catch (Exception e) { + // System.out.printf("Error while parsing %s %s\n", className, node); + } } - - if (vanillaMethodNode == null){ - CoreDescription.log.fatal(String.format("Method node %s.%s %s not found in Vanilla ! This is going to crash !.", className, methodDesc.getMethodName(), methodDesc.getDescriptor())); + + if (vanillaMethodNode == null) { + CoreDescription.log.fatal(String.format( + "Method node %s.%s %s not found in Vanilla ! This is going to crash !.", + className, methodDesc.getMethodName(), methodDesc.getDescriptor())); } - if (coremodMethodNode == null){ - CoreDescription.log.fatal(String.format("Method node %s.%s %s not found in Coremod ! This is going to crash !.", className, methodDesc.getMethodName(), methodDesc.getDescriptor())); + if (coremodMethodNode == null) { + CoreDescription.log.fatal(String.format( + "Method node %s.%s %s not found in Coremod ! This is going to crash !.", + className, methodDesc.getMethodName(), methodDesc.getDescriptor())); } - + vanillaNode.methods.remove(vanillaMethodNode); coremodMethodNode.accept(vanillaNode); - //vanillaNode.methods.add(coremodMethodNode); - + // vanillaNode.methods.add(coremodMethodNode); + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); vanillaNode.accept(writer); - return writer.toByteArray(); - } - - /* - * Inject a new method with a new signature to the list of methods. - */ - protected byte[] injectMethod(String className, MethodDescriptor methodDesc, byte[] vanillaBytes){ - - try{ - byte[] coremodBytes = this.getJarClass(className); - - ClassNode vanillaNode = new ClassNode(); - ClassReader vanillaReader = new ClassReader(vanillaBytes); - ClassNode coremodNode = new ClassNode(); - ClassReader coremodReader = new ClassReader(coremodBytes); - - vanillaReader.accept(vanillaNode, 0); - coremodReader.accept(coremodNode, 0); - - MethodNode coremodMethodNode = null; - for (MethodNode node: coremodNode.methods){ - try{ - if (node != null && node.desc.equals(methodDesc.getDescriptor()) && (node.name.equals(methodDesc.getMethodName()))){ - CoreDescription.log.info(String.format("Found method node %s.%s %s in Coremod. Injecting !", className, methodDesc.getMethodName(), methodDesc.getDescriptor())); - coremodMethodNode = node; - } - } catch (Exception e){ - //System.out.printf("Error while parsing %s %s\n", className, node); - } - } - - if (coremodMethodNode == null){ - CoreDescription.log.fatal(String.format("Method node %s.%s %s not found in Coremod ! This is going to crash !.", className, methodDesc.getMethodName(), methodDesc.getDescriptor())); - } - - coremodMethodNode.accept(vanillaNode); - //vanillaNode.methods.add(coremodMethodNode); - - ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); - vanillaNode.accept(writer); - return writer.toByteArray(); - } catch (ClassFormatError e){ - CoreDescription.log.warn("Class already injected."); - return vanillaBytes; - } - } - - public static String dumpChecksum(byte[] data, String obf, String searge){ - try{ - //System.out.printf("[MobiusCore] Found %s with checksum %s\n", filename, MessageDigest.getInstance("MD5").digest(data)); - - MessageDigest m = MessageDigest.getInstance("MD5"); - m.reset(); - m.update(data); - byte[] digest = m.digest(); - BigInteger bigInt = new BigInteger(1,digest); - String hashtext = bigInt.toString(16); - // Now we need to zero pad it if you actually want the full 32 chars. - while(hashtext.length() < 32 ){ - hashtext = "0"+hashtext; - } - - if (obf.equals(searge)) - CoreDescription.log.info(String.format("Found %s with checksum %s", searge, hashtext.toUpperCase())); - else - CoreDescription.log.info(String.format("[MobiusCore] Found %s [ %s ] with checksum %s", searge, obf, hashtext.toUpperCase())); - - return hashtext.toUpperCase(); - } - catch (Exception e) { - } - - return "00000000000000000000000000000000"; - } - - protected MethodNode getMethod(ClassNode classNode, String methodName){ + return writer.toByteArray(); + } + + /* + * Inject a new method with a new signature to the list of methods. + */ + protected byte[] injectMethod(String className, MethodDescriptor methodDesc, byte[] vanillaBytes) { + + try { + byte[] coremodBytes = this.getJarClass(className); + + ClassNode vanillaNode = new ClassNode(); + ClassReader vanillaReader = new ClassReader(vanillaBytes); + ClassNode coremodNode = new ClassNode(); + ClassReader coremodReader = new ClassReader(coremodBytes); + + vanillaReader.accept(vanillaNode, 0); + coremodReader.accept(coremodNode, 0); + + MethodNode coremodMethodNode = null; + for (MethodNode node : coremodNode.methods) { + try { + if (node != null + && node.desc.equals(methodDesc.getDescriptor()) + && (node.name.equals(methodDesc.getMethodName()))) { + CoreDescription.log.info(String.format( + "Found method node %s.%s %s in Coremod. Injecting !", + className, methodDesc.getMethodName(), methodDesc.getDescriptor())); + coremodMethodNode = node; + } + } catch (Exception e) { + // System.out.printf("Error while parsing %s %s\n", className, node); + } + } + + if (coremodMethodNode == null) { + CoreDescription.log.fatal(String.format( + "Method node %s.%s %s not found in Coremod ! This is going to crash !.", + className, methodDesc.getMethodName(), methodDesc.getDescriptor())); + } + + coremodMethodNode.accept(vanillaNode); + // vanillaNode.methods.add(coremodMethodNode); + + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + vanillaNode.accept(writer); + return writer.toByteArray(); + } catch (ClassFormatError e) { + CoreDescription.log.warn("Class already injected."); + return vanillaBytes; + } + } + + public static String dumpChecksum(byte[] data, String obf, String searge) { + try { + // System.out.printf("[MobiusCore] Found %s with checksum %s\n", filename, + // MessageDigest.getInstance("MD5").digest(data)); + + MessageDigest m = MessageDigest.getInstance("MD5"); + m.reset(); + m.update(data); + byte[] digest = m.digest(); + BigInteger bigInt = new BigInteger(1, digest); + String hashtext = bigInt.toString(16); + // Now we need to zero pad it if you actually want the full 32 chars. + while (hashtext.length() < 32) { + hashtext = "0" + hashtext; + } + + if (obf.equals(searge)) + CoreDescription.log.info(String.format("Found %s with checksum %s", searge, hashtext.toUpperCase())); + else + CoreDescription.log.info(String.format( + "[MobiusCore] Found %s [ %s ] with checksum %s", searge, obf, hashtext.toUpperCase())); + + return hashtext.toUpperCase(); + } catch (Exception e) { + } + + return "00000000000000000000000000000000"; + } + + protected MethodNode getMethod(ClassNode classNode, String methodName) { for (MethodNode methodNode : classNode.methods) - if (String.format("%s %s", methodNode.name, methodNode.desc).equals(methodName)) - return methodNode; + if (String.format("%s %s", methodNode.name, methodNode.desc).equals(methodName)) return methodNode; throw new RuntimeException(String.format("Method %s not found in %s\n", methodName, classNode.name)); - } - - protected List getMethods(ClassNode classNode, String methodName){ - List methods = new ArrayList(); - for (MethodNode methodNode : classNode.methods) - if (methodNode.name.equals(methodName)) - methods.add(methodNode); - - if (methods.size() > 0) - return methods; - else - throw new RuntimeException(String.format("Method %s not found in %s\n", methodName, classNode.name)); - } + } + + protected List getMethods(ClassNode classNode, String methodName) { + List methods = new ArrayList(); + for (MethodNode methodNode : classNode.methods) if (methodNode.name.equals(methodName)) methods.add(methodNode); + + if (methods.size() > 0) return methods; + else throw new RuntimeException(String.format("Method %s not found in %s\n", methodName, classNode.name)); + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerASMEventHandler.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerASMEventHandler.java index 2baf5e4..f5dce85 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerASMEventHandler.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerASMEventHandler.java @@ -1,10 +1,10 @@ package mcp.mobius.mobiuscore.asm.transformers.common; +import static org.objectweb.asm.Opcodes.*; + import mcp.mobius.mobiuscore.asm.Opcode; import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import static org.objectweb.asm.Opcodes.*; - import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.AbstractInsnNode; @@ -13,87 +13,86 @@ import org.objectweb.asm.tree.MethodNode; public class TransformerASMEventHandler extends TransformerBase { - /* SHOULD WORK BOTH SIDES */ - - private static String ASMEH_INVOKE; - private static String ASMEH_INIT; - - private static AbstractInsnNode[] ASMEH_INVOKE_PATTERN; - - private static AbstractInsnNode[] ASMEH_INVOKE_PAYLOAD_PRE; - private static AbstractInsnNode[] ASMEH_INVOKE_PAYLOAD_POST; + /* SHOULD WORK BOTH SIDES */ - private static AbstractInsnNode[] ASMEH_INIT_PAYLOAD_PRE; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - ASMEH_INVOKE = "invoke (Lcpw/mods/fml/common/eventhandler/Event;)V"; - ASMEH_INIT = " (Ljava/lang/Object;Ljava/lang/reflect/Method;Lcpw/mods/fml/common/ModContainer;)V"; - - ASMEH_INVOKE_PATTERN = new AbstractInsnNode[] - { - Opcode.ALOAD(-1), - Opcode.GETFIELD("cpw/mods/fml/common/eventhandler/ASMEventHandler.handler Lcpw/mods/fml/common/eventhandler/IEventListener;"), - Opcode.ALOAD(-1), - Opcode.INVOKEINTERFACE("cpw/mods/fml/common/eventhandler/IEventListener.invoke (Lcpw/mods/fml/common/eventhandler/Event;)V") - }; + private static String ASMEH_INVOKE; + private static String ASMEH_INIT; - - ASMEH_INIT_PAYLOAD_PRE = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.ALOAD(2), - Opcode.INVOKEVIRTUAL("java/lang/reflect/Method.getDeclaringClass ()Ljava/lang/Class;"), - Opcode.INVOKEVIRTUAL("java/lang/Class.getCanonicalName ()Ljava/lang/String;"), - Opcode.PUTFIELD("cpw/mods/fml/common/eventhandler/ASMEventHandler.package_ Ljava/lang/String;"), - }; + private static AbstractInsnNode[] ASMEH_INVOKE_PATTERN; + + private static AbstractInsnNode[] ASMEH_INVOKE_PAYLOAD_PRE; + private static AbstractInsnNode[] ASMEH_INVOKE_PAYLOAD_POST; + + private static AbstractInsnNode[] ASMEH_INIT_PAYLOAD_PRE; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + ASMEH_INVOKE = "invoke (Lcpw/mods/fml/common/eventhandler/Event;)V"; + ASMEH_INIT = " (Ljava/lang/Object;Ljava/lang/reflect/Method;Lcpw/mods/fml/common/ModContainer;)V"; + + ASMEH_INVOKE_PATTERN = new AbstractInsnNode[] { + Opcode.ALOAD(-1), + Opcode.GETFIELD( + "cpw/mods/fml/common/eventhandler/ASMEventHandler.handler Lcpw/mods/fml/common/eventhandler/IEventListener;"), + Opcode.ALOAD(-1), + Opcode.INVOKEINTERFACE( + "cpw/mods/fml/common/eventhandler/IEventListener.invoke (Lcpw/mods/fml/common/eventhandler/Event;)V") + }; + + ASMEH_INIT_PAYLOAD_PRE = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.ALOAD(2), + Opcode.INVOKEVIRTUAL("java/lang/reflect/Method.getDeclaringClass ()Ljava/lang/Class;"), + Opcode.INVOKEVIRTUAL("java/lang/Class.getCanonicalName ()Ljava/lang/String;"), + Opcode.PUTFIELD("cpw/mods/fml/common/eventhandler/ASMEventHandler.package_ Ljava/lang/String;"), + }; + + ASMEH_INVOKE_PAYLOAD_PRE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.EVENT_INVOKE.name(), profilerType), + Opcode.INVOKEVIRTUAL(profilerClass, "start", "()V") + }; + + ASMEH_INVOKE_PAYLOAD_POST = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.EVENT_INVOKE.name(), profilerType), + Opcode.ALOAD(1), + Opcode.ALOAD(0), + Opcode.GETFIELD("cpw/mods/fml/common/eventhandler/ASMEventHandler.package_ Ljava/lang/String;"), + Opcode.ALOAD(0), + Opcode.GETFIELD( + "cpw/mods/fml/common/eventhandler/ASMEventHandler.handler Lcpw/mods/fml/common/eventhandler/IEventListener;"), + Opcode.ALOAD(0), + Opcode.GETFIELD( + "cpw/mods/fml/common/eventhandler/ASMEventHandler.owner Lcpw/mods/fml/common/ModContainer;"), + Opcode.INVOKEVIRTUAL( + profilerClass, + "stop", + "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V") + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); - - ASMEH_INVOKE_PAYLOAD_PRE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.EVENT_INVOKE.name(), profilerType), - Opcode.INVOKEVIRTUAL(profilerClass, "start", "()V") - }; - - ASMEH_INVOKE_PAYLOAD_POST = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.EVENT_INVOKE.name(), profilerType), - Opcode.ALOAD(1), - Opcode.ALOAD(0), - Opcode.GETFIELD("cpw/mods/fml/common/eventhandler/ASMEventHandler.package_ Ljava/lang/String;"), - Opcode.ALOAD(0), - Opcode.GETFIELD("cpw/mods/fml/common/eventhandler/ASMEventHandler.handler Lcpw/mods/fml/common/eventhandler/IEventListener;"), - Opcode.ALOAD(0), - Opcode.GETFIELD("cpw/mods/fml/common/eventhandler/ASMEventHandler.owner Lcpw/mods/fml/common/ModContainer;"), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V") - }; - - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes) { - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); - - MethodNode initNode = this.getMethod(classNode, ASMEH_INIT); + + MethodNode initNode = this.getMethod(classNode, ASMEH_INIT); this.applyPayloadFirst(initNode, ASMEH_INIT_PAYLOAD_PRE); - + MethodNode invokeNode = this.getMethod(classNode, ASMEH_INVOKE); - this.applyPayloadBefore(invokeNode, ASMEH_INVOKE_PATTERN, ASMEH_INVOKE_PAYLOAD_PRE); - this.applyPayloadAfter (invokeNode, ASMEH_INVOKE_PATTERN, ASMEH_INVOKE_PAYLOAD_POST); - + this.applyPayloadBefore(invokeNode, ASMEH_INVOKE_PATTERN, ASMEH_INVOKE_PAYLOAD_PRE); + this.applyPayloadAfter(invokeNode, ASMEH_INVOKE_PATTERN, ASMEH_INVOKE_PAYLOAD_POST); + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(writer); - - writer.visitField(ACC_PRIVATE + ACC_FINAL, "package_", "Ljava/lang/String;", null, null); - - return writer.toByteArray(); - } + writer.visitField(ACC_PRIVATE + ACC_FINAL, "package_", "Ljava/lang/String;", null, null); + + return writer.toByteArray(); + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLCommonHandler.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLCommonHandler.java index b2540c3..a18af62 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLCommonHandler.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLCommonHandler.java @@ -4,7 +4,6 @@ import mcp.mobius.mobiuscore.asm.ObfTable; import mcp.mobius.mobiuscore.asm.Opcode; import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; import mcp.mobius.mobiuscore.profiler.ProfilerSection; - import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.AbstractInsnNode; @@ -13,82 +12,77 @@ import org.objectweb.asm.tree.MethodNode; public class TransformerFMLCommonHandler extends TransformerBase { - //(Ljava/util/EnumSet;Lcpw/mods/fml/relauncher/Side;[Ljava/lang/Object;)V - private static String FMLCH_ONPRESERVERTICK; - private static String FMLCH_ONPOSTSERVERTICK; - private static String FMLCH_ONPREWORLDTICK; - private static String FMLCH_ONPOSTWORLDTICK; - - private static AbstractInsnNode[] FMLCH_PAYLOAD_PRESERVERTICK; - private static AbstractInsnNode[] FMLCH_PAYLOAD_POSTSERVERTICK; - - private static AbstractInsnNode[] FMLCH_PAYLOAD_PREWORLDTICK; - private static AbstractInsnNode[] FMLCH_PAYLOAD_POSTWORLDTICK; - - - private static boolean isEclipse; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - FMLCH_ONPRESERVERTICK = "onPreServerTick ()V"; - FMLCH_ONPOSTSERVERTICK = "onPostServerTick ()V"; - - FMLCH_ONPREWORLDTICK = ObfTable.FMLCH_PREWORLDTICK.getFullDescriptor(); - FMLCH_ONPOSTWORLDTICK = ObfTable.FMLCH_POSTWORLDTICK.getFullDescriptor(); - - - FMLCH_PAYLOAD_PRESERVERTICK = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.TICK.name(), profilerType), - Opcode.INVOKEVIRTUAL(profilerClass, "start", "()V"), - }; - - FMLCH_PAYLOAD_POSTSERVERTICK = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.TICK.name(), profilerType), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "()V"), - }; - - FMLCH_PAYLOAD_PREWORLDTICK = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.DIMENSION_TICK.name(), profilerType), - Opcode.ALOAD(1), - Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V")}; - - FMLCH_PAYLOAD_POSTWORLDTICK = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.DIMENSION_TICK.name(), profilerType), - Opcode.ALOAD(1), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V")}; - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes) { - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - + // (Ljava/util/EnumSet;Lcpw/mods/fml/relauncher/Side;[Ljava/lang/Object;)V + private static String FMLCH_ONPRESERVERTICK; + private static String FMLCH_ONPOSTSERVERTICK; + private static String FMLCH_ONPREWORLDTICK; + private static String FMLCH_ONPOSTWORLDTICK; + + private static AbstractInsnNode[] FMLCH_PAYLOAD_PRESERVERTICK; + private static AbstractInsnNode[] FMLCH_PAYLOAD_POSTSERVERTICK; + + private static AbstractInsnNode[] FMLCH_PAYLOAD_PREWORLDTICK; + private static AbstractInsnNode[] FMLCH_PAYLOAD_POSTWORLDTICK; + + private static boolean isEclipse; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + FMLCH_ONPRESERVERTICK = "onPreServerTick ()V"; + FMLCH_ONPOSTSERVERTICK = "onPostServerTick ()V"; + + FMLCH_ONPREWORLDTICK = ObfTable.FMLCH_PREWORLDTICK.getFullDescriptor(); + FMLCH_ONPOSTWORLDTICK = ObfTable.FMLCH_POSTWORLDTICK.getFullDescriptor(); + + FMLCH_PAYLOAD_PRESERVERTICK = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.TICK.name(), profilerType), + Opcode.INVOKEVIRTUAL(profilerClass, "start", "()V"), + }; + + FMLCH_PAYLOAD_POSTSERVERTICK = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.TICK.name(), profilerType), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "()V"), + }; + + FMLCH_PAYLOAD_PREWORLDTICK = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.DIMENSION_TICK.name(), profilerType), + Opcode.ALOAD(1), + Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") + }; + + FMLCH_PAYLOAD_POSTWORLDTICK = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.DIMENSION_TICK.name(), profilerType), + Opcode.ALOAD(1), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); + classReader.accept(classNode, 0); - - MethodNode preServerTickNode = this.getMethod(classNode, FMLCH_ONPRESERVERTICK); + + MethodNode preServerTickNode = this.getMethod(classNode, FMLCH_ONPRESERVERTICK); this.applyPayloadFirst(preServerTickNode, FMLCH_PAYLOAD_PRESERVERTICK); - - MethodNode postServerTickNode = this.getMethod(classNode, FMLCH_ONPOSTSERVERTICK); + + MethodNode postServerTickNode = this.getMethod(classNode, FMLCH_ONPOSTSERVERTICK); this.applyPayloadLast(postServerTickNode, FMLCH_PAYLOAD_POSTSERVERTICK); - - MethodNode preworldTick = this.getMethod(classNode, FMLCH_ONPREWORLDTICK); + + MethodNode preworldTick = this.getMethod(classNode, FMLCH_ONPREWORLDTICK); this.applyPayloadFirst(preworldTick, FMLCH_PAYLOAD_PREWORLDTICK); - + MethodNode postWorldTick = this.getMethod(classNode, FMLCH_ONPOSTWORLDTICK); this.applyPayloadLast(postWorldTick, FMLCH_PAYLOAD_POSTWORLDTICK); - + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(writer); - - return writer.toByteArray(); - } + return writer.toByteArray(); + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLOutboundHandler.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLOutboundHandler.java index af8c8ab..ddc4deb 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLOutboundHandler.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLOutboundHandler.java @@ -1,58 +1,55 @@ package mcp.mobius.mobiuscore.asm.transformers.common; +import mcp.mobius.mobiuscore.asm.Opcode; +import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; +import mcp.mobius.mobiuscore.profiler.ProfilerSection; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; -import mcp.mobius.mobiuscore.asm.Opcode; -import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; -import mcp.mobius.mobiuscore.profiler.ProfilerSection; - public class TransformerFMLOutboundHandler extends TransformerBase { - private static String FMLOH_WRITE; - - private static AbstractInsnNode[] FMLOH_WRITE_PATTERN; - private static AbstractInsnNode[] FMLOH_WRITE_PAYLOAD; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - FMLOH_WRITE = "write (Lio/netty/channel/ChannelHandlerContext;Ljava/lang/Object;Lio/netty/channel/ChannelPromise;)V"; - - FMLOH_WRITE_PATTERN = new AbstractInsnNode[] - { - Opcode.INVOKEVIRTUAL("cpw/mods/fml/common/network/handshake/NetworkDispatcher.sendProxy (Lcpw/mods/fml/common/network/internal/FMLProxyPacket;)V"), - }; - - FMLOH_WRITE_PAYLOAD = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.PACKET_OUTBOUND.name(), profilerType), - Opcode.ALOAD(4), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V"), - }; - - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes) { - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - + private static String FMLOH_WRITE; + + private static AbstractInsnNode[] FMLOH_WRITE_PATTERN; + private static AbstractInsnNode[] FMLOH_WRITE_PAYLOAD; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + FMLOH_WRITE = + "write (Lio/netty/channel/ChannelHandlerContext;Ljava/lang/Object;Lio/netty/channel/ChannelPromise;)V"; + + FMLOH_WRITE_PATTERN = new AbstractInsnNode[] { + Opcode.INVOKEVIRTUAL( + "cpw/mods/fml/common/network/handshake/NetworkDispatcher.sendProxy (Lcpw/mods/fml/common/network/internal/FMLProxyPacket;)V"), + }; + + FMLOH_WRITE_PAYLOAD = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.PACKET_OUTBOUND.name(), profilerType), + Opcode.ALOAD(4), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V"), + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); + classReader.accept(classNode, 0); - - MethodNode write = this.getMethod(classNode, FMLOH_WRITE); + + MethodNode write = this.getMethod(classNode, FMLOH_WRITE); this.applyPayloadAfter(write, FMLOH_WRITE_PATTERN, FMLOH_WRITE_PAYLOAD); - + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(writer); - - return writer.toByteArray(); - } + return writer.toByteArray(); + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLProxyPacket.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLProxyPacket.java index 2bcc7f3..81c175f 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLProxyPacket.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerFMLProxyPacket.java @@ -1,53 +1,49 @@ package mcp.mobius.mobiuscore.asm.transformers.common; +import mcp.mobius.mobiuscore.asm.ObfTable; +import mcp.mobius.mobiuscore.asm.Opcode; +import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; +import mcp.mobius.mobiuscore.profiler.ProfilerSection; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; -import mcp.mobius.mobiuscore.asm.ObfTable; -import mcp.mobius.mobiuscore.asm.Opcode; -import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; -import mcp.mobius.mobiuscore.profiler.ProfilerSection; - public class TransformerFMLProxyPacket extends TransformerBase { - private static String FMLPP_PROCESS; - - private static AbstractInsnNode[] FMLPP_PROCESS_PAYLOAD; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - FMLPP_PROCESS = ObfTable.FMLPP_PROCESSPACKET.getFullDescriptor(); - - FMLPP_PROCESS_PAYLOAD = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.PACKET_INBOUND.name(), profilerType), - Opcode.ALOAD(0), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V"), - }; - - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes) { - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - + private static String FMLPP_PROCESS; + + private static AbstractInsnNode[] FMLPP_PROCESS_PAYLOAD; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + FMLPP_PROCESS = ObfTable.FMLPP_PROCESSPACKET.getFullDescriptor(); + + FMLPP_PROCESS_PAYLOAD = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.PACKET_INBOUND.name(), profilerType), + Opcode.ALOAD(0), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V"), + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); + classReader.accept(classNode, 0); - - MethodNode process = this.getMethod(classNode, FMLPP_PROCESS); + + MethodNode process = this.getMethod(classNode, FMLPP_PROCESS); this.applyPayloadFirst(process, FMLPP_PROCESS_PAYLOAD); - + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(writer); - - return writer.toByteArray(); - } + return writer.toByteArray(); + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerMessageDeserializer.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerMessageDeserializer.java index 2054da7..80e59a7 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerMessageDeserializer.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerMessageDeserializer.java @@ -1,5 +1,8 @@ package mcp.mobius.mobiuscore.asm.transformers.common; +import mcp.mobius.mobiuscore.asm.ObfTable; +import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; +import mcp.mobius.mobiuscore.profiler.ProfilerSection; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; @@ -10,58 +13,61 @@ import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; -import mcp.mobius.mobiuscore.asm.ObfTable; -import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; -import mcp.mobius.mobiuscore.profiler.ProfilerSection; - public class TransformerMessageDeserializer extends TransformerBase { - private static String DESERIALIZER_DECODE; - - private static AbstractInsnNode[] DESERIALIZER_PATTERN; - private static AbstractInsnNode[] DESERIALIZER_PAYLOAD; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - DESERIALIZER_DECODE = ObfTable.DESERIALIZER_DECODE.getFullDescriptor(); + private static String DESERIALIZER_DECODE; + + private static AbstractInsnNode[] DESERIALIZER_PATTERN; + private static AbstractInsnNode[] DESERIALIZER_PAYLOAD; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + DESERIALIZER_DECODE = ObfTable.DESERIALIZER_DECODE.getFullDescriptor(); + + DESERIALIZER_PATTERN = new AbstractInsnNode[] { + new VarInsnNode(Opcodes.ALOAD, -1), + new VarInsnNode(Opcodes.ALOAD, -1), + new MethodInsnNode( + Opcodes.INVOKEVIRTUAL, + ObfTable.PACKET_READPACKETDATA.getClazz(), + ObfTable.PACKET_READPACKETDATA.getName(), + ObfTable.PACKET_READPACKETDATA.getDescriptor(), + false), + }; + + DESERIALIZER_PAYLOAD = new AbstractInsnNode[] { + new FieldInsnNode(Opcodes.GETSTATIC, profilerClass, ProfilerSection.PACKET_INBOUND.name(), profilerType), + new VarInsnNode(Opcodes.ALOAD, 7), + new VarInsnNode(Opcodes.ALOAD, 5), + new MethodInsnNode( + Opcodes.INVOKEVIRTUAL, + ObfTable.PACKETBUFFER_CAPACITY.getClazz(), + ObfTable.PACKETBUFFER_CAPACITY.getName(), + ObfTable.PACKETBUFFER_CAPACITY.getDescriptor(), + false), + new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false), + new MethodInsnNode( + Opcodes.INVOKEVIRTUAL, profilerClass, "start", "(Ljava/lang/Object;Ljava/lang/Object;)V", false), + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); - DESERIALIZER_PATTERN = new AbstractInsnNode[] - { - new VarInsnNode (Opcodes.ALOAD, -1), - new VarInsnNode (Opcodes.ALOAD, -1), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, ObfTable.PACKET_READPACKETDATA.getClazz(), ObfTable.PACKET_READPACKETDATA.getName(), ObfTable.PACKET_READPACKETDATA.getDescriptor(), false), - }; - - DESERIALIZER_PAYLOAD = new AbstractInsnNode[] - { - new FieldInsnNode (Opcodes.GETSTATIC, profilerClass, ProfilerSection.PACKET_INBOUND.name(), profilerType), - new VarInsnNode (Opcodes.ALOAD, 7), - new VarInsnNode (Opcodes.ALOAD, 5), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, ObfTable.PACKETBUFFER_CAPACITY.getClazz(), ObfTable.PACKETBUFFER_CAPACITY.getName(), ObfTable.PACKETBUFFER_CAPACITY.getDescriptor(), false), - new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "start", "(Ljava/lang/Object;Ljava/lang/Object;)V", false), - }; - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes) { - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); - - MethodNode decode = this.getMethod(classNode, DESERIALIZER_DECODE); - this.applyPayloadBefore(decode, DESERIALIZER_PATTERN, DESERIALIZER_PAYLOAD); - - ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES |ClassWriter.COMPUTE_MAXS); - classNode.accept(writer); - - return writer.toByteArray(); - } + MethodNode decode = this.getMethod(classNode, DESERIALIZER_DECODE); + this.applyPayloadBefore(decode, DESERIALIZER_PATTERN, DESERIALIZER_PAYLOAD); + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + classNode.accept(writer); + + return writer.toByteArray(); + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerMessageSerializer.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerMessageSerializer.java index 8922238..0ee8986 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerMessageSerializer.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerMessageSerializer.java @@ -1,5 +1,8 @@ package mcp.mobius.mobiuscore.asm.transformers.common; +import mcp.mobius.mobiuscore.asm.ObfTable; +import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; +import mcp.mobius.mobiuscore.profiler.ProfilerSection; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; @@ -10,57 +13,61 @@ import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; -import mcp.mobius.mobiuscore.asm.ObfTable; -import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; -import mcp.mobius.mobiuscore.profiler.ProfilerSection; - public class TransformerMessageSerializer extends TransformerBase { - private static String SERIALIZER_ENCODE; - - private static AbstractInsnNode[] SERIALIZER_PATTERN; - private static AbstractInsnNode[] SERIALIZER_PAYLOAD; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - SERIALIZER_ENCODE = ObfTable.SERIALIZER_ENCODE.getFullDescriptor(); + private static String SERIALIZER_ENCODE; - SERIALIZER_PATTERN = new AbstractInsnNode[] - { - new VarInsnNode (Opcodes.ALOAD, -1), - new VarInsnNode (Opcodes.ALOAD, -1), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, ObfTable.PACKET_WRITEPACKETDATA.getClazz(), ObfTable.PACKET_WRITEPACKETDATA.getName(), ObfTable.PACKET_WRITEPACKETDATA.getDescriptor(), false) - }; + private static AbstractInsnNode[] SERIALIZER_PATTERN; + private static AbstractInsnNode[] SERIALIZER_PAYLOAD; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + SERIALIZER_ENCODE = ObfTable.SERIALIZER_ENCODE.getFullDescriptor(); + + SERIALIZER_PATTERN = new AbstractInsnNode[] { + new VarInsnNode(Opcodes.ALOAD, -1), + new VarInsnNode(Opcodes.ALOAD, -1), + new MethodInsnNode( + Opcodes.INVOKEVIRTUAL, + ObfTable.PACKET_WRITEPACKETDATA.getClazz(), + ObfTable.PACKET_WRITEPACKETDATA.getName(), + ObfTable.PACKET_WRITEPACKETDATA.getDescriptor(), + false) + }; + + SERIALIZER_PAYLOAD = new AbstractInsnNode[] { + new FieldInsnNode(Opcodes.GETSTATIC, profilerClass, ProfilerSection.PACKET_OUTBOUND.name(), profilerType), + new VarInsnNode(Opcodes.ALOAD, 2), + new VarInsnNode(Opcodes.ALOAD, 5), + new MethodInsnNode( + Opcodes.INVOKEVIRTUAL, + ObfTable.PACKETBUFFER_READABLE.getClazz(), + ObfTable.PACKETBUFFER_READABLE.getName(), + ObfTable.PACKETBUFFER_READABLE.getDescriptor(), + false), + new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false), + new MethodInsnNode( + Opcodes.INVOKEVIRTUAL, profilerClass, "start", "(Ljava/lang/Object;Ljava/lang/Object;)V", false), + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); - SERIALIZER_PAYLOAD = new AbstractInsnNode[] - { - new FieldInsnNode (Opcodes.GETSTATIC, profilerClass, ProfilerSection.PACKET_OUTBOUND.name(), profilerType), - new VarInsnNode (Opcodes.ALOAD, 2), - new VarInsnNode (Opcodes.ALOAD, 5), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, ObfTable.PACKETBUFFER_READABLE.getClazz(), ObfTable.PACKETBUFFER_READABLE.getName(), ObfTable.PACKETBUFFER_READABLE.getDescriptor(), false), - new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "start", "(Ljava/lang/Object;Ljava/lang/Object;)V", false), - }; - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes) { - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); - - MethodNode encode = this.getMethod(classNode, SERIALIZER_ENCODE); - this.applyPayloadAfter(encode, SERIALIZER_PATTERN, SERIALIZER_PAYLOAD); - - ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES |ClassWriter.COMPUTE_MAXS); - classNode.accept(writer); - - return writer.toByteArray(); - } + MethodNode encode = this.getMethod(classNode, SERIALIZER_ENCODE); + this.applyPayloadAfter(encode, SERIALIZER_PATTERN, SERIALIZER_PAYLOAD); + + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + classNode.accept(writer); + + return writer.toByteArray(); + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerRenderManager.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerRenderManager.java index 2d32eca..4ae61c5 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerRenderManager.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerRenderManager.java @@ -1,14 +1,12 @@ package mcp.mobius.mobiuscore.asm.transformers.common; -import org.objectweb.asm.tree.AbstractInsnNode; - import mcp.mobius.mobiuscore.asm.ObfTable; import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; import mcp.mobius.mobiuscore.profiler.ProfilerSection; - import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.MethodInsnNode; @@ -17,59 +15,58 @@ import org.objectweb.asm.tree.VarInsnNode; public class TransformerRenderManager extends TransformerBase { - //private static String RM_RENDERENT; - //private static String RM_RENDERPOSYAW; - private static String RM_RENDER; - - private static AbstractInsnNode[] RM_RENDER_PAYLOAD_TOP; - private static AbstractInsnNode[] RM_RENDER_PAYLOAD_BOTTOM; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - //RM_RENDERENT = ObfTable.RENDERMANAGER_RENDERENTITY.getFullDescriptor(); - //RM_RENDERPOSYAW = ObfTable.RENDERMANAGER_RENDERPOSYAW.getFullDescriptor(); - - RM_RENDER = ObfTable.RENDERMANAGER_RENDER.getFullDescriptor(); - - RM_RENDER_PAYLOAD_TOP = new AbstractInsnNode[] - {new FieldInsnNode(Opcodes.GETSTATIC, profilerClass, ProfilerSection.RENDER_ENTITY.name(), profilerType), - new VarInsnNode(Opcodes.ALOAD, 1), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "start", "(Ljava/lang/Object;)V", false)}; - - RM_RENDER_PAYLOAD_BOTTOM = new AbstractInsnNode[] - {new FieldInsnNode(Opcodes.GETSTATIC, profilerClass, ProfilerSection.RENDER_ENTITY.name(), profilerType), - new VarInsnNode(Opcodes.ALOAD, 1), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "stop", "(Ljava/lang/Object;)V", false)}; - - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes) { - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - + // private static String RM_RENDERENT; + // private static String RM_RENDERPOSYAW; + private static String RM_RENDER; + + private static AbstractInsnNode[] RM_RENDER_PAYLOAD_TOP; + private static AbstractInsnNode[] RM_RENDER_PAYLOAD_BOTTOM; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + // RM_RENDERENT = ObfTable.RENDERMANAGER_RENDERENTITY.getFullDescriptor(); + // RM_RENDERPOSYAW = ObfTable.RENDERMANAGER_RENDERPOSYAW.getFullDescriptor(); + + RM_RENDER = ObfTable.RENDERMANAGER_RENDER.getFullDescriptor(); + + RM_RENDER_PAYLOAD_TOP = new AbstractInsnNode[] { + new FieldInsnNode(Opcodes.GETSTATIC, profilerClass, ProfilerSection.RENDER_ENTITY.name(), profilerType), + new VarInsnNode(Opcodes.ALOAD, 1), + new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "start", "(Ljava/lang/Object;)V", false) + }; + + RM_RENDER_PAYLOAD_BOTTOM = new AbstractInsnNode[] { + new FieldInsnNode(Opcodes.GETSTATIC, profilerClass, ProfilerSection.RENDER_ENTITY.name(), profilerType), + new VarInsnNode(Opcodes.ALOAD, 1), + new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "stop", "(Ljava/lang/Object;)V", false) + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); + classReader.accept(classNode, 0); - - MethodNode renderEntNode = this.getMethod(classNode, RM_RENDER); + + MethodNode renderEntNode = this.getMethod(classNode, RM_RENDER); this.applyPayloadFirst(renderEntNode, RM_RENDER_PAYLOAD_TOP); - - - this.applyPayloadLast (renderEntNode, RM_RENDER_PAYLOAD_BOTTOM); - + + this.applyPayloadLast(renderEntNode, RM_RENDER_PAYLOAD_BOTTOM); + /* MethodNode renderPosYawNode = this.getMethod(classNode, RM_RENDERPOSYAW); this.applyPayloadFirst(renderPosYawNode, RM_RENDER_PAYLOAD_TOP); - this.applyPayloadLast (renderPosYawNode, RM_RENDER_PAYLOAD_BOTTOM); + this.applyPayloadLast (renderPosYawNode, RM_RENDER_PAYLOAD_BOTTOM); */ - + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(writer); - - return writer.toByteArray(); - } + return writer.toByteArray(); + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerTERenderer.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerTERenderer.java index bb59928..cf28890 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerTERenderer.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerTERenderer.java @@ -1,14 +1,12 @@ package mcp.mobius.mobiuscore.asm.transformers.common; -import org.objectweb.asm.tree.AbstractInsnNode; - import mcp.mobius.mobiuscore.asm.ObfTable; import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; import mcp.mobius.mobiuscore.profiler.ProfilerSection; - import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.MethodInsnNode; @@ -17,47 +15,47 @@ import org.objectweb.asm.tree.VarInsnNode; public class TransformerTERenderer extends TransformerBase { - private static String TER_RENDER; - - private static AbstractInsnNode[] TER_RENDER_PAYLOAD_TOP; - private static AbstractInsnNode[] TER_RENDER_PAYLOAD_BOTTOM; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - //TER_RENDER = "a (Lasp;F)V"; - TER_RENDER = ObfTable.TERENDER_RENDERAT.getFullDescriptor(); - - TER_RENDER_PAYLOAD_TOP = new AbstractInsnNode[] - {new FieldInsnNode(Opcodes.GETSTATIC, profilerClass, ProfilerSection.RENDER_TILEENTITY.name(), profilerType), - new VarInsnNode(Opcodes.ALOAD, 1), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "start", "(Ljava/lang/Object;)V", false)}; - - TER_RENDER_PAYLOAD_BOTTOM = new AbstractInsnNode[] - {new FieldInsnNode(Opcodes.GETSTATIC, profilerClass, ProfilerSection.RENDER_TILEENTITY.name(), profilerType), - new VarInsnNode(Opcodes.ALOAD, 1), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "stop", "(Ljava/lang/Object;)V", false)}; - - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes) { - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - + private static String TER_RENDER; + + private static AbstractInsnNode[] TER_RENDER_PAYLOAD_TOP; + private static AbstractInsnNode[] TER_RENDER_PAYLOAD_BOTTOM; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + // TER_RENDER = "a (Lasp;F)V"; + TER_RENDER = ObfTable.TERENDER_RENDERAT.getFullDescriptor(); + + TER_RENDER_PAYLOAD_TOP = new AbstractInsnNode[] { + new FieldInsnNode(Opcodes.GETSTATIC, profilerClass, ProfilerSection.RENDER_TILEENTITY.name(), profilerType), + new VarInsnNode(Opcodes.ALOAD, 1), + new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "start", "(Ljava/lang/Object;)V", false) + }; + + TER_RENDER_PAYLOAD_BOTTOM = new AbstractInsnNode[] { + new FieldInsnNode(Opcodes.GETSTATIC, profilerClass, ProfilerSection.RENDER_TILEENTITY.name(), profilerType), + new VarInsnNode(Opcodes.ALOAD, 1), + new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "stop", "(Ljava/lang/Object;)V", false) + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); + classReader.accept(classNode, 0); - - MethodNode renderEntNode = this.getMethod(classNode, TER_RENDER); + + MethodNode renderEntNode = this.getMethod(classNode, TER_RENDER); this.applyPayloadFirst(renderEntNode, TER_RENDER_PAYLOAD_TOP); - this.applyPayloadLast (renderEntNode, TER_RENDER_PAYLOAD_BOTTOM); - + this.applyPayloadLast(renderEntNode, TER_RENDER_PAYLOAD_BOTTOM); + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(writer); - - return writer.toByteArray(); - } + return writer.toByteArray(); + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerWorldServer.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerWorldServer.java index 6130c01..31d182a 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerWorldServer.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/common/TransformerWorldServer.java @@ -3,7 +3,6 @@ package mcp.mobius.mobiuscore.asm.transformers.common; import mcp.mobius.mobiuscore.asm.ObfTable; import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; import mcp.mobius.mobiuscore.profiler.ProfilerSection; - import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; @@ -16,66 +15,81 @@ import org.objectweb.asm.tree.VarInsnNode; public class TransformerWorldServer extends TransformerBase { - private static String WORLDSERVER_TICK; - - private static AbstractInsnNode[] WORLDSERVER_PAYLOAD_TICKSTART; - private static AbstractInsnNode[] WORLDSERVER_PAYLOAD_TICKEND; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - WORLDSERVER_TICK = ObfTable.WORLDSERVER_TICK.getFullDescriptor(); + private static String WORLDSERVER_TICK; - /* - WORLDSERVER_PAYLOAD_TICKSTART = new AbstractInsnNode[] - { - new FieldInsnNode (Opcodes.GETSTATIC, "mcp/mobius/mobiuscore/profiler/ProfilerRegistrar", "profilerWorldTick", "Lmcp/mobius/mobiuscore/profiler/IProfilerWorldTick;"), - new VarInsnNode (Opcodes.ALOAD, 0), - new FieldInsnNode (Opcodes.GETFIELD, "net/minecraft/world/WorldServer", "provider", "Lnet/minecraft/world/WorldProvider;"), - new FieldInsnNode (Opcodes.GETFIELD, "net/minecraft/world/WorldProvider", "dimensionId", "I"), - new MethodInsnNode(Opcodes.INVOKEINTERFACE, "mcp/mobius/mobiuscore/profiler/IProfilerWorldTick", "WorldTickStart", "(I)V"), - }; - */ + private static AbstractInsnNode[] WORLDSERVER_PAYLOAD_TICKSTART; + private static AbstractInsnNode[] WORLDSERVER_PAYLOAD_TICKEND; - WORLDSERVER_PAYLOAD_TICKSTART = new AbstractInsnNode[] - { - new FieldInsnNode (Opcodes.GETSTATIC, profilerClass, ProfilerSection.DIMENSION_BLOCKTICK.name(), profilerType), - new VarInsnNode (Opcodes.ALOAD, 0), - new FieldInsnNode (Opcodes.GETFIELD, ObfTable.WORLD_PROVIDER.getClazz(), ObfTable.WORLD_PROVIDER.getName(), ObfTable.WORLD_PROVIDER.getDescriptor()), - new FieldInsnNode (Opcodes.GETFIELD, ObfTable.WORLDPROVIDER_DIMID.getClazz(), ObfTable.WORLDPROVIDER_DIMID.getName(), ObfTable.WORLDPROVIDER_DIMID.getDescriptor()), - new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "start", "(Ljava/lang/Object;)V", false), - }; + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + WORLDSERVER_TICK = ObfTable.WORLDSERVER_TICK.getFullDescriptor(); + + /* + WORLDSERVER_PAYLOAD_TICKSTART = new AbstractInsnNode[] + { + new FieldInsnNode (Opcodes.GETSTATIC, "mcp/mobius/mobiuscore/profiler/ProfilerRegistrar", "profilerWorldTick", "Lmcp/mobius/mobiuscore/profiler/IProfilerWorldTick;"), + new VarInsnNode (Opcodes.ALOAD, 0), + new FieldInsnNode (Opcodes.GETFIELD, "net/minecraft/world/WorldServer", "provider", "Lnet/minecraft/world/WorldProvider;"), + new FieldInsnNode (Opcodes.GETFIELD, "net/minecraft/world/WorldProvider", "dimensionId", "I"), + new MethodInsnNode(Opcodes.INVOKEINTERFACE, "mcp/mobius/mobiuscore/profiler/IProfilerWorldTick", "WorldTickStart", "(I)V"), + }; + */ + + WORLDSERVER_PAYLOAD_TICKSTART = new AbstractInsnNode[] { + new FieldInsnNode( + Opcodes.GETSTATIC, profilerClass, ProfilerSection.DIMENSION_BLOCKTICK.name(), profilerType), + new VarInsnNode(Opcodes.ALOAD, 0), + new FieldInsnNode( + Opcodes.GETFIELD, + ObfTable.WORLD_PROVIDER.getClazz(), + ObfTable.WORLD_PROVIDER.getName(), + ObfTable.WORLD_PROVIDER.getDescriptor()), + new FieldInsnNode( + Opcodes.GETFIELD, + ObfTable.WORLDPROVIDER_DIMID.getClazz(), + ObfTable.WORLDPROVIDER_DIMID.getName(), + ObfTable.WORLDPROVIDER_DIMID.getDescriptor()), + new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false), + new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "start", "(Ljava/lang/Object;)V", false), + }; + + WORLDSERVER_PAYLOAD_TICKEND = new AbstractInsnNode[] { + new FieldInsnNode( + Opcodes.GETSTATIC, profilerClass, ProfilerSection.DIMENSION_BLOCKTICK.name(), profilerType), + new VarInsnNode(Opcodes.ALOAD, 0), + new FieldInsnNode( + Opcodes.GETFIELD, + ObfTable.WORLD_PROVIDER.getClazz(), + ObfTable.WORLD_PROVIDER.getName(), + ObfTable.WORLD_PROVIDER.getDescriptor()), + new FieldInsnNode( + Opcodes.GETFIELD, + ObfTable.WORLDPROVIDER_DIMID.getClazz(), + ObfTable.WORLDPROVIDER_DIMID.getName(), + ObfTable.WORLDPROVIDER_DIMID.getDescriptor()), + new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false), + new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "stop", "(Ljava/lang/Object;)V", false), + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); - WORLDSERVER_PAYLOAD_TICKEND = new AbstractInsnNode[] - { - new FieldInsnNode (Opcodes.GETSTATIC, profilerClass, ProfilerSection.DIMENSION_BLOCKTICK.name(), profilerType), - new VarInsnNode (Opcodes.ALOAD, 0), - new FieldInsnNode (Opcodes.GETFIELD, ObfTable.WORLD_PROVIDER.getClazz(), ObfTable.WORLD_PROVIDER.getName(), ObfTable.WORLD_PROVIDER.getDescriptor()), - new FieldInsnNode (Opcodes.GETFIELD, ObfTable.WORLDPROVIDER_DIMID.getClazz(), ObfTable.WORLDPROVIDER_DIMID.getName(), ObfTable.WORLDPROVIDER_DIMID.getDescriptor()), - new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false), - new MethodInsnNode(Opcodes.INVOKEVIRTUAL, profilerClass, "stop", "(Ljava/lang/Object;)V", false), - }; - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes) { - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); - - MethodNode tickNode = this.getMethod(classNode, WORLDSERVER_TICK); - this.applyPayloadFirst(tickNode, WORLDSERVER_PAYLOAD_TICKSTART); - this.applyPayloadLast (tickNode, WORLDSERVER_PAYLOAD_TICKEND); - - ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES |ClassWriter.COMPUTE_MAXS); - classNode.accept(writer); - - return writer.toByteArray(); - } + MethodNode tickNode = this.getMethod(classNode, WORLDSERVER_TICK); + this.applyPayloadFirst(tickNode, WORLDSERVER_PAYLOAD_TICKSTART); + this.applyPayloadLast(tickNode, WORLDSERVER_PAYLOAD_TICKEND); + + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + classNode.accept(writer); + + return writer.toByteArray(); + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/forge/TransformerWorld.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/forge/TransformerWorld.java index a261b47..b05edfc 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/forge/TransformerWorld.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/forge/TransformerWorld.java @@ -1,175 +1,176 @@ package mcp.mobius.mobiuscore.asm.transformers.forge; -import static org.objectweb.asm.Opcodes.ACC_FINAL; -import static org.objectweb.asm.Opcodes.ACC_PRIVATE; -import static org.objectweb.asm.Opcodes.ACC_PUBLIC; import mcp.mobius.mobiuscore.asm.CoreDescription; import mcp.mobius.mobiuscore.asm.ObfTable; import mcp.mobius.mobiuscore.asm.Opcode; import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; import mcp.mobius.mobiuscore.profiler.ProfilerSection; - import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.LineNumberNode; +import org.objectweb.asm.tree.MethodNode; -public class TransformerWorld extends TransformerBase{ +public class TransformerWorld extends TransformerBase { - private static String WORLD_UPDATEENTITIES; - private static String WORLD_INIT; - - //tileentity.updateEntity(); World:2215 - private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_TEUPDATE; + private static String WORLD_UPDATEENTITIES; + private static String WORLD_INIT; - //ProfilerRegistrar.profilerTileEntity.Start(tileentity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_TEUPDATE; + // tileentity.updateEntity(); World:2215 + private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_TEUPDATE; - //ProfilerRegistrar.profilerTileEntity.Stop(tileentity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE; - - //this.updateEntity(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_ENTUPDATE; + // ProfilerRegistrar.profilerTileEntity.Start(tileentity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_TEUPDATE; - //ProfilerRegistrar.profilerEntity.Start(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_ENTUPDATE; + // ProfilerRegistrar.profilerTileEntity.Stop(tileentity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE; - //ProfilerRegistrar.profilerEntity.Stop(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE; - - //World.loadedEntityList - private static AbstractInsnNode[] WORLD_PATTERN_LOADEDENTS; + // this.updateEntity(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_ENTUPDATE; - //World.loadedTileEntityList - private static AbstractInsnNode[] WORLD_PATTERN_LOADEDTILES; + // ProfilerRegistrar.profilerEntity.Start(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_ENTUPDATE; - //World.loadedEntityList - private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDENTS; + // ProfilerRegistrar.profilerEntity.Stop(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE; - //World.loadedTileEntityList - private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDTILES; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - WORLD_UPDATEENTITIES = ObfTable.WORLD_UPDATEENTITIES.getFullDescriptor(); //updateEntities.getFullDescriptor(); - WORLD_INIT = ObfTable.WORLD_INIT.getFullDescriptor(); - - WORLD_UPDATE_PATTERN_TEUPDATE = new AbstractInsnNode[] - { - new LineNumberNode(-1, new LabelNode()), - Opcode.ALOAD(-1), - Opcode.INVOKEVIRTUAL(ObfTable.TILEENTITY_UPDATEENTITY.getClazz(), ObfTable.TILEENTITY_UPDATEENTITY.getName(), ObfTable.TILEENTITY_UPDATEENTITY.getDescriptor()) - }; + // World.loadedEntityList + private static AbstractInsnNode[] WORLD_PATTERN_LOADEDENTS; - WORLD_UPDATE_PAYLOAD_START_TEUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), - Opcode.ALOAD(8), - Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") - }; + // World.loadedTileEntityList + private static AbstractInsnNode[] WORLD_PATTERN_LOADEDTILES; - WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), - Opcode.ALOAD(8), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") - }; - - WORLD_UPDATE_PATTERN_ENTUPDATE = new AbstractInsnNode[] - { - new LineNumberNode(-1, new LabelNode()), - Opcode.ALOAD(-1), - Opcode.ALOAD(-1), - Opcode.INVOKEVIRTUAL(ObfTable.WORLD_UPDATEENTITY.getClazz(), ObfTable.WORLD_UPDATEENTITY.getName(), ObfTable.WORLD_UPDATEENTITY.getDescriptor()) - }; + // World.loadedEntityList + private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDENTS; - WORLD_UPDATE_PAYLOAD_START_ENTUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), - Opcode.ALOAD(2), - Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") - }; + // World.loadedTileEntityList + private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDTILES; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + WORLD_UPDATEENTITIES = ObfTable.WORLD_UPDATEENTITIES.getFullDescriptor(); // updateEntities.getFullDescriptor(); + WORLD_INIT = ObfTable.WORLD_INIT.getFullDescriptor(); + + WORLD_UPDATE_PATTERN_TEUPDATE = new AbstractInsnNode[] { + new LineNumberNode(-1, new LabelNode()), + Opcode.ALOAD(-1), + Opcode.INVOKEVIRTUAL( + ObfTable.TILEENTITY_UPDATEENTITY.getClazz(), + ObfTable.TILEENTITY_UPDATEENTITY.getName(), + ObfTable.TILEENTITY_UPDATEENTITY.getDescriptor()) + }; + + WORLD_UPDATE_PAYLOAD_START_TEUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), + Opcode.ALOAD(8), + Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), + Opcode.ALOAD(8), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PATTERN_ENTUPDATE = new AbstractInsnNode[] { + new LineNumberNode(-1, new LabelNode()), + Opcode.ALOAD(-1), + Opcode.ALOAD(-1), + Opcode.INVOKEVIRTUAL( + ObfTable.WORLD_UPDATEENTITY.getClazz(), + ObfTable.WORLD_UPDATEENTITY.getName(), + ObfTable.WORLD_UPDATEENTITY.getDescriptor()) + }; + + WORLD_UPDATE_PAYLOAD_START_ENTUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), + Opcode.ALOAD(2), + Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), + Opcode.ALOAD(2), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") + }; + + WORLD_PATTERN_LOADEDENTS = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("java/util/ArrayList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDENTS.getClazz(), + ObfTable.WORLD_LOADEDENTS.getName(), + ObfTable.WORLD_LOADEDENTS.getDescriptor()) + }; + + WORLD_PATTERN_LOADEDTILES = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("java/util/ArrayList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDTILES.getClazz(), + ObfTable.WORLD_LOADEDTILES.getName(), + ObfTable.WORLD_LOADEDTILES.getDescriptor()) + }; + + WORLD_PAYLOAD_LOADEDENTS = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredEntityList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredEntityList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDENTS.getClazz(), + ObfTable.WORLD_LOADEDENTS.getName(), + ObfTable.WORLD_LOADEDENTS.getDescriptor()) + }; + + WORLD_PAYLOAD_LOADEDTILES = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredTileList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredTileList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDTILES.getClazz(), + ObfTable.WORLD_LOADEDTILES.getName(), + ObfTable.WORLD_LOADEDTILES.getDescriptor()) + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); - WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), - Opcode.ALOAD(2), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") - }; - - - WORLD_PATTERN_LOADEDENTS = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("java/util/ArrayList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDENTS.getClazz(), ObfTable.WORLD_LOADEDENTS.getName(), ObfTable.WORLD_LOADEDENTS.getDescriptor()) - }; - - WORLD_PATTERN_LOADEDTILES = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("java/util/ArrayList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDTILES.getClazz(), ObfTable.WORLD_LOADEDTILES.getName(), ObfTable.WORLD_LOADEDTILES.getDescriptor()) - }; - - WORLD_PAYLOAD_LOADEDENTS = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredEntityList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredEntityList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDENTS.getClazz(), ObfTable.WORLD_LOADEDENTS.getName(), ObfTable.WORLD_LOADEDENTS.getDescriptor()) - }; - - WORLD_PAYLOAD_LOADEDTILES = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredTileList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredTileList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDTILES.getClazz(), ObfTable.WORLD_LOADEDTILES.getName(), ObfTable.WORLD_LOADEDTILES.getDescriptor()) - }; - - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes){ - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); - - MethodNode updateEntitiesNode = this.getMethod(classNode, WORLD_UPDATEENTITIES); - CoreDescription.log.info("Found World.updateEntities()..."); - - this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_START_TEUPDATE); - this.applyPayloadAfter (updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE); - this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_START_ENTUPDATE); - this.applyPayloadAfter (updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE); - - MethodNode initNode = this.getMethod(classNode, WORLD_INIT); - CoreDescription.log.info(String.format("Found World.%s %s", initNode.name, initNode.desc)); - - this.applyPayloadAfter (initNode, WORLD_PATTERN_LOADEDENTS, WORLD_PAYLOAD_LOADEDENTS); - this.applyPayloadAfter (initNode, WORLD_PATTERN_LOADEDTILES, WORLD_PAYLOAD_LOADEDTILES); - - + MethodNode updateEntitiesNode = this.getMethod(classNode, WORLD_UPDATEENTITIES); + CoreDescription.log.info("Found World.updateEntities()..."); + + this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_START_TEUPDATE); + this.applyPayloadAfter(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE); + + this.applyPayloadBefore( + updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_START_ENTUPDATE); + this.applyPayloadAfter(updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE); + + MethodNode initNode = this.getMethod(classNode, WORLD_INIT); + CoreDescription.log.info(String.format("Found World.%s %s", initNode.name, initNode.desc)); + + this.applyPayloadAfter(initNode, WORLD_PATTERN_LOADEDENTS, WORLD_PAYLOAD_LOADEDENTS); + this.applyPayloadAfter(initNode, WORLD_PATTERN_LOADEDTILES, WORLD_PAYLOAD_LOADEDTILES); + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(writer); - + return writer.toByteArray(); - } - + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/kcauldron/TransformerWorldKCauldron.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/kcauldron/TransformerWorldKCauldron.java index 73ed85b..bd2eb37 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/kcauldron/TransformerWorldKCauldron.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/kcauldron/TransformerWorldKCauldron.java @@ -9,156 +9,164 @@ import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.*; -public class TransformerWorldKCauldron extends TransformerBase{ +public class TransformerWorldKCauldron extends TransformerBase { - private static String WORLD_UPDATEENTITIES; - private static String WORLD_INIT; - - //tileentity.updateEntity(); World:2215 - private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_TEUPDATE; + private static String WORLD_UPDATEENTITIES; + private static String WORLD_INIT; - //ProfilerRegistrar.profilerTileEntity.Start(tileentity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_TEUPDATE; + // tileentity.updateEntity(); World:2215 + private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_TEUPDATE; - //ProfilerRegistrar.profilerTileEntity.Stop(tileentity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE; - - //this.updateEntity(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_ENTUPDATE; + // ProfilerRegistrar.profilerTileEntity.Start(tileentity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_TEUPDATE; - //ProfilerRegistrar.profilerEntity.Start(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_ENTUPDATE; + // ProfilerRegistrar.profilerTileEntity.Stop(tileentity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE; - //ProfilerRegistrar.profilerEntity.Stop(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE; - - //World.loadedEntityList - private static AbstractInsnNode[] WORLD_PATTERN_LOADEDENTS; + // this.updateEntity(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_ENTUPDATE; - //World.loadedTileEntityList - private static AbstractInsnNode[] WORLD_PATTERN_LOADEDTILES; + // ProfilerRegistrar.profilerEntity.Start(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_ENTUPDATE; - //World.loadedEntityList - private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDENTS; + // ProfilerRegistrar.profilerEntity.Stop(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE; - //World.loadedTileEntityList - private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDTILES; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - WORLD_UPDATEENTITIES = ObfTable.WORLD_UPDATEENTITIES.getFullDescriptor(); //updateEntities.getFullDescriptor(); - WORLD_INIT = ObfTable.WORLD_INIT.getFullDescriptor(); - - WORLD_UPDATE_PATTERN_TEUPDATE = new AbstractInsnNode[] - { - new LineNumberNode(-1, new LabelNode()), - Opcode.ALOAD(-1), - Opcode.INVOKEVIRTUAL(ObfTable.TILEENTITY_UPDATEENTITY.getClazz(), ObfTable.TILEENTITY_UPDATEENTITY.getName(), ObfTable.TILEENTITY_UPDATEENTITY.getDescriptor()) - }; + // World.loadedEntityList + private static AbstractInsnNode[] WORLD_PATTERN_LOADEDENTS; - WORLD_UPDATE_PAYLOAD_START_TEUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), - Opcode.ALOAD(9), - Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") - }; + // World.loadedTileEntityList + private static AbstractInsnNode[] WORLD_PATTERN_LOADEDTILES; - WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), - Opcode.ALOAD(9), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") - }; - - WORLD_UPDATE_PATTERN_ENTUPDATE = new AbstractInsnNode[] - { - new LineNumberNode(-1, new LabelNode()), - Opcode.ALOAD(-1), - Opcode.ALOAD(-1), - Opcode.INVOKEVIRTUAL(ObfTable.WORLD_UPDATEENTITY.getClazz(), ObfTable.WORLD_UPDATEENTITY.getName(), ObfTable.WORLD_UPDATEENTITY.getDescriptor()) - }; + // World.loadedEntityList + private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDENTS; - WORLD_UPDATE_PAYLOAD_START_ENTUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), - Opcode.ALOAD(2), - Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") - }; + // World.loadedTileEntityList + private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDTILES; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + WORLD_UPDATEENTITIES = ObfTable.WORLD_UPDATEENTITIES.getFullDescriptor(); // updateEntities.getFullDescriptor(); + WORLD_INIT = ObfTable.WORLD_INIT.getFullDescriptor(); + + WORLD_UPDATE_PATTERN_TEUPDATE = new AbstractInsnNode[] { + new LineNumberNode(-1, new LabelNode()), + Opcode.ALOAD(-1), + Opcode.INVOKEVIRTUAL( + ObfTable.TILEENTITY_UPDATEENTITY.getClazz(), + ObfTable.TILEENTITY_UPDATEENTITY.getName(), + ObfTable.TILEENTITY_UPDATEENTITY.getDescriptor()) + }; + + WORLD_UPDATE_PAYLOAD_START_TEUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), + Opcode.ALOAD(9), + Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), + Opcode.ALOAD(9), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PATTERN_ENTUPDATE = new AbstractInsnNode[] { + new LineNumberNode(-1, new LabelNode()), + Opcode.ALOAD(-1), + Opcode.ALOAD(-1), + Opcode.INVOKEVIRTUAL( + ObfTable.WORLD_UPDATEENTITY.getClazz(), + ObfTable.WORLD_UPDATEENTITY.getName(), + ObfTable.WORLD_UPDATEENTITY.getDescriptor()) + }; + + WORLD_UPDATE_PAYLOAD_START_ENTUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), + Opcode.ALOAD(2), + Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), + Opcode.ALOAD(2), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") + }; + + WORLD_PATTERN_LOADEDENTS = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("java/util/ArrayList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDENTS.getClazz(), + ObfTable.WORLD_LOADEDENTS.getName(), + ObfTable.WORLD_LOADEDENTS.getDescriptor()) + }; + + WORLD_PATTERN_LOADEDTILES = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("java/util/ArrayList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDTILES.getClazz(), + ObfTable.WORLD_LOADEDTILES.getName(), + ObfTable.WORLD_LOADEDTILES.getDescriptor()) + }; + + WORLD_PAYLOAD_LOADEDENTS = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredEntityList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredEntityList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDENTS.getClazz(), + ObfTable.WORLD_LOADEDENTS.getName(), + ObfTable.WORLD_LOADEDENTS.getDescriptor()) + }; + + WORLD_PAYLOAD_LOADEDTILES = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredTileList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredTileList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDTILES.getClazz(), + ObfTable.WORLD_LOADEDTILES.getName(), + ObfTable.WORLD_LOADEDTILES.getDescriptor()) + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); - WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), - Opcode.ALOAD(2), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") - }; - - WORLD_PATTERN_LOADEDENTS = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("java/util/ArrayList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDENTS.getClazz(), ObfTable.WORLD_LOADEDENTS.getName(), ObfTable.WORLD_LOADEDENTS.getDescriptor()) - }; - - WORLD_PATTERN_LOADEDTILES = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("java/util/ArrayList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDTILES.getClazz(), ObfTable.WORLD_LOADEDTILES.getName(), ObfTable.WORLD_LOADEDTILES.getDescriptor()) - }; - - WORLD_PAYLOAD_LOADEDENTS = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredEntityList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredEntityList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDENTS.getClazz(), ObfTable.WORLD_LOADEDENTS.getName(), ObfTable.WORLD_LOADEDENTS.getDescriptor()) - }; - - WORLD_PAYLOAD_LOADEDTILES = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredTileList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredTileList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDTILES.getClazz(), ObfTable.WORLD_LOADEDTILES.getName(), ObfTable.WORLD_LOADEDTILES.getDescriptor()) - }; - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes){ - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); - - MethodNode updateEntitiesNode = this.getMethod(classNode, WORLD_UPDATEENTITIES); - CoreDescription.log.info("Found World.updateEntities()..."); - - this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_START_TEUPDATE); - this.applyPayloadAfter (updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE); - this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_START_ENTUPDATE); - this.applyPayloadAfter (updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE); - - MethodNode initNode = this.getMethod(classNode, WORLD_INIT); - CoreDescription.log.info(String.format("Found World.%s %s", initNode.name, initNode.desc)); - - this.applyPayloadAfter (initNode, WORLD_PATTERN_LOADEDENTS, WORLD_PAYLOAD_LOADEDENTS); - this.applyPayloadAfter (initNode, WORLD_PATTERN_LOADEDTILES, WORLD_PAYLOAD_LOADEDTILES); - + MethodNode updateEntitiesNode = this.getMethod(classNode, WORLD_UPDATEENTITIES); + CoreDescription.log.info("Found World.updateEntities()..."); + + this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_START_TEUPDATE); + this.applyPayloadAfter(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE); + + this.applyPayloadBefore( + updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_START_ENTUPDATE); + this.applyPayloadAfter(updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE); + + MethodNode initNode = this.getMethod(classNode, WORLD_INIT); + CoreDescription.log.info(String.format("Found World.%s %s", initNode.name, initNode.desc)); + + this.applyPayloadAfter(initNode, WORLD_PATTERN_LOADEDENTS, WORLD_PAYLOAD_LOADEDENTS); + this.applyPayloadAfter(initNode, WORLD_PATTERN_LOADEDTILES, WORLD_PAYLOAD_LOADEDTILES); + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(writer); - + return writer.toByteArray(); - } - + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/mcpc/TransformerWorldCauldron.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/mcpc/TransformerWorldCauldron.java index b134659..376da8e 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/mcpc/TransformerWorldCauldron.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/mcpc/TransformerWorldCauldron.java @@ -5,165 +5,172 @@ import mcp.mobius.mobiuscore.asm.ObfTable; import mcp.mobius.mobiuscore.asm.Opcode; import mcp.mobius.mobiuscore.asm.transformers.TransformerBase; import mcp.mobius.mobiuscore.profiler.ProfilerSection; - import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.LineNumberNode; +import org.objectweb.asm.tree.MethodNode; -public class TransformerWorldCauldron extends TransformerBase{ +public class TransformerWorldCauldron extends TransformerBase { - private static String WORLD_UPDATEENTITIES; - private static String WORLD_INIT; - - //tileentity.updateEntity(); World:2215 - private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_TEUPDATE; + private static String WORLD_UPDATEENTITIES; + private static String WORLD_INIT; - //ProfilerRegistrar.profilerTileEntity.Start(tileentity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_TEUPDATE; + // tileentity.updateEntity(); World:2215 + private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_TEUPDATE; - //ProfilerRegistrar.profilerTileEntity.Stop(tileentity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE; - - //this.updateEntity(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_ENTUPDATE; + // ProfilerRegistrar.profilerTileEntity.Start(tileentity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_TEUPDATE; - //ProfilerRegistrar.profilerEntity.Start(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_ENTUPDATE; + // ProfilerRegistrar.profilerTileEntity.Stop(tileentity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE; - //ProfilerRegistrar.profilerEntity.Stop(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE; - - //World.loadedEntityList - private static AbstractInsnNode[] WORLD_PATTERN_LOADEDENTS; + // this.updateEntity(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_ENTUPDATE; - //World.loadedTileEntityList - private static AbstractInsnNode[] WORLD_PATTERN_LOADEDTILES; + // ProfilerRegistrar.profilerEntity.Start(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_ENTUPDATE; - //World.loadedEntityList - private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDENTS; + // ProfilerRegistrar.profilerEntity.Stop(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE; - //World.loadedTileEntityList - private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDTILES; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - WORLD_UPDATEENTITIES = ObfTable.WORLD_UPDATEENTITIES.getFullDescriptor(); //updateEntities.getFullDescriptor(); - WORLD_INIT = ObfTable.WORLD_INIT.getFullDescriptor(); - - WORLD_UPDATE_PATTERN_TEUPDATE = new AbstractInsnNode[] - { - new LineNumberNode(-1, new LabelNode()), - Opcode.ALOAD(-1), - Opcode.INVOKEVIRTUAL(ObfTable.TILEENTITY_UPDATEENTITY.getClazz(), ObfTable.TILEENTITY_UPDATEENTITY.getName(), ObfTable.TILEENTITY_UPDATEENTITY.getDescriptor()) - }; + // World.loadedEntityList + private static AbstractInsnNode[] WORLD_PATTERN_LOADEDENTS; - WORLD_UPDATE_PAYLOAD_START_TEUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), - Opcode.ALOAD(8), - Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") - }; + // World.loadedTileEntityList + private static AbstractInsnNode[] WORLD_PATTERN_LOADEDTILES; - WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), - Opcode.ALOAD(8), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") - }; - - WORLD_UPDATE_PATTERN_ENTUPDATE = new AbstractInsnNode[] - { - new LineNumberNode(-1, new LabelNode()), - Opcode.ALOAD(-1), - Opcode.ALOAD(-1), - Opcode.INVOKEVIRTUAL(ObfTable.WORLD_UPDATEENTITY.getClazz(), ObfTable.WORLD_UPDATEENTITY.getName(), ObfTable.WORLD_UPDATEENTITY.getDescriptor()) - }; + // World.loadedEntityList + private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDENTS; - WORLD_UPDATE_PAYLOAD_START_ENTUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), - Opcode.ALOAD(2), - Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") - }; + // World.loadedTileEntityList + private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDTILES; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + WORLD_UPDATEENTITIES = ObfTable.WORLD_UPDATEENTITIES.getFullDescriptor(); // updateEntities.getFullDescriptor(); + WORLD_INIT = ObfTable.WORLD_INIT.getFullDescriptor(); + + WORLD_UPDATE_PATTERN_TEUPDATE = new AbstractInsnNode[] { + new LineNumberNode(-1, new LabelNode()), + Opcode.ALOAD(-1), + Opcode.INVOKEVIRTUAL( + ObfTable.TILEENTITY_UPDATEENTITY.getClazz(), + ObfTable.TILEENTITY_UPDATEENTITY.getName(), + ObfTable.TILEENTITY_UPDATEENTITY.getDescriptor()) + }; + + WORLD_UPDATE_PAYLOAD_START_TEUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), + Opcode.ALOAD(8), + Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), + Opcode.ALOAD(8), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PATTERN_ENTUPDATE = new AbstractInsnNode[] { + new LineNumberNode(-1, new LabelNode()), + Opcode.ALOAD(-1), + Opcode.ALOAD(-1), + Opcode.INVOKEVIRTUAL( + ObfTable.WORLD_UPDATEENTITY.getClazz(), + ObfTable.WORLD_UPDATEENTITY.getName(), + ObfTable.WORLD_UPDATEENTITY.getDescriptor()) + }; + + WORLD_UPDATE_PAYLOAD_START_ENTUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), + Opcode.ALOAD(2), + Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), + Opcode.ALOAD(2), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") + }; + + WORLD_PATTERN_LOADEDENTS = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("java/util/ArrayList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDENTS.getClazz(), + ObfTable.WORLD_LOADEDENTS.getName(), + ObfTable.WORLD_LOADEDENTS.getDescriptor()) + }; + + WORLD_PATTERN_LOADEDTILES = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("java/util/ArrayList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDTILES.getClazz(), + ObfTable.WORLD_LOADEDTILES.getName(), + ObfTable.WORLD_LOADEDTILES.getDescriptor()) + }; + + WORLD_PAYLOAD_LOADEDENTS = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredEntityList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredEntityList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDENTS.getClazz(), + ObfTable.WORLD_LOADEDENTS.getName(), + ObfTable.WORLD_LOADEDENTS.getDescriptor()) + }; + + WORLD_PAYLOAD_LOADEDTILES = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredTileList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredTileList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDTILES.getClazz(), + ObfTable.WORLD_LOADEDTILES.getName(), + ObfTable.WORLD_LOADEDTILES.getDescriptor()) + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); - WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), - Opcode.ALOAD(2), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") - }; - - WORLD_PATTERN_LOADEDENTS = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("java/util/ArrayList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDENTS.getClazz(), ObfTable.WORLD_LOADEDENTS.getName(), ObfTable.WORLD_LOADEDENTS.getDescriptor()) - }; - - WORLD_PATTERN_LOADEDTILES = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("java/util/ArrayList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("java/util/ArrayList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDTILES.getClazz(), ObfTable.WORLD_LOADEDTILES.getName(), ObfTable.WORLD_LOADEDTILES.getDescriptor()) - }; - - WORLD_PAYLOAD_LOADEDENTS = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredEntityList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredEntityList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDENTS.getClazz(), ObfTable.WORLD_LOADEDENTS.getName(), ObfTable.WORLD_LOADEDENTS.getDescriptor()) - }; - - WORLD_PAYLOAD_LOADEDTILES = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredTileList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredTileList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDTILES.getClazz(), ObfTable.WORLD_LOADEDTILES.getName(), ObfTable.WORLD_LOADEDTILES.getDescriptor()) - }; - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes){ - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); - - MethodNode updateEntitiesNode = this.getMethod(classNode, WORLD_UPDATEENTITIES); - CoreDescription.log.info("Found World.updateEntities()..."); - - this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_START_TEUPDATE); - this.applyPayloadAfter (updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE); - this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_START_ENTUPDATE); - this.applyPayloadAfter (updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE); - - MethodNode initNode = this.getMethod(classNode, WORLD_INIT); - CoreDescription.log.info(String.format("Found World.%s %s", initNode.name, initNode.desc)); - - this.applyPayloadAfter (initNode, WORLD_PATTERN_LOADEDENTS, WORLD_PAYLOAD_LOADEDENTS); - this.applyPayloadAfter (initNode, WORLD_PATTERN_LOADEDTILES, WORLD_PAYLOAD_LOADEDTILES); - + MethodNode updateEntitiesNode = this.getMethod(classNode, WORLD_UPDATEENTITIES); + CoreDescription.log.info("Found World.updateEntities()..."); + + this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_START_TEUPDATE); + this.applyPayloadAfter(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE); + + this.applyPayloadBefore( + updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_START_ENTUPDATE); + this.applyPayloadAfter(updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE); + + MethodNode initNode = this.getMethod(classNode, WORLD_INIT); + CoreDescription.log.info(String.format("Found World.%s %s", initNode.name, initNode.desc)); + + this.applyPayloadAfter(initNode, WORLD_PATTERN_LOADEDENTS, WORLD_PAYLOAD_LOADEDENTS); + this.applyPayloadAfter(initNode, WORLD_PATTERN_LOADEDTILES, WORLD_PAYLOAD_LOADEDTILES); + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(writer); - + return writer.toByteArray(); - } - + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/thermos/TransformerWorldThermos.java b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/thermos/TransformerWorldThermos.java index 04cf8ce..52832f7 100644 --- a/src/main/java/mcp/mobius/mobiuscore/asm/transformers/thermos/TransformerWorldThermos.java +++ b/src/main/java/mcp/mobius/mobiuscore/asm/transformers/thermos/TransformerWorldThermos.java @@ -9,156 +9,164 @@ import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.*; -public class TransformerWorldThermos extends TransformerBase{ +public class TransformerWorldThermos extends TransformerBase { - private static String WORLD_UPDATEENTITIES; - private static String WORLD_INIT; - - //tileentity.updateEntity(); World:2215 - private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_TEUPDATE; + private static String WORLD_UPDATEENTITIES; + private static String WORLD_INIT; - //ProfilerRegistrar.profilerTileEntity.Start(tileentity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_TEUPDATE; + // tileentity.updateEntity(); World:2215 + private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_TEUPDATE; - //ProfilerRegistrar.profilerTileEntity.Stop(tileentity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE; - - //this.updateEntity(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_ENTUPDATE; + // ProfilerRegistrar.profilerTileEntity.Start(tileentity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_TEUPDATE; - //ProfilerRegistrar.profilerEntity.Start(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_ENTUPDATE; + // ProfilerRegistrar.profilerTileEntity.Stop(tileentity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE; - //ProfilerRegistrar.profilerEntity.Stop(entity); - private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE; - - //World.loadedEntityList - private static AbstractInsnNode[] WORLD_PATTERN_LOADEDENTS; + // this.updateEntity(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PATTERN_ENTUPDATE; - //World.loadedTileEntityList - private static AbstractInsnNode[] WORLD_PATTERN_LOADEDTILES; + // ProfilerRegistrar.profilerEntity.Start(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_START_ENTUPDATE; - //World.loadedEntityList - private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDENTS; + // ProfilerRegistrar.profilerEntity.Stop(entity); + private static AbstractInsnNode[] WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE; - //World.loadedTileEntityList - private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDTILES; - - static{ - String profilerClass = ProfilerSection.getClassName(); - String profilerType = ProfilerSection.getTypeName(); - - WORLD_UPDATEENTITIES = ObfTable.WORLD_UPDATEENTITIES.getFullDescriptor(); //updateEntities.getFullDescriptor(); - WORLD_INIT = ObfTable.WORLD_INIT.getFullDescriptor(); - - WORLD_UPDATE_PATTERN_TEUPDATE = new AbstractInsnNode[] - { - new LineNumberNode(-1, new LabelNode()), - Opcode.ALOAD(-1), - Opcode.INVOKEVIRTUAL(ObfTable.TILEENTITY_UPDATEENTITY.getClazz(), ObfTable.TILEENTITY_UPDATEENTITY.getName(), ObfTable.TILEENTITY_UPDATEENTITY.getDescriptor()) - }; + // World.loadedEntityList + private static AbstractInsnNode[] WORLD_PATTERN_LOADEDENTS; - WORLD_UPDATE_PAYLOAD_START_TEUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), - Opcode.ALOAD(9), - Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") - }; + // World.loadedTileEntityList + private static AbstractInsnNode[] WORLD_PATTERN_LOADEDTILES; - WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), - Opcode.ALOAD(9), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") - }; - - WORLD_UPDATE_PATTERN_ENTUPDATE = new AbstractInsnNode[] - { - new LineNumberNode(-1, new LabelNode()), - Opcode.ALOAD(-1), - Opcode.ALOAD(-1), - Opcode.INVOKEVIRTUAL(ObfTable.WORLD_UPDATEENTITY.getClazz(), ObfTable.WORLD_UPDATEENTITY.getName(), ObfTable.WORLD_UPDATEENTITY.getDescriptor()) - }; + // World.loadedEntityList + private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDENTS; - WORLD_UPDATE_PAYLOAD_START_ENTUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), - Opcode.ALOAD(2), - Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") - }; + // World.loadedTileEntityList + private static AbstractInsnNode[] WORLD_PAYLOAD_LOADEDTILES; + + static { + String profilerClass = ProfilerSection.getClassName(); + String profilerType = ProfilerSection.getTypeName(); + + WORLD_UPDATEENTITIES = ObfTable.WORLD_UPDATEENTITIES.getFullDescriptor(); // updateEntities.getFullDescriptor(); + WORLD_INIT = ObfTable.WORLD_INIT.getFullDescriptor(); + + WORLD_UPDATE_PATTERN_TEUPDATE = new AbstractInsnNode[] { + new LineNumberNode(-1, new LabelNode()), + Opcode.ALOAD(-1), + Opcode.INVOKEVIRTUAL( + ObfTable.TILEENTITY_UPDATEENTITY.getClazz(), + ObfTable.TILEENTITY_UPDATEENTITY.getName(), + ObfTable.TILEENTITY_UPDATEENTITY.getDescriptor()) + }; + + WORLD_UPDATE_PAYLOAD_START_TEUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), + Opcode.ALOAD(9), + Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.TILEENT_UPDATETIME.name(), profilerType), + Opcode.ALOAD(9), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PATTERN_ENTUPDATE = new AbstractInsnNode[] { + new LineNumberNode(-1, new LabelNode()), + Opcode.ALOAD(-1), + Opcode.ALOAD(-1), + Opcode.INVOKEVIRTUAL( + ObfTable.WORLD_UPDATEENTITY.getClazz(), + ObfTable.WORLD_UPDATEENTITY.getName(), + ObfTable.WORLD_UPDATEENTITY.getDescriptor()) + }; + + WORLD_UPDATE_PAYLOAD_START_ENTUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), + Opcode.ALOAD(2), + Opcode.INVOKEVIRTUAL(profilerClass, "start", "(Ljava/lang/Object;)V") + }; + + WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE = new AbstractInsnNode[] { + Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), + Opcode.ALOAD(2), + Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") + }; + + WORLD_PATTERN_LOADEDENTS = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("thermos/chaud/HashedArrayList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("thermos/chaud/HashedArrayList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDENTS.getClazz(), + ObfTable.WORLD_LOADEDENTS.getName(), + ObfTable.WORLD_LOADEDENTS.getDescriptor()) + }; + + WORLD_PATTERN_LOADEDTILES = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("thermos/chaud/HashedArrayList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("thermos/chaud/HashedArrayList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDTILES.getClazz(), + ObfTable.WORLD_LOADEDTILES.getName(), + ObfTable.WORLD_LOADEDTILES.getDescriptor()) + }; + + WORLD_PAYLOAD_LOADEDENTS = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredEntityList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredEntityList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDENTS.getClazz(), + ObfTable.WORLD_LOADEDENTS.getName(), + ObfTable.WORLD_LOADEDENTS.getDescriptor()) + }; + + WORLD_PAYLOAD_LOADEDTILES = new AbstractInsnNode[] { + Opcode.ALOAD(0), + Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredTileList"), + Opcode.DUP(), + Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredTileList", "", "()V"), + Opcode.PUTFIELD( + ObfTable.WORLD_LOADEDTILES.getClazz(), + ObfTable.WORLD_LOADEDTILES.getName(), + ObfTable.WORLD_LOADEDTILES.getDescriptor()) + }; + } + + @Override + public byte[] transform(String name, String srgname, byte[] bytes) { + dumpChecksum(bytes, name, srgname); + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); - WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE = new AbstractInsnNode[] - { - Opcode.GETSTATIC(profilerClass, ProfilerSection.ENTITY_UPDATETIME.name(), profilerType), - Opcode.ALOAD(2), - Opcode.INVOKEVIRTUAL(profilerClass, "stop", "(Ljava/lang/Object;)V") - }; - - WORLD_PATTERN_LOADEDENTS = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("thermos/chaud/HashedArrayList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("thermos/chaud/HashedArrayList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDENTS.getClazz(), ObfTable.WORLD_LOADEDENTS.getName(), ObfTable.WORLD_LOADEDENTS.getDescriptor()) - }; - - WORLD_PATTERN_LOADEDTILES = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("thermos/chaud/HashedArrayList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("thermos/chaud/HashedArrayList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDTILES.getClazz(), ObfTable.WORLD_LOADEDTILES.getName(), ObfTable.WORLD_LOADEDTILES.getDescriptor()) - }; - - WORLD_PAYLOAD_LOADEDENTS = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredEntityList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredEntityList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDENTS.getClazz(), ObfTable.WORLD_LOADEDENTS.getName(), ObfTable.WORLD_LOADEDENTS.getDescriptor()) - }; - - WORLD_PAYLOAD_LOADEDTILES = new AbstractInsnNode[] - { - Opcode.ALOAD(0), - Opcode.NEW("mcp/mobius/mobiuscore/monitors/MonitoredTileList"), - Opcode.DUP(), - Opcode.INVOKESPECIAL("mcp/mobius/mobiuscore/monitors/MonitoredTileList", "", "()V"), - Opcode.PUTFIELD(ObfTable.WORLD_LOADEDTILES.getClazz(), ObfTable.WORLD_LOADEDTILES.getName(), ObfTable.WORLD_LOADEDTILES.getDescriptor()) - }; - } - - @Override - public byte[] transform(String name, String srgname, byte[] bytes){ - dumpChecksum(bytes, name, srgname); - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); - - MethodNode updateEntitiesNode = this.getMethod(classNode, WORLD_UPDATEENTITIES); - CoreDescription.log.info("Found World.updateEntities()..."); - - this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_START_TEUPDATE); - this.applyPayloadAfter (updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE); - this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_START_ENTUPDATE); - this.applyPayloadAfter (updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE); - - MethodNode initNode = this.getMethod(classNode, WORLD_INIT); - CoreDescription.log.info(String.format("Found World.%s %s", initNode.name, initNode.desc)); - - this.applyPayloadAfter (initNode, WORLD_PATTERN_LOADEDENTS, WORLD_PAYLOAD_LOADEDENTS); - this.applyPayloadAfter (initNode, WORLD_PATTERN_LOADEDTILES, WORLD_PAYLOAD_LOADEDTILES); - + MethodNode updateEntitiesNode = this.getMethod(classNode, WORLD_UPDATEENTITIES); + CoreDescription.log.info("Found World.updateEntities()..."); + + this.applyPayloadBefore(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_START_TEUPDATE); + this.applyPayloadAfter(updateEntitiesNode, WORLD_UPDATE_PATTERN_TEUPDATE, WORLD_UPDATE_PAYLOAD_STOP_TEUPDATE); + + this.applyPayloadBefore( + updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_START_ENTUPDATE); + this.applyPayloadAfter(updateEntitiesNode, WORLD_UPDATE_PATTERN_ENTUPDATE, WORLD_UPDATE_PAYLOAD_STOP_ENTUPDATE); + + MethodNode initNode = this.getMethod(classNode, WORLD_INIT); + CoreDescription.log.info(String.format("Found World.%s %s", initNode.name, initNode.desc)); + + this.applyPayloadAfter(initNode, WORLD_PATTERN_LOADEDENTS, WORLD_PAYLOAD_LOADEDENTS); + this.applyPayloadAfter(initNode, WORLD_PATTERN_LOADEDTILES, WORLD_PAYLOAD_LOADEDTILES); + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(writer); - + return writer.toByteArray(); - } - -} \ No newline at end of file + } +} diff --git a/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredEntityList.java b/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredEntityList.java index 2d4d0f1..d1ae5c4 100644 --- a/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredEntityList.java +++ b/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredEntityList.java @@ -2,67 +2,63 @@ package mcp.mobius.mobiuscore.monitors; import java.util.HashMap; import java.util.Map; - import mcp.mobius.mobiuscore.asm.CoreDescription; import net.minecraft.entity.Entity; -public class MonitoredEntityList extends MonitoredList{ - - private Map count = new HashMap(); - - @Override - protected void addCount(E e){ - if (e == null) return; - String name = this.getName(e); - try{ - count.put(name, count.get(name) + 1); - } catch (NullPointerException ex){ - count.put(name, 1); - } catch (Exception ex){ - ex.printStackTrace(); - count.put(name, 1); - } - } - - @Override - protected void removeCount(int index){ - this.removeCount(this.get(index)); - } - - @Override - protected void removeCount(Object o){ - if (!(o instanceof Entity)) return; - String name = this.getName(o); - - try{ - this.count.put(name, this.count.get(name) - 1); - } catch (NullPointerException e){ - this.count.put(name, 0); - } - } +public class MonitoredEntityList extends MonitoredList { - @Override - protected void clearCount(){ - this.count.clear(); - } + private Map count = new HashMap(); - protected String getName(Object o){ - try { - return ((Entity) o).getCommandSenderName(); - } - catch (ClassCastException|NullPointerException suppressed) { - return ""; - } - } + @Override + protected void addCount(E e) { + if (e == null) return; + String name = this.getName(e); + try { + count.put(name, count.get(name) + 1); + } catch (NullPointerException ex) { + count.put(name, 1); + } catch (Exception ex) { + ex.printStackTrace(); + count.put(name, 1); + } + } - @Override - public void printCount(){ - for (String s : this.count.keySet()) - CoreDescription.log.info(String.format("%s : %s", s, this.count.get(s))); - } - - public Map getCount(){ - return this.count; - } - + @Override + protected void removeCount(int index) { + this.removeCount(this.get(index)); + } + + @Override + protected void removeCount(Object o) { + if (!(o instanceof Entity)) return; + String name = this.getName(o); + + try { + this.count.put(name, this.count.get(name) - 1); + } catch (NullPointerException e) { + this.count.put(name, 0); + } + } + + @Override + protected void clearCount() { + this.count.clear(); + } + + protected String getName(Object o) { + try { + return ((Entity) o).getCommandSenderName(); + } catch (ClassCastException | NullPointerException suppressed) { + return ""; + } + } + + @Override + public void printCount() { + for (String s : this.count.keySet()) CoreDescription.log.info(String.format("%s : %s", s, this.count.get(s))); + } + + public Map getCount() { + return this.count; + } } diff --git a/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredList.java b/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredList.java index 774a65c..5a4cfd8 100644 --- a/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredList.java +++ b/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredList.java @@ -3,66 +3,66 @@ package mcp.mobius.mobiuscore.monitors; import java.util.ArrayList; import java.util.Collection; -public abstract class MonitoredList extends ArrayList{ - - abstract void addCount(E e); - abstract void removeCount(int index); - abstract void removeCount(Object o); - abstract void printCount(); - abstract void clearCount(); - - @Override - public boolean add(E e){ - this.addCount(e); - return super.add(e); - } - - @Override - public void add(int index, E e){ - this.addCount(e); - super.add(index, e); - } - - @Override - public boolean addAll(Collection c){ - for (E e : c) - this.addCount(e); - - return super.addAll(c); - } - - @Override - public boolean addAll(int index, Collection c){ - for (E e : c) - this.addCount(e); - - return super.addAll(index, c); - } - - @Override - public void clear(){ - this.clearCount(); - super.clear(); - } - - @Override - public E remove(int index){ - this.removeCount(index); - return super.remove(index); - } - - @Override - public boolean remove(Object o){ - this.removeCount(o); - return super.remove(o); - } - - @Override - public boolean removeAll(Collection c){ - for (Object o : c) - this.removeCount(o); - - return super.removeAll(c); - } -} +public abstract class MonitoredList extends ArrayList { + abstract void addCount(E e); + + abstract void removeCount(int index); + + abstract void removeCount(Object o); + + abstract void printCount(); + + abstract void clearCount(); + + @Override + public boolean add(E e) { + this.addCount(e); + return super.add(e); + } + + @Override + public void add(int index, E e) { + this.addCount(e); + super.add(index, e); + } + + @Override + public boolean addAll(Collection c) { + for (E e : c) this.addCount(e); + + return super.addAll(c); + } + + @Override + public boolean addAll(int index, Collection c) { + for (E e : c) this.addCount(e); + + return super.addAll(index, c); + } + + @Override + public void clear() { + this.clearCount(); + super.clear(); + } + + @Override + public E remove(int index) { + this.removeCount(index); + return super.remove(index); + } + + @Override + public boolean remove(Object o) { + this.removeCount(o); + return super.remove(o); + } + + @Override + public boolean removeAll(Collection c) { + for (Object o : c) this.removeCount(o); + + return super.removeAll(c); + } +} diff --git a/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredTileList.java b/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredTileList.java index 10447d1..f6b2fdc 100644 --- a/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredTileList.java +++ b/src/main/java/mcp/mobius/mobiuscore/monitors/MonitoredTileList.java @@ -1,96 +1,91 @@ package mcp.mobius.mobiuscore.monitors; -import java.util.HashMap; -import java.util.Map; -import java.util.WeakHashMap; - import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import com.google.common.collect.Table.Cell; - +import java.util.Map; +import java.util.WeakHashMap; import mcp.mobius.mobiuscore.asm.CoreDescription; import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -public class MonitoredTileList extends MonitoredList{ - - //private Map count = new HashMap(); - private Table count = HashBasedTable.create(); - private Map blockdata = new WeakHashMap(); - - private class BlockData{ - public final Block block; - public final int meta; - - public BlockData(Block b, int m){ - this.block = b; - this.meta = m; - } - } - - @Override - protected void addCount(E e){ - TileEntity te = ((TileEntity)e); - if (te == null || te.getWorldObj() == null) return; - - Block block = te.getWorldObj().getBlock(te.xCoord, te.yCoord, te.zCoord); - int meta = te.getWorldObj().getBlockMetadata(te.xCoord, te.yCoord, te.zCoord); - - blockdata.put(te, new BlockData(block, meta)); - - try{ - count.put(block, meta, count.get(block, meta) + 1); - } catch (NullPointerException ex){ - count.put(block, meta, 1); - } catch (Exception ex){ - ex.printStackTrace(); - count.put(block, meta, 1); - } - } - - @Override - protected void removeCount(int index){ - this.removeCount(this.get(index)); - } - - @Override - protected void removeCount(Object o){ - //TODO THIS IS WHERE THE CHUNK KEEP GETTING LOADED. - //TODO SHOULD STORE BLOCK/META IN A TABLE ALONG WITH THE TE IN ORDER TO DECREASE THOSE - //WITHOUT ACCESSING THE WORLD !!!! - - /* - TileEntity te = ((TileEntity)o); - if (te == null || te.getWorldObj() == null) return; - - Block block = te.getWorldObj().getBlock(te.xCoord, te.yCoord, te.zCoord); - int meta = te.getWorldObj().getBlockMetadata(te.xCoord, te.yCoord, te.zCoord); - */ - - if (blockdata.containsKey(o)){ - BlockData d = blockdata.get(o); - try{ - this.count.put(d.block, d.meta, this.count.get(d.block, d.meta) - 1); - } catch (NullPointerException e){ - this.count.put(d.block, d.meta, 0); - } - } - } +public class MonitoredTileList extends MonitoredList { - @Override - protected void clearCount(){ - this.count.clear(); - } - - @Override - public void printCount(){ - for (Cell c : this.count.cellSet()) - CoreDescription.log.info(String.format("%s | %s : %s", c.getRowKey(), c.getColumnKey(), c.getValue())); - - } - - public Table getCount(){ - return this.count; - } -} \ No newline at end of file + // private Map count = new HashMap(); + private Table count = HashBasedTable.create(); + private Map blockdata = new WeakHashMap(); + + private class BlockData { + public final Block block; + public final int meta; + + public BlockData(Block b, int m) { + this.block = b; + this.meta = m; + } + } + + @Override + protected void addCount(E e) { + TileEntity te = ((TileEntity) e); + if (te == null || te.getWorldObj() == null) return; + + Block block = te.getWorldObj().getBlock(te.xCoord, te.yCoord, te.zCoord); + int meta = te.getWorldObj().getBlockMetadata(te.xCoord, te.yCoord, te.zCoord); + + blockdata.put(te, new BlockData(block, meta)); + + try { + count.put(block, meta, count.get(block, meta) + 1); + } catch (NullPointerException ex) { + count.put(block, meta, 1); + } catch (Exception ex) { + ex.printStackTrace(); + count.put(block, meta, 1); + } + } + + @Override + protected void removeCount(int index) { + this.removeCount(this.get(index)); + } + + @Override + protected void removeCount(Object o) { + // TODO THIS IS WHERE THE CHUNK KEEP GETTING LOADED. + // TODO SHOULD STORE BLOCK/META IN A TABLE ALONG WITH THE TE IN ORDER TO DECREASE THOSE + // WITHOUT ACCESSING THE WORLD !!!! + + /* + TileEntity te = ((TileEntity)o); + if (te == null || te.getWorldObj() == null) return; + + Block block = te.getWorldObj().getBlock(te.xCoord, te.yCoord, te.zCoord); + int meta = te.getWorldObj().getBlockMetadata(te.xCoord, te.yCoord, te.zCoord); + */ + + if (blockdata.containsKey(o)) { + BlockData d = blockdata.get(o); + try { + this.count.put(d.block, d.meta, this.count.get(d.block, d.meta) - 1); + } catch (NullPointerException e) { + this.count.put(d.block, d.meta, 0); + } + } + } + + @Override + protected void clearCount() { + this.count.clear(); + } + + @Override + public void printCount() { + for (Cell c : this.count.cellSet()) + CoreDescription.log.info(String.format("%s | %s : %s", c.getRowKey(), c.getColumnKey(), c.getValue())); + } + + public Table getCount() { + return this.count; + } +} diff --git a/src/main/java/mcp/mobius/mobiuscore/profiler/DummyProfiler.java b/src/main/java/mcp/mobius/mobiuscore/profiler/DummyProfiler.java index 3c737b0..c50c2c7 100644 --- a/src/main/java/mcp/mobius/mobiuscore/profiler/DummyProfiler.java +++ b/src/main/java/mcp/mobius/mobiuscore/profiler/DummyProfiler.java @@ -1,38 +1,36 @@ package mcp.mobius.mobiuscore.profiler; -import net.minecraft.world.World; +public class DummyProfiler implements IProfilerBase { + @Override + public void reset() {} -public class DummyProfiler implements IProfilerBase{ - @Override - public void reset() {} - - @Override - public void start() {} + @Override + public void start() {} - @Override - public void stop() {} + @Override + public void stop() {} - @Override - public void start(Object key) {} + @Override + public void start(Object key) {} - @Override - public void stop(Object key) {} + @Override + public void stop(Object key) {} - @Override - public void start(Object key1, Object key2) {} + @Override + public void start(Object key1, Object key2) {} - @Override - public void stop(Object key1, Object key2) {} + @Override + public void stop(Object key1, Object key2) {} - @Override - public void start(Object key1, Object key2, Object key3) {} + @Override + public void start(Object key1, Object key2, Object key3) {} - @Override - public void stop(Object key1, Object key2, Object key3) {} - - @Override - public void start(Object key1, Object key2, Object key3, Object key4) {} + @Override + public void stop(Object key1, Object key2, Object key3) {} - @Override - public void stop(Object key1, Object key2, Object key3, Object key4) {} + @Override + public void start(Object key1, Object key2, Object key3, Object key4) {} + + @Override + public void stop(Object key1, Object key2, Object key3, Object key4) {} } diff --git a/src/main/java/mcp/mobius/mobiuscore/profiler/IProfilerBase.java b/src/main/java/mcp/mobius/mobiuscore/profiler/IProfilerBase.java index c263eb3..8404f34 100644 --- a/src/main/java/mcp/mobius/mobiuscore/profiler/IProfilerBase.java +++ b/src/main/java/mcp/mobius/mobiuscore/profiler/IProfilerBase.java @@ -1,24 +1,26 @@ package mcp.mobius.mobiuscore.profiler; -import net.minecraft.world.World; - public interface IProfilerBase { - public void reset(); - - public void start(); - public void stop(); + public void reset(); - public void start(Object key); - public void stop(Object key); + public void start(); - public void start(Object key1, Object key2); - public void stop(Object key1, Object key2); + public void stop(); - public void start(Object key1, Object key2, Object key3); - public void stop(Object key1, Object key2, Object key3); - - public void start(Object key1, Object key2, Object key3, Object key4); - public void stop(Object key1, Object key2, Object key3, Object key4); - + public void start(Object key); + + public void stop(Object key); + + public void start(Object key1, Object key2); + + public void stop(Object key1, Object key2); + + public void start(Object key1, Object key2, Object key3); + + public void stop(Object key1, Object key2, Object key3); + + public void start(Object key1, Object key2, Object key3, Object key4); + + public void stop(Object key1, Object key2, Object key3, Object key4); } diff --git a/src/main/java/mcp/mobius/mobiuscore/profiler/ProfilerSection.java b/src/main/java/mcp/mobius/mobiuscore/profiler/ProfilerSection.java index 20214a6..6d00ec7 100644 --- a/src/main/java/mcp/mobius/mobiuscore/profiler/ProfilerSection.java +++ b/src/main/java/mcp/mobius/mobiuscore/profiler/ProfilerSection.java @@ -1,129 +1,158 @@ package mcp.mobius.mobiuscore.profiler; +import cpw.mods.fml.relauncher.Side; import java.util.EnumSet; -import cpw.mods.fml.relauncher.Side; -import net.minecraft.world.World; +public enum ProfilerSection implements IProfilerBase { + DIMENSION_TICK(RunType.REALTIME, Side.SERVER), // Global section around the ticks for each dim (Blocks & ents). + DIMENSION_BLOCKTICK(RunType.ONREQUEST, Side.SERVER), // Subsection for dimension block tick. + ENTITY_UPDATETIME(RunType.ONREQUEST, Side.SERVER), // Profiling of the entity tick time, per entity. + TICK(RunType.REALTIME, Side.SERVER), // Tick timing profiling + TILEENT_UPDATETIME(RunType.ONREQUEST, Side.SERVER), // Profiling of the TileEntity tick time, per TE. + // HANDLER_TICKSTART (RunType.ONREQUEST, EnumSet.of(Side.CLIENT, Side.SERVER)), //Server handler for ServerTick + // start. + // HANDLER_TICKSTOP (RunType.ONREQUEST, EnumSet.of(Side.CLIENT, Side.SERVER)), //Server handler for ServerTick + // stop. + PACKET_INBOUND(RunType.REALTIME, Side.SERVER), // Outbound packet analysis + PACKET_OUTBOUND(RunType.REALTIME, Side.SERVER), // Inbound packet analysis + // PACKETFML_INBOUND (RunType.REALTIME, Side.SERVER), //Outbound packet analysis + // PACKETFML_OUTBOUND (RunType.REALTIME, Side.SERVER), //Inbound packet analysis -public enum ProfilerSection implements IProfilerBase{ - DIMENSION_TICK (RunType.REALTIME, Side.SERVER), //Global section around the ticks for each dim (Blocks & ents). - DIMENSION_BLOCKTICK(RunType.ONREQUEST, Side.SERVER), //Subsection for dimension block tick. - ENTITY_UPDATETIME (RunType.ONREQUEST, Side.SERVER), //Profiling of the entity tick time, per entity. - TICK (RunType.REALTIME, Side.SERVER), //Tick timing profiling - TILEENT_UPDATETIME (RunType.ONREQUEST, Side.SERVER), //Profiling of the TileEntity tick time, per TE. - //HANDLER_TICKSTART (RunType.ONREQUEST, EnumSet.of(Side.CLIENT, Side.SERVER)), //Server handler for ServerTick start. - //HANDLER_TICKSTOP (RunType.ONREQUEST, EnumSet.of(Side.CLIENT, Side.SERVER)), //Server handler for ServerTick stop. - PACKET_INBOUND (RunType.REALTIME, Side.SERVER), //Outbound packet analysis - PACKET_OUTBOUND (RunType.REALTIME, Side.SERVER), //Inbound packet analysis - //PACKETFML_INBOUND (RunType.REALTIME, Side.SERVER), //Outbound packet analysis - //PACKETFML_OUTBOUND (RunType.REALTIME, Side.SERVER), //Inbound packet analysis - - - NETWORK_TICK (RunType.ONREQUEST, Side.SERVER), //The time it takes for the server to handle the packets during a tick. - EVENT_INVOKE (RunType.ONREQUEST, EnumSet.of(Side.CLIENT, Side.SERVER)), //Timing of the event invokation - - RENDER_TILEENTITY (RunType.ONREQUEST, Side.CLIENT), //Profiler for TileEnt rendering - RENDER_ENTITY (RunType.ONREQUEST, Side.CLIENT), //Profiler for Entity rendering - RENDER_BLOCK (RunType.ONREQUEST, Side.CLIENT); //Profiler for Block rendering - - public enum RunType{ - REALTIME, - ONREQUEST; - } - - private EnumSet sides; - private RunType runType; - private IProfilerBase profiler = new DummyProfiler();; - private IProfilerBase profilerSuspended = new DummyProfiler();; - - public static long timeStampLastRun; - - private ProfilerSection(RunType runType, Side side){ - this.runType = runType; - this.profiler = new DummyProfiler(); - this.sides = EnumSet.of(side); - } - - private ProfilerSection(RunType runType, EnumSet sides){ - this.runType = runType; - this.profiler = new DummyProfiler(); - this.sides = sides; - } - - public RunType getRunType(){ - return this.runType; - } - - public EnumSet getSide(){ - return this.sides; - } - - public IProfilerBase getProfiler(){ - return this.profilerSuspended; - } - - public void setProfiler(IProfilerBase profiler){ - this.profilerSuspended = profiler; - if (this.runType == RunType.REALTIME) - this.profiler = profiler; - } + NETWORK_TICK( + RunType.ONREQUEST, Side.SERVER), // The time it takes for the server to handle the packets during a tick. + EVENT_INVOKE(RunType.ONREQUEST, EnumSet.of(Side.CLIENT, Side.SERVER)), // Timing of the event invokation - public void activate(){ - this.profiler = profilerSuspended; - this.timeStampLastRun = System.currentTimeMillis(); - } - - public void desactivate(){ - if (this.runType == RunType.ONREQUEST) - this.profiler = new DummyProfiler(); - } - - public static void activateAll(Side trgside){ - for (ProfilerSection section : ProfilerSection.values()) - if (section.sides.contains(trgside)) - section.activate(); - } + RENDER_TILEENTITY(RunType.ONREQUEST, Side.CLIENT), // Profiler for TileEnt rendering + RENDER_ENTITY(RunType.ONREQUEST, Side.CLIENT), // Profiler for Entity rendering + RENDER_BLOCK(RunType.ONREQUEST, Side.CLIENT); // Profiler for Block rendering - public static void desactivateAll(Side trgside){ - for (ProfilerSection section : ProfilerSection.values()) - if (section.sides.contains(trgside)) - section.desactivate(); - } + public enum RunType { + REALTIME, + ONREQUEST; + } - public static void resetAll(Side trgside){ - for (ProfilerSection section : ProfilerSection.values()) - if (section.sides.contains(trgside)) - section.reset(); - } - - public static String getClassName(){ - return ProfilerSection.class.getCanonicalName().replace(".", "/"); - } - - public static String getTypeName(){ - return "L" + ProfilerSection.getClassName() + ";"; - } - - @Override - public void reset() { this.profiler.reset(); this.profilerSuspended.reset(); } - @Override - public void start() { this.profiler.start(); } - @Override - public void stop() { this.profiler.stop(); } - @Override - public void start(Object key) { this.profiler.start(key); } - @Override - public void stop(Object key) { this.profiler.stop(key); } - @Override - public void start(Object key1, Object key2) { this.profiler.start(key1, key2); } - @Override - public void stop(Object key1, Object key2) { this.profiler.stop(key1, key2); } - @Override - public void start(Object key1, Object key2, Object key3) { this.profiler.start(key1, key2, key3);} - @Override - public void stop(Object key1, Object key2, Object key3) { this.profiler.stop(key1, key2, key3); } - @Override - public void start(Object key1, Object key2, Object key3, Object key4) { this.profiler.start(key1, key2, key3, key4);} - @Override - public void stop(Object key1, Object key2, Object key3, Object key4) { this.profiler.stop(key1, key2, key3, key4); } + private EnumSet sides; + private RunType runType; + private IProfilerBase profiler = new DummyProfiler(); + ; + private IProfilerBase profilerSuspended = new DummyProfiler(); + ; + + public static long timeStampLastRun; + + private ProfilerSection(RunType runType, Side side) { + this.runType = runType; + this.profiler = new DummyProfiler(); + this.sides = EnumSet.of(side); + } + + private ProfilerSection(RunType runType, EnumSet sides) { + this.runType = runType; + this.profiler = new DummyProfiler(); + this.sides = sides; + } + + public RunType getRunType() { + return this.runType; + } + + public EnumSet getSide() { + return this.sides; + } + + public IProfilerBase getProfiler() { + return this.profilerSuspended; + } + + public void setProfiler(IProfilerBase profiler) { + this.profilerSuspended = profiler; + if (this.runType == RunType.REALTIME) this.profiler = profiler; + } + + public void activate() { + this.profiler = profilerSuspended; + this.timeStampLastRun = System.currentTimeMillis(); + } + + public void desactivate() { + if (this.runType == RunType.ONREQUEST) this.profiler = new DummyProfiler(); + } + + public static void activateAll(Side trgside) { + for (ProfilerSection section : ProfilerSection.values()) + if (section.sides.contains(trgside)) section.activate(); + } + + public static void desactivateAll(Side trgside) { + for (ProfilerSection section : ProfilerSection.values()) + if (section.sides.contains(trgside)) section.desactivate(); + } + + public static void resetAll(Side trgside) { + for (ProfilerSection section : ProfilerSection.values()) if (section.sides.contains(trgside)) section.reset(); + } + + public static String getClassName() { + return ProfilerSection.class.getCanonicalName().replace(".", "/"); + } + + public static String getTypeName() { + return "L" + ProfilerSection.getClassName() + ";"; + } + + @Override + public void reset() { + this.profiler.reset(); + this.profilerSuspended.reset(); + } + + @Override + public void start() { + this.profiler.start(); + } + + @Override + public void stop() { + this.profiler.stop(); + } + + @Override + public void start(Object key) { + this.profiler.start(key); + } + + @Override + public void stop(Object key) { + this.profiler.stop(key); + } + + @Override + public void start(Object key1, Object key2) { + this.profiler.start(key1, key2); + } + + @Override + public void stop(Object key1, Object key2) { + this.profiler.stop(key1, key2); + } + + @Override + public void start(Object key1, Object key2, Object key3) { + this.profiler.start(key1, key2, key3); + } + + @Override + public void stop(Object key1, Object key2, Object key3) { + this.profiler.stop(key1, key2, key3); + } + + @Override + public void start(Object key1, Object key2, Object key3, Object key4) { + this.profiler.start(key1, key2, key3, key4); + } + + @Override + public void stop(Object key1, Object key2, Object key3, Object key4) { + this.profiler.stop(key1, key2, key3, key4); + } } diff --git a/src/main/java/mcp/mobius/opis/api/IMessageHandler.java b/src/main/java/mcp/mobius/opis/api/IMessageHandler.java index f36468d..074e422 100644 --- a/src/main/java/mcp/mobius/opis/api/IMessageHandler.java +++ b/src/main/java/mcp/mobius/opis/api/IMessageHandler.java @@ -4,5 +4,5 @@ import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; public interface IMessageHandler { - public boolean handleMessage(Message msg, PacketBase rawdata); + public boolean handleMessage(Message msg, PacketBase rawdata); } diff --git a/src/main/java/mcp/mobius/opis/api/ITabPanel.java b/src/main/java/mcp/mobius/opis/api/ITabPanel.java index f57a079..af00048 100644 --- a/src/main/java/mcp/mobius/opis/api/ITabPanel.java +++ b/src/main/java/mcp/mobius/opis/api/ITabPanel.java @@ -1,10 +1,11 @@ package mcp.mobius.opis.api; -import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.swing.SelectedTab; public interface ITabPanel { - SelectedTab getSelectedTab(); - boolean refreshOnString(); //Should we refresh on a cache update ? - boolean refresh(); //Do the actual refresh + SelectedTab getSelectedTab(); + + boolean refreshOnString(); // Should we refresh on a cache update ? + + boolean refresh(); // Do the actual refresh } diff --git a/src/main/java/mcp/mobius/opis/api/MessageHandlerRegistrar.java b/src/main/java/mcp/mobius/opis/api/MessageHandlerRegistrar.java index 03cfb9b..4d86780 100644 --- a/src/main/java/mcp/mobius/opis/api/MessageHandlerRegistrar.java +++ b/src/main/java/mcp/mobius/opis/api/MessageHandlerRegistrar.java @@ -1,36 +1,32 @@ package mcp.mobius.opis.api; -import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; - import mcp.mobius.opis.modOpis; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; public enum MessageHandlerRegistrar { - INSTANCE; - - private HashMap> msgHandlers = new HashMap>(); - - public void registerHandler(Message msg, IMessageHandler handler){ - if (!msgHandlers.containsKey(msg)) - msgHandlers.put(msg, new HashSet()); - - msgHandlers.get(msg).add(handler); - } - - public void routeMessage(Message msg, PacketBase rawdata){ - - if (msgHandlers.containsKey(msg)){ - for (IMessageHandler handler : msgHandlers.get(msg)){ - if (!handler.handleMessage(msg, rawdata)){ - modOpis.log.warn(String.format("Unhandled msg %s in handler %s", msg, handler)); - } - } - } - else{ - modOpis.log.warn(String.format("Unhandled msg : %s", msg)); - } - } + INSTANCE; + + private HashMap> msgHandlers = new HashMap>(); + + public void registerHandler(Message msg, IMessageHandler handler) { + if (!msgHandlers.containsKey(msg)) msgHandlers.put(msg, new HashSet()); + + msgHandlers.get(msg).add(handler); + } + + public void routeMessage(Message msg, PacketBase rawdata) { + + if (msgHandlers.containsKey(msg)) { + for (IMessageHandler handler : msgHandlers.get(msg)) { + if (!handler.handleMessage(msg, rawdata)) { + modOpis.log.warn(String.format("Unhandled msg %s in handler %s", msg, handler)); + } + } + } else { + modOpis.log.warn(String.format("Unhandled msg : %s", msg)); + } + } } diff --git a/src/main/java/mcp/mobius/opis/api/TabPanelRegistrar.java b/src/main/java/mcp/mobius/opis/api/TabPanelRegistrar.java index 48332df..319b50d 100644 --- a/src/main/java/mcp/mobius/opis/api/TabPanelRegistrar.java +++ b/src/main/java/mcp/mobius/opis/api/TabPanelRegistrar.java @@ -1,14 +1,11 @@ package mcp.mobius.opis.api; import java.awt.Component; -import java.util.ArrayList; import java.util.HashMap; - import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; - import mcp.mobius.opis.data.holders.basetypes.SerialInt; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; @@ -16,62 +13,61 @@ import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.SwingUI; -public enum TabPanelRegistrar implements ChangeListener{ - INSTANCE; - - //private ArrayList panels = new ArrayList(); - //private HashMap lookup = new HashMap(); - private HashMap sections = new HashMap(); - private HashMap lookup = new HashMap(); - - public JTabbedPane registerSection(String name){ - JTabbedPane pane = new JTabbedPane(); - pane.addChangeListener(this); - this.sections.put(name, pane); - SwingUI.instance().getTabbedPane().addTab(name, pane); - return pane; - } - - public ITabPanel registerTab(ITabPanel panel, String name){ - this.lookup.put(panel.getSelectedTab(), panel); - SwingUI.instance().getTabbedPane().addTab(name, (JPanel)panel); - return panel; - } - - public ITabPanel registerTab(ITabPanel panel, String name, String section){ - this.lookup.put(panel.getSelectedTab(), panel); - this.sections.get(section).addTab(name, (JPanel)panel); - return panel; - } - - public ITabPanel getTab(SelectedTab refname){ - return lookup.get(refname); - } +public enum TabPanelRegistrar implements ChangeListener { + INSTANCE; - public JPanel getTabAsPanel(SelectedTab refname){ - return (JPanel)lookup.get(refname); - } + // private ArrayList panels = new ArrayList(); + // private HashMap lookup = new HashMap(); + private HashMap sections = new HashMap(); + private HashMap lookup = new HashMap(); - public void refreshAll(){ - for (ITabPanel panel : this.lookup.values()) - if (panel.refreshOnString()) - panel.refresh(); - } - - @Override - public void stateChanged(ChangeEvent e) { - Component source = ((JTabbedPane)e.getSource()).getSelectedComponent(); - - if (source instanceof ITabPanel){ - ITabPanel panel = (ITabPanel)source; - PacketManager.sendToServer(new PacketReqData(Message.SWING_TAB_CHANGED, new SerialInt(panel.getSelectedTab().ordinal()))); - } - - } - - /* - public ArrayList getTabs(){ - return this.panels; - } - */ + public JTabbedPane registerSection(String name) { + JTabbedPane pane = new JTabbedPane(); + pane.addChangeListener(this); + this.sections.put(name, pane); + SwingUI.instance().getTabbedPane().addTab(name, pane); + return pane; + } + + public ITabPanel registerTab(ITabPanel panel, String name) { + this.lookup.put(panel.getSelectedTab(), panel); + SwingUI.instance().getTabbedPane().addTab(name, (JPanel) panel); + return panel; + } + + public ITabPanel registerTab(ITabPanel panel, String name, String section) { + this.lookup.put(panel.getSelectedTab(), panel); + this.sections.get(section).addTab(name, (JPanel) panel); + return panel; + } + + public ITabPanel getTab(SelectedTab refname) { + return lookup.get(refname); + } + + public JPanel getTabAsPanel(SelectedTab refname) { + return (JPanel) lookup.get(refname); + } + + public void refreshAll() { + for (ITabPanel panel : this.lookup.values()) if (panel.refreshOnString()) panel.refresh(); + } + + @Override + public void stateChanged(ChangeEvent e) { + Component source = ((JTabbedPane) e.getSource()).getSelectedComponent(); + + if (source instanceof ITabPanel) { + ITabPanel panel = (ITabPanel) source; + PacketManager.sendToServer(new PacketReqData( + Message.SWING_TAB_CHANGED, + new SerialInt(panel.getSelectedTab().ordinal()))); + } + } + + /* + public ArrayList getTabs(){ + return this.panels; + } + */ } diff --git a/src/main/java/mcp/mobius/opis/commands/IOpisCommand.java b/src/main/java/mcp/mobius/opis/commands/IOpisCommand.java index 972bba7..9a382ab 100644 --- a/src/main/java/mcp/mobius/opis/commands/IOpisCommand.java +++ b/src/main/java/mcp/mobius/opis/commands/IOpisCommand.java @@ -1,6 +1,7 @@ package mcp.mobius.opis.commands; public interface IOpisCommand { - String getDescription(); - String getCommandNameOpis(); + String getDescription(); + + String getCommandNameOpis(); } diff --git a/src/main/java/mcp/mobius/opis/commands/client/CommandClientShowRenderTick.java b/src/main/java/mcp/mobius/opis/commands/client/CommandClientShowRenderTick.java index 44739b0..db53b46 100644 --- a/src/main/java/mcp/mobius/opis/commands/client/CommandClientShowRenderTick.java +++ b/src/main/java/mcp/mobius/opis/commands/client/CommandClientShowRenderTick.java @@ -1,6 +1,5 @@ package mcp.mobius.opis.commands.client; - import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.server.NetDataCommand; @@ -10,33 +9,31 @@ import net.minecraft.entity.player.EntityPlayerMP; public class CommandClientShowRenderTick extends CommandBase { - @Override - public String getCommandName() { - return "opis_ctick"; - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (icommandsender instanceof EntityPlayerMP) - PacketManager.validateAndSend(new NetDataCommand(Message.CLIENT_SHOW_RENDER_TICK), (EntityPlayerMP)icommandsender); - //((EntityPlayerMP)icommandsender).playerNetServerHandler.sendPacketToPlayer(NetDataCommand.create(Message.CLIENT_SHOW_RENDER_TICK)); - } - - @Override - public int getRequiredPermissionLevel() - { - return 0; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - return true; + @Override + public String getCommandName() { + return "opis_ctick"; } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (icommandsender instanceof EntityPlayerMP) + PacketManager.validateAndSend( + new NetDataCommand(Message.CLIENT_SHOW_RENDER_TICK), (EntityPlayerMP) icommandsender); + // ((EntityPlayerMP)icommandsender).playerNetServerHandler.sendPacketToPlayer(NetDataCommand.create(Message.CLIENT_SHOW_RENDER_TICK)); + } + + @Override + public int getRequiredPermissionLevel() { + return 0; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/client/CommandClientStart.java b/src/main/java/mcp/mobius/opis/commands/client/CommandClientStart.java index 9efaaf5..e352b46 100644 --- a/src/main/java/mcp/mobius/opis/commands/client/CommandClientStart.java +++ b/src/main/java/mcp/mobius/opis/commands/client/CommandClientStart.java @@ -9,33 +9,31 @@ import net.minecraft.entity.player.EntityPlayerMP; public class CommandClientStart extends CommandBase { - @Override - public String getCommandName() { - return "opis_cstart"; - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (icommandsender instanceof EntityPlayerMP) - PacketManager.validateAndSend(new NetDataCommand(Message.CLIENT_START_PROFILING), (EntityPlayerMP)icommandsender); - //((EntityPlayerMP)icommandsender).playerNetServerHandler.sendPacketToPlayer(NetDataCommand.create(Message.CLIENT_START_PROFILING)); - } - - @Override - public int getRequiredPermissionLevel() - { - return 0; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - return true; + @Override + public String getCommandName() { + return "opis_cstart"; } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (icommandsender instanceof EntityPlayerMP) + PacketManager.validateAndSend( + new NetDataCommand(Message.CLIENT_START_PROFILING), (EntityPlayerMP) icommandsender); + // ((EntityPlayerMP)icommandsender).playerNetServerHandler.sendPacketToPlayer(NetDataCommand.create(Message.CLIENT_START_PROFILING)); + } + + @Override + public int getRequiredPermissionLevel() { + return 0; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/client/CommandOpis.java b/src/main/java/mcp/mobius/opis/commands/client/CommandOpis.java index e2819a6..436d802 100644 --- a/src/main/java/mcp/mobius/opis/commands/client/CommandOpis.java +++ b/src/main/java/mcp/mobius/opis/commands/client/CommandOpis.java @@ -1,57 +1,54 @@ package mcp.mobius.opis.commands.client; -import javax.swing.JFrame; -import javax.swing.JLabel; - import mcp.mobius.opis.events.PlayerTracker; import mcp.mobius.opis.network.PacketManager; -import mcp.mobius.opis.network.ServerMessageHandler; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.server.NetDataCommand; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ChatComponentText; public class CommandOpis extends CommandBase { - @Override - public String getCommandName() { - return "opis"; - } + @Override + public String getCommandName() { + return "opis"; + } - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (!(icommandsender instanceof EntityPlayerMP)){ - icommandsender.addChatMessage(new ChatComponentText("You are not a normal client and can't open the Swing interface.")); - return; - } - - if (!Message.COMMAND_OPEN_SWING.canPlayerUseCommand((EntityPlayerMP)icommandsender)){ - icommandsender.addChatMessage(new ChatComponentText("Your access level prevents you from doing that.")); - return; - } - - PlayerTracker.INSTANCE.playersSwing.add((EntityPlayerMP)icommandsender); - //((EntityPlayerMP)icommandsender).playerNetServerHandler.sendPacketToPlayer(NetDataCommand.create(Message.CLIENT_SHOW_SWING)); - if (icommandsender instanceof EntityPlayerMP) - PacketManager.validateAndSend(new NetDataCommand(Message.CLIENT_SHOW_SWING), (EntityPlayerMP)icommandsender); - PacketManager.sendFullUpdate((EntityPlayerMP)icommandsender); - } - - @Override - public int getRequiredPermissionLevel(){ + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (!(icommandsender instanceof EntityPlayerMP)) { + icommandsender.addChatMessage( + new ChatComponentText("You are not a normal client and can't open the Swing interface.")); + return; + } + + if (!Message.COMMAND_OPEN_SWING.canPlayerUseCommand((EntityPlayerMP) icommandsender)) { + icommandsender.addChatMessage(new ChatComponentText("Your access level prevents you from doing that.")); + return; + } + + PlayerTracker.INSTANCE.playersSwing.add((EntityPlayerMP) icommandsender); + // ((EntityPlayerMP)icommandsender).playerNetServerHandler.sendPacketToPlayer(NetDataCommand.create(Message.CLIENT_SHOW_SWING)); + if (icommandsender instanceof EntityPlayerMP) + PacketManager.validateAndSend( + new NetDataCommand(Message.CLIENT_SHOW_SWING), (EntityPlayerMP) icommandsender); + PacketManager.sendFullUpdate((EntityPlayerMP) icommandsender); + } + + @Override + public int getRequiredPermissionLevel() { return 0; - } + } - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender){ - return true; - } + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandAddPrivileged.java b/src/main/java/mcp/mobius/opis/commands/server/CommandAddPrivileged.java index 0e8f472..5f1d5f9 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandAddPrivileged.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandAddPrivileged.java @@ -8,50 +8,47 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; +public class CommandAddPrivileged extends CommandBase implements IOpisCommand { -public class CommandAddPrivileged extends CommandBase implements IOpisCommand{ - - @Override - public String getCommandName() { - return "opis_addpriv"; - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - PlayerTracker.INSTANCE.addPrivilegedPlayer(astring[0]); - icommandsender.addChatMessage(new ChatComponentText(String.format("Player %s added to Opis user list", astring[0]))); - } - - @Override - public int getRequiredPermissionLevel() - { - return 3; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - if (sender instanceof EntityPlayerMP) - return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP)sender); - - if (sender instanceof DedicatedServer) return true; - if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; - - return false; + @Override + public String getCommandName() { + return "opis_addpriv"; } - @Override - public String getDescription() { - return "Add a user to the privileged list of users."; - } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } - @Override - public String getCommandNameOpis() { - return "opis_addpriv"; - } + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + PlayerTracker.INSTANCE.addPrivilegedPlayer(astring[0]); + icommandsender.addChatMessage( + new ChatComponentText(String.format("Player %s added to Opis user list", astring[0]))); + } + + @Override + public int getRequiredPermissionLevel() { + return 3; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + if (sender instanceof EntityPlayerMP) return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP) sender); + + if (sender instanceof DedicatedServer) return true; + if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; + + return false; + } + + @Override + public String getDescription() { + return "Add a user to the privileged list of users."; + } + + @Override + public String getCommandNameOpis() { + return "opis_addpriv"; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandAmountEntities.java b/src/main/java/mcp/mobius/opis/commands/server/CommandAmountEntities.java index 51de1ca..b5af7c1 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandAmountEntities.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandAmountEntities.java @@ -1,73 +1,59 @@ package mcp.mobius.opis.commands.server; import java.util.ArrayList; -import java.util.HashMap; - import mcp.mobius.opis.commands.IOpisCommand; import mcp.mobius.opis.data.holders.basetypes.AmountHolder; import mcp.mobius.opis.data.managers.EntityManager; -import mcp.mobius.opis.events.PlayerTracker; -import mcp.mobius.opis.network.enums.Message; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.rcon.RConConsoleSource; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; -public class CommandAmountEntities extends CommandBase implements IOpisCommand{ +public class CommandAmountEntities extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_nent"; - } - - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (icommandsender instanceof EntityPlayerMP){ - icommandsender.addChatMessage(new ChatComponentText("DEPRECATED ! Please run /opis instead.")); - return; - } - - - ArrayList ents; - - if (astring.length == 1 && astring[0].equals("all")) - ents = EntityManager.INSTANCE.getCumulativeEntities(false); - else - ents = EntityManager.INSTANCE.getCumulativeEntities(true); - - for (AmountHolder s : ents) - icommandsender.addChatMessage(new ChatComponentText(String.format("%s : %s", s.key, s.value))); - } - - @Override - public int getRequiredPermissionLevel() - { - return 0; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - return true; + @Override + public String getCommandName() { + return "opis_nent"; } - @Override - public String getDescription() { - return "Opens a summary of the number of entities on the server, by type."; - } + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (icommandsender instanceof EntityPlayerMP) { + icommandsender.addChatMessage(new ChatComponentText("DEPRECATED ! Please run /opis instead.")); + return; + } + + ArrayList ents; + + if (astring.length == 1 && astring[0].equals("all")) ents = EntityManager.INSTANCE.getCumulativeEntities(false); + else ents = EntityManager.INSTANCE.getCumulativeEntities(true); + + for (AmountHolder s : ents) + icommandsender.addChatMessage(new ChatComponentText(String.format("%s : %s", s.key, s.value))); + } + + @Override + public int getRequiredPermissionLevel() { + return 0; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return true; + } + + @Override + public String getDescription() { + return "Opens a summary of the number of entities on the server, by type."; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandChunkDump.java b/src/main/java/mcp/mobius/opis/commands/server/CommandChunkDump.java index 11f8e48..6c6b977 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandChunkDump.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandChunkDump.java @@ -1,75 +1,67 @@ package mcp.mobius.opis.commands.server; import java.util.HashMap; -import java.util.HashSet; import java.util.Set; - -import org.apache.logging.log4j.Level; - -import com.google.common.collect.ImmutableSetMultimap; - -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.commands.IOpisCommand; +import mcp.mobius.opis.modOpis; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.world.ChunkCoordIntPair; -import net.minecraft.world.WorldServer; import net.minecraftforge.common.DimensionManager; -import net.minecraftforge.common.ForgeChunkManager.Ticket; -import net.minecraft.entity.player.EntityPlayerMP; +import org.apache.logging.log4j.Level; -public class CommandChunkDump extends CommandBase implements IOpisCommand{ +public class CommandChunkDump extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "chunkdump"; - } + @Override + public String getCommandName() { + return "chunkdump"; + } - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - modOpis.log.log(Level.INFO, "== CHUNK DUMP =="); - - HashMap chunkStatus = new HashMap(); - - Integer[] worldIDs = DimensionManager.getIDs(); - for (Integer worldID : worldIDs){ - Set persistantChunks = DimensionManager.getWorld(worldID).getPersistentChunks().keySet(); - Set chunks = (Set)DimensionManager.getWorld(worldID).activeChunkSet; - - for (ChunkCoordIntPair chunk : chunks){ - modOpis.log.log(Level.INFO, String.format("Dim : %s, %s, Forced : %s", worldID, chunk, persistantChunks.contains(chunk))); - chunkStatus.put(chunk, persistantChunks.contains(chunk)); - } - } - - //((EntityPlayerMP)icommandsender).playerNetServerHandler.sendPacketToPlayer(Packet_LoadedChunks.create(chunkStatus)); - } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } - @Override - public int getRequiredPermissionLevel() - { + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + modOpis.log.log(Level.INFO, "== CHUNK DUMP =="); + + HashMap chunkStatus = new HashMap(); + + Integer[] worldIDs = DimensionManager.getIDs(); + for (Integer worldID : worldIDs) { + Set persistantChunks = + DimensionManager.getWorld(worldID).getPersistentChunks().keySet(); + Set chunks = (Set) DimensionManager.getWorld(worldID).activeChunkSet; + + for (ChunkCoordIntPair chunk : chunks) { + modOpis.log.log( + Level.INFO, + String.format("Dim : %s, %s, Forced : %s", worldID, chunk, persistantChunks.contains(chunk))); + chunkStatus.put(chunk, persistantChunks.contains(chunk)); + } + } + + // ((EntityPlayerMP)icommandsender).playerNetServerHandler.sendPacketToPlayer(Packet_LoadedChunks.create(chunkStatus)); + } + + @Override + public int getRequiredPermissionLevel() { return 0; - } + } - @Override - public boolean canCommandSenderUseCommand(ICommandSender par1ICommandSender) - { + @Override + public boolean canCommandSenderUseCommand(ICommandSender par1ICommandSender) { return false; } - @Override - public String getDescription() { - return "Unused"; - } - + @Override + public String getDescription() { + return "Unused"; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandChunkList.java b/src/main/java/mcp/mobius/opis/commands/server/CommandChunkList.java index 41811dd..fce4536 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandChunkList.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandChunkList.java @@ -1,76 +1,66 @@ package mcp.mobius.opis.commands.server; import java.util.ArrayList; - import mcp.mobius.opis.commands.IOpisCommand; import mcp.mobius.opis.data.holders.stats.StatsChunk; import mcp.mobius.opis.data.managers.ChunkManager; -import mcp.mobius.opis.events.PlayerTracker; -import mcp.mobius.opis.network.enums.Message; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; public class CommandChunkList extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_chunk"; - } - - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (icommandsender instanceof EntityPlayerMP){ - icommandsender.addChatMessage(new ChatComponentText("DEPRECATED ! Please run /opis instead.")); - return; - } - - ArrayList chunks = new ArrayList(); - - if (astring.length == 0) - chunks = ChunkManager.INSTANCE.getTopChunks(20); - else - try{ - chunks = ChunkManager.INSTANCE.getTopChunks(Integer.valueOf(astring.length)); - }catch (Exception e){return;} - - icommandsender.addChatMessage(new ChatComponentText("[DIM X Z] Time NTEs")); - for (StatsChunk stat : chunks){ - icommandsender.addChatMessage(new ChatComponentText(stat.toString())); - } - - - } - - @Override - public int getRequiredPermissionLevel() - { - return 0; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - return true; + @Override + public String getCommandName() { + return "opis_chunk"; } - @Override - public String getDescription() { - return "Shows the 20 slowest chunks, in respect to tile entities."; - } + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (icommandsender instanceof EntityPlayerMP) { + icommandsender.addChatMessage(new ChatComponentText("DEPRECATED ! Please run /opis instead.")); + return; + } + + ArrayList chunks = new ArrayList(); + + if (astring.length == 0) chunks = ChunkManager.INSTANCE.getTopChunks(20); + else + try { + chunks = ChunkManager.INSTANCE.getTopChunks(Integer.valueOf(astring.length)); + } catch (Exception e) { + return; + } + + icommandsender.addChatMessage(new ChatComponentText("[DIM X Z] Time NTEs")); + for (StatsChunk stat : chunks) { + icommandsender.addChatMessage(new ChatComponentText(stat.toString())); + } + } + + @Override + public int getRequiredPermissionLevel() { + return 0; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return true; + } + + @Override + public String getDescription() { + return "Shows the 20 slowest chunks, in respect to tile entities."; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandEntityCreate.java b/src/main/java/mcp/mobius/opis/commands/server/CommandEntityCreate.java index c73d1c0..66ec385 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandEntityCreate.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandEntityCreate.java @@ -5,53 +5,49 @@ import mcp.mobius.opis.events.PlayerTracker; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; public class CommandEntityCreate extends CommandBase { - @Override - public String getCommandName() { - return "opis_enttrace"; - } + @Override + public String getCommandName() { + return "opis_enttrace"; + } - @Override - public String getCommandUsage(ICommandSender icommandsender) { - // TODO Auto-generated method stub - return ""; - } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + // TODO Auto-generated method stub + return ""; + } - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - - if (astring.length == 1 && astring[0].equals("full")){ - OpisServerEventHandler.printEntityFull = true; - OpisServerEventHandler.printEntityTrace = true; - } else { - OpisServerEventHandler.printEntityTrace = !OpisServerEventHandler.printEntityTrace; - OpisServerEventHandler.printEntityFull = false; - } - - icommandsender.addChatMessage(new ChatComponentText(String.format("Entity trace is %s", OpisServerEventHandler.printEntityTrace))); - } + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { - @Override - public int getRequiredPermissionLevel() - { + if (astring.length == 1 && astring[0].equals("full")) { + OpisServerEventHandler.printEntityFull = true; + OpisServerEventHandler.printEntityTrace = true; + } else { + OpisServerEventHandler.printEntityTrace = !OpisServerEventHandler.printEntityTrace; + OpisServerEventHandler.printEntityFull = false; + } + + icommandsender.addChatMessage( + new ChatComponentText(String.format("Entity trace is %s", OpisServerEventHandler.printEntityTrace))); + } + + @Override + public int getRequiredPermissionLevel() { return 3; - } + } - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - if (sender instanceof EntityPlayerMP) - return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP)sender); - - if (sender instanceof DedicatedServer) return true; - if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + if (sender instanceof EntityPlayerMP) return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP) sender); - return false; - } - + if (sender instanceof DedicatedServer) return true; + if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; + + return false; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandFrequency.java b/src/main/java/mcp/mobius/opis/commands/server/CommandFrequency.java index 79ece9d..a9a5213 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandFrequency.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandFrequency.java @@ -1,64 +1,60 @@ package mcp.mobius.opis.commands.server; -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.commands.IOpisCommand; import mcp.mobius.opis.events.PlayerTracker; +import mcp.mobius.opis.modOpis; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; public class CommandFrequency extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_delay"; - } - - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (astring.length < 1) return; - try{ - modOpis.profilerDelay = Integer.valueOf(astring[0]); - icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oOpis delay set to %s ticks.", astring[0]))); - - } catch (Exception e){} - } - - @Override - public int getRequiredPermissionLevel() - { - return 3; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - if (sender instanceof EntityPlayerMP) - return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP)sender); - - if (sender instanceof DedicatedServer) return true; - if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; - - return false; + @Override + public String getCommandName() { + return "opis_delay"; } - @Override - public String getDescription() { - return "Sets the delay in ticks between 2 data points."; - } - + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } + + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (astring.length < 1) return; + try { + modOpis.profilerDelay = Integer.valueOf(astring[0]); + icommandsender.addChatMessage( + new ChatComponentText(String.format("\u00A7oOpis delay set to %s ticks.", astring[0]))); + + } catch (Exception e) { + } + } + + @Override + public int getRequiredPermissionLevel() { + return 3; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + if (sender instanceof EntityPlayerMP) return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP) sender); + + if (sender instanceof DedicatedServer) return true; + if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; + + return false; + } + + @Override + public String getDescription() { + return "Sets the delay in ticks between 2 data points."; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandHelp.java b/src/main/java/mcp/mobius/opis/commands/server/CommandHelp.java index 58ddac4..6c4d297 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandHelp.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandHelp.java @@ -3,70 +3,60 @@ package mcp.mobius.opis.commands.server; import mcp.mobius.opis.commands.IOpisCommand; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; public class CommandHelp extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_help"; - } - - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - IOpisCommand[] commands = { - new CommandStart(), - new CommandStop(), - new CommandReset(), - new CommandFrequency(), - new CommandTicks(), - - new CommandChunkList(), - new CommandTimingTileEntities(), - - new CommandTimingEntities(), - new CommandAmountEntities(), - - new CommandKill(), - new CommandKillAll(), - - new CommandAddPrivileged(), - new CommandRmPrivileged() - }; - - for (IOpisCommand cmd : commands) - icommandsender.addChatMessage(new ChatComponentText(String.format("/%s : %s", cmd.getCommandNameOpis(), cmd.getDescription()))); - } - - @Override - public int getRequiredPermissionLevel() - { - return 3; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - return true; + @Override + public String getCommandName() { + return "opis_help"; } - @Override - public String getDescription() { - return "This message."; - } + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + IOpisCommand[] commands = { + new CommandStart(), + new CommandStop(), + new CommandReset(), + new CommandFrequency(), + new CommandTicks(), + new CommandChunkList(), + new CommandTimingTileEntities(), + new CommandTimingEntities(), + new CommandAmountEntities(), + new CommandKill(), + new CommandKillAll(), + new CommandAddPrivileged(), + new CommandRmPrivileged() + }; + + for (IOpisCommand cmd : commands) + icommandsender.addChatMessage( + new ChatComponentText(String.format("/%s : %s", cmd.getCommandNameOpis(), cmd.getDescription()))); + } + + @Override + public int getRequiredPermissionLevel() { + return 3; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return true; + } + + @Override + public String getDescription() { + return "This message."; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandKill.java b/src/main/java/mcp/mobius/opis/commands/server/CommandKill.java index 98363b9..cc6421e 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandKill.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandKill.java @@ -6,7 +6,6 @@ import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; @@ -14,65 +13,64 @@ import net.minecraftforge.common.DimensionManager; public class CommandKill extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_kill"; - } - - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (astring.length != 2) return; - int dim = Integer.valueOf(astring[0]); - int eid = Integer.valueOf(astring[1]); - - World world = DimensionManager.getWorld(dim); - if (world == null){ - icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oCannot find dim %d in world %d", dim))); - return; - } - - Entity entity = world.getEntityByID(eid); - if (entity == null) { - icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oCannot find entity %d in dim %d", eid, dim))); - return; - } - - entity.setDead(); - icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oKilled entity %d in dim %d", eid, dim))); - return; - } - - @Override - public int getRequiredPermissionLevel() - { - return 3; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - if (sender instanceof EntityPlayerMP) - return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP)sender); - - if (sender instanceof DedicatedServer) return true; - if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; - - return false; + @Override + public String getCommandName() { + return "opis_kill"; } - @Override - public String getDescription() { - return "Kills the given entity id in the given dimension."; - } + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (astring.length != 2) return; + int dim = Integer.valueOf(astring[0]); + int eid = Integer.valueOf(astring[1]); + + World world = DimensionManager.getWorld(dim); + if (world == null) { + icommandsender.addChatMessage( + new ChatComponentText(String.format("\u00A7oCannot find dim %d in world %d", dim))); + return; + } + + Entity entity = world.getEntityByID(eid); + if (entity == null) { + icommandsender.addChatMessage( + new ChatComponentText(String.format("\u00A7oCannot find entity %d in dim %d", eid, dim))); + return; + } + + entity.setDead(); + icommandsender.addChatMessage( + new ChatComponentText(String.format("\u00A7oKilled entity %d in dim %d", eid, dim))); + return; + } + + @Override + public int getRequiredPermissionLevel() { + return 3; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + if (sender instanceof EntityPlayerMP) return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP) sender); + + if (sender instanceof DedicatedServer) return true; + if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; + + return false; + } + + @Override + public String getDescription() { + return "Kills the given entity id in the given dimension."; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandKillAll.java b/src/main/java/mcp/mobius/opis/commands/server/CommandKillAll.java index f65206f..b9bcfbf 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandKillAll.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandKillAll.java @@ -1,101 +1,91 @@ package mcp.mobius.opis.commands.server; -import java.util.ArrayList; - -import org.apache.commons.lang3.StringUtils; - import mcp.mobius.opis.commands.IOpisCommand; import mcp.mobius.opis.data.managers.EntityManager; import mcp.mobius.opis.events.PlayerTracker; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; -import net.minecraft.world.World; -import net.minecraftforge.common.DimensionManager; +import org.apache.commons.lang3.StringUtils; public class CommandKillAll extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_killall"; - } - - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (astring.length < 1) return; - - String searchname = StringUtils.join(astring, " ").toLowerCase(); - - int nkilled = EntityManager.INSTANCE.killAll(searchname); - - if (nkilled == -1){ - icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oSeriously ? I can't, seriously, I can't. I should remove you from the OP list !"))); - return; - } - - icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oKilled %d entities of type %s", nkilled, searchname))); - - /* - World world = DimensionManager.getWorld(dim); - if (world == null){ - PacketDispatcher.sendPacketToPlayer( - new Packet3Chat(ChatMessageComponent.createFromText(String.format("\u00A7oCannot find dim %d in world %d", dim))), - (Player)icommandsender); - return; - } - - Entity entity = world.getEntityByID(eid); - if (entity == null) { - PacketDispatcher.sendPacketToPlayer( - new Packet3Chat(ChatMessageComponent.createFromText(String.format("\u00A7oCannot find entity %d in dim %d", eid, dim))), - (Player)icommandsender); - return; - } - - entity.setDead(); - PacketDispatcher.sendPacketToPlayer( - new Packet3Chat(ChatMessageComponent.createFromText(String.format("\u00A7oKilled entity %d in dim %d", eid, dim))), - (Player)icommandsender); - return; - */ - } - - @Override - public int getRequiredPermissionLevel() - { - return 3; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - if (sender instanceof EntityPlayerMP) - return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP)sender); - - if (sender instanceof DedicatedServer) return true; - if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; - - return false; + @Override + public String getCommandName() { + return "opis_killall"; } - @Override - public String getDescription() { - return "Kills all entities of the given name."; - } + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (astring.length < 1) return; + + String searchname = StringUtils.join(astring, " ").toLowerCase(); + + int nkilled = EntityManager.INSTANCE.killAll(searchname); + + if (nkilled == -1) { + icommandsender.addChatMessage(new ChatComponentText(String.format( + "\u00A7oSeriously ? I can't, seriously, I can't. I should remove you from the OP list !"))); + return; + } + + icommandsender.addChatMessage( + new ChatComponentText(String.format("\u00A7oKilled %d entities of type %s", nkilled, searchname))); + + /* + World world = DimensionManager.getWorld(dim); + if (world == null){ + PacketDispatcher.sendPacketToPlayer( + new Packet3Chat(ChatMessageComponent.createFromText(String.format("\u00A7oCannot find dim %d in world %d", dim))), + (Player)icommandsender); + return; + } + + Entity entity = world.getEntityByID(eid); + if (entity == null) { + PacketDispatcher.sendPacketToPlayer( + new Packet3Chat(ChatMessageComponent.createFromText(String.format("\u00A7oCannot find entity %d in dim %d", eid, dim))), + (Player)icommandsender); + return; + } + + entity.setDead(); + PacketDispatcher.sendPacketToPlayer( + new Packet3Chat(ChatMessageComponent.createFromText(String.format("\u00A7oKilled entity %d in dim %d", eid, dim))), + (Player)icommandsender); + return; + */ + } + + @Override + public int getRequiredPermissionLevel() { + return 3; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + if (sender instanceof EntityPlayerMP) return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP) sender); + + if (sender instanceof DedicatedServer) return true; + if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; + + return false; + } + + @Override + public String getDescription() { + return "Kills all entities of the given name."; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandReset.java b/src/main/java/mcp/mobius/opis/commands/server/CommandReset.java index 497c548..9f222a3 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandReset.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandReset.java @@ -14,53 +14,50 @@ import net.minecraft.util.ChatComponentText; public class CommandReset extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_reset"; - } - - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - MetaManager.reset(); - - icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oInternal data reseted."))); - - //PacketDispatcher.sendPacketToAllPlayers(NetDataCommand.create(Message.CLIENT_CLEAR_SELECTION)); - if (icommandsender instanceof EntityPlayerMP) - PacketManager.validateAndSend(new NetDataCommand(Message.CLIENT_CLEAR_SELECTION), (EntityPlayerMP)icommandsender); - } - - @Override - public int getRequiredPermissionLevel() - { - return 3; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - if (sender instanceof EntityPlayerMP) - return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP)sender); - - if (sender instanceof DedicatedServer) return true; - if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; - - return false; + @Override + public String getCommandName() { + return "opis_reset"; } - @Override - public String getDescription() { - return "Cleans up all profiling data."; - } + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + MetaManager.reset(); + + icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oInternal data reseted."))); + + // PacketDispatcher.sendPacketToAllPlayers(NetDataCommand.create(Message.CLIENT_CLEAR_SELECTION)); + if (icommandsender instanceof EntityPlayerMP) + PacketManager.validateAndSend( + new NetDataCommand(Message.CLIENT_CLEAR_SELECTION), (EntityPlayerMP) icommandsender); + } + + @Override + public int getRequiredPermissionLevel() { + return 3; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + if (sender instanceof EntityPlayerMP) return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP) sender); + + if (sender instanceof DedicatedServer) return true; + if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; + + return false; + } + + @Override + public String getDescription() { + return "Cleans up all profiling data."; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandRmPrivileged.java b/src/main/java/mcp/mobius/opis/commands/server/CommandRmPrivileged.java index 60752ef..309786b 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandRmPrivileged.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandRmPrivileged.java @@ -8,53 +8,52 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; -public class CommandRmPrivileged extends CommandBase implements IOpisCommand{ +public class CommandRmPrivileged extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_rmpriv"; - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (PlayerTracker.INSTANCE.isInPrivilegedList(astring[0])){ - PlayerTracker.INSTANCE.rmPrivilegedPlayer(astring[0]); - icommandsender.addChatMessage(new ChatComponentText(String.format("Player %s removed from Opis user list.", astring[0]))); - } else { - icommandsender.addChatMessage(new ChatComponentText(String.format("Player %s not found in list.", astring[0]))); - } - } - - @Override - public int getRequiredPermissionLevel() - { - return 3; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - if (sender instanceof EntityPlayerMP) - return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP)sender); - - if (sender instanceof DedicatedServer) return true; - if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; - - return false; + @Override + public String getCommandName() { + return "opis_rmpriv"; } - - @Override - public String getDescription() { - return "Remove a user from the privileged list of users."; - } - @Override - public String getCommandNameOpis() { - return "opis_rmpriv"; - } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (PlayerTracker.INSTANCE.isInPrivilegedList(astring[0])) { + PlayerTracker.INSTANCE.rmPrivilegedPlayer(astring[0]); + icommandsender.addChatMessage( + new ChatComponentText(String.format("Player %s removed from Opis user list.", astring[0]))); + } else { + icommandsender.addChatMessage( + new ChatComponentText(String.format("Player %s not found in list.", astring[0]))); + } + } + + @Override + public int getRequiredPermissionLevel() { + return 3; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + if (sender instanceof EntityPlayerMP) return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP) sender); + + if (sender instanceof DedicatedServer) return true; + if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; + + return false; + } + + @Override + public String getDescription() { + return "Remove a user from the privileged list of users."; + } + + @Override + public String getCommandNameOpis() { + return "opis_rmpriv"; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandStart.java b/src/main/java/mcp/mobius/opis/commands/server/CommandStart.java index 0a5e234..a3fa53e 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandStart.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandStart.java @@ -1,75 +1,65 @@ package mcp.mobius.opis.commands.server; import cpw.mods.fml.relauncher.Side; -import mcp.mobius.opis.modOpis; +import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.commands.IOpisCommand; import mcp.mobius.opis.data.holders.basetypes.SerialInt; -import mcp.mobius.opis.data.managers.EntityManager; import mcp.mobius.opis.data.managers.MetaManager; -import mcp.mobius.opis.data.managers.TileEntityManager; -import mcp.mobius.opis.events.OpisServerTickHandler; -import mcp.mobius.opis.events.PlayerTracker; +import mcp.mobius.opis.modOpis; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.server.NetDataValue; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; -import mcp.mobius.mobiuscore.profiler.ProfilerSection; public class CommandStart extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_start"; - } - - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (icommandsender instanceof EntityPlayerMP){ - icommandsender.addChatMessage(new ChatComponentText("DEPRECATED ! Please run /opis instead.")); - return; - } - - MetaManager.reset(); - modOpis.profilerRun = true; - ProfilerSection.activateAll(Side.SERVER); - - PacketManager.sendPacketToAllSwing(new NetDataValue(Message.STATUS_START, new SerialInt(modOpis.profilerMaxTicks))); - icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oOpis started with a tick delay %s.", modOpis.profilerDelay))); - - - } - - @Override - public int getRequiredPermissionLevel() - { - return 0; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - return true; + @Override + public String getCommandName() { + return "opis_start"; } - @Override - public String getDescription() { - return "Starts a run."; - } - + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } + + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (icommandsender instanceof EntityPlayerMP) { + icommandsender.addChatMessage(new ChatComponentText("DEPRECATED ! Please run /opis instead.")); + return; + } + + MetaManager.reset(); + modOpis.profilerRun = true; + ProfilerSection.activateAll(Side.SERVER); + + PacketManager.sendPacketToAllSwing( + new NetDataValue(Message.STATUS_START, new SerialInt(modOpis.profilerMaxTicks))); + icommandsender.addChatMessage(new ChatComponentText( + String.format("\u00A7oOpis started with a tick delay %s.", modOpis.profilerDelay))); + } + + @Override + public int getRequiredPermissionLevel() { + return 0; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return true; + } + + @Override + public String getDescription() { + return "Starts a run."; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandStop.java b/src/main/java/mcp/mobius/opis/commands/server/CommandStop.java index 92c72de..d8f5e0f 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandStop.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandStop.java @@ -1,64 +1,57 @@ package mcp.mobius.opis.commands.server; import cpw.mods.fml.relauncher.Side; -import mcp.mobius.opis.modOpis; +import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.commands.IOpisCommand; -import mcp.mobius.opis.events.OpisServerTickHandler; import mcp.mobius.opis.events.PlayerTracker; +import mcp.mobius.opis.modOpis; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; -import mcp.mobius.mobiuscore.profiler.ProfilerSection; public class CommandStop extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_stop"; - } - - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - modOpis.profilerRun = false; - ProfilerSection.desactivateAll(Side.SERVER); - icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oOpis stopped."))); - } - - @Override - public int getRequiredPermissionLevel() - { - return 3; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - if (sender instanceof EntityPlayerMP) - return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP)sender); - - if (sender instanceof DedicatedServer) return true; - if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; - - return false; + @Override + public String getCommandName() { + return "opis_stop"; } - @Override - public String getDescription() { - return "Ends a run before completion."; - } - + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } + + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + modOpis.profilerRun = false; + ProfilerSection.desactivateAll(Side.SERVER); + icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oOpis stopped."))); + } + + @Override + public int getRequiredPermissionLevel() { + return 3; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + if (sender instanceof EntityPlayerMP) return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP) sender); + + if (sender instanceof DedicatedServer) return true; + if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; + + return false; + } + + @Override + public String getDescription() { + return "Ends a run before completion."; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandTicks.java b/src/main/java/mcp/mobius/opis/commands/server/CommandTicks.java index d231f62..1b6c7e8 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandTicks.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandTicks.java @@ -1,64 +1,60 @@ package mcp.mobius.opis.commands.server; -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.commands.IOpisCommand; import mcp.mobius.opis.events.PlayerTracker; +import mcp.mobius.opis.modOpis; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; public class CommandTicks extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_ticks"; - } - - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (astring.length < 1) return; - try{ - modOpis.profilerMaxTicks = Integer.valueOf(astring[0]); - icommandsender.addChatMessage(new ChatComponentText(String.format("\u00A7oOpis ticks set to %s ticks.", astring[0]))); - - } catch (Exception e){} - } - - @Override - public int getRequiredPermissionLevel() - { - return 3; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - if (sender instanceof EntityPlayerMP) - return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP)sender); - - if (sender instanceof DedicatedServer) return true; - if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; - - return false; + @Override + public String getCommandName() { + return "opis_ticks"; } - @Override - public String getDescription() { - return "Sets the amount of data points to gather."; - } - + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } + + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (astring.length < 1) return; + try { + modOpis.profilerMaxTicks = Integer.valueOf(astring[0]); + icommandsender.addChatMessage( + new ChatComponentText(String.format("\u00A7oOpis ticks set to %s ticks.", astring[0]))); + + } catch (Exception e) { + } + } + + @Override + public int getRequiredPermissionLevel() { + return 3; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + if (sender instanceof EntityPlayerMP) return PlayerTracker.INSTANCE.isPrivileged((EntityPlayerMP) sender); + + if (sender instanceof DedicatedServer) return true; + if (!(sender instanceof DedicatedServer) && !(sender instanceof EntityPlayerMP)) return true; + + return false; + } + + @Override + public String getDescription() { + return "Sets the amount of data points to gather."; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandTimingEntities.java b/src/main/java/mcp/mobius/opis/commands/server/CommandTimingEntities.java index b4541af..aa324cc 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandTimingEntities.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandTimingEntities.java @@ -1,79 +1,67 @@ package mcp.mobius.opis.commands.server; import java.util.ArrayList; -import java.util.HashMap; - import mcp.mobius.opis.commands.IOpisCommand; -import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; import mcp.mobius.opis.data.holders.newtypes.DataEntity; import mcp.mobius.opis.data.managers.EntityManager; -import mcp.mobius.opis.events.PlayerTracker; -import mcp.mobius.opis.network.enums.Message; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; public class CommandTimingEntities extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_ent"; - } - - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (icommandsender instanceof EntityPlayerMP){ - icommandsender.addChatMessage(new ChatComponentText("DEPRECATED ! Please run /opis instead.")); - return; - } - - ArrayList ents = new ArrayList(); - if (astring.length == 0){ - ents = EntityManager.INSTANCE.getWorses(20); - } - else{ - try{ - ents = EntityManager.INSTANCE.getWorses(Integer.valueOf(astring[0])); - } catch (Exception e) {return;} - } - - icommandsender.addChatMessage(new ChatComponentText("[DIM X Z] Time NTEs")); - for (DataEntity stat : ents){ - icommandsender.addChatMessage(new ChatComponentText(stat.toString())); - } - - - } - - @Override - public int getRequiredPermissionLevel() - { - return 0; - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - return true; + @Override + public String getCommandName() { + return "opis_ent"; } - @Override - public String getDescription() { - return "Returns the 20 longest entities to update."; - } + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } + + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (icommandsender instanceof EntityPlayerMP) { + icommandsender.addChatMessage(new ChatComponentText("DEPRECATED ! Please run /opis instead.")); + return; + } + + ArrayList ents = new ArrayList(); + if (astring.length == 0) { + ents = EntityManager.INSTANCE.getWorses(20); + } else { + try { + ents = EntityManager.INSTANCE.getWorses(Integer.valueOf(astring[0])); + } catch (Exception e) { + return; + } + } + + icommandsender.addChatMessage(new ChatComponentText("[DIM X Z] Time NTEs")); + for (DataEntity stat : ents) { + icommandsender.addChatMessage(new ChatComponentText(stat.toString())); + } + } + + @Override + public int getRequiredPermissionLevel() { + return 0; + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return true; + } + + @Override + public String getDescription() { + return "Returns the 20 longest entities to update."; + } } diff --git a/src/main/java/mcp/mobius/opis/commands/server/CommandTimingTileEntities.java b/src/main/java/mcp/mobius/opis/commands/server/CommandTimingTileEntities.java index 0dfeaa7..623c502 100644 --- a/src/main/java/mcp/mobius/opis/commands/server/CommandTimingTileEntities.java +++ b/src/main/java/mcp/mobius/opis/commands/server/CommandTimingTileEntities.java @@ -1,76 +1,66 @@ package mcp.mobius.opis.commands.server; import java.util.ArrayList; - import mcp.mobius.opis.commands.IOpisCommand; import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; import mcp.mobius.opis.data.managers.TileEntityManager; -import mcp.mobius.opis.events.PlayerTracker; -import mcp.mobius.opis.network.enums.Message; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; public class CommandTimingTileEntities extends CommandBase implements IOpisCommand { - @Override - public String getCommandName() { - return "opis_te"; - } + @Override + public String getCommandName() { + return "opis_te"; + } - @Override - public String getCommandNameOpis() { - return this.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) { - return ""; - } + @Override + public String getCommandNameOpis() { + return this.getCommandName(); + } - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - if (icommandsender instanceof EntityPlayerMP){ - icommandsender.addChatMessage(new ChatComponentText("DEPRECATED ! Please run /opis instead.")); - return; - } - - ArrayList tes = new ArrayList(); - if (astring.length == 0){ - tes = TileEntityManager.INSTANCE.getWorses(20); - } - else{ - try{ - tes = TileEntityManager.INSTANCE.getWorses(Integer.valueOf(astring[0])); - } catch (Exception e) {return;} - } - - for (DataBlockTileEntity stat : tes){ - icommandsender.addChatMessage(new ChatComponentText(stat.toString())); - } - - - } + @Override + public String getCommandUsage(ICommandSender icommandsender) { + return ""; + } - @Override - public int getRequiredPermissionLevel() - { + @Override + public void processCommand(ICommandSender icommandsender, String[] astring) { + if (icommandsender instanceof EntityPlayerMP) { + icommandsender.addChatMessage(new ChatComponentText("DEPRECATED ! Please run /opis instead.")); + return; + } + + ArrayList tes = new ArrayList(); + if (astring.length == 0) { + tes = TileEntityManager.INSTANCE.getWorses(20); + } else { + try { + tes = TileEntityManager.INSTANCE.getWorses(Integer.valueOf(astring[0])); + } catch (Exception e) { + return; + } + } + + for (DataBlockTileEntity stat : tes) { + icommandsender.addChatMessage(new ChatComponentText(stat.toString())); + } + } + + @Override + public int getRequiredPermissionLevel() { return 0; - } + } - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) - { - return true; - } - - @Override - public String getDescription() { - return "Returns the 20 longest TEs to update."; - } - + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return true; + } + + @Override + public String getDescription() { + return "Returns the 20 longest TEs to update."; + } } diff --git a/src/main/java/mcp/mobius/opis/data/client/DataCache.java b/src/main/java/mcp/mobius/opis/data/client/DataCache.java index 47d5542..f610c9a 100644 --- a/src/main/java/mcp/mobius/opis/data/client/DataCache.java +++ b/src/main/java/mcp/mobius/opis/data/client/DataCache.java @@ -1,81 +1,49 @@ package mcp.mobius.opis.data.client; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.image.BufferedImage; -import java.util.ArrayList; -import java.util.HashMap; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JTable; -import javax.swing.table.DefaultTableModel; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; -import org.jfree.chart.ChartFactory; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.axis.NumberAxis; -import org.jfree.chart.plot.PlotOrientation; -import org.jfree.chart.plot.ValueMarker; -import org.jfree.chart.plot.XYPlot; -import org.jfree.data.category.DefaultCategoryDataset; -import org.jfree.data.xy.DefaultTableXYDataset; -import org.jfree.data.xy.DefaultXYDataset; -import org.jfree.data.xy.XYBarDataset; -import org.jfree.data.xy.XYDataset; -import org.jfree.data.xy.XYSeries; -import org.jfree.data.xy.XYSeriesCollection; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.MathHelper; import mcp.mobius.opis.api.IMessageHandler; -import mcp.mobius.opis.data.holders.ISerializable; -import mcp.mobius.opis.data.holders.basetypes.AmountHolder; import mcp.mobius.opis.data.holders.basetypes.SerialInt; import mcp.mobius.opis.data.holders.basetypes.SerialLong; -import mcp.mobius.opis.data.holders.stats.StatAbstract; -import mcp.mobius.opis.data.holders.stats.StatsChunk; -import mcp.mobius.opis.helpers.ModIdentification; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.AccessLevel; import mcp.mobius.opis.network.enums.Message; -import mcp.mobius.opis.swing.SwingUI; -import mcp.mobius.opis.swing.widgets.JButtonAccess; -public class DataCache implements IMessageHandler{ +public class DataCache implements IMessageHandler { - private static DataCache _instance = new DataCache(); - public static DataCache instance() { return _instance; }; - - private long clockScrew = 0; - private AccessLevel clientAccess = AccessLevel.NONE; - - public AccessLevel getAccessLevel(){ - return this.clientAccess; - } - - public long getClockScrew(){ - return this.clockScrew; - } + private static DataCache _instance = new DataCache(); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case STATUS_ACCESS_LEVEL:{ - this.clientAccess = AccessLevel.values()[((SerialInt)rawdata.value).value]; - break; - } - - case STATUS_CURRENT_TIME:{ - this.clockScrew = System.currentTimeMillis() - ((SerialLong)rawdata.value).value; - System.out.printf("Adjusting clock screw. Server differential is %d ms.\n", clockScrew); - break; - } - - default: - return false; - - } - return true; - } + public static DataCache instance() { + return _instance; + } + ; + + private long clockScrew = 0; + private AccessLevel clientAccess = AccessLevel.NONE; + + public AccessLevel getAccessLevel() { + return this.clientAccess; + } + + public long getClockScrew() { + return this.clockScrew; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case STATUS_ACCESS_LEVEL: { + this.clientAccess = AccessLevel.values()[((SerialInt) rawdata.value).value]; + break; + } + + case STATUS_CURRENT_TIME: { + this.clockScrew = System.currentTimeMillis() - ((SerialLong) rawdata.value).value; + System.out.printf("Adjusting clock screw. Server differential is %d ms.\n", clockScrew); + break; + } + + default: + return false; + } + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/DataType.java b/src/main/java/mcp/mobius/opis/data/holders/DataType.java index 5634267..291fbba 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/DataType.java +++ b/src/main/java/mcp/mobius/opis/data/holders/DataType.java @@ -1,6 +1,6 @@ package mcp.mobius.opis.data.holders; -import mcp.mobius.opis.modOpis; +import com.google.common.collect.HashBiMap; import mcp.mobius.opis.data.holders.basetypes.AmountHolder; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; @@ -11,27 +11,27 @@ import mcp.mobius.opis.data.holders.basetypes.SerialLong; import mcp.mobius.opis.data.holders.basetypes.SerialString; import mcp.mobius.opis.data.holders.basetypes.TargetEntity; import mcp.mobius.opis.data.holders.basetypes.TicketData; +import mcp.mobius.opis.data.holders.clienttypes.DataBlockRender; +import mcp.mobius.opis.data.holders.clienttypes.DataEntityRender; import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.ChatMsg; import mcp.mobius.opis.data.holders.newtypes.ConnectionProperties; import mcp.mobius.opis.data.holders.newtypes.DataAmountRate; +import mcp.mobius.opis.data.holders.newtypes.DataBlockTick; +import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntityPerClass; import mcp.mobius.opis.data.holders.newtypes.DataByteRate; import mcp.mobius.opis.data.holders.newtypes.DataByteSize; -import mcp.mobius.opis.data.holders.clienttypes.DataBlockRender; -import mcp.mobius.opis.data.holders.newtypes.DataBlockTick; import mcp.mobius.opis.data.holders.newtypes.DataChunk; import mcp.mobius.opis.data.holders.newtypes.DataChunkEntities; import mcp.mobius.opis.data.holders.newtypes.DataDimension; import mcp.mobius.opis.data.holders.newtypes.DataEntity; import mcp.mobius.opis.data.holders.newtypes.DataEntityPerClass; -import mcp.mobius.opis.data.holders.clienttypes.DataEntityRender; import mcp.mobius.opis.data.holders.newtypes.DataEvent; import mcp.mobius.opis.data.holders.newtypes.DataNetworkTick; import mcp.mobius.opis.data.holders.newtypes.DataPacket; import mcp.mobius.opis.data.holders.newtypes.DataPacket250; import mcp.mobius.opis.data.holders.newtypes.DataStringUpdate; -import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; import mcp.mobius.opis.data.holders.newtypes.DataThread; import mcp.mobius.opis.data.holders.newtypes.DataTileEntity; import mcp.mobius.opis.data.holders.newtypes.DataTileEntityRender; @@ -42,86 +42,83 @@ import mcp.mobius.opis.data.holders.newtypes.NexusData; import mcp.mobius.opis.data.holders.newtypes.PlayerStatus; import mcp.mobius.opis.data.holders.stats.StatAbstract; import mcp.mobius.opis.data.holders.stats.StatsChunk; - -import com.google.common.collect.HashBiMap; +import mcp.mobius.opis.modOpis; public enum DataType { - AMOUNTHOLDER (AmountHolder.class), - COORDINATESBLOCK(CoordinatesBlock.class), - COORDINATESCHUNK(CoordinatesChunk.class), - SERIALDOUBLE (SerialDouble.class), - SERIALFLOAT (SerialFloat.class), - SERIALINT (SerialInt.class), - SERIALLONG (SerialLong.class), - SERIALSTRING (SerialString.class), - TARGETENTITY (TargetEntity.class), - TICKETDATA (TicketData.class), - - CACHEDSTRING (CachedString.class), - DATAAMOUNTRATE (DataAmountRate.class), - DATABITRATE (DataByteRate.class), - DATABITSIZE (DataByteSize.class), - DATABLOCKRENDER (DataBlockRender.class), - DATABLOCKTICK (DataBlockTick.class), - DATABLOCKTILEENTITY (DataBlockTileEntity.class), - DATABLOCKTILEENTITYPERCLASS (DataBlockTileEntityPerClass.class), - DATACHUNK (DataChunk.class), - DATACHUNKENTITIES (DataChunkEntities.class), - DATADIMENSION (DataDimension.class), - DATAENTITY (DataEntity.class), - DATAENTITYPERCLASS (DataEntityPerClass.class), - DATAENTITYRENDER (DataEntityRender.class), - DATAEVENT (DataEvent.class), - DATANETWORKTICK (DataNetworkTick.class), - DATAPACKET (DataPacket.class), - DATAPACKET250 (DataPacket250.class), - DATASTRINGUPD (DataStringUpdate.class), - DATATHREAD (DataThread.class), - DATATILEENTITY (DataTileEntity.class), - DATATILEENTITYRENDER (DataTileEntityRender.class), - DATATIMING (DataTiming.class), - DATATIMINGMILLISECOND (DataTimingMillisecond.class), - STATABSTRACT (StatAbstract.class), - STATSCHUNK (StatsChunk.class), - NEXUSDATA (NexusData.class), - NEXUSAUTH (NexusAuth.class), - PLAYERLOGGING (PlayerStatus.class), - CONNECTIONPROPERTIES (ConnectionProperties.class), - CHATMSG (ChatMsg.class); - - private Class clazz; - private static HashBiMap bimap = HashBiMap.create(50); - - static - { - for (DataType type : DataType.values()) - bimap.put(type, type.clazz); - } - - private DataType(Class clazz){ - this.clazz = clazz; - } - - public static DataType getForClass(Class clazz){ - DataType type = bimap.inverse().get(clazz); - if (type == null){ - modOpis.log.warn(String.format("Class %s was not registered with the DataType enum", clazz)); - } - return type; - } - - public static Class getForOrdinal(int ordinal){ - Class retVal; - try{ - DataType type = DataType.values()[ordinal]; - retVal = bimap.get(type); - if (retVal == null){ - modOpis.log.warn(String.format("DataType doesn't have a class registered for %s", type)); - } - } catch (Exception e) { - retVal = null; - modOpis.log.warn(String.format("Index out of bound for ordinal %d in DataType", ordinal)); - } - return retVal; - } + AMOUNTHOLDER(AmountHolder.class), + COORDINATESBLOCK(CoordinatesBlock.class), + COORDINATESCHUNK(CoordinatesChunk.class), + SERIALDOUBLE(SerialDouble.class), + SERIALFLOAT(SerialFloat.class), + SERIALINT(SerialInt.class), + SERIALLONG(SerialLong.class), + SERIALSTRING(SerialString.class), + TARGETENTITY(TargetEntity.class), + TICKETDATA(TicketData.class), + + CACHEDSTRING(CachedString.class), + DATAAMOUNTRATE(DataAmountRate.class), + DATABITRATE(DataByteRate.class), + DATABITSIZE(DataByteSize.class), + DATABLOCKRENDER(DataBlockRender.class), + DATABLOCKTICK(DataBlockTick.class), + DATABLOCKTILEENTITY(DataBlockTileEntity.class), + DATABLOCKTILEENTITYPERCLASS(DataBlockTileEntityPerClass.class), + DATACHUNK(DataChunk.class), + DATACHUNKENTITIES(DataChunkEntities.class), + DATADIMENSION(DataDimension.class), + DATAENTITY(DataEntity.class), + DATAENTITYPERCLASS(DataEntityPerClass.class), + DATAENTITYRENDER(DataEntityRender.class), + DATAEVENT(DataEvent.class), + DATANETWORKTICK(DataNetworkTick.class), + DATAPACKET(DataPacket.class), + DATAPACKET250(DataPacket250.class), + DATASTRINGUPD(DataStringUpdate.class), + DATATHREAD(DataThread.class), + DATATILEENTITY(DataTileEntity.class), + DATATILEENTITYRENDER(DataTileEntityRender.class), + DATATIMING(DataTiming.class), + DATATIMINGMILLISECOND(DataTimingMillisecond.class), + STATABSTRACT(StatAbstract.class), + STATSCHUNK(StatsChunk.class), + NEXUSDATA(NexusData.class), + NEXUSAUTH(NexusAuth.class), + PLAYERLOGGING(PlayerStatus.class), + CONNECTIONPROPERTIES(ConnectionProperties.class), + CHATMSG(ChatMsg.class); + + private Class clazz; + private static HashBiMap bimap = HashBiMap.create(50); + + static { + for (DataType type : DataType.values()) bimap.put(type, type.clazz); + } + + private DataType(Class clazz) { + this.clazz = clazz; + } + + public static DataType getForClass(Class clazz) { + DataType type = bimap.inverse().get(clazz); + if (type == null) { + modOpis.log.warn(String.format("Class %s was not registered with the DataType enum", clazz)); + } + return type; + } + + public static Class getForOrdinal(int ordinal) { + Class retVal; + try { + DataType type = DataType.values()[ordinal]; + retVal = bimap.get(type); + if (retVal == null) { + modOpis.log.warn(String.format("DataType doesn't have a class registered for %s", type)); + } + } catch (Exception e) { + retVal = null; + modOpis.log.warn(String.format("Index out of bound for ordinal %d in DataType", ordinal)); + } + return retVal; + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/ISerializable.java b/src/main/java/mcp/mobius/opis/data/holders/ISerializable.java index 7779cb9..17ed644 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/ISerializable.java +++ b/src/main/java/mcp/mobius/opis/data/holders/ISerializable.java @@ -1,14 +1,8 @@ package mcp.mobius.opis.data.holders; -import io.netty.buffer.ByteBuf; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataOutput; public interface ISerializable { - void writeToStream(ByteArrayDataOutput stream); - //Object readFromStream(DataInputStream stream) throws IOException; + void writeToStream(ByteArrayDataOutput stream); + // Object readFromStream(DataInputStream stream) throws IOException; } diff --git a/src/main/java/mcp/mobius/opis/data/holders/basetypes/AmountHolder.java b/src/main/java/mcp/mobius/opis/data/holders/basetypes/AmountHolder.java index c21b387..6aa0ce8 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/basetypes/AmountHolder.java +++ b/src/main/java/mcp/mobius/opis/data/holders/basetypes/AmountHolder.java @@ -1,42 +1,37 @@ package mcp.mobius.opis.data.holders.basetypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.newtypes.CachedString; -import mcp.mobius.opis.network.PacketManager; public class AmountHolder implements ISerializable { - public CachedString key = null; - public Integer value = 0; - public CachedString data = null; - - public AmountHolder(String key, Integer value, String data){ - this.key = new CachedString(key); - this.value = value; - this.data = new CachedString(data); - } + public CachedString key = null; + public Integer value = 0; + public CachedString data = null; - public AmountHolder(CachedString key, Integer value, CachedString data){ - this.key = key; - this.value = value; - this.data = data; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - this.key.writeToStream(stream); - stream.writeInt(this.value); - this.data.writeToStream(stream); - } + public AmountHolder(String key, Integer value, String data) { + this.key = new CachedString(key); + this.value = value; + this.data = new CachedString(data); + } - public static AmountHolder readFromStream(ByteArrayDataInput istream){ - return new AmountHolder(CachedString.readFromStream(istream), istream.readInt(), CachedString.readFromStream(istream)); - } + public AmountHolder(CachedString key, Integer value, CachedString data) { + this.key = key; + this.value = value; + this.data = data; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.key.writeToStream(stream); + stream.writeInt(this.value); + this.data.writeToStream(stream); + } + + public static AmountHolder readFromStream(ByteArrayDataInput istream) { + return new AmountHolder( + CachedString.readFromStream(istream), istream.readInt(), CachedString.readFromStream(istream)); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/basetypes/CoordinatesBlock.java b/src/main/java/mcp/mobius/opis/data/holders/basetypes/CoordinatesBlock.java index 2960dae..280b1e8 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/basetypes/CoordinatesBlock.java +++ b/src/main/java/mcp/mobius/opis/data/holders/basetypes/CoordinatesBlock.java @@ -1,128 +1,123 @@ package mcp.mobius.opis.data.holders.basetypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; import net.minecraft.entity.Entity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; public final class CoordinatesBlock implements ISerializable { - public final int dim, x, y, z; - public final int chunkX, chunkZ; - //public boolean isChunk; - - public final static CoordinatesBlock INVALID = new CoordinatesBlock(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); - - public CoordinatesBlock(Entity entity){ - this.dim = entity.worldObj.provider.dimensionId; - this.x = MathHelper.floor_double(entity.posX); - this.y = MathHelper.floor_double(entity.posY); - this.z = MathHelper.floor_double(entity.posZ); - this.chunkX = x >> 4; - this.chunkZ = z >> 4; - //this.isChunk = false; - } - - public CoordinatesBlock(int dim, int x, int y, int z){ - this.dim = dim; - this.x = x; - this.y = y; - this.z = z; - this.chunkX = x >> 4; - this.chunkZ = z >> 4; - //this.isChunk = false; - } + public final int dim, x, y, z; + public final int chunkX, chunkZ; + // public boolean isChunk; - public CoordinatesBlock(int dim, double x, double y, double z){ - this.dim = dim; - this.x = MathHelper.floor_double(x); - this.y = MathHelper.floor_double(y); - this.z = MathHelper.floor_double(z); - this.chunkX = MathHelper.floor_double(x) >> 4; - this.chunkZ = MathHelper.floor_double(z) >> 4; - //this.isChunk = false; - } - - public CoordinatesBlock(CoordinatesChunk coord){ - this.dim = coord.dim; - this.chunkX = coord.chunkX; - this.chunkZ = coord.chunkZ; - - this.x = coord.x; - this.y = coord.y; - this.z = coord.z; - } - - /* - public CoordinatesBlock(int dim, int chunkX, int chunkZ){ - this.dim = dim; - this.chunkX = chunkX; - this.chunkZ = chunkZ; - this.x = chunkX << 4; - this.y = 0; - this.z = chunkZ << 4; - this.isChunk = true; - } - */ - - public CoordinatesBlock(TileEntity te){ - this.dim = te.getWorldObj().provider.dimensionId; - this.x = te.xCoord; - this.y = te.yCoord; - this.z = te.zCoord; - this.chunkX = x >> 4; - this.chunkZ = z >> 4; - //this.isChunk = false; - } - - public CoordinatesChunk asCoordinatesChunk(){ - return new CoordinatesChunk(this); - } - - public String toString(){ - //if (this.isChunk) - // return String.format("[%6d %6d %6d]", this.dim, this.chunkX, this.chunkZ); - //else - return String.format("[%6d %6d %6d %6d]", this.dim, this.x, this.y, this.z); - } - - public boolean equals(Object o) { - CoordinatesBlock c = (CoordinatesBlock)o; - //if (this.isChunk) - // return (this.dim == c.dim) && (this.chunkX == c.chunkX) && (this.chunkZ == c.chunkZ); - //else - return (this.dim == c.dim) && (this.x == c.x) && (this.y == c.y) && (this.z == c.z); - }; - - public boolean isInvalid(){ - return this.equals(CoordinatesBlock.INVALID); - } - - public int hashCode() { - //if (this.isChunk) - // return String.format("%s %s %s", this.dim, this.chunkX, this.chunkZ).hashCode(); - //else - // return String.format("%s %s %s %s", this.dim, this.x, this.y, this.z).hashCode(); - return this.dim + 31 * this.x + 877 * this.y + 3187 * this.z; - } + public static final CoordinatesBlock INVALID = + new CoordinatesBlock(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeInt(this.dim); - stream.writeInt(this.x); - stream.writeInt(this.y); - stream.writeInt(this.z); - } + public CoordinatesBlock(Entity entity) { + this.dim = entity.worldObj.provider.dimensionId; + this.x = MathHelper.floor_double(entity.posX); + this.y = MathHelper.floor_double(entity.posY); + this.z = MathHelper.floor_double(entity.posZ); + this.chunkX = x >> 4; + this.chunkZ = z >> 4; + // this.isChunk = false; + } - public static CoordinatesBlock readFromStream(ByteArrayDataInput stream){ - return new CoordinatesBlock(stream.readInt(), stream.readInt(), stream.readInt(), stream.readInt()); - } - - + public CoordinatesBlock(int dim, int x, int y, int z) { + this.dim = dim; + this.x = x; + this.y = y; + this.z = z; + this.chunkX = x >> 4; + this.chunkZ = z >> 4; + // this.isChunk = false; + } + + public CoordinatesBlock(int dim, double x, double y, double z) { + this.dim = dim; + this.x = MathHelper.floor_double(x); + this.y = MathHelper.floor_double(y); + this.z = MathHelper.floor_double(z); + this.chunkX = MathHelper.floor_double(x) >> 4; + this.chunkZ = MathHelper.floor_double(z) >> 4; + // this.isChunk = false; + } + + public CoordinatesBlock(CoordinatesChunk coord) { + this.dim = coord.dim; + this.chunkX = coord.chunkX; + this.chunkZ = coord.chunkZ; + + this.x = coord.x; + this.y = coord.y; + this.z = coord.z; + } + + /* + public CoordinatesBlock(int dim, int chunkX, int chunkZ){ + this.dim = dim; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + this.x = chunkX << 4; + this.y = 0; + this.z = chunkZ << 4; + this.isChunk = true; + } + */ + + public CoordinatesBlock(TileEntity te) { + this.dim = te.getWorldObj().provider.dimensionId; + this.x = te.xCoord; + this.y = te.yCoord; + this.z = te.zCoord; + this.chunkX = x >> 4; + this.chunkZ = z >> 4; + // this.isChunk = false; + } + + public CoordinatesChunk asCoordinatesChunk() { + return new CoordinatesChunk(this); + } + + public String toString() { + // if (this.isChunk) + // return String.format("[%6d %6d %6d]", this.dim, this.chunkX, this.chunkZ); + // else + return String.format("[%6d %6d %6d %6d]", this.dim, this.x, this.y, this.z); + } + + public boolean equals(Object o) { + CoordinatesBlock c = (CoordinatesBlock) o; + // if (this.isChunk) + // return (this.dim == c.dim) && (this.chunkX == c.chunkX) && (this.chunkZ == c.chunkZ); + // else + return (this.dim == c.dim) && (this.x == c.x) && (this.y == c.y) && (this.z == c.z); + } + ; + + public boolean isInvalid() { + return this.equals(CoordinatesBlock.INVALID); + } + + public int hashCode() { + // if (this.isChunk) + // return String.format("%s %s %s", this.dim, this.chunkX, this.chunkZ).hashCode(); + // else + // return String.format("%s %s %s %s", this.dim, this.x, this.y, this.z).hashCode(); + return this.dim + 31 * this.x + 877 * this.y + 3187 * this.z; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeInt(this.dim); + stream.writeInt(this.x); + stream.writeInt(this.y); + stream.writeInt(this.z); + } + + public static CoordinatesBlock readFromStream(ByteArrayDataInput stream) { + return new CoordinatesBlock(stream.readInt(), stream.readInt(), stream.readInt(), stream.readInt()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/basetypes/CoordinatesChunk.java b/src/main/java/mcp/mobius/opis/data/holders/basetypes/CoordinatesChunk.java index 10421ca..a7cadea 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/basetypes/CoordinatesChunk.java +++ b/src/main/java/mcp/mobius/opis/data/holders/basetypes/CoordinatesChunk.java @@ -1,136 +1,130 @@ package mcp.mobius.opis.data.holders.basetypes; -import io.netty.buffer.ByteBuf; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.ChunkCoordIntPair; public final class CoordinatesChunk implements ISerializable { - public final int dim, x, y, z; - public final int chunkX, chunkZ; - public final byte metadata; - //public boolean isChunk; - - public final static CoordinatesChunk INVALID = new CoordinatesChunk(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); - - public CoordinatesChunk(CoordinatesBlock coord){ - this.dim = coord.dim; - this.chunkX = coord.chunkX; - this.chunkZ = coord.chunkZ; - - this.x = chunkX << 4; - this.y = 0; - this.z = chunkZ << 4; - - this.metadata = 0; - } - - public CoordinatesChunk(int dim, int chunkX, int chunkZ){ - this.dim = dim; - this.chunkX = chunkX; - this.chunkZ = chunkZ; - - this.x = chunkX << 4; - this.y = 0; - this.z = chunkZ << 4; - - this.metadata = 0; - } - - public CoordinatesChunk(int dim, int chunkX, int chunkZ, byte metadata){ - this.dim = dim; - this.chunkX = chunkX; - this.chunkZ = chunkZ; - - this.x = chunkX << 4; - this.y = 0; - this.z = chunkZ << 4; - - this.metadata = metadata; - } - - public CoordinatesChunk(int dim, ChunkCoordIntPair coord){ - this.dim = dim; - this.chunkX = coord.chunkXPos; - this.chunkZ = coord.chunkZPos; - - this.x = chunkX << 4; - this.y = 0; - this.z = chunkZ << 4; - - this.metadata = 0; - } + public final int dim, x, y, z; + public final int chunkX, chunkZ; + public final byte metadata; + // public boolean isChunk; - public CoordinatesChunk(int dim, ChunkCoordIntPair coord, byte metadata){ - this.dim = dim; - this.chunkX = coord.chunkXPos; - this.chunkZ = coord.chunkZPos; - - this.x = chunkX << 4; - this.y = 0; - this.z = chunkZ << 4; - - this.metadata = metadata; - } - - public CoordinatesChunk(TileEntity te){ - this.dim = te.getWorldObj().provider.dimensionId; - this.chunkX = te.xCoord >> 4; - this.chunkZ = te.zCoord >> 4; - - this.x = this.chunkX << 4; - this.y = 0; - this.z = this.chunkZ << 4; - - this.metadata = 0; - } - - public boolean isInvalid(){ - return this.equals(CoordinatesChunk.INVALID); - } - - public String toString(){ - return String.format("[%6d %6d %6d]", this.dim, this.chunkX, this.chunkZ); - } - - public boolean equals(Object o) { - CoordinatesChunk c = (CoordinatesChunk)o; - return (this.dim == c.dim) && (this.chunkX == c.chunkX) && (this.chunkZ == c.chunkZ); - } - - //00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 - //11111111 11111111 11111111 11122222 22222222 22222222 22222200 00000000 - - public int hashCode() { - //return String.format("%s %s %s", this.dim, this.chunkX, this.chunkZ).hashCode(); - return this.dim + 31 * this.chunkX + 877 * this.chunkZ; - } + public static final CoordinatesChunk INVALID = + new CoordinatesChunk(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); - public ChunkCoordIntPair toChunkCoordIntPair(){ - return new ChunkCoordIntPair(this.chunkX, this.chunkZ); - } - - public CoordinatesBlock asCoordinatesBlock(){ - return new CoordinatesBlock(this); - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeInt(this.dim); - stream.writeInt(this.chunkX); - stream.writeInt(this.chunkZ); - stream.writeByte(this.metadata); - } + public CoordinatesChunk(CoordinatesBlock coord) { + this.dim = coord.dim; + this.chunkX = coord.chunkX; + this.chunkZ = coord.chunkZ; - public static CoordinatesChunk readFromStream(ByteArrayDataInput stream){ - return new CoordinatesChunk(stream.readInt(), stream.readInt(), stream.readInt(), stream.readByte()); - } + this.x = chunkX << 4; + this.y = 0; + this.z = chunkZ << 4; + + this.metadata = 0; + } + + public CoordinatesChunk(int dim, int chunkX, int chunkZ) { + this.dim = dim; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + + this.x = chunkX << 4; + this.y = 0; + this.z = chunkZ << 4; + + this.metadata = 0; + } + + public CoordinatesChunk(int dim, int chunkX, int chunkZ, byte metadata) { + this.dim = dim; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + + this.x = chunkX << 4; + this.y = 0; + this.z = chunkZ << 4; + + this.metadata = metadata; + } + + public CoordinatesChunk(int dim, ChunkCoordIntPair coord) { + this.dim = dim; + this.chunkX = coord.chunkXPos; + this.chunkZ = coord.chunkZPos; + + this.x = chunkX << 4; + this.y = 0; + this.z = chunkZ << 4; + + this.metadata = 0; + } + + public CoordinatesChunk(int dim, ChunkCoordIntPair coord, byte metadata) { + this.dim = dim; + this.chunkX = coord.chunkXPos; + this.chunkZ = coord.chunkZPos; + + this.x = chunkX << 4; + this.y = 0; + this.z = chunkZ << 4; + + this.metadata = metadata; + } + + public CoordinatesChunk(TileEntity te) { + this.dim = te.getWorldObj().provider.dimensionId; + this.chunkX = te.xCoord >> 4; + this.chunkZ = te.zCoord >> 4; + + this.x = this.chunkX << 4; + this.y = 0; + this.z = this.chunkZ << 4; + + this.metadata = 0; + } + + public boolean isInvalid() { + return this.equals(CoordinatesChunk.INVALID); + } + + public String toString() { + return String.format("[%6d %6d %6d]", this.dim, this.chunkX, this.chunkZ); + } + + public boolean equals(Object o) { + CoordinatesChunk c = (CoordinatesChunk) o; + return (this.dim == c.dim) && (this.chunkX == c.chunkX) && (this.chunkZ == c.chunkZ); + } + + // 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 + // 11111111 11111111 11111111 11122222 22222222 22222222 22222200 00000000 + + public int hashCode() { + // return String.format("%s %s %s", this.dim, this.chunkX, this.chunkZ).hashCode(); + return this.dim + 31 * this.chunkX + 877 * this.chunkZ; + } + + public ChunkCoordIntPair toChunkCoordIntPair() { + return new ChunkCoordIntPair(this.chunkX, this.chunkZ); + } + + public CoordinatesBlock asCoordinatesBlock() { + return new CoordinatesBlock(this); + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeInt(this.dim); + stream.writeInt(this.chunkX); + stream.writeInt(this.chunkZ); + stream.writeByte(this.metadata); + } + + public static CoordinatesChunk readFromStream(ByteArrayDataInput stream) { + return new CoordinatesChunk(stream.readInt(), stream.readInt(), stream.readInt(), stream.readByte()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialDouble.java b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialDouble.java index 879c7bd..365c6ea 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialDouble.java +++ b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialDouble.java @@ -1,30 +1,23 @@ package mcp.mobius.opis.data.holders.basetypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; public class SerialDouble implements ISerializable { - public double value = 0; - - public SerialDouble(double value){ - this.value = value; - } - - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeDouble(this.value); - } + public double value = 0; - public static SerialDouble readFromStream(ByteArrayDataInput stream){ - return new SerialDouble(stream.readDouble()); - } - + public SerialDouble(double value) { + this.value = value; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeDouble(this.value); + } + + public static SerialDouble readFromStream(ByteArrayDataInput stream) { + return new SerialDouble(stream.readDouble()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialFloat.java b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialFloat.java index 6013004..374dedf 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialFloat.java +++ b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialFloat.java @@ -1,29 +1,23 @@ package mcp.mobius.opis.data.holders.basetypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; public class SerialFloat implements ISerializable { - public float value = 0; - - public SerialFloat(float value){ - this.value = value; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeFloat(this.value); - } + public float value = 0; - public static SerialFloat readFromStream(ByteArrayDataInput stream){ - return new SerialFloat(stream.readFloat()); - } - + public SerialFloat(float value) { + this.value = value; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeFloat(this.value); + } + + public static SerialFloat readFromStream(ByteArrayDataInput stream) { + return new SerialFloat(stream.readFloat()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialInt.java b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialInt.java index f657291..6534771 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialInt.java +++ b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialInt.java @@ -1,29 +1,23 @@ package mcp.mobius.opis.data.holders.basetypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; public class SerialInt implements ISerializable { - public int value = 0; - - public SerialInt(int value){ - this.value = value; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeInt(this.value); - } + public int value = 0; - public static SerialInt readFromStream(ByteArrayDataInput stream){ - return new SerialInt(stream.readInt()); - } - + public SerialInt(int value) { + this.value = value; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeInt(this.value); + } + + public static SerialInt readFromStream(ByteArrayDataInput stream) { + return new SerialInt(stream.readInt()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialLong.java b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialLong.java index b11874b..f14d366 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialLong.java +++ b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialLong.java @@ -1,29 +1,23 @@ package mcp.mobius.opis.data.holders.basetypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; public class SerialLong implements ISerializable { - public long value = 0; - - public SerialLong(long value){ - this.value = value; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeLong(this.value); - } + public long value = 0; - public static SerialLong readFromStream(ByteArrayDataInput stream){ - return new SerialLong(stream.readLong()); - } - + public SerialLong(long value) { + this.value = value; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeLong(this.value); + } + + public static SerialLong readFromStream(ByteArrayDataInput stream) { + return new SerialLong(stream.readLong()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialNumeral.java b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialNumeral.java index a570f77..803b3ad 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialNumeral.java +++ b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialNumeral.java @@ -5,81 +5,81 @@ import java.io.DataOutputStream; import java.io.IOException; public class SerialNumeral { - private enum Type{ - INTEGER, - LONG, - FLOAT, - DOUBLE, - STRING; - } - - public static final SerialNumeral INTEGER = new SerialNumeral(Type.INTEGER); - public static final SerialNumeral FLOAT = new SerialNumeral(Type.FLOAT); - public static final SerialNumeral LONG = new SerialNumeral(Type.LONG); - public static final SerialNumeral DOUBLE = new SerialNumeral(Type.DOUBLE); - - U value; - Type type; - - public SerialNumeral(Type type){ - this.type = type; - } - - public void setValue(U value){ - this.value = value; - } - - public U getValue(){ - return this.value; - } - - public void writeToSteam(DataOutputStream stream) throws IOException { - stream.writeByte(this.type.ordinal()); - - switch(type){ - case DOUBLE: - stream.writeDouble((Double)this.value); - break; - case FLOAT: - stream.writeFloat((Float)this.value); - break; - case INTEGER: - stream.writeInt((Integer)this.value); - break; - case LONG: - stream.writeLong((Long)this.value); - break; - default: - break; - } - } - - public static SerialNumeral readFromStream(DataInputStream stream) throws IOException { - Type datatype = Type.values()[stream.readByte()]; - switch(datatype){ - case DOUBLE:{ - SerialNumeral retVal = new SerialNumeral(Type.DOUBLE); - retVal.setValue(stream.readDouble()); - return retVal; - } - case FLOAT:{ - SerialNumeral retVal = new SerialNumeral(Type.FLOAT); - retVal.setValue(stream.readFloat()); - return retVal; - } - case INTEGER:{ - SerialNumeral retVal = new SerialNumeral(Type.INTEGER); - retVal.setValue(stream.readInt()); - return retVal; - } - case LONG:{ - SerialNumeral retVal = new SerialNumeral(Type.LONG); - retVal.setValue(stream.readLong()); - return retVal; - } - default: - break; - } - return null; - } + private enum Type { + INTEGER, + LONG, + FLOAT, + DOUBLE, + STRING; + } + + public static final SerialNumeral INTEGER = new SerialNumeral(Type.INTEGER); + public static final SerialNumeral FLOAT = new SerialNumeral(Type.FLOAT); + public static final SerialNumeral LONG = new SerialNumeral(Type.LONG); + public static final SerialNumeral DOUBLE = new SerialNumeral(Type.DOUBLE); + + U value; + Type type; + + public SerialNumeral(Type type) { + this.type = type; + } + + public void setValue(U value) { + this.value = value; + } + + public U getValue() { + return this.value; + } + + public void writeToSteam(DataOutputStream stream) throws IOException { + stream.writeByte(this.type.ordinal()); + + switch (type) { + case DOUBLE: + stream.writeDouble((Double) this.value); + break; + case FLOAT: + stream.writeFloat((Float) this.value); + break; + case INTEGER: + stream.writeInt((Integer) this.value); + break; + case LONG: + stream.writeLong((Long) this.value); + break; + default: + break; + } + } + + public static SerialNumeral readFromStream(DataInputStream stream) throws IOException { + Type datatype = Type.values()[stream.readByte()]; + switch (datatype) { + case DOUBLE: { + SerialNumeral retVal = new SerialNumeral(Type.DOUBLE); + retVal.setValue(stream.readDouble()); + return retVal; + } + case FLOAT: { + SerialNumeral retVal = new SerialNumeral(Type.FLOAT); + retVal.setValue(stream.readFloat()); + return retVal; + } + case INTEGER: { + SerialNumeral retVal = new SerialNumeral(Type.INTEGER); + retVal.setValue(stream.readInt()); + return retVal; + } + case LONG: { + SerialNumeral retVal = new SerialNumeral(Type.LONG); + retVal.setValue(stream.readLong()); + return retVal; + } + default: + break; + } + return null; + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialString.java b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialString.java index 7ebc265..fa98b62 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialString.java +++ b/src/main/java/mcp/mobius/opis/data/holders/basetypes/SerialString.java @@ -1,29 +1,23 @@ package mcp.mobius.opis.data.holders.basetypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; -import mcp.mobius.opis.data.holders.newtypes.CachedString; public class SerialString implements ISerializable { - public String value = ""; - - public SerialString(String value){ - this.value = value; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeUTF(this.value); - } + public String value = ""; - public static SerialString readFromStream(ByteArrayDataInput stream){ - return new SerialString(stream.readUTF()); - } + public SerialString(String value) { + this.value = value; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeUTF(this.value); + } + + public static SerialString readFromStream(ByteArrayDataInput stream) { + return new SerialString(stream.readUTF()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/basetypes/TargetEntity.java b/src/main/java/mcp/mobius/opis/data/holders/basetypes/TargetEntity.java index cf36a06..21f1d6d 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/basetypes/TargetEntity.java +++ b/src/main/java/mcp/mobius/opis/data/holders/basetypes/TargetEntity.java @@ -1,31 +1,26 @@ package mcp.mobius.opis.data.holders.basetypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; public class TargetEntity implements ISerializable { - public int entityID = 0; - public int dim = 0; - - public TargetEntity(int id, int dim){ - this.entityID = id; - this.dim = dim; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeInt(this.entityID); - stream.writeInt(this.dim); - } + public int entityID = 0; + public int dim = 0; - public static TargetEntity readFromStream(ByteArrayDataInput stream){ - return new TargetEntity(stream.readInt(), stream.readInt()); - } + public TargetEntity(int id, int dim) { + this.entityID = id; + this.dim = dim; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeInt(this.entityID); + stream.writeInt(this.dim); + } + + public static TargetEntity readFromStream(ByteArrayDataInput stream) { + return new TargetEntity(stream.readInt(), stream.readInt()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/basetypes/TicketData.java b/src/main/java/mcp/mobius/opis/data/holders/basetypes/TicketData.java index 7c115e3..983d124 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/basetypes/TicketData.java +++ b/src/main/java/mcp/mobius/opis/data/holders/basetypes/TicketData.java @@ -1,80 +1,76 @@ package mcp.mobius.opis.data.holders.basetypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.LinkedHashSet; - import com.google.common.collect.ImmutableSet; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; import net.minecraft.world.ChunkCoordIntPair; import net.minecraftforge.common.ForgeChunkManager.Ticket; -public final class TicketData implements ISerializable{ - public final CoordinatesChunk coord; - public final int nchunks; - public final String modID; - public final Ticket ticket; +public final class TicketData implements ISerializable { + public final CoordinatesChunk coord; + public final int nchunks; + public final String modID; + public final Ticket ticket; - public TicketData(Ticket ticket){ - ImmutableSet requestedChunks = ticket.getChunkList(); - int maxChunkX = -999999, minChunkX = 9999999, maxChunkZ = -999999, minChunkZ = 9999999; - - for (Object obj : requestedChunks){ - ChunkCoordIntPair chunk = (ChunkCoordIntPair)obj; - maxChunkX = Math.max(maxChunkX, chunk.chunkXPos); - minChunkX = Math.min(minChunkX, chunk.chunkXPos); - maxChunkZ = Math.max(maxChunkZ, chunk.chunkZPos); - minChunkZ = Math.min(minChunkZ, chunk.chunkZPos); - } - - this.coord = new CoordinatesChunk(ticket.world.provider.dimensionId, (minChunkX + maxChunkX)/2, (minChunkZ + maxChunkZ)/2); - this.nchunks = requestedChunks.size(); - this.modID = ticket.getModId(); - this.ticket = ticket; - } + public TicketData(Ticket ticket) { + ImmutableSet requestedChunks = ticket.getChunkList(); + int maxChunkX = -999999, minChunkX = 9999999, maxChunkZ = -999999, minChunkZ = 9999999; - public TicketData(CoordinatesChunk coord, int nchunks, String modid){ - this.coord = coord; - this.nchunks = nchunks; - this.modID = modid; - this.ticket = null; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - this.coord.writeToStream(stream); - stream.writeInt(this.nchunks); - stream.writeUTF(this.modID); - } - - public static TicketData readFromStream(ByteArrayDataInput stream){ - return new TicketData(CoordinatesChunk.readFromStream(stream), stream.readInt(), stream.readUTF()); - } - - public boolean equals(Object o) { - TicketData c = (TicketData)o; - - if (this.ticket != null && c.ticket != null) - return this.ticket.equals(c.ticket); - - return (this.coord.dim == c.coord.dim) && - (this.coord.chunkX == c.coord.chunkX) && - (this.coord.chunkZ == c.coord.chunkZ) && - (this.nchunks == c.nchunks); - }; - - public int hashCode() { - if (this.ticket != null) - return this.ticket.hashCode(); - return String.format("%s %s %s %s", this.coord.dim, this.coord.chunkX, this.coord.chunkZ, this.nchunks).hashCode(); - } - - public String toString(){ - return String.format("Ticket %s [%d %d %d] %d", this.modID, this.coord.dim, this.coord.chunkX, this.coord.chunkZ, this.nchunks); - } - + for (Object obj : requestedChunks) { + ChunkCoordIntPair chunk = (ChunkCoordIntPair) obj; + maxChunkX = Math.max(maxChunkX, chunk.chunkXPos); + minChunkX = Math.min(minChunkX, chunk.chunkXPos); + maxChunkZ = Math.max(maxChunkZ, chunk.chunkZPos); + minChunkZ = Math.min(minChunkZ, chunk.chunkZPos); + } + + this.coord = new CoordinatesChunk( + ticket.world.provider.dimensionId, (minChunkX + maxChunkX) / 2, (minChunkZ + maxChunkZ) / 2); + this.nchunks = requestedChunks.size(); + this.modID = ticket.getModId(); + this.ticket = ticket; + } + + public TicketData(CoordinatesChunk coord, int nchunks, String modid) { + this.coord = coord; + this.nchunks = nchunks; + this.modID = modid; + this.ticket = null; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.coord.writeToStream(stream); + stream.writeInt(this.nchunks); + stream.writeUTF(this.modID); + } + + public static TicketData readFromStream(ByteArrayDataInput stream) { + return new TicketData(CoordinatesChunk.readFromStream(stream), stream.readInt(), stream.readUTF()); + } + + public boolean equals(Object o) { + TicketData c = (TicketData) o; + + if (this.ticket != null && c.ticket != null) return this.ticket.equals(c.ticket); + + return (this.coord.dim == c.coord.dim) + && (this.coord.chunkX == c.coord.chunkX) + && (this.coord.chunkZ == c.coord.chunkZ) + && (this.nchunks == c.nchunks); + } + ; + + public int hashCode() { + if (this.ticket != null) return this.ticket.hashCode(); + return String.format("%s %s %s %s", this.coord.dim, this.coord.chunkX, this.coord.chunkZ, this.nchunks) + .hashCode(); + } + + public String toString() { + return String.format( + "Ticket %s [%d %d %d] %d", + this.modID, this.coord.dim, this.coord.chunkX, this.coord.chunkZ, this.nchunks); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataBlockRender.java b/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataBlockRender.java index 541600b..d73c58d 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataBlockRender.java +++ b/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataBlockRender.java @@ -1,5 +1,6 @@ package mcp.mobius.opis.data.holders.clienttypes; +import java.util.HashMap; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; @@ -10,23 +11,19 @@ import net.minecraft.client.Minecraft; import net.minecraft.world.World; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; -import java.util.HashMap; +public class DataBlockRender extends DataBlockTileEntity { -public class DataBlockRender extends DataBlockTileEntity -{ + public DataBlockRender fill(CoordinatesBlock coord) { + this.pos = coord; + World world = Minecraft.getMinecraft().theWorld; // DimensionManager.getWorld(this.pos.dim); - public DataBlockRender fill(CoordinatesBlock coord){ - this.pos = coord; - World world = Minecraft.getMinecraft().theWorld; //DimensionManager.getWorld(this.pos.dim); - - this.id = (short) Block.getIdFromBlock(world.getBlock(this.pos.x, this.pos.y, this.pos.z)); - this.meta = (short) world.getBlockMetadata(this.pos.x, this.pos.y, this.pos.z); + this.id = (short) Block.getIdFromBlock(world.getBlock(this.pos.x, this.pos.y, this.pos.z)); + this.meta = (short) world.getBlockMetadata(this.pos.x, this.pos.y, this.pos.z); - HashMap data = ((ProfilerRenderBlock)(ProfilerSection.RENDER_BLOCK.getProfiler())).data; - this.update = new DataTiming(data.containsKey(coord) ? data.get(coord).getGeometricMean() : 0.0D); - - return this; - } - - + HashMap data = + ((ProfilerRenderBlock) (ProfilerSection.RENDER_BLOCK.getProfiler())).data; + this.update = new DataTiming(data.containsKey(coord) ? data.get(coord).getGeometricMean() : 0.0D); + + return this; + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataEntityRender.java b/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataEntityRender.java index fd4b0d6..5adc32a 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataEntityRender.java +++ b/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataEntityRender.java @@ -1,5 +1,6 @@ package mcp.mobius.opis.data.holders.clienttypes; +import java.util.WeakHashMap; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.newtypes.DataTiming; @@ -8,32 +9,30 @@ import mcp.mobius.opis.data.profilers.ProfilerRenderEntity; import net.minecraft.entity.Entity; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; -import java.util.WeakHashMap; +public class DataEntityRender implements Comparable { -public class DataEntityRender implements Comparable -{ + public int eid; + public long npoints; + public String name; + public CoordinatesBlock pos; + public DataTiming update; - public int eid; - public long npoints; - public String name; - public CoordinatesBlock pos; - public DataTiming update; + public DataEntityRender fill(Entity entity) { - public DataEntityRender fill(Entity entity){ - - this.eid = entity.getEntityId(); - this.name = EntityManager.INSTANCE.getEntityName(entity, false); - this.pos = new CoordinatesBlock(entity); - - WeakHashMap data = ((ProfilerRenderEntity)(ProfilerSection.RENDER_ENTITY.getProfiler())).data; - this.update = new DataTiming(data.containsKey(entity) ? data.get(entity).getGeometricMean() : 0.0D); - this.npoints = data.containsKey(entity) ? data.get(entity).getN() : 0; - - return this; - } + this.eid = entity.getEntityId(); + this.name = EntityManager.INSTANCE.getEntityName(entity, false); + this.pos = new CoordinatesBlock(entity); - @Override - public int compareTo(Object o) { - return this.update.compareTo(((DataEntityRender)o).update); - } + WeakHashMap data = + ((ProfilerRenderEntity) (ProfilerSection.RENDER_ENTITY.getProfiler())).data; + this.update = new DataTiming(data.containsKey(entity) ? data.get(entity).getGeometricMean() : 0.0D); + this.npoints = data.containsKey(entity) ? data.get(entity).getN() : 0; + + return this; + } + + @Override + public int compareTo(Object o) { + return this.update.compareTo(((DataEntityRender) o).update); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataRenderEvent.java b/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataRenderEvent.java index cfec13d..3329ff6 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataRenderEvent.java +++ b/src/main/java/mcp/mobius/opis/data/holders/clienttypes/DataRenderEvent.java @@ -5,41 +5,42 @@ import mcp.mobius.opis.data.holders.newtypes.DataTiming; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class DataRenderEvent implements Comparable { - public String event; - public String handler; - public String package_; - public String mod; - public long nCalls; - public DataTiming update; - - public DataRenderEvent fill(Cell cellData, String modName){ - /* - String handlerName = cell.getColumnKey().getSimpleName(); - try { - String[] splitHandler = handlerName.split("_"); - handlerName = splitHandler[2] + "." + splitHandler[3]; - } catch (Exception e){} - */ - String[] nameRaw = cellData.getColumnKey().split("\\|"); - - String handlerName = nameRaw[1]; - try { - String[] splitHandler = handlerName.split("_"); - handlerName = splitHandler[2] + "." + splitHandler[3]; - } catch (Exception e){} - - this.package_= nameRaw[0]; - this.handler = handlerName; - this.event = cellData.getRowKey().getName().replace("net.minecraftforge.event.", ""); - this.nCalls = cellData.getValue().getN(); - this.mod = modName; - - this.update = new DataTiming(cellData.getValue().getGeometricMean()); - return this; - } + public String event; + public String handler; + public String package_; + public String mod; + public long nCalls; + public DataTiming update; - @Override - public int compareTo(Object o) { - return this.update.compareTo(((DataRenderEvent)o).update); - } + public DataRenderEvent fill(Cell cellData, String modName) { + /* + String handlerName = cell.getColumnKey().getSimpleName(); + try { + String[] splitHandler = handlerName.split("_"); + handlerName = splitHandler[2] + "." + splitHandler[3]; + } catch (Exception e){} + */ + String[] nameRaw = cellData.getColumnKey().split("\\|"); + + String handlerName = nameRaw[1]; + try { + String[] splitHandler = handlerName.split("_"); + handlerName = splitHandler[2] + "." + splitHandler[3]; + } catch (Exception e) { + } + + this.package_ = nameRaw[0]; + this.handler = handlerName; + this.event = cellData.getRowKey().getName().replace("net.minecraftforge.event.", ""); + this.nCalls = cellData.getValue().getN(); + this.mod = modName; + + this.update = new DataTiming(cellData.getValue().getGeometricMean()); + return this; + } + + @Override + public int compareTo(Object o) { + return this.update.compareTo(((DataRenderEvent) o).update); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/CachedString.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/CachedString.java index 556ac3a..6618fea 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/CachedString.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/CachedString.java @@ -1,69 +1,56 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - -import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.server.FMLServerHandler; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.managers.StringCache; import mcp.mobius.opis.helpers.Helpers; +public class CachedString implements Comparable, ISerializable { -public class CachedString implements Comparable, ISerializable{ + public String str; + public int index; + private boolean valid = false; - public String str; - public int index; - private boolean valid = false; - - - public CachedString(int index) { - this.index = index; - this.str = StringCache.INSTANCE.getString(index); - this.valid = !this.str.equals(""); - } - - public CachedString(String str){ + public CachedString(int index) { + this.index = index; + this.str = StringCache.INSTANCE.getString(index); + this.valid = !this.str.equals(""); + } - //if(FMLCommonHandler.instance().getSide() == Side.SERVER){ - if(Helpers.getEffectiveSide() == Side.SERVER){ - this.index = StringCache.INSTANCE.getIndex(str); - this.str = str; - } else { - this.index = -1; - this.str = str; - } - } - + public CachedString(String str) { - - @Override - public int compareTo(Object o) { - return ((CachedString)o).str.compareTo(this.str); // Reverse order ! Put higher values FIRST - } - - public String toString(){ - //return String.format("[%d] %s",this.index, this.str); - if (!this.valid){ - this.str = StringCache.INSTANCE.getString(index); - this.valid = !this.str.equals(""); - } - - return this.str; - - } - - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeInt(this.index); - } - - public static CachedString readFromStream(ByteArrayDataInput stream){ - return new CachedString(stream.readInt()); - } - + // if(FMLCommonHandler.instance().getSide() == Side.SERVER){ + if (Helpers.getEffectiveSide() == Side.SERVER) { + this.index = StringCache.INSTANCE.getIndex(str); + this.str = str; + } else { + this.index = -1; + this.str = str; + } + } + + @Override + public int compareTo(Object o) { + return ((CachedString) o).str.compareTo(this.str); // Reverse order ! Put higher values FIRST + } + + public String toString() { + // return String.format("[%d] %s",this.index, this.str); + if (!this.valid) { + this.str = StringCache.INSTANCE.getString(index); + this.valid = !this.str.equals(""); + } + + return this.str; + } + + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeInt(this.index); + } + + public static CachedString readFromStream(ByteArrayDataInput stream) { + return new CachedString(stream.readInt()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/ChatMsg.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/ChatMsg.java index caa597f..8f22aef 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/ChatMsg.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/ChatMsg.java @@ -2,41 +2,35 @@ package mcp.mobius.opis.data.holders.newtypes; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.basetypes.SerialString; -public class ChatMsg implements ISerializable{ +public class ChatMsg implements ISerializable { - public long timestamp; - public CachedString username; - public SerialString message; - - public ChatMsg(String username, String message){ - this.username = new CachedString(username); - this.message = new SerialString(message); - this.timestamp = System.currentTimeMillis(); - } + public long timestamp; + public CachedString username; + public SerialString message; - public ChatMsg(CachedString username, SerialString message, long timestamp){ - this.username = username; - this.message = message; - this.timestamp = timestamp; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream) { - this.username.writeToStream(stream); - this.message.writeToStream(stream); - stream.writeLong(this.timestamp); - } + public ChatMsg(String username, String message) { + this.username = new CachedString(username); + this.message = new SerialString(message); + this.timestamp = System.currentTimeMillis(); + } - public static ChatMsg readFromStream(ByteArrayDataInput stream){ - return new ChatMsg( - CachedString.readFromStream(stream), - SerialString.readFromStream(stream), - stream.readLong() - ); - } - + public ChatMsg(CachedString username, SerialString message, long timestamp) { + this.username = username; + this.message = message; + this.timestamp = timestamp; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.username.writeToStream(stream); + this.message.writeToStream(stream); + stream.writeLong(this.timestamp); + } + + public static ChatMsg readFromStream(ByteArrayDataInput stream) { + return new ChatMsg(CachedString.readFromStream(stream), SerialString.readFromStream(stream), stream.readLong()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/ConnectionProperties.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/ConnectionProperties.java index 14808ea..4ef912e 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/ConnectionProperties.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/ConnectionProperties.java @@ -1,10 +1,8 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.util.Properties; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - +import java.util.Properties; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.basetypes.SerialString; @@ -12,23 +10,23 @@ public class ConnectionProperties implements ISerializable { public Properties prop = new Properties(); - public ConnectionProperties(Properties prop){ + public ConnectionProperties(Properties prop) { this.prop = prop; } @Override public void writeToStream(ByteArrayDataOutput stream) { stream.writeInt(this.prop.size()); - for (String key : this.prop.stringPropertyNames()){ + for (String key : this.prop.stringPropertyNames()) { new SerialString(key).writeToStream(stream); new SerialString(this.prop.getProperty(key)).writeToStream(stream); } } - public static ConnectionProperties readFromStream(ByteArrayDataInput stream){ + public static ConnectionProperties readFromStream(ByteArrayDataInput stream) { Properties prop = new Properties(); int nkeys = stream.readInt(); - for (int i = 0; i < nkeys; i++){ + for (int i = 0; i < nkeys; i++) { String key = SerialString.readFromStream(stream).value; String val = SerialString.readFromStream(stream).value; prop.setProperty(key, val); diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataAmountRate.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataAmountRate.java index 208f122..2ec3667 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataAmountRate.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataAmountRate.java @@ -1,40 +1,38 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; public class DataAmountRate implements Comparable, ISerializable { - public Long size; // Size is stored in byte - public int interval; - - //public DataByteRate(int interval){ this.size = 0L; this.interval = interval;} - public DataAmountRate(long size, int interval){ this.size = size; this.interval = interval;} - - @Override - public int compareTo(Object o) { - return ((DataAmountRate)o).size.compareTo(this.size); // Reverse order ! Put higher values FIRST - } - - public void reset(){ - this.size = 0L; - } - - public String toString(){ - return String.format("%.2f packet/s", (double)this.size / (double)this.interval); - } - - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeLong(this.size); - stream.writeInt(this.interval); - } - - public static DataAmountRate readFromStream(ByteArrayDataInput stream){ - return new DataAmountRate(stream.readLong(), stream.readInt()); - } + public Long size; // Size is stored in byte + public int interval; + + // public DataByteRate(int interval){ this.size = 0L; this.interval = interval;} + public DataAmountRate(long size, int interval) { + this.size = size; + this.interval = interval; + } + + @Override + public int compareTo(Object o) { + return ((DataAmountRate) o).size.compareTo(this.size); // Reverse order ! Put higher values FIRST + } + + public void reset() { + this.size = 0L; + } + + public String toString() { + return String.format("%.2f packet/s", (double) this.size / (double) this.interval); + } + + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeLong(this.size); + stream.writeInt(this.interval); + } + + public static DataAmountRate readFromStream(ByteArrayDataInput stream) { + return new DataAmountRate(stream.readLong(), stream.readInt()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTick.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTick.java index 35c8285..4753e0b 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTick.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTick.java @@ -1,51 +1,45 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.HashMap; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - +import java.util.HashMap; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.profilers.ProfilerDimBlockTick; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; -public class DataBlockTick implements ISerializable{ - public HashMap perdim = new HashMap(); - public DataTiming total; - - public DataBlockTick fill(){ - this.total = new DataTiming(); - HashMap data = ((ProfilerDimBlockTick)ProfilerSection.DIMENSION_BLOCKTICK.getProfiler()).data; - - for (Integer dim : data.keySet()){ - this.perdim.put(dim, new DataTiming(data.get(dim).getGeometricMean())); - this.total.timing += data.get(dim).getGeometricMean(); - } - - return this; - } +public class DataBlockTick implements ISerializable { + public HashMap perdim = new HashMap(); + public DataTiming total; - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeShort(this.perdim.size()); - for (Integer key : this.perdim.keySet()){ - stream.writeInt(key); - this.perdim.get(key).writeToStream(stream); - } - this.total.writeToStream(stream); - } - - public static DataBlockTick readFromStream(ByteArrayDataInput stream){ - DataBlockTick retVal = new DataBlockTick(); - int nkeys = stream.readShort(); - for (int i = 0; i < nkeys; i++) - retVal.perdim.put(stream.readInt(), DataTiming.readFromStream(stream)); - retVal.total = DataTiming.readFromStream(stream); - return retVal; - } + public DataBlockTick fill() { + this.total = new DataTiming(); + HashMap data = + ((ProfilerDimBlockTick) ProfilerSection.DIMENSION_BLOCKTICK.getProfiler()).data; + + for (Integer dim : data.keySet()) { + this.perdim.put(dim, new DataTiming(data.get(dim).getGeometricMean())); + this.total.timing += data.get(dim).getGeometricMean(); + } + + return this; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeShort(this.perdim.size()); + for (Integer key : this.perdim.keySet()) { + stream.writeInt(key); + this.perdim.get(key).writeToStream(stream); + } + this.total.writeToStream(stream); + } + + public static DataBlockTick readFromStream(ByteArrayDataInput stream) { + DataBlockTick retVal = new DataBlockTick(); + int nkeys = stream.readShort(); + for (int i = 0; i < nkeys; i++) retVal.perdim.put(stream.readInt(), DataTiming.readFromStream(stream)); + retVal.total = DataTiming.readFromStream(stream); + return retVal; + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTileEntity.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTileEntity.java index fa9d08c..3ead51d 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTileEntity.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTileEntity.java @@ -1,64 +1,58 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.HashMap; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - -import net.minecraft.block.Block; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.DimensionManager; +import java.util.HashMap; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.profilers.ProfilerTileEntityUpdate; +import net.minecraft.block.Block; +import net.minecraft.world.World; +import net.minecraftforge.common.DimensionManager; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class DataBlockTileEntity implements ISerializable, Comparable { - public short id; - public short meta; - public CoordinatesBlock pos; - public DataTiming update; - - public DataBlockTileEntity fill(CoordinatesBlock coord){ - this.pos = coord; - World world = DimensionManager.getWorld(this.pos.dim); - - this.id = (short) Block.getIdFromBlock(world.getBlock(this.pos.x, this.pos.y, this.pos.z)); - this.meta = (short) world.getBlockMetadata(this.pos.x, this.pos.y, this.pos.z); + public short id; + public short meta; + public CoordinatesBlock pos; + public DataTiming update; - HashMap data = ((ProfilerTileEntityUpdate)(ProfilerSection.TILEENT_UPDATETIME.getProfiler())).data; - this.update = new DataTiming(data.containsKey(this.pos) ? data.get(this.pos).getGeometricMean() : 0.0D); - - return this; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream) { - stream.writeShort(this.id); - stream.writeShort(this.meta); - this.pos.writeToStream(stream); - this.update.writeToStream(stream); - } + public DataBlockTileEntity fill(CoordinatesBlock coord) { + this.pos = coord; + World world = DimensionManager.getWorld(this.pos.dim); - public static DataBlockTileEntity readFromStream(ByteArrayDataInput stream){ - DataBlockTileEntity retVal = new DataBlockTileEntity(); - retVal.id = stream.readShort(); - retVal.meta = stream.readShort(); - retVal.pos = CoordinatesBlock.readFromStream(stream); - retVal.update = DataTiming.readFromStream(stream); - return retVal; - } + this.id = (short) Block.getIdFromBlock(world.getBlock(this.pos.x, this.pos.y, this.pos.z)); + this.meta = (short) world.getBlockMetadata(this.pos.x, this.pos.y, this.pos.z); - @Override - public int compareTo(Object o) { - return this.update.compareTo(((DataBlockTileEntity)o).update); - } + HashMap data = + ((ProfilerTileEntityUpdate) (ProfilerSection.TILEENT_UPDATETIME.getProfiler())).data; + this.update = + new DataTiming(data.containsKey(this.pos) ? data.get(this.pos).getGeometricMean() : 0.0D); + return this; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeShort(this.id); + stream.writeShort(this.meta); + this.pos.writeToStream(stream); + this.update.writeToStream(stream); + } + + public static DataBlockTileEntity readFromStream(ByteArrayDataInput stream) { + DataBlockTileEntity retVal = new DataBlockTileEntity(); + retVal.id = stream.readShort(); + retVal.meta = stream.readShort(); + retVal.pos = CoordinatesBlock.readFromStream(stream); + retVal.update = DataTiming.readFromStream(stream); + return retVal; + } + + @Override + public int compareTo(Object o) { + return this.update.compareTo(((DataBlockTileEntity) o).update); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTileEntityPerClass.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTileEntityPerClass.java index d9b143b..dd2f7b9 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTileEntityPerClass.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataBlockTileEntityPerClass.java @@ -1,79 +1,72 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.helpers.ModIdentification; public class DataBlockTileEntityPerClass implements ISerializable, Comparable { - public int id; - public int meta; - public int amount; - public CachedString name; - public CachedString mod; - public DataTiming update; - - public DataBlockTileEntityPerClass(){} - - public DataBlockTileEntityPerClass(int id, int meta){ - this.id = id; - this.meta = meta; - this.amount = 0; - this.name = new CachedString(ModIdentification.getStackName(id, meta)); - this.mod = new CachedString(ModIdentification.getModStackName(id, meta)); - this.update = new DataTiming(); - } - - public DataBlockTileEntityPerClass add(){ - this.amount += 1; - return this; - } - - public DataBlockTileEntityPerClass add(Double timing){ - this.amount += 1; - this.update.timing += timing; - - return this; - } + public int id; + public int meta; + public int amount; + public CachedString name; + public CachedString mod; + public DataTiming update; - public DataBlockTileEntityPerClass add(int amount, Double timing){ - this.amount += amount; - this.update.timing += timing; - - return this; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeInt(this.id); - stream.writeInt(this.meta); - stream.writeInt(this.amount); - this.name.writeToStream(stream); - this.mod.writeToStream(stream); - this.update.writeToStream(stream); - } + public DataBlockTileEntityPerClass() {} - public static DataBlockTileEntityPerClass readFromStream(ByteArrayDataInput stream){ - DataBlockTileEntityPerClass retVal = new DataBlockTileEntityPerClass(); - retVal.id = stream.readInt(); - retVal.meta = stream.readInt(); - retVal.amount = stream.readInt(); - retVal.name = CachedString.readFromStream(stream); - retVal.mod = CachedString.readFromStream(stream); - retVal.update = DataTiming.readFromStream(stream); - return retVal; - } + public DataBlockTileEntityPerClass(int id, int meta) { + this.id = id; + this.meta = meta; + this.amount = 0; + this.name = new CachedString(ModIdentification.getStackName(id, meta)); + this.mod = new CachedString(ModIdentification.getModStackName(id, meta)); + this.update = new DataTiming(); + } - @Override - public int compareTo(Object o) { - return this.update.compareTo(((DataBlockTileEntityPerClass)o).update); - } - + public DataBlockTileEntityPerClass add() { + this.amount += 1; + return this; + } + + public DataBlockTileEntityPerClass add(Double timing) { + this.amount += 1; + this.update.timing += timing; + + return this; + } + + public DataBlockTileEntityPerClass add(int amount, Double timing) { + this.amount += amount; + this.update.timing += timing; + + return this; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeInt(this.id); + stream.writeInt(this.meta); + stream.writeInt(this.amount); + this.name.writeToStream(stream); + this.mod.writeToStream(stream); + this.update.writeToStream(stream); + } + + public static DataBlockTileEntityPerClass readFromStream(ByteArrayDataInput stream) { + DataBlockTileEntityPerClass retVal = new DataBlockTileEntityPerClass(); + retVal.id = stream.readInt(); + retVal.meta = stream.readInt(); + retVal.amount = stream.readInt(); + retVal.name = CachedString.readFromStream(stream); + retVal.mod = CachedString.readFromStream(stream); + retVal.update = DataTiming.readFromStream(stream); + return retVal; + } + + @Override + public int compareTo(Object o) { + return this.update.compareTo(((DataBlockTileEntityPerClass) o).update); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataByteRate.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataByteRate.java index 6cae341..201dcbb 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataByteRate.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataByteRate.java @@ -1,49 +1,47 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; public class DataByteRate implements Comparable, ISerializable { - public Long size; // Size is stored in byte - public int interval; - - //public DataByteRate(int interval){ this.size = 0L; this.interval = interval;} - public DataByteRate(long size, int interval){ this.size = size; this.interval = interval;} - - @Override - public int compareTo(Object o) { - return ((DataByteRate)o).size.compareTo(this.size); // Reverse order ! Put higher values FIRST - } - - public void reset(){ - this.size = 0L; - } - - public String toString(){ - - if (size >= 1024 && size < (1024*1024)){ - return String.format("%.3f KiB/s", this.size / 1024.0 / this.interval); - } + public Long size; // Size is stored in byte + public int interval; - if (size >= (1024*1024)){ - return String.format("%.3f MiB/s", this.size / 1024.0 / 1024.0 / this.interval); - } + // public DataByteRate(int interval){ this.size = 0L; this.interval = interval;} + public DataByteRate(long size, int interval) { + this.size = size; + this.interval = interval; + } - return String.format("%4d B/s", this.size / this.interval); - } - - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeLong(this.size); - stream.writeInt(this.interval); - } - - public static DataByteRate readFromStream(ByteArrayDataInput stream){ - return new DataByteRate(stream.readLong(), stream.readInt()); - } + @Override + public int compareTo(Object o) { + return ((DataByteRate) o).size.compareTo(this.size); // Reverse order ! Put higher values FIRST + } + + public void reset() { + this.size = 0L; + } + + public String toString() { + + if (size >= 1024 && size < (1024 * 1024)) { + return String.format("%.3f KiB/s", this.size / 1024.0 / this.interval); + } + + if (size >= (1024 * 1024)) { + return String.format("%.3f MiB/s", this.size / 1024.0 / 1024.0 / this.interval); + } + + return String.format("%4d B/s", this.size / this.interval); + } + + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeLong(this.size); + stream.writeInt(this.interval); + } + + public static DataByteRate readFromStream(ByteArrayDataInput stream) { + return new DataByteRate(stream.readLong(), stream.readInt()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataByteSize.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataByteSize.java index 880d8ff..5320978 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataByteSize.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataByteSize.java @@ -1,43 +1,43 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; public class DataByteSize implements Comparable, ISerializable { - public Long size; // Size is stored in byte + public Long size; // Size is stored in byte - public DataByteSize(){ this.size = 0L; } - public DataByteSize(long size){ this.size = size; } - - @Override - public int compareTo(Object o) { - return ((DataByteSize)o).size.compareTo(this.size); // Reverse order ! Put higher values FIRST - } - - public String toString(){ - - if (size >= 1024 && size < (1024*1024)){ - return String.format("%.3f KiB", this.size / 1024.0); - } + public DataByteSize() { + this.size = 0L; + } - if (size >= (1024*1024)){ - return String.format("%.3f MiB", this.size / 1024.0 / 1024.0); - } + public DataByteSize(long size) { + this.size = size; + } - return String.format("%4d B", this.size); - } - - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeLong(this.size); - } - - public static DataByteSize readFromStream(ByteArrayDataInput stream){ - return new DataByteSize(stream.readLong()); - } + @Override + public int compareTo(Object o) { + return ((DataByteSize) o).size.compareTo(this.size); // Reverse order ! Put higher values FIRST + } + + public String toString() { + + if (size >= 1024 && size < (1024 * 1024)) { + return String.format("%.3f KiB", this.size / 1024.0); + } + + if (size >= (1024 * 1024)) { + return String.format("%.3f MiB", this.size / 1024.0 / 1024.0); + } + + return String.format("%4d B", this.size); + } + + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeLong(this.size); + } + + public static DataByteSize readFromStream(ByteArrayDataInput stream) { + return new DataByteSize(stream.readLong()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataChunk.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataChunk.java index 4250d55..55089e0 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataChunk.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataChunk.java @@ -1,61 +1,54 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.ArrayList; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - +import java.util.ArrayList; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; import mcp.mobius.opis.data.managers.EntityManager; import mcp.mobius.opis.data.managers.TileEntityManager; public class DataChunk implements ISerializable, Comparable { - int nentities; - int ntileents; - DataTiming update; - CoordinatesChunk chunk; - - public DataChunk fill(CoordinatesChunk chunk){ - this.chunk = chunk; - ArrayList tileEnts = TileEntityManager.INSTANCE.getTileEntitiesInChunk(this.chunk); - ArrayList entities = EntityManager.INSTANCE.getEntitiesInChunk(this.chunk); - - this.nentities = entities.size(); - this.ntileents = tileEnts.size(); - double totalUpdate = 0.0D; - for (DataBlockTileEntity tileent : tileEnts) - totalUpdate += tileent.update.timing; + int nentities; + int ntileents; + DataTiming update; + CoordinatesChunk chunk; - for (DataEntity ent : entities) - totalUpdate += ent.update.timing; - - this.update = new DataTiming(totalUpdate); - return this; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeInt(this.nentities); - stream.writeInt(this.ntileents); - this.update.writeToStream(stream); - this.chunk.writeToStream(stream); - } + public DataChunk fill(CoordinatesChunk chunk) { + this.chunk = chunk; + ArrayList tileEnts = TileEntityManager.INSTANCE.getTileEntitiesInChunk(this.chunk); + ArrayList entities = EntityManager.INSTANCE.getEntitiesInChunk(this.chunk); - public static DataChunk readFromStream(ByteArrayDataInput stream){ - DataChunk retVal = new DataChunk(); - retVal.nentities = stream.readInt(); - retVal.ntileents = stream.readInt(); - retVal.update = DataTiming.readFromStream(stream); - retVal.chunk = CoordinatesChunk.readFromStream(stream); - return retVal; - } + this.nentities = entities.size(); + this.ntileents = tileEnts.size(); + double totalUpdate = 0.0D; + for (DataBlockTileEntity tileent : tileEnts) totalUpdate += tileent.update.timing; - @Override - public int compareTo(Object o) { - return this.update.compareTo(((DataEntity)o).update); - } + for (DataEntity ent : entities) totalUpdate += ent.update.timing; + + this.update = new DataTiming(totalUpdate); + return this; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeInt(this.nentities); + stream.writeInt(this.ntileents); + this.update.writeToStream(stream); + this.chunk.writeToStream(stream); + } + + public static DataChunk readFromStream(ByteArrayDataInput stream) { + DataChunk retVal = new DataChunk(); + retVal.nentities = stream.readInt(); + retVal.ntileents = stream.readInt(); + retVal.update = DataTiming.readFromStream(stream); + retVal.chunk = CoordinatesChunk.readFromStream(stream); + return retVal; + } + + @Override + public int compareTo(Object o) { + return this.update.compareTo(((DataEntity) o).update); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataChunkEntities.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataChunkEntities.java index 5bcd570..c52f8f7 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataChunkEntities.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataChunkEntities.java @@ -1,34 +1,28 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.util.ArrayList; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; -import mcp.mobius.opis.data.managers.EntityManager; -import mcp.mobius.opis.data.managers.TileEntityManager; -public class DataChunkEntities implements ISerializable{ +public class DataChunkEntities implements ISerializable { - public int entities; - public CoordinatesChunk chunk; - - public DataChunkEntities(CoordinatesChunk chunk, int entities){ - this.chunk = chunk; - this.entities = entities; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - this.chunk.writeToStream(stream); - stream.writeInt(this.entities); - } + public int entities; + public CoordinatesChunk chunk; - public static DataChunkEntities readFromStream(ByteArrayDataInput stream){ - DataChunkEntities retVal = new DataChunkEntities(CoordinatesChunk.readFromStream(stream), stream.readInt()); - return retVal; - } - + public DataChunkEntities(CoordinatesChunk chunk, int entities) { + this.chunk = chunk; + this.entities = entities; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.chunk.writeToStream(stream); + stream.writeInt(this.entities); + } + + public static DataChunkEntities readFromStream(ByteArrayDataInput stream) { + DataChunkEntities retVal = new DataChunkEntities(CoordinatesChunk.readFromStream(stream), stream.readInt()); + return retVal; + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataDimension.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataDimension.java index 274856c..6e7e112 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataDimension.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataDimension.java @@ -1,16 +1,9 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - +import java.util.ArrayList; +import java.util.HashMap; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.profilers.ProfilerDimTick; @@ -20,79 +13,77 @@ import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.world.WorldServer; import net.minecraftforge.common.DimensionManager; - +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; /* Data holder for infos about dimensions */ public class DataDimension implements ISerializable { - public int dim; - public CachedString name; - public int players; - public int forced; - public int loaded; - public int entities; - public int mobs; - public int neutral; - public int itemstacks; - public DataTiming update; - - public DataDimension fill(int dim){ - WorldServer world = DimensionManager.getWorld(dim); - - this.dim = dim; - this.name = new CachedString(world.provider.getDimensionName()); - this.players = world.playerEntities.size(); - this.forced = world.getPersistentChunks().size(); - this.loaded = world.getChunkProvider().getLoadedChunkCount(); - - HashMap data = ((ProfilerDimTick)(ProfilerSection.DIMENSION_TICK.getProfiler())).data; - this.update = new DataTiming(data.containsKey(dim) ? data.get(dim).getGeometricMean() : 0.0D); - - this.mobs = 0; - this.neutral = 0; - this.entities = world.loadedEntityList.size(); - - for (Entity entity : (ArrayList)world.loadedEntityList){ - if (entity instanceof EntityMob) - this.mobs += 1; - if (entity instanceof EntityAnimal) - this.neutral += 1; - if (entity instanceof EntityItem) - this.itemstacks += 1; - } - - return this; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeInt(dim); - stream.writeInt(players); - stream.writeInt(forced); - stream.writeInt(loaded); - stream.writeInt(entities); - stream.writeInt(mobs); - stream.writeInt(neutral); - stream.writeInt(itemstacks); - //stream.writeDouble(update); - this.update.writeToStream(stream); - this.name.writeToStream(stream); - } + public int dim; + public CachedString name; + public int players; + public int forced; + public int loaded; + public int entities; + public int mobs; + public int neutral; + public int itemstacks; + public DataTiming update; - public static DataDimension readFromStream(ByteArrayDataInput stream){ - DataDimension retVal = new DataDimension(); - retVal.dim = stream.readInt(); - retVal.players = stream.readInt(); - retVal.forced = stream.readInt(); - retVal.loaded = stream.readInt(); - retVal.entities= stream.readInt(); - retVal.mobs = stream.readInt(); - retVal.neutral = stream.readInt(); - retVal.itemstacks = stream.readInt(); - //retVal.update = stream.readDouble(); - retVal.update = DataTiming.readFromStream(stream); - retVal.name = CachedString.readFromStream(stream); - return retVal; - } + public DataDimension fill(int dim) { + WorldServer world = DimensionManager.getWorld(dim); + + this.dim = dim; + this.name = new CachedString(world.provider.getDimensionName()); + this.players = world.playerEntities.size(); + this.forced = world.getPersistentChunks().size(); + this.loaded = world.getChunkProvider().getLoadedChunkCount(); + + HashMap data = + ((ProfilerDimTick) (ProfilerSection.DIMENSION_TICK.getProfiler())).data; + this.update = new DataTiming(data.containsKey(dim) ? data.get(dim).getGeometricMean() : 0.0D); + + this.mobs = 0; + this.neutral = 0; + this.entities = world.loadedEntityList.size(); + + for (Entity entity : (ArrayList) world.loadedEntityList) { + if (entity instanceof EntityMob) this.mobs += 1; + if (entity instanceof EntityAnimal) this.neutral += 1; + if (entity instanceof EntityItem) this.itemstacks += 1; + } + + return this; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeInt(dim); + stream.writeInt(players); + stream.writeInt(forced); + stream.writeInt(loaded); + stream.writeInt(entities); + stream.writeInt(mobs); + stream.writeInt(neutral); + stream.writeInt(itemstacks); + // stream.writeDouble(update); + this.update.writeToStream(stream); + this.name.writeToStream(stream); + } + + public static DataDimension readFromStream(ByteArrayDataInput stream) { + DataDimension retVal = new DataDimension(); + retVal.dim = stream.readInt(); + retVal.players = stream.readInt(); + retVal.forced = stream.readInt(); + retVal.loaded = stream.readInt(); + retVal.entities = stream.readInt(); + retVal.mobs = stream.readInt(); + retVal.neutral = stream.readInt(); + retVal.itemstacks = stream.readInt(); + // retVal.update = stream.readDouble(); + retVal.update = DataTiming.readFromStream(stream); + retVal.name = CachedString.readFromStream(stream); + return retVal; + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEntity.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEntity.java index 1a696d9..65a5e4b 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEntity.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEntity.java @@ -1,65 +1,59 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.WeakHashMap; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - -import net.minecraft.entity.Entity; +import java.util.WeakHashMap; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.managers.EntityManager; import mcp.mobius.opis.data.profilers.ProfilerEntityUpdate; +import net.minecraft.entity.Entity; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class DataEntity implements ISerializable, Comparable { - public int eid; - public long npoints; - public CachedString name; - public CoordinatesBlock pos; - public DataTiming update; - - public DataEntity fill(Entity entity){ - - this.eid = entity.getEntityId(); - this.name = new CachedString(EntityManager.INSTANCE.getEntityName(entity, false)); - this.pos = new CoordinatesBlock(entity); - - WeakHashMap data = ((ProfilerEntityUpdate)(ProfilerSection.ENTITY_UPDATETIME.getProfiler())).data; - this.update = new DataTiming(data.containsKey(entity) ? data.get(entity).getGeometricMean() : 0.0D); - this.npoints = data.containsKey(entity) ? data.get(entity).getN() : 0; - - return this; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeInt(this.eid); - this.name.writeToStream(stream); - this.pos.writeToStream(stream); - this.update.writeToStream(stream); - stream.writeLong(this.npoints); - } + public int eid; + public long npoints; + public CachedString name; + public CoordinatesBlock pos; + public DataTiming update; - public static DataEntity readFromStream(ByteArrayDataInput stream){ - DataEntity retVal = new DataEntity(); - retVal.eid = stream.readInt(); - retVal.name = CachedString.readFromStream(stream); - retVal.pos = CoordinatesBlock.readFromStream(stream); - retVal.update = DataTiming.readFromStream(stream); - retVal.npoints= stream.readLong(); - return retVal; - } + public DataEntity fill(Entity entity) { - @Override - public int compareTo(Object o) { - return this.update.compareTo(((DataEntity)o).update); - } + this.eid = entity.getEntityId(); + this.name = new CachedString(EntityManager.INSTANCE.getEntityName(entity, false)); + this.pos = new CoordinatesBlock(entity); + + WeakHashMap data = + ((ProfilerEntityUpdate) (ProfilerSection.ENTITY_UPDATETIME.getProfiler())).data; + this.update = new DataTiming(data.containsKey(entity) ? data.get(entity).getGeometricMean() : 0.0D); + this.npoints = data.containsKey(entity) ? data.get(entity).getN() : 0; + + return this; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeInt(this.eid); + this.name.writeToStream(stream); + this.pos.writeToStream(stream); + this.update.writeToStream(stream); + stream.writeLong(this.npoints); + } + + public static DataEntity readFromStream(ByteArrayDataInput stream) { + DataEntity retVal = new DataEntity(); + retVal.eid = stream.readInt(); + retVal.name = CachedString.readFromStream(stream); + retVal.pos = CoordinatesBlock.readFromStream(stream); + retVal.update = DataTiming.readFromStream(stream); + retVal.npoints = stream.readLong(); + return retVal; + } + + @Override + public int compareTo(Object o) { + return this.update.compareTo(((DataEntity) o).update); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEntityPerClass.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEntityPerClass.java index 3527eaa..8f54c6f 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEntityPerClass.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEntityPerClass.java @@ -1,53 +1,47 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; -public class DataEntityPerClass implements Comparable, ISerializable{ +public class DataEntityPerClass implements Comparable, ISerializable { - public int nents; - public CachedString name; - public DataTiming update; + public int nents; + public CachedString name; + public DataTiming update; - public DataEntityPerClass(){} - - public DataEntityPerClass(String name){ - this.name = new CachedString(name); - this.nents = 0; - this.update = new DataTiming(); - } - - public DataEntityPerClass add(Double timing){ - this.nents += 1; - this.update.timing += timing; - - return this; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeInt(this.nents); - this.name.writeToStream(stream); - this.update.writeToStream(stream); - } + public DataEntityPerClass() {} - public static DataEntityPerClass readFromStream(ByteArrayDataInput stream){ - DataEntityPerClass retVal = new DataEntityPerClass(); - retVal.nents = stream.readInt(); - retVal.name = CachedString.readFromStream(stream); - retVal.update = DataTiming.readFromStream(stream); - return retVal; - } + public DataEntityPerClass(String name) { + this.name = new CachedString(name); + this.nents = 0; + this.update = new DataTiming(); + } - @Override - public int compareTo(Object o) { - return this.update.compareTo(((DataEntityPerClass)o).update); - } - + public DataEntityPerClass add(Double timing) { + this.nents += 1; + this.update.timing += timing; + + return this; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeInt(this.nents); + this.name.writeToStream(stream); + this.update.writeToStream(stream); + } + + public static DataEntityPerClass readFromStream(ByteArrayDataInput stream) { + DataEntityPerClass retVal = new DataEntityPerClass(); + retVal.nents = stream.readInt(); + retVal.name = CachedString.readFromStream(stream); + retVal.update = DataTiming.readFromStream(stream); + return retVal; + } + + @Override + public int compareTo(Object o) { + return this.update.compareTo(((DataEntityPerClass) o).update); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataError.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataError.java index 4480ca2..09a47db 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataError.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataError.java @@ -1,21 +1,15 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; public class DataError implements ISerializable { - @Override - public void writeToStream(ByteArrayDataOutput stream){ - } + @Override + public void writeToStream(ByteArrayDataOutput stream) {} - public static DataError readFromStream(ByteArrayDataInput stream){ - return new DataError(); - } + public static DataError readFromStream(ByteArrayDataInput stream) { + return new DataError(); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEvent.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEvent.java index 94d12ae..e78c98a 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEvent.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataEvent.java @@ -1,74 +1,69 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - import com.google.common.collect.Table.Cell; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class DataEvent implements ISerializable, Comparable { - public CachedString event; - public CachedString handler; - public CachedString package_; - public CachedString mod; - public long nCalls; - public DataTiming update; - - public DataEvent fill(Cell cellData, String modName){ - /* - String handlerName = cell.getColumnKey().getSimpleName(); - try { - String[] splitHandler = handlerName.split("_"); - handlerName = splitHandler[2] + "." + splitHandler[3]; - } catch (Exception e){} - */ - String[] nameRaw = cellData.getColumnKey().split("\\|"); - - String handlerName = nameRaw[1]; - try { - String[] splitHandler = handlerName.split("_"); - handlerName = splitHandler[2] + "." + splitHandler[3]; - } catch (Exception e){} - - this.package_= new CachedString(nameRaw[0]); - this.handler = new CachedString(handlerName); - this.event = new CachedString(cellData.getRowKey().getName().replace("net.minecraftforge.event.", "")); - this.nCalls = cellData.getValue().getN(); - this.mod = new CachedString(modName); - - this.update = new DataTiming(cellData.getValue().getGeometricMean()); - return this; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - this.event.writeToStream(stream); - this.package_.writeToStream(stream); - this.handler.writeToStream(stream); - this.update.writeToStream(stream); - this.mod.writeToStream(stream); - stream.writeLong(this.nCalls); - } + public CachedString event; + public CachedString handler; + public CachedString package_; + public CachedString mod; + public long nCalls; + public DataTiming update; - public static DataEvent readFromStream(ByteArrayDataInput stream){ - DataEvent retVal = new DataEvent(); - retVal.event = CachedString.readFromStream(stream); - retVal.package_= CachedString.readFromStream(stream); - retVal.handler = CachedString.readFromStream(stream); - retVal.update = DataTiming.readFromStream(stream); - retVal.mod = CachedString.readFromStream(stream); - retVal.nCalls = stream.readLong(); - return retVal; - } + public DataEvent fill(Cell cellData, String modName) { + /* + String handlerName = cell.getColumnKey().getSimpleName(); + try { + String[] splitHandler = handlerName.split("_"); + handlerName = splitHandler[2] + "." + splitHandler[3]; + } catch (Exception e){} + */ + String[] nameRaw = cellData.getColumnKey().split("\\|"); - @Override - public int compareTo(Object o) { - return this.update.compareTo(((DataEvent)o).update); - } + String handlerName = nameRaw[1]; + try { + String[] splitHandler = handlerName.split("_"); + handlerName = splitHandler[2] + "." + splitHandler[3]; + } catch (Exception e) { + } + + this.package_ = new CachedString(nameRaw[0]); + this.handler = new CachedString(handlerName); + this.event = new CachedString(cellData.getRowKey().getName().replace("net.minecraftforge.event.", "")); + this.nCalls = cellData.getValue().getN(); + this.mod = new CachedString(modName); + + this.update = new DataTiming(cellData.getValue().getGeometricMean()); + return this; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.event.writeToStream(stream); + this.package_.writeToStream(stream); + this.handler.writeToStream(stream); + this.update.writeToStream(stream); + this.mod.writeToStream(stream); + stream.writeLong(this.nCalls); + } + + public static DataEvent readFromStream(ByteArrayDataInput stream) { + DataEvent retVal = new DataEvent(); + retVal.event = CachedString.readFromStream(stream); + retVal.package_ = CachedString.readFromStream(stream); + retVal.handler = CachedString.readFromStream(stream); + retVal.update = DataTiming.readFromStream(stream); + retVal.mod = CachedString.readFromStream(stream); + retVal.nCalls = stream.readLong(); + return retVal; + } + + @Override + public int compareTo(Object o) { + return this.update.compareTo(((DataEvent) o).update); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataNetworkTick.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataNetworkTick.java index c9582a4..18749a0 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataNetworkTick.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataNetworkTick.java @@ -1,42 +1,36 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.profilers.ProfilerNetworkTick; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class DataNetworkTick implements ISerializable, Comparable { - public DataTiming update; - - public DataNetworkTick fill(){ + public DataTiming update; - DescriptiveStatistics data = ((ProfilerNetworkTick)(ProfilerSection.NETWORK_TICK.getProfiler())).data; - this.update = new DataTiming(data.getN() != 0 ? data.getGeometricMean() : 0.0D); - - return this; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - this.update.writeToStream(stream); - } + public DataNetworkTick fill() { - public static DataNetworkTick readFromStream(ByteArrayDataInput stream){ - DataNetworkTick retVal = new DataNetworkTick(); - retVal.update = DataTiming.readFromStream(stream); - return retVal; - } + DescriptiveStatistics data = ((ProfilerNetworkTick) (ProfilerSection.NETWORK_TICK.getProfiler())).data; + this.update = new DataTiming(data.getN() != 0 ? data.getGeometricMean() : 0.0D); - @Override - public int compareTo(Object o) { - return this.update.compareTo(((DataNetworkTick)o).update); - } + return this; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.update.writeToStream(stream); + } + + public static DataNetworkTick readFromStream(ByteArrayDataInput stream) { + DataNetworkTick retVal = new DataNetworkTick(); + retVal.update = DataTiming.readFromStream(stream); + return retVal; + } + + @Override + public int compareTo(Object o) { + return this.update.compareTo(((DataNetworkTick) o).update); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataPacket.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataPacket.java index 72a73ab..bd3fc97 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataPacket.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataPacket.java @@ -1,74 +1,63 @@ package mcp.mobius.opis.data.holders.newtypes; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import net.minecraft.network.Packet; -import net.minecraft.network.PacketBuffer; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; +import net.minecraft.network.Packet; -public class DataPacket implements ISerializable{ - public int id; - public DataByteSize size; - public DataByteRate rate; - public DataAmountRate amount; - public CachedString type; - - public DataPacket(){ - } - - public DataPacket(Packet packet){ - this.type = new CachedString(packet.getClass().getSimpleName()); - this.size = new DataByteSize(0); - this.rate = new DataByteRate(0, 5); - this.amount = new DataAmountRate(0, 5); - } +public class DataPacket implements ISerializable { + public int id; + public DataByteSize size; + public DataByteRate rate; + public DataAmountRate amount; + public CachedString type; - public DataPacket fill(Packet packet, int pktsize){ - /* - PacketBuffer buff = new PacketBuffer(Unpooled.buffer()); - int pktsize = 0; - try{ - packet.writePacketData(buff); - pktsize = buff.readableBytes(); - } catch (Exception e){ - - } - */ - this.size.size += pktsize; - this.rate.size += pktsize; - this.amount.size += 1; - return this; - } - - public void startInterval(){ - this.rate.reset(); - this.amount.reset(); - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - this.size.writeToStream(stream); - this.rate.writeToStream(stream); - this.amount.writeToStream(stream); - this.type.writeToStream(stream); - } + public DataPacket() {} - public static DataPacket readFromStream(ByteArrayDataInput stream){ - DataPacket retVal = new DataPacket(); - retVal.size = DataByteSize.readFromStream(stream); - retVal.rate = DataByteRate.readFromStream(stream); - retVal.amount = DataAmountRate.readFromStream(stream); - retVal.type = CachedString.readFromStream(stream); + public DataPacket(Packet packet) { + this.type = new CachedString(packet.getClass().getSimpleName()); + this.size = new DataByteSize(0); + this.rate = new DataByteRate(0, 5); + this.amount = new DataAmountRate(0, 5); + } - return retVal; - } + public DataPacket fill(Packet packet, int pktsize) { + /* + PacketBuffer buff = new PacketBuffer(Unpooled.buffer()); + int pktsize = 0; + try{ + packet.writePacketData(buff); + pktsize = buff.readableBytes(); + } catch (Exception e){ + + } + */ + this.size.size += pktsize; + this.rate.size += pktsize; + this.amount.size += 1; + return this; + } + + public void startInterval() { + this.rate.reset(); + this.amount.reset(); + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.size.writeToStream(stream); + this.rate.writeToStream(stream); + this.amount.writeToStream(stream); + this.type.writeToStream(stream); + } + + public static DataPacket readFromStream(ByteArrayDataInput stream) { + DataPacket retVal = new DataPacket(); + retVal.size = DataByteSize.readFromStream(stream); + retVal.rate = DataByteRate.readFromStream(stream); + retVal.amount = DataAmountRate.readFromStream(stream); + retVal.type = CachedString.readFromStream(stream); + + return retVal; + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataPacket250.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataPacket250.java index 67d87f4..ff53025 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataPacket250.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataPacket250.java @@ -1,57 +1,52 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import cpw.mods.fml.common.network.internal.FMLProxyPacket; import mcp.mobius.opis.data.holders.ISerializable; -public class DataPacket250 implements ISerializable{ - public CachedString channel; - public DataByteSize size; - public DataByteRate rate; - public DataAmountRate amount; +public class DataPacket250 implements ISerializable { + public CachedString channel; + public DataByteSize size; + public DataByteRate rate; + public DataAmountRate amount; - public DataPacket250(){ } - - public DataPacket250(String channel){ - this.channel = new CachedString(channel); - this.size = new DataByteSize(0); - this.rate = new DataByteRate(0, 5); - this.amount = new DataAmountRate(0, 5); - } - - public DataPacket250 fill(FMLProxyPacket packet, int pktsize){ - this.size.size += pktsize; - this.rate.size += pktsize; - this.amount.size += 1; - return this; - } - - public void startInterval(){ - this.rate.reset(); - this.amount.reset(); - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - this.channel.writeToStream(stream); - this.size.writeToStream(stream); - this.rate.writeToStream(stream); - this.amount.writeToStream(stream); - } + public DataPacket250() {} - public static DataPacket250 readFromStream(ByteArrayDataInput stream){ - DataPacket250 retVal = new DataPacket250(); - retVal.channel = CachedString.readFromStream(stream); - retVal.size = DataByteSize.readFromStream(stream); - retVal.rate = DataByteRate.readFromStream(stream); - retVal.amount = DataAmountRate.readFromStream(stream); + public DataPacket250(String channel) { + this.channel = new CachedString(channel); + this.size = new DataByteSize(0); + this.rate = new DataByteRate(0, 5); + this.amount = new DataAmountRate(0, 5); + } - return retVal; - } -} \ No newline at end of file + public DataPacket250 fill(FMLProxyPacket packet, int pktsize) { + this.size.size += pktsize; + this.rate.size += pktsize; + this.amount.size += 1; + return this; + } + + public void startInterval() { + this.rate.reset(); + this.amount.reset(); + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.channel.writeToStream(stream); + this.size.writeToStream(stream); + this.rate.writeToStream(stream); + this.amount.writeToStream(stream); + } + + public static DataPacket250 readFromStream(ByteArrayDataInput stream) { + DataPacket250 retVal = new DataPacket250(); + retVal.channel = CachedString.readFromStream(stream); + retVal.size = DataByteSize.readFromStream(stream); + retVal.rate = DataByteRate.readFromStream(stream); + retVal.amount = DataAmountRate.readFromStream(stream); + + return retVal; + } +} diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataStringUpdate.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataStringUpdate.java index 5e4bfc6..9e8f10d 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataStringUpdate.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataStringUpdate.java @@ -1,35 +1,28 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; public class DataStringUpdate implements ISerializable { - public String str; - public int index; + public String str; + public int index; - public DataStringUpdate(){} - - public DataStringUpdate(String str, int index){ - this.str = str; - this.index = index; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeUTF(this.str); - stream.writeInt(this.index); + public DataStringUpdate() {} - } + public DataStringUpdate(String str, int index) { + this.str = str; + this.index = index; + } - public static DataStringUpdate readFromStream(ByteArrayDataInput stream){ - return new DataStringUpdate(stream.readUTF(), stream.readInt()); - } - + @Override + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeUTF(this.str); + stream.writeInt(this.index); + } + + public static DataStringUpdate readFromStream(ByteArrayDataInput stream) { + return new DataStringUpdate(stream.readUTF(), stream.readInt()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataThread.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataThread.java index 57cb558..5fee7cf 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataThread.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataThread.java @@ -1,36 +1,29 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; -public class DataThread implements ISerializable{ +public class DataThread implements ISerializable { - public CachedString name; - public CachedString clzz; - - public DataThread fill(Thread thread){ - this.name = new CachedString(thread.getName()); - this.clzz = new CachedString(thread.getClass().getSimpleName()); - return this; - } - - public void writeToStream(ByteArrayDataOutput stream){ - this.name.writeToStream(stream); - this.clzz.writeToStream(stream); - - } - - public static DataThread readFromStream(ByteArrayDataInput stream){ - DataThread retVal = new DataThread(); - retVal.name = CachedString.readFromStream(stream); - retVal.clzz = CachedString.readFromStream(stream); - return retVal; - } - + public CachedString name; + public CachedString clzz; + + public DataThread fill(Thread thread) { + this.name = new CachedString(thread.getName()); + this.clzz = new CachedString(thread.getClass().getSimpleName()); + return this; + } + + public void writeToStream(ByteArrayDataOutput stream) { + this.name.writeToStream(stream); + this.clzz.writeToStream(stream); + } + + public static DataThread readFromStream(ByteArrayDataInput stream) { + DataThread retVal = new DataThread(); + retVal.name = CachedString.readFromStream(stream); + retVal.clzz = CachedString.readFromStream(stream); + return retVal; + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTileEntity.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTileEntity.java index 2969e08..5ff0819 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTileEntity.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTileEntity.java @@ -1,63 +1,55 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.DimensionManager; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; +import net.minecraft.tileentity.TileEntity; public class DataTileEntity implements ISerializable { - public CachedString clazz; - public CoordinatesBlock pos; - public int hashCode; - public boolean isValid; - public CachedString cause; - - public DataTileEntity fill(TileEntity tileEntity, String cause){ - this.pos = new CoordinatesBlock(tileEntity.getWorldObj().provider.dimensionId, tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); - this.clazz = new CachedString(tileEntity.getClass().getCanonicalName()); - this.hashCode = System.identityHashCode(tileEntity); - this.isValid = !tileEntity.isInvalid(); - this.cause = new CachedString(cause); - return this; - } - - /* - public DataTileEntity fill(CoordinatesBlock coord, String clazz, int hashCode, boolean isInvalid){ - this.pos = coord; - this.clazz = new CachedString(clazz); - this.hashCode = hashCode; - this.isValid = !isInvalid; - return this; - } - */ - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - this.clazz.writeToStream(stream); - this.pos.writeToStream(stream); - this.cause.writeToStream(stream); - stream.writeInt(this.hashCode); - stream.writeBoolean(this.isValid); - - } + public CachedString clazz; + public CoordinatesBlock pos; + public int hashCode; + public boolean isValid; + public CachedString cause; - public static DataTileEntity readFromStream(ByteArrayDataInput stream){ - DataTileEntity retVal = new DataTileEntity(); - retVal.clazz = CachedString.readFromStream(stream); - retVal.pos = CoordinatesBlock.readFromStream(stream); - retVal.cause = CachedString.readFromStream(stream); - retVal.hashCode = stream.readInt(); - retVal.isValid = stream.readBoolean(); - return retVal; - } + public DataTileEntity fill(TileEntity tileEntity, String cause) { + this.pos = new CoordinatesBlock( + tileEntity.getWorldObj().provider.dimensionId, tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); + this.clazz = new CachedString(tileEntity.getClass().getCanonicalName()); + this.hashCode = System.identityHashCode(tileEntity); + this.isValid = !tileEntity.isInvalid(); + this.cause = new CachedString(cause); + return this; + } + /* + public DataTileEntity fill(CoordinatesBlock coord, String clazz, int hashCode, boolean isInvalid){ + this.pos = coord; + this.clazz = new CachedString(clazz); + this.hashCode = hashCode; + this.isValid = !isInvalid; + return this; + } + */ + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.clazz.writeToStream(stream); + this.pos.writeToStream(stream); + this.cause.writeToStream(stream); + stream.writeInt(this.hashCode); + stream.writeBoolean(this.isValid); + } + + public static DataTileEntity readFromStream(ByteArrayDataInput stream) { + DataTileEntity retVal = new DataTileEntity(); + retVal.clazz = CachedString.readFromStream(stream); + retVal.pos = CoordinatesBlock.readFromStream(stream); + retVal.cause = CachedString.readFromStream(stream); + retVal.hashCode = stream.readInt(); + retVal.isValid = stream.readBoolean(); + return retVal; + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTileEntityRender.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTileEntityRender.java index 7dd4c41..1e1f0c6 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTileEntityRender.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTileEntityRender.java @@ -1,5 +1,6 @@ package mcp.mobius.opis.data.holders.newtypes; +import java.util.WeakHashMap; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.profilers.ProfilerRenderTileEntity; @@ -9,21 +10,19 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; -import java.util.WeakHashMap; - public class DataTileEntityRender extends DataBlockTileEntity { - public DataTileEntityRender fill(TileEntity ent){ - this.pos = new CoordinatesBlock(ent.getWorldObj().provider.dimensionId, ent.xCoord, ent.yCoord, ent.zCoord); - World world = Minecraft.getMinecraft().theWorld; //DimensionManager.getWorld(this.pos.dim); - - this.id = (short) Block.getIdFromBlock(world.getBlock(this.pos.x, this.pos.y, this.pos.z)); - this.meta = (short) world.getBlockMetadata(this.pos.x, this.pos.y, this.pos.z); + public DataTileEntityRender fill(TileEntity ent) { + this.pos = new CoordinatesBlock(ent.getWorldObj().provider.dimensionId, ent.xCoord, ent.yCoord, ent.zCoord); + World world = Minecraft.getMinecraft().theWorld; // DimensionManager.getWorld(this.pos.dim); - WeakHashMap data = ((ProfilerRenderTileEntity)(ProfilerSection.RENDER_TILEENTITY.getProfiler())).data; - this.update = new DataTiming(data.containsKey(ent) ? data.get(ent).getGeometricMean() : 0.0D); - - return this; - } - + this.id = (short) Block.getIdFromBlock(world.getBlock(this.pos.x, this.pos.y, this.pos.z)); + this.meta = (short) world.getBlockMetadata(this.pos.x, this.pos.y, this.pos.z); + + WeakHashMap data = + ((ProfilerRenderTileEntity) (ProfilerSection.RENDER_TILEENTITY.getProfiler())).data; + this.update = new DataTiming(data.containsKey(ent) ? data.get(ent).getGeometricMean() : 0.0D); + + return this; + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTiming.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTiming.java index a0b9ec9..57a0dd6 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTiming.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTiming.java @@ -1,38 +1,38 @@ package mcp.mobius.opis.data.holders.newtypes; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.ISerializable; -public class DataTiming implements Comparable, ISerializable{ - public Double timing; +public class DataTiming implements Comparable, ISerializable { + public Double timing; - public DataTiming(){ this.timing = 0.0D; } - public DataTiming(double timing){ this.timing = timing; } - - @Override - public int compareTo(Object o) { - return ((DataTiming)o).timing.compareTo(this.timing); // Reverse order ! Put higher values FIRST - } - - public DataTimingMillisecond asMillisecond(){ - return new DataTimingMillisecond(this.timing); - } - - public String toString(){ - return String.format("%.3f µs", this.timing / 1000.0); - } - - public void writeToStream(ByteArrayDataOutput stream){ - stream.writeDouble(this.timing); - } - - public static DataTiming readFromStream(ByteArrayDataInput stream){ - return new DataTiming(stream.readDouble()); - } + public DataTiming() { + this.timing = 0.0D; + } + + public DataTiming(double timing) { + this.timing = timing; + } + + @Override + public int compareTo(Object o) { + return ((DataTiming) o).timing.compareTo(this.timing); // Reverse order ! Put higher values FIRST + } + + public DataTimingMillisecond asMillisecond() { + return new DataTimingMillisecond(this.timing); + } + + public String toString() { + return String.format("%.3f µs", this.timing / 1000.0); + } + + public void writeToStream(ByteArrayDataOutput stream) { + stream.writeDouble(this.timing); + } + + public static DataTiming readFromStream(ByteArrayDataInput stream) { + return new DataTiming(stream.readDouble()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTimingMillisecond.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTimingMillisecond.java index 8565306..f2590b0 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTimingMillisecond.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/DataTimingMillisecond.java @@ -6,19 +6,23 @@ import java.io.IOException; public class DataTimingMillisecond extends DataTiming { - public DataTimingMillisecond(){ this.timing = 0.0D; } - public DataTimingMillisecond(double timing){ this.timing = timing; } - - public String toString(){ - return String.format("%.3f ms", this.timing / 1000.0 / 1000.0); - } - - public void writeToStream(DataOutputStream stream) throws IOException{ - stream.writeDouble(this.timing); - } - - public static DataTimingMillisecond readFromStream(DataInputStream stream) throws IOException { - return new DataTimingMillisecond(stream.readDouble()); - } - + public DataTimingMillisecond() { + this.timing = 0.0D; + } + + public DataTimingMillisecond(double timing) { + this.timing = timing; + } + + public String toString() { + return String.format("%.3f ms", this.timing / 1000.0 / 1000.0); + } + + public void writeToStream(DataOutputStream stream) throws IOException { + stream.writeDouble(this.timing); + } + + public static DataTimingMillisecond readFromStream(DataInputStream stream) throws IOException { + return new DataTimingMillisecond(stream.readDouble()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/NexusAuth.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/NexusAuth.java index 51d0c05..1d26909 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/NexusAuth.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/NexusAuth.java @@ -1,48 +1,41 @@ package mcp.mobius.opis.data.holders.newtypes; -import mcp.mobius.opis.data.holders.ISerializable; -import mcp.mobius.opis.data.holders.basetypes.SerialInt; -import mcp.mobius.opis.data.holders.basetypes.SerialLong; -import mcp.mobius.opis.data.holders.basetypes.SerialString; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; +import mcp.mobius.opis.data.holders.ISerializable; +import mcp.mobius.opis.data.holders.basetypes.SerialString; public class NexusAuth implements ISerializable { - SerialString uuid; - SerialString passphrase; - boolean reconnect; - long timestamp; - - public NexusAuth(String uuid, String passphrase, boolean reconnect){ - this.uuid = new SerialString(uuid); - this.passphrase = new SerialString(passphrase); - this.reconnect = reconnect; - this.timestamp = System.currentTimeMillis(); - } - - public NexusAuth(SerialString uuid, SerialString passphrase, boolean reconnect){ - this.uuid = uuid; - this.passphrase = passphrase; - this.reconnect = reconnect; - this.timestamp = System.currentTimeMillis(); - } - - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - this.uuid.writeToStream(stream); - this.passphrase.writeToStream(stream); - stream.writeBoolean(reconnect); - stream.writeLong(this.timestamp); - } - - public static NexusAuth readFromStream(ByteArrayDataInput stream){ - return new NexusAuth( - SerialString.readFromStream(stream), - SerialString.readFromStream(stream), - stream.readBoolean() - ); - } -} \ No newline at end of file + SerialString uuid; + SerialString passphrase; + boolean reconnect; + long timestamp; + + public NexusAuth(String uuid, String passphrase, boolean reconnect) { + this.uuid = new SerialString(uuid); + this.passphrase = new SerialString(passphrase); + this.reconnect = reconnect; + this.timestamp = System.currentTimeMillis(); + } + + public NexusAuth(SerialString uuid, SerialString passphrase, boolean reconnect) { + this.uuid = uuid; + this.passphrase = passphrase; + this.reconnect = reconnect; + this.timestamp = System.currentTimeMillis(); + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.uuid.writeToStream(stream); + this.passphrase.writeToStream(stream); + stream.writeBoolean(reconnect); + stream.writeLong(this.timestamp); + } + + public static NexusAuth readFromStream(ByteArrayDataInput stream) { + return new NexusAuth( + SerialString.readFromStream(stream), SerialString.readFromStream(stream), stream.readBoolean()); + } +} diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/NexusData.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/NexusData.java index f4c25a7..ca613b4 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/NexusData.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/NexusData.java @@ -1,64 +1,65 @@ package mcp.mobius.opis.data.holders.newtypes; -import mcp.mobius.opis.data.holders.ISerializable; -import mcp.mobius.opis.data.holders.basetypes.SerialDouble; -import mcp.mobius.opis.data.holders.basetypes.SerialInt; -import mcp.mobius.opis.data.holders.basetypes.SerialLong; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; +import mcp.mobius.opis.data.holders.ISerializable; +import mcp.mobius.opis.data.holders.basetypes.SerialInt; +import mcp.mobius.opis.data.holders.basetypes.SerialLong; -public class NexusData implements ISerializable { +public class NexusData implements ISerializable { - public SerialLong packetOutbound; - public SerialLong packetInbound; - public SerialInt chunkForced; - public SerialInt chunkLoaded; - public DataTiming timingTick; - public SerialInt amountTileEnts; - public SerialInt amountEntities; - public SerialInt amountPlayers; - long timestamp; - - - public NexusData(SerialLong Packet_Outbound, SerialLong Packet_Inbound, SerialInt Chunk_Forced, SerialInt Chunk_Loaded, - DataTiming Timing_Tick, SerialInt Amount_TileEnts, SerialInt Amount_Entities, SerialInt Amount_Players - ){ - this.packetOutbound = Packet_Outbound; - this.packetInbound = Packet_Inbound; - this.chunkForced = Chunk_Forced; - this.chunkLoaded = Chunk_Loaded; - this.timingTick = Timing_Tick; - this.amountTileEnts = Amount_TileEnts; - this.amountEntities = Amount_Entities; - this.amountPlayers = Amount_Players; - this.timestamp = System.currentTimeMillis(); - } - - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - this.packetOutbound.writeToStream(stream); - this.packetInbound.writeToStream(stream); - this.chunkForced.writeToStream(stream); - this.chunkLoaded.writeToStream(stream); - this.timingTick.writeToStream(stream); - this.amountTileEnts.writeToStream(stream); - this.amountEntities.writeToStream(stream); - this.amountPlayers.writeToStream(stream); - stream.writeLong(this.timestamp); - } + public SerialLong packetOutbound; + public SerialLong packetInbound; + public SerialInt chunkForced; + public SerialInt chunkLoaded; + public DataTiming timingTick; + public SerialInt amountTileEnts; + public SerialInt amountEntities; + public SerialInt amountPlayers; + long timestamp; - public static NexusData readFromStream(ByteArrayDataInput stream){ - return new NexusData( - SerialLong.readFromStream(stream), - SerialLong.readFromStream(stream), - SerialInt.readFromStream(stream), - SerialInt.readFromStream(stream), - DataTiming.readFromStream(stream), - SerialInt.readFromStream(stream), - SerialInt.readFromStream(stream), - SerialInt.readFromStream(stream) - ); - } + public NexusData( + SerialLong Packet_Outbound, + SerialLong Packet_Inbound, + SerialInt Chunk_Forced, + SerialInt Chunk_Loaded, + DataTiming Timing_Tick, + SerialInt Amount_TileEnts, + SerialInt Amount_Entities, + SerialInt Amount_Players) { + this.packetOutbound = Packet_Outbound; + this.packetInbound = Packet_Inbound; + this.chunkForced = Chunk_Forced; + this.chunkLoaded = Chunk_Loaded; + this.timingTick = Timing_Tick; + this.amountTileEnts = Amount_TileEnts; + this.amountEntities = Amount_Entities; + this.amountPlayers = Amount_Players; + this.timestamp = System.currentTimeMillis(); + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.packetOutbound.writeToStream(stream); + this.packetInbound.writeToStream(stream); + this.chunkForced.writeToStream(stream); + this.chunkLoaded.writeToStream(stream); + this.timingTick.writeToStream(stream); + this.amountTileEnts.writeToStream(stream); + this.amountEntities.writeToStream(stream); + this.amountPlayers.writeToStream(stream); + stream.writeLong(this.timestamp); + } + + public static NexusData readFromStream(ByteArrayDataInput stream) { + return new NexusData( + SerialLong.readFromStream(stream), + SerialLong.readFromStream(stream), + SerialInt.readFromStream(stream), + SerialInt.readFromStream(stream), + DataTiming.readFromStream(stream), + SerialInt.readFromStream(stream), + SerialInt.readFromStream(stream), + SerialInt.readFromStream(stream)); + } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/newtypes/PlayerStatus.java b/src/main/java/mcp/mobius/opis/data/holders/newtypes/PlayerStatus.java index 00e40da..d581c88 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/newtypes/PlayerStatus.java +++ b/src/main/java/mcp/mobius/opis/data/holders/newtypes/PlayerStatus.java @@ -1,42 +1,39 @@ package mcp.mobius.opis.data.holders.newtypes; -import mcp.mobius.opis.data.holders.ISerializable; -import mcp.mobius.opis.data.holders.basetypes.SerialString; -import mcp.mobius.opis.network.enums.PlayerEv; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; +import mcp.mobius.opis.data.holders.ISerializable; +import mcp.mobius.opis.network.enums.PlayerEv; public class PlayerStatus implements ISerializable { public CachedString name; - public PlayerEv status; - public int x, y, z, dim; - public long timestamp; + public PlayerEv status; + public int x, y, z, dim; + public long timestamp; - public PlayerStatus(String name_, PlayerEv status, int dim, int x, int y, int z){ - this.name = new CachedString(name_); - this.status = status; - this.dim = dim; - this.x = x; - this.y = y; - this.z = z; + public PlayerStatus(String name_, PlayerEv status, int dim, int x, int y, int z) { + this.name = new CachedString(name_); + this.status = status; + this.dim = dim; + this.x = x; + this.y = y; + this.z = z; this.timestamp = System.currentTimeMillis(); } - public PlayerStatus(CachedString name, PlayerEv status, int dim, int x, int y, int z, long timestamp){ - this.name = name; - this.status = status; - this.dim = dim; - this.x = x; - this.y = y; - this.z = z; + public PlayerStatus(CachedString name, PlayerEv status, int dim, int x, int y, int z, long timestamp) { + this.name = name; + this.status = status; + this.dim = dim; + this.x = x; + this.y = y; + this.z = z; this.timestamp = timestamp; } - @Override - public void writeToStream(ByteArrayDataOutput stream){ + public void writeToStream(ByteArrayDataOutput stream) { this.name.writeToStream(stream); stream.writeInt(this.status.ordinal()); stream.writeInt(this.dim); @@ -46,7 +43,7 @@ public class PlayerStatus implements ISerializable { stream.writeLong(this.timestamp); } - public static PlayerStatus readFromStream(ByteArrayDataInput stream){ + public static PlayerStatus readFromStream(ByteArrayDataInput stream) { return new PlayerStatus( CachedString.readFromStream(stream), PlayerEv.values()[stream.readInt()], @@ -54,7 +51,6 @@ public class PlayerStatus implements ISerializable { stream.readInt(), stream.readInt(), stream.readInt(), - stream.readLong() - ); + stream.readLong()); } } diff --git a/src/main/java/mcp/mobius/opis/data/holders/stats/StatAbstract.java b/src/main/java/mcp/mobius/opis/data/holders/stats/StatAbstract.java index a67b1f1..c9f32e5 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/stats/StatAbstract.java +++ b/src/main/java/mcp/mobius/opis/data/holders/stats/StatAbstract.java @@ -1,93 +1,91 @@ package mcp.mobius.opis.data.holders.stats; -import java.io.DataOutputStream; -import java.io.IOException; - +import com.google.common.io.ByteArrayDataOutput; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; - import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; -import com.google.common.io.ByteArrayDataOutput; +public abstract class StatAbstract implements Comparable, ISerializable { + protected DescriptiveStatistics dstat = new DescriptiveStatistics(); + public Long dataPoints = 0L; + protected Double geomMean = null; + protected Double dataSum = null; + protected CoordinatesBlock coord = CoordinatesBlock.INVALID; + protected CoordinatesChunk chunk = CoordinatesChunk.INVALID; + protected String name; -public abstract class StatAbstract implements Comparable, ISerializable{ - protected DescriptiveStatistics dstat = new DescriptiveStatistics(); - public Long dataPoints = 0L; - protected Double geomMean = null; - protected Double dataSum = null; - protected CoordinatesBlock coord = CoordinatesBlock.INVALID; - protected CoordinatesChunk chunk = CoordinatesChunk.INVALID; - protected String name; - - /* - public StatAbstract(){ - dstat = new DescriptiveStatistics(); - } + /* + public StatAbstract(){ + dstat = new DescriptiveStatistics(); + } - public StatAbstract(int points){ - dstat = new DescriptiveStatistics(points); - } - */ - - public void addMeasure(long timing){ - //this.dstat.addValue((double)timing/1000.0); - this.dstat.addValue((double)timing/1000.); - dataPoints += 1; - } - - public void addMeasure(double timing){ - this.dstat.addValue(timing); - dataPoints += 1; - } - - public double getGeometricMean(){ - if (geomMean != null) - return geomMean; - else - return dstat.getGeometricMean(); - } - - public void setGeometricMean(double value){ - this.geomMean = value; - } - - public double getDataSum(){ - if (dataSum != null) - return dataSum; - else - return dstat.getSum(); - } - - public void setDataSum(double value){ - this.dataSum = value; - } - - public long getDataPoints(){ - return this.dataPoints; - } - - public void setDataPoints(long ndata){ - this.dataPoints = ndata; - } - - @Override - public int compareTo(Object o) { - double value = ((StatAbstract)o).getGeometricMean() - this.getGeometricMean(); - if (value > 0) - return 1; - if (value < 0) - return -1; - return 0; - } - - public String getName(){ return this.name; }; - - public CoordinatesBlock getCoordinates() {return this.coord;} - public CoordinatesChunk getChunk() {return this.chunk;} - public CoordinatesBlock getTeleportTarget(){return this.coord;} - - - public abstract void writeToStream(ByteArrayDataOutput stream); + public StatAbstract(int points){ + dstat = new DescriptiveStatistics(points); + } + */ + public void addMeasure(long timing) { + // this.dstat.addValue((double)timing/1000.0); + this.dstat.addValue((double) timing / 1000.); + dataPoints += 1; + } + + public void addMeasure(double timing) { + this.dstat.addValue(timing); + dataPoints += 1; + } + + public double getGeometricMean() { + if (geomMean != null) return geomMean; + else return dstat.getGeometricMean(); + } + + public void setGeometricMean(double value) { + this.geomMean = value; + } + + public double getDataSum() { + if (dataSum != null) return dataSum; + else return dstat.getSum(); + } + + public void setDataSum(double value) { + this.dataSum = value; + } + + public long getDataPoints() { + return this.dataPoints; + } + + public void setDataPoints(long ndata) { + this.dataPoints = ndata; + } + + @Override + public int compareTo(Object o) { + double value = ((StatAbstract) o).getGeometricMean() - this.getGeometricMean(); + if (value > 0) return 1; + if (value < 0) return -1; + return 0; + } + + public String getName() { + return this.name; + } + ; + + public CoordinatesBlock getCoordinates() { + return this.coord; + } + + public CoordinatesChunk getChunk() { + return this.chunk; + } + + public CoordinatesBlock getTeleportTarget() { + return this.coord; + } + + public abstract void writeToStream(ByteArrayDataOutput stream); } diff --git a/src/main/java/mcp/mobius/opis/data/holders/stats/StatsChunk.java b/src/main/java/mcp/mobius/opis/data/holders/stats/StatsChunk.java index f88c630..885bc19 100644 --- a/src/main/java/mcp/mobius/opis/data/holders/stats/StatsChunk.java +++ b/src/main/java/mcp/mobius/opis/data/holders/stats/StatsChunk.java @@ -1,74 +1,67 @@ package mcp.mobius.opis.data.holders.stats; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; -public class StatsChunk extends StatAbstract{ - public int tileEntities = 0; - public int entities = 0; - - public StatsChunk(){} - - public StatsChunk(CoordinatesChunk chunk){ - this.chunk = chunk; - this.coord = chunk.asCoordinatesBlock(); - } +public class StatsChunk extends StatAbstract { + public int tileEntities = 0; + public int entities = 0; - public StatsChunk(CoordinatesChunk chunk, int tileEntities, int entities){ - this.chunk = chunk; - this.coord = chunk.asCoordinatesBlock(); - this.tileEntities = tileEntities; - this.entities = entities; - } - - public StatsChunk(CoordinatesChunk chunk, int tileEntities, int entities, double time){ - this.chunk = chunk; - this.coord = chunk.asCoordinatesBlock(); - this.tileEntities = tileEntities; - this.entities = entities; - this.setDataSum(time); - } - - public void addTileEntity(){ - this.tileEntities += 1; - } - - public void addEntity(){ - this.entities += 1; - } - - @Override - public void writeToStream(ByteArrayDataOutput stream){ - this.chunk.writeToStream(stream); - stream.writeInt(this.tileEntities); - stream.writeInt(this.entities); - stream.writeDouble(this.getDataSum()); - } + public StatsChunk() {} - public static StatsChunk readFromStream(ByteArrayDataInput stream){ - CoordinatesChunk chunk = CoordinatesChunk.readFromStream(stream); - StatsChunk chunkStats = new StatsChunk(chunk, stream.readInt(), stream.readInt()); - chunkStats.setDataSum(stream.readDouble()); - return chunkStats; - } - - @Override - public int compareTo(Object o) { - double value = ((StatAbstract)o).getDataSum() - this.getDataSum(); - if (value > 0) - return 1; - if (value < 0) - return -1; - return 0; - } - - public String toString(){ - return String.format("%.3f µs", this.getDataSum()/1000.0); - } + public StatsChunk(CoordinatesChunk chunk) { + this.chunk = chunk; + this.coord = chunk.asCoordinatesBlock(); + } + + public StatsChunk(CoordinatesChunk chunk, int tileEntities, int entities) { + this.chunk = chunk; + this.coord = chunk.asCoordinatesBlock(); + this.tileEntities = tileEntities; + this.entities = entities; + } + + public StatsChunk(CoordinatesChunk chunk, int tileEntities, int entities, double time) { + this.chunk = chunk; + this.coord = chunk.asCoordinatesBlock(); + this.tileEntities = tileEntities; + this.entities = entities; + this.setDataSum(time); + } + + public void addTileEntity() { + this.tileEntities += 1; + } + + public void addEntity() { + this.entities += 1; + } + + @Override + public void writeToStream(ByteArrayDataOutput stream) { + this.chunk.writeToStream(stream); + stream.writeInt(this.tileEntities); + stream.writeInt(this.entities); + stream.writeDouble(this.getDataSum()); + } + + public static StatsChunk readFromStream(ByteArrayDataInput stream) { + CoordinatesChunk chunk = CoordinatesChunk.readFromStream(stream); + StatsChunk chunkStats = new StatsChunk(chunk, stream.readInt(), stream.readInt()); + chunkStats.setDataSum(stream.readDouble()); + return chunkStats; + } + + @Override + public int compareTo(Object o) { + double value = ((StatAbstract) o).getDataSum() - this.getDataSum(); + if (value > 0) return 1; + if (value < 0) return -1; + return 0; + } + + public String toString() { + return String.format("%.3f µs", this.getDataSum() / 1000.0); + } } diff --git a/src/main/java/mcp/mobius/opis/data/managers/ChunkManager.java b/src/main/java/mcp/mobius/opis/data/managers/ChunkManager.java index 778a4f8..5ebcae3 100644 --- a/src/main/java/mcp/mobius/opis/data/managers/ChunkManager.java +++ b/src/main/java/mcp/mobius/opis/data/managers/ChunkManager.java @@ -10,8 +10,8 @@ import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; import mcp.mobius.opis.data.holders.basetypes.TicketData; -import mcp.mobius.opis.data.holders.newtypes.DataEntity; import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; +import mcp.mobius.opis.data.holders.newtypes.DataEntity; import mcp.mobius.opis.data.holders.stats.StatsChunk; import mcp.mobius.opis.data.profilers.ProfilerEntityUpdate; import mcp.mobius.opis.data.profilers.ProfilerTileEntityUpdate; @@ -25,157 +25,151 @@ import net.minecraft.world.gen.ChunkProviderServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.ForgeChunkManager.Ticket; -public enum ChunkManager implements IMessageHandler{ - INSTANCE; - - private ArrayList chunksLoad = new ArrayList(); - private HashMap chunkMeanTime = new HashMap(); - public ArrayList tickets = new ArrayList(); +public enum ChunkManager implements IMessageHandler { + INSTANCE; - public void addLoadedChunks(ArrayList data){ - //chunksLoad.clear(); - for (ISerializable chunk : data){ - chunksLoad.add((CoordinatesChunk)chunk); - } - } - - public ArrayList getLoadedChunks(){ - return chunksLoad; - } - - public void setChunkMeanTime(ArrayList data){ - chunkMeanTime.clear(); - for (ISerializable stat : data) - chunkMeanTime.put(((StatsChunk)stat).getChunk(), (StatsChunk)stat); - } - - public HashMap getChunkMeanTime(){ - return chunkMeanTime; - } - - public ArrayList getLoadedChunks(int dimension){ - HashSet chunkStatus = new HashSet(); - WorldServer world = DimensionManager.getWorld(dimension); - if (world != null) - { - for (ChunkCoordIntPair coord : world.getPersistentChunks().keySet()){ - chunkStatus.add(new CoordinatesChunk(dimension, coord, (byte)1)); - } - - for (Object o : ((ChunkProviderServer)world.getChunkProvider()).loadedChunks){ - Chunk chunk = (Chunk)o; - - chunkStatus.add(new CoordinatesChunk(dimension, chunk.getChunkCoordIntPair(), (byte)0)); - } - } - - return new ArrayList(chunkStatus); - } + private ArrayList chunksLoad = new ArrayList(); + private HashMap chunkMeanTime = new HashMap(); + public ArrayList tickets = new ArrayList(); - public HashSet getTickets(){ - HashSet tickets = new HashSet(); - for (int dim : DimensionManager.getIDs()) - for (Ticket ticket : DimensionManager.getWorld(dim).getPersistentChunks().values()) - tickets.add(new TicketData(ticket)); - - return tickets; - } - - public ArrayList getChunksUpdateTime(){ - HashMap chunks = new HashMap(); - - for (CoordinatesBlock coords : ((ProfilerTileEntityUpdate)ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()){ - DataBlockTileEntity data = new DataBlockTileEntity().fill(coords); - CoordinatesChunk chunk = data.pos.asCoordinatesChunk(); - - if (!chunks.containsKey(chunk)) - chunks.put(chunk, new StatsChunk(chunk)); - - chunks.get(chunk).addTileEntity(); - chunks.get(chunk).addMeasure(data.update.timing); - - } - - for (Entity entity : ((ProfilerEntityUpdate)ProfilerSection.ENTITY_UPDATETIME.getProfiler()).data.keySet()){ - DataEntity data = new DataEntity().fill(entity); - CoordinatesChunk chunk = data.pos.asCoordinatesChunk(); - - if (!chunks.containsKey(chunk)) - chunks.put(chunk, new StatsChunk(chunk)); - - chunks.get(chunk).addEntity(); - chunks.get(chunk).addMeasure(data.update.timing); - } - - ArrayList chunksUpdate = new ArrayList(chunks.values()); - return chunksUpdate; - } - - public ArrayList getTopChunks(int quantity){ - ArrayList chunks = this.getChunksUpdateTime(); - ArrayList outList = new ArrayList(); - Collections.sort(chunks); - - for (int i = 0; i < Math.min(quantity, chunks.size()); i++) - outList.add(chunks.get(i)); - - return outList; - } + public void addLoadedChunks(ArrayList data) { + // chunksLoad.clear(); + for (ISerializable chunk : data) { + chunksLoad.add((CoordinatesChunk) chunk); + } + } - public int getLoadedChunkAmount(){ - int loadedChunks = 0; - for (WorldServer world : DimensionManager.getWorlds()){ - int loadedChunksForDim = world.getChunkProvider().getLoadedChunkCount(); - loadedChunks += loadedChunksForDim; - //System.out.printf("[ %2d ] %d chunks\n", world.provider.dimensionId, loadedChunksForDim); - } - //System.out.printf("Total : %d chunks\n", loadedChunks); - return loadedChunks; - } - - public int getForcedChunkAmount(){ - int forcedChunks = 0; - for (WorldServer world : DimensionManager.getWorlds()){ - forcedChunks += world.getPersistentChunks().size(); - } - return forcedChunks; - } - - public void purgeChunks(int dim){ - WorldServer world = DimensionManager.getWorld(dim); - if (world == null) return; - - int loadedChunksDelta = 100; - - ((ChunkProviderServer)world.getChunkProvider()).unloadAllChunks(); - - while(loadedChunksDelta >= 100){ - int loadedBefore = world.getChunkProvider().getLoadedChunkCount(); - world.getChunkProvider().unloadQueuedChunks(); - loadedChunksDelta = loadedBefore - world.getChunkProvider().getLoadedChunkCount(); - } - } + public ArrayList getLoadedChunks() { + return chunksLoad; + } - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_TIMING_CHUNK:{ - this.setChunkMeanTime(rawdata.array); - break; - } - case LIST_CHUNK_LOADED:{ - this.addLoadedChunks(rawdata.array); - break; - } - case LIST_CHUNK_LOADED_CLEAR:{ - chunksLoad.clear(); - break; - } - default: - return false; - } - - - return true; - } + public void setChunkMeanTime(ArrayList data) { + chunkMeanTime.clear(); + for (ISerializable stat : data) chunkMeanTime.put(((StatsChunk) stat).getChunk(), (StatsChunk) stat); + } + + public HashMap getChunkMeanTime() { + return chunkMeanTime; + } + + public ArrayList getLoadedChunks(int dimension) { + HashSet chunkStatus = new HashSet(); + WorldServer world = DimensionManager.getWorld(dimension); + if (world != null) { + for (ChunkCoordIntPair coord : world.getPersistentChunks().keySet()) { + chunkStatus.add(new CoordinatesChunk(dimension, coord, (byte) 1)); + } + + for (Object o : ((ChunkProviderServer) world.getChunkProvider()).loadedChunks) { + Chunk chunk = (Chunk) o; + + chunkStatus.add(new CoordinatesChunk(dimension, chunk.getChunkCoordIntPair(), (byte) 0)); + } + } + + return new ArrayList(chunkStatus); + } + + public HashSet getTickets() { + HashSet tickets = new HashSet(); + for (int dim : DimensionManager.getIDs()) + for (Ticket ticket : + DimensionManager.getWorld(dim).getPersistentChunks().values()) tickets.add(new TicketData(ticket)); + + return tickets; + } + + public ArrayList getChunksUpdateTime() { + HashMap chunks = new HashMap(); + + for (CoordinatesBlock coords : + ((ProfilerTileEntityUpdate) ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()) { + DataBlockTileEntity data = new DataBlockTileEntity().fill(coords); + CoordinatesChunk chunk = data.pos.asCoordinatesChunk(); + + if (!chunks.containsKey(chunk)) chunks.put(chunk, new StatsChunk(chunk)); + + chunks.get(chunk).addTileEntity(); + chunks.get(chunk).addMeasure(data.update.timing); + } + + for (Entity entity : ((ProfilerEntityUpdate) ProfilerSection.ENTITY_UPDATETIME.getProfiler()).data.keySet()) { + DataEntity data = new DataEntity().fill(entity); + CoordinatesChunk chunk = data.pos.asCoordinatesChunk(); + + if (!chunks.containsKey(chunk)) chunks.put(chunk, new StatsChunk(chunk)); + + chunks.get(chunk).addEntity(); + chunks.get(chunk).addMeasure(data.update.timing); + } + + ArrayList chunksUpdate = new ArrayList(chunks.values()); + return chunksUpdate; + } + + public ArrayList getTopChunks(int quantity) { + ArrayList chunks = this.getChunksUpdateTime(); + ArrayList outList = new ArrayList(); + Collections.sort(chunks); + + for (int i = 0; i < Math.min(quantity, chunks.size()); i++) outList.add(chunks.get(i)); + + return outList; + } + + public int getLoadedChunkAmount() { + int loadedChunks = 0; + for (WorldServer world : DimensionManager.getWorlds()) { + int loadedChunksForDim = world.getChunkProvider().getLoadedChunkCount(); + loadedChunks += loadedChunksForDim; + // System.out.printf("[ %2d ] %d chunks\n", world.provider.dimensionId, loadedChunksForDim); + } + // System.out.printf("Total : %d chunks\n", loadedChunks); + return loadedChunks; + } + + public int getForcedChunkAmount() { + int forcedChunks = 0; + for (WorldServer world : DimensionManager.getWorlds()) { + forcedChunks += world.getPersistentChunks().size(); + } + return forcedChunks; + } + + public void purgeChunks(int dim) { + WorldServer world = DimensionManager.getWorld(dim); + if (world == null) return; + + int loadedChunksDelta = 100; + + ((ChunkProviderServer) world.getChunkProvider()).unloadAllChunks(); + + while (loadedChunksDelta >= 100) { + int loadedBefore = world.getChunkProvider().getLoadedChunkCount(); + world.getChunkProvider().unloadQueuedChunks(); + loadedChunksDelta = loadedBefore - world.getChunkProvider().getLoadedChunkCount(); + } + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_TIMING_CHUNK: { + this.setChunkMeanTime(rawdata.array); + break; + } + case LIST_CHUNK_LOADED: { + this.addLoadedChunks(rawdata.array); + break; + } + case LIST_CHUNK_LOADED_CLEAR: { + chunksLoad.clear(); + break; + } + default: + return false; + } + + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/data/managers/EntityManager.java b/src/main/java/mcp/mobius/opis/data/managers/EntityManager.java index 1eca2c1..30a11a8 100644 --- a/src/main/java/mcp/mobius/opis/data/managers/EntityManager.java +++ b/src/main/java/mcp/mobius/opis/data/managers/EntityManager.java @@ -5,17 +5,8 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.World; -import net.minecraft.world.WorldServer; -import net.minecraftforge.common.DimensionManager; +import mcp.mobius.mobiuscore.monitors.MonitoredEntityList; import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.data.holders.basetypes.AmountHolder; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; @@ -25,302 +16,323 @@ import mcp.mobius.opis.data.holders.newtypes.DataTiming; import mcp.mobius.opis.data.holders.newtypes.PlayerStatus; import mcp.mobius.opis.data.profilers.ProfilerEntityUpdate; import mcp.mobius.opis.helpers.Teleport; +import mcp.mobius.opis.modOpis; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.PlayerEv; -import mcp.mobius.mobiuscore.monitors.MonitoredEntityList; +import net.minecraft.entity.Entity; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.World; +import net.minecraft.world.WorldServer; +import net.minecraftforge.common.DimensionManager; public enum EntityManager { - INSTANCE; - - public ArrayList getWorses(int amount){ - ArrayList sorted = new ArrayList(); - ArrayList topEntities = new ArrayList(); - - for (Entity entity : ((ProfilerEntityUpdate)ProfilerSection.ENTITY_UPDATETIME.getProfiler()).data.keySet()) - sorted.add(new DataEntity().fill(entity)); + INSTANCE; - Collections.sort(sorted); - - int i = 0; - while (topEntities.size() < Math.min(amount, sorted.size()) && (i < sorted.size()) ){ - DataEntity testats = sorted.get(i); - - if (testats.npoints < 40){ i++; continue; } - if (DimensionManager.getWorld(testats.pos.dim) == null) { i++; continue; } + public ArrayList getWorses(int amount) { + ArrayList sorted = new ArrayList(); + ArrayList topEntities = new ArrayList(); - topEntities.add(testats); - i++; - } - return topEntities; - } - - /* Returns all the entities in all dimensions (without timing data) */ - public ArrayList getAllEntities(){ - ArrayList entities = new ArrayList(); - for (int i : DimensionManager.getIDs()){ - entities.addAll(this.getEntitiesInDim(i)); - } - return entities; - } - - /* Returns all the entities in the given dimension (without timing data) */ - public ArrayList getEntitiesInDim(int dim){ - ArrayList entities = new ArrayList(); - - World world = DimensionManager.getWorld(dim); - if (world == null) return entities; - - for (Object o : world.loadedEntityList.toArray()){ - Entity ent = (Entity)o; - entities.add(new DataEntity().fill(ent)); - } - - return entities; - } - - /* Returns a hashmap of all entities per chunk (not timing) */ - public HashMap> getAllEntitiesPerChunk(){ - HashMap> entities = new HashMap>(); - for (int i : DimensionManager.getIDs()){ - entities.putAll(this.getEntitiesPerChunkInDim(i)); - } - return entities; - } - - /* Returns a hashmap of entities in the given dimension (not timing) */ - public HashMap> getEntitiesPerChunkInDim(int dim){ - HashMap> entities = new HashMap>(); - World world = DimensionManager.getWorld(dim); - if (world == null) return entities; - - for (Object o : world.loadedEntityList.toArray()){ - Entity ent = (Entity)o; - CoordinatesChunk chunk = new CoordinatesBlock(ent.dimension, (int)ent.posX, (int)ent.posY, (int)ent.posZ).asCoordinatesChunk(); - - if (!entities.containsKey(chunk)) - entities.put(chunk, new ArrayList()); - - //entities.get(chunk).add(new EntityStats(ent.entityId, ent.getClass().getName(), ent.dimension, ent.posX, ent.posY, ent.posZ)); - entities.get(chunk).add(new DataEntity().fill(ent)); - } - - return entities; - } - - /* Returns an array of all entities in a given chunk */ - public ArrayList getEntitiesInChunk(CoordinatesChunk coord){ - ArrayList entities = new ArrayList(); - - World world = DimensionManager.getWorld(coord.dim); - if (world == null) return entities; - - for (Object o : world.loadedEntityList.toArray()){ - Entity ent = (Entity)o; - CoordinatesChunk chunk = new CoordinatesBlock(ent.dimension, (int)ent.posX, (int)ent.posY, (int)ent.posZ).asCoordinatesChunk(); - if (chunk.equals(coord)) - //entities.add(new EntityStats(ent.entityId, ent.getClass().getName(), ent.dimension, ent.posX, ent.posY, ent.posZ)); - entities.add(new DataEntity().fill(ent)); - } - - return entities; - } - - /* Returns a hashmap with the entity name and amount of it on the server */ - public ArrayList getCumulativeEntities(boolean filtered){ - ArrayList cumData = new ArrayList(); + for (Entity entity : ((ProfilerEntityUpdate) ProfilerSection.ENTITY_UPDATETIME.getProfiler()).data.keySet()) + sorted.add(new DataEntity().fill(entity)); - for (int dim : DimensionManager.getIDs()){ - World world = DimensionManager.getWorld(dim); - if (world == null) continue; - - if (!(world.loadedEntityList instanceof MonitoredEntityList)){ - modOpis.log.info("Improper type detected for entity list in world " + dim + ". Regenerating tracking list."); - List newList = new MonitoredEntityList(); - for (Object o : world.loadedEntityList) - newList.add((Entity)o); - world.loadedEntityList = newList; - } - - Map count = ((MonitoredEntityList)world.loadedEntityList).getCount(); - for (String key : count.keySet()) - if (count.get(key) > 0) - cumData.add(new AmountHolder(key, count.get(key), "Plop")); - } - return cumData; - } - - public boolean teleportPlayer(CoordinatesBlock coord, EntityPlayerMP player){ - //System.out.printf("%s %s\n", coord, getTeleportTarget(coord)); - CoordinatesBlock target = Teleport.instance().getTeleportTarget(coord); - if (target == null) return false; - - target = Teleport.instance().fixNetherTP(target); + Collections.sort(sorted); - if (target == null) return false; - - if (Teleport.instance().movePlayerToDimension(player, coord.dim)) - player.setPositionAndUpdate(target.x + 0.5, target.y, target.z + 0.5); - else - return false; - - return true; - } + int i = 0; + while (topEntities.size() < Math.min(amount, sorted.size()) && (i < sorted.size())) { + DataEntity testats = sorted.get(i); - public boolean teleportEntity(Entity src, Entity trg, EntityPlayerMP msgtrg){ - if ((src == null) && (msgtrg != null)) { - PacketManager.sendChatMsg(String.format("\u00A7oCannot find source entity %s", src), msgtrg); - return false; - } + if (testats.npoints < 40) { + i++; + continue; + } + if (DimensionManager.getWorld(testats.pos.dim) == null) { + i++; + continue; + } - if ((trg == null) && (msgtrg != null)) { - PacketManager.sendChatMsg(String.format("\u00A7oCannot find target entity %s", src), msgtrg); - return false; - } - - if (src instanceof EntityPlayerMP){ - if (Teleport.instance().movePlayerToDimension((EntityPlayerMP)src, trg.worldObj.provider.dimensionId)) - src.setLocationAndAngles(trg.posX, trg.posY, trg.posZ, src.rotationYaw, src.rotationPitch); - else - return false; - } - else{ - if (Teleport.instance().moveEntityToDimension(src, trg.worldObj.provider.dimensionId)) - src.setLocationAndAngles(trg.posX, trg.posY, trg.posZ, src.rotationYaw, src.rotationPitch); - else - return false; - } - - return true; - - } + topEntities.add(testats); + i++; + } + return topEntities; + } - public Entity getEntity(int eid, int dim){ - World world = DimensionManager.getWorld(dim); - if (world == null) return null; - - Entity entity = world.getEntityByID(eid); - return entity; - } - - public String getEntityName(Entity ent){ - return getEntityName(ent, false); - } - - public String getEntityName(Entity ent, boolean filtered){ - if (ent instanceof EntityItem && filtered){ - return "Dropped Item"; - } else if (ent instanceof EntityItem && !filtered){ - try { - return "[Stack] " + ((EntityItem)ent).getEntityItem().getDisplayName(); - } catch (Exception e) { - return ""; - } - } - - - if (ent instanceof EntityPlayerMP && filtered) - return "Player"; - else if (ent instanceof EntityPlayerMP && !filtered) - return "[ Player ] " + ((EntityPlayerMP)ent).getGameProfile().getName(); - - String name = ent.getCommandSenderName(); - - if (name.contains(".")){ - String[] namelst = ent.getClass().getName().split("\\."); - return namelst[namelst.length - 1]; - } - - return name; - } - - public DataTiming getTotalUpdateTime(){ - double updateTime = 0D; - for (Entity entity : ((ProfilerEntityUpdate)ProfilerSection.ENTITY_UPDATETIME.getProfiler()).data.keySet()){ - updateTime += ((ProfilerEntityUpdate)ProfilerSection.ENTITY_UPDATETIME.getProfiler()).data.get(entity).getGeometricMean(); - } - return new DataTiming(updateTime); - } + /* Returns all the entities in all dimensions (without timing data) */ + public ArrayList getAllEntities() { + ArrayList entities = new ArrayList(); + for (int i : DimensionManager.getIDs()) { + entities.addAll(this.getEntitiesInDim(i)); + } + return entities; + } - public int killAll(String entName){ - int nkilled = 0; - - if (entName.contains("Player")){ - return -1; //Error msg for when trying to kill a player - } - - - for (int dim : DimensionManager.getIDs()){ - World world = DimensionManager.getWorld(dim); - if (world == null) continue; - - for (Object o : world.loadedEntityList.toArray()){ - Entity ent = (Entity)o; - String nameFiltered = this.getEntityName(ent, true).toLowerCase(); - String nameUnfiltered = this.getEntityName(ent, false).toLowerCase(); - - if (nameFiltered.equals(entName.toLowerCase()) || nameUnfiltered.equals(entName.toLowerCase())){ - ent.setDead(); - nkilled += 1; - } - } - } + /* Returns all the entities in the given dimension (without timing data) */ + public ArrayList getEntitiesInDim(int dim) { + ArrayList entities = new ArrayList(); - System.out.printf("Killed %d %s\n", nkilled, entName); - - return nkilled; - } - - public ArrayList getAllPlayers(){ - //List players = MinecraftServer.getServerConfigurationManager(MinecraftServer.getServer()).playerEntityList; - List players = MinecraftServer.getServer().getConfigurationManager().playerEntityList; - - ArrayList outList = new ArrayList(); - - for (Object o : players){ - //outList.add(new DataEntity().fill((EntityPlayer) p)); - EntityPlayer p = (EntityPlayer) o; - outList.add(new PlayerStatus(p.getGameProfile().getName(), PlayerEv.ONLINE, - p.worldObj.provider.dimensionId, (int)p.posX, (int)p.posY, (int)p.posZ)); - } - - return outList; - } - - public int getAmountEntities(){ - int amountEntities = 0; - for (WorldServer world : DimensionManager.getWorlds()){ - amountEntities += world.loadedEntityList.size(); - } - return amountEntities; - } - - public int killAllPerClass(int dim, Class clazz){ - WorldServer world = DimensionManager.getWorld(dim); - if (world == null) return -1; - - int killedEnts = 0; - - ArrayList copyList = new ArrayList(world.loadedEntityList); - - for (Entity entity : (ArrayList)copyList){ - if (clazz.isInstance(entity)){ - entity.setDead(); - killedEnts += 1; - } - } - return killedEnts; - } - - public ArrayList getTotalPerClass(){ - HashMap data = new HashMap(); - - for (Entity entity : ((ProfilerEntityUpdate)ProfilerSection.ENTITY_UPDATETIME.getProfiler()).data.keySet()){ - String name = this.getEntityName(entity, true); - if (!data.containsKey(name)) - data.put(name, new DataEntityPerClass(name)); - - data.get(name).add(((ProfilerEntityUpdate)ProfilerSection.ENTITY_UPDATETIME.getProfiler()).data.get(entity).getGeometricMean()); - } - return new ArrayList(data.values()); - } + World world = DimensionManager.getWorld(dim); + if (world == null) return entities; + + for (Object o : world.loadedEntityList.toArray()) { + Entity ent = (Entity) o; + entities.add(new DataEntity().fill(ent)); + } + + return entities; + } + + /* Returns a hashmap of all entities per chunk (not timing) */ + public HashMap> getAllEntitiesPerChunk() { + HashMap> entities = + new HashMap>(); + for (int i : DimensionManager.getIDs()) { + entities.putAll(this.getEntitiesPerChunkInDim(i)); + } + return entities; + } + + /* Returns a hashmap of entities in the given dimension (not timing) */ + public HashMap> getEntitiesPerChunkInDim(int dim) { + HashMap> entities = + new HashMap>(); + World world = DimensionManager.getWorld(dim); + if (world == null) return entities; + + for (Object o : world.loadedEntityList.toArray()) { + Entity ent = (Entity) o; + CoordinatesChunk chunk = new CoordinatesBlock(ent.dimension, (int) ent.posX, (int) ent.posY, (int) ent.posZ) + .asCoordinatesChunk(); + + if (!entities.containsKey(chunk)) entities.put(chunk, new ArrayList()); + + // entities.get(chunk).add(new EntityStats(ent.entityId, ent.getClass().getName(), ent.dimension, ent.posX, + // ent.posY, ent.posZ)); + entities.get(chunk).add(new DataEntity().fill(ent)); + } + + return entities; + } + + /* Returns an array of all entities in a given chunk */ + public ArrayList getEntitiesInChunk(CoordinatesChunk coord) { + ArrayList entities = new ArrayList(); + + World world = DimensionManager.getWorld(coord.dim); + if (world == null) return entities; + + for (Object o : world.loadedEntityList.toArray()) { + Entity ent = (Entity) o; + CoordinatesChunk chunk = new CoordinatesBlock(ent.dimension, (int) ent.posX, (int) ent.posY, (int) ent.posZ) + .asCoordinatesChunk(); + if (chunk.equals(coord)) + // entities.add(new EntityStats(ent.entityId, ent.getClass().getName(), ent.dimension, ent.posX, + // ent.posY, ent.posZ)); + entities.add(new DataEntity().fill(ent)); + } + + return entities; + } + + /* Returns a hashmap with the entity name and amount of it on the server */ + public ArrayList getCumulativeEntities(boolean filtered) { + ArrayList cumData = new ArrayList(); + + for (int dim : DimensionManager.getIDs()) { + World world = DimensionManager.getWorld(dim); + if (world == null) continue; + + if (!(world.loadedEntityList instanceof MonitoredEntityList)) { + modOpis.log.info( + "Improper type detected for entity list in world " + dim + ". Regenerating tracking list."); + List newList = new MonitoredEntityList(); + for (Object o : world.loadedEntityList) newList.add((Entity) o); + world.loadedEntityList = newList; + } + + Map count = ((MonitoredEntityList) world.loadedEntityList).getCount(); + for (String key : count.keySet()) + if (count.get(key) > 0) cumData.add(new AmountHolder(key, count.get(key), "Plop")); + } + return cumData; + } + + public boolean teleportPlayer(CoordinatesBlock coord, EntityPlayerMP player) { + // System.out.printf("%s %s\n", coord, getTeleportTarget(coord)); + CoordinatesBlock target = Teleport.instance().getTeleportTarget(coord); + if (target == null) return false; + + target = Teleport.instance().fixNetherTP(target); + + if (target == null) return false; + + if (Teleport.instance().movePlayerToDimension(player, coord.dim)) + player.setPositionAndUpdate(target.x + 0.5, target.y, target.z + 0.5); + else return false; + + return true; + } + + public boolean teleportEntity(Entity src, Entity trg, EntityPlayerMP msgtrg) { + if ((src == null) && (msgtrg != null)) { + PacketManager.sendChatMsg(String.format("\u00A7oCannot find source entity %s", src), msgtrg); + return false; + } + + if ((trg == null) && (msgtrg != null)) { + PacketManager.sendChatMsg(String.format("\u00A7oCannot find target entity %s", src), msgtrg); + return false; + } + + if (src instanceof EntityPlayerMP) { + if (Teleport.instance().movePlayerToDimension((EntityPlayerMP) src, trg.worldObj.provider.dimensionId)) + src.setLocationAndAngles(trg.posX, trg.posY, trg.posZ, src.rotationYaw, src.rotationPitch); + else return false; + } else { + if (Teleport.instance().moveEntityToDimension(src, trg.worldObj.provider.dimensionId)) + src.setLocationAndAngles(trg.posX, trg.posY, trg.posZ, src.rotationYaw, src.rotationPitch); + else return false; + } + + return true; + } + + public Entity getEntity(int eid, int dim) { + World world = DimensionManager.getWorld(dim); + if (world == null) return null; + + Entity entity = world.getEntityByID(eid); + return entity; + } + + public String getEntityName(Entity ent) { + return getEntityName(ent, false); + } + + public String getEntityName(Entity ent, boolean filtered) { + if (ent instanceof EntityItem && filtered) { + return "Dropped Item"; + } else if (ent instanceof EntityItem && !filtered) { + try { + return "[Stack] " + ((EntityItem) ent).getEntityItem().getDisplayName(); + } catch (Exception e) { + return ""; + } + } + + if (ent instanceof EntityPlayerMP && filtered) return "Player"; + else if (ent instanceof EntityPlayerMP && !filtered) + return "[ Player ] " + ((EntityPlayerMP) ent).getGameProfile().getName(); + + String name = ent.getCommandSenderName(); + + if (name.contains(".")) { + String[] namelst = ent.getClass().getName().split("\\."); + return namelst[namelst.length - 1]; + } + + return name; + } + + public DataTiming getTotalUpdateTime() { + double updateTime = 0D; + for (Entity entity : ((ProfilerEntityUpdate) ProfilerSection.ENTITY_UPDATETIME.getProfiler()).data.keySet()) { + updateTime += ((ProfilerEntityUpdate) ProfilerSection.ENTITY_UPDATETIME.getProfiler()) + .data + .get(entity) + .getGeometricMean(); + } + return new DataTiming(updateTime); + } + + public int killAll(String entName) { + int nkilled = 0; + + if (entName.contains("Player")) { + return -1; // Error msg for when trying to kill a player + } + + for (int dim : DimensionManager.getIDs()) { + World world = DimensionManager.getWorld(dim); + if (world == null) continue; + + for (Object o : world.loadedEntityList.toArray()) { + Entity ent = (Entity) o; + String nameFiltered = this.getEntityName(ent, true).toLowerCase(); + String nameUnfiltered = this.getEntityName(ent, false).toLowerCase(); + + if (nameFiltered.equals(entName.toLowerCase()) || nameUnfiltered.equals(entName.toLowerCase())) { + ent.setDead(); + nkilled += 1; + } + } + } + + System.out.printf("Killed %d %s\n", nkilled, entName); + + return nkilled; + } + + public ArrayList getAllPlayers() { + // List players = MinecraftServer.getServerConfigurationManager(MinecraftServer.getServer()).playerEntityList; + List players = MinecraftServer.getServer().getConfigurationManager().playerEntityList; + + ArrayList outList = new ArrayList(); + + for (Object o : players) { + // outList.add(new DataEntity().fill((EntityPlayer) p)); + EntityPlayer p = (EntityPlayer) o; + outList.add(new PlayerStatus( + p.getGameProfile().getName(), + PlayerEv.ONLINE, + p.worldObj.provider.dimensionId, + (int) p.posX, + (int) p.posY, + (int) p.posZ)); + } + + return outList; + } + + public int getAmountEntities() { + int amountEntities = 0; + for (WorldServer world : DimensionManager.getWorlds()) { + amountEntities += world.loadedEntityList.size(); + } + return amountEntities; + } + + public int killAllPerClass(int dim, Class clazz) { + WorldServer world = DimensionManager.getWorld(dim); + if (world == null) return -1; + + int killedEnts = 0; + + ArrayList copyList = new ArrayList(world.loadedEntityList); + + for (Entity entity : (ArrayList) copyList) { + if (clazz.isInstance(entity)) { + entity.setDead(); + killedEnts += 1; + } + } + return killedEnts; + } + + public ArrayList getTotalPerClass() { + HashMap data = new HashMap(); + + for (Entity entity : ((ProfilerEntityUpdate) ProfilerSection.ENTITY_UPDATETIME.getProfiler()).data.keySet()) { + String name = this.getEntityName(entity, true); + if (!data.containsKey(name)) data.put(name, new DataEntityPerClass(name)); + + data.get(name) + .add(((ProfilerEntityUpdate) ProfilerSection.ENTITY_UPDATETIME.getProfiler()) + .data + .get(entity) + .getGeometricMean()); + } + return new ArrayList(data.values()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/managers/MetaManager.java b/src/main/java/mcp/mobius/opis/data/managers/MetaManager.java index a7f3e49..e2140d5 100644 --- a/src/main/java/mcp/mobius/opis/data/managers/MetaManager.java +++ b/src/main/java/mcp/mobius/opis/data/managers/MetaManager.java @@ -2,20 +2,19 @@ package mcp.mobius.opis.data.managers; import cpw.mods.fml.relauncher.Side; import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.events.OpisServerTickHandler; +import mcp.mobius.opis.modOpis; public class MetaManager { - public static void reset(){ - modOpis.profilerRun = false; - modOpis.selectedBlock = null; - OpisServerTickHandler.INSTANCE.profilerRunningTicks = 0; - - ProfilerSection.resetAll(Side.SERVER); - ProfilerSection.desactivateAll(Side.SERVER); - //ProfilerSection.resetAll(Side.CLIENT); - //ProfilerSection.desactivateAll(Side.CLIENT); - } - + public static void reset() { + modOpis.profilerRun = false; + modOpis.selectedBlock = null; + OpisServerTickHandler.INSTANCE.profilerRunningTicks = 0; + + ProfilerSection.resetAll(Side.SERVER); + ProfilerSection.desactivateAll(Side.SERVER); + // ProfilerSection.resetAll(Side.CLIENT); + // ProfilerSection.desactivateAll(Side.CLIENT); + } } diff --git a/src/main/java/mcp/mobius/opis/data/managers/StringCache.java b/src/main/java/mcp/mobius/opis/data/managers/StringCache.java index 0bc41ba..5a429d6 100644 --- a/src/main/java/mcp/mobius/opis/data/managers/StringCache.java +++ b/src/main/java/mcp/mobius/opis/data/managers/StringCache.java @@ -1,16 +1,10 @@ package mcp.mobius.opis.data.managers; -import java.util.ArrayList; -import java.util.concurrent.ConcurrentLinkedQueue; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraftforge.common.util.FakePlayer; - import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Maps; - -import mcp.mobius.opis.modOpis; +import java.util.ArrayList; +import java.util.concurrent.ConcurrentLinkedQueue; import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.data.holders.ISerializable; @@ -20,116 +14,117 @@ import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.server.NetDataList; import mcp.mobius.opis.network.packets.server.NetDataValue; -import mcp.mobius.opis.network.rcon.server.RConServer; +import net.minecraft.entity.player.EntityPlayerMP; public enum StringCache implements IMessageHandler { - INSTANCE; + INSTANCE; - private int currentIndex = -1; - //private HashBiMap cache = HashBiMap.create(); - //private ArrayList toSend = new ArrayList(); - private BiMap cache = Maps.synchronizedBiMap(HashBiMap.create()); - private ConcurrentLinkedQueue fullsync = new ConcurrentLinkedQueue(); - private ConcurrentLinkedQueue unsynced = new ConcurrentLinkedQueue(); // This is the current list of unsynced - - private StringCache(){ - this.getIndex("Server"); - } - - public String getString(int index){ - synchronized(cache){ - String retVal = this.cache.get(index); - if (retVal == null){ - return ""; - }else - return retVal; - } - } - - public int getIndex(String str){ - synchronized(cache){ - if (cache.inverse().containsKey(str)){ - return cache.inverse().get(str); - } - else{ - currentIndex += 1; - cache.put(currentIndex, str); - - DataStringUpdate upd = new DataStringUpdate(str, currentIndex); - this.fullsync.add(upd); - this.unsynced.add(upd); - - //PacketManager.sendToAll(new NetDataValue(Message.STATUS_STRINGUPD, upd)); - return currentIndex; - } - } - } - - public void syncCache(EntityPlayerMP player){ - - int i = 0; - - ArrayList toSendCopy = new ArrayList(fullsync); - - while (i < toSendCopy.size()){ - PacketManager.sendToPlayer(new NetDataList(Message.STATUS_STRINGUPD_FULL, toSendCopy.subList(i, Math.min(i + 50, toSendCopy.size()))), player); - i += 50; - } - - - } + private int currentIndex = -1; + // private HashBiMap cache = HashBiMap.create(); + // private ArrayList toSend = new ArrayList(); + private BiMap cache = Maps.synchronizedBiMap(HashBiMap.create()); + private ConcurrentLinkedQueue fullsync = new ConcurrentLinkedQueue(); + private ConcurrentLinkedQueue unsynced = + new ConcurrentLinkedQueue(); // This is the current list of unsynced - public void syncNewCache(){ - while (!unsynced.isEmpty()){ - DataStringUpdate update = this.unsynced.poll(); - PacketManager.sendToAll(new NetDataValue(Message.STATUS_STRINGUPD, update)); - } - } - - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case STATUS_STRINGUPD:{ - //modOpis.log.info(String.format("Received partial String Cache update : [ %d ] [ %s ]", ((DataStringUpdate)rawdata.value).index, ((DataStringUpdate)rawdata.value).str)); - - DataStringUpdate data = (DataStringUpdate)rawdata.value; - //modOpis.log.info(String.format("++++ Received String Cache update : [%d] %s", data.index, data.str)); - try{ - this.cache.put(data.index, data.str); - } catch (IllegalArgumentException e){ - this.cache.remove(data.index); - this.cache.inverse().remove(data.str); - this.cache.put(data.index, data.str); - } - - TabPanelRegistrar.INSTANCE.refreshAll(); - - break; - } - case STATUS_STRINGUPD_FULL:{ - //modOpis.log.info(String.format("Received full String Cache update containing %d entries", rawdata.array.size())); - - for (ISerializable idata : rawdata.array){ - DataStringUpdate data = (DataStringUpdate)idata; - //modOpis.log.info(String.format("++++ Received String Cache update : [%d] %s", data.index, data.str)); - try{ - this.cache.put(data.index, data.str); - } catch (IllegalArgumentException e){ - this.cache.remove(data.index); - this.cache.inverse().remove(data.str); - this.cache.put(data.index, data.str); - } - } - - TabPanelRegistrar.INSTANCE.refreshAll(); - - break; - } - default: - return false; - - } - return true; - } + private StringCache() { + this.getIndex("Server"); + } + public String getString(int index) { + synchronized (cache) { + String retVal = this.cache.get(index); + if (retVal == null) { + return ""; + } else return retVal; + } + } + + public int getIndex(String str) { + synchronized (cache) { + if (cache.inverse().containsKey(str)) { + return cache.inverse().get(str); + } else { + currentIndex += 1; + cache.put(currentIndex, str); + + DataStringUpdate upd = new DataStringUpdate(str, currentIndex); + this.fullsync.add(upd); + this.unsynced.add(upd); + + // PacketManager.sendToAll(new NetDataValue(Message.STATUS_STRINGUPD, upd)); + return currentIndex; + } + } + } + + public void syncCache(EntityPlayerMP player) { + + int i = 0; + + ArrayList toSendCopy = new ArrayList(fullsync); + + while (i < toSendCopy.size()) { + PacketManager.sendToPlayer( + new NetDataList( + Message.STATUS_STRINGUPD_FULL, toSendCopy.subList(i, Math.min(i + 50, toSendCopy.size()))), + player); + i += 50; + } + } + + public void syncNewCache() { + while (!unsynced.isEmpty()) { + DataStringUpdate update = this.unsynced.poll(); + PacketManager.sendToAll(new NetDataValue(Message.STATUS_STRINGUPD, update)); + } + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case STATUS_STRINGUPD: { + // modOpis.log.info(String.format("Received partial String Cache update : [ %d ] [ %s ]", + // ((DataStringUpdate)rawdata.value).index, ((DataStringUpdate)rawdata.value).str)); + + DataStringUpdate data = (DataStringUpdate) rawdata.value; + // modOpis.log.info(String.format("++++ Received String Cache update : [%d] %s", data.index, data.str)); + try { + this.cache.put(data.index, data.str); + } catch (IllegalArgumentException e) { + this.cache.remove(data.index); + this.cache.inverse().remove(data.str); + this.cache.put(data.index, data.str); + } + + TabPanelRegistrar.INSTANCE.refreshAll(); + + break; + } + case STATUS_STRINGUPD_FULL: { + // modOpis.log.info(String.format("Received full String Cache update containing %d entries", + // rawdata.array.size())); + + for (ISerializable idata : rawdata.array) { + DataStringUpdate data = (DataStringUpdate) idata; + // modOpis.log.info(String.format("++++ Received String Cache update : [%d] %s", data.index, + // data.str)); + try { + this.cache.put(data.index, data.str); + } catch (IllegalArgumentException e) { + this.cache.remove(data.index); + this.cache.inverse().remove(data.str); + this.cache.put(data.index, data.str); + } + } + + TabPanelRegistrar.INSTANCE.refreshAll(); + + break; + } + default: + return false; + } + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/data/managers/TileEntityManager.java b/src/main/java/mcp/mobius/opis/data/managers/TileEntityManager.java index 60cbc51..af5b9fc 100644 --- a/src/main/java/mcp/mobius/opis/data/managers/TileEntityManager.java +++ b/src/main/java/mcp/mobius/opis/data/managers/TileEntityManager.java @@ -1,21 +1,15 @@ package mcp.mobius.opis.data.managers; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import com.google.common.collect.Table.Cell; - -import mcp.mobius.mobiuscore.monitors.MonitoredEntityList; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; import mcp.mobius.mobiuscore.monitors.MonitoredTileList; import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.data.holders.basetypes.AmountHolder; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; @@ -26,8 +20,8 @@ import mcp.mobius.opis.data.holders.newtypes.DataTiming; import mcp.mobius.opis.data.holders.stats.StatsChunk; import mcp.mobius.opis.data.profilers.ProfilerTileEntityUpdate; import mcp.mobius.opis.helpers.ModIdentification; +import mcp.mobius.opis.modOpis; import net.minecraft.block.Block; -import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; @@ -35,215 +29,230 @@ import net.minecraft.world.WorldServer; import net.minecraftforge.common.DimensionManager; public enum TileEntityManager { - INSTANCE; - - public HashMap getTimes(int dim){ - HashMap chunks = new HashMap(); - - for (CoordinatesBlock coord : ((ProfilerTileEntityUpdate)ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()){ - if (coord.dim == dim){ + INSTANCE; - CoordinatesChunk coordC = new CoordinatesChunk(coord); - if (!(chunks.containsKey(coordC))) - chunks.put(coordC, new StatsChunk()); - - chunks.get(coordC).addEntity(); - chunks.get(coordC).addMeasure(((ProfilerTileEntityUpdate)ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.get(coord).getGeometricMean()); - } - } - return chunks; - } - - private void cleanUpStats(){ - - /* - HashSet dirty = new HashSet(); - - for (CoordinatesBlock tecoord : TileEntityManager.stats.keySet()){ - World world = DimensionManager.getWorld(tecoord.dim); - int blockID = world.getBlockId(tecoord.x, tecoord.y, tecoord.z); - short blockMeta = (short)world.getBlockMetadata(tecoord.x, tecoord.y, tecoord.z); - - if ((blockID != TileEntityManager.stats.get(tecoord).getID()) || (blockMeta != TileEntityManager.stats.get(tecoord).getMeta())){ - dirty.add(tecoord); - } - } - - for (CoordinatesBlock tecoord : dirty){ - stats.remove(tecoord); - references.remove(tecoord); - } - */ - - } - - public ArrayList getTileEntitiesInChunk(CoordinatesChunk coord){ - cleanUpStats(); - - ArrayList returnList = new ArrayList(); - - for (CoordinatesBlock tecoord : ((ProfilerTileEntityUpdate)ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()){ - if (coord.equals(tecoord.asCoordinatesChunk())){ - DataBlockTileEntity testats = new DataBlockTileEntity().fill(tecoord); - - returnList.add(testats); - } - } - - return returnList; - } - - public ArrayList getWorses(int amount){ - ArrayList sorted = new ArrayList(); - ArrayList topEntities = new ArrayList(); - - for (CoordinatesBlock coord : ((ProfilerTileEntityUpdate)ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()) - sorted.add(new DataBlockTileEntity().fill(coord)); - - Collections.sort(sorted); - - for (int i = 0; i < Math.min(amount, sorted.size()); i++) - topEntities.add(sorted.get(i)); - + public HashMap getTimes(int dim) { + HashMap chunks = new HashMap(); - return topEntities; - } + for (CoordinatesBlock coord : + ((ProfilerTileEntityUpdate) ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()) { + if (coord.dim == dim) { - public DataTiming getTotalUpdateTime(){ - double updateTime = 0D; - for (CoordinatesBlock coords : ((ProfilerTileEntityUpdate)ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()){ - updateTime += ((ProfilerTileEntityUpdate)ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.get(coords).getGeometricMean(); - } - return new DataTiming(updateTime); - } - - public int getAmountTileEntities(){ - int amountTileEntities = 0; - for (WorldServer world : DimensionManager.getWorlds()){ - amountTileEntities += world.loadedTileEntityList.size(); - } - return amountTileEntities; - } - - public ArrayList getOrphans(){ - ArrayList orphans = new ArrayList(); - HashMap coordHashset = new HashMap(); - HashSet registeredEntities = new HashSet(); - - for (WorldServer world : DimensionManager.getWorlds()){ - for (Object o : world.loadedTileEntityList.toArray()){ - TileEntity tileEntity = (TileEntity)o; - if (tileEntity == null) continue; - CoordinatesBlock coord = new CoordinatesBlock(world.provider.dimensionId, tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); - int hash = System.identityHashCode(tileEntity); - - if (registeredEntities.contains(hash)) continue; //This entitie has already been seen; - - Block block = world.getBlock(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); - if (block == Blocks.air || block == null - || !block.hasTileEntity(0) - || world.getTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord) == null - || world.getTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord).getClass() != tileEntity.getClass()){ + CoordinatesChunk coordC = new CoordinatesChunk(coord); + if (!(chunks.containsKey(coordC))) chunks.put(coordC, new StatsChunk()); - orphans.add(new DataTileEntity().fill(tileEntity, "Orphan")); - registeredEntities.add(hash); - } + chunks.get(coordC).addEntity(); + chunks.get(coordC) + .addMeasure(((ProfilerTileEntityUpdate) ProfilerSection.TILEENT_UPDATETIME.getProfiler()) + .data + .get(coord) + .getGeometricMean()); + } + } + return chunks; + } - if (coordHashset.containsKey(coord)){ - if (!registeredEntities.contains(hash)) - orphans.add(new DataTileEntity().fill(tileEntity, "Duplicate")); + private void cleanUpStats() { - if (!registeredEntities.contains(coordHashset.get(coord).hashCode)) - orphans.add(coordHashset.get(coord)); - } + /* + HashSet dirty = new HashSet(); - if (!coordHashset.containsKey(coord)){ - coordHashset.put(coord, new DataTileEntity().fill(tileEntity, "Duplicate")); - } - } - } - - modOpis.log.warn(String.format("Found %d potential orphans !", orphans.size())); - - return orphans; - } - - public ArrayList getCumulativeAmountTileEntities(){ - ArrayList cumData = new ArrayList(); + for (CoordinatesBlock tecoord : TileEntityManager.stats.keySet()){ + World world = DimensionManager.getWorld(tecoord.dim); + int blockID = world.getBlockId(tecoord.x, tecoord.y, tecoord.z); + short blockMeta = (short)world.getBlockMetadata(tecoord.x, tecoord.y, tecoord.z); - for (int dim : DimensionManager.getIDs()){ - World world = DimensionManager.getWorld(dim); - if (world == null) continue; + if ((blockID != TileEntityManager.stats.get(tecoord).getID()) || (blockMeta != TileEntityManager.stats.get(tecoord).getMeta())){ + dirty.add(tecoord); + } + } - if (!(world.loadedTileEntityList instanceof MonitoredTileList)) { - modOpis.log.info("Improper type detected for tile entity list in world " + dim + ". Regenerating tracking list."); + for (CoordinatesBlock tecoord : dirty){ + stats.remove(tecoord); + references.remove(tecoord); + } + */ - /* - * MonitoredTileList will, whenever a tile entity is added to it, load the block at the tile - * entity's position. This can cause Minecraft to load chunks, which will result in more tile - * entities being added to world.loadedTileEntityList. - * - * If we iterate through world.loadedTileEntityList and add its entries to newList, this would - * result in getting a ConcurrentModificationException. We get around this by using a regular - * for-loop instead of a for-each loop. - * - * As a bonus, since the for-loop checks world.loadedTileEntityList.size() at the start of each - * loop iteration, it'll pick up any new entries in world.loadedTileEntityList immediately, and will - * add them to newList without requiring us to check separately. However, this does require a few - * assumptions about what can happen in the for-loop body: - * 1. New entries are always added at the end of world.loadedTileEntityList - * 2. Entries are never removed from world.loadedTileEntityList - * WARNING: if any of those assumptions are broken, we will likely get unexpected behavior that is - * also extremely difficult to debug! - */ - - List newList = new MonitoredTileList(); - for (int i = 0; i < world.loadedTileEntityList.size(); i++) { - newList.add((TileEntity) world.loadedTileEntityList.get(i)); - } + } - world.loadedTileEntityList = newList; - } + public ArrayList getTileEntitiesInChunk(CoordinatesChunk coord) { + cleanUpStats(); - Table count = ((MonitoredTileList)world.loadedTileEntityList).getCount(); - Table reducedCount = HashBasedTable.create(); - - for (Cell c : count.cellSet()){ - if (c.getValue() > 0){ - String stackName = ModIdentification.getStackName(c.getRowKey(), c.getColumnKey()); - String modName = ModIdentification.getModStackName(c.getRowKey(), c.getColumnKey()); + ArrayList returnList = new ArrayList(); - try{ - reducedCount.put(stackName, modName, reducedCount.get(stackName, modName) + c.getValue()); - } catch (Exception e){ - reducedCount.put(stackName, modName, c.getValue()); - } - } - } - - for (Cell c : reducedCount.cellSet()){ - cumData.add(new AmountHolder(c.getRowKey(), c.getValue(), c.getColumnKey())); - } - - } - return cumData; - } - - public ArrayList getCumulativeTimingTileEntities(){ - HashBasedTable data = HashBasedTable.create(); - - for (CoordinatesBlock coord : ((ProfilerTileEntityUpdate)ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()){ - World world = DimensionManager.getWorld(coord.dim); - int id = Block.getIdFromBlock(world.getBlock(coord.x, coord.y, coord.z)); - int meta = world.getBlockMetadata(coord.x, coord.y, coord.z); - - if (!data.contains(id, meta)) - data.put(id, meta, new DataBlockTileEntityPerClass(id, meta)); - - data.get(id, meta).add(((ProfilerTileEntityUpdate)ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.get(coord).getGeometricMean()); - - } - - return new ArrayList(data.values()); - } + for (CoordinatesBlock tecoord : + ((ProfilerTileEntityUpdate) ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()) { + if (coord.equals(tecoord.asCoordinatesChunk())) { + DataBlockTileEntity testats = new DataBlockTileEntity().fill(tecoord); + + returnList.add(testats); + } + } + + return returnList; + } + + public ArrayList getWorses(int amount) { + ArrayList sorted = new ArrayList(); + ArrayList topEntities = new ArrayList(); + + for (CoordinatesBlock coord : + ((ProfilerTileEntityUpdate) ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()) + sorted.add(new DataBlockTileEntity().fill(coord)); + + Collections.sort(sorted); + + for (int i = 0; i < Math.min(amount, sorted.size()); i++) topEntities.add(sorted.get(i)); + + return topEntities; + } + + public DataTiming getTotalUpdateTime() { + double updateTime = 0D; + for (CoordinatesBlock coords : + ((ProfilerTileEntityUpdate) ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()) { + updateTime += ((ProfilerTileEntityUpdate) ProfilerSection.TILEENT_UPDATETIME.getProfiler()) + .data + .get(coords) + .getGeometricMean(); + } + return new DataTiming(updateTime); + } + + public int getAmountTileEntities() { + int amountTileEntities = 0; + for (WorldServer world : DimensionManager.getWorlds()) { + amountTileEntities += world.loadedTileEntityList.size(); + } + return amountTileEntities; + } + + public ArrayList getOrphans() { + ArrayList orphans = new ArrayList(); + HashMap coordHashset = new HashMap(); + HashSet registeredEntities = new HashSet(); + + for (WorldServer world : DimensionManager.getWorlds()) { + for (Object o : world.loadedTileEntityList.toArray()) { + TileEntity tileEntity = (TileEntity) o; + if (tileEntity == null) continue; + CoordinatesBlock coord = new CoordinatesBlock( + world.provider.dimensionId, tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); + int hash = System.identityHashCode(tileEntity); + + if (registeredEntities.contains(hash)) continue; // This entitie has already been seen; + + Block block = world.getBlock(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); + if (block == Blocks.air + || block == null + || !block.hasTileEntity(0) + || world.getTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord) == null + || world.getTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord) + .getClass() + != tileEntity.getClass()) { + + orphans.add(new DataTileEntity().fill(tileEntity, "Orphan")); + registeredEntities.add(hash); + } + + if (coordHashset.containsKey(coord)) { + if (!registeredEntities.contains(hash)) + orphans.add(new DataTileEntity().fill(tileEntity, "Duplicate")); + + if (!registeredEntities.contains(coordHashset.get(coord).hashCode)) + orphans.add(coordHashset.get(coord)); + } + + if (!coordHashset.containsKey(coord)) { + coordHashset.put(coord, new DataTileEntity().fill(tileEntity, "Duplicate")); + } + } + } + + modOpis.log.warn(String.format("Found %d potential orphans !", orphans.size())); + + return orphans; + } + + public ArrayList getCumulativeAmountTileEntities() { + ArrayList cumData = new ArrayList(); + + for (int dim : DimensionManager.getIDs()) { + World world = DimensionManager.getWorld(dim); + if (world == null) continue; + + if (!(world.loadedTileEntityList instanceof MonitoredTileList)) { + modOpis.log.info("Improper type detected for tile entity list in world " + dim + + ". Regenerating tracking list."); + + /* + * MonitoredTileList will, whenever a tile entity is added to it, load the block at the tile + * entity's position. This can cause Minecraft to load chunks, which will result in more tile + * entities being added to world.loadedTileEntityList. + * + * If we iterate through world.loadedTileEntityList and add its entries to newList, this would + * result in getting a ConcurrentModificationException. We get around this by using a regular + * for-loop instead of a for-each loop. + * + * As a bonus, since the for-loop checks world.loadedTileEntityList.size() at the start of each + * loop iteration, it'll pick up any new entries in world.loadedTileEntityList immediately, and will + * add them to newList without requiring us to check separately. However, this does require a few + * assumptions about what can happen in the for-loop body: + * 1. New entries are always added at the end of world.loadedTileEntityList + * 2. Entries are never removed from world.loadedTileEntityList + * WARNING: if any of those assumptions are broken, we will likely get unexpected behavior that is + * also extremely difficult to debug! + */ + + List newList = new MonitoredTileList(); + for (int i = 0; i < world.loadedTileEntityList.size(); i++) { + newList.add((TileEntity) world.loadedTileEntityList.get(i)); + } + + world.loadedTileEntityList = newList; + } + + Table count = ((MonitoredTileList) world.loadedTileEntityList).getCount(); + Table reducedCount = HashBasedTable.create(); + + for (Cell c : count.cellSet()) { + if (c.getValue() > 0) { + String stackName = ModIdentification.getStackName(c.getRowKey(), c.getColumnKey()); + String modName = ModIdentification.getModStackName(c.getRowKey(), c.getColumnKey()); + + try { + reducedCount.put(stackName, modName, reducedCount.get(stackName, modName) + c.getValue()); + } catch (Exception e) { + reducedCount.put(stackName, modName, c.getValue()); + } + } + } + + for (Cell c : reducedCount.cellSet()) { + cumData.add(new AmountHolder(c.getRowKey(), c.getValue(), c.getColumnKey())); + } + } + return cumData; + } + + public ArrayList getCumulativeTimingTileEntities() { + HashBasedTable data = HashBasedTable.create(); + + for (CoordinatesBlock coord : + ((ProfilerTileEntityUpdate) ProfilerSection.TILEENT_UPDATETIME.getProfiler()).data.keySet()) { + World world = DimensionManager.getWorld(coord.dim); + int id = Block.getIdFromBlock(world.getBlock(coord.x, coord.y, coord.z)); + int meta = world.getBlockMetadata(coord.x, coord.y, coord.z); + + if (!data.contains(id, meta)) data.put(id, meta, new DataBlockTileEntityPerClass(id, meta)); + + data.get(id, meta) + .add(((ProfilerTileEntityUpdate) ProfilerSection.TILEENT_UPDATETIME.getProfiler()) + .data + .get(coord) + .getGeometricMean()); + } + + return new ArrayList(data.values()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/Clock.java b/src/main/java/mcp/mobius/opis/data/profilers/Clock.java index 0b3efeb..83f3a3b 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/Clock.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/Clock.java @@ -5,42 +5,60 @@ import java.lang.management.ThreadMXBean; public class Clock { - public interface IClock{ - void start(); - void stop(); - long getDelta(); - } - - public static ThreadMXBean threadMX = ManagementFactory.getThreadMXBean(); - //public static boolean canThreadCPU = threadMX.isCurrentThreadCpuTimeSupported(); - public static boolean canThreadCPU = false; + public interface IClock { + void start(); - public class ClockMX implements IClock{ - public long startTime = 0; - public long timeDelta = 0; - @Override - public void start(){this.startTime = threadMX.getCurrentThreadCpuTime();} - @Override - public void stop() {this.timeDelta = threadMX.getCurrentThreadCpuTime() - this.startTime;} - @Override - public long getDelta() {return this.timeDelta;} - } - - public class ClockNano implements IClock{ - public long startTime = 0; - public long timeDelta = 0; - @Override - public void start(){this.startTime = System.nanoTime();} - @Override - public void stop() {this.timeDelta = System.nanoTime() - this.startTime;} - @Override - public long getDelta() {return this.timeDelta;} - } - - public static IClock getNewClock(){ - if (Clock.canThreadCPU) - return new Clock().new ClockMX(); - else - return new Clock().new ClockNano(); - } + void stop(); + + long getDelta(); + } + + public static ThreadMXBean threadMX = ManagementFactory.getThreadMXBean(); + // public static boolean canThreadCPU = threadMX.isCurrentThreadCpuTimeSupported(); + public static boolean canThreadCPU = false; + + public class ClockMX implements IClock { + public long startTime = 0; + public long timeDelta = 0; + + @Override + public void start() { + this.startTime = threadMX.getCurrentThreadCpuTime(); + } + + @Override + public void stop() { + this.timeDelta = threadMX.getCurrentThreadCpuTime() - this.startTime; + } + + @Override + public long getDelta() { + return this.timeDelta; + } + } + + public class ClockNano implements IClock { + public long startTime = 0; + public long timeDelta = 0; + + @Override + public void start() { + this.startTime = System.nanoTime(); + } + + @Override + public void stop() { + this.timeDelta = System.nanoTime() - this.startTime; + } + + @Override + public long getDelta() { + return this.timeDelta; + } + } + + public static IClock getNewClock() { + if (Clock.canThreadCPU) return new Clock().new ClockMX(); + else return new Clock().new ClockNano(); + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/DeadManSwitch.java b/src/main/java/mcp/mobius/opis/data/profilers/DeadManSwitch.java index 8ba7774..a21710e 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/DeadManSwitch.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/DeadManSwitch.java @@ -6,90 +6,89 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.LockSupport; import net.minecraft.server.MinecraftServer; -public class DeadManSwitch implements Runnable{ +public class DeadManSwitch implements Runnable { - public static DeadManSwitch instance; - private Thread serverThread = null; - private MinecraftServer server = null; - private AtomicLong timer = new AtomicLong(); - private AtomicLong timerPrev = new AtomicLong(); - private Long lastTested = 0L; - private long nderps = 0L; - private BlockingQueue queue = new ArrayBlockingQueue(2); - - public DeadManSwitch(MinecraftServer server, Thread serverThread){ - this.server = server; - this.serverThread = serverThread; - DeadManSwitch.instance = this; - - } - - public void setTimer(long time){ - this.timerPrev.set(this.timer.get()); - this.timer.set(time); - } + public static DeadManSwitch instance; + private Thread serverThread = null; + private MinecraftServer server = null; + private AtomicLong timer = new AtomicLong(); + private AtomicLong timerPrev = new AtomicLong(); + private Long lastTested = 0L; + private long nderps = 0L; + private BlockingQueue queue = new ArrayBlockingQueue(2); - public long getTimerDelta(){ - return this.timer.get() - this.timerPrev.get(); - } - - @Override - public void run() { - - System.out.printf("Starting Dead Man Switch\n"); - - //while (server.isServerRunning()){ - while (true){ - - try{ - if (this.lastTested != this.timer.get()){ - - //if (this.getTimerDelta() / 1000. / 1000. > 1000.){ - if (this.getTimerDelta() / 1000. / 1000. > 300.){ - System.out.printf("==== Main thread is staled ! %.3f ms [ %d ]====\n", this.getTimerDelta() / 1000. / 1000., this.nderps); - - this.nderps += 1; - - if (this.nderps > 10){ - /* - this.nderps = 0; - this.serverThread.interrupt(); - System.out.printf("Restarting\n"); - Thread.sleep(1000); - MinecraftServer.main(MinecraftServer.arguments); - System.out.printf("Restarted\n"); - return; - */ - for (Thread thread : Thread.getAllStackTraces().keySet()){ - if (thread != Thread.currentThread()){ - try{ - thread.interrupt(); - } catch (Exception e){ - System.out.printf("%s\n",e); - } - } - } - return; - } - } - } - this.lastTested = this.timer.get(); - } - catch (Exception e){ - throw new RuntimeException(e); - } - LockSupport.parkNanos(1L * 1000L * 1000L); - } - } - - public static DeadManSwitch startDeadManSwitch(MinecraftServer server){ - DeadManSwitch deadManSwitch = new DeadManSwitch(server, Thread.currentThread()); - Thread deadManSwitchThrd = new Thread(deadManSwitch); - deadManSwitchThrd.setName("Dead Man Switch"); - deadManSwitchThrd.setPriority(Thread.MAX_PRIORITY); - //deadManSwitchThrd.setDaemon(false); - deadManSwitchThrd.start(); - return deadManSwitch; - } - + public DeadManSwitch(MinecraftServer server, Thread serverThread) { + this.server = server; + this.serverThread = serverThread; + DeadManSwitch.instance = this; + } + + public void setTimer(long time) { + this.timerPrev.set(this.timer.get()); + this.timer.set(time); + } + + public long getTimerDelta() { + return this.timer.get() - this.timerPrev.get(); + } + + @Override + public void run() { + + System.out.printf("Starting Dead Man Switch\n"); + + // while (server.isServerRunning()){ + while (true) { + + try { + if (this.lastTested != this.timer.get()) { + + // if (this.getTimerDelta() / 1000. / 1000. > 1000.){ + if (this.getTimerDelta() / 1000. / 1000. > 300.) { + System.out.printf( + "==== Main thread is staled ! %.3f ms [ %d ]====\n", + this.getTimerDelta() / 1000. / 1000., this.nderps); + + this.nderps += 1; + + if (this.nderps > 10) { + /* + this.nderps = 0; + this.serverThread.interrupt(); + System.out.printf("Restarting\n"); + Thread.sleep(1000); + MinecraftServer.main(MinecraftServer.arguments); + System.out.printf("Restarted\n"); + return; + */ + for (Thread thread : Thread.getAllStackTraces().keySet()) { + if (thread != Thread.currentThread()) { + try { + thread.interrupt(); + } catch (Exception e) { + System.out.printf("%s\n", e); + } + } + } + return; + } + } + } + this.lastTested = this.timer.get(); + } catch (Exception e) { + throw new RuntimeException(e); + } + LockSupport.parkNanos(1L * 1000L * 1000L); + } + } + + public static DeadManSwitch startDeadManSwitch(MinecraftServer server) { + DeadManSwitch deadManSwitch = new DeadManSwitch(server, Thread.currentThread()); + Thread deadManSwitchThrd = new Thread(deadManSwitch); + deadManSwitchThrd.setName("Dead Man Switch"); + deadManSwitchThrd.setPriority(Thread.MAX_PRIORITY); + // deadManSwitchThrd.setDaemon(false); + deadManSwitchThrd.start(); + return deadManSwitch; + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerAbstract.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerAbstract.java index efbec70..3e09e2b 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerAbstract.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerAbstract.java @@ -4,37 +4,36 @@ import mcp.mobius.mobiuscore.profiler.IProfilerBase; public abstract class ProfilerAbstract implements IProfilerBase { - @Override - public abstract void reset(); + @Override + public abstract void reset(); - @Override - public void start() {} + @Override + public void start() {} - @Override - public void stop() {} + @Override + public void stop() {} - @Override - public void start(Object key) {} + @Override + public void start(Object key) {} - @Override - public void stop(Object key) {} + @Override + public void stop(Object key) {} - @Override - public void start(Object key1, Object key2) {} + @Override + public void start(Object key1, Object key2) {} - @Override - public void stop(Object key1, Object key2) {} + @Override + public void stop(Object key1, Object key2) {} - @Override - public void start(Object key1, Object key2, Object key3) {} - - @Override - public void stop(Object key1, Object key2, Object key3) {} - - @Override - public void start(Object key1, Object key2, Object key3, Object key4) {} - - @Override - public void stop(Object key1, Object key2, Object key3, Object key4) {} - + @Override + public void start(Object key1, Object key2, Object key3) {} + + @Override + public void stop(Object key1, Object key2, Object key3) {} + + @Override + public void start(Object key1, Object key2, Object key3, Object key4) {} + + @Override + public void stop(Object key1, Object key2, Object key3, Object key4) {} } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerDimBlockTick.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerDimBlockTick.java index aa8ebbc..48663bb 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerDimBlockTick.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerDimBlockTick.java @@ -1,41 +1,36 @@ package mcp.mobius.opis.data.profilers; import java.util.HashMap; - -import net.minecraftforge.common.DimensionManager; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - import mcp.mobius.mobiuscore.profiler.IProfilerBase; import mcp.mobius.opis.data.profilers.Clock.IClock; +import net.minecraftforge.common.DimensionManager; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class ProfilerDimBlockTick extends ProfilerAbstract implements IProfilerBase { - private IClock clock = Clock.getNewClock(); - public HashMap data = new HashMap(); - - - @Override - public void reset() { - this.data.clear(); - } - - @Override - public void start(Object key) { - Integer dim = (Integer)key; - if (DimensionManager.getWorld(dim).isRemote) return; - - if (!data.containsKey(dim)) - data.put(dim, new DescriptiveStatistics()); - clock.start(); - } - - @Override - public void stop(Object key) { - Integer dim = (Integer)key; - if (DimensionManager.getWorld(dim).isRemote) return; - - clock.stop(); - data.get(dim).addValue(clock.getDelta()); - } + private IClock clock = Clock.getNewClock(); + public HashMap data = new HashMap(); + + @Override + public void reset() { + this.data.clear(); + } + + @Override + public void start(Object key) { + Integer dim = (Integer) key; + if (DimensionManager.getWorld(dim).isRemote) return; + + if (!data.containsKey(dim)) data.put(dim, new DescriptiveStatistics()); + clock.start(); + } + + @Override + public void stop(Object key) { + Integer dim = (Integer) key; + if (DimensionManager.getWorld(dim).isRemote) return; + + clock.stop(); + data.get(dim).addValue(clock.getDelta()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerDimTick.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerDimTick.java index d281801..7573ada 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerDimTick.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerDimTick.java @@ -1,39 +1,37 @@ package mcp.mobius.opis.data.profilers; import java.util.HashMap; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - -import net.minecraft.world.World; import mcp.mobius.mobiuscore.profiler.IProfilerBase; import mcp.mobius.opis.data.profilers.Clock.IClock; +import net.minecraft.world.World; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class ProfilerDimTick extends ProfilerAbstract implements IProfilerBase { - private IClock clock = Clock.getNewClock(); - public HashMap data = new HashMap(); - - @Override - public void reset() { - this.data.clear(); - } - - @Override - public void start(Object key) { - World world = (World)key; - if (world.isRemote) return; - - if (!data.containsKey(world.provider.dimensionId)) - data.put(world.provider.dimensionId, new DescriptiveStatistics(20)); - clock.start(); - } - - @Override - public void stop(Object key) { - World world = (World)key; - if (world.isRemote) return; - - clock.stop(); - data.get(world.provider.dimensionId).addValue(clock.getDelta()); - } + private IClock clock = Clock.getNewClock(); + public HashMap data = new HashMap(); + + @Override + public void reset() { + this.data.clear(); + } + + @Override + public void start(Object key) { + World world = (World) key; + if (world.isRemote) return; + + if (!data.containsKey(world.provider.dimensionId)) + data.put(world.provider.dimensionId, new DescriptiveStatistics(20)); + clock.start(); + } + + @Override + public void stop(Object key) { + World world = (World) key; + if (world.isRemote) return; + + clock.stop(); + data.get(world.provider.dimensionId).addValue(clock.getDelta()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEntityUpdate.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEntityUpdate.java index de83db8..67a1cb4 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEntityUpdate.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEntityUpdate.java @@ -1,45 +1,41 @@ package mcp.mobius.opis.data.profilers; import java.util.WeakHashMap; - -import net.minecraft.entity.Entity; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - import mcp.mobius.mobiuscore.profiler.IProfilerBase; -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.data.profilers.Clock.IClock; +import mcp.mobius.opis.modOpis; +import net.minecraft.entity.Entity; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class ProfilerEntityUpdate extends ProfilerAbstract implements IProfilerBase { - private IClock clock = Clock.getNewClock(); - public WeakHashMap data = new WeakHashMap(); - - @Override - public void reset() { - this.data = new WeakHashMap(); - } - - @Override - public void start(Object key) { - Entity entity = (Entity)key; - if (entity.worldObj.isRemote) return; - - if (!data.containsKey(entity)) - data.put(entity, new DescriptiveStatistics()); - clock.start(); - } - - @Override - public void stop(Object key) { - Entity entity = (Entity)key; - if (entity.worldObj.isRemote) return; - - clock.stop(); - try{ - data.get(entity).addValue(clock.getDelta()); - } catch (Exception e){ - modOpis.log.warn(String.format("Error while profiling entity %s\n", key)); - } - } + private IClock clock = Clock.getNewClock(); + public WeakHashMap data = new WeakHashMap(); + + @Override + public void reset() { + this.data = new WeakHashMap(); + } + + @Override + public void start(Object key) { + Entity entity = (Entity) key; + if (entity.worldObj.isRemote) return; + + if (!data.containsKey(entity)) data.put(entity, new DescriptiveStatistics()); + clock.start(); + } + + @Override + public void stop(Object key) { + Entity entity = (Entity) key; + if (entity.worldObj.isRemote) return; + + clock.stop(); + try { + data.get(entity).addValue(clock.getDelta()); + } catch (Exception e) { + modOpis.log.warn(String.format("Error while profiling entity %s\n", key)); + } + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEvent.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEvent.java index b7c2ec5..4a2eb47 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEvent.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEvent.java @@ -1,63 +1,60 @@ package mcp.mobius.opis.data.profilers; -import mcp.mobius.opis.data.profilers.Clock.IClock; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - import com.google.common.collect.HashBasedTable; import cpw.mods.fml.common.ModContainer; +import mcp.mobius.opis.data.profilers.Clock.IClock; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class ProfilerEvent extends ProfilerAbstract { - private IClock clock = Clock.getNewClock(); - public HashBasedTable data = HashBasedTable.create(); - public HashBasedTable dataMod = HashBasedTable.create(); + private IClock clock = Clock.getNewClock(); + public HashBasedTable data = HashBasedTable.create(); + public HashBasedTable dataMod = HashBasedTable.create(); - public HashBasedTable dataTick = HashBasedTable.create(); - public HashBasedTable dataModTick = HashBasedTable.create(); - - @Override - public void reset() { - data.clear(); - } - - @Override - public void start() { - clock.start(); - } + public HashBasedTable dataTick = HashBasedTable.create(); + public HashBasedTable dataModTick = HashBasedTable.create(); - @Override - public void stop(Object event, Object pkg, Object handler, Object mod) { - clock.stop(); - - String eventName = event.getClass().getSimpleName(); - if (eventName.contains("TickEvent")){ - - try{ - String name = (String)pkg + "|" + handler.getClass().getSimpleName(); - dataTick.get(event.getClass(), name).addValue(clock.getDelta()); - } catch (Exception e) { - String name = (String)pkg + "|" + handler.getClass().getSimpleName(); - dataTick.put(event.getClass(), name, new DescriptiveStatistics(250)); - dataModTick.put(event.getClass(), name, ((ModContainer)mod).getName()); - dataTick.get(event.getClass(), name).addValue(clock.getDelta()); - } - - } else { - - try{ - String name = (String)pkg + "|" + handler.getClass().getSimpleName(); - data.get(event.getClass(), name).addValue(clock.getDelta()); - } catch (Exception e) { - try{ - String name = (String)pkg + "|" + handler.getClass().getSimpleName(); - data.put(event.getClass(), name, new DescriptiveStatistics(250)); - dataMod.put(event.getClass(), name, ((ModContainer)mod).getName()); - data.get(event.getClass(), name).addValue(clock.getDelta()); - } catch (Exception f){} - } - - } - } + @Override + public void reset() { + data.clear(); + } + @Override + public void start() { + clock.start(); + } + + @Override + public void stop(Object event, Object pkg, Object handler, Object mod) { + clock.stop(); + + String eventName = event.getClass().getSimpleName(); + if (eventName.contains("TickEvent")) { + + try { + String name = (String) pkg + "|" + handler.getClass().getSimpleName(); + dataTick.get(event.getClass(), name).addValue(clock.getDelta()); + } catch (Exception e) { + String name = (String) pkg + "|" + handler.getClass().getSimpleName(); + dataTick.put(event.getClass(), name, new DescriptiveStatistics(250)); + dataModTick.put(event.getClass(), name, ((ModContainer) mod).getName()); + dataTick.get(event.getClass(), name).addValue(clock.getDelta()); + } + + } else { + + try { + String name = (String) pkg + "|" + handler.getClass().getSimpleName(); + data.get(event.getClass(), name).addValue(clock.getDelta()); + } catch (Exception e) { + try { + String name = (String) pkg + "|" + handler.getClass().getSimpleName(); + data.put(event.getClass(), name, new DescriptiveStatistics(250)); + dataMod.put(event.getClass(), name, ((ModContainer) mod).getName()); + data.get(event.getClass(), name).addValue(clock.getDelta()); + } catch (Exception f) { + } + } + } + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerNetworkTick.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerNetworkTick.java index 05d5d1a..37e390d 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerNetworkTick.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerNetworkTick.java @@ -1,28 +1,26 @@ package mcp.mobius.opis.data.profilers; import mcp.mobius.opis.data.profilers.Clock.IClock; - import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class ProfilerNetworkTick extends ProfilerAbstract { - private IClock clock = Clock.getNewClock(); - public DescriptiveStatistics data = new DescriptiveStatistics(); - - @Override - public void reset() { - data.clear(); - } + private IClock clock = Clock.getNewClock(); + public DescriptiveStatistics data = new DescriptiveStatistics(); - @Override - public void start(){ - clock.start(); - } + @Override + public void reset() { + data.clear(); + } - @Override - public void stop(){ - clock.stop(); - data.addValue(clock.getDelta()); - } - + @Override + public void start() { + clock.start(); + } + + @Override + public void stop() { + clock.stop(); + data.addValue(clock.getDelta()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerPacket.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerPacket.java index a31d9d0..059d6bf 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerPacket.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerPacket.java @@ -1,71 +1,67 @@ package mcp.mobius.opis.data.profilers; -import java.util.ArrayList; -import java.util.HashMap; - -import net.minecraft.network.Packet; import cpw.mods.fml.common.network.internal.FMLProxyPacket; import cpw.mods.fml.relauncher.Side; +import java.util.ArrayList; +import java.util.HashMap; import mcp.mobius.opis.data.holders.newtypes.DataPacket; import mcp.mobius.opis.data.holders.newtypes.DataPacket250; import mcp.mobius.opis.helpers.Helpers; +import net.minecraft.network.Packet; public class ProfilerPacket extends ProfilerAbstract { - public long dataAmount = 0; - public HashMap data = new HashMap(); - public HashMap data250 = new HashMap(); - - public ArrayList jabbaSpec = new ArrayList(); - - public void startInterval(){ - for (DataPacket packet : data.values()) - packet.startInterval(); - - for (DataPacket250 packet : data250.values()) - packet.startInterval(); - } - - @Override - public void reset() { - dataAmount = 0; - } - - @Override - public void start(Object msg, Object size) { - if ((msg != null) && (Helpers.getEffectiveSide() == Side.SERVER)){ - if (!(msg instanceof FMLProxyPacket)){ - Packet pkt = (Packet) msg; - - dataAmount += (Integer)size; - - try{ - data.get(msg.getClass().getSimpleName()).fill(pkt, (Integer)size); - } catch (Exception e){ - data.put(msg.getClass().getSimpleName(), new DataPacket((Packet)msg)); - data.get(msg.getClass().getSimpleName()).fill(pkt, (Integer)size); - } - } - } - } + public long dataAmount = 0; + public HashMap data = new HashMap(); + public HashMap data250 = new HashMap(); - @Override - public void stop(Object msg) { - if ((msg != null) && (Helpers.getEffectiveSide() == Side.SERVER)){ - if (msg instanceof FMLProxyPacket){ - FMLProxyPacket pkt = (FMLProxyPacket) msg; - String channel = pkt.channel(); - int pktsize = pkt.payload().capacity(); - dataAmount += pktsize; - - try{ - data250.get(channel).fill(pkt, pktsize); - } catch (Exception e){ - data250.put(channel, new DataPacket250(channel)); - data250.get(channel).fill(pkt, pktsize); - } - } - } - } - + public ArrayList jabbaSpec = new ArrayList(); + + public void startInterval() { + for (DataPacket packet : data.values()) packet.startInterval(); + + for (DataPacket250 packet : data250.values()) packet.startInterval(); + } + + @Override + public void reset() { + dataAmount = 0; + } + + @Override + public void start(Object msg, Object size) { + if ((msg != null) && (Helpers.getEffectiveSide() == Side.SERVER)) { + if (!(msg instanceof FMLProxyPacket)) { + Packet pkt = (Packet) msg; + + dataAmount += (Integer) size; + + try { + data.get(msg.getClass().getSimpleName()).fill(pkt, (Integer) size); + } catch (Exception e) { + data.put(msg.getClass().getSimpleName(), new DataPacket((Packet) msg)); + data.get(msg.getClass().getSimpleName()).fill(pkt, (Integer) size); + } + } + } + } + + @Override + public void stop(Object msg) { + if ((msg != null) && (Helpers.getEffectiveSide() == Side.SERVER)) { + if (msg instanceof FMLProxyPacket) { + FMLProxyPacket pkt = (FMLProxyPacket) msg; + String channel = pkt.channel(); + int pktsize = pkt.payload().capacity(); + dataAmount += pktsize; + + try { + data250.get(channel).fill(pkt, pktsize); + } catch (Exception e) { + data250.put(channel, new DataPacket250(channel)); + data250.get(channel).fill(pkt, pktsize); + } + } + } + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderBlock.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderBlock.java index 153aaa0..18d4e8d 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderBlock.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderBlock.java @@ -1,7 +1,6 @@ package mcp.mobius.opis.data.profilers; import java.util.HashMap; - import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.profilers.Clock.IClock; import net.minecraft.client.Minecraft; @@ -9,28 +8,28 @@ import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class ProfilerRenderBlock extends ProfilerAbstract { - private IClock clock = Clock.getNewClock(); - public HashMap data = new HashMap(); - - @Override - public void reset() { - } + private IClock clock = Clock.getNewClock(); + public HashMap data = + new HashMap(); - @Override - public void start(Object key1, Object key2, Object key3, Object key4) { - CoordinatesBlock coord = new CoordinatesBlock(Minecraft.getMinecraft().theWorld.provider.dimensionId, (Integer)key2, (Integer)key3, (Integer)key4); - - if (!data.containsKey(coord)) - data.put(coord, new DescriptiveStatistics()); - clock.start(); - } - - @Override - public void stop(Object key1, Object key2, Object key3, Object key4) { - CoordinatesBlock coord = new CoordinatesBlock(Minecraft.getMinecraft().theWorld.provider.dimensionId, (Integer)key2, (Integer)key3, (Integer)key4); - - clock.stop(); - data.get(coord).addValue(clock.getDelta()); - } - + @Override + public void reset() {} + + @Override + public void start(Object key1, Object key2, Object key3, Object key4) { + CoordinatesBlock coord = new CoordinatesBlock( + Minecraft.getMinecraft().theWorld.provider.dimensionId, (Integer) key2, (Integer) key3, (Integer) key4); + + if (!data.containsKey(coord)) data.put(coord, new DescriptiveStatistics()); + clock.start(); + } + + @Override + public void stop(Object key1, Object key2, Object key3, Object key4) { + CoordinatesBlock coord = new CoordinatesBlock( + Minecraft.getMinecraft().theWorld.provider.dimensionId, (Integer) key2, (Integer) key3, (Integer) key4); + + clock.stop(); + data.get(coord).addValue(clock.getDelta()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderEntity.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderEntity.java index 2160e3c..0492498 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderEntity.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderEntity.java @@ -1,40 +1,37 @@ package mcp.mobius.opis.data.profilers; import java.util.WeakHashMap; - -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.data.profilers.Clock.IClock; +import mcp.mobius.opis.modOpis; import net.minecraft.entity.Entity; - import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class ProfilerRenderEntity extends ProfilerAbstract { - public WeakHashMap data = new WeakHashMap(); - private IClock clock = Clock.getNewClock(); - - @Override - public void reset() { - data.clear(); - } + public WeakHashMap data = new WeakHashMap(); + private IClock clock = Clock.getNewClock(); - @Override - public void start(Object key){ - Entity entity = (Entity)key; - if (!data.containsKey(entity)) - data.put(entity, new DescriptiveStatistics()); - - clock.start(); - } - - @Override - public void stop(Object key){ - clock.stop(); - try{ - //data.get((Entity)key).addValue((double)clock.getDelta()); - data.get(key).addValue(clock.getDelta()); - } catch (Exception e) { - modOpis.log.warn(String.format("Error while profiling entity %s\n", key)); - } - } -} \ No newline at end of file + @Override + public void reset() { + data.clear(); + } + + @Override + public void start(Object key) { + Entity entity = (Entity) key; + if (!data.containsKey(entity)) data.put(entity, new DescriptiveStatistics()); + + clock.start(); + } + + @Override + public void stop(Object key) { + clock.stop(); + try { + // data.get((Entity)key).addValue((double)clock.getDelta()); + data.get(key).addValue(clock.getDelta()); + } catch (Exception e) { + modOpis.log.warn(String.format("Error while profiling entity %s\n", key)); + } + } +} diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderTileEntity.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderTileEntity.java index 49b0347..3fb7464 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderTileEntity.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderTileEntity.java @@ -1,39 +1,36 @@ package mcp.mobius.opis.data.profilers; import java.util.WeakHashMap; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.data.profilers.Clock.IClock; +import mcp.mobius.opis.modOpis; import net.minecraft.tileentity.TileEntity; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class ProfilerRenderTileEntity extends ProfilerAbstract { - public WeakHashMap data = new WeakHashMap(); - private IClock clock = Clock.getNewClock(); - - @Override - public void reset() { - data.clear(); - } + public WeakHashMap data = new WeakHashMap(); + private IClock clock = Clock.getNewClock(); - @Override - public void start(Object key){ - TileEntity tileEnt = (TileEntity)key; - if (!data.containsKey(tileEnt)) - data.put(tileEnt, new DescriptiveStatistics()); - - clock.start(); - } - - @Override - public void stop(Object key){ - clock.stop(); - try{ - data.get(key).addValue(clock.getDelta()); - } catch (Exception e) { - modOpis.log.warn(String.format("Error while profiling entity %s\n", key)); - } - } + @Override + public void reset() { + data.clear(); + } + + @Override + public void start(Object key) { + TileEntity tileEnt = (TileEntity) key; + if (!data.containsKey(tileEnt)) data.put(tileEnt, new DescriptiveStatistics()); + + clock.start(); + } + + @Override + public void stop(Object key) { + clock.stop(); + try { + data.get(key).addValue(clock.getDelta()); + } catch (Exception e) { + modOpis.log.warn(String.format("Error while profiling entity %s\n", key)); + } + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerTick.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerTick.java index 330bd6b..efdd36a 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerTick.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerTick.java @@ -1,29 +1,27 @@ package mcp.mobius.opis.data.profilers; import mcp.mobius.opis.data.profilers.Clock.IClock; - import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class ProfilerTick extends ProfilerAbstract { - private IClock clock = Clock.getNewClock(); - public DescriptiveStatistics data = new DescriptiveStatistics(20); - - @Override - public void reset() { - //this.data.clear(); - } - - @Override - public void start() { - //DeadManSwitch.instance.setTimer(System.nanoTime()); - this.clock.start(); - } - - @Override - public void stop() { - this.clock.stop(); - this.data.addValue(clock.getDelta()); - } - + private IClock clock = Clock.getNewClock(); + public DescriptiveStatistics data = new DescriptiveStatistics(20); + + @Override + public void reset() { + // this.data.clear(); + } + + @Override + public void start() { + // DeadManSwitch.instance.setTimer(System.nanoTime()); + this.clock.start(); + } + + @Override + public void stop() { + this.clock.stop(); + this.data.addValue(clock.getDelta()); + } } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerTileEntityUpdate.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerTileEntityUpdate.java index 464cc51..7774f0c 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerTileEntityUpdate.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerTileEntityUpdate.java @@ -1,46 +1,46 @@ package mcp.mobius.opis.data.profilers; import java.util.HashMap; -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; - import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.profilers.Clock.IClock; import net.minecraft.tileentity.TileEntity; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public class ProfilerTileEntityUpdate extends ProfilerAbstract { - private IClock clock = Clock.getNewClock(); - public HashMap data = new HashMap(); - public HashMap refs = new HashMap(); - - @Override - public void reset() { - this.data.clear(); - this.refs.clear(); - } - - @Override - public void start(Object key) { - TileEntity tileent = (TileEntity)key; - if (tileent.getWorldObj().isRemote) return; - - CoordinatesBlock coord = new CoordinatesBlock(tileent); - - if (!data.containsKey(coord) || (refs.get(coord) != tileent.getClass())){ - data.put(coord, new DescriptiveStatistics()); - refs.put(coord, tileent.getClass()); - } - clock.start(); - } - - @Override - public void stop(Object key) { - TileEntity tileent = (TileEntity)key; - if (tileent.getWorldObj().isRemote) return; - - clock.stop(); - CoordinatesBlock coord = new CoordinatesBlock(tileent); + private IClock clock = Clock.getNewClock(); + public HashMap data = + new HashMap(); + public HashMap refs = new HashMap(); - data.get(coord).addValue(clock.getDelta()); - } + @Override + public void reset() { + this.data.clear(); + this.refs.clear(); + } + + @Override + public void start(Object key) { + TileEntity tileent = (TileEntity) key; + if (tileent.getWorldObj().isRemote) return; + + CoordinatesBlock coord = new CoordinatesBlock(tileent); + + if (!data.containsKey(coord) || (refs.get(coord) != tileent.getClass())) { + data.put(coord, new DescriptiveStatistics()); + refs.put(coord, tileent.getClass()); + } + clock.start(); + } + + @Override + public void stop(Object key) { + TileEntity tileent = (TileEntity) key; + if (tileent.getWorldObj().isRemote) return; + + clock.stop(); + CoordinatesBlock coord = new CoordinatesBlock(tileent); + + data.get(coord).addValue(clock.getDelta()); + } } diff --git a/src/main/java/mcp/mobius/opis/events/EventTimer.java b/src/main/java/mcp/mobius/opis/events/EventTimer.java index c1a39dc..165dad2 100644 --- a/src/main/java/mcp/mobius/opis/events/EventTimer.java +++ b/src/main/java/mcp/mobius/opis/events/EventTimer.java @@ -1,20 +1,20 @@ package mcp.mobius.opis.events; public class EventTimer { - private long interval; - private long lastTick = System.nanoTime(); - - public EventTimer(long interval){ - this.interval = interval * 1000L * 1000L; //Interval is passed in millisecond but stored in nanosecond. - } - - public boolean isDone(){ - long time = System.nanoTime(); - long delta = (time - this.lastTick) - this.interval; - boolean done = delta >= 0; - if (!done) return false; - - this.lastTick = time - delta; - return true; - } + private long interval; + private long lastTick = System.nanoTime(); + + public EventTimer(long interval) { + this.interval = interval * 1000L * 1000L; // Interval is passed in millisecond but stored in nanosecond. + } + + public boolean isDone() { + long time = System.nanoTime(); + long delta = (time - this.lastTick) - this.interval; + boolean done = delta >= 0; + if (!done) return false; + + this.lastTick = time - delta; + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/events/OpisClientEventHandler.java b/src/main/java/mcp/mobius/opis/events/OpisClientEventHandler.java index bd4af99..2188f8f 100644 --- a/src/main/java/mcp/mobius/opis/events/OpisClientEventHandler.java +++ b/src/main/java/mcp/mobius/opis/events/OpisClientEventHandler.java @@ -1,7 +1,5 @@ package mcp.mobius.opis.events; -import org.lwjgl.opengl.GL11; - import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -10,81 +8,83 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.EntityLivingBase; import net.minecraftforge.client.event.RenderWorldLastEvent; +import org.lwjgl.opengl.GL11; public class OpisClientEventHandler { - @SubscribeEvent + @SubscribeEvent @SideOnly(Side.CLIENT) public void onRenderWorldLast(RenderWorldLastEvent event) { - if (modOpis.selectedBlock == null) return; - if (Minecraft.getMinecraft().theWorld.provider.dimensionId != modOpis.selectedBlock.dim) return; - if (Minecraft.getMinecraft().theWorld.isAirBlock(modOpis.selectedBlock.x, modOpis.selectedBlock.y, modOpis.selectedBlock.z)) return; - - double partialTicks = event.partialTicks; + if (modOpis.selectedBlock == null) return; + if (Minecraft.getMinecraft().theWorld.provider.dimensionId != modOpis.selectedBlock.dim) return; + if (Minecraft.getMinecraft() + .theWorld + .isAirBlock(modOpis.selectedBlock.x, modOpis.selectedBlock.y, modOpis.selectedBlock.z)) return; - EntityLivingBase player = Minecraft.getMinecraft().renderViewEntity; - double px = player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTicks; - double py = player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTicks; - double pz = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTicks; + double partialTicks = event.partialTicks; - int bx = modOpis.selectedBlock.x; - int by = modOpis.selectedBlock.y; - int bz = modOpis.selectedBlock.z; + EntityLivingBase player = Minecraft.getMinecraft().renderViewEntity; + double px = player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTicks; + double py = player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTicks; + double pz = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTicks; - double offset = 0.02; - double delta = 1 + 2 * offset; + int bx = modOpis.selectedBlock.x; + int by = modOpis.selectedBlock.y; + int bz = modOpis.selectedBlock.z; - double x = bx - px - offset; - double y = by - py - offset; - double z = bz - pz - offset; + double offset = 0.02; + double delta = 1 + 2 * offset; - GL11.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); + double x = bx - px - offset; + double y = by - py - offset; + double z = bz - pz - offset; - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glDepthMask(false); + GL11.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glDepthMask(false); - tessellator.setColorRGBA(255, 0, 0, 150); + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); - tessellator.addVertex(x, y, z); - tessellator.addVertex(x + delta, y, z); - tessellator.addVertex(x + delta, y, z + delta); - tessellator.addVertex(x, y, z + delta); + tessellator.setColorRGBA(255, 0, 0, 150); - tessellator.addVertex(x, y + delta, z); - tessellator.addVertex(x, y + delta, z + delta); - tessellator.addVertex(x + delta, y + delta, z + delta); - tessellator.addVertex(x + delta, y + delta, z); + tessellator.addVertex(x, y, z); + tessellator.addVertex(x + delta, y, z); + tessellator.addVertex(x + delta, y, z + delta); + tessellator.addVertex(x, y, z + delta); - tessellator.addVertex(x, y, z); - tessellator.addVertex(x, y + delta, z); - tessellator.addVertex(x + delta, y + delta, z); - tessellator.addVertex(x + delta, y, z); + tessellator.addVertex(x, y + delta, z); + tessellator.addVertex(x, y + delta, z + delta); + tessellator.addVertex(x + delta, y + delta, z + delta); + tessellator.addVertex(x + delta, y + delta, z); - tessellator.addVertex(x, y, z + delta); - tessellator.addVertex(x + delta, y, z + delta); - tessellator.addVertex(x + delta, y + delta, z + delta); - tessellator.addVertex(x, y + delta, z + delta); + tessellator.addVertex(x, y, z); + tessellator.addVertex(x, y + delta, z); + tessellator.addVertex(x + delta, y + delta, z); + tessellator.addVertex(x + delta, y, z); - tessellator.addVertex(x, y, z); - tessellator.addVertex(x, y, z + delta); - tessellator.addVertex(x, y + delta, z + delta); - tessellator.addVertex(x, y + delta, z); + tessellator.addVertex(x, y, z + delta); + tessellator.addVertex(x + delta, y, z + delta); + tessellator.addVertex(x + delta, y + delta, z + delta); + tessellator.addVertex(x, y + delta, z + delta); - tessellator.addVertex(x + delta, y, z); - tessellator.addVertex(x + delta, y + delta, z); - tessellator.addVertex(x + delta, y + delta, z + delta); - tessellator.addVertex(x + delta, y, z + delta); + tessellator.addVertex(x, y, z); + tessellator.addVertex(x, y, z + delta); + tessellator.addVertex(x, y + delta, z + delta); + tessellator.addVertex(x, y + delta, z); - tessellator.draw(); + tessellator.addVertex(x + delta, y, z); + tessellator.addVertex(x + delta, y + delta, z); + tessellator.addVertex(x + delta, y + delta, z + delta); + tessellator.addVertex(x + delta, y, z + delta); - GL11.glEnable(GL11.GL_TEXTURE_2D); + tessellator.draw(); - GL11.glPopAttrib(); - } - + GL11.glEnable(GL11.GL_TEXTURE_2D); + + GL11.glPopAttrib(); + } } diff --git a/src/main/java/mcp/mobius/opis/events/OpisClientTickHandler.java b/src/main/java/mcp/mobius/opis/events/OpisClientTickHandler.java index 9c40729..8afd1fe 100644 --- a/src/main/java/mcp/mobius/opis/events/OpisClientTickHandler.java +++ b/src/main/java/mcp/mobius/opis/events/OpisClientTickHandler.java @@ -6,13 +6,15 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.Collections; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.basetypes.SerialLong; -import mcp.mobius.opis.data.holders.clienttypes.DataRenderEvent; import mcp.mobius.opis.data.holders.clienttypes.DataBlockRender; import mcp.mobius.opis.data.holders.clienttypes.DataEntityRender; +import mcp.mobius.opis.data.holders.clienttypes.DataRenderEvent; import mcp.mobius.opis.data.holders.newtypes.DataTileEntityRender; import mcp.mobius.opis.data.profilers.ProfilerEvent; import mcp.mobius.opis.data.profilers.ProfilerRenderBlock; @@ -31,137 +33,153 @@ import net.minecraft.entity.Entity; import net.minecraft.tileentity.TileEntity; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; -import java.util.ArrayList; -import java.util.Collections; +public enum OpisClientTickHandler { + INSTANCE; -public enum OpisClientTickHandler{ - INSTANCE; - - public long profilerUpdateTickCounter = 0; - public long profilerRunningTicks = 0; - public EventTimer timer500 = new EventTimer(500); - public EventTimer timer1000 = new EventTimer(1000); - public EventTimer timer2000 = new EventTimer(2000); - public EventTimer timer5000 = new EventTimer(5000); - public EventTimer timer10000 = new EventTimer(10000); - - @SubscribeEvent - @SideOnly(Side.CLIENT) - public void tickEnd(TickEvent.ClientTickEvent event) { - - // One second timer - if (timer1000.isDone()){ - if(modOpis.swingOpen) - PacketManager.sendToServer(new PacketReqData(Message.STATUS_PING, new SerialLong(System.nanoTime()))); - } - - - - if (modOpis.profilerRunClient){ - ((PanelRenderTileEnts)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERTILEENTS))).getBtnRunRender().setText("Running..."); - ((PanelRenderEntities)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERENTITIES))).getBtnRunRender().setText("Running..."); - ((PanelRenderHandlers)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERHANDLERS))).getBtnRunRender().setText("Running..."); - ((PanelEventClient)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.CLIENTEVENTS))).getBtnRunRender().setText("Running..."); - } - else{ - ((PanelRenderTileEnts)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERTILEENTS))).getBtnRunRender().setText("Run Render"); - ((PanelRenderEntities)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERENTITIES))).getBtnRunRender().setText("Run Render"); - ((PanelRenderHandlers)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERHANDLERS))).getBtnRunRender().setText("Run Render"); - ((PanelEventClient)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.CLIENTEVENTS))).getBtnRunRender().setText("Run Render"); - } - - profilerUpdateTickCounter++; - - if (profilerRunningTicks < modOpis.profilerMaxTicks && modOpis.profilerRunClient){ - profilerRunningTicks++; - }else if (profilerRunningTicks >= modOpis.profilerMaxTicks && modOpis.profilerRunClient){ - profilerRunningTicks = 0; - modOpis.profilerRunClient = false; - ProfilerSection.desactivateAll(Side.CLIENT); - - System.out.printf("Profiling done\n"); + public long profilerUpdateTickCounter = 0; + public long profilerRunningTicks = 0; + public EventTimer timer500 = new EventTimer(500); + public EventTimer timer1000 = new EventTimer(1000); + public EventTimer timer2000 = new EventTimer(2000); + public EventTimer timer5000 = new EventTimer(5000); + public EventTimer timer10000 = new EventTimer(10000); - this.updateTabs(); - - } - } + @SubscribeEvent + @SideOnly(Side.CLIENT) + public void tickEnd(TickEvent.ClientTickEvent event) { - private void updateTabs(){ - //==================================================================================== - - ArrayList tileEntData = new ArrayList(); - double tileEntTotal = 0.0D; - for (TileEntity te : ((ProfilerRenderTileEntity)ProfilerSection.RENDER_TILEENTITY.getProfiler()).data.keySet()){ - try{ - DataTileEntityRender dataTe = new DataTileEntityRender().fill(te); - tileEntData.add(dataTe); - tileEntTotal += dataTe.update.timing; - } catch (Exception e) { - modOpis.log.warn(String.format("Error while adding entity %s to the list", te)); - } - } + // One second timer + if (timer1000.isDone()) { + if (modOpis.swingOpen) + PacketManager.sendToServer(new PacketReqData(Message.STATUS_PING, new SerialLong(System.nanoTime()))); + } - System.out.printf("Rendered %d TileEntities\n", tileEntData.size()); - - Collections.sort(tileEntData); - ((PanelRenderTileEnts)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERTILEENTS))).setTable(tileEntData); - ((PanelRenderTileEnts)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERTILEENTS))).getLblTotal().setText(String.format("Total : %.3f µs", tileEntTotal / 1000.0)); - - //==================================================================================== - - ArrayList entData = new ArrayList(); - double entTotal = 0.0D; - for (Entity ent : ((ProfilerRenderEntity)ProfilerSection.RENDER_ENTITY.getProfiler()).data.keySet()){ - try{ - DataEntityRender dataEnt = new DataEntityRender().fill(ent); - entData.add(dataEnt); - entTotal += dataEnt.update.timing; - } catch (Exception e) { - modOpis.log.warn(String.format("Error while adding entity %s to the list", ent)); - } - } + if (modOpis.profilerRunClient) { + ((PanelRenderTileEnts) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERTILEENTS))) + .getBtnRunRender() + .setText("Running..."); + ((PanelRenderEntities) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERENTITIES))) + .getBtnRunRender() + .setText("Running..."); + ((PanelRenderHandlers) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERHANDLERS))) + .getBtnRunRender() + .setText("Running..."); + ((PanelEventClient) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.CLIENTEVENTS))) + .getBtnRunRender() + .setText("Running..."); + } else { + ((PanelRenderTileEnts) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERTILEENTS))) + .getBtnRunRender() + .setText("Run Render"); + ((PanelRenderEntities) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERENTITIES))) + .getBtnRunRender() + .setText("Run Render"); + ((PanelRenderHandlers) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERHANDLERS))) + .getBtnRunRender() + .setText("Run Render"); + ((PanelEventClient) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.CLIENTEVENTS))) + .getBtnRunRender() + .setText("Run Render"); + } - System.out.printf("Rendered %d Entities\n", entData.size()); - - Collections.sort(entData); - ((PanelRenderEntities)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERENTITIES))).setTable(entData); - ((PanelRenderEntities)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERENTITIES))).getLblTotal().setText(String.format("Total : %.3f µs", entTotal / 1000.0)); + profilerUpdateTickCounter++; - //==================================================================================== - - //((PanelRenderHandlers)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERHANDLERS))).setTable(TickHandlerManager.getCumulatedStatsRender()); - - //==================================================================================== - - ArrayList timingEvents = new ArrayList(); - HashBasedTable eventData = ((ProfilerEvent)ProfilerSection.EVENT_INVOKE.getProfiler()).data; - HashBasedTable eventMod = ((ProfilerEvent)ProfilerSection.EVENT_INVOKE.getProfiler()).dataMod; - for (Cell cell : eventData.cellSet()){ - timingEvents.add(new DataRenderEvent().fill(cell, eventMod.get(cell.getRowKey(), cell.getColumnKey()))); - } - ((PanelEventClient)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.CLIENTEVENTS))).setTable(timingEvents); - - //==================================================================================== - - ArrayList blockData = new ArrayList(); - for (CoordinatesBlock coord : ((ProfilerRenderBlock)ProfilerSection.RENDER_BLOCK.getProfiler()).data.keySet()){ - try{ - DataBlockRender dataBlock = new DataBlockRender().fill(coord); - blockData.add(dataBlock); - } catch (Exception e) { - modOpis.log.warn(String.format("Error while adding block %s to the list", coord)); - } - } + if (profilerRunningTicks < modOpis.profilerMaxTicks && modOpis.profilerRunClient) { + profilerRunningTicks++; + } else if (profilerRunningTicks >= modOpis.profilerMaxTicks && modOpis.profilerRunClient) { + profilerRunningTicks = 0; + modOpis.profilerRunClient = false; + ProfilerSection.desactivateAll(Side.CLIENT); - /* - Collections.sort(blockData); - for (DataBlockRender data : blockData){ - ItemStack stack = new ItemStack(data.id, 0, data.meta); - String name = stack.getDisplayName(); - - System.out.printf("%s %s : %s\n", data.pos, name, data.update); - } - */ - } - + System.out.printf("Profiling done\n"); + + this.updateTabs(); + } + } + + private void updateTabs() { + // ==================================================================================== + + ArrayList tileEntData = new ArrayList(); + double tileEntTotal = 0.0D; + for (TileEntity te : + ((ProfilerRenderTileEntity) ProfilerSection.RENDER_TILEENTITY.getProfiler()).data.keySet()) { + try { + DataTileEntityRender dataTe = new DataTileEntityRender().fill(te); + tileEntData.add(dataTe); + tileEntTotal += dataTe.update.timing; + } catch (Exception e) { + modOpis.log.warn(String.format("Error while adding entity %s to the list", te)); + } + } + + System.out.printf("Rendered %d TileEntities\n", tileEntData.size()); + + Collections.sort(tileEntData); + ((PanelRenderTileEnts) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERTILEENTS))).setTable(tileEntData); + ((PanelRenderTileEnts) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERTILEENTS))) + .getLblTotal() + .setText(String.format("Total : %.3f µs", tileEntTotal / 1000.0)); + + // ==================================================================================== + + ArrayList entData = new ArrayList(); + double entTotal = 0.0D; + for (Entity ent : ((ProfilerRenderEntity) ProfilerSection.RENDER_ENTITY.getProfiler()).data.keySet()) { + try { + DataEntityRender dataEnt = new DataEntityRender().fill(ent); + entData.add(dataEnt); + entTotal += dataEnt.update.timing; + } catch (Exception e) { + modOpis.log.warn(String.format("Error while adding entity %s to the list", ent)); + } + } + + System.out.printf("Rendered %d Entities\n", entData.size()); + + Collections.sort(entData); + ((PanelRenderEntities) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERENTITIES))).setTable(entData); + ((PanelRenderEntities) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERENTITIES))) + .getLblTotal() + .setText(String.format("Total : %.3f µs", entTotal / 1000.0)); + + // ==================================================================================== + + // ((PanelRenderHandlers)(TabPanelRegistrar.INSTANCE.getTab(SelectedTab.RENDERHANDLERS))).setTable(TickHandlerManager.getCumulatedStatsRender()); + + // ==================================================================================== + + ArrayList timingEvents = new ArrayList(); + HashBasedTable eventData = + ((ProfilerEvent) ProfilerSection.EVENT_INVOKE.getProfiler()).data; + HashBasedTable eventMod = + ((ProfilerEvent) ProfilerSection.EVENT_INVOKE.getProfiler()).dataMod; + for (Cell cell : eventData.cellSet()) { + timingEvents.add(new DataRenderEvent().fill(cell, eventMod.get(cell.getRowKey(), cell.getColumnKey()))); + } + ((PanelEventClient) (TabPanelRegistrar.INSTANCE.getTab(SelectedTab.CLIENTEVENTS))).setTable(timingEvents); + + // ==================================================================================== + + ArrayList blockData = new ArrayList(); + for (CoordinatesBlock coord : + ((ProfilerRenderBlock) ProfilerSection.RENDER_BLOCK.getProfiler()).data.keySet()) { + try { + DataBlockRender dataBlock = new DataBlockRender().fill(coord); + blockData.add(dataBlock); + } catch (Exception e) { + modOpis.log.warn(String.format("Error while adding block %s to the list", coord)); + } + } + + /* + Collections.sort(blockData); + for (DataBlockRender data : blockData){ + ItemStack stack = new ItemStack(data.id, 0, data.meta); + String name = stack.getDisplayName(); + + System.out.printf("%s %s : %s\n", data.pos, name, data.update); + } + */ + } } diff --git a/src/main/java/mcp/mobius/opis/events/OpisServerEventHandler.java b/src/main/java/mcp/mobius/opis/events/OpisServerEventHandler.java index d94a989..9404d89 100644 --- a/src/main/java/mcp/mobius/opis/events/OpisServerEventHandler.java +++ b/src/main/java/mcp/mobius/opis/events/OpisServerEventHandler.java @@ -1,6 +1,8 @@ package mcp.mobius.opis.events; -import mcp.mobius.opis.modOpis; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import mcp.mobius.opis.data.holders.newtypes.ChatMsg; import mcp.mobius.opis.data.holders.newtypes.PlayerStatus; import mcp.mobius.opis.network.PacketManager; @@ -8,82 +10,83 @@ import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.enums.PlayerEv; import mcp.mobius.opis.network.packets.server.NetDataValue; import mcp.mobius.opis.network.rcon.RConHandler; -import mcp.mobius.opis.network.rcon.nexus.NexusClient; -import mcp.mobius.opis.network.rcon.server.RConServer; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.event.ServerChatEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.world.WorldEvent; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; public class OpisServerEventHandler { - public static boolean printEntityTrace = false; - public static boolean printEntityFull = false; - - public static boolean firstLoad = false; - - @SubscribeEvent + public static boolean printEntityTrace = false; + public static boolean printEntityFull = false; + + public static boolean firstLoad = false; + + @SubscribeEvent @SideOnly(Side.SERVER) public void onWorldLoad(WorldEvent.Load event) { - - /* - if (!firstLoad && event.world.provider.dimensionId == 0){ - firstLoad = true; - - Thread rconserver = new Thread(RConServer.instance); - rconserver.setName("Opis Server"); - rconserver.start(); - Thread nexusclient = new Thread(NexusClient.instance); - nexusclient.setName("Nexus Client"); - nexusclient.start(); - - } - */ - - } - - @SubscribeEvent - public void onPlayerDeath(LivingDeathEvent event){ - if (event.entityLiving instanceof EntityPlayer){ - EntityPlayer p = (EntityPlayer)event.entityLiving; - PacketManager.sendPacketToAllSwing(new NetDataValue(Message.PLAYER_STATUS_UPDATE, - new PlayerStatus(p.getGameProfile().getName(), PlayerEv.DEATH, - p.worldObj.provider.dimensionId, (int)p.posX, (int)p.posY, (int)p.posZ))); - } - } - - @SubscribeEvent - public void onChatMessage(ServerChatEvent event){ - RConHandler.sendToAllNexus(new NetDataValue(Message.CHAT_MSG, new ChatMsg(event.username, event.message))); - } - - /* - @SubscribeEvent - @SideOnly(Side.SERVER) - public void onEntityConstructed(EntityEvent.EntityConstructing event) { - if (printEntityTrace){ + /* + if (!firstLoad && event.world.provider.dimensionId == 0){ + firstLoad = true; - if (event.entity instanceof EntityItem){ - System.out.printf("Entity %s of type %s [ %s ] created\n", event.entity.getEntityId(), event.entity.getClass().getName(), ((EntityItem)(event.entity)).getEntityItem().getDisplayName()); - - - } else { - System.out.printf("Entity %s of type %s created\n", event.entity.getEntityId(), event.entity.getClass().getName()); - } - - - if (printEntityFull){ - try{ - throw new RuntimeException(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - */ + Thread rconserver = new Thread(RConServer.instance); + rconserver.setName("Opis Server"); + rconserver.start(); + + Thread nexusclient = new Thread(NexusClient.instance); + nexusclient.setName("Nexus Client"); + nexusclient.start(); + + } + */ + + } + + @SubscribeEvent + public void onPlayerDeath(LivingDeathEvent event) { + if (event.entityLiving instanceof EntityPlayer) { + EntityPlayer p = (EntityPlayer) event.entityLiving; + PacketManager.sendPacketToAllSwing(new NetDataValue( + Message.PLAYER_STATUS_UPDATE, + new PlayerStatus( + p.getGameProfile().getName(), + PlayerEv.DEATH, + p.worldObj.provider.dimensionId, + (int) p.posX, + (int) p.posY, + (int) p.posZ))); + } + } + + @SubscribeEvent + public void onChatMessage(ServerChatEvent event) { + RConHandler.sendToAllNexus(new NetDataValue(Message.CHAT_MSG, new ChatMsg(event.username, event.message))); + } + + /* + @SubscribeEvent + @SideOnly(Side.SERVER) + public void onEntityConstructed(EntityEvent.EntityConstructing event) { + if (printEntityTrace){ + + if (event.entity instanceof EntityItem){ + System.out.printf("Entity %s of type %s [ %s ] created\n", event.entity.getEntityId(), event.entity.getClass().getName(), ((EntityItem)(event.entity)).getEntityItem().getDisplayName()); + + + } else { + System.out.printf("Entity %s of type %s created\n", event.entity.getEntityId(), event.entity.getClass().getName()); + } + + + if (printEntityFull){ + try{ + throw new RuntimeException(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + */ } diff --git a/src/main/java/mcp/mobius/opis/events/OpisServerTickHandler.java b/src/main/java/mcp/mobius/opis/events/OpisServerTickHandler.java index c8ae674..6800884 100644 --- a/src/main/java/mcp/mobius/opis/events/OpisServerTickHandler.java +++ b/src/main/java/mcp/mobius/opis/events/OpisServerTickHandler.java @@ -4,6 +4,8 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.relauncher.Side; +import java.util.ArrayList; +import java.util.HashMap; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.basetypes.SerialInt; import mcp.mobius.opis.data.holders.basetypes.SerialLong; @@ -23,118 +25,144 @@ import mcp.mobius.opis.network.packets.server.NetDataValue; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.common.DimensionManager; -import java.util.ArrayList; -import java.util.HashMap; +public enum OpisServerTickHandler { + INSTANCE; -public enum OpisServerTickHandler{ - INSTANCE; - - public long profilerUpdateTickCounter = 0; - public int profilerRunningTicks; - public EventTimer timer500 = new EventTimer(500); - public EventTimer timer1000 = new EventTimer(1000); - public EventTimer timer2000 = new EventTimer(2000); - public EventTimer timer5000 = new EventTimer(5000); - public EventTimer timer10000 = new EventTimer(10000); - - public HashMap cachedAccess = new HashMap(); - - @SubscribeEvent - public void tickEnd(TickEvent.ServerTickEvent event) { - - StringCache.INSTANCE.syncNewCache(); - - // One second timer - if (timer1000.isDone() && PlayerTracker.INSTANCE.playersSwing.size() > 0){ - - DataTiming tickTiming = new DataTiming(((ProfilerTick)ProfilerSection.TICK.getProfiler()).data.getGeometricMean()); - if (!tickTiming.timing.isNaN()){ - PacketManager.sendPacketToAllSwing(new NetDataValue(Message.NEXUS_DATA, - new NexusData( - new SerialLong(((ProfilerPacket)ProfilerSection.PACKET_OUTBOUND.getProfiler()).dataAmount), - new SerialLong(((ProfilerPacket)ProfilerSection.PACKET_INBOUND.getProfiler()).dataAmount), - new SerialInt(ChunkManager.INSTANCE.getForcedChunkAmount()), - new SerialInt(ChunkManager.INSTANCE.getLoadedChunkAmount()), - new DataTiming(((ProfilerTick)ProfilerSection.TICK.getProfiler()).data.getGeometricMean()), - new SerialInt(TileEntityManager.INSTANCE.getAmountTileEntities()), - new SerialInt(EntityManager.INSTANCE.getAmountEntities()), - new SerialInt(FMLCommonHandler.instance().getMinecraftServerInstance().getCurrentPlayerCount()) - ))); - } - // End of summary update - - - for (EntityPlayerMP player : PlayerTracker.INSTANCE.playersSwing){ - if (!cachedAccess.containsKey(player) || cachedAccess.get(player) != PlayerTracker.INSTANCE.getPlayerAccessLevel(player)){ - PacketManager.validateAndSend(new NetDataValue(Message.STATUS_ACCESS_LEVEL, new SerialInt(PlayerTracker.INSTANCE.getPlayerAccessLevel(player).ordinal())), player); - cachedAccess.put(player, PlayerTracker.INSTANCE.getPlayerAccessLevel(player)); - } - } - - // Dimension data update. - ArrayList dimData = new ArrayList(); - for (int dim : DimensionManager.getIDs()){ - dimData.add(new DataDimension().fill(dim)); - } - PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_DIMENSION_DATA, dimData)); + public long profilerUpdateTickCounter = 0; + public int profilerRunningTicks; + public EventTimer timer500 = new EventTimer(500); + public EventTimer timer1000 = new EventTimer(1000); + public EventTimer timer2000 = new EventTimer(2000); + public EventTimer timer5000 = new EventTimer(5000); + public EventTimer timer10000 = new EventTimer(10000); - // Profiler update (if running) - if (modOpis.profilerRun){ - PacketManager.sendPacketToAllSwing(new NetDataValue(Message.STATUS_RUNNING, new SerialInt(modOpis.profilerMaxTicks))); - PacketManager.sendPacketToAllSwing(new NetDataValue(Message.STATUS_RUN_UPDATE, new SerialInt(profilerRunningTicks))); - } - - ((ProfilerPacket)ProfilerSection.PACKET_INBOUND.getProfiler()).dataAmount = 0L; - ((ProfilerPacket)ProfilerSection.PACKET_OUTBOUND.getProfiler()).dataAmount = 0L; - } - - // Two second timer - if (timer2000.isDone() && PlayerTracker.INSTANCE.playersSwing.size() > 0){ - ArrayList threads = new ArrayList(); - for (Thread t : Thread.getAllStackTraces().keySet()){ - threads.add(new DataThread().fill(t)); - } - PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_THREADS, threads)); - - PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_PLAYERS, EntityManager.INSTANCE.getAllPlayers())); - } - - // Five second timer - if (timer5000.isDone() && PlayerTracker.INSTANCE.playersSwing.size() > 0){ - PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_AMOUNT_ENTITIES, EntityManager.INSTANCE.getCumulativeEntities(false))); - PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_AMOUNT_TILEENTS, TileEntityManager.INSTANCE.getCumulativeAmountTileEntities())); + public HashMap cachedAccess = new HashMap(); - PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_PACKETS_OUTBOUND, new ArrayList( ((ProfilerPacket)ProfilerSection.PACKET_OUTBOUND.getProfiler()).data.values()))); - PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_PACKETS_INBOUND, new ArrayList( ((ProfilerPacket)ProfilerSection.PACKET_INBOUND.getProfiler()).data.values()))); - - PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_PACKETS_OUTBOUND_250, new ArrayList( ((ProfilerPacket)ProfilerSection.PACKET_OUTBOUND.getProfiler()).data250.values()))); - PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_PACKETS_INBOUND_250, new ArrayList( ((ProfilerPacket)ProfilerSection.PACKET_INBOUND.getProfiler()).data250.values()))); + @SubscribeEvent + public void tickEnd(TickEvent.ServerTickEvent event) { - ((ProfilerPacket)ProfilerSection.PACKET_OUTBOUND.getProfiler()).startInterval(); - ((ProfilerPacket)ProfilerSection.PACKET_INBOUND.getProfiler()).startInterval(); - - /* - for (DataPacket data : ((ProfilerPacket)ProfilerSection.PACKET_OUTBOUND.getProfiler()).jabbaSpec){ - System.out.printf("[ %d ] %d %d\n", data.id, data.amount, data.size); - } - */ - } - - profilerUpdateTickCounter++; - - if (profilerRunningTicks < modOpis.profilerMaxTicks && modOpis.profilerRun){ - profilerRunningTicks++; - }else if (profilerRunningTicks >= modOpis.profilerMaxTicks && modOpis.profilerRun){ - profilerRunningTicks = 0; - modOpis.profilerRun = false; - ProfilerSection.desactivateAll(Side.SERVER); - - PacketManager.sendPacketToAllSwing(new NetDataValue(Message.STATUS_STOP, new SerialInt(modOpis.profilerMaxTicks))); - - for (EntityPlayerMP player : PlayerTracker.INSTANCE.playersSwing){ - PacketManager.sendFullUpdate(player); - } - } - } - + StringCache.INSTANCE.syncNewCache(); + + // One second timer + if (timer1000.isDone() && PlayerTracker.INSTANCE.playersSwing.size() > 0) { + + DataTiming tickTiming = + new DataTiming(((ProfilerTick) ProfilerSection.TICK.getProfiler()).data.getGeometricMean()); + if (!tickTiming.timing.isNaN()) { + PacketManager.sendPacketToAllSwing(new NetDataValue( + Message.NEXUS_DATA, + new NexusData( + new SerialLong( + ((ProfilerPacket) ProfilerSection.PACKET_OUTBOUND.getProfiler()).dataAmount), + new SerialLong( + ((ProfilerPacket) ProfilerSection.PACKET_INBOUND.getProfiler()).dataAmount), + new SerialInt(ChunkManager.INSTANCE.getForcedChunkAmount()), + new SerialInt(ChunkManager.INSTANCE.getLoadedChunkAmount()), + new DataTiming( + ((ProfilerTick) ProfilerSection.TICK.getProfiler()).data.getGeometricMean()), + new SerialInt(TileEntityManager.INSTANCE.getAmountTileEntities()), + new SerialInt(EntityManager.INSTANCE.getAmountEntities()), + new SerialInt(FMLCommonHandler.instance() + .getMinecraftServerInstance() + .getCurrentPlayerCount())))); + } + // End of summary update + + for (EntityPlayerMP player : PlayerTracker.INSTANCE.playersSwing) { + if (!cachedAccess.containsKey(player) + || cachedAccess.get(player) != PlayerTracker.INSTANCE.getPlayerAccessLevel(player)) { + PacketManager.validateAndSend( + new NetDataValue( + Message.STATUS_ACCESS_LEVEL, + new SerialInt(PlayerTracker.INSTANCE + .getPlayerAccessLevel(player) + .ordinal())), + player); + cachedAccess.put(player, PlayerTracker.INSTANCE.getPlayerAccessLevel(player)); + } + } + + // Dimension data update. + ArrayList dimData = new ArrayList(); + for (int dim : DimensionManager.getIDs()) { + dimData.add(new DataDimension().fill(dim)); + } + PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_DIMENSION_DATA, dimData)); + + // Profiler update (if running) + if (modOpis.profilerRun) { + PacketManager.sendPacketToAllSwing( + new NetDataValue(Message.STATUS_RUNNING, new SerialInt(modOpis.profilerMaxTicks))); + PacketManager.sendPacketToAllSwing( + new NetDataValue(Message.STATUS_RUN_UPDATE, new SerialInt(profilerRunningTicks))); + } + + ((ProfilerPacket) ProfilerSection.PACKET_INBOUND.getProfiler()).dataAmount = 0L; + ((ProfilerPacket) ProfilerSection.PACKET_OUTBOUND.getProfiler()).dataAmount = 0L; + } + + // Two second timer + if (timer2000.isDone() && PlayerTracker.INSTANCE.playersSwing.size() > 0) { + ArrayList threads = new ArrayList(); + for (Thread t : Thread.getAllStackTraces().keySet()) { + threads.add(new DataThread().fill(t)); + } + PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_THREADS, threads)); + + PacketManager.sendPacketToAllSwing( + new NetDataList(Message.LIST_PLAYERS, EntityManager.INSTANCE.getAllPlayers())); + } + + // Five second timer + if (timer5000.isDone() && PlayerTracker.INSTANCE.playersSwing.size() > 0) { + PacketManager.sendPacketToAllSwing( + new NetDataList(Message.LIST_AMOUNT_ENTITIES, EntityManager.INSTANCE.getCumulativeEntities(false))); + PacketManager.sendPacketToAllSwing(new NetDataList( + Message.LIST_AMOUNT_TILEENTS, TileEntityManager.INSTANCE.getCumulativeAmountTileEntities())); + + PacketManager.sendPacketToAllSwing(new NetDataList( + Message.LIST_PACKETS_OUTBOUND, + new ArrayList( + ((ProfilerPacket) ProfilerSection.PACKET_OUTBOUND.getProfiler()).data.values()))); + PacketManager.sendPacketToAllSwing(new NetDataList( + Message.LIST_PACKETS_INBOUND, + new ArrayList( + ((ProfilerPacket) ProfilerSection.PACKET_INBOUND.getProfiler()).data.values()))); + + PacketManager.sendPacketToAllSwing(new NetDataList( + Message.LIST_PACKETS_OUTBOUND_250, + new ArrayList( + ((ProfilerPacket) ProfilerSection.PACKET_OUTBOUND.getProfiler()).data250.values()))); + PacketManager.sendPacketToAllSwing(new NetDataList( + Message.LIST_PACKETS_INBOUND_250, + new ArrayList( + ((ProfilerPacket) ProfilerSection.PACKET_INBOUND.getProfiler()).data250.values()))); + + ((ProfilerPacket) ProfilerSection.PACKET_OUTBOUND.getProfiler()).startInterval(); + ((ProfilerPacket) ProfilerSection.PACKET_INBOUND.getProfiler()).startInterval(); + + /* + for (DataPacket data : ((ProfilerPacket)ProfilerSection.PACKET_OUTBOUND.getProfiler()).jabbaSpec){ + System.out.printf("[ %d ] %d %d\n", data.id, data.amount, data.size); + } + */ + } + + profilerUpdateTickCounter++; + + if (profilerRunningTicks < modOpis.profilerMaxTicks && modOpis.profilerRun) { + profilerRunningTicks++; + } else if (profilerRunningTicks >= modOpis.profilerMaxTicks && modOpis.profilerRun) { + profilerRunningTicks = 0; + modOpis.profilerRun = false; + ProfilerSection.desactivateAll(Side.SERVER); + + PacketManager.sendPacketToAllSwing( + new NetDataValue(Message.STATUS_STOP, new SerialInt(modOpis.profilerMaxTicks))); + + for (EntityPlayerMP player : PlayerTracker.INSTANCE.playersSwing) { + PacketManager.sendFullUpdate(player); + } + } + } } diff --git a/src/main/java/mcp/mobius/opis/events/PlayerTracker.java b/src/main/java/mcp/mobius/opis/events/PlayerTracker.java index 592724b..9894fd1 100644 --- a/src/main/java/mcp/mobius/opis/events/PlayerTracker.java +++ b/src/main/java/mcp/mobius/opis/events/PlayerTracker.java @@ -3,6 +3,8 @@ package mcp.mobius.opis.events; import com.mojang.authlib.GameProfile; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; +import java.util.HashMap; +import java.util.HashSet; import mcp.mobius.opis.data.holders.basetypes.SerialLong; import mcp.mobius.opis.data.holders.newtypes.PlayerStatus; import mcp.mobius.opis.data.managers.StringCache; @@ -18,110 +20,129 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraftforge.common.util.FakePlayer; -import java.util.HashMap; -import java.util.HashSet; +// public class PlayerTracker implements IPlayerTracker{ +public enum PlayerTracker { + INSTANCE; -//public class PlayerTracker implements IPlayerTracker{ -public enum PlayerTracker{ - INSTANCE; - - private PlayerTracker(){} - - public HashSet playersSwing = new HashSet(); //This is the list of players who have opened the UI - //public HashSet playersOpis = new HashSet(); //This is the list of players who have opened the UI or used the command line - public HashMap filteredAmount = new HashMap(); //Should the entity amount be filtered or not - public HashMap playerDimension = new HashMap(); - public HashMap playerTab = new HashMap(); - private HashSet playerPrivileged = new HashSet(); - - public SelectedTab getPlayerSelectedTab(EntityPlayerMP player){ - return this.playerTab.get(player); - } - - public AccessLevel getPlayerAccessLevel(EntityPlayerMP player){ - if (player instanceof FakePlayer && RConHandler.isPriviledge((FakePlayer)player)) - return AccessLevel.PRIVILEGED; - - return this.getPlayerAccessLevel(player.getGameProfile().getName()); - } - - public AccessLevel getPlayerAccessLevel(String name){ - - EntityPlayerMP player = MinecraftServer.getServer().getConfigurationManager().func_152612_a(name); - GameProfile profile = player.getGameProfile(); - - if (MinecraftServer.getServer().getConfigurationManager().func_152596_g(profile) || MinecraftServer.getServer().isSinglePlayer()) - return AccessLevel.ADMIN; - else if (playerPrivileged.contains(name)) - return AccessLevel.PRIVILEGED; - else - return AccessLevel.NONE; - } - - public void addPrivilegedPlayer(String name, boolean save){ - this.playerPrivileged.add(name); - if (save){ - modOpis.instance.config.get("ACCESS_RIGHTS", "privileged", new String[]{}, modOpis.commentPrivileged).set(playerPrivileged.toArray(new String[]{})); - modOpis.instance.config.save(); - } - } - - public void addPrivilegedPlayer(String name){ - this.addPrivilegedPlayer(name, true); - } - - public void rmPrivilegedPlayer(String name){ - this.playerPrivileged.remove(name); - modOpis.instance.config.get("ACCESS_RIGHTS", "privileged", new String[]{}, modOpis.commentPrivileged).set(playerPrivileged.toArray(new String[]{})); - modOpis.instance.config.save(); - } - - public void reloeadPriviligedPlayers(){ - String[] users = modOpis.instance.config.get("ACCESS_RIGHTS", "privileged", new String[]{}, modOpis.commentPrivileged).getStringList(); - for (String s : users) - PlayerTracker.INSTANCE.addPrivilegedPlayer(s,false); - } - - public boolean isAdmin(EntityPlayerMP player){ - return this.getPlayerAccessLevel(player).ordinal() >= AccessLevel.ADMIN.ordinal(); - } - - public boolean isPrivileged(EntityPlayerMP player){ - return this.getPlayerAccessLevel(player).ordinal() >= AccessLevel.PRIVILEGED.ordinal(); - } - - public boolean isInPrivilegedList(String name){ - return this.playerPrivileged.contains(name); - } + private PlayerTracker() {} - - //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// - - @SubscribeEvent - public void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event){ - this.playerDimension.remove(event.player); - //this.playersOpis.remove(player); - this.playersSwing.remove(event.player); - PacketManager.sendPacketToAllSwing(new NetDataValue(Message.PLAYER_STATUS_UPDATE, - new PlayerStatus(event.player.getGameProfile().getName(), PlayerEv.LOGOUT, - event.player.worldObj.provider.dimensionId, (int)event.player.posX, (int)event.player.posY, (int)event.player.posZ))); - } - - @SubscribeEvent - public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event){ - PacketManager.validateAndSend(new NetDataValue(Message.STATUS_CURRENT_TIME, new SerialLong(System.currentTimeMillis())), (EntityPlayerMP)event.player); - - /* - if (manager instanceof MemoryConnection){ - System.out.printf("Adding SSP player to list of privileged users\n"); - PlayerTracker.INSTANCE.addPrivilegedPlayer(((EntityPlayer)event.player).getGameProfile().getName(), false); - } - */ - - StringCache.INSTANCE.syncCache((EntityPlayerMP)event.player); - PacketManager.sendPacketToAllSwing(new NetDataValue(Message.PLAYER_STATUS_UPDATE, - new PlayerStatus(event.player.getGameProfile().getName(), PlayerEv.LOGIN, - event.player.worldObj.provider.dimensionId, (int)event.player.posX, (int)event.player.posY, (int)event.player.posZ))); - } + public HashSet playersSwing = + new HashSet(); // This is the list of players who have opened the UI + // public HashSet playersOpis = new HashSet(); //This is the list of players who have opened the + // UI or used the command line + public HashMap filteredAmount = + new HashMap(); // Should the entity amount be filtered or not + public HashMap playerDimension = new HashMap(); + public HashMap playerTab = new HashMap(); + private HashSet playerPrivileged = new HashSet(); + public SelectedTab getPlayerSelectedTab(EntityPlayerMP player) { + return this.playerTab.get(player); + } + + public AccessLevel getPlayerAccessLevel(EntityPlayerMP player) { + if (player instanceof FakePlayer && RConHandler.isPriviledge((FakePlayer) player)) + return AccessLevel.PRIVILEGED; + + return this.getPlayerAccessLevel(player.getGameProfile().getName()); + } + + public AccessLevel getPlayerAccessLevel(String name) { + + EntityPlayerMP player = + MinecraftServer.getServer().getConfigurationManager().func_152612_a(name); + GameProfile profile = player.getGameProfile(); + + if (MinecraftServer.getServer().getConfigurationManager().func_152596_g(profile) + || MinecraftServer.getServer().isSinglePlayer()) return AccessLevel.ADMIN; + else if (playerPrivileged.contains(name)) return AccessLevel.PRIVILEGED; + else return AccessLevel.NONE; + } + + public void addPrivilegedPlayer(String name, boolean save) { + this.playerPrivileged.add(name); + if (save) { + modOpis.instance + .config + .get("ACCESS_RIGHTS", "privileged", new String[] {}, modOpis.commentPrivileged) + .set(playerPrivileged.toArray(new String[] {})); + modOpis.instance.config.save(); + } + } + + public void addPrivilegedPlayer(String name) { + this.addPrivilegedPlayer(name, true); + } + + public void rmPrivilegedPlayer(String name) { + this.playerPrivileged.remove(name); + modOpis.instance + .config + .get("ACCESS_RIGHTS", "privileged", new String[] {}, modOpis.commentPrivileged) + .set(playerPrivileged.toArray(new String[] {})); + modOpis.instance.config.save(); + } + + public void reloeadPriviligedPlayers() { + String[] users = modOpis.instance + .config + .get("ACCESS_RIGHTS", "privileged", new String[] {}, modOpis.commentPrivileged) + .getStringList(); + for (String s : users) PlayerTracker.INSTANCE.addPrivilegedPlayer(s, false); + } + + public boolean isAdmin(EntityPlayerMP player) { + return this.getPlayerAccessLevel(player).ordinal() >= AccessLevel.ADMIN.ordinal(); + } + + public boolean isPrivileged(EntityPlayerMP player) { + return this.getPlayerAccessLevel(player).ordinal() >= AccessLevel.PRIVILEGED.ordinal(); + } + + public boolean isInPrivilegedList(String name) { + return this.playerPrivileged.contains(name); + } + + // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// + + @SubscribeEvent + public void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event) { + this.playerDimension.remove(event.player); + // this.playersOpis.remove(player); + this.playersSwing.remove(event.player); + PacketManager.sendPacketToAllSwing(new NetDataValue( + Message.PLAYER_STATUS_UPDATE, + new PlayerStatus( + event.player.getGameProfile().getName(), + PlayerEv.LOGOUT, + event.player.worldObj.provider.dimensionId, + (int) event.player.posX, + (int) event.player.posY, + (int) event.player.posZ))); + } + + @SubscribeEvent + public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) { + PacketManager.validateAndSend( + new NetDataValue(Message.STATUS_CURRENT_TIME, new SerialLong(System.currentTimeMillis())), + (EntityPlayerMP) event.player); + + /* + if (manager instanceof MemoryConnection){ + System.out.printf("Adding SSP player to list of privileged users\n"); + PlayerTracker.INSTANCE.addPrivilegedPlayer(((EntityPlayer)event.player).getGameProfile().getName(), false); + } + */ + + StringCache.INSTANCE.syncCache((EntityPlayerMP) event.player); + PacketManager.sendPacketToAllSwing(new NetDataValue( + Message.PLAYER_STATUS_UPDATE, + new PlayerStatus( + event.player.getGameProfile().getName(), + PlayerEv.LOGIN, + event.player.worldObj.provider.dimensionId, + (int) event.player.posX, + (int) event.player.posY, + (int) event.player.posZ))); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/events/MouseEvent.java b/src/main/java/mcp/mobius/opis/gui/events/MouseEvent.java index ed573b2..b4ee592 100644 --- a/src/main/java/mcp/mobius/opis/gui/events/MouseEvent.java +++ b/src/main/java/mcp/mobius/opis/gui/events/MouseEvent.java @@ -1,101 +1,101 @@ package mcp.mobius.opis.gui.events; -import net.minecraft.client.Minecraft; - -import org.lwjgl.input.Mouse; - import mcp.mobius.opis.gui.interfaces.IWidget; +import net.minecraft.client.Minecraft; +import org.lwjgl.input.Mouse; public class MouseEvent { - public enum EventType {NONE, MOVE, CLICK, RELEASED, DRAG, WHEEL, ENTER, LEAVE}; - - public long timestamp; - public Minecraft mc; - public IWidget srcwidget; - public IWidget trgwidget; - public double x,y; - public int z; - public static int buttonCount = Mouse.getButtonCount(); - public boolean[] buttonState = new boolean[buttonCount]; - public EventType type; - public int button = -1; - - - public MouseEvent(IWidget widget){ - this.srcwidget = widget; - this.timestamp = System.nanoTime(); - - this.mc = Minecraft.getMinecraft(); - - this.x = (double)Mouse.getEventX() * (double)this.srcwidget.getSize().getX() / (double)this.mc.displayWidth; - this.y = (double)this.srcwidget.getSize().getY() - (double)Mouse.getEventY() * (double)this.srcwidget.getSize().getY() / (double)this.mc.displayHeight - 1.0; - - //this.x = Mouse.getEventX(); - //this.y = Mouse.getEventY(); - - //System.out.printf("%s %s\n", this.x, this.y); - - //this.z = Mouse.getEventDWheel(); + public enum EventType { + NONE, + MOVE, + CLICK, + RELEASED, + DRAG, + WHEEL, + ENTER, + LEAVE + }; + + public long timestamp; + public Minecraft mc; + public IWidget srcwidget; + public IWidget trgwidget; + public double x, y; + public int z; + public static int buttonCount = Mouse.getButtonCount(); + public boolean[] buttonState = new boolean[buttonCount]; + public EventType type; + public int button = -1; + + public MouseEvent(IWidget widget) { + this.srcwidget = widget; + this.timestamp = System.nanoTime(); + + this.mc = Minecraft.getMinecraft(); + + this.x = (double) Mouse.getEventX() * (double) this.srcwidget.getSize().getX() / (double) this.mc.displayWidth; + this.y = (double) this.srcwidget.getSize().getY() + - (double) Mouse.getEventY() * (double) this.srcwidget.getSize().getY() / (double) this.mc.displayHeight + - 1.0; + + // this.x = Mouse.getEventX(); + // this.y = Mouse.getEventY(); + + // System.out.printf("%s %s\n", this.x, this.y); + + // this.z = Mouse.getEventDWheel(); this.z = Mouse.getDWheel(); - - for (int i = 0; i < buttonCount; i++) - buttonState[i] = Mouse.isButtonDown(i); - + + for (int i = 0; i < buttonCount; i++) buttonState[i] = Mouse.isButtonDown(i); + this.trgwidget = this.srcwidget.getWidgetAtCoordinates(this.x, this.y); - } - - public String toString(){ - String retstring = String.format("MOUSE %s : [%s] [ %.2f %.2f %d ] [", this.type, this.timestamp, this.x, this.y, this.z); - if (this.buttonCount < 5) - for (int i = 0; i < this.buttonCount; i++) - retstring += String.format(" %s ", this.buttonState[i]); - else - for (int i = 0; i < 5; i++) - retstring += String.format(" %s ", this.buttonState[i]); - retstring += "]"; - - if (this.button != -1) - retstring += String.format(" Button %s", this.button); - - return retstring; - } - - // Returns the event type based on the previous mouse event. - public EventType getEventType(MouseEvent me){ - - this.type = EventType.NONE; - - if (this.trgwidget != me.trgwidget){ - this.type = EventType.ENTER; - return this.type; - } - - if (this.z != 0){ - this.type = EventType.WHEEL; - return this.type; - } - - for (int i = 0; i < this.buttonCount; i++){ - if (this.buttonState[i] != me.buttonState[i]){ - if (this.buttonState[i] == true) - this.type = EventType.CLICK; - else - this.type = EventType.RELEASED; - this.button = i; - return this.type; - } - } - - //MOVE & DRAG EVENTS (we moved the mouse and button 0 was clicked or not) - if ((this.x != me.x) || (this.y != me.y)){ - if (this.buttonState[0] == true) - this.type = EventType.DRAG; - else - this.type = EventType.MOVE; - return this.type; - } - - return this.type; - } + } + + public String toString() { + String retstring = + String.format("MOUSE %s : [%s] [ %.2f %.2f %d ] [", this.type, this.timestamp, this.x, this.y, this.z); + if (this.buttonCount < 5) + for (int i = 0; i < this.buttonCount; i++) retstring += String.format(" %s ", this.buttonState[i]); + else for (int i = 0; i < 5; i++) retstring += String.format(" %s ", this.buttonState[i]); + retstring += "]"; + + if (this.button != -1) retstring += String.format(" Button %s", this.button); + + return retstring; + } + + // Returns the event type based on the previous mouse event. + public EventType getEventType(MouseEvent me) { + + this.type = EventType.NONE; + + if (this.trgwidget != me.trgwidget) { + this.type = EventType.ENTER; + return this.type; + } + + if (this.z != 0) { + this.type = EventType.WHEEL; + return this.type; + } + + for (int i = 0; i < this.buttonCount; i++) { + if (this.buttonState[i] != me.buttonState[i]) { + if (this.buttonState[i] == true) this.type = EventType.CLICK; + else this.type = EventType.RELEASED; + this.button = i; + return this.type; + } + } + + // MOVE & DRAG EVENTS (we moved the mouse and button 0 was clicked or not) + if ((this.x != me.x) || (this.y != me.y)) { + if (this.buttonState[0] == true) this.type = EventType.DRAG; + else this.type = EventType.MOVE; + return this.type; + } + + return this.type; + } } diff --git a/src/main/java/mcp/mobius/opis/gui/font/FontHelper.java b/src/main/java/mcp/mobius/opis/gui/font/FontHelper.java index 861c4a6..0475807 100644 --- a/src/main/java/mcp/mobius/opis/gui/font/FontHelper.java +++ b/src/main/java/mcp/mobius/opis/gui/font/FontHelper.java @@ -1,74 +1,59 @@ package mcp.mobius.opis.gui.font; import java.nio.FloatBuffer; - -import org.lwjgl.BufferUtils; -import org.lwjgl.opengl.GL11; - import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; - - - - - - - +import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.util.vector.Matrix4f; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.ScaledResolution; - - public class FontHelper { - public static void drawString(String s, int x, int y, TrueTypeFont font, float scaleX, float scaleY, float... rgba){ - Minecraft mc = Minecraft.getMinecraft(); - ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - if(mc.gameSettings.hideGUI){ - return; - } - int amt = 1; - if(sr.getScaleFactor() == 1){ - amt = 2; - } - - FloatBuffer matrixData = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixData); - Matrix4f matrix = new Matrix4f(); - matrix.load(matrixData); - - FontHelper.set2DMode(); - y = mc.displayHeight-(y*sr.getScaleFactor())-(((font.getLineHeight()/amt))); - GL11.glEnable(GL11.GL_BLEND); - - font.drawString(x*sr.getScaleFactor(), y - matrix.m31*sr.getScaleFactor(), s, scaleX/amt, scaleY/amt, rgba); - GL11.glDisable(GL11.GL_BLEND); - FontHelper.set3DMode(); - } + public static void drawString( + String s, int x, int y, TrueTypeFont font, float scaleX, float scaleY, float... rgba) { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + if (mc.gameSettings.hideGUI) { + return; + } + int amt = 1; + if (sr.getScaleFactor() == 1) { + amt = 2; + } - private static void set2DMode() { - Minecraft mc = Minecraft.getMinecraft(); + FloatBuffer matrixData = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixData); + Matrix4f matrix = new Matrix4f(); + matrix.load(matrixData); - GL11.glMatrixMode(GL11.GL_PROJECTION); - GL11.glPushMatrix(); - GL11.glLoadIdentity(); - GL11.glOrtho(0, mc.displayWidth, 0, mc.displayHeight, -1, 1); - GL11.glMatrixMode(GL11.GL_MODELVIEW); - GL11.glPushMatrix(); - GL11.glLoadIdentity(); - } + FontHelper.set2DMode(); + y = mc.displayHeight - (y * sr.getScaleFactor()) - (((font.getLineHeight() / amt))); + GL11.glEnable(GL11.GL_BLEND); - private static void set3DMode() { - GL11.glMatrixMode(GL11.GL_PROJECTION); - GL11.glPopMatrix(); - GL11.glMatrixMode(GL11.GL_MODELVIEW); - GL11.glPopMatrix(); - Minecraft mc = Minecraft.getMinecraft(); - mc.entityRenderer.setupOverlayRendering(); - } + font.drawString( + x * sr.getScaleFactor(), y - matrix.m31 * sr.getScaleFactor(), s, scaleX / amt, scaleY / amt, rgba); + GL11.glDisable(GL11.GL_BLEND); + FontHelper.set3DMode(); + } + private static void set2DMode() { + Minecraft mc = Minecraft.getMinecraft(); + + GL11.glMatrixMode(GL11.GL_PROJECTION); + GL11.glPushMatrix(); + GL11.glLoadIdentity(); + GL11.glOrtho(0, mc.displayWidth, 0, mc.displayHeight, -1, 1); + GL11.glMatrixMode(GL11.GL_MODELVIEW); + GL11.glPushMatrix(); + GL11.glLoadIdentity(); + } + + private static void set3DMode() { + GL11.glMatrixMode(GL11.GL_PROJECTION); + GL11.glPopMatrix(); + GL11.glMatrixMode(GL11.GL_MODELVIEW); + GL11.glPopMatrix(); + Minecraft mc = Minecraft.getMinecraft(); + mc.entityRenderer.setupOverlayRendering(); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/font/Fonts.java b/src/main/java/mcp/mobius/opis/gui/font/Fonts.java index 7b54968..773f26f 100644 --- a/src/main/java/mcp/mobius/opis/gui/font/Fonts.java +++ b/src/main/java/mcp/mobius/opis/gui/font/Fonts.java @@ -1,92 +1,91 @@ package mcp.mobius.opis.gui.font; import java.awt.Font; -import java.awt.FontFormatException; -import java.awt.geom.AffineTransform; -import java.io.IOException; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; -public class Fonts{ - - - /** - * USAGE GUIDE, HUE! - * - * create a TrueTypeFont object variable - * using either a resource location to a .ttf or - * name of a system font, choose base size and - * whether or not you want anti aliasing like so: - * - * testFont = createFont(new ResourceLocation("modid", "testfont.ttf"), 24f, false); - * - * - * Once the font has been created, to render to screen, simply use the static call: - * - * FontHelper.drawString(String name, int x, int y, TrueTypeFont font, float scaleX, float scaleY, float... rgba) - * - * (^ help me think of a better class name for that class please o7) - * -- - * - * Example: - * - * FontHelper.drawString(windowTitle, posX, posY, Fonts.fontHelvetica, 1f, 1f); - * - * -- - * - * gl&hf - * - oku - * - * */ - - public static TrueTypeFont fontHelvetica = null, fontMinecraft = null, fontCoolvetica = null, - fontArial = null, fontArialSmall = null, fontVenice = null; - - public static void initFonts(){ - fontVenice = createFont(new ResourceLocation("okuguiapi", "venice.ttf"), 25, false); - fontMinecraft = createFont(new ResourceLocation("okuguiapi", "Minecraftia.ttf"), 16, true); - fontCoolvetica = createFont(new ResourceLocation("okuguiapi", "coolvetica.ttf"), 26, true); - fontHelvetica = loadSystemFont("Helvetica", 18, false); - fontArial = loadSystemFont("Arial", 24, false); - fontArialSmall = loadSystemFont("Arial", 16, false); - } +public class Fonts { - public static TrueTypeFont loadSystemFont(String name, float defSize, boolean antialias){ - return loadSystemFont(name, defSize, antialias, Font.TRUETYPE_FONT); - - } - - public static TrueTypeFont loadSystemFont(String name, float defSize, boolean antialias, int type){ - Font font; - TrueTypeFont out = null; - try { - font = new Font(name, type, (int)defSize); - font = font.deriveFont(defSize); - out = new TrueTypeFont(font, antialias); - } catch (Exception e) { - e.printStackTrace(); - } - return out; - } + /** + * USAGE GUIDE, HUE! + * + * create a TrueTypeFont object variable + * using either a resource location to a .ttf or + * name of a system font, choose base size and + * whether or not you want anti aliasing like so: + * + * testFont = createFont(new ResourceLocation("modid", "testfont.ttf"), 24f, false); + * + * + * Once the font has been created, to render to screen, simply use the static call: + * + * FontHelper.drawString(String name, int x, int y, TrueTypeFont font, float scaleX, float scaleY, float... rgba) + * + * (^ help me think of a better class name for that class please o7) + * -- + * + * Example: + * + * FontHelper.drawString(windowTitle, posX, posY, Fonts.fontHelvetica, 1f, 1f); + * + * -- + * + * gl&hf + * - oku + * + * */ + public static TrueTypeFont fontHelvetica = null, + fontMinecraft = null, + fontCoolvetica = null, + fontArial = null, + fontArialSmall = null, + fontVenice = null; - public static TrueTypeFont createFont(ResourceLocation res, float defSize, boolean antialias){ - return createFont(res, defSize, antialias, Font.TRUETYPE_FONT); - } - - public static TrueTypeFont createFont(ResourceLocation res, float defSize, boolean antialias, int type){ - Font font; - TrueTypeFont out = null; - try { - font = Font.createFont(type, Minecraft.getMinecraft().getResourceManager().getResource(res).getInputStream()); - font = font.deriveFont(defSize); - out = new TrueTypeFont(font, antialias); - } catch (Exception e) { - e.printStackTrace(); - } - return out; - } - -} \ No newline at end of file + public static void initFonts() { + fontVenice = createFont(new ResourceLocation("okuguiapi", "venice.ttf"), 25, false); + fontMinecraft = createFont(new ResourceLocation("okuguiapi", "Minecraftia.ttf"), 16, true); + fontCoolvetica = createFont(new ResourceLocation("okuguiapi", "coolvetica.ttf"), 26, true); + fontHelvetica = loadSystemFont("Helvetica", 18, false); + fontArial = loadSystemFont("Arial", 24, false); + fontArialSmall = loadSystemFont("Arial", 16, false); + } + + public static TrueTypeFont loadSystemFont(String name, float defSize, boolean antialias) { + return loadSystemFont(name, defSize, antialias, Font.TRUETYPE_FONT); + } + + public static TrueTypeFont loadSystemFont(String name, float defSize, boolean antialias, int type) { + Font font; + TrueTypeFont out = null; + try { + font = new Font(name, type, (int) defSize); + font = font.deriveFont(defSize); + out = new TrueTypeFont(font, antialias); + } catch (Exception e) { + e.printStackTrace(); + } + return out; + } + + public static TrueTypeFont createFont(ResourceLocation res, float defSize, boolean antialias) { + return createFont(res, defSize, antialias, Font.TRUETYPE_FONT); + } + + public static TrueTypeFont createFont(ResourceLocation res, float defSize, boolean antialias, int type) { + Font font; + TrueTypeFont out = null; + try { + font = Font.createFont( + type, + Minecraft.getMinecraft() + .getResourceManager() + .getResource(res) + .getInputStream()); + font = font.deriveFont(defSize); + out = new TrueTypeFont(font, antialias); + } catch (Exception e) { + e.printStackTrace(); + } + return out; + } +} diff --git a/src/main/java/mcp/mobius/opis/gui/font/TrueTypeFont.java b/src/main/java/mcp/mobius/opis/gui/font/TrueTypeFont.java index 77de144..f57a7a6 100644 --- a/src/main/java/mcp/mobius/opis/gui/font/TrueTypeFont.java +++ b/src/main/java/mcp/mobius/opis/gui/font/TrueTypeFont.java @@ -4,6 +4,7 @@ import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; +import java.awt.GraphicsEnvironment; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; @@ -14,494 +15,470 @@ import java.nio.ByteOrder; import java.nio.IntBuffer; import java.util.HashMap; import java.util.Map; -import java.awt.GraphicsEnvironment; - -import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.settings.GameSettings; - import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; -import org.lwjgl.opengl.GL30; import org.lwjgl.util.glu.GLU; - /** * A TrueType font implementation originally for Slick, modified to use * Minecraft's Tessellator and add native floating point colour support */ - public class TrueTypeFont { - public final static int - ALIGN_LEFT = 0, - ALIGN_RIGHT = 1, - ALIGN_CENTER = 2; - /** Array that holds necessary information about the font characters */ - private IntObject[] charArray = new IntObject[256]; - - /** Map of user defined font characters (Character <-> IntObject) */ - private Map customChars = new HashMap(); + public static final int ALIGN_LEFT = 0, ALIGN_RIGHT = 1, ALIGN_CENTER = 2; + /** Array that holds necessary information about the font characters */ + private IntObject[] charArray = new IntObject[256]; - /** Boolean flag on whether AntiAliasing is enabled or not */ - private boolean antiAlias; + /** Map of user defined font characters (Character <-> IntObject) */ + private Map customChars = new HashMap(); - /** Font's size */ - private int fontSize = 0; + /** Boolean flag on whether AntiAliasing is enabled or not */ + private boolean antiAlias; - /** Font's height */ - private int fontHeight = 0; + /** Font's size */ + private int fontSize = 0; - /** Texture used to cache the font 0-255 characters */ - private int fontTextureID; - - /** Default font texture width */ - private int textureWidth = 1024; + /** Font's height */ + private int fontHeight = 0; - /** Default font texture height */ - private int textureHeight = 1024; + /** Texture used to cache the font 0-255 characters */ + private int fontTextureID; - /** A reference to Java's AWT Font that we create our font texture from */ - private Font font; + /** Default font texture width */ + private int textureWidth = 1024; - /** The font metrics for our Java AWT font */ - private FontMetrics fontMetrics; + /** Default font texture height */ + private int textureHeight = 1024; - - private int correctL = 9, correctR = 8; - - private class IntObject { - /** Character's width */ - public int width; + /** A reference to Java's AWT Font that we create our font texture from */ + private Font font; - /** Character's height */ - public int height; + /** The font metrics for our Java AWT font */ + private FontMetrics fontMetrics; - /** Character's stored x position */ - public int storedX; + private int correctL = 9, correctR = 8; - /** Character's stored y position */ - public int storedY; - } + private class IntObject { + /** Character's width */ + public int width; + /** Character's height */ + public int height; - public TrueTypeFont(Font font, boolean antiAlias, char[] additionalChars) { - this.font = font; - this.fontSize = font.getSize()+3; - this.antiAlias = antiAlias; + /** Character's stored x position */ + public int storedX; - createSet( additionalChars ); - System.out.println("TrueTypeFont loaded: "+font+" - AntiAlias = "+antiAlias); - fontHeight -= 1; - if (fontHeight <= 0) fontHeight = 1; - } + /** Character's stored y position */ + public int storedY; + } - public TrueTypeFont(Font font, boolean antiAlias) { - this( font, antiAlias, null ); - } - public void setCorrection(boolean on) { - if (on) { - correctL = 2; - correctR = 1; - } else { - correctL = 0; - correctR = 0; - } - } - - private BufferedImage getFontImage(char ch) { - // Create a temporary image to extract the character's size - BufferedImage tempfontImage = new BufferedImage(1, 1, - BufferedImage.TYPE_INT_ARGB); - Graphics2D g = (Graphics2D) tempfontImage.getGraphics(); - if (antiAlias == true) { - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - } - g.setFont(font); - fontMetrics = g.getFontMetrics(); - int charwidth = fontMetrics.charWidth(ch)+8; + public TrueTypeFont(Font font, boolean antiAlias, char[] additionalChars) { + this.font = font; + this.fontSize = font.getSize() + 3; + this.antiAlias = antiAlias; - if (charwidth <= 0) { - charwidth = 7; - } - int charheight = fontMetrics.getHeight()+3; - if (charheight <= 0) { - charheight = fontSize; - } + createSet(additionalChars); + System.out.println("TrueTypeFont loaded: " + font + " - AntiAlias = " + antiAlias); + fontHeight -= 1; + if (fontHeight <= 0) fontHeight = 1; + } - // Create another image holding the character we are creating - BufferedImage fontImage; - fontImage = new BufferedImage(charwidth, charheight, - BufferedImage.TYPE_INT_ARGB); - Graphics2D gt = (Graphics2D) fontImage.getGraphics(); - if (antiAlias == true) { - gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - } - gt.setFont(font); + public TrueTypeFont(Font font, boolean antiAlias) { + this(font, antiAlias, null); + } - gt.setColor(Color.WHITE); - int charx = 3; - int chary = 1; - gt.drawString(String.valueOf(ch), (charx), (chary) - + fontMetrics.getAscent()); + public void setCorrection(boolean on) { + if (on) { + correctL = 2; + correctR = 1; + } else { + correctL = 0; + correctR = 0; + } + } - return fontImage; + private BufferedImage getFontImage(char ch) { + // Create a temporary image to extract the character's size + BufferedImage tempfontImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = (Graphics2D) tempfontImage.getGraphics(); + if (antiAlias == true) { + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + } + g.setFont(font); + fontMetrics = g.getFontMetrics(); + int charwidth = fontMetrics.charWidth(ch) + 8; - } + if (charwidth <= 0) { + charwidth = 7; + } + int charheight = fontMetrics.getHeight() + 3; + if (charheight <= 0) { + charheight = fontSize; + } - private void createSet( char[] customCharsArray ) { - // If there are custom chars then I expand the font texture twice - if (customCharsArray != null && customCharsArray.length > 0) { - textureWidth *= 2; - } - - // In any case this should be done in other way. Texture with size 512x512 - // can maintain only 256 characters with resolution of 32x32. The texture - // size should be calculated dynamicaly by looking at character sizes. - - try { - - BufferedImage imgTemp = new BufferedImage(textureWidth, textureHeight, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = (Graphics2D) imgTemp.getGraphics(); + // Create another image holding the character we are creating + BufferedImage fontImage; + fontImage = new BufferedImage(charwidth, charheight, BufferedImage.TYPE_INT_ARGB); + Graphics2D gt = (Graphics2D) fontImage.getGraphics(); + if (antiAlias == true) { + gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + } + gt.setFont(font); - g.setColor(new Color(0,0,0,1)); - g.fillRect(0,0,textureWidth,textureHeight); - - int rowHeight = 0; - int positionX = 0; - int positionY = 0; - - int customCharsLength = ( customCharsArray != null ) ? customCharsArray.length : 0; + gt.setColor(Color.WHITE); + int charx = 3; + int chary = 1; + gt.drawString(String.valueOf(ch), (charx), (chary) + fontMetrics.getAscent()); - for (int i = 0; i < 256 + customCharsLength; i++) { - - // get 0-255 characters and then custom characters - char ch = ( i < 256 ) ? (char) i : customCharsArray[i-256]; - - BufferedImage fontImage = getFontImage(ch); + return fontImage; + } - IntObject newIntObject = new IntObject(); + private void createSet(char[] customCharsArray) { + // If there are custom chars then I expand the font texture twice + if (customCharsArray != null && customCharsArray.length > 0) { + textureWidth *= 2; + } - newIntObject.width = fontImage.getWidth(); - newIntObject.height = fontImage.getHeight(); + // In any case this should be done in other way. Texture with size 512x512 + // can maintain only 256 characters with resolution of 32x32. The texture + // size should be calculated dynamicaly by looking at character sizes. - if (positionX + newIntObject.width >= textureWidth) { - positionX = 0; - positionY += rowHeight; - rowHeight = 0; - } + try { - newIntObject.storedX = positionX; - newIntObject.storedY = positionY; + BufferedImage imgTemp = new BufferedImage(textureWidth, textureHeight, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = (Graphics2D) imgTemp.getGraphics(); - if (newIntObject.height > fontHeight) { - fontHeight = newIntObject.height; - } + g.setColor(new Color(0, 0, 0, 1)); + g.fillRect(0, 0, textureWidth, textureHeight); - if (newIntObject.height > rowHeight) { - rowHeight = newIntObject.height; - } + int rowHeight = 0; + int positionX = 0; + int positionY = 0; - // Draw it here - g.drawImage(fontImage, positionX, positionY, null); + int customCharsLength = (customCharsArray != null) ? customCharsArray.length : 0; - positionX += newIntObject.width; + for (int i = 0; i < 256 + customCharsLength; i++) { - if( i < 256 ) { // standard characters - charArray[i] = newIntObject; - } else { // custom characters - customChars.put( new Character( ch ), newIntObject ); - } + // get 0-255 characters and then custom characters + char ch = (i < 256) ? (char) i : customCharsArray[i - 256]; - fontImage = null; - } + BufferedImage fontImage = getFontImage(ch); - fontTextureID = loadImage(imgTemp); - + IntObject newIntObject = new IntObject(); + newIntObject.width = fontImage.getWidth(); + newIntObject.height = fontImage.getHeight(); - //.getTexture(font.toString(), imgTemp); + if (positionX + newIntObject.width >= textureWidth) { + positionX = 0; + positionY += rowHeight; + rowHeight = 0; + } - } catch (Exception e) { - System.err.println("Failed to create font."); - e.printStackTrace(); - } - } - - private void drawQuad(float drawX, float drawY, float drawX2, float drawY2, - float srcX, float srcY, float srcX2, float srcY2) { - float DrawWidth = drawX2 - drawX; - float DrawHeight = drawY2 - drawY; - float TextureSrcX= srcX / textureWidth; - float TextureSrcY = srcY / textureHeight; - float SrcWidth = srcX2 - srcX; - float SrcHeight = srcY2 - srcY; - float RenderWidth = (SrcWidth / textureWidth); - float RenderHeight = (SrcHeight / textureHeight); - Tessellator t = Tessellator.instance; - - //t.setColorRGBA_F(0f, 0f, 0f, 1f); - - t.addVertexWithUV(drawX, drawY, 0, TextureSrcX, TextureSrcY); - //GL11.glTexCoord2f(TextureSrcX, TextureSrcY); - //GL11.glVertex2f(drawX, drawY); - - t.addVertexWithUV(drawX, drawY + DrawHeight, 0, TextureSrcX, TextureSrcY + RenderHeight); - //GL11.glTexCoord2f(TextureSrcX, TextureSrcY + RenderHeight); - //GL11.glVertex2f(drawX, drawY + DrawHeight); - - t.addVertexWithUV(drawX + DrawWidth, drawY + DrawHeight, 0, TextureSrcX + RenderWidth, TextureSrcY + RenderHeight); - //GL11.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY + RenderHeight); - //GL11.glVertex2f(drawX + DrawWidth, drawY + DrawHeight); - - t.addVertexWithUV(drawX + DrawWidth, drawY, 0, TextureSrcX + RenderWidth, TextureSrcY); - //GL11.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY); - //GL11.glVertex2f(drawX + DrawWidth, drawY); - } + newIntObject.storedX = positionX; + newIntObject.storedY = positionY; - public int getWidth(String whatchars) { - int totalwidth = 0; - IntObject intObject = null; - int currentChar = 0; - int lastWidth = -10; - for (int i = 0; i < whatchars.length(); i++) { - currentChar = whatchars.charAt(i); - if (currentChar < 256) { - intObject = charArray[currentChar]; - } else { - intObject = (IntObject)customChars.get( new Character( (char) currentChar ) ); - } - - if( intObject != null ){ - totalwidth += intObject.width/4; - lastWidth = intObject.width; - } - } - //System.out.println("Size: "+totalwidth); - return (totalwidth); - } + if (newIntObject.height > fontHeight) { + fontHeight = newIntObject.height; + } - public int getHeight() { - return fontHeight; - } + if (newIntObject.height > rowHeight) { + rowHeight = newIntObject.height; + } + // Draw it here + g.drawImage(fontImage, positionX, positionY, null); - public int getHeight(String HeightString) { - return fontHeight; - } + positionX += newIntObject.width; - public int getLineHeight() { - return fontHeight; - } + if (i < 256) { // standard characters + charArray[i] = newIntObject; + } else { // custom characters + customChars.put(new Character(ch), newIntObject); + } - public void drawString(float x, float y, String whatchars, float scaleX, float scaleY, float... rgba) { - if (whatchars == null) - whatchars = ""; - drawString(x,y,whatchars, 0, whatchars.length()-1, scaleX, scaleY, ALIGN_LEFT, rgba); - } - public void drawString(float x, float y, String whatchars, float scaleX, float scaleY, int format, float... rgba) { - if (whatchars == null) - whatchars = ""; - drawString(x,y,whatchars, 0, whatchars.length()-1, scaleX, scaleY, format, rgba); - } + fontImage = null; + } + fontTextureID = loadImage(imgTemp); - public void drawString(float x, float y, String whatchars, int startIndex, int endIndex, float scaleX, float scaleY, int format, float... rgba) { - - //GameSettings gameSettings = new GameSettings(); - - //gameSettings.setOptionValue(EnumOptions.GUI_SCALE, par2); - - GL11.glPushMatrix(); - GL11.glScalef (scaleX, scaleY, 1.0f); - - IntObject intObject = null; - int charCurrent; - + // .getTexture(font.toString(), imgTemp); - float totalwidth = 0; - int i = startIndex, d, c; - float startY = 0; + } catch (Exception e) { + System.err.println("Failed to create font."); + e.printStackTrace(); + } + } + private void drawQuad( + float drawX, float drawY, float drawX2, float drawY2, float srcX, float srcY, float srcX2, float srcY2) { + float DrawWidth = drawX2 - drawX; + float DrawHeight = drawY2 - drawY; + float TextureSrcX = srcX / textureWidth; + float TextureSrcY = srcY / textureHeight; + float SrcWidth = srcX2 - srcX; + float SrcHeight = srcY2 - srcY; + float RenderWidth = (SrcWidth / textureWidth); + float RenderHeight = (SrcHeight / textureHeight); + Tessellator t = Tessellator.instance; - - switch (format) { - case ALIGN_RIGHT: { - d = -1; - c = correctR; - - while (i < endIndex) { - if (whatchars.charAt(i) == '\n') startY -= fontHeight; - i++; - } - break; - } - case ALIGN_CENTER: { - for (int l = startIndex; l <= endIndex; l++) { - charCurrent = whatchars.charAt(l); - if (charCurrent == '\n') break; - if (charCurrent < 256) { - intObject = charArray[charCurrent]; - } else { - intObject = (IntObject)customChars.get( new Character( (char) charCurrent ) ); - } - totalwidth += intObject.width-correctL; - } - totalwidth /= -2; - } - case ALIGN_LEFT: - default: { - d = 1; - c = correctL; - break; - } - - } - GL11.glBindTexture(GL11.GL_TEXTURE_2D, fontTextureID); - Tessellator t = Tessellator.instance; - t.startDrawingQuads(); - // GL11.glBegin(GL11.GL_QUADS); - if(rgba.length == 4) - t.setColorRGBA_F(rgba[0], rgba[1], rgba[2], rgba[3]); - while (i >= startIndex && i <= endIndex) { - - charCurrent = whatchars.charAt(i); - if (charCurrent < 256) { - intObject = charArray[charCurrent]; - } else { - intObject = (IntObject)customChars.get( new Character( (char) charCurrent ) ); - } - - if( intObject != null ) { - if (d < 0) totalwidth += (intObject.width-c) * d; - if (charCurrent == '\n') { - startY -= fontHeight * d; - totalwidth = 0; - if (format == ALIGN_CENTER) { - for (int l = i+1; l <= endIndex; l++) { - charCurrent = whatchars.charAt(l); - if (charCurrent == '\n') break; - if (charCurrent < 256) { - intObject = charArray[charCurrent]; - } else { - intObject = (IntObject)customChars.get( new Character( (char) charCurrent ) ); - } - totalwidth += intObject.width-correctL; - } - totalwidth /= -2; - } - //if center get next lines total width/2; - } - else { - drawQuad((totalwidth + intObject.width) + x/scaleX, - startY + y/scaleY, - totalwidth + x/scaleX, - (startY + intObject.height) + y/scaleY, - intObject.storedX + intObject.width, - intObject.storedY + intObject.height, - intObject.storedX, - intObject.storedY); - if (d > 0) totalwidth += (intObject.width-c) * d ; - } - i += d; - - } - } - t.draw(); - // GL11.glEnd(); - - GL11.glPopMatrix(); - } - public static int loadImage(BufferedImage bufferedImage) { - try { - short width = (short)bufferedImage.getWidth(); - short height = (short)bufferedImage.getHeight(); - //textureLoader.bpp = bufferedImage.getColorModel().hasAlpha() ? (byte)32 : (byte)24; - int bpp = (byte)bufferedImage.getColorModel().getPixelSize(); - ByteBuffer byteBuffer; - DataBuffer db = bufferedImage.getData().getDataBuffer(); - if (db instanceof DataBufferInt) { - int intI[] = ((DataBufferInt)(bufferedImage.getData().getDataBuffer())).getData(); - byte newI[] = new byte[intI.length * 4]; - for (int i = 0; i < intI.length; i++) { - byte b[] = intToByteArray(intI[i]); - int newIndex = i*4; - - newI[newIndex] = b[1]; - newI[newIndex+1] = b[2]; - newI[newIndex+2] = b[3]; - newI[newIndex+3] = b[0]; - } - - byteBuffer = ByteBuffer.allocateDirect( - width*height*(bpp/8)) - .order(ByteOrder.nativeOrder()) - .put(newI); - } else { - byteBuffer = ByteBuffer.allocateDirect( - width*height*(bpp/8)) - .order(ByteOrder.nativeOrder()) - .put(((DataBufferByte)(bufferedImage.getData().getDataBuffer())).getData()); - } - byteBuffer.flip(); - - - int internalFormat = GL11.GL_RGBA8, - format = GL11.GL_RGBA; - IntBuffer textureId = BufferUtils.createIntBuffer(1);; - GL11.glGenTextures(textureId); - GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId.get(0)); - - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP); - - - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); - //GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); - //GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_NEAREST); - - //GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR); - //GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST_MIPMAP_LINEAR); - //GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST_MIPMAP_NEAREST); - - GL11.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE); + // t.setColorRGBA_F(0f, 0f, 0f, 1f); - GLU.gluBuild2DMipmaps(GL11.GL_TEXTURE_2D, internalFormat, width, height, format, GL11.GL_UNSIGNED_BYTE, byteBuffer); - return textureId.get(0); - - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } - - return -1; - } - public static boolean isSupported(String fontname) { - Font font[] = getFonts(); - for (int i = font.length-1; i >= 0; i--) { - if (font[i].getName().equalsIgnoreCase(fontname)) - return true; - } - return false; - } - public static Font[] getFonts() { - return GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); - } - public static byte[] intToByteArray(int value) { - return new byte[] { - (byte)(value >>> 24), - (byte)(value >>> 16), - (byte)(value >>> 8), - (byte)value}; - } - - public void destroy() { - IntBuffer scratch = BufferUtils.createIntBuffer(1); - scratch.put(0, fontTextureID); - GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); - GL11.glDeleteTextures(scratch); - } -} \ No newline at end of file + t.addVertexWithUV(drawX, drawY, 0, TextureSrcX, TextureSrcY); + // GL11.glTexCoord2f(TextureSrcX, TextureSrcY); + // GL11.glVertex2f(drawX, drawY); + + t.addVertexWithUV(drawX, drawY + DrawHeight, 0, TextureSrcX, TextureSrcY + RenderHeight); + // GL11.glTexCoord2f(TextureSrcX, TextureSrcY + RenderHeight); + // GL11.glVertex2f(drawX, drawY + DrawHeight); + + t.addVertexWithUV( + drawX + DrawWidth, drawY + DrawHeight, 0, TextureSrcX + RenderWidth, TextureSrcY + RenderHeight); + // GL11.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY + RenderHeight); + // GL11.glVertex2f(drawX + DrawWidth, drawY + DrawHeight); + + t.addVertexWithUV(drawX + DrawWidth, drawY, 0, TextureSrcX + RenderWidth, TextureSrcY); + // GL11.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY); + // GL11.glVertex2f(drawX + DrawWidth, drawY); + } + + public int getWidth(String whatchars) { + int totalwidth = 0; + IntObject intObject = null; + int currentChar = 0; + int lastWidth = -10; + for (int i = 0; i < whatchars.length(); i++) { + currentChar = whatchars.charAt(i); + if (currentChar < 256) { + intObject = charArray[currentChar]; + } else { + intObject = (IntObject) customChars.get(new Character((char) currentChar)); + } + + if (intObject != null) { + totalwidth += intObject.width / 4; + lastWidth = intObject.width; + } + } + // System.out.println("Size: "+totalwidth); + return (totalwidth); + } + + public int getHeight() { + return fontHeight; + } + + public int getHeight(String HeightString) { + return fontHeight; + } + + public int getLineHeight() { + return fontHeight; + } + + public void drawString(float x, float y, String whatchars, float scaleX, float scaleY, float... rgba) { + if (whatchars == null) whatchars = ""; + drawString(x, y, whatchars, 0, whatchars.length() - 1, scaleX, scaleY, ALIGN_LEFT, rgba); + } + + public void drawString(float x, float y, String whatchars, float scaleX, float scaleY, int format, float... rgba) { + if (whatchars == null) whatchars = ""; + drawString(x, y, whatchars, 0, whatchars.length() - 1, scaleX, scaleY, format, rgba); + } + + public void drawString( + float x, + float y, + String whatchars, + int startIndex, + int endIndex, + float scaleX, + float scaleY, + int format, + float... rgba) { + + // GameSettings gameSettings = new GameSettings(); + + // gameSettings.setOptionValue(EnumOptions.GUI_SCALE, par2); + + GL11.glPushMatrix(); + GL11.glScalef(scaleX, scaleY, 1.0f); + + IntObject intObject = null; + int charCurrent; + + float totalwidth = 0; + int i = startIndex, d, c; + float startY = 0; + + switch (format) { + case ALIGN_RIGHT: { + d = -1; + c = correctR; + + while (i < endIndex) { + if (whatchars.charAt(i) == '\n') startY -= fontHeight; + i++; + } + break; + } + case ALIGN_CENTER: { + for (int l = startIndex; l <= endIndex; l++) { + charCurrent = whatchars.charAt(l); + if (charCurrent == '\n') break; + if (charCurrent < 256) { + intObject = charArray[charCurrent]; + } else { + intObject = (IntObject) customChars.get(new Character((char) charCurrent)); + } + totalwidth += intObject.width - correctL; + } + totalwidth /= -2; + } + case ALIGN_LEFT: + default: { + d = 1; + c = correctL; + break; + } + } + GL11.glBindTexture(GL11.GL_TEXTURE_2D, fontTextureID); + Tessellator t = Tessellator.instance; + t.startDrawingQuads(); + // GL11.glBegin(GL11.GL_QUADS); + if (rgba.length == 4) t.setColorRGBA_F(rgba[0], rgba[1], rgba[2], rgba[3]); + while (i >= startIndex && i <= endIndex) { + + charCurrent = whatchars.charAt(i); + if (charCurrent < 256) { + intObject = charArray[charCurrent]; + } else { + intObject = (IntObject) customChars.get(new Character((char) charCurrent)); + } + + if (intObject != null) { + if (d < 0) totalwidth += (intObject.width - c) * d; + if (charCurrent == '\n') { + startY -= fontHeight * d; + totalwidth = 0; + if (format == ALIGN_CENTER) { + for (int l = i + 1; l <= endIndex; l++) { + charCurrent = whatchars.charAt(l); + if (charCurrent == '\n') break; + if (charCurrent < 256) { + intObject = charArray[charCurrent]; + } else { + intObject = (IntObject) customChars.get(new Character((char) charCurrent)); + } + totalwidth += intObject.width - correctL; + } + totalwidth /= -2; + } + // if center get next lines total width/2; + } else { + drawQuad( + (totalwidth + intObject.width) + x / scaleX, + startY + y / scaleY, + totalwidth + x / scaleX, + (startY + intObject.height) + y / scaleY, + intObject.storedX + intObject.width, + intObject.storedY + intObject.height, + intObject.storedX, + intObject.storedY); + if (d > 0) totalwidth += (intObject.width - c) * d; + } + i += d; + } + } + t.draw(); + // GL11.glEnd(); + + GL11.glPopMatrix(); + } + + public static int loadImage(BufferedImage bufferedImage) { + try { + short width = (short) bufferedImage.getWidth(); + short height = (short) bufferedImage.getHeight(); + // textureLoader.bpp = bufferedImage.getColorModel().hasAlpha() ? (byte)32 : (byte)24; + int bpp = (byte) bufferedImage.getColorModel().getPixelSize(); + ByteBuffer byteBuffer; + DataBuffer db = bufferedImage.getData().getDataBuffer(); + if (db instanceof DataBufferInt) { + int intI[] = ((DataBufferInt) (bufferedImage.getData().getDataBuffer())).getData(); + byte newI[] = new byte[intI.length * 4]; + for (int i = 0; i < intI.length; i++) { + byte b[] = intToByteArray(intI[i]); + int newIndex = i * 4; + + newI[newIndex] = b[1]; + newI[newIndex + 1] = b[2]; + newI[newIndex + 2] = b[3]; + newI[newIndex + 3] = b[0]; + } + + byteBuffer = ByteBuffer.allocateDirect(width * height * (bpp / 8)) + .order(ByteOrder.nativeOrder()) + .put(newI); + } else { + byteBuffer = ByteBuffer.allocateDirect(width * height * (bpp / 8)) + .order(ByteOrder.nativeOrder()) + .put(((DataBufferByte) (bufferedImage.getData().getDataBuffer())).getData()); + } + byteBuffer.flip(); + + int internalFormat = GL11.GL_RGBA8, format = GL11.GL_RGBA; + IntBuffer textureId = BufferUtils.createIntBuffer(1); + ; + GL11.glGenTextures(textureId); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId.get(0)); + + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP); + + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + // GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); + // GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_NEAREST); + + // GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR); + // GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST_MIPMAP_LINEAR); + // GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST_MIPMAP_NEAREST); + + GL11.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE); + + GLU.gluBuild2DMipmaps( + GL11.GL_TEXTURE_2D, internalFormat, width, height, format, GL11.GL_UNSIGNED_BYTE, byteBuffer); + return textureId.get(0); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + + return -1; + } + + public static boolean isSupported(String fontname) { + Font font[] = getFonts(); + for (int i = font.length - 1; i >= 0; i--) { + if (font[i].getName().equalsIgnoreCase(fontname)) return true; + } + return false; + } + + public static Font[] getFonts() { + return GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); + } + + public static byte[] intToByteArray(int value) { + return new byte[] {(byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}; + } + + public void destroy() { + IntBuffer scratch = BufferUtils.createIntBuffer(1); + scratch.put(0, fontTextureID); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GL11.glDeleteTextures(scratch); + } +} diff --git a/src/main/java/mcp/mobius/opis/gui/helpers/ReverseIterator.java b/src/main/java/mcp/mobius/opis/gui/helpers/ReverseIterator.java index b29068f..21f71ce 100644 --- a/src/main/java/mcp/mobius/opis/gui/helpers/ReverseIterator.java +++ b/src/main/java/mcp/mobius/opis/gui/helpers/ReverseIterator.java @@ -1,20 +1,19 @@ package mcp.mobius.opis.gui.helpers; +import com.google.common.collect.Lists; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; -import com.google.common.collect.Lists; - public class ReverseIterator implements Iterable { - private ListIterator listIterator; + private ListIterator listIterator; public ReverseIterator(Collection wrappedList) { - List list = Lists.newArrayList(wrappedList); - this.listIterator = list.listIterator(wrappedList.size()); - } + List list = Lists.newArrayList(wrappedList); + this.listIterator = list.listIterator(wrappedList.size()); + } public Iterator iterator() { return new Iterator() { @@ -30,8 +29,6 @@ public class ReverseIterator implements Iterable { public void remove() { listIterator.remove(); } - }; - } - + } } diff --git a/src/main/java/mcp/mobius/opis/gui/helpers/UIHelper.java b/src/main/java/mcp/mobius/opis/gui/helpers/UIHelper.java index a8793a9..f979f0e 100644 --- a/src/main/java/mcp/mobius/opis/gui/helpers/UIHelper.java +++ b/src/main/java/mcp/mobius/opis/gui/helpers/UIHelper.java @@ -1,40 +1,44 @@ package mcp.mobius.opis.gui.helpers; +import net.minecraft.client.renderer.Tessellator; import org.lwjgl.opengl.GL11; -import net.minecraft.client.renderer.Tessellator; - public class UIHelper { - - public static void drawTexture(int posX, int posY, int sizeX, int sizeY) - { - UIHelper.drawTexture(posX, posY, sizeX, sizeY, 0, 0, 256, 256); - } - - public static void drawTexture(int posX, int posY, int sizeX, int sizeY, int texU, int texV, int texSizeU, int texSizeV) - { + + public static void drawTexture(int posX, int posY, int sizeX, int sizeY) { + UIHelper.drawTexture(posX, posY, sizeX, sizeY, 0, 0, 256, 256); + } + + public static void drawTexture( + int posX, int posY, int sizeX, int sizeY, int texU, int texV, int texSizeU, int texSizeV) { float zLevel = 0.0F; float f = 0.00390625F; - + Tessellator tess = Tessellator.instance; tess.startDrawingQuads(); - tess.addVertexWithUV((double)(posX + 0), (double)(posY + sizeY), (double)zLevel, texU*f, (texV + texSizeV)*f); - tess.addVertexWithUV((double)(posX + sizeX), (double)(posY + sizeY), (double)zLevel, (texU + texSizeU)*f, (texV + texSizeV)*f); - tess.addVertexWithUV((double)(posX + sizeX), (double)(posY + 0), (double)zLevel, (texU + texSizeU)*f, texV*f); - tess.addVertexWithUV((double)(posX + 0), (double)(posY + 0), (double)zLevel, texU*f, texV*f); + tess.addVertexWithUV( + (double) (posX + 0), (double) (posY + sizeY), (double) zLevel, texU * f, (texV + texSizeV) * f); + tess.addVertexWithUV( + (double) (posX + sizeX), + (double) (posY + sizeY), + (double) zLevel, + (texU + texSizeU) * f, + (texV + texSizeV) * f); + tess.addVertexWithUV( + (double) (posX + sizeX), (double) (posY + 0), (double) zLevel, (texU + texSizeU) * f, texV * f); + tess.addVertexWithUV((double) (posX + 0), (double) (posY + 0), (double) zLevel, texU * f, texV * f); tess.draw(); - } - - public static void drawGradientRect(int minx, int miny, int maxx, int maxy, int zlevel, int color1, int color2) - { - float alpha1 = (float)(color1 >> 24 & 255) / 255.0F; - float red1 = (float)(color1 >> 16 & 255) / 255.0F; - float green1 = (float)(color1 >> 8 & 255) / 255.0F; - float blue1 = (float)(color1 & 255) / 255.0F; - float alpha2 = (float)(color2 >> 24 & 255) / 255.0F; - float red2 = (float)(color2 >> 16 & 255) / 255.0F; - float green2 = (float)(color2 >> 8 & 255) / 255.0F; - float blue2 = (float)(color2 & 255) / 255.0F; + } + + public static void drawGradientRect(int minx, int miny, int maxx, int maxy, int zlevel, int color1, int color2) { + float alpha1 = (float) (color1 >> 24 & 255) / 255.0F; + float red1 = (float) (color1 >> 16 & 255) / 255.0F; + float green1 = (float) (color1 >> 8 & 255) / 255.0F; + float blue1 = (float) (color1 & 255) / 255.0F; + float alpha2 = (float) (color2 >> 24 & 255) / 255.0F; + float red2 = (float) (color2 >> 16 & 255) / 255.0F; + float green2 = (float) (color2 >> 8 & 255) / 255.0F; + float blue2 = (float) (color2 & 255) / 255.0F; GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_ALPHA_TEST); @@ -43,40 +47,36 @@ public class UIHelper { Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.setColorRGBA_F(red1, green1, blue1, alpha1); - tessellator.addVertex((double)maxx, (double)miny, (double)zlevel); - tessellator.addVertex((double)minx, (double)miny, (double)zlevel); + tessellator.addVertex((double) maxx, (double) miny, (double) zlevel); + tessellator.addVertex((double) minx, (double) miny, (double) zlevel); tessellator.setColorRGBA_F(red2, green2, blue2, alpha2); - tessellator.addVertex((double)minx, (double)maxy, (double)zlevel); - tessellator.addVertex((double)maxx, (double)maxy, (double)zlevel); + tessellator.addVertex((double) minx, (double) maxy, (double) zlevel); + tessellator.addVertex((double) maxx, (double) maxy, (double) zlevel); tessellator.draw(); GL11.glShadeModel(GL11.GL_FLAT); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_TEXTURE_2D); - } + } public void drawLine(int x, int y, int x2, int y2, int width, float... rgba) { - Tessellator tess = Tessellator.instance; - GL11.glPushMatrix(); - //GL11.glLineWidth(3); - GL11.glLineWidth(width); - GL11.glDisable(GL11.GL_TEXTURE_2D); - tess.startDrawing(3); + Tessellator tess = Tessellator.instance; + GL11.glPushMatrix(); + // GL11.glLineWidth(3); + GL11.glLineWidth(width); + GL11.glDisable(GL11.GL_TEXTURE_2D); + tess.startDrawing(3); - if(rgba.length == 4) - tess.setColorRGBA_F(rgba[0], rgba[1], rgba[2], rgba[3]); - //tess.setColorRGBA_F(1,1,1,1); - - tess.addVertex(x, y, 0); - tess.addVertex(x2, y2, 0); + if (rgba.length == 4) tess.setColorRGBA_F(rgba[0], rgba[1], rgba[2], rgba[3]); + // tess.setColorRGBA_F(1,1,1,1); + tess.addVertex(x, y, 0); + tess.addVertex(x2, y2, 0); - tess.draw(); - GL11.glDisable(32826 /*GL_RESCALE_NORMAL_EXT*/); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glPopMatrix(); - - } - + tess.draw(); + GL11.glDisable(32826 /*GL_RESCALE_NORMAL_EXT*/); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glPopMatrix(); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/interfaces/CType.java b/src/main/java/mcp/mobius/opis/gui/interfaces/CType.java index b55cd84..27d78c8 100644 --- a/src/main/java/mcp/mobius/opis/gui/interfaces/CType.java +++ b/src/main/java/mcp/mobius/opis/gui/interfaces/CType.java @@ -1,8 +1,8 @@ package mcp.mobius.opis.gui.interfaces; public enum CType { -REL_X, -REL_Y, -RELXY, -ABSXY; + REL_X, + REL_Y, + RELXY, + ABSXY; } diff --git a/src/main/java/mcp/mobius/opis/gui/interfaces/IWidget.java b/src/main/java/mcp/mobius/opis/gui/interfaces/IWidget.java index 5dc8137..b9b232b 100644 --- a/src/main/java/mcp/mobius/opis/gui/interfaces/IWidget.java +++ b/src/main/java/mcp/mobius/opis/gui/interfaces/IWidget.java @@ -2,65 +2,94 @@ package mcp.mobius.opis.gui.interfaces; import mcp.mobius.opis.gui.events.MouseEvent; import mcp.mobius.opis.gui.widgets.WidgetGeometry; - import org.lwjgl.util.Point; public interface IWidget { - // Should all the coordinates, sizes, etc be % or absolute values ? - // Should we allow 2 methods for an absolute referencing (screen pos) and relative one (parent pos) ? - - IWidget getParent(); - void setParent(IWidget parent); - - IWidget setGeometry(WidgetGeometry geom); - WidgetGeometry getGeometry(); + // Should all the coordinates, sizes, etc be % or absolute values ? + // Should we allow 2 methods for an absolute referencing (screen pos) and relative one (parent pos) ? + + IWidget getParent(); + + void setParent(IWidget parent); + + IWidget setGeometry(WidgetGeometry geom); + + WidgetGeometry getGeometry(); + + IWidget setPos(double x, double y); + + IWidget setPos(double x, double y, boolean fracX, boolean fracY); + + IWidget setSize(double sx, double sy); + + IWidget setSize(double sx, double sy, boolean fracX, boolean fracY); + + IWidget adjustSize(); + + Point getPos(); + + Point getSize(); + + int getRight(); + + int getLeft(); + + int getTop(); + + int getBottom(); + + void draw(); + + void draw(Point pos); + + void show(); + + void hide(); + + void setAlpha(float alpha); + + float getAlpha(); + + boolean shouldRender(); + + IWidget addWidget(String name, IWidget widget); + + IWidget addWidget(String name, IWidget widget, RenderPriority priority); + + IWidget getWidget(String name); + + IWidget delWidget(String name); + + IWidget getWidgetAtCoordinates(double posX, double posY); + + IWidget getWidgetAtLayer(double posX, double posY, int layer); + + boolean hasWidget(String name); + + boolean isWidgetAtCoordinates(double posx, double posy); + + void handleMouseInput(); + + void onMouseClick(MouseEvent event); + + void onMouseDrag(MouseEvent event); + + void onMouseMove(MouseEvent event); + + void onMouseRelease(MouseEvent event); + + void onMouseWheel(MouseEvent event); + + void onMouseEnter(MouseEvent event); + + void onMouseLeave(MouseEvent event); + + void emit(Signal signal, Object... params); + + void onWidgetEvent(IWidget srcwidget, Signal signal, Object... params); + + // boolean onMouseEnter(); + // boolean onMouseMoved(); + // boolean onMouseLeave(); - IWidget setPos(double x, double y); - IWidget setPos(double x, double y, boolean fracX, boolean fracY); - IWidget setSize(double sx, double sy); - IWidget setSize(double sx, double sy, boolean fracX, boolean fracY); - IWidget adjustSize(); - - Point getPos(); - Point getSize(); - int getRight(); - int getLeft(); - int getTop(); - int getBottom(); - - void draw(); - void draw(Point pos); - void show(); - void hide(); - void setAlpha(float alpha); - float getAlpha(); - boolean shouldRender(); - - IWidget addWidget(String name, IWidget widget); - IWidget addWidget(String name, IWidget widget, RenderPriority priority); - IWidget getWidget(String name); - IWidget delWidget(String name); - IWidget getWidgetAtCoordinates(double posX, double posY); - IWidget getWidgetAtLayer(double posX, double posY, int layer); - boolean hasWidget(String name); - - boolean isWidgetAtCoordinates(double posx, double posy); - - void handleMouseInput(); - - void onMouseClick(MouseEvent event); - void onMouseDrag(MouseEvent event); - void onMouseMove(MouseEvent event); - void onMouseRelease(MouseEvent event); - void onMouseWheel(MouseEvent event); - void onMouseEnter(MouseEvent event); - void onMouseLeave(MouseEvent event); - - void emit(Signal signal, Object... params); - void onWidgetEvent(IWidget srcwidget, Signal signal, Object... params); - - //boolean onMouseEnter(); - //boolean onMouseMoved(); - //boolean onMouseLeave(); - } diff --git a/src/main/java/mcp/mobius/opis/gui/interfaces/RenderPriority.java b/src/main/java/mcp/mobius/opis/gui/interfaces/RenderPriority.java index 1bc9f68..4004d14 100644 --- a/src/main/java/mcp/mobius/opis/gui/interfaces/RenderPriority.java +++ b/src/main/java/mcp/mobius/opis/gui/interfaces/RenderPriority.java @@ -1,7 +1,7 @@ package mcp.mobius.opis.gui.interfaces; public enum RenderPriority { - LOW, - MEDIUM, - HIGH; + LOW, + MEDIUM, + HIGH; } diff --git a/src/main/java/mcp/mobius/opis/gui/interfaces/Signal.java b/src/main/java/mcp/mobius/opis/gui/interfaces/Signal.java index 96dcdfc..f07b6e7 100644 --- a/src/main/java/mcp/mobius/opis/gui/interfaces/Signal.java +++ b/src/main/java/mcp/mobius/opis/gui/interfaces/Signal.java @@ -1,8 +1,8 @@ package mcp.mobius.opis.gui.interfaces; public enum Signal { - DRAGGED, - CLICKED, - VALUE_CHANGED, - GEOM_CHANGED; + DRAGGED, + CLICKED, + VALUE_CHANGED, + GEOM_CHANGED; } diff --git a/src/main/java/mcp/mobius/opis/gui/interfaces/WAlign.java b/src/main/java/mcp/mobius/opis/gui/interfaces/WAlign.java index 536d666..fdd8720 100644 --- a/src/main/java/mcp/mobius/opis/gui/interfaces/WAlign.java +++ b/src/main/java/mcp/mobius/opis/gui/interfaces/WAlign.java @@ -1,5 +1,9 @@ package mcp.mobius.opis.gui.interfaces; public enum WAlign { -LEFT,CENTER,RIGHT,TOP,BOTTOM; + LEFT, + CENTER, + RIGHT, + TOP, + BOTTOM; } diff --git a/src/main/java/mcp/mobius/opis/gui/screens/ScreenBase.java b/src/main/java/mcp/mobius/opis/gui/screens/ScreenBase.java index 87ddaf3..d9a39ac 100644 --- a/src/main/java/mcp/mobius/opis/gui/screens/ScreenBase.java +++ b/src/main/java/mcp/mobius/opis/gui/screens/ScreenBase.java @@ -1,94 +1,86 @@ package mcp.mobius.opis.gui.screens; import java.util.HashMap; - -import org.lwjgl.input.Mouse; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.widgets.LayoutCanvas; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; +import org.lwjgl.input.Mouse; -public abstract class ScreenBase extends GuiScreen{ - protected GuiScreen parent; // Return screen if available. - protected Minecraft mc; // Minecraft instance - protected HashMap widgets; // List of widgets on this ui - - public ScreenBase(GuiScreen parent) { - this.parent = parent; - this.mc = Minecraft.getMinecraft(); - this.widgets = new HashMap(); - - this.addWidget("canvas", new LayoutCanvas()); - - Mouse.getDWheel(); // We init the DWheel method (getDWheel returns the value since the last call, so we have to call it once on ui creation) - } - - ///////////////////// - // WIDGET HANDLING // - ///////////////////// - - public IWidget addWidget(String name, IWidget widget){ - this.widgets.put(name, widget); - return this.getWidget(name); - } - - public IWidget getWidget(String name){ - return this.widgets.get(name); - } - - public IWidget delWidget(String name){ - IWidget widget = this.getWidget(name); - //this.widgets.remove(widget); - this.widgets.remove(name); - return widget; - } - - public IWidget getRoot(){ - return this.getWidget("canvas"); - } - - ///////////////////// - // DRAWING METHODS // - ///////////////////// - - @Override - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); //The dark background common to most of the UIs - super.drawScreen(i, j, f); - - for (IWidget widget: this.widgets.values()) - widget.draw(); - } +public abstract class ScreenBase extends GuiScreen { + protected GuiScreen parent; // Return screen if available. + protected Minecraft mc; // Minecraft instance + protected HashMap widgets; // List of widgets on this ui - // Used to easily display a UI without having to mess with mc handle. - public void display(){ - this.parent = this.mc.currentScreen; - this.mc.displayGuiScreen(this); - } - - ///////////////////// - // INPUT METHODS // - ///////////////////// - - //Keyboard handling. Basic one is just returning to the previous UI when Esc is pressed - @Override - public void keyTyped(char keyChar, int keyID) - { - if (keyID == 1) - if (this.parent == null){ - this.mc.displayGuiScreen((GuiScreen)null); - this.mc.setIngameFocus(); - } else - this.mc.displayGuiScreen(this.parent); - } + public ScreenBase(GuiScreen parent) { + this.parent = parent; + this.mc = Minecraft.getMinecraft(); + this.widgets = new HashMap(); - @Override - public void handleMouseInput() - { - this.getRoot().handleMouseInput(); - } + this.addWidget("canvas", new LayoutCanvas()); + Mouse.getDWheel(); // We init the DWheel method (getDWheel returns the value since the last call, so we have + // to call it once on ui creation) + } + + ///////////////////// + // WIDGET HANDLING // + ///////////////////// + + public IWidget addWidget(String name, IWidget widget) { + this.widgets.put(name, widget); + return this.getWidget(name); + } + + public IWidget getWidget(String name) { + return this.widgets.get(name); + } + + public IWidget delWidget(String name) { + IWidget widget = this.getWidget(name); + // this.widgets.remove(widget); + this.widgets.remove(name); + return widget; + } + + public IWidget getRoot() { + return this.getWidget("canvas"); + } + + ///////////////////// + // DRAWING METHODS // + ///////////////////// + + @Override + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); // The dark background common to most of the UIs + super.drawScreen(i, j, f); + + for (IWidget widget : this.widgets.values()) widget.draw(); + } + + // Used to easily display a UI without having to mess with mc handle. + public void display() { + this.parent = this.mc.currentScreen; + this.mc.displayGuiScreen(this); + } + + ///////////////////// + // INPUT METHODS // + ///////////////////// + + // Keyboard handling. Basic one is just returning to the previous UI when Esc is pressed + @Override + public void keyTyped(char keyChar, int keyID) { + if (keyID == 1) + if (this.parent == null) { + this.mc.displayGuiScreen((GuiScreen) null); + this.mc.setIngameFocus(); + } else this.mc.displayGuiScreen(this.parent); + } + + @Override + public void handleMouseInput() { + this.getRoot().handleMouseInput(); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/LabelFixedFont.java b/src/main/java/mcp/mobius/opis/gui/widgets/LabelFixedFont.java index 911311b..212e27d 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/LabelFixedFont.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/LabelFixedFont.java @@ -2,56 +2,59 @@ package mcp.mobius.opis.gui.widgets; import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; -import mcp.mobius.opis.gui.interfaces.Signal; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.util.ResourceLocation; - import org.lwjgl.util.Point; public class LabelFixedFont extends WidgetBase { - protected String text = ""; - protected int color; + protected String text = ""; + protected int color; - public LabelFixedFont(IWidget parent, String text){ - super(parent); - this.setText(text); - this.color = 0xFFFFFF; - } - - public LabelFixedFont(IWidget parent, String text, int color){ - super(parent); - this.setText(text); - this.color = color; - } - - @Override - public IWidget setGeometry(WidgetGeometry geom){ - this.geom = geom; - this.updateGeometry(); - return this; - } - - public void setText(String text){ - this.text = text; - this.updateGeometry(); - } - - public void setColor(int color){ - this.color = color; - } - - protected void updateGeometry(){ - if (this.geom == null) - this.geom = new WidgetGeometry(0,0,50,50, CType.ABSXY, CType.ABSXY); - - this.geom = new WidgetGeometry(this.geom.x, this.geom.y, this.mc.fontRenderer.getStringWidth(this.text), 8, this.geom.posType, CType.ABSXY, this.geom.alignX, this.geom.alignY); - } - - @Override - public void draw(Point pos) { - this.saveGLState(); - this.mc.fontRenderer.drawString(this.text, pos.getX(), pos.getY(), this.color); - this.loadGLState(); - } + public LabelFixedFont(IWidget parent, String text) { + super(parent); + this.setText(text); + this.color = 0xFFFFFF; + } + + public LabelFixedFont(IWidget parent, String text, int color) { + super(parent); + this.setText(text); + this.color = color; + } + + @Override + public IWidget setGeometry(WidgetGeometry geom) { + this.geom = geom; + this.updateGeometry(); + return this; + } + + public void setText(String text) { + this.text = text; + this.updateGeometry(); + } + + public void setColor(int color) { + this.color = color; + } + + protected void updateGeometry() { + if (this.geom == null) this.geom = new WidgetGeometry(0, 0, 50, 50, CType.ABSXY, CType.ABSXY); + + this.geom = new WidgetGeometry( + this.geom.x, + this.geom.y, + this.mc.fontRenderer.getStringWidth(this.text), + 8, + this.geom.posType, + CType.ABSXY, + this.geom.alignX, + this.geom.alignY); + } + + @Override + public void draw(Point pos) { + this.saveGLState(); + this.mc.fontRenderer.drawString(this.text, pos.getX(), pos.getY(), this.color); + this.loadGLState(); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/LabelScalable.java b/src/main/java/mcp/mobius/opis/gui/widgets/LabelScalable.java index 43da986..9e2353f 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/LabelScalable.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/LabelScalable.java @@ -1,33 +1,32 @@ package mcp.mobius.opis.gui.widgets; +import mcp.mobius.opis.gui.interfaces.IWidget; import org.lwjgl.opengl.GL11; import org.lwjgl.util.Point; -import mcp.mobius.opis.gui.interfaces.IWidget; - public class LabelScalable extends LabelFixedFont { - private float scale = 1.0f; - - public LabelScalable(IWidget parent, String text){ - super(parent, text); - } - - public LabelScalable(IWidget parent, String text, int color){ - super(parent,text, color); - } - - public LabelScalable setScale(float scale){ - this.scale = scale; - return this; - } - - @Override - public void draw(Point pos) { - this.saveGLState(); - GL11.glScalef(this.scale, this.scale, 1.0f); - this.mc.fontRenderer.drawString(this.text, (int)(pos.getX()/this.scale), (int)(pos.getY()/this.scale), this.color); - this.loadGLState(); - } - + private float scale = 1.0f; + + public LabelScalable(IWidget parent, String text) { + super(parent, text); + } + + public LabelScalable(IWidget parent, String text, int color) { + super(parent, text, color); + } + + public LabelScalable setScale(float scale) { + this.scale = scale; + return this; + } + + @Override + public void draw(Point pos) { + this.saveGLState(); + GL11.glScalef(this.scale, this.scale, 1.0f); + this.mc.fontRenderer.drawString( + this.text, (int) (pos.getX() / this.scale), (int) (pos.getY() / this.scale), this.color); + this.loadGLState(); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/LabelTTF.java b/src/main/java/mcp/mobius/opis/gui/widgets/LabelTTF.java index a79ea80..b6f19a8 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/LabelTTF.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/LabelTTF.java @@ -1,69 +1,69 @@ package mcp.mobius.opis.gui.widgets; -import org.lwjgl.opengl.GL11; -import org.lwjgl.util.Point; - import mcp.mobius.opis.gui.font.FontHelper; import mcp.mobius.opis.gui.font.TrueTypeFont; import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; +import org.lwjgl.util.Point; public class LabelTTF extends WidgetBase { - protected TrueTypeFont font; - protected String text = ""; - protected int color; - protected float scale = 1.0f; - - public LabelTTF(IWidget parent, String text, TrueTypeFont font){ - super(parent); - this.font = font; - this.color = 0xFFFFFF; - this.setText(text); - } - - public LabelTTF(IWidget parent, String text, int color, TrueTypeFont font){ - super(parent); - this.font = font; - this.color = color; - this.setText(text); - } - - public void setText(String text){ - this.text = text; - this.updateGeometry(); - } - - @Override - public IWidget setGeometry(WidgetGeometry geom){ - this.geom = geom; - this.updateGeometry(); - return this; - } - - public LabelTTF setScale(float scale){ - this.scale = scale; - return this; - } - - protected void updateGeometry(){ - if (this.geom == null) - this.geom = new WidgetGeometry(0,0,50,50, CType.ABSXY, CType.ABSXY); - - if (this.font == null || this.text == null) - return; - - this.geom = new WidgetGeometry(this.geom.x, this.geom.y, - this.font.getWidth(this.text), - this.font.getHeight(this.text) / this.rez.getScaleFactor(), - this.geom.posType, CType.ABSXY, this.geom.alignX, this.geom.alignY); - } - - @Override - public void draw(Point pos) { - this.saveGLState(); - FontHelper.drawString(this.text, pos.getX(), pos.getY(), this.font, this.scale, this.scale, this.color); - this.loadGLState(); - } - + protected TrueTypeFont font; + protected String text = ""; + protected int color; + protected float scale = 1.0f; + + public LabelTTF(IWidget parent, String text, TrueTypeFont font) { + super(parent); + this.font = font; + this.color = 0xFFFFFF; + this.setText(text); + } + + public LabelTTF(IWidget parent, String text, int color, TrueTypeFont font) { + super(parent); + this.font = font; + this.color = color; + this.setText(text); + } + + public void setText(String text) { + this.text = text; + this.updateGeometry(); + } + + @Override + public IWidget setGeometry(WidgetGeometry geom) { + this.geom = geom; + this.updateGeometry(); + return this; + } + + public LabelTTF setScale(float scale) { + this.scale = scale; + return this; + } + + protected void updateGeometry() { + if (this.geom == null) this.geom = new WidgetGeometry(0, 0, 50, 50, CType.ABSXY, CType.ABSXY); + + if (this.font == null || this.text == null) return; + + this.geom = new WidgetGeometry( + this.geom.x, + this.geom.y, + this.font.getWidth(this.text), + this.font.getHeight(this.text) / this.rez.getScaleFactor(), + this.geom.posType, + CType.ABSXY, + this.geom.alignX, + this.geom.alignY); + } + + @Override + public void draw(Point pos) { + this.saveGLState(); + FontHelper.drawString(this.text, pos.getX(), pos.getY(), this.font, this.scale, this.scale, this.color); + this.loadGLState(); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/LayoutBase.java b/src/main/java/mcp/mobius/opis/gui/widgets/LayoutBase.java index c884c1d..74fbceb 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/LayoutBase.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/LayoutBase.java @@ -1,47 +1,46 @@ package mcp.mobius.opis.gui.widgets; -import mcp.mobius.opis.gui.events.MouseEvent; import mcp.mobius.opis.gui.helpers.UIHelper; import mcp.mobius.opis.gui.interfaces.IWidget; - import org.lwjgl.util.Point; public class LayoutBase extends WidgetBase { - protected int bgcolor1 = 0x00000000; - protected int bgcolor2 = 0x00000000; - protected boolean renderBG; - - public LayoutBase(IWidget parent){ - super(parent); - } - - @Override - public void draw(Point pos) { - if (this.renderBG) - UIHelper.drawGradientRect(this.getLeft(), this.getTop(), this.getRight(), this.getBottom(), 0, this.bgcolor1, this.bgcolor2); - } + protected int bgcolor1 = 0x00000000; + protected int bgcolor2 = 0x00000000; + protected boolean renderBG; + + public LayoutBase(IWidget parent) { + super(parent); + } + + @Override + public void draw(Point pos) { + if (this.renderBG) + UIHelper.drawGradientRect( + this.getLeft(), this.getTop(), this.getRight(), this.getBottom(), 0, this.bgcolor1, this.bgcolor2); + } + + public void setBackgroundColors(int bg1, int bg2) { + this.bgcolor1 = bg1; + this.bgcolor2 = bg2; + this.renderBG = true; + } + + /* + @Override + public void onMouseEnter(MouseEvent event) { + IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); + if (widget != null && widget != this) + widget.onMouseEnter(event); + } + + @Override + public void onMouseLeave(MouseEvent event) { + IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); + if (widget != null && widget != this) + widget.onMouseLeave(event); + } + */ - public void setBackgroundColors(int bg1, int bg2){ - this.bgcolor1 = bg1; - this.bgcolor2 = bg2; - this.renderBG = true; - } - - /* - @Override - public void onMouseEnter(MouseEvent event) { - IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); - if (widget != null && widget != this) - widget.onMouseEnter(event); - } - - @Override - public void onMouseLeave(MouseEvent event) { - IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); - if (widget != null && widget != this) - widget.onMouseLeave(event); - } - */ - } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/LayoutCanvas.java b/src/main/java/mcp/mobius/opis/gui/widgets/LayoutCanvas.java index f6f8fdb..8de7e0d 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/LayoutCanvas.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/LayoutCanvas.java @@ -1,132 +1,123 @@ package mcp.mobius.opis.gui.widgets; -import net.minecraft.client.gui.ScaledResolution; - -import org.lwjgl.input.Mouse; -import org.lwjgl.util.Point; - import mcp.mobius.opis.gui.events.MouseEvent; import mcp.mobius.opis.gui.events.MouseEvent.EventType; import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.Signal; +import net.minecraft.client.gui.ScaledResolution; +import org.lwjgl.input.Mouse; +import org.lwjgl.util.Point; -public class LayoutCanvas extends LayoutBase{ +public class LayoutCanvas extends LayoutBase { - private MouseEvent lastMouseEvent; - private IWidget draggedWidget = null; - - public LayoutCanvas(){ - super(null); - this.setGeometry(0, 0, this.rez.getScaledWidth(), this.rez.getScaledHeight(), CType.ABSXY, CType.ABSXY); - Mouse.getDWheel(); // This is to "calibrate" the DWheel + private MouseEvent lastMouseEvent; + private IWidget draggedWidget = null; + + public LayoutCanvas() { + super(null); + this.setGeometry(0, 0, this.rez.getScaledWidth(), this.rez.getScaledHeight(), CType.ABSXY, CType.ABSXY); + Mouse.getDWheel(); // This is to "calibrate" the DWheel this.lastMouseEvent = new MouseEvent(this); - } - - @Override - public void draw(){ - this.rez = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - this.setGeometry(0, 0, this.rez.getScaledWidth(), this.rez.getScaledHeight(), CType.ABSXY, CType.ABSXY); - - /* - this.draw(this.getPos()); - - for (IWidget widget: this.widgets.values()) - if (widget.shouldRender()) - widget.draw(); - */ - - super.draw(); - - this.handleMouseInput(); - } - - @Override - public void draw(Point pos) { super.draw(pos); } - - @Override - public void handleMouseInput(){ - // Here we are going to generate the require mouse events we will pass down to all the other widgets - // This is more or less where the magic happens. If you want mouse support for a widget, it should be - // attached to a canvas like this one, or any inheriting one. - - MouseEvent event = new MouseEvent(this); - EventType type = event.getEventType(this.lastMouseEvent); - IWidget targetWidget = this.getWidgetAtCoordinates(event.x, event.y); - - switch (type){ - case CLICK: - if (targetWidget != null) - targetWidget.onMouseClick(event); - //this.onMouseClick(event); - break; - case DRAG: - if (targetWidget != null) - targetWidget.onMouseDrag(event); - //this.onMouseDrag(event); - break; - case MOVE: - if (targetWidget != null) - targetWidget.onMouseMove(event); - //this.onMouseMove(event); - break; - case RELEASED: - if (targetWidget != null) - targetWidget.onMouseRelease(event); - //this.onMouseRelease(event); - break; - case WHEEL: - if (targetWidget != null) - targetWidget.onMouseWheel(event); - //this.onMouseWheel(event); - break; - case ENTER: - if (event.trgwidget != null) - event.trgwidget.onMouseEnter(event); - if (this.lastMouseEvent.trgwidget != null){ - event.type = EventType.LEAVE; - this.lastMouseEvent.trgwidget.onMouseLeave(event); - } - break; - case NONE: - break; - default: - break; - } - - this.lastMouseEvent = event; - } + } @Override - public void onWidgetEvent(IWidget srcwidget, Signal signal, Object... params){ - if (signal == Signal.DRAGGED) - this.draggedWidget = srcwidget; - else - super.onWidgetEvent(srcwidget, signal, params); + public void draw() { + this.rez = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + this.setGeometry(0, 0, this.rez.getScaledWidth(), this.rez.getScaledHeight(), CType.ABSXY, CType.ABSXY); + + /* + this.draw(this.getPos()); + + for (IWidget widget: this.widgets.values()) + if (widget.shouldRender()) + widget.draw(); + */ + + super.draw(); + + this.handleMouseInput(); } - + @Override - public void onMouseRelease(MouseEvent event){ - if(event.button == 0) - this.draggedWidget = null; - super.onMouseRelease(event); + public void draw(Point pos) { + super.draw(pos); } - + @Override - public void onMouseDrag(MouseEvent event){ - if (this.draggedWidget != null) - this.draggedWidget.onMouseDrag(event); - else - super.onMouseDrag(event); + public void handleMouseInput() { + // Here we are going to generate the require mouse events we will pass down to all the other widgets + // This is more or less where the magic happens. If you want mouse support for a widget, it should be + // attached to a canvas like this one, or any inheriting one. + + MouseEvent event = new MouseEvent(this); + EventType type = event.getEventType(this.lastMouseEvent); + IWidget targetWidget = this.getWidgetAtCoordinates(event.x, event.y); + + switch (type) { + case CLICK: + if (targetWidget != null) targetWidget.onMouseClick(event); + // this.onMouseClick(event); + break; + case DRAG: + if (targetWidget != null) targetWidget.onMouseDrag(event); + // this.onMouseDrag(event); + break; + case MOVE: + if (targetWidget != null) targetWidget.onMouseMove(event); + // this.onMouseMove(event); + break; + case RELEASED: + if (targetWidget != null) targetWidget.onMouseRelease(event); + // this.onMouseRelease(event); + break; + case WHEEL: + if (targetWidget != null) targetWidget.onMouseWheel(event); + // this.onMouseWheel(event); + break; + case ENTER: + if (event.trgwidget != null) event.trgwidget.onMouseEnter(event); + if (this.lastMouseEvent.trgwidget != null) { + event.type = EventType.LEAVE; + this.lastMouseEvent.trgwidget.onMouseLeave(event); + } + break; + case NONE: + break; + default: + break; + } + + this.lastMouseEvent = event; } - - public boolean hasWidgetAtCursor(){ - double x = (double)Mouse.getEventX() * (double)this.getSize().getX() / (double)this.mc.displayWidth; - double y = (double)this.getSize().getY() - (double)Mouse.getEventY() * (double)this.getSize().getY() / (double)this.mc.displayHeight - 1.0; - IWidget widget = this.getWidgetAtCoordinates(x, y); - if (widget != null && !widget.equals(this)){ - return true; - } - return false; + + @Override + public void onWidgetEvent(IWidget srcwidget, Signal signal, Object... params) { + if (signal == Signal.DRAGGED) this.draggedWidget = srcwidget; + else super.onWidgetEvent(srcwidget, signal, params); + } + + @Override + public void onMouseRelease(MouseEvent event) { + if (event.button == 0) this.draggedWidget = null; + super.onMouseRelease(event); + } + + @Override + public void onMouseDrag(MouseEvent event) { + if (this.draggedWidget != null) this.draggedWidget.onMouseDrag(event); + else super.onMouseDrag(event); + } + + public boolean hasWidgetAtCursor() { + double x = (double) Mouse.getEventX() * (double) this.getSize().getX() / (double) this.mc.displayWidth; + double y = (double) this.getSize().getY() + - (double) Mouse.getEventY() * (double) this.getSize().getY() / (double) this.mc.displayHeight + - 1.0; + IWidget widget = this.getWidgetAtCoordinates(x, y); + if (widget != null && !widget.equals(this)) { + return true; + } + return false; } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/LayoutCropping.java b/src/main/java/mcp/mobius/opis/gui/widgets/LayoutCropping.java index 8c015af..90da8f9 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/LayoutCropping.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/LayoutCropping.java @@ -2,71 +2,71 @@ package mcp.mobius.opis.gui.widgets; import mcp.mobius.opis.gui.interfaces.IWidget; import net.minecraft.client.gui.ScaledResolution; - import org.lwjgl.opengl.GL11; import org.lwjgl.util.Point; public class LayoutCropping extends LayoutBase { - int xOffset = 0; - int yOffset = 0; - - public LayoutCropping(IWidget parent){ - super(parent); - } + int xOffset = 0; + int yOffset = 0; - public void setOffsets(int xoffset, int yoffset){ - this.xOffset = xoffset; - this.yOffset = yoffset; - } - - @Override - public void draw(){ - this.rez = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - this.saveGLState(); - - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA,GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glColor4f(1.0f, 1.0f, 1.0f, this.alpha); - - this.draw(this.getPos()); - - GL11.glEnable(GL11.GL_SCISSOR_TEST); - GL11.glScissor(this.getPos().getX()*this.rez.getScaleFactor(), (this.rez.getScaledHeight() - (this.getPos().getY() + this.getSize().getY())) * this.rez.getScaleFactor(), this.getSize().getX()*this.rez.getScaleFactor(), this.getSize().getY()*this.rez.getScaleFactor()); - //GL11.glScissor(this.getPos().getX()*this.rez.getScaleFactor(), this.getPos().getY()*this.rez.getScaleFactor(), this.getSize().getX()*this.rez.getScaleFactor(), this.getSize().getY()*this.rez.getScaleFactor()); - - //this.setPos(this.getLeft() - xOffset, this.getTop() - yOffset); - - GL11.glTranslatef(xOffset, yOffset, 0.0f); - - /* - for (IWidget widget: this.widgets.values()) - if (widget.shouldRender()) - widget.draw(); - */ - + public LayoutCropping(IWidget parent) { + super(parent); + } - for (IWidget widget: this.renderQueue_LOW.values()) - if (widget.shouldRender()) - widget.draw(); + public void setOffsets(int xoffset, int yoffset) { + this.xOffset = xoffset; + this.yOffset = yoffset; + } - for (IWidget widget: this.renderQueue_MEDIUM.values()) - if (widget.shouldRender()) - widget.draw(); - - for (IWidget widget: this.renderQueue_HIGH.values()) - if (widget.shouldRender()) - widget.draw(); + @Override + public void draw() { + this.rez = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + this.saveGLState(); - //this.setPos(this.getLeft() + xOffset, this.getTop() + yOffset); - + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1.0f, 1.0f, 1.0f, this.alpha); - GL11.glDisable(GL11.GL_SCISSOR_TEST); - - this.loadGLState(); - } - - @Override - public void draw(Point pos) { super.draw(pos); } + this.draw(this.getPos()); + GL11.glEnable(GL11.GL_SCISSOR_TEST); + GL11.glScissor( + this.getPos().getX() * this.rez.getScaleFactor(), + (this.rez.getScaledHeight() + - (this.getPos().getY() + this.getSize().getY())) + * this.rez.getScaleFactor(), + this.getSize().getX() * this.rez.getScaleFactor(), + this.getSize().getY() * this.rez.getScaleFactor()); + // GL11.glScissor(this.getPos().getX()*this.rez.getScaleFactor(), + // this.getPos().getY()*this.rez.getScaleFactor(), this.getSize().getX()*this.rez.getScaleFactor(), + // this.getSize().getY()*this.rez.getScaleFactor()); + + // this.setPos(this.getLeft() - xOffset, this.getTop() - yOffset); + + GL11.glTranslatef(xOffset, yOffset, 0.0f); + + /* + for (IWidget widget: this.widgets.values()) + if (widget.shouldRender()) + widget.draw(); + */ + + for (IWidget widget : this.renderQueue_LOW.values()) if (widget.shouldRender()) widget.draw(); + + for (IWidget widget : this.renderQueue_MEDIUM.values()) if (widget.shouldRender()) widget.draw(); + + for (IWidget widget : this.renderQueue_HIGH.values()) if (widget.shouldRender()) widget.draw(); + + // this.setPos(this.getLeft() + xOffset, this.getTop() + yOffset); + + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + this.loadGLState(); + } + + @Override + public void draw(Point pos) { + super.draw(pos); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/LayoutMargin.java b/src/main/java/mcp/mobius/opis/gui/widgets/LayoutMargin.java index 78ee2aa..7cb5762 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/LayoutMargin.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/LayoutMargin.java @@ -3,41 +3,41 @@ package mcp.mobius.opis.gui.widgets; import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.WAlign; - import org.lwjgl.util.Point; public class LayoutMargin extends LayoutBase { - int left = 0; - int right = 0; - int top = 0; - int bottom = 0; - - public LayoutMargin(IWidget parent){ - super (parent); - this.setGeometry(new WidgetGeometry(0,0,0,0,CType.ABSXY,CType.ABSXY,WAlign.CENTER,WAlign.CENTER)); - } - - public void setMargins(int left, int right, int top, int bottom){ - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; - } - - @Override - public Point getSize(){ - Point parentSize = this.parent.getSize(); - return new Point(parentSize.getX() - left - right, parentSize.getY() - top - bottom); - } + int left = 0; + int right = 0; + int top = 0; + int bottom = 0; - @Override - public Point getPos(){ - Point parentPos = this.parent.getPos(); - return new Point(parentPos.getX() + left, parentPos.getY() + top); - } - - @Override - public void draw(Point pos) { super.draw(pos); } + public LayoutMargin(IWidget parent) { + super(parent); + this.setGeometry(new WidgetGeometry(0, 0, 0, 0, CType.ABSXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); + } + public void setMargins(int left, int right, int top, int bottom) { + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + } + + @Override + public Point getSize() { + Point parentSize = this.parent.getSize(); + return new Point(parentSize.getX() - left - right, parentSize.getY() - top - bottom); + } + + @Override + public Point getPos() { + Point parentPos = this.parent.getPos(); + return new Point(parentPos.getX() + left, parentPos.getY() + top); + } + + @Override + public void draw(Point pos) { + super.draw(pos); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/PictureDisplay.java b/src/main/java/mcp/mobius/opis/gui/widgets/PictureDisplay.java index 1977030..9b3d2d2 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/PictureDisplay.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/PictureDisplay.java @@ -2,30 +2,29 @@ package mcp.mobius.opis.gui.widgets; import mcp.mobius.opis.gui.helpers.UIHelper; import mcp.mobius.opis.gui.interfaces.IWidget; -import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.ResourceLocation; - import org.lwjgl.opengl.GL11; import org.lwjgl.util.Point; public class PictureDisplay extends WidgetBase { - protected ResourceLocation texture; - - public PictureDisplay(IWidget parent, String uri){ - super(parent); - this.texture = new ResourceLocation(uri); - } - - @Override - public void draw(Point pos) { - this.saveGLState(); - - GL11.glPushMatrix(); - this.texManager.bindTexture(texture); - UIHelper.drawTexture(pos.getX(), pos.getY(), this.getSize().getX(), this.getSize().getY()); - GL11.glPopMatrix(); + protected ResourceLocation texture; - this.loadGLState(); - } + public PictureDisplay(IWidget parent, String uri) { + super(parent); + this.texture = new ResourceLocation(uri); + } + + @Override + public void draw(Point pos) { + this.saveGLState(); + + GL11.glPushMatrix(); + this.texManager.bindTexture(texture); + UIHelper.drawTexture( + pos.getX(), pos.getY(), this.getSize().getX(), this.getSize().getY()); + GL11.glPopMatrix(); + + this.loadGLState(); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/PictureSwitch.java b/src/main/java/mcp/mobius/opis/gui/widgets/PictureSwitch.java index c9b9b2d..f97496a 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/PictureSwitch.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/PictureSwitch.java @@ -4,46 +4,45 @@ import mcp.mobius.opis.gui.events.MouseEvent; import mcp.mobius.opis.gui.helpers.UIHelper; import mcp.mobius.opis.gui.interfaces.IWidget; import net.minecraft.util.ResourceLocation; - import org.lwjgl.opengl.GL11; import org.lwjgl.util.Point; public class PictureSwitch extends WidgetBase { - private ResourceLocation texture1; - private ResourceLocation texture2; - private boolean mouseOver = false; - - public PictureSwitch(IWidget parent, String uri1, String uri2){ - super(parent); - this.texture1 = new ResourceLocation(uri1); - this.texture2 = new ResourceLocation(uri2); - } - - @Override - public void draw(Point pos) { - this.saveGLState(); - - ResourceLocation texture = mouseOver ? this.texture2 : this.texture1; - - GL11.glPushMatrix(); - this.texManager.bindTexture(texture); - UIHelper.drawTexture(pos.getX(), pos.getY(), this.getSize().getX(), this.getSize().getY()); - GL11.glPopMatrix(); + private ResourceLocation texture1; + private ResourceLocation texture2; + private boolean mouseOver = false; - this.loadGLState(); - } - - @Override - public void onMouseEnter(MouseEvent event){ - //System.out.printf("%s %s\n", this, event); - mouseOver = true; - } + public PictureSwitch(IWidget parent, String uri1, String uri2) { + super(parent); + this.texture1 = new ResourceLocation(uri1); + this.texture2 = new ResourceLocation(uri2); + } - @Override - public void onMouseLeave(MouseEvent event){ - //System.out.printf("%s %s\n", this, event); - mouseOver = false; - } - + @Override + public void draw(Point pos) { + this.saveGLState(); + + ResourceLocation texture = mouseOver ? this.texture2 : this.texture1; + + GL11.glPushMatrix(); + this.texManager.bindTexture(texture); + UIHelper.drawTexture( + pos.getX(), pos.getY(), this.getSize().getX(), this.getSize().getY()); + GL11.glPopMatrix(); + + this.loadGLState(); + } + + @Override + public void onMouseEnter(MouseEvent event) { + // System.out.printf("%s %s\n", this, event); + mouseOver = true; + } + + @Override + public void onMouseLeave(MouseEvent event) { + // System.out.printf("%s %s\n", this, event); + mouseOver = false; + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/ViewportScrollable.java b/src/main/java/mcp/mobius/opis/gui/widgets/ViewportScrollable.java index 3512765..7cfcd41 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/ViewportScrollable.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/ViewportScrollable.java @@ -6,176 +6,178 @@ import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.Signal; import mcp.mobius.opis.gui.interfaces.WAlign; - -import org.lwjgl.opengl.Display; import org.lwjgl.util.Point; public class ViewportScrollable extends WidgetBase { - public class Escalator extends WidgetBase{ - int yOffset = 0; - int sizeCursor = 8; - int maxValue = 0; - int step = 0; - boolean drag = false; - - public Escalator(IWidget parent, int step){ - this.parent = parent; - this.step = step; - } + public class Escalator extends WidgetBase { + int yOffset = 0; + int sizeCursor = 8; + int maxValue = 0; + int step = 0; + boolean drag = false; - public void setOffset(int yoffset){ - this.yOffset = yoffset; - } - - public void setMaxValue(int value){ - this.maxValue = value; - } - - public void setStep(int step){ - this.step = step; - } - - @Override - public void draw(Point pos) { - UIHelper.drawGradientRect(this.getLeft(), this.getTop(), this.getRight(), this.getBottom(), 1, 0xff999999, 0xff999999); - int offsetScaled = (int)(((double)this.getSize().getY() - (double)sizeCursor + 1) / (double)this.maxValue * (yOffset)); - UIHelper.drawGradientRect(this.getLeft(), this.getTop() + offsetScaled, this.getRight(), this.getTop() + offsetScaled + sizeCursor, 1, 0xffffffff, 0xffffffff); - } - - @Override - public void onMouseClick(MouseEvent event){ - if (event.button == 0){ - int offsetScaled = this.getTop() + (int)(((double)this.getSize().getY() - (double)sizeCursor + 1) / (double)this.maxValue * (yOffset)); - - this.drag = false; - - if (event.y < offsetScaled) - this.yOffset += this.step; - else if (event.y > offsetScaled + sizeCursor) - this.yOffset -= this.step; - else - this.drag = true; - - this.emit(Signal.VALUE_CHANGED, this.yOffset); - - } else { - super.onMouseClick(event); - } - } - - @Override - public void onMouseRelease(MouseEvent event){ - if (event.button == 0) - this.drag = false; - super.onMouseRelease(event); - } - - @Override - public void onMouseDrag(MouseEvent event){ - if (this.drag){ - int relativeY = (int)event.y - this.getTop(); - double factor = ((double)this.getSize().getY() - (double)sizeCursor + 1) / (double)this.maxValue; - this.yOffset = (int)(relativeY / factor); - this.yOffset = Math.max(this.yOffset, this.maxValue); - this.yOffset = Math.min(this.yOffset, 0); - this.emit(Signal.VALUE_CHANGED, this.yOffset); - this.emit(Signal.DRAGGED, this); - } - else - super.onMouseDrag(event); - } - - } - - IWidget attachedWidget = null; - int yOffset = 0; - int step = 5; + public Escalator(IWidget parent, int step) { + this.parent = parent; + this.step = step; + } - public ViewportScrollable( IWidget parent){ - super(parent); - this.addWidget("Cropping", new LayoutCropping(null)).setGeometry(new WidgetGeometry(0.0, 0.0, 100.0, 100.0, CType.RELXY, CType.RELXY, WAlign.LEFT, WAlign.TOP)); - this.addWidget("Escalator", new Escalator(null, this.step * 5)).setGeometry(new WidgetGeometry(100.0, 0, 8, 100.0, CType.RELXY, CType.REL_Y, WAlign.RIGHT, WAlign.TOP)).hide(); - } + public void setOffset(int yoffset) { + this.yOffset = yoffset; + } - public IWidget attachWidget(IWidget widget){ - this.attachedWidget = this.getWidget("Cropping").addWidget("Cropped", widget); - return this.attachedWidget; - } + public void setMaxValue(int value) { + this.maxValue = value; + } - public IWidget getAttachedWidget(){ - return this.attachedWidget; - } - - public IWidget setStep(int step){ - this.step = step; - ((Escalator)this.getWidget("Escalator")).setStep(this.step * 5); - return this; - } - - public int getOffset(){ return this.yOffset; }; - - @Override - public void draw(Point pos) {} - - @Override - public void draw(){ - //if (Display.wasResized()) - - if ((this.attachedWidget != null) && (this.attachedWidget.getSize().getY() > this.getSize().getY())) - this.getWidget("Escalator").show(); - else - this.getWidget("Escalator").hide(); - - super.draw(); - } - - @Override - public void onMouseWheel(MouseEvent event){ - this.yOffset += event.z / 120.0 * this.step; + public void setStep(int step) { + this.step = step; + } - this.yOffset = Math.max(this.yOffset, this.getSize().getY() - this.attachedWidget.getSize().getY()); - this.yOffset = Math.min(this.yOffset, 0); - - ((LayoutCropping)this.getWidget("Cropping")).setOffsets(0, this.yOffset); - ((Escalator)this.getWidget("Escalator")).setOffset(this.yOffset); - } - - @Override - public void onWidgetEvent(IWidget srcwidget, Signal signal, Object... params){ - if (srcwidget.equals(this.attachedWidget) && signal == Signal.GEOM_CHANGED){ - ((Escalator)this.getWidget("Escalator")).setMaxValue(this.getSize().getY() - srcwidget.getSize().getY()); - } + @Override + public void draw(Point pos) { + UIHelper.drawGradientRect( + this.getLeft(), this.getTop(), this.getRight(), this.getBottom(), 1, 0xff999999, 0xff999999); + int offsetScaled = (int) + (((double) this.getSize().getY() - (double) sizeCursor + 1) / (double) this.maxValue * (yOffset)); + UIHelper.drawGradientRect( + this.getLeft(), + this.getTop() + offsetScaled, + this.getRight(), + this.getTop() + offsetScaled + sizeCursor, + 1, + 0xffffffff, + 0xffffffff); + } - else if (srcwidget.equals(this.getWidget("Escalator")) && signal == Signal.VALUE_CHANGED){ - this.yOffset = (Integer)params[0]; - ((LayoutCropping)this.getWidget("Cropping")).setOffsets(0, this.yOffset); - } - else - super.onWidgetEvent(srcwidget, signal, params); - - } - - @Override - public void onMouseDrag(MouseEvent event){ - if (this.getWidget("Escalator").shouldRender() && ((Escalator)this.getWidget("Escalator")).drag) - this.getWidget("Escalator").onMouseDrag(event); - else - super.onMouseDrag(event); - } + @Override + public void onMouseClick(MouseEvent event) { + if (event.button == 0) { + int offsetScaled = this.getTop() + + (int) (((double) this.getSize().getY() - (double) sizeCursor + 1) + / (double) this.maxValue + * (yOffset)); - @Override - public void onMouseClick(MouseEvent event){ - if (event.button == 0){ - if (!this.getWidget("Escalator").isWidgetAtCoordinates(event.x, event.y)){ - ((Escalator)this.getWidget("Escalator")).drag = false; - super.onMouseClick(event); - } - else - this.getWidget("Escalator").onMouseClick(event); - } - else - super.onMouseClick(event); - } - + this.drag = false; + + if (event.y < offsetScaled) this.yOffset += this.step; + else if (event.y > offsetScaled + sizeCursor) this.yOffset -= this.step; + else this.drag = true; + + this.emit(Signal.VALUE_CHANGED, this.yOffset); + + } else { + super.onMouseClick(event); + } + } + + @Override + public void onMouseRelease(MouseEvent event) { + if (event.button == 0) this.drag = false; + super.onMouseRelease(event); + } + + @Override + public void onMouseDrag(MouseEvent event) { + if (this.drag) { + int relativeY = (int) event.y - this.getTop(); + double factor = ((double) this.getSize().getY() - (double) sizeCursor + 1) / (double) this.maxValue; + this.yOffset = (int) (relativeY / factor); + this.yOffset = Math.max(this.yOffset, this.maxValue); + this.yOffset = Math.min(this.yOffset, 0); + this.emit(Signal.VALUE_CHANGED, this.yOffset); + this.emit(Signal.DRAGGED, this); + } else super.onMouseDrag(event); + } + } + + IWidget attachedWidget = null; + int yOffset = 0; + int step = 5; + + public ViewportScrollable(IWidget parent) { + super(parent); + this.addWidget("Cropping", new LayoutCropping(null)) + .setGeometry( + new WidgetGeometry(0.0, 0.0, 100.0, 100.0, CType.RELXY, CType.RELXY, WAlign.LEFT, WAlign.TOP)); + this.addWidget("Escalator", new Escalator(null, this.step * 5)) + .setGeometry(new WidgetGeometry(100.0, 0, 8, 100.0, CType.RELXY, CType.REL_Y, WAlign.RIGHT, WAlign.TOP)) + .hide(); + } + + public IWidget attachWidget(IWidget widget) { + this.attachedWidget = this.getWidget("Cropping").addWidget("Cropped", widget); + return this.attachedWidget; + } + + public IWidget getAttachedWidget() { + return this.attachedWidget; + } + + public IWidget setStep(int step) { + this.step = step; + ((Escalator) this.getWidget("Escalator")).setStep(this.step * 5); + return this; + } + + public int getOffset() { + return this.yOffset; + } + ; + + @Override + public void draw(Point pos) {} + + @Override + public void draw() { + // if (Display.wasResized()) + + if ((this.attachedWidget != null) + && (this.attachedWidget.getSize().getY() > this.getSize().getY())) + this.getWidget("Escalator").show(); + else this.getWidget("Escalator").hide(); + + super.draw(); + } + + @Override + public void onMouseWheel(MouseEvent event) { + this.yOffset += event.z / 120.0 * this.step; + + this.yOffset = Math.max( + this.yOffset, + this.getSize().getY() - this.attachedWidget.getSize().getY()); + this.yOffset = Math.min(this.yOffset, 0); + + ((LayoutCropping) this.getWidget("Cropping")).setOffsets(0, this.yOffset); + ((Escalator) this.getWidget("Escalator")).setOffset(this.yOffset); + } + + @Override + public void onWidgetEvent(IWidget srcwidget, Signal signal, Object... params) { + if (srcwidget.equals(this.attachedWidget) && signal == Signal.GEOM_CHANGED) { + ((Escalator) this.getWidget("Escalator")) + .setMaxValue(this.getSize().getY() - srcwidget.getSize().getY()); + } else if (srcwidget.equals(this.getWidget("Escalator")) && signal == Signal.VALUE_CHANGED) { + this.yOffset = (Integer) params[0]; + ((LayoutCropping) this.getWidget("Cropping")).setOffsets(0, this.yOffset); + } else super.onWidgetEvent(srcwidget, signal, params); + } + + @Override + public void onMouseDrag(MouseEvent event) { + if (this.getWidget("Escalator").shouldRender() && ((Escalator) this.getWidget("Escalator")).drag) + this.getWidget("Escalator").onMouseDrag(event); + else super.onMouseDrag(event); + } + + @Override + public void onMouseClick(MouseEvent event) { + if (event.button == 0) { + if (!this.getWidget("Escalator").isWidgetAtCoordinates(event.x, event.y)) { + ((Escalator) this.getWidget("Escalator")).drag = false; + super.onMouseClick(event); + } else this.getWidget("Escalator").onMouseClick(event); + } else super.onMouseClick(event); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/WidgetBase.java b/src/main/java/mcp/mobius/opis/gui/widgets/WidgetBase.java index bf71059..2a7c711 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/WidgetBase.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/WidgetBase.java @@ -1,392 +1,410 @@ package mcp.mobius.opis.gui.widgets; -import java.util.ArrayList; -import java.util.HashMap; import java.util.LinkedHashMap; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.util.Point; - -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.Table; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.ScaledResolution; -import net.minecraft.client.renderer.texture.TextureManager; import mcp.mobius.opis.gui.events.MouseEvent; import mcp.mobius.opis.gui.helpers.ReverseIterator; import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.RenderPriority; import mcp.mobius.opis.gui.interfaces.Signal; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.texture.TextureManager; +import org.lwjgl.opengl.GL11; +import org.lwjgl.util.Point; public abstract class WidgetBase implements IWidget { - protected IWidget parent; - protected WidgetGeometry geom; - protected LinkedHashMap widgets = new LinkedHashMap(); - protected LinkedHashMap renderQueue_HIGH = new LinkedHashMap(); + protected IWidget parent; + protected WidgetGeometry geom; + protected LinkedHashMap widgets = new LinkedHashMap(); + protected LinkedHashMap renderQueue_HIGH = new LinkedHashMap(); protected LinkedHashMap renderQueue_MEDIUM = new LinkedHashMap(); - protected LinkedHashMap renderQueue_LOW = new LinkedHashMap(); - protected Minecraft mc; + protected LinkedHashMap renderQueue_LOW = new LinkedHashMap(); + protected Minecraft mc; protected TextureManager texManager; protected ScaledResolution rez; - protected boolean hasBlending; - protected boolean hasLight; - protected int boundTexIndex; - - protected boolean isRendering = true; - - protected float alpha = 1.0f; - - public WidgetBase(){ - this.setParent(null); - this.mc = Minecraft.getMinecraft(); - this.rez = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - this.texManager = this.mc.renderEngine; - this.setGeometry(new WidgetGeometry(0, 0, 50, 50, CType.ABSXY, CType.ABSXY)); - } - - public WidgetBase(IWidget parent){ - this.setParent(parent); - this.mc = Minecraft.getMinecraft(); - this.rez = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - this.texManager = this.mc.renderEngine; - this.setGeometry(new WidgetGeometry(0, 0, 50, 50, CType.ABSXY, CType.ABSXY)); - } - - ///////////////////// - // WIDGET HANDLING // - ///////////////////// - - @Override - public IWidget addWidget(String name, IWidget widget){ - return this.addWidget(name, widget, RenderPriority.MEDIUM); - } - - @Override - public IWidget addWidget(String name, IWidget widget, RenderPriority priority){ - widget.setParent(this); - this.widgets.put(name, widget); - - switch(priority){ - case LOW: - this.renderQueue_LOW.put(name, widget); - break; - case HIGH: - this.renderQueue_HIGH.put(name, widget); - break; - case MEDIUM: - this.renderQueue_MEDIUM.put(name, widget); - break; - } - + protected boolean hasBlending; + protected boolean hasLight; + protected int boundTexIndex; - return this.getWidget(name); - } - - - @Override - public IWidget getWidget(String name){ - return this.widgets.get(name); - } - - @Override - public IWidget delWidget(String name){ - IWidget widget = this.getWidget(name); - //this.widgets.remove(widget); - this.widgets.remove(name); - return widget; - } + protected boolean isRendering = true; - @Override - public boolean hasWidget(String name){ - if (this.widgets.containsKey(name)) return true; - return false; - } - - @Override - public IWidget getWidgetAtLayer(double posX, double posY, int layer){ - if (layer == 0) return this; - - int depth = 0; - return this._getWidgetAtLayer(posX, posY, layer, depth + 1); - } + protected float alpha = 1.0f; - private IWidget _getWidgetAtLayer(double posX, double posY, int layer, int depth){ - for (IWidget widget : this.widgets.values()){ - if ((posX >= widget.getPos().getX()) && - (posX <= widget.getPos().getX() + widget.getSize().getX()) && - (posY >= widget.getPos().getY()) && - (posY <= widget.getPos().getY() + widget.getSize().getY())){ - if (depth == layer) - return widget; - else - return ((WidgetBase)widget)._getWidgetAtLayer(posX, posY, layer, depth + 1); - } - } - return null; - } - - @Override - public IWidget getWidgetAtCoordinates(double posX, double posY){ - for (IWidget widget : new ReverseIterator(this.widgets.values())) - if ((posX >= widget.getPos().getX()) && - (posX <= widget.getPos().getX() + widget.getSize().getX()) && - (posY >= widget.getPos().getY()) && - (posY <= widget.getPos().getY() + widget.getSize().getY())) - return widget.getWidgetAtCoordinates(posX, posY); - - if ((posX >= this.getPos().getX()) && - (posX <= this.getPos().getX() + this.getSize().getX()) && - (posY >= this.getPos().getY()) && - (posY <= this.getPos().getY() + this.getSize().getY())) - return this; - - return null; - } - - @Override - public boolean isWidgetAtCoordinates(double posx, double posy){ - if (this.getLeft() > posx) return false; - if (this.getRight() < posx) return false; - if (this.getTop() > posy) return false; - if (this.getBottom() < posy) return false; - return true; - } - - /////////////////////// - // IWIDGET INTERFACE // - /////////////////////// - - @Override - public IWidget getParent() { return this.parent; } - @Override - public void setParent(IWidget parent) { this.parent = parent; } - - @Override - public void draw(){ - this.saveGLState(); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA,GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glColor4f(1.0f, 1.0f, 1.0f, this.alpha); - - this.draw(this.getPos()); - - /* - for (IWidget widget: this.widgets.values()) - if (widget.shouldRender()) - widget.draw(); - */ - - for (IWidget widget: this.renderQueue_LOW.values()) - if (widget.shouldRender()) - widget.draw(); - - for (IWidget widget: this.renderQueue_MEDIUM.values()) - if (widget.shouldRender()) - widget.draw(); - - for (IWidget widget: this.renderQueue_HIGH.values()) - if (widget.shouldRender()) - widget.draw(); - - this.loadGLState(); - } - - @Override - public abstract void draw(Point pos); - - @Override - public IWidget setGeometry(WidgetGeometry geom) { - this.geom = geom; - this.emit(Signal.GEOM_CHANGED, this.geom); - return this; - } - - public IWidget setGeometry(double x, double y, double sx, double sy, CType fp, CType fs){ - this.setGeometry(new WidgetGeometry (x, y, sx, sy, fp, fs)); - this.emit(Signal.GEOM_CHANGED, this.geom); - return this; - } - - @Override - public WidgetGeometry getGeometry() { return this.geom; } - @Override - public Point getPos() { return this.geom.getPos(this.parent); } - @Override - public Point getSize() { return this.geom.getSize(this.parent); } - @Override - public int getLeft() { return this.getPos().getX(); } - @Override - public int getRight() { return this.getPos().getX() + this.getSize().getX(); } - @Override - public int getTop() { return this.getPos().getY(); } - @Override - public int getBottom() { return this.getPos().getY() + this.getSize().getY(); } - - @Override - public IWidget setPos(double x, double y){ - return this.setPos(x, y, this.geom.fracPosX, this.geom.fracPosY); - } - - @Override - public IWidget setPos(double x, double y, boolean fracX, boolean fracY){ - this.geom.setPos(x, y, fracX, fracY); - this.emit(Signal.GEOM_CHANGED, this.geom); - return this; - }; - - @Override - public IWidget setSize(double sx, double sy){ - return this.setSize(sx, sy, this.geom.fracSizeX, this.geom.fracSizeY); - } - - @Override - public IWidget setSize(double sx, double sy, boolean fracX, boolean fracY){ - this.geom.setSize(sx, sy, fracX, fracY); - this.emit(Signal.GEOM_CHANGED, this.geom); - return this; - }; - - @Override - public IWidget adjustSize(){ - int minleft = 9999; - int maxright = 0; - int mintop = 9999; - int maxbottom = 0; - - for (IWidget widget : this.widgets.values()){ - minleft = Math.min(minleft, widget.getLeft()); - maxright = Math.max(maxright, widget.getRight()); - - mintop = Math.min(mintop, widget.getTop()); - maxbottom = Math.max(maxbottom, widget.getBottom()); - } - - this.setSize(maxright - minleft, maxbottom - mintop, false, false); - - this.emit(Signal.GEOM_CHANGED, this.geom); - return this; - } - - //////////////////////////// - // SOME RENDERING HELPERS // - //////////////////////////// - - protected void saveGLState(){ - hasBlending = GL11.glGetBoolean(GL11.GL_BLEND); - hasLight = GL11.glGetBoolean(GL11.GL_LIGHTING); - boundTexIndex = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); - GL11.glPushAttrib(GL11.GL_CURRENT_BIT); - GL11.glPushMatrix(); + public WidgetBase() { + this.setParent(null); + this.mc = Minecraft.getMinecraft(); + this.rez = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + this.texManager = this.mc.renderEngine; + this.setGeometry(new WidgetGeometry(0, 0, 50, 50, CType.ABSXY, CType.ABSXY)); } - - protected void loadGLState(){ - if (hasBlending) GL11.glEnable(GL11.GL_BLEND); else GL11.glDisable(GL11.GL_BLEND); - if (hasLight) GL11.glEnable(GL11.GL_LIGHTING); else GL11.glDisable(GL11.GL_LIGHTING); - GL11.glBindTexture(GL11.GL_TEXTURE_2D, boundTexIndex); - GL11.glPopMatrix(); - GL11.glPopAttrib(); - //GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + + public WidgetBase(IWidget parent) { + this.setParent(parent); + this.mc = Minecraft.getMinecraft(); + this.rez = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + this.texManager = this.mc.renderEngine; + this.setGeometry(new WidgetGeometry(0, 0, 50, 50, CType.ABSXY, CType.ABSXY)); } - - @Override - public void setAlpha(float alpha){this.alpha = alpha;}; - + + ///////////////////// + // WIDGET HANDLING // + ///////////////////// + @Override - public float getAlpha(){return this.alpha;}; - - @Override - public void show(){this.isRendering = true;}; - @Override - public void hide(){this.isRendering = false;}; - @Override - public boolean shouldRender(){return this.isRendering;}; - + public IWidget addWidget(String name, IWidget widget) { + return this.addWidget(name, widget, RenderPriority.MEDIUM); + } + + @Override + public IWidget addWidget(String name, IWidget widget, RenderPriority priority) { + widget.setParent(this); + this.widgets.put(name, widget); + + switch (priority) { + case LOW: + this.renderQueue_LOW.put(name, widget); + break; + case HIGH: + this.renderQueue_HIGH.put(name, widget); + break; + case MEDIUM: + this.renderQueue_MEDIUM.put(name, widget); + break; + } + + return this.getWidget(name); + } + + @Override + public IWidget getWidget(String name) { + return this.widgets.get(name); + } + + @Override + public IWidget delWidget(String name) { + IWidget widget = this.getWidget(name); + // this.widgets.remove(widget); + this.widgets.remove(name); + return widget; + } + + @Override + public boolean hasWidget(String name) { + if (this.widgets.containsKey(name)) return true; + return false; + } + + @Override + public IWidget getWidgetAtLayer(double posX, double posY, int layer) { + if (layer == 0) return this; + + int depth = 0; + return this._getWidgetAtLayer(posX, posY, layer, depth + 1); + } + + private IWidget _getWidgetAtLayer(double posX, double posY, int layer, int depth) { + for (IWidget widget : this.widgets.values()) { + if ((posX >= widget.getPos().getX()) + && (posX <= widget.getPos().getX() + widget.getSize().getX()) + && (posY >= widget.getPos().getY()) + && (posY <= widget.getPos().getY() + widget.getSize().getY())) { + if (depth == layer) return widget; + else return ((WidgetBase) widget)._getWidgetAtLayer(posX, posY, layer, depth + 1); + } + } + return null; + } + + @Override + public IWidget getWidgetAtCoordinates(double posX, double posY) { + for (IWidget widget : new ReverseIterator(this.widgets.values())) + if ((posX >= widget.getPos().getX()) + && (posX <= widget.getPos().getX() + widget.getSize().getX()) + && (posY >= widget.getPos().getY()) + && (posY <= widget.getPos().getY() + widget.getSize().getY())) + return widget.getWidgetAtCoordinates(posX, posY); + + if ((posX >= this.getPos().getX()) + && (posX <= this.getPos().getX() + this.getSize().getX()) + && (posY >= this.getPos().getY()) + && (posY <= this.getPos().getY() + this.getSize().getY())) return this; + + return null; + } + + @Override + public boolean isWidgetAtCoordinates(double posx, double posy) { + if (this.getLeft() > posx) return false; + if (this.getRight() < posx) return false; + if (this.getTop() > posy) return false; + if (this.getBottom() < posy) return false; + return true; + } + + /////////////////////// + // IWIDGET INTERFACE // + /////////////////////// + + @Override + public IWidget getParent() { + return this.parent; + } + + @Override + public void setParent(IWidget parent) { + this.parent = parent; + } + + @Override + public void draw() { + this.saveGLState(); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1.0f, 1.0f, 1.0f, this.alpha); + + this.draw(this.getPos()); + + /* + for (IWidget widget: this.widgets.values()) + if (widget.shouldRender()) + widget.draw(); + */ + + for (IWidget widget : this.renderQueue_LOW.values()) if (widget.shouldRender()) widget.draw(); + + for (IWidget widget : this.renderQueue_MEDIUM.values()) if (widget.shouldRender()) widget.draw(); + + for (IWidget widget : this.renderQueue_HIGH.values()) if (widget.shouldRender()) widget.draw(); + + this.loadGLState(); + } + + @Override + public abstract void draw(Point pos); + + @Override + public IWidget setGeometry(WidgetGeometry geom) { + this.geom = geom; + this.emit(Signal.GEOM_CHANGED, this.geom); + return this; + } + + public IWidget setGeometry(double x, double y, double sx, double sy, CType fp, CType fs) { + this.setGeometry(new WidgetGeometry(x, y, sx, sy, fp, fs)); + this.emit(Signal.GEOM_CHANGED, this.geom); + return this; + } + + @Override + public WidgetGeometry getGeometry() { + return this.geom; + } + + @Override + public Point getPos() { + return this.geom.getPos(this.parent); + } + + @Override + public Point getSize() { + return this.geom.getSize(this.parent); + } + + @Override + public int getLeft() { + return this.getPos().getX(); + } + + @Override + public int getRight() { + return this.getPos().getX() + this.getSize().getX(); + } + + @Override + public int getTop() { + return this.getPos().getY(); + } + + @Override + public int getBottom() { + return this.getPos().getY() + this.getSize().getY(); + } + + @Override + public IWidget setPos(double x, double y) { + return this.setPos(x, y, this.geom.fracPosX, this.geom.fracPosY); + } + + @Override + public IWidget setPos(double x, double y, boolean fracX, boolean fracY) { + this.geom.setPos(x, y, fracX, fracY); + this.emit(Signal.GEOM_CHANGED, this.geom); + return this; + } + ; + + @Override + public IWidget setSize(double sx, double sy) { + return this.setSize(sx, sy, this.geom.fracSizeX, this.geom.fracSizeY); + } + + @Override + public IWidget setSize(double sx, double sy, boolean fracX, boolean fracY) { + this.geom.setSize(sx, sy, fracX, fracY); + this.emit(Signal.GEOM_CHANGED, this.geom); + return this; + } + ; + + @Override + public IWidget adjustSize() { + int minleft = 9999; + int maxright = 0; + int mintop = 9999; + int maxbottom = 0; + + for (IWidget widget : this.widgets.values()) { + minleft = Math.min(minleft, widget.getLeft()); + maxright = Math.max(maxright, widget.getRight()); + + mintop = Math.min(mintop, widget.getTop()); + maxbottom = Math.max(maxbottom, widget.getBottom()); + } + + this.setSize(maxright - minleft, maxbottom - mintop, false, false); + + this.emit(Signal.GEOM_CHANGED, this.geom); + return this; + } + + //////////////////////////// + // SOME RENDERING HELPERS // + //////////////////////////// + + protected void saveGLState() { + hasBlending = GL11.glGetBoolean(GL11.GL_BLEND); + hasLight = GL11.glGetBoolean(GL11.GL_LIGHTING); + boundTexIndex = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + GL11.glPushAttrib(GL11.GL_CURRENT_BIT); + GL11.glPushMatrix(); + } + + protected void loadGLState() { + if (hasBlending) GL11.glEnable(GL11.GL_BLEND); + else GL11.glDisable(GL11.GL_BLEND); + if (hasLight) GL11.glEnable(GL11.GL_LIGHTING); + else GL11.glDisable(GL11.GL_LIGHTING); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, boundTexIndex); + GL11.glPopMatrix(); + GL11.glPopAttrib(); + // GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } + + @Override + public void setAlpha(float alpha) { + this.alpha = alpha; + } + ; + + @Override + public float getAlpha() { + return this.alpha; + } + ; + + @Override + public void show() { + this.isRendering = true; + } + ; + + @Override + public void hide() { + this.isRendering = false; + } + ; + + @Override + public boolean shouldRender() { + return this.isRendering; + } + ; + //////////////////// // INPUT HANDLING // //////////////////// - + @Override - public void handleMouseInput(){} + public void handleMouseInput() {} - @Override - public void onMouseClick(MouseEvent event) { - //System.out.printf("%s %s\n", this, event); - if (this.parent != null) - this.parent.onMouseClick(event); - - //IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); - //if (widget != null && widget != this) - // widget.onMouseClick(event); - } + @Override + public void onMouseClick(MouseEvent event) { + // System.out.printf("%s %s\n", this, event); + if (this.parent != null) this.parent.onMouseClick(event); - @Override - public void onMouseDrag(MouseEvent event) { - //System.out.printf("%s %s\n", this, event); - if (this.parent != null) - this.parent.onMouseDrag(event); - - //IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); - //if (widget != null && widget != this) - // widget.onMouseDrag(event); - } + // IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); + // if (widget != null && widget != this) + // widget.onMouseClick(event); + } - @Override - public void onMouseMove(MouseEvent event) { - //System.out.printf("%s %s\n", this, event); - if (this.parent != null) - this.parent.onMouseMove(event); - - - //IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); - //if (widget != null && widget != this) - // widget.onMouseMove(event); - } + @Override + public void onMouseDrag(MouseEvent event) { + // System.out.printf("%s %s\n", this, event); + if (this.parent != null) this.parent.onMouseDrag(event); - @Override - public void onMouseRelease(MouseEvent event) { - //System.out.printf("%s %s\n", this, event); - if (this.parent != null) - this.parent.onMouseRelease(event); - - //IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); - //if (widget != null && widget != this) - // widget.onMouseRelease(event); - } + // IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); + // if (widget != null && widget != this) + // widget.onMouseDrag(event); + } - @Override - public void onMouseWheel(MouseEvent event) { - //System.out.printf("%s %s\n", this, event); - if (this.parent != null) - this.parent.onMouseWheel(event); - } + @Override + public void onMouseMove(MouseEvent event) { + // System.out.printf("%s %s\n", this, event); + if (this.parent != null) this.parent.onMouseMove(event); - @Override - public void onMouseEnter(MouseEvent event) { - //System.out.printf("%s %s\n", this, event); - if (this.parent != null) - this.parent.onMouseEnter(event); - } - - @Override - public void onMouseLeave(MouseEvent event) { - //System.out.printf("%s %s\n", this, event); - if (this.parent != null) - this.parent.onMouseLeave(event); - } + // IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); + // if (widget != null && widget != this) + // widget.onMouseMove(event); + } - @Override - public void emit(Signal signal, Object... params) { - if(this.parent != null) - this.parent.onWidgetEvent(this, signal, params); - } + @Override + public void onMouseRelease(MouseEvent event) { + // System.out.printf("%s %s\n", this, event); + if (this.parent != null) this.parent.onMouseRelease(event); - @Override - public void onWidgetEvent(IWidget srcwidget, Signal signal, Object... params) { - if (this.parent != null) - this.parent.onWidgetEvent(srcwidget, signal, params); - } + // IWidget widget = this.getWidgetAtCoordinates(event.x, event.y); + // if (widget != null && widget != this) + // widget.onMouseRelease(event); + } + + @Override + public void onMouseWheel(MouseEvent event) { + // System.out.printf("%s %s\n", this, event); + if (this.parent != null) this.parent.onMouseWheel(event); + } + + @Override + public void onMouseEnter(MouseEvent event) { + // System.out.printf("%s %s\n", this, event); + if (this.parent != null) this.parent.onMouseEnter(event); + } + + @Override + public void onMouseLeave(MouseEvent event) { + // System.out.printf("%s %s\n", this, event); + if (this.parent != null) this.parent.onMouseLeave(event); + } + + @Override + public void emit(Signal signal, Object... params) { + if (this.parent != null) this.parent.onWidgetEvent(this, signal, params); + } + + @Override + public void onWidgetEvent(IWidget srcwidget, Signal signal, Object... params) { + if (this.parent != null) this.parent.onWidgetEvent(srcwidget, signal, params); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/WidgetGeometry.java b/src/main/java/mcp/mobius/opis/gui/widgets/WidgetGeometry.java index 15ec5c0..99bfe19 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/WidgetGeometry.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/WidgetGeometry.java @@ -4,183 +4,182 @@ import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.WAlign; import net.minecraft.util.MathHelper; - import org.lwjgl.util.Point; +// public class WidgetGeometry implements Cloneable{ +public class WidgetGeometry { + // public enum Align {LEFT, CENTER, RIGHT, TOP, BOTTOM}; -//public class WidgetGeometry implements Cloneable{ -public class WidgetGeometry{ - - //public enum Align {LEFT, CENTER, RIGHT, TOP, BOTTOM}; + double x = -1; + double y = -1; + double sx = -1; + double sy = -1; - - double x = -1; - double y = -1; - double sx = -1; - double sy = -1; - - CType posType; - CType sizeType; - - boolean fracPosX = false; - boolean fracPosY = false; - boolean fracSizeX = false; - boolean fracSizeY = false; - - WAlign alignX; - WAlign alignY; - - public class PointDouble{ - double x; double y; - public PointDouble(double x, double y){ this.x = x; this.y = y;}; - public double getX(){return this.x;} - public double getY(){return this.y;} - public String toString(){return String.format("PointDouble : %.5f %.5f", this.x, this.y);} - } - - public WidgetGeometry(double x, double y, double sx, double sy, CType fracPos, CType fracSize){ - this(x, y, sx, sy, fracPos, fracSize, WAlign.LEFT, WAlign.TOP); - } - - public WidgetGeometry(double x, double y, double sx, double sy, CType fracPos, CType fracSize, WAlign alignX, WAlign alignY){ - this.x = x; - this.y = y; - this.sx = sx; - this.sy = sy; - this.posType = fracPos; - this.sizeType = fracSize; - - switch(fracPos){ - case REL_X: - this.fracPosX = true; - break; - case RELXY: - this.fracPosX = true; - this.fracPosY = true; - break; - case REL_Y: - this.fracPosY = true; - break; - default: - break; - - } + CType posType; + CType sizeType; - switch(fracSize){ - case REL_X: - this.fracSizeX = true; - break; - case RELXY: - this.fracSizeX = true; - this.fracSizeY = true; - break; - case REL_Y: - this.fracSizeY = true; - break; - default: - break; - - } + boolean fracPosX = false; + boolean fracPosY = false; + boolean fracSizeX = false; + boolean fracSizeY = false; - this.alignX = alignX; - this.alignY = alignY; - } - - public void setPos(double x, double y, boolean fracX, boolean fracY){ - this.x = x; - this.y = y; - this.fracPosX = fracX; - this.fracPosY = fracY; - } - - public void setSize(double sx, double sy, boolean fracSizeX, boolean fracSizeY){ - this.sx = sx; - this.sy = sy; - this.fracSizeX = fracSizeX; - this.fracSizeY = fracSizeY; - } - - public PointDouble getRawPos(){ - return new PointDouble(this.x, this.y); - } - - public Point getUnalignedPos(IWidget parent){ - int x = -1; - if (this.fracPosX) - x = MathHelper.ceiling_double_int(parent.getPos().getX() + parent.getSize().getX() * this.x / 100D); - if (!this.fracPosX && parent != null) - x = parent.getPos().getX() + (int)this.x; - if (!this.fracPosX && parent == null) - x = (int)this.x; - - int y = -1; - if (this.fracPosY) - y = MathHelper.ceiling_double_int(parent.getPos().getY() + parent.getSize().getY() * this.y / 100D); - if (!this.fracPosY && parent != null) - y = parent.getPos().getY() + (int)this.y; - if (!this.fracPosY && parent == null) - y = (int)this.y; - - return new Point(x,y); - } - - public Point getPos(IWidget parent){ - - int x = -1; - if (this.fracPosX) - x = MathHelper.ceiling_double_int(parent.getPos().getX() + parent.getSize().getX() * this.x / 100D); - if (!this.fracPosX && parent != null) - x = parent.getPos().getX() + (int)this.x; - if (!this.fracPosX && parent == null) - x = (int)this.x; - - int y = -1; - if (this.fracPosY) - y = MathHelper.ceiling_double_int(parent.getPos().getY() + parent.getSize().getY() * this.y / 100D); - if (!this.fracPosY && parent != null) - y = parent.getPos().getY() + (int)this.y; - if (!this.fracPosY && parent == null) - y = (int)this.y; - - - if (this.alignX == WAlign.CENTER) - x -= this.getSize(parent).getX() / 2; - - if (this.alignY == WAlign.CENTER) - y -= this.getSize(parent).getY() / 2; - - if (this.alignX == WAlign.RIGHT) - x -= this.getSize(parent).getX() - 1; - - if (this.alignY == WAlign.BOTTOM) - y -= this.getSize(parent).getY() - 1; - - return new Point(x,y); - } - - public Point getSize(IWidget parent){ - int sx = -1; - if (this.fracSizeX) - sx = MathHelper.ceiling_double_int(parent.getSize().getX() * this.sx / 100D); - if (!this.fracSizeX) - sx = (int)this.sx; - - int sy = -1; - if (this.fracSizeY) - sy = MathHelper.ceiling_double_int(parent.getSize().getY() * this.sy / 100D); - if (!this.fracSizeY) - sy = (int)this.sy; - - return new Point(sx,sy); - } - - public String toString(){ - return String.format("Geometry : [%s %s] [%s %s] [%s %s] [%s %s]", this.x, this.y, this.sx, this.sy, this.posType, this.sizeType, this.alignX, this.alignY); - } - - //@Override - //public WidgetGeometry clone() throws CloneNotSupportedException{ - // return (WidgetGeometry)super.clone(); - //} + WAlign alignX; + WAlign alignY; + + public class PointDouble { + double x; + double y; + + public PointDouble(double x, double y) { + this.x = x; + this.y = y; + } + ; + + public double getX() { + return this.x; + } + + public double getY() { + return this.y; + } + + public String toString() { + return String.format("PointDouble : %.5f %.5f", this.x, this.y); + } + } + + public WidgetGeometry(double x, double y, double sx, double sy, CType fracPos, CType fracSize) { + this(x, y, sx, sy, fracPos, fracSize, WAlign.LEFT, WAlign.TOP); + } + + public WidgetGeometry( + double x, double y, double sx, double sy, CType fracPos, CType fracSize, WAlign alignX, WAlign alignY) { + this.x = x; + this.y = y; + this.sx = sx; + this.sy = sy; + this.posType = fracPos; + this.sizeType = fracSize; + + switch (fracPos) { + case REL_X: + this.fracPosX = true; + break; + case RELXY: + this.fracPosX = true; + this.fracPosY = true; + break; + case REL_Y: + this.fracPosY = true; + break; + default: + break; + } + + switch (fracSize) { + case REL_X: + this.fracSizeX = true; + break; + case RELXY: + this.fracSizeX = true; + this.fracSizeY = true; + break; + case REL_Y: + this.fracSizeY = true; + break; + default: + break; + } + + this.alignX = alignX; + this.alignY = alignY; + } + + public void setPos(double x, double y, boolean fracX, boolean fracY) { + this.x = x; + this.y = y; + this.fracPosX = fracX; + this.fracPosY = fracY; + } + + public void setSize(double sx, double sy, boolean fracSizeX, boolean fracSizeY) { + this.sx = sx; + this.sy = sy; + this.fracSizeX = fracSizeX; + this.fracSizeY = fracSizeY; + } + + public PointDouble getRawPos() { + return new PointDouble(this.x, this.y); + } + + public Point getUnalignedPos(IWidget parent) { + int x = -1; + if (this.fracPosX) + x = MathHelper.ceiling_double_int( + parent.getPos().getX() + parent.getSize().getX() * this.x / 100D); + if (!this.fracPosX && parent != null) x = parent.getPos().getX() + (int) this.x; + if (!this.fracPosX && parent == null) x = (int) this.x; + + int y = -1; + if (this.fracPosY) + y = MathHelper.ceiling_double_int( + parent.getPos().getY() + parent.getSize().getY() * this.y / 100D); + if (!this.fracPosY && parent != null) y = parent.getPos().getY() + (int) this.y; + if (!this.fracPosY && parent == null) y = (int) this.y; + + return new Point(x, y); + } + + public Point getPos(IWidget parent) { + + int x = -1; + if (this.fracPosX) + x = MathHelper.ceiling_double_int( + parent.getPos().getX() + parent.getSize().getX() * this.x / 100D); + if (!this.fracPosX && parent != null) x = parent.getPos().getX() + (int) this.x; + if (!this.fracPosX && parent == null) x = (int) this.x; + + int y = -1; + if (this.fracPosY) + y = MathHelper.ceiling_double_int( + parent.getPos().getY() + parent.getSize().getY() * this.y / 100D); + if (!this.fracPosY && parent != null) y = parent.getPos().getY() + (int) this.y; + if (!this.fracPosY && parent == null) y = (int) this.y; + + if (this.alignX == WAlign.CENTER) x -= this.getSize(parent).getX() / 2; + + if (this.alignY == WAlign.CENTER) y -= this.getSize(parent).getY() / 2; + + if (this.alignX == WAlign.RIGHT) x -= this.getSize(parent).getX() - 1; + + if (this.alignY == WAlign.BOTTOM) y -= this.getSize(parent).getY() - 1; + + return new Point(x, y); + } + + public Point getSize(IWidget parent) { + int sx = -1; + if (this.fracSizeX) sx = MathHelper.ceiling_double_int(parent.getSize().getX() * this.sx / 100D); + if (!this.fracSizeX) sx = (int) this.sx; + + int sy = -1; + if (this.fracSizeY) sy = MathHelper.ceiling_double_int(parent.getSize().getY() * this.sy / 100D); + if (!this.fracSizeY) sy = (int) this.sy; + + return new Point(sx, sy); + } + + public String toString() { + return String.format( + "Geometry : [%s %s] [%s %s] [%s %s] [%s %s]", + this.x, this.y, this.sx, this.sy, this.posType, this.sizeType, this.alignX, this.alignY); + } + + // @Override + // public WidgetGeometry clone() throws CloneNotSupportedException{ + // return (WidgetGeometry)super.clone(); + // } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonBase.java b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonBase.java index a094831..f45b9f3 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonBase.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonBase.java @@ -8,67 +8,73 @@ import mcp.mobius.opis.gui.widgets.LabelFixedFont; import mcp.mobius.opis.gui.widgets.WidgetBase; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.util.ResourceLocation; - import org.lwjgl.opengl.GL11; import org.lwjgl.util.Point; public abstract class ButtonBase extends WidgetBase { - protected boolean mouseOver = false; - protected static ResourceLocation widgetsTexture = new ResourceLocation("textures/gui/widgets.png"); - - public ButtonBase(IWidget parent){ - super(parent); - } + protected boolean mouseOver = false; + protected static ResourceLocation widgetsTexture = new ResourceLocation("textures/gui/widgets.png"); - @Override - public void draw() { + public ButtonBase(IWidget parent) { + super(parent); + } + + @Override + public void draw() { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - - for (IWidget widget : this.widgets.values()) - if (widget instanceof LabelFixedFont) - if (this.mouseOver) - ((LabelFixedFont)widget).setColor(0xffffa0); - else - ((LabelFixedFont)widget).setColor(0xffffff); - - super.draw(); - } - - @Override - public void draw(Point pos) { - this.saveGLState(); - int texOffset = 0; - if (this.mouseOver) - texOffset = 1; - - this.mc.getTextureManager().bindTexture(widgetsTexture); - UIHelper.drawTexture(this.getPos().getX(), this.getPos().getY(), this.getSize().getX(), this.getSize().getY(), 0, 66 + texOffset*20, 200, 20); - - this.loadGLState(); - } + for (IWidget widget : this.widgets.values()) + if (widget instanceof LabelFixedFont) + if (this.mouseOver) ((LabelFixedFont) widget).setColor(0xffffa0); + else ((LabelFixedFont) widget).setColor(0xffffff); - @Override - public void onMouseEnter(MouseEvent event){ - mouseOver = true; - } + super.draw(); + } - @Override - public void onMouseLeave(MouseEvent event){ - mouseOver = false; - } + @Override + public void draw(Point pos) { + this.saveGLState(); + int texOffset = 0; - @Override - public IWidget getWidgetAtCoordinates(double posX, double posY){ - return this; - } - - @Override - public void onMouseClick(MouseEvent event){ - if (event.button == 0) - this.mc.getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)); - - this.emit(Signal.CLICKED, event.button); - } + if (this.mouseOver) texOffset = 1; + + this.mc.getTextureManager().bindTexture(widgetsTexture); + UIHelper.drawTexture( + this.getPos().getX(), + this.getPos().getY(), + this.getSize().getX(), + this.getSize().getY(), + 0, + 66 + texOffset * 20, + 200, + 20); + + this.loadGLState(); + } + + @Override + public void onMouseEnter(MouseEvent event) { + mouseOver = true; + } + + @Override + public void onMouseLeave(MouseEvent event) { + mouseOver = false; + } + + @Override + public IWidget getWidgetAtCoordinates(double posX, double posY) { + return this; + } + + @Override + public void onMouseClick(MouseEvent event) { + if (event.button == 0) + this.mc + .getSoundHandler() + .playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)); + + this.emit(Signal.CLICKED, event.button); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonBoolean.java b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonBoolean.java index 0ce8754..88db2b2 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonBoolean.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonBoolean.java @@ -1,43 +1,42 @@ package mcp.mobius.opis.gui.widgets.buttons; import mcp.mobius.opis.gui.events.MouseEvent; -import mcp.mobius.opis.gui.helpers.UIHelper; import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.WAlign; import mcp.mobius.opis.gui.widgets.LabelFixedFont; import mcp.mobius.opis.gui.widgets.WidgetGeometry; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.util.Point; public class ButtonBoolean extends ButtonBase { - protected boolean state = false; - - public ButtonBoolean(IWidget parent, String textFalse, String textTrue){ - super(parent); - - this.addWidget("LabelFalse", new LabelFixedFont(this, textFalse)); - this.getWidget("LabelFalse").setGeometry(new WidgetGeometry(50.0D, 50.0D, 100.0D, 20.0D, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); - this.addWidget("LabelTrue", new LabelFixedFont(this, textTrue)); - this.getWidget("LabelTrue").hide(); - this.getWidget("LabelTrue").setGeometry(new WidgetGeometry(50.0D, 50.0D, 100.0D, 20.0D, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); - } - - @Override - public void onMouseClick(MouseEvent event){ - super.onMouseClick(event); - - if (event.button == 0) - this.state = !this.state; - - if (this.state){ - this.getWidget("LabelTrue").show(); - this.getWidget("LabelFalse").hide(); - } else { - this.getWidget("LabelTrue").hide(); - this.getWidget("LabelFalse").show(); - } - } + protected boolean state = false; + + public ButtonBoolean(IWidget parent, String textFalse, String textTrue) { + super(parent); + + this.addWidget("LabelFalse", new LabelFixedFont(this, textFalse)); + this.getWidget("LabelFalse") + .setGeometry(new WidgetGeometry( + 50.0D, 50.0D, 100.0D, 20.0D, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); + this.addWidget("LabelTrue", new LabelFixedFont(this, textTrue)); + this.getWidget("LabelTrue").hide(); + this.getWidget("LabelTrue") + .setGeometry(new WidgetGeometry( + 50.0D, 50.0D, 100.0D, 20.0D, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); + } + + @Override + public void onMouseClick(MouseEvent event) { + super.onMouseClick(event); + + if (event.button == 0) this.state = !this.state; + + if (this.state) { + this.getWidget("LabelTrue").show(); + this.getWidget("LabelFalse").hide(); + } else { + this.getWidget("LabelTrue").hide(); + this.getWidget("LabelFalse").show(); + } + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonContainer.java b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonContainer.java index 5cefdd5..520069a 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonContainer.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonContainer.java @@ -1,50 +1,59 @@ package mcp.mobius.opis.gui.widgets.buttons; -import org.lwjgl.util.Point; - import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.WAlign; -import mcp.mobius.opis.gui.widgets.LabelFixedFont; import mcp.mobius.opis.gui.widgets.LayoutBase; import mcp.mobius.opis.gui.widgets.WidgetBase; import mcp.mobius.opis.gui.widgets.WidgetGeometry; +import org.lwjgl.util.Point; public class ButtonContainer extends WidgetBase { - private int nButtons = 0; - private int columns; - private int buttonSize; - private double spacing; - - public ButtonContainer(IWidget parent, int columns, int buttonSize, double spacing){ - super (parent); - this.columns = columns; - this.spacing = spacing; - this.buttonSize = buttonSize; - } - - public void addButton(ButtonBase button){ - String buttonName = String.format("Button_%d", nButtons); - String layoutName = String.format("Layout_%d", nButtons); - String layoutLabelName = String.format("LayoutLabel_%d", nButtons); - String labelName = String.format("Label_%d", nButtons); - - this.addWidget(layoutName, new LayoutBase(this)); - this.addWidget(layoutLabelName, new LayoutBase(this)); - - int column = this.nButtons % this.columns; - int row = this.nButtons / this.columns; - double sizeColumn = 100.0 / this.columns; - - this.getWidget(layoutName).setGeometry(new WidgetGeometry(sizeColumn * column, spacing * row, sizeColumn, spacing, CType.REL_X, CType.REL_X, WAlign.LEFT, WAlign.TOP)); - this.getWidget(layoutName).addWidget(buttonName, button); - this.getWidget(layoutName).getWidget(buttonName).setGeometry(new WidgetGeometry(50.0, 50.0, buttonSize, 20.0, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); - - this.nButtons += 1; - } - - @Override - public void draw(Point pos) {} + private int nButtons = 0; + private int columns; + private int buttonSize; + private double spacing; + public ButtonContainer(IWidget parent, int columns, int buttonSize, double spacing) { + super(parent); + this.columns = columns; + this.spacing = spacing; + this.buttonSize = buttonSize; + } + + public void addButton(ButtonBase button) { + String buttonName = String.format("Button_%d", nButtons); + String layoutName = String.format("Layout_%d", nButtons); + String layoutLabelName = String.format("LayoutLabel_%d", nButtons); + String labelName = String.format("Label_%d", nButtons); + + this.addWidget(layoutName, new LayoutBase(this)); + this.addWidget(layoutLabelName, new LayoutBase(this)); + + int column = this.nButtons % this.columns; + int row = this.nButtons / this.columns; + double sizeColumn = 100.0 / this.columns; + + this.getWidget(layoutName) + .setGeometry(new WidgetGeometry( + sizeColumn * column, + spacing * row, + sizeColumn, + spacing, + CType.REL_X, + CType.REL_X, + WAlign.LEFT, + WAlign.TOP)); + this.getWidget(layoutName).addWidget(buttonName, button); + this.getWidget(layoutName) + .getWidget(buttonName) + .setGeometry(new WidgetGeometry( + 50.0, 50.0, buttonSize, 20.0, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); + + this.nButtons += 1; + } + + @Override + public void draw(Point pos) {} } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonContainerLabel.java b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonContainerLabel.java index 1abe0fd..6d7aa29 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonContainerLabel.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonContainerLabel.java @@ -7,49 +7,72 @@ import mcp.mobius.opis.gui.widgets.LabelFixedFont; import mcp.mobius.opis.gui.widgets.LayoutBase; import mcp.mobius.opis.gui.widgets.WidgetBase; import mcp.mobius.opis.gui.widgets.WidgetGeometry; - import org.lwjgl.util.Point; -//TODO : THIS CLASS IS WIP AND CAN'T WORK RIGHT NOW +// TODO : THIS CLASS IS WIP AND CAN'T WORK RIGHT NOW public class ButtonContainerLabel extends WidgetBase { - private int nButtons = 0; - private int columns; - private int buttonSize; - private double spacing; - - public ButtonContainerLabel(IWidget parent, int columns, int buttonSize, double spacing){ - super (parent); - this.columns = columns; - this.spacing = spacing; - this.buttonSize = buttonSize; - } - - public void addButton(ButtonBase button, String label){ - String buttonName = String.format("Button_%d", nButtons); - String layoutName = String.format("Layout_%d", nButtons); - String layoutLabelName = String.format("LayoutLabel_%d", nButtons); - String labelName = String.format("Label_%d", nButtons); - - this.addWidget(layoutName, new LayoutBase(this)); - this.addWidget(layoutLabelName, new LayoutBase(this)); - - int column = (this.nButtons % this.columns) * 2; - int row = this.nButtons / this.columns; - double sizeColumn = 100.0 / (this.columns * 2); - - this.getWidget(layoutName).setGeometry(new WidgetGeometry(sizeColumn * (column + 1), spacing * row, sizeColumn, spacing, CType.REL_X, CType.REL_X, WAlign.LEFT, WAlign.TOP)); - this.getWidget(layoutName).addWidget(buttonName, button); - this.getWidget(layoutName).getWidget(buttonName).setGeometry(new WidgetGeometry(50.0, 50.0, buttonSize, 20.0, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); + private int nButtons = 0; + private int columns; + private int buttonSize; + private double spacing; - this.getWidget(layoutLabelName).setGeometry(new WidgetGeometry(sizeColumn * column, spacing * row, sizeColumn, spacing, CType.REL_X, CType.REL_X, WAlign.LEFT, WAlign.TOP)); - this.getWidget(layoutLabelName).addWidget(labelName, new LabelFixedFont(this, label)); - this.getWidget(layoutLabelName).getWidget(labelName).setGeometry(new WidgetGeometry(50.0, 50.0, buttonSize, 20.0, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); - - this.nButtons += 1; - } - - @Override - public void draw(Point pos) {} + public ButtonContainerLabel(IWidget parent, int columns, int buttonSize, double spacing) { + super(parent); + this.columns = columns; + this.spacing = spacing; + this.buttonSize = buttonSize; + } + + public void addButton(ButtonBase button, String label) { + String buttonName = String.format("Button_%d", nButtons); + String layoutName = String.format("Layout_%d", nButtons); + String layoutLabelName = String.format("LayoutLabel_%d", nButtons); + String labelName = String.format("Label_%d", nButtons); + + this.addWidget(layoutName, new LayoutBase(this)); + this.addWidget(layoutLabelName, new LayoutBase(this)); + + int column = (this.nButtons % this.columns) * 2; + int row = this.nButtons / this.columns; + double sizeColumn = 100.0 / (this.columns * 2); + + this.getWidget(layoutName) + .setGeometry(new WidgetGeometry( + sizeColumn * (column + 1), + spacing * row, + sizeColumn, + spacing, + CType.REL_X, + CType.REL_X, + WAlign.LEFT, + WAlign.TOP)); + this.getWidget(layoutName).addWidget(buttonName, button); + this.getWidget(layoutName) + .getWidget(buttonName) + .setGeometry(new WidgetGeometry( + 50.0, 50.0, buttonSize, 20.0, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); + + this.getWidget(layoutLabelName) + .setGeometry(new WidgetGeometry( + sizeColumn * column, + spacing * row, + sizeColumn, + spacing, + CType.REL_X, + CType.REL_X, + WAlign.LEFT, + WAlign.TOP)); + this.getWidget(layoutLabelName).addWidget(labelName, new LabelFixedFont(this, label)); + this.getWidget(layoutLabelName) + .getWidget(labelName) + .setGeometry(new WidgetGeometry( + 50.0, 50.0, buttonSize, 20.0, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); + + this.nButtons += 1; + } + + @Override + public void draw(Point pos) {} } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonInteger.java b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonInteger.java index 7797bd6..f5b15ff 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonInteger.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonInteger.java @@ -1,49 +1,44 @@ package mcp.mobius.opis.gui.widgets.buttons; import mcp.mobius.opis.gui.events.MouseEvent; -import mcp.mobius.opis.gui.helpers.UIHelper; import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.WAlign; import mcp.mobius.opis.gui.widgets.LabelFixedFont; import mcp.mobius.opis.gui.widgets.WidgetGeometry; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.util.Point; public class ButtonInteger extends ButtonBase { - protected int state = 0; - protected int nStates; - - public ButtonInteger(IWidget parent, String... texts){ - super(parent); - - this.nStates = texts.length; - - for (int i = 0; i < texts.length; i++){ - String labelName = String.format("Label_%d", i); - this.addWidget(labelName, new LabelFixedFont(this, texts[i])); - this.getWidget(labelName).hide(); - this.getWidget(labelName).setGeometry(new WidgetGeometry(50.0D, 50.0D, 100.0D, 20.0D, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); - } - this.getWidget("Label_0").show(); - } + protected int state = 0; + protected int nStates; - @Override - public void onMouseClick(MouseEvent event){ - super.onMouseClick(event); - - if (event.button == 0) - this.state += 1; - - if (this.state >= this.nStates) - this.state = 0; - - for (int i = 0; i < this.nStates; i++) - this.getWidget(String.format("Label_%d", i)).hide(); - - this.getWidget(String.format("Label_%d", state)).show(); - } + public ButtonInteger(IWidget parent, String... texts) { + super(parent); + this.nStates = texts.length; + + for (int i = 0; i < texts.length; i++) { + String labelName = String.format("Label_%d", i); + this.addWidget(labelName, new LabelFixedFont(this, texts[i])); + this.getWidget(labelName).hide(); + this.getWidget(labelName) + .setGeometry(new WidgetGeometry( + 50.0D, 50.0D, 100.0D, 20.0D, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); + } + this.getWidget("Label_0").show(); + } + + @Override + public void onMouseClick(MouseEvent event) { + super.onMouseClick(event); + + if (event.button == 0) this.state += 1; + + if (this.state >= this.nStates) this.state = 0; + + for (int i = 0; i < this.nStates; i++) + this.getWidget(String.format("Label_%d", i)).hide(); + + this.getWidget(String.format("Label_%d", state)).show(); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonLabel.java b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonLabel.java index 917f512..653d661 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonLabel.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonLabel.java @@ -6,19 +6,20 @@ import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.WAlign; import mcp.mobius.opis.gui.widgets.LabelFixedFont; import mcp.mobius.opis.gui.widgets.WidgetGeometry; -import net.minecraft.client.gui.GuiScreen; public class ButtonLabel extends ButtonBase { - - public ButtonLabel(IWidget parent, String text){ - super(parent); - - this.addWidget("Label", new LabelFixedFont(this, text)); - this.getWidget("Label").setGeometry(new WidgetGeometry(50.0D, 50.0D, 100.0D, 20.0D, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); - } - - @Override - public void onMouseClick(MouseEvent event){ - super.onMouseClick(event); - } + + public ButtonLabel(IWidget parent, String text) { + super(parent); + + this.addWidget("Label", new LabelFixedFont(this, text)); + this.getWidget("Label") + .setGeometry(new WidgetGeometry( + 50.0D, 50.0D, 100.0D, 20.0D, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); + } + + @Override + public void onMouseClick(MouseEvent event) { + super.onMouseClick(event); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonScreenChange.java b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonScreenChange.java index 7a6b4b0..bdb82a2 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonScreenChange.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/buttons/ButtonScreenChange.java @@ -1,31 +1,31 @@ package mcp.mobius.opis.gui.widgets.buttons; -import net.minecraft.client.gui.GuiScreen; import mcp.mobius.opis.gui.events.MouseEvent; import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.WAlign; -import mcp.mobius.opis.gui.screens.ScreenBase; import mcp.mobius.opis.gui.widgets.LabelFixedFont; import mcp.mobius.opis.gui.widgets.WidgetGeometry; +import net.minecraft.client.gui.GuiScreen; public class ButtonScreenChange extends ButtonBase { - - GuiScreen linkedScreen; - - public ButtonScreenChange(IWidget parent, String text, GuiScreen linkedscreen){ - super(parent); - this.linkedScreen = linkedscreen; - - this.addWidget("Label", new LabelFixedFont(this, text)); - this.getWidget("Label").setGeometry(new WidgetGeometry(50.0D, 50.0D, 100.0D, 20.0D, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); - } - - @Override - public void onMouseClick(MouseEvent event){ - super.onMouseClick(event); - - if (event.button == 0) - this.mc.displayGuiScreen(this.linkedScreen); - } + + GuiScreen linkedScreen; + + public ButtonScreenChange(IWidget parent, String text, GuiScreen linkedscreen) { + super(parent); + this.linkedScreen = linkedscreen; + + this.addWidget("Label", new LabelFixedFont(this, text)); + this.getWidget("Label") + .setGeometry(new WidgetGeometry( + 50.0D, 50.0D, 100.0D, 20.0D, CType.RELXY, CType.ABSXY, WAlign.CENTER, WAlign.CENTER)); + } + + @Override + public void onMouseClick(MouseEvent event) { + super.onMouseClick(event); + + if (event.button == 0) this.mc.displayGuiScreen(this.linkedScreen); + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/movable/PictureMovableRC.java b/src/main/java/mcp/mobius/opis/gui/widgets/movable/PictureMovableRC.java index 93447e2..ddcfe15 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/movable/PictureMovableRC.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/movable/PictureMovableRC.java @@ -2,67 +2,63 @@ package mcp.mobius.opis.gui.widgets.movable; import mcp.mobius.opis.gui.events.MouseEvent; import mcp.mobius.opis.gui.helpers.UIHelper; -import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.Signal; -import mcp.mobius.opis.gui.interfaces.WAlign; import mcp.mobius.opis.gui.widgets.WidgetBase; -import mcp.mobius.opis.gui.widgets.WidgetGeometry; -import mcp.mobius.opis.gui.widgets.WidgetGeometry.PointDouble; import net.minecraft.util.ResourceLocation; - import org.lwjgl.opengl.GL11; import org.lwjgl.util.Point; - // A movable picture setup especially for centered relative positions. - + public class PictureMovableRC extends WidgetBase { - - private double offsetX, offsetY; - protected ResourceLocation texture; - - public PictureMovableRC(IWidget parent, String uri) { - super(parent); - this.texture = new ResourceLocation(uri); - } - - @Override - public void onMouseClick(MouseEvent event){ - this.offsetX = event.x - this.geom.getUnalignedPos(this.parent).getX(); - this.offsetY = event.y - this.geom.getUnalignedPos(this.parent).getY(); - //System.out.printf("%s %s\n", this.offsetX, this.offsetY); - } - - @Override - public void onMouseDrag(MouseEvent event){ - double newX = event.x - this.offsetX ; - double newY = event.y - this.offsetY ; - newX = Math.max(newX, this.parent.getLeft()); - newY = Math.max(newY, this.parent.getTop()); + private double offsetX, offsetY; + protected ResourceLocation texture; - newX = Math.min(newX, this.parent.getRight()); - newY = Math.min(newY, this.parent.getBottom()); + public PictureMovableRC(IWidget parent, String uri) { + super(parent); + this.texture = new ResourceLocation(uri); + } - this.setPos(((newX - this.parent.getLeft()) / this.parent.getSize().getX()) * 100.0, ((newY - this.parent.getTop())/ this.parent.getSize().getY()) * 100.0); - - //System.out.printf("%s\n", this.parent.getGeometry()); - //System.out.printf("%s %s\n", this.parent.getPos(), this.parent.getSize()); - - this.emit(Signal.DRAGGED, this.getPos()); - } - - @Override - public void draw(Point pos) { - this.saveGLState(); - - GL11.glPushMatrix(); - this.texManager.bindTexture(texture); - UIHelper.drawTexture(pos.getX(), pos.getY(), this.getSize().getX(), this.getSize().getY()); - GL11.glPopMatrix(); + @Override + public void onMouseClick(MouseEvent event) { + this.offsetX = event.x - this.geom.getUnalignedPos(this.parent).getX(); + this.offsetY = event.y - this.geom.getUnalignedPos(this.parent).getY(); + // System.out.printf("%s %s\n", this.offsetX, this.offsetY); + } - this.loadGLState(); - } + @Override + public void onMouseDrag(MouseEvent event) { + double newX = event.x - this.offsetX; + double newY = event.y - this.offsetY; + + newX = Math.max(newX, this.parent.getLeft()); + newY = Math.max(newY, this.parent.getTop()); + + newX = Math.min(newX, this.parent.getRight()); + newY = Math.min(newY, this.parent.getBottom()); + + this.setPos( + ((newX - this.parent.getLeft()) / this.parent.getSize().getX()) * 100.0, + ((newY - this.parent.getTop()) / this.parent.getSize().getY()) * 100.0); + + // System.out.printf("%s\n", this.parent.getGeometry()); + // System.out.printf("%s %s\n", this.parent.getPos(), this.parent.getSize()); + + this.emit(Signal.DRAGGED, this.getPos()); + } + + @Override + public void draw(Point pos) { + this.saveGLState(); + + GL11.glPushMatrix(); + this.texManager.bindTexture(texture); + UIHelper.drawTexture( + pos.getX(), pos.getY(), this.getSize().getX(), this.getSize().getY()); + GL11.glPopMatrix(); + + this.loadGLState(); + } } - diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/tableview/TableCell.java b/src/main/java/mcp/mobius/opis/gui/widgets/tableview/TableCell.java index 19c013d..05d3a6e 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/tableview/TableCell.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/tableview/TableCell.java @@ -1,7 +1,5 @@ package mcp.mobius.opis.gui.widgets.tableview; -import org.lwjgl.util.Point; - import mcp.mobius.opis.gui.helpers.UIException; import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; @@ -10,69 +8,71 @@ import mcp.mobius.opis.gui.widgets.LabelTTF; import mcp.mobius.opis.gui.widgets.WidgetBase; import mcp.mobius.opis.gui.widgets.WidgetGeometry; import mcp.mobius.opis.proxy.ProxyClient; +import org.lwjgl.util.Point; -class TableCell extends WidgetBase{ - float fontSize = 1.0f; - - public TableCell(IWidget parent, String text, WAlign align, float fontSize){ - super(parent); - - this.fontSize = fontSize; - - //this.addWidget("Crop", new LayoutCropping(null)).setGeometry(new WidgetGeometry(50.0, 50.0, 90.0, 100.0, CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); - - /* - switch(align){ - case CENTER: - //this.getWidget("Crop").addWidget("Text", new LabelFixedFont(null, text)) - this.addWidget("Text", new LabelScalable(null, text)) - .setGeometry(new WidgetGeometry(50.0, 50.0, 100.0, 100.0, CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); - ((LabelScalable)this.getWidget("Text")).setScale(this.fontSize); - break; - case LEFT: - //this.getWidget("Crop").addWidget("Text", new LabelFixedFont(null, text)) - this.addWidget("Text", new LabelScalable(null, text)) - .setGeometry(new WidgetGeometry(5.0, 50.0, 95.0, 100.0, CType.RELXY, CType.RELXY, WAlign.LEFT, WAlign.CENTER)); - ((LabelScalable)this.getWidget("Text")).setScale(this.fontSize); - break; - case RIGHT: - //this.getWidget("Crop").addWidget("Text", new LabelFixedFont(null, text)) - this.addWidget("Text", new LabelScalable(null, text)) - .setGeometry(new WidgetGeometry(5.0, 50.0, 95.0, 100.0, CType.RELXY, CType.RELXY, WAlign.RIGHT, WAlign.CENTER)); - ((LabelScalable)this.getWidget("Text")).setScale(this.fontSize); - break; - default: - throw new UIException(String.format("Unexpected align value : %s", align)); - } - */ +class TableCell extends WidgetBase { + float fontSize = 1.0f; - //LabelTTF label = (LabelTTF)this.addWidget("Text", new LabelTTF(null, text, ProxyClient.fontMC16)); - LabelTTF label = (LabelTTF)this.addWidget("Text", new LabelTTF(null, text, ProxyClient.fontMC8)); - switch(align){ - case CENTER: - label.setGeometry(new WidgetGeometry(50.0, 50.0, 100.0, 100.0, CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); - label.setScale(this.fontSize); - break; - case LEFT: - label.setGeometry(new WidgetGeometry(5.0, 50.0, 95.0, 100.0, CType.RELXY, CType.RELXY, WAlign.LEFT, WAlign.CENTER)); - label.setScale(this.fontSize); - break; - case RIGHT: - label.setGeometry(new WidgetGeometry(5.0, 50.0, 95.0, 100.0, CType.RELXY, CType.RELXY, WAlign.RIGHT, WAlign.CENTER)); - label.setScale(this.fontSize); - break; - default: - throw new UIException(String.format("Unexpected align value : %s", align)); - } - - } - - @Override - public void draw(Point pos){} - + public TableCell(IWidget parent, String text, WAlign align, float fontSize) { + super(parent); - public void setFontSize(float size){ - this.fontSize = size; - } - + this.fontSize = fontSize; + + // this.addWidget("Crop", new LayoutCropping(null)).setGeometry(new WidgetGeometry(50.0, 50.0, 90.0, 100.0, + // CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); + + /* + switch(align){ + case CENTER: + //this.getWidget("Crop").addWidget("Text", new LabelFixedFont(null, text)) + this.addWidget("Text", new LabelScalable(null, text)) + .setGeometry(new WidgetGeometry(50.0, 50.0, 100.0, 100.0, CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); + ((LabelScalable)this.getWidget("Text")).setScale(this.fontSize); + break; + case LEFT: + //this.getWidget("Crop").addWidget("Text", new LabelFixedFont(null, text)) + this.addWidget("Text", new LabelScalable(null, text)) + .setGeometry(new WidgetGeometry(5.0, 50.0, 95.0, 100.0, CType.RELXY, CType.RELXY, WAlign.LEFT, WAlign.CENTER)); + ((LabelScalable)this.getWidget("Text")).setScale(this.fontSize); + break; + case RIGHT: + //this.getWidget("Crop").addWidget("Text", new LabelFixedFont(null, text)) + this.addWidget("Text", new LabelScalable(null, text)) + .setGeometry(new WidgetGeometry(5.0, 50.0, 95.0, 100.0, CType.RELXY, CType.RELXY, WAlign.RIGHT, WAlign.CENTER)); + ((LabelScalable)this.getWidget("Text")).setScale(this.fontSize); + break; + default: + throw new UIException(String.format("Unexpected align value : %s", align)); + } + */ + + // LabelTTF label = (LabelTTF)this.addWidget("Text", new LabelTTF(null, text, ProxyClient.fontMC16)); + LabelTTF label = (LabelTTF) this.addWidget("Text", new LabelTTF(null, text, ProxyClient.fontMC8)); + switch (align) { + case CENTER: + label.setGeometry(new WidgetGeometry( + 50.0, 50.0, 100.0, 100.0, CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); + label.setScale(this.fontSize); + break; + case LEFT: + label.setGeometry(new WidgetGeometry( + 5.0, 50.0, 95.0, 100.0, CType.RELXY, CType.RELXY, WAlign.LEFT, WAlign.CENTER)); + label.setScale(this.fontSize); + break; + case RIGHT: + label.setGeometry(new WidgetGeometry( + 5.0, 50.0, 95.0, 100.0, CType.RELXY, CType.RELXY, WAlign.RIGHT, WAlign.CENTER)); + label.setScale(this.fontSize); + break; + default: + throw new UIException(String.format("Unexpected align value : %s", align)); + } + } + + @Override + public void draw(Point pos) {} + + public void setFontSize(float size) { + this.fontSize = size; + } } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/tableview/TableRow.java b/src/main/java/mcp/mobius/opis/gui/widgets/tableview/TableRow.java index d70f37a..c91eee8 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/tableview/TableRow.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/tableview/TableRow.java @@ -1,7 +1,5 @@ package mcp.mobius.opis.gui.widgets.tableview; -import org.lwjgl.util.Point; - import mcp.mobius.opis.gui.helpers.UIException; import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; @@ -9,101 +7,112 @@ import mcp.mobius.opis.gui.interfaces.WAlign; import mcp.mobius.opis.gui.widgets.LayoutBase; import mcp.mobius.opis.gui.widgets.WidgetBase; import mcp.mobius.opis.gui.widgets.WidgetGeometry; +import org.lwjgl.util.Point; -public class TableRow extends WidgetBase{ - int ncolumns = -1; - double[] widths; - String[] texts; - WAlign[] aligns; - float fontSize = 1.0f; - boolean init = false; - int bgcolor1 = 0xff505050; - int bgcolor2 = 0xff505050; - Object obj; - - public TableRow(IWidget parent, float fontSize){ - super(parent); +public class TableRow extends WidgetBase { + int ncolumns = -1; + double[] widths; + String[] texts; + WAlign[] aligns; + float fontSize = 1.0f; + boolean init = false; + int bgcolor1 = 0xff505050; + int bgcolor2 = 0xff505050; + Object obj; - this.fontSize = fontSize; - - this.addWidget("Background", new LayoutBase(null)).setGeometry(new WidgetGeometry(50.0, 50.0, 100.0, 100.0, CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); - ((LayoutBase)this.getWidget("Background")).setBackgroundColors(this.bgcolor1, this.bgcolor2); - - } - - public TableRow attachObject(Object obj){ - this.obj = obj; - return this; - } + public TableRow(IWidget parent, float fontSize) { + super(parent); - public Object getObject(){ - return this.obj; - } - - public void setFontSize(float size){ - this.fontSize = size; - } - - public TableRow setColumnsWidth(double... widths){ - if (this.ncolumns == -1) - this.ncolumns = widths.length; - else if(this.ncolumns != widths.length){ - throw new UIException(String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, widths.length)); - } - - this.widths = widths; - - return this; - } - - public TableRow setColumnsText(String...strings ){ - if (this.ncolumns == -1) - this.ncolumns = strings.length; - else if(this.ncolumns != strings.length){ - throw new UIException(String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, strings.length)); - } - - this.texts = strings; - - return this; - } - - public TableRow setColumnsAlign(WAlign... aligns ){ - if (this.ncolumns == -1) - this.ncolumns = aligns.length; - else if(this.ncolumns != aligns.length){ - throw new UIException(String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, aligns.length)); - } - - this.aligns = aligns; - - return this; - } - - public TableRow setColors(int bg1, int bg2){ - this.bgcolor1 = bg1; - this.bgcolor2 = bg2; - ((LayoutBase)this.getWidget("Background")).setBackgroundColors(this.bgcolor1, this.bgcolor2); - return this; - } - - @Override - public void draw(){ - if (!init) - { - double currentOffset = 0.0; - for (int i = 0; i < this.ncolumns; i++){ - if (!this.widgets.containsKey(String.format("Cell_%02d", i))){ - TableCell cell = (TableCell)(this.addWidget(String.format("Cell_%02d", i), new TableCell(null, this.texts[i], this.aligns[i], this.fontSize))); - cell.setGeometry(new WidgetGeometry(currentOffset, 50.0, this.widths[i], 100.0, CType.RELXY, CType.RELXY, WAlign.LEFT, WAlign.CENTER)); - currentOffset += this.widths[i]; - } - } - init = true; - } - super.draw(); - } - - @Override - public void draw(Point pos){} + this.fontSize = fontSize; + + this.addWidget("Background", new LayoutBase(null)) + .setGeometry(new WidgetGeometry( + 50.0, 50.0, 100.0, 100.0, CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); + ((LayoutBase) this.getWidget("Background")).setBackgroundColors(this.bgcolor1, this.bgcolor2); + } + + public TableRow attachObject(Object obj) { + this.obj = obj; + return this; + } + + public Object getObject() { + return this.obj; + } + + public void setFontSize(float size) { + this.fontSize = size; + } + + public TableRow setColumnsWidth(double... widths) { + if (this.ncolumns == -1) this.ncolumns = widths.length; + else if (this.ncolumns != widths.length) { + throw new UIException( + String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, widths.length)); + } + + this.widths = widths; + + return this; + } + + public TableRow setColumnsText(String... strings) { + if (this.ncolumns == -1) this.ncolumns = strings.length; + else if (this.ncolumns != strings.length) { + throw new UIException( + String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, strings.length)); + } + + this.texts = strings; + + return this; + } + + public TableRow setColumnsAlign(WAlign... aligns) { + if (this.ncolumns == -1) this.ncolumns = aligns.length; + else if (this.ncolumns != aligns.length) { + throw new UIException( + String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, aligns.length)); + } + + this.aligns = aligns; + + return this; + } + + public TableRow setColors(int bg1, int bg2) { + this.bgcolor1 = bg1; + this.bgcolor2 = bg2; + ((LayoutBase) this.getWidget("Background")).setBackgroundColors(this.bgcolor1, this.bgcolor2); + return this; + } + + @Override + public void draw() { + if (!init) { + double currentOffset = 0.0; + for (int i = 0; i < this.ncolumns; i++) { + if (!this.widgets.containsKey(String.format("Cell_%02d", i))) { + TableCell cell = (TableCell) (this.addWidget( + String.format("Cell_%02d", i), + new TableCell(null, this.texts[i], this.aligns[i], this.fontSize))); + cell.setGeometry(new WidgetGeometry( + currentOffset, + 50.0, + this.widths[i], + 100.0, + CType.RELXY, + CType.RELXY, + WAlign.LEFT, + WAlign.CENTER)); + currentOffset += this.widths[i]; + } + } + init = true; + } + super.draw(); + } + + @Override + public void draw(Point pos) {} } diff --git a/src/main/java/mcp/mobius/opis/gui/widgets/tableview/ViewTable.java b/src/main/java/mcp/mobius/opis/gui/widgets/tableview/ViewTable.java index 782befc..92d5a52 100644 --- a/src/main/java/mcp/mobius/opis/gui/widgets/tableview/ViewTable.java +++ b/src/main/java/mcp/mobius/opis/gui/widgets/tableview/ViewTable.java @@ -1,125 +1,124 @@ package mcp.mobius.opis.gui.widgets.tableview; -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.gui.helpers.UIException; import mcp.mobius.opis.gui.interfaces.CType; import mcp.mobius.opis.gui.interfaces.IWidget; import mcp.mobius.opis.gui.interfaces.WAlign; -import mcp.mobius.opis.gui.widgets.LabelTTF; import mcp.mobius.opis.gui.widgets.LayoutBase; import mcp.mobius.opis.gui.widgets.ViewportScrollable; import mcp.mobius.opis.gui.widgets.WidgetBase; import mcp.mobius.opis.gui.widgets.WidgetGeometry; -import mcp.mobius.opis.proxy.ProxyClient; - -import org.lwjgl.opengl.GL11; import org.lwjgl.util.Point; -public class ViewTable extends WidgetBase{ +public class ViewTable extends WidgetBase { - int ncolumns = -1; - int nrows = 0; - double[] widths; - String[] texts; - WAlign[] aligns; - float fontSize = 1.0f; - boolean init = false; - int rowColorOdd = 0x50505050; - int rowColorEven = 0x50808080; - - public ViewTable(IWidget parent){ - super(parent); - this.addWidget("Titles", new TableRow(null, this.fontSize)).setGeometry(new WidgetGeometry(0.0, 0.0, 100.0, 16.0, CType.REL_X, CType.REL_X, WAlign.LEFT, WAlign.TOP)); - ((TableRow)this.getWidget("Titles")).setColors(0x00000000, 0x00000000); - this.addWidget("Viewport", new ViewportScrollable(null)).setGeometry(new WidgetGeometry(0.0, 16.0, 100.0, 90.0, CType.REL_X, CType.RELXY, WAlign.LEFT, WAlign.TOP)); - ((ViewportScrollable)(this.getWidget("Viewport"))).attachWidget(new LayoutBase(null)).setGeometry(new WidgetGeometry(0.0, 0.0, 100.0, 0.0, CType.RELXY, CType.REL_X, WAlign.LEFT, WAlign.TOP)); - - } - - @Override - public void draw(Point pos){} - - public ViewTable setColumnsWidth(double... widths){ - if (this.ncolumns == -1) - this.ncolumns = widths.length; - else if(this.ncolumns != widths.length){ - throw new UIException(String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, widths.length)); - } - - this.widths = widths; - ((TableRow)this.getWidget("Titles")).setColumnsWidth(widths); - return this; - } - - public ViewTable setRowColors(int even, int odd){ - this.rowColorEven = even; - this.rowColorOdd = odd; - return this; - } - - public ViewTable setColumnsTitle(String...strings ){ - if (this.ncolumns == -1) - this.ncolumns = strings.length; - else if(this.ncolumns != strings.length){ - throw new UIException(String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, strings.length)); - } - - this.texts = strings; - ((TableRow)this.getWidget("Titles")).setColumnsText(strings); - - return this; - } - - public ViewTable setColumnsAlign(WAlign... aligns ){ - if (this.ncolumns == -1) - this.ncolumns = aligns.length; - else if(this.ncolumns != aligns.length){ - throw new UIException(String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, aligns.length)); - } - - this.aligns = aligns; - ((TableRow)this.getWidget("Titles")).setColumnsAlign(aligns); - - return this; - } - - public ViewTable addRow(String...strings ){ - this.addRow(null, strings); - return this; - } - - public ViewTable addRow(Object obj, String...strings){ - IWidget tableLayout = ((ViewportScrollable)(this.getWidget("Viewport"))).getAttachedWidget(); - tableLayout.setSize(100.0, (this.nrows + 1) * 16); - - TableRow newRow = (TableRow)new TableRow(null, this.fontSize); - newRow.setColumnsWidth(this.widths); - newRow.setColumnsText(strings); - newRow.setColumnsAlign(this.aligns); - if(this.nrows % 2 == 1) - newRow.setColors(this.rowColorOdd, this.rowColorOdd); - else - newRow.setColors(this.rowColorEven, this.rowColorEven); - newRow.setGeometry(new WidgetGeometry(0.0, 16*this.nrows, 100.0, 16, CType.REL_X, CType.REL_X, WAlign.LEFT, WAlign.TOP)); - newRow.attachObject(obj); - - tableLayout.addWidget(String.format("Row_%03d", this.nrows), newRow); - - this.nrows += 1; - - return this; - } - - public TableRow getRow(double x, double y){ - ViewportScrollable viewport = (ViewportScrollable)this.getWidget("Viewport"); - IWidget layout = viewport.getAttachedWidget(); - TableRow row = (TableRow)layout.getWidgetAtLayer(x, y - viewport.getOffset(), 1); + int ncolumns = -1; + int nrows = 0; + double[] widths; + String[] texts; + WAlign[] aligns; + float fontSize = 1.0f; + boolean init = false; + int rowColorOdd = 0x50505050; + int rowColorEven = 0x50808080; - return row; - } - - public void setFontSize(float size){ - this.fontSize = size; - } - + public ViewTable(IWidget parent) { + super(parent); + this.addWidget("Titles", new TableRow(null, this.fontSize)) + .setGeometry( + new WidgetGeometry(0.0, 0.0, 100.0, 16.0, CType.REL_X, CType.REL_X, WAlign.LEFT, WAlign.TOP)); + ((TableRow) this.getWidget("Titles")).setColors(0x00000000, 0x00000000); + this.addWidget("Viewport", new ViewportScrollable(null)) + .setGeometry( + new WidgetGeometry(0.0, 16.0, 100.0, 90.0, CType.REL_X, CType.RELXY, WAlign.LEFT, WAlign.TOP)); + ((ViewportScrollable) (this.getWidget("Viewport"))) + .attachWidget(new LayoutBase(null)) + .setGeometry( + new WidgetGeometry(0.0, 0.0, 100.0, 0.0, CType.RELXY, CType.REL_X, WAlign.LEFT, WAlign.TOP)); + } + + @Override + public void draw(Point pos) {} + + public ViewTable setColumnsWidth(double... widths) { + if (this.ncolumns == -1) this.ncolumns = widths.length; + else if (this.ncolumns != widths.length) { + throw new UIException( + String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, widths.length)); + } + + this.widths = widths; + ((TableRow) this.getWidget("Titles")).setColumnsWidth(widths); + return this; + } + + public ViewTable setRowColors(int even, int odd) { + this.rowColorEven = even; + this.rowColorOdd = odd; + return this; + } + + public ViewTable setColumnsTitle(String... strings) { + if (this.ncolumns == -1) this.ncolumns = strings.length; + else if (this.ncolumns != strings.length) { + throw new UIException( + String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, strings.length)); + } + + this.texts = strings; + ((TableRow) this.getWidget("Titles")).setColumnsText(strings); + + return this; + } + + public ViewTable setColumnsAlign(WAlign... aligns) { + if (this.ncolumns == -1) this.ncolumns = aligns.length; + else if (this.ncolumns != aligns.length) { + throw new UIException( + String.format("Number of columns mismatch. Expecting %d, got %d", this.ncolumns, aligns.length)); + } + + this.aligns = aligns; + ((TableRow) this.getWidget("Titles")).setColumnsAlign(aligns); + + return this; + } + + public ViewTable addRow(String... strings) { + this.addRow(null, strings); + return this; + } + + public ViewTable addRow(Object obj, String... strings) { + IWidget tableLayout = ((ViewportScrollable) (this.getWidget("Viewport"))).getAttachedWidget(); + tableLayout.setSize(100.0, (this.nrows + 1) * 16); + + TableRow newRow = (TableRow) new TableRow(null, this.fontSize); + newRow.setColumnsWidth(this.widths); + newRow.setColumnsText(strings); + newRow.setColumnsAlign(this.aligns); + if (this.nrows % 2 == 1) newRow.setColors(this.rowColorOdd, this.rowColorOdd); + else newRow.setColors(this.rowColorEven, this.rowColorEven); + newRow.setGeometry( + new WidgetGeometry(0.0, 16 * this.nrows, 100.0, 16, CType.REL_X, CType.REL_X, WAlign.LEFT, WAlign.TOP)); + newRow.attachObject(obj); + + tableLayout.addWidget(String.format("Row_%03d", this.nrows), newRow); + + this.nrows += 1; + + return this; + } + + public TableRow getRow(double x, double y) { + ViewportScrollable viewport = (ViewportScrollable) this.getWidget("Viewport"); + IWidget layout = viewport.getAttachedWidget(); + TableRow row = (TableRow) layout.getWidgetAtLayer(x, y - viewport.getOffset(), 1); + + return row; + } + + public void setFontSize(float size) { + this.fontSize = size; + } } diff --git a/src/main/java/mcp/mobius/opis/helpers/Helpers.java b/src/main/java/mcp/mobius/opis/helpers/Helpers.java index d86fb87..a10ae0e 100644 --- a/src/main/java/mcp/mobius/opis/helpers/Helpers.java +++ b/src/main/java/mcp/mobius/opis/helpers/Helpers.java @@ -3,23 +3,24 @@ package mcp.mobius.opis.helpers; import cpw.mods.fml.relauncher.Side; public class Helpers { - public static Side getEffectiveSide(){ + public static Side getEffectiveSide() { Thread thr = Thread.currentThread(); - - if ((thr.getName().equals("Server thread")) || (thr.getName().contains("Netty IO")) || (thr.getName().startsWith("nioEventLoopGroup"))) - { + + if ((thr.getName().equals("Server thread")) + || (thr.getName().contains("Netty IO")) + || (thr.getName().startsWith("nioEventLoopGroup"))) { return Side.SERVER; } - return Side.CLIENT; - + return Side.CLIENT; + /* if ((thr instanceof ThreadMinecraftServer) || (thr instanceof ServerListenThread) || (thr instanceof TcpWriterThread) || (thr instanceof TcpReaderThread)) { return Side.SERVER; } - + return Side.CLIENT; - */ - } + */ + } } diff --git a/src/main/java/mcp/mobius/opis/helpers/ModIdentification.java b/src/main/java/mcp/mobius/opis/helpers/ModIdentification.java index 4157f57..8349deb 100644 --- a/src/main/java/mcp/mobius/opis/helpers/ModIdentification.java +++ b/src/main/java/mcp/mobius/opis/helpers/ModIdentification.java @@ -1,108 +1,110 @@ package mcp.mobius.opis.helpers; +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.ModContainer; +import cpw.mods.fml.common.registry.*; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.HashMap; - -import cpw.mods.fml.common.registry.*; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; -import cpw.mods.fml.common.Loader; -import cpw.mods.fml.common.ModContainer; public class ModIdentification { - - public static HashMap modSource_Name = new HashMap(); - public static HashMap modSource_ID = new HashMap(); - public static HashMap itemMap = new HashMap(); - public static HashMap keyhandlerStrings = new HashMap(); - - public static void init(){ - - for (ModContainer mod : Loader.instance().getModList()){ - modSource_Name.put(mod.getSource().getName(), mod.getName()); - modSource_ID.put(mod.getSource().getName(), mod.getModId()); + + public static HashMap modSource_Name = new HashMap(); + public static HashMap modSource_ID = new HashMap(); + public static HashMap itemMap = new HashMap(); + public static HashMap keyhandlerStrings = new HashMap(); + + public static void init() { + + for (ModContainer mod : Loader.instance().getModList()) { + modSource_Name.put(mod.getSource().getName(), mod.getName()); + modSource_ID.put(mod.getSource().getName(), mod.getModId()); } - //TODO : Update this to match new version (1.7.2) + // TODO : Update this to match new version (1.7.2) modSource_Name.put("1.6.2.jar", "Minecraft"); - modSource_Name.put("1.6.3.jar", "Minecraft"); + modSource_Name.put("1.6.3.jar", "Minecraft"); modSource_Name.put("1.6.4.jar", "Minecraft"); modSource_Name.put("1.7.2.jar", "Minecraft"); - modSource_Name.put("Forge", "Minecraft"); + modSource_Name.put("Forge", "Minecraft"); modSource_ID.put("1.6.2.jar", "Minecraft"); - modSource_ID.put("1.6.3.jar", "Minecraft"); + modSource_ID.put("1.6.3.jar", "Minecraft"); modSource_ID.put("1.6.4.jar", "Minecraft"); modSource_ID.put("1.7.2.jar", "Minecraft"); - modSource_ID.put("Forge", "Minecraft"); - } - - public static String nameFromObject(Object obj){ - String objPath = obj.getClass().getProtectionDomain().getCodeSource().getLocation().toString(); - - try { - objPath = URLDecoder.decode(objPath, "UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - - String modName = ""; - for (String s: modSource_Name.keySet()) - if (objPath.contains(s)){ - modName = modSource_Name.get(s); - break; - } - - if (modName.equals("Minecraft Coder Pack")) - modName = "Minecraft"; - - return modName; - } - - public static String nameFromStack(ItemStack stack){ - try{ - String name = GameData.getItemRegistry().getNameForObject(stack.getItem()); - GameRegistry.UniqueIdentifier ui = new GameRegistry.UniqueIdentifier(name); - ModContainer mod = Loader.instance().getIndexedModList().get(ui.modId); - String modname = mod == null ? "Minecraft" : mod.getName(); - return modname; - } catch (NullPointerException e){ - //System.out.printf("NPE : %s\n",itemstack.toString()); - return ""; - } - } - - public static String getStackName(int id, int meta){ - return getStackName(Block.getBlockById(id), meta); + modSource_ID.put("Forge", "Minecraft"); + } + + public static String nameFromObject(Object obj) { + String objPath = obj.getClass() + .getProtectionDomain() + .getCodeSource() + .getLocation() + .toString(); + + try { + objPath = URLDecoder.decode(objPath, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + + String modName = ""; + for (String s : modSource_Name.keySet()) + if (objPath.contains(s)) { + modName = modSource_Name.get(s); + break; + } + + if (modName.equals("Minecraft Coder Pack")) modName = "Minecraft"; + + return modName; + } + + public static String nameFromStack(ItemStack stack) { + try { + String name = GameData.getItemRegistry().getNameForObject(stack.getItem()); + GameRegistry.UniqueIdentifier ui = new GameRegistry.UniqueIdentifier(name); + ModContainer mod = Loader.instance().getIndexedModList().get(ui.modId); + String modname = mod == null ? "Minecraft" : mod.getName(); + return modname; + } catch (NullPointerException e) { + // System.out.printf("NPE : %s\n",itemstack.toString()); + return ""; + } + } + + public static String getStackName(int id, int meta) { + return getStackName(Block.getBlockById(id), meta); + } + + public static String getStackName(Block block, int meta) { + ItemStack is; + String name = String.format("te.%s.%d", block, meta); + + try { + is = new ItemStack(block, 1, meta); + name = is.getDisplayName(); + } catch (Exception e) { + } + + return name; + } + + public static String getModStackName(int id, int meta) { + return getModStackName(Block.getBlockById(id), meta); + } + + public static String getModStackName(Block block, int meta) { + ItemStack is; + String modID = ""; + + try { + is = new ItemStack(block, 1, meta); + modID = nameFromStack(is); + } catch (Exception e) { + } + + return modID; } - - public static String getStackName(Block block, int meta){ - ItemStack is; - String name = String.format("te.%s.%d", block, meta); - - try{ - is = new ItemStack(block, 1, meta); - name = is.getDisplayName(); - } catch (Exception e) { } - - return name; - } - - public static String getModStackName(int id, int meta){ - return getModStackName(Block.getBlockById(id), meta); - } - - public static String getModStackName(Block block, int meta){ - ItemStack is; - String modID = ""; - - try{ - is = new ItemStack(block, 1, meta); - modID = nameFromStack(is); - } catch (Exception e) { } - - return modID; - } - - } diff --git a/src/main/java/mcp/mobius/opis/helpers/NBTUtil.java b/src/main/java/mcp/mobius/opis/helpers/NBTUtil.java index 8c3ebbd..3efe3b2 100644 --- a/src/main/java/mcp/mobius/opis/helpers/NBTUtil.java +++ b/src/main/java/mcp/mobius/opis/helpers/NBTUtil.java @@ -3,7 +3,6 @@ package mcp.mobius.opis.helpers; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; - import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTSizeTracker; @@ -14,103 +13,89 @@ import net.minecraft.nbt.NBTTagShort; public class NBTUtil { - public static NBTBase getTag(String key, NBTTagCompound tag){ - String[] path = key.split("\\."); - - NBTTagCompound deepTag = tag; - for (String i : path){ - if (deepTag.hasKey(i)){ - if (deepTag.getTag(i) instanceof NBTTagCompound) - deepTag = deepTag.getCompoundTag(i); - else{ - return deepTag.getTag(i); - } - } else { - return null; - } - } - return deepTag; - } - - /* - public static NBTTagCompound setTag(String key, NBTTagCompound targetTag, NBTBase addedTag){ - String[] path = key.split("\\."); - - NBTTagCompound deepTag = targetTag; - for (int i = 0; i < path.length - 1; i++){ - if (!deepTag.hasKey(path[i])) - deepTag.setCompoundTag(path[i], new NBTTagCompound()); - - deepTag = deepTag.getCompoundTag(path[i]); - } - - deepTag.setTag(path[path.length - 1], addedTag); - - return targetTag; - } - - public static NBTTagCompound createTag(NBTTagCompound inTag, HashSet keys){ - if (keys.contains("*")) return inTag; - - NBTTagCompound outTag = new NBTTagCompound(); - - for (String key : keys){ - NBTBase tagToAdd = getTag(key, inTag); - //System.out.printf("%s\n", tagToAdd); - if (tagToAdd != null) - outTag = setTag(key, outTag, tagToAdd); - } - - return outTag; - } - */ - - public static void writeNBTTagCompound(NBTTagCompound par0NBTTagCompound, DataOutputStream ostream) throws IOException - { - if (par0NBTTagCompound == null) - { - ostream.writeShort(-1); - } - else - { - byte[] abyte = CompressedStreamTools.compress(par0NBTTagCompound); - - if (abyte.length > 32000) - ostream.writeShort(-1); - else{ - ostream.writeShort((short)abyte.length); - ostream.write(abyte); + public static NBTBase getTag(String key, NBTTagCompound tag) { + String[] path = key.split("\\."); + + NBTTagCompound deepTag = tag; + for (String i : path) { + if (deepTag.hasKey(i)) { + if (deepTag.getTag(i) instanceof NBTTagCompound) deepTag = deepTag.getCompoundTag(i); + else { + return deepTag.getTag(i); + } + } else { + return null; } } - } + return deepTag; + } - public static NBTTagCompound readNBTTagCompound(DataInputStream istream) throws IOException - { + /* + public static NBTTagCompound setTag(String key, NBTTagCompound targetTag, NBTBase addedTag){ + String[] path = key.split("\\."); + + NBTTagCompound deepTag = targetTag; + for (int i = 0; i < path.length - 1; i++){ + if (!deepTag.hasKey(path[i])) + deepTag.setCompoundTag(path[i], new NBTTagCompound()); + + deepTag = deepTag.getCompoundTag(path[i]); + } + + deepTag.setTag(path[path.length - 1], addedTag); + + return targetTag; + } + + public static NBTTagCompound createTag(NBTTagCompound inTag, HashSet keys){ + if (keys.contains("*")) return inTag; + + NBTTagCompound outTag = new NBTTagCompound(); + + for (String key : keys){ + NBTBase tagToAdd = getTag(key, inTag); + //System.out.printf("%s\n", tagToAdd); + if (tagToAdd != null) + outTag = setTag(key, outTag, tagToAdd); + } + + return outTag; + } + */ + + public static void writeNBTTagCompound(NBTTagCompound par0NBTTagCompound, DataOutputStream ostream) + throws IOException { + if (par0NBTTagCompound == null) { + ostream.writeShort(-1); + } else { + byte[] abyte = CompressedStreamTools.compress(par0NBTTagCompound); + + if (abyte.length > 32000) ostream.writeShort(-1); + else { + ostream.writeShort((short) abyte.length); + ostream.write(abyte); + } + } + } + + public static NBTTagCompound readNBTTagCompound(DataInputStream istream) throws IOException { short short1 = istream.readShort(); - if (short1 < 0) - { + if (short1 < 0) { return null; - } - else - { + } else { byte[] abyte = new byte[short1]; istream.readFully(abyte); return CompressedStreamTools.func_152457_a(abyte, NBTSizeTracker.field_152451_a); } - } - - public static int getNBTInteger(NBTTagCompound tag, String keyname){ - NBTBase subtag = tag.getTag(keyname); - if (subtag instanceof NBTTagInt) - return tag.getInteger(keyname); - if (subtag instanceof NBTTagShort) - return tag.getShort(keyname); - if (subtag instanceof NBTTagByte) - return tag.getByte(keyname); + } - return 0; - } - + public static int getNBTInteger(NBTTagCompound tag, String keyname) { + NBTBase subtag = tag.getTag(keyname); + if (subtag instanceof NBTTagInt) return tag.getInteger(keyname); + if (subtag instanceof NBTTagShort) return tag.getShort(keyname); + if (subtag instanceof NBTTagByte) return tag.getByte(keyname); + + return 0; + } } - diff --git a/src/main/java/mcp/mobius/opis/helpers/Teleport.java b/src/main/java/mcp/mobius/opis/helpers/Teleport.java index 7101ee6..42cb02f 100644 --- a/src/main/java/mcp/mobius/opis/helpers/Teleport.java +++ b/src/main/java/mcp/mobius/opis/helpers/Teleport.java @@ -1,8 +1,7 @@ package mcp.mobius.opis.helpers; -import java.util.Iterator; - import cpw.mods.fml.common.FMLCommonHandler; +import java.util.Iterator; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; @@ -21,71 +20,76 @@ import net.minecraftforge.common.DimensionManager; public class Teleport { - private static Teleport _instance = new Teleport(); - public static Teleport instance(){return _instance;}; - - // Originally in EntityPlayerMP - public boolean movePlayerToDimension(EntityPlayerMP player, int dim) - { - return this.transferPlayerToDimension(player.mcServer.getConfigurationManager(), player, dim); - } - + private static Teleport _instance = new Teleport(); + + public static Teleport instance() { + return _instance; + } + ; + + // Originally in EntityPlayerMP + public boolean movePlayerToDimension(EntityPlayerMP player, int dim) { + return this.transferPlayerToDimension(player.mcServer.getConfigurationManager(), player, dim); + } + // Originally in ServerConfigurationManager - public boolean transferPlayerToDimension(ServerConfigurationManager manager, EntityPlayerMP player, int targetID) - { + public boolean transferPlayerToDimension(ServerConfigurationManager manager, EntityPlayerMP player, int targetID) { int sourceID = player.dimension; WorldServer sourceWorld = DimensionManager.getWorld(player.dimension); WorldServer targetWorld = DimensionManager.getWorld(targetID); - + if (sourceID == targetID) return true; if (sourceWorld == null || targetWorld == null) return false; - player.dimension = targetID; - - //player.playerNetServerHandler.sendPacket(new Packet9Respawn(player.dimension, (byte)player.worldObj.difficultySetting, targetWorld.getWorldInfo().getTerrainType(), targetWorld.getHeight(), player.theItemInWorldManager.getGameType())); - player.playerNetServerHandler.sendPacket(new S07PacketRespawn(player.dimension, player.worldObj.difficultySetting, player.worldObj.getWorldInfo().getTerrainType(), player.theItemInWorldManager.getGameType())); + player.dimension = targetID; + + // player.playerNetServerHandler.sendPacket(new Packet9Respawn(player.dimension, + // (byte)player.worldObj.difficultySetting, targetWorld.getWorldInfo().getTerrainType(), + // targetWorld.getHeight(), player.theItemInWorldManager.getGameType())); + player.playerNetServerHandler.sendPacket(new S07PacketRespawn( + player.dimension, + player.worldObj.difficultySetting, + player.worldObj.getWorldInfo().getTerrainType(), + player.theItemInWorldManager.getGameType())); sourceWorld.removePlayerEntityDangerously(player); player.isDead = false; this.transferEntityToWorld(player, sourceID, sourceWorld, targetWorld); this.preloadChunk(player, sourceWorld); - - player.playerNetServerHandler.setPlayerLocation(player.posX, player.posY, player.posZ, player.rotationYaw, player.rotationPitch); + + player.playerNetServerHandler.setPlayerLocation( + player.posX, player.posY, player.posZ, player.rotationYaw, player.rotationPitch); player.theItemInWorldManager.setWorld(targetWorld); - + manager.updateTimeAndWeatherForPlayer(player, targetWorld); manager.syncPlayerInventory(player); Iterator iterator = player.getActivePotionEffects().iterator(); - while (iterator.hasNext()) - { - PotionEffect potioneffect = (PotionEffect)iterator.next(); - //player.playerNetServerHandler.sendPacket(new Packet41EntityEffect(player.entityId, potioneffect)); + while (iterator.hasNext()) { + PotionEffect potioneffect = (PotionEffect) iterator.next(); + // player.playerNetServerHandler.sendPacket(new Packet41EntityEffect(player.entityId, potioneffect)); player.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(player.getEntityId(), potioneffect)); } - //GameRegistry.onPlayerChangedDimension(player); - FMLCommonHandler.instance().firePlayerChangedDimensionEvent(player, sourceID, targetID); + // GameRegistry.onPlayerChangedDimension(player); + FMLCommonHandler.instance().firePlayerChangedDimensionEvent(player, sourceID, targetID); return true; - } - - // Originally in ServerConfigurationManager - public void preloadChunk(EntityPlayerMP player, WorldServer sourceWorld) - { + } + + // Originally in ServerConfigurationManager + public void preloadChunk(EntityPlayerMP player, WorldServer sourceWorld) { WorldServer otherWorld = player.getServerForPlayer(); - if (sourceWorld != null) - { + if (sourceWorld != null) { sourceWorld.getPlayerManager().removePlayer(player); } otherWorld.getPlayerManager().addPlayer(player); - otherWorld.theChunkProviderServer.loadChunk((int)player.posX >> 4, (int)player.posZ >> 4); - } + otherWorld.theChunkProviderServer.loadChunk((int) player.posX >> 4, (int) player.posZ >> 4); + } - public void transferEntityToWorld(Entity ent, int dim, WorldServer srcWorld, WorldServer trgWorld) - { + public void transferEntityToWorld(Entity ent, int dim, WorldServer srcWorld, WorldServer trgWorld) { WorldProvider pOld = srcWorld.provider; WorldProvider pNew = trgWorld.provider; double moveFactor = pOld.getMovementFactor() / pNew.getMovementFactor(); @@ -97,40 +101,36 @@ public class Teleport { float f = ent.rotationYaw; srcWorld.theProfiler.startSection("placing"); - d0 = MathHelper.clamp_int((int)d0, -29999872, 29999872); - d1 = MathHelper.clamp_int((int)d1, -29999872, 29999872); + d0 = MathHelper.clamp_int((int) d0, -29999872, 29999872); + d1 = MathHelper.clamp_int((int) d1, -29999872, 29999872); - if (ent.isEntityAlive()) - { + if (ent.isEntityAlive()) { trgWorld.spawnEntityInWorld(ent); ent.setLocationAndAngles(d0, ent.posY, d1, ent.rotationYaw, ent.rotationPitch); trgWorld.updateEntityWithOptionalForce(ent, false); } ent.setWorld(trgWorld); - } - - public boolean moveEntityToDimension(Entity target, int targetID) - { - if (!target.worldObj.isRemote && !target.isDead) - { + } + + public boolean moveEntityToDimension(Entity target, int targetID) { + if (!target.worldObj.isRemote && !target.isDead) { MinecraftServer server = MinecraftServer.getServer(); int sourceID = target.dimension; WorldServer sourceWorld = DimensionManager.getWorld(sourceID); WorldServer targetWorld = DimensionManager.getWorld(targetID); if (sourceID == targetID) return true; - if (sourceWorld == null || targetWorld == null) return false; - + if (sourceWorld == null || targetWorld == null) return false; + target.dimension = targetID; - + target.worldObj.removeEntity(target); target.isDead = false; this.transferEntityToWorld(target, sourceID, sourceWorld, targetWorld); Entity entity = EntityList.createEntityByName(EntityList.getEntityString(target), targetWorld); - if (entity != null) - { + if (entity != null) { entity.copyDataFrom(target, true); targetWorld.spawnEntityInWorld(entity); } @@ -139,100 +139,102 @@ public class Teleport { sourceWorld.resetUpdateEntityTick(); targetWorld.resetUpdateEntityTick(); } - + return true; - } - - public CoordinatesBlock getTeleportTarget(CoordinatesBlock coord){ - World world = DimensionManager.getWorld(coord.dim); - if (world == null) {return null;} - - int maxOffset = 16; - boolean targetFound = false; - - if (coord.y > 0){ - for (int xoffset = 0; xoffset <= maxOffset; xoffset++){ - for (int zoffset = 0; zoffset <= maxOffset; zoffset++){ - if ( world.isAirBlock(coord.x + xoffset, coord.y, coord.z + zoffset) && - world.isAirBlock(coord.x + xoffset, coord.y + 1, coord.z + zoffset) && - !world.isAirBlock(coord.x + xoffset, coord.y - 1, coord.z + zoffset)) - return new CoordinatesBlock(coord.dim, coord.x + xoffset, coord.y, coord.z + zoffset); - - if (world.isAirBlock(coord.x - xoffset, coord.y, coord.z + zoffset) && - world.isAirBlock(coord.x - xoffset, coord.y + 1, coord.z + zoffset) && - !world.isAirBlock(coord.x - xoffset, coord.y - 1, coord.z + zoffset)) - return new CoordinatesBlock(coord.dim, coord.x - xoffset, coord.y, coord.z + zoffset); - - if (world.isAirBlock(coord.x + xoffset, coord.y, coord.z - zoffset) && - world.isAirBlock(coord.x + xoffset, coord.y + 1, coord.z - zoffset) && - !world.isAirBlock(coord.x + xoffset, coord.y - 1, coord.z - zoffset)) - return new CoordinatesBlock(coord.dim, coord.x + xoffset, coord.y, coord.z - zoffset); - - if (world.isAirBlock(coord.x - xoffset, coord.y, coord.z - zoffset) && - world.isAirBlock(coord.x - xoffset, coord.y + 1, coord.z - zoffset) && - !world.isAirBlock(coord.x - xoffset, coord.y - 1, coord.z - zoffset)) - return new CoordinatesBlock(coord.dim, coord.x - xoffset, coord.y, coord.z - zoffset); - } - } - } else { - int y = 256; - while (world.isAirBlock(coord.x, y, coord.z) || - world.getBlock(coord.x, y, coord.z) == Blocks.vine - ) - y--; - - for (int xoffset = 0; xoffset <= maxOffset; xoffset++){ - for (int zoffset = 0; zoffset <= maxOffset; zoffset++){ - if (world.isAirBlock(coord.x + xoffset, y, coord.z + zoffset) && world.isAirBlock(coord.x + xoffset, y + 1, coord.z + zoffset)) - return new CoordinatesBlock(coord.dim, coord.x + xoffset, y, coord.z + zoffset); - - if (world.isAirBlock(coord.x - xoffset, y, coord.z + zoffset) && world.isAirBlock(coord.x - xoffset, y + 1, coord.z + zoffset)) - return new CoordinatesBlock(coord.dim, coord.x - xoffset, y, coord.z + zoffset); - - if (world.isAirBlock(coord.x + xoffset, y, coord.z - zoffset) && world.isAirBlock(coord.x + xoffset, y + 1, coord.z - zoffset)) - return new CoordinatesBlock(coord.dim, coord.x + xoffset, y, coord.z - zoffset); - - if (world.isAirBlock(coord.x - xoffset, y, coord.z - zoffset) && world.isAirBlock(coord.x - xoffset, y + 1, coord.z - zoffset)) - return new CoordinatesBlock(coord.dim, coord.x - xoffset, y, coord.z - zoffset); - } - } - } - - return null; - } - - public CoordinatesBlock fixNetherTP(CoordinatesBlock target){ - World targetWorld = DimensionManager.getWorld(target.dim); - boolean isBedrock = targetWorld.getBlock(target.x, target.y - 1, target.z) == Blocks.bedrock; - boolean canTeleport = false; - CoordinatesBlock finalTarget; - - // Fix for the nether and all cavern worlds. - if ((target.y > 64) && isBedrock){ - int tempY = target.y - 1; - while (tempY > 1){ - if (targetWorld.isAirBlock(target.x, tempY, target.z) && targetWorld.isAirBlock(target.x, tempY - 1, target.z)){ - canTeleport = true; - - while (targetWorld.isAirBlock(target.x, tempY, target.z)){tempY -= 1;} - - break; - } - tempY -= 1; - } - - finalTarget = new CoordinatesBlock(target.dim, target.x, tempY + 1, target.z); - - - } else { - canTeleport = true; - finalTarget = target; - } - - if (canTeleport) - return finalTarget; - else - return null; - } - + } + + public CoordinatesBlock getTeleportTarget(CoordinatesBlock coord) { + World world = DimensionManager.getWorld(coord.dim); + if (world == null) { + return null; + } + + int maxOffset = 16; + boolean targetFound = false; + + if (coord.y > 0) { + for (int xoffset = 0; xoffset <= maxOffset; xoffset++) { + for (int zoffset = 0; zoffset <= maxOffset; zoffset++) { + if (world.isAirBlock(coord.x + xoffset, coord.y, coord.z + zoffset) + && world.isAirBlock(coord.x + xoffset, coord.y + 1, coord.z + zoffset) + && !world.isAirBlock(coord.x + xoffset, coord.y - 1, coord.z + zoffset)) + return new CoordinatesBlock(coord.dim, coord.x + xoffset, coord.y, coord.z + zoffset); + + if (world.isAirBlock(coord.x - xoffset, coord.y, coord.z + zoffset) + && world.isAirBlock(coord.x - xoffset, coord.y + 1, coord.z + zoffset) + && !world.isAirBlock(coord.x - xoffset, coord.y - 1, coord.z + zoffset)) + return new CoordinatesBlock(coord.dim, coord.x - xoffset, coord.y, coord.z + zoffset); + + if (world.isAirBlock(coord.x + xoffset, coord.y, coord.z - zoffset) + && world.isAirBlock(coord.x + xoffset, coord.y + 1, coord.z - zoffset) + && !world.isAirBlock(coord.x + xoffset, coord.y - 1, coord.z - zoffset)) + return new CoordinatesBlock(coord.dim, coord.x + xoffset, coord.y, coord.z - zoffset); + + if (world.isAirBlock(coord.x - xoffset, coord.y, coord.z - zoffset) + && world.isAirBlock(coord.x - xoffset, coord.y + 1, coord.z - zoffset) + && !world.isAirBlock(coord.x - xoffset, coord.y - 1, coord.z - zoffset)) + return new CoordinatesBlock(coord.dim, coord.x - xoffset, coord.y, coord.z - zoffset); + } + } + } else { + int y = 256; + while (world.isAirBlock(coord.x, y, coord.z) || world.getBlock(coord.x, y, coord.z) == Blocks.vine) y--; + + for (int xoffset = 0; xoffset <= maxOffset; xoffset++) { + for (int zoffset = 0; zoffset <= maxOffset; zoffset++) { + if (world.isAirBlock(coord.x + xoffset, y, coord.z + zoffset) + && world.isAirBlock(coord.x + xoffset, y + 1, coord.z + zoffset)) + return new CoordinatesBlock(coord.dim, coord.x + xoffset, y, coord.z + zoffset); + + if (world.isAirBlock(coord.x - xoffset, y, coord.z + zoffset) + && world.isAirBlock(coord.x - xoffset, y + 1, coord.z + zoffset)) + return new CoordinatesBlock(coord.dim, coord.x - xoffset, y, coord.z + zoffset); + + if (world.isAirBlock(coord.x + xoffset, y, coord.z - zoffset) + && world.isAirBlock(coord.x + xoffset, y + 1, coord.z - zoffset)) + return new CoordinatesBlock(coord.dim, coord.x + xoffset, y, coord.z - zoffset); + + if (world.isAirBlock(coord.x - xoffset, y, coord.z - zoffset) + && world.isAirBlock(coord.x - xoffset, y + 1, coord.z - zoffset)) + return new CoordinatesBlock(coord.dim, coord.x - xoffset, y, coord.z - zoffset); + } + } + } + + return null; + } + + public CoordinatesBlock fixNetherTP(CoordinatesBlock target) { + World targetWorld = DimensionManager.getWorld(target.dim); + boolean isBedrock = targetWorld.getBlock(target.x, target.y - 1, target.z) == Blocks.bedrock; + boolean canTeleport = false; + CoordinatesBlock finalTarget; + + // Fix for the nether and all cavern worlds. + if ((target.y > 64) && isBedrock) { + int tempY = target.y - 1; + while (tempY > 1) { + if (targetWorld.isAirBlock(target.x, tempY, target.z) + && targetWorld.isAirBlock(target.x, tempY - 1, target.z)) { + canTeleport = true; + + while (targetWorld.isAirBlock(target.x, tempY, target.z)) { + tempY -= 1; + } + + break; + } + tempY -= 1; + } + + finalTarget = new CoordinatesBlock(target.dim, target.x, tempY + 1, target.z); + + } else { + canTeleport = true; + finalTarget = target; + } + + if (canTeleport) return finalTarget; + else return null; + } } diff --git a/src/main/java/mcp/mobius/opis/modOpis.java b/src/main/java/mcp/mobius/opis/modOpis.java index fd96ce6..3d1ffe8 100644 --- a/src/main/java/mcp/mobius/opis/modOpis.java +++ b/src/main/java/mcp/mobius/opis/modOpis.java @@ -32,8 +32,11 @@ import net.minecraftforge.common.config.Configuration; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -@Mod(modid="GRADLETOKEN_MODID", name="GRADLETOKEN_MODNAME", version="GRADLETOKEN_VERSION", acceptableRemoteVersions="*") - +@Mod( + modid = "GRADLETOKEN_MODID", + name = "GRADLETOKEN_MODNAME", + version = "GRADLETOKEN_VERSION", + acceptableRemoteVersions = "*") public class modOpis { @Instance("Opis") @@ -41,25 +44,27 @@ public class modOpis { public static Logger log = LogManager.getLogger("Opis"); - @SidedProxy(clientSide="mcp.mobius.opis.proxy.ProxyClient", serverSide="mcp.mobius.opis.proxy.ProxyServer") + @SidedProxy(clientSide = "mcp.mobius.opis.proxy.ProxyClient", serverSide = "mcp.mobius.opis.proxy.ProxyServer") public static ProxyServer proxy; - public static int profilerDelay = 1; - public static boolean profilerRun = false; - public static boolean profilerRunClient = false; - public static int profilerMaxTicks = 250; - public static int rconport = 25566; - public static boolean rconactive = false; - public static String rconpass = ""; - public static boolean microseconds = true; - private static int lagGenID = -1; + public static int profilerDelay = 1; + public static boolean profilerRun = false; + public static boolean profilerRunClient = false; + public static int profilerMaxTicks = 250; + public static int rconport = 25566; + public static boolean rconactive = false; + public static String rconpass = ""; + public static boolean microseconds = true; + private static int lagGenID = -1; public static CoordinatesBlock selectedBlock = null; public static boolean swingOpen = false; - public Configuration config = null; + public Configuration config = null; - public static String commentTables = "Minimum access level to be able to view tables in /opis command. Valid values : NONE, PRIVILEGED, ADMIN"; - public static String commentOpis = "Minimum access level to be open Opis interface. Valid values : NONE, PRIVILEGED, ADMIN"; + public static String commentTables = + "Minimum access level to be able to view tables in /opis command. Valid values : NONE, PRIVILEGED, ADMIN"; + public static String commentOpis = + "Minimum access level to be open Opis interface. Valid values : NONE, PRIVILEGED, ADMIN"; public static String commentPrivileged = "List of players with PRIVILEGED access level."; @EventHandler @@ -67,25 +72,37 @@ public class modOpis { config = new Configuration(event.getSuggestedConfigurationFile()); - profilerDelay = config.get(Configuration.CATEGORY_GENERAL, "profiler.delay", 1).getInt(); - lagGenID = config.get(Configuration.CATEGORY_GENERAL, "laggenerator_id", -1).getInt(); - profilerMaxTicks = config.get(Configuration.CATEGORY_GENERAL, "profiler.maxpts", 250).getInt(); - microseconds = config.get(Configuration.CATEGORY_GENERAL, "display.microseconds", true).getBoolean(true); - rconport = config.get("REMOTE_CONSOLE", "opisrcon.port", 25566).getInt(); - rconactive = config.get("REMOTE_CONSOLE", "opisrcon.active", false).getBoolean(false); - rconpass = config.get("REMOTE_CONSOLE", "opisrcon.password", "").getString(); + profilerDelay = + config.get(Configuration.CATEGORY_GENERAL, "profiler.delay", 1).getInt(); + lagGenID = config.get(Configuration.CATEGORY_GENERAL, "laggenerator_id", -1) + .getInt(); + profilerMaxTicks = config.get(Configuration.CATEGORY_GENERAL, "profiler.maxpts", 250) + .getInt(); + microseconds = config.get(Configuration.CATEGORY_GENERAL, "display.microseconds", true) + .getBoolean(true); + rconport = config.get("REMOTE_CONSOLE", "opisrcon.port", 25566).getInt(); + rconactive = config.get("REMOTE_CONSOLE", "opisrcon.active", false).getBoolean(false); + rconpass = config.get("REMOTE_CONSOLE", "opisrcon.password", "").getString(); - String[] users = config.get("ACCESS_RIGHTS", "privileged", new String[]{}, commentPrivileged).getStringList(); - AccessLevel minTables = AccessLevel.PRIVILEGED; - AccessLevel openOpis = AccessLevel.PRIVILEGED; - try{ openOpis = AccessLevel.valueOf(config.get("ACCESS_RIGHTS", "opis", "NONE", commentTables).getString()); } catch (IllegalArgumentException e){} - try{ minTables = AccessLevel.valueOf(config.get("ACCESS_RIGHTS", "tables", "NONE", commentTables).getString()); } catch (IllegalArgumentException e){} + String[] users = config.get("ACCESS_RIGHTS", "privileged", new String[] {}, commentPrivileged) + .getStringList(); + AccessLevel minTables = AccessLevel.PRIVILEGED; + AccessLevel openOpis = AccessLevel.PRIVILEGED; + try { + openOpis = AccessLevel.valueOf( + config.get("ACCESS_RIGHTS", "opis", "NONE", commentTables).getString()); + } catch (IllegalArgumentException e) { + } + try { + minTables = AccessLevel.valueOf( + config.get("ACCESS_RIGHTS", "tables", "NONE", commentTables).getString()); + } catch (IllegalArgumentException e) { + } Message.setTablesMinimumLevel(minTables); Message.setOpisMinimumLevel(openOpis); - for (String s : users) - PlayerTracker.INSTANCE.addPrivilegedPlayer(s,false); + for (String s : users) PlayerTracker.INSTANCE.addPrivilegedPlayer(s, false); config.save(); @@ -101,7 +118,7 @@ public class modOpis { @EventHandler public void load(FMLInitializationEvent event) { - if (lagGenID != -1){ + if (lagGenID != -1) { Block blockDemo = new BlockLag(Material.wood); GameRegistry.registerBlock(blockDemo, "opis.laggen"); GameRegistry.registerTileEntity(TileLag.class, "opis.laggen"); @@ -111,10 +128,10 @@ public class modOpis { GameRegistry.registerTileEntity(TileDebug.class, "opis.debug"); } - ProfilerSection.RENDER_TILEENTITY .setProfiler(new ProfilerRenderTileEntity()); - ProfilerSection.RENDER_ENTITY .setProfiler(new ProfilerRenderEntity()); - ProfilerSection.RENDER_BLOCK .setProfiler(new ProfilerRenderBlock()); - ProfilerSection.EVENT_INVOKE .setProfiler(new ProfilerEvent()); + ProfilerSection.RENDER_TILEENTITY.setProfiler(new ProfilerRenderTileEntity()); + ProfilerSection.RENDER_ENTITY.setProfiler(new ProfilerRenderEntity()); + ProfilerSection.RENDER_BLOCK.setProfiler(new ProfilerRenderBlock()); + ProfilerSection.EVENT_INVOKE.setProfiler(new ProfilerEvent()); } @EventHandler @@ -124,15 +141,15 @@ public class modOpis { } @EventHandler - public void serverStarting(FMLServerStartingEvent event){ - ProfilerSection.DIMENSION_TICK .setProfiler(new ProfilerDimTick()); + public void serverStarting(FMLServerStartingEvent event) { + ProfilerSection.DIMENSION_TICK.setProfiler(new ProfilerDimTick()); ProfilerSection.DIMENSION_BLOCKTICK.setProfiler(new ProfilerDimBlockTick()); - ProfilerSection.ENTITY_UPDATETIME .setProfiler(new ProfilerEntityUpdate()); - ProfilerSection.TICK .setProfiler(new ProfilerTick()); - ProfilerSection.TILEENT_UPDATETIME .setProfiler(new ProfilerTileEntityUpdate()); - ProfilerSection.PACKET_INBOUND .setProfiler(new ProfilerPacket()); - ProfilerSection.PACKET_OUTBOUND .setProfiler(new ProfilerPacket()); - ProfilerSection.NETWORK_TICK .setProfiler(new ProfilerNetworkTick()); + ProfilerSection.ENTITY_UPDATETIME.setProfiler(new ProfilerEntityUpdate()); + ProfilerSection.TICK.setProfiler(new ProfilerTick()); + ProfilerSection.TILEENT_UPDATETIME.setProfiler(new ProfilerTileEntityUpdate()); + ProfilerSection.PACKET_INBOUND.setProfiler(new ProfilerPacket()); + ProfilerSection.PACKET_OUTBOUND.setProfiler(new ProfilerPacket()); + ProfilerSection.NETWORK_TICK.setProfiler(new ProfilerNetworkTick()); event.registerServerCommand(new CommandChunkList()); event.registerServerCommand(new CommandFrequency()); @@ -150,16 +167,15 @@ public class modOpis { event.registerServerCommand(new CommandAddPrivileged()); event.registerServerCommand(new CommandRmPrivileged()); - //event.registerServerCommand(new CommandClientTest()); - //event.registerServerCommand(new CommandClientStart()); - //event.registerServerCommand(new CommandClientShowRenderTick()); + // event.registerServerCommand(new CommandClientTest()); + // event.registerServerCommand(new CommandClientStart()); + // event.registerServerCommand(new CommandClientShowRenderTick()); event.registerServerCommand(new CommandHelp()); + // GameRegistry.registerPlayerTracker(PlayerTracker.instance()); - //GameRegistry.registerPlayerTracker(PlayerTracker.instance()); - - //DeadManSwitch.startDeadManSwitch(MinecraftServer.getServer()); + // DeadManSwitch.startDeadManSwitch(MinecraftServer.getServer()); /* for (ProfilerSection sec : ProfilerSection.values()){ System.out.printf("%s : %s\n", sec, sec.getProfiler().getClass().getSimpleName()); diff --git a/src/main/java/mcp/mobius/opis/network/PacketBase.java b/src/main/java/mcp/mobius/opis/network/PacketBase.java index 455ab79..34f0cf4 100644 --- a/src/main/java/mcp/mobius/opis/network/PacketBase.java +++ b/src/main/java/mcp/mobius/opis/network/PacketBase.java @@ -1,8 +1,11 @@ package mcp.mobius.opis.network; +import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteArrayDataOutput; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import java.lang.reflect.Method; import java.util.ArrayList; - import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.newtypes.DataError; import mcp.mobius.opis.network.enums.Message; @@ -10,49 +13,42 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.world.World; -import com.google.common.io.ByteArrayDataInput; -import com.google.common.io.ByteArrayDataOutput; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - /** -* @author abrarsyed -* This is the base packet type for tall the SecretRoomsMod network stuff. -* Any class that extends this should have an empty constructor, otherwise the network system will fail. -*/ -public abstract class PacketBase -{ - public byte header; - public Message msg; - public String clazzStr; - public Class clazz; - public ArrayList array = null; - public ISerializable value = null; - + * @author abrarsyed + * This is the base packet type for tall the SecretRoomsMod network stuff. + * Any class that extends this should have an empty constructor, otherwise the network system will fail. + */ +public abstract class PacketBase { + public byte header; + public Message msg; + public String clazzStr; + public Class clazz; + public ArrayList array = null; + public ISerializable value = null; + public abstract void encode(ByteArrayDataOutput output); public abstract void decode(ByteArrayDataInput input); @SideOnly(Side.CLIENT) - public void actionClient(World world, EntityPlayer player){ - throw new RuntimeException("Packet is not going the right way ! Server side packet seen client side."); + public void actionClient(World world, EntityPlayer player) { + throw new RuntimeException("Packet is not going the right way ! Server side packet seen client side."); } - public void actionServer(World world, EntityPlayerMP player){ - throw new RuntimeException("Packet is not going the right way ! Client side packet seen server side."); + public void actionServer(World world, EntityPlayerMP player) { + throw new RuntimeException("Packet is not going the right way ! Client side packet seen server side."); } - - protected ISerializable dataRead(Class datatype, ByteArrayDataInput istream){ - if (datatype == null) return new DataError(); - - try{ - Method readFromStream = datatype.getMethod("readFromStream", ByteArrayDataInput.class); - - return (ISerializable)readFromStream.invoke(null, istream); - } catch (Exception e) { - throw new RuntimeException(e); - } - } -} \ No newline at end of file + protected ISerializable dataRead(Class datatype, ByteArrayDataInput istream) { + if (datatype == null) return new DataError(); + + try { + Method readFromStream = datatype.getMethod("readFromStream", ByteArrayDataInput.class); + + return (ISerializable) readFromStream.invoke(null, istream); + + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/mcp/mobius/opis/network/PacketManager.java b/src/main/java/mcp/mobius/opis/network/PacketManager.java index d0c4bf5..9f63443 100644 --- a/src/main/java/mcp/mobius/opis/network/PacketManager.java +++ b/src/main/java/mcp/mobius/opis/network/PacketManager.java @@ -1,5 +1,8 @@ package mcp.mobius.opis.network; +import static cpw.mods.fml.relauncher.Side.CLIENT; +import static cpw.mods.fml.relauncher.Side.SERVER; + import com.google.common.collect.HashBasedTable; import com.google.common.collect.Maps; import com.google.common.collect.Table.Cell; @@ -17,6 +20,9 @@ import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.EnumMap; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.basetypes.AmountHolder; @@ -48,28 +54,19 @@ import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.EnumMap; - -import static cpw.mods.fml.relauncher.Side.CLIENT; -import static cpw.mods.fml.relauncher.Side.SERVER; - @Sharable -//public class PacketManager extends FMLIndexedMessageToMessageCodec -public class PacketManager -{ - //private static final PacketManager INSTANCE = new PacketManager(); - //private static final Logger LOGGER = LogManager.getLogger(); +// public class PacketManager extends FMLIndexedMessageToMessageCodec +public class PacketManager { + // private static final PacketManager INSTANCE = new PacketManager(); + // private static final Logger LOGGER = LogManager.getLogger(); private static final EnumMap channels = Maps.newEnumMap(Side.class); - public static void init() - { + public static void init() { if (!channels.isEmpty()) // avoid duplicate inits.. - return; - - Codec codec = new Codec(); - + return; + + Codec codec = new Codec(); + codec.addDiscriminator(0, PacketReqChunks.class); codec.addDiscriminator(1, PacketReqData.class); codec.addDiscriminator(2, NetDataCommand.class); @@ -77,77 +74,68 @@ public class PacketManager codec.addDiscriminator(4, NetDataValue.class); channels.putAll(NetworkRegistry.INSTANCE.newChannel("Opis", codec)); - + // add handlers - if (FMLCommonHandler.instance().getSide().isClient()) - { + if (FMLCommonHandler.instance().getSide().isClient()) { // for the client FMLEmbeddedChannel channel = channels.get(Side.CLIENT); String codecName = channel.findChannelHandlerNameForType(Codec.class); channel.pipeline().addAfter(codecName, "ClientHandler", new HandlerClient()); } - //else - { + // else + { // for the server FMLEmbeddedChannel channel = channels.get(Side.SERVER); String codecName = channel.findChannelHandlerNameForType(Codec.class); channel.pipeline().addAfter(codecName, "ServerHandler", new HandlerServer()); - } - + } } /** * @author abrarsyed * This class converts FMLMessage to PacketBase for my system to handle. */ - private static final class Codec extends FMLIndexedMessageToMessageCodec - { + private static final class Codec extends FMLIndexedMessageToMessageCodec { @Override - public void encodeInto(ChannelHandlerContext ctx, PacketBase packet, ByteBuf target) throws Exception - { + public void encodeInto(ChannelHandlerContext ctx, PacketBase packet, ByteBuf target) throws Exception { ByteArrayDataOutput output = ByteStreams.newDataOutput(); packet.encode(output); target.writeBytes(output.toByteArray()); } @Override - public void decodeInto(ChannelHandlerContext ctx, ByteBuf source, PacketBase packet) - { + public void decodeInto(ChannelHandlerContext ctx, ByteBuf source, PacketBase packet) { ByteArrayDataInput input = ByteStreams.newDataInput(source.array()); input.skipBytes(1); // skip the packet identifier byte packet.decode(input); - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) - { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { actionClient(packet); - } - else - { + } else { actionServer(ctx, packet); } } @SideOnly(Side.CLIENT) - private void actionClient(PacketBase packet) - { + private void actionClient(PacketBase packet) { Minecraft mc = Minecraft.getMinecraft(); packet.actionClient(mc.theWorld, mc.thePlayer); } - private void actionServer(ChannelHandlerContext ctx, PacketBase packet) - { - EntityPlayerMP player = ((NetHandlerPlayServer) ctx.channel().attr(NetworkRegistry.NET_HANDLER).get()).playerEntity; + private void actionServer(ChannelHandlerContext ctx, PacketBase packet) { + EntityPlayerMP player = ((NetHandlerPlayServer) + ctx.channel().attr(NetworkRegistry.NET_HANDLER).get()) + .playerEntity; packet.actionServer(player.worldObj, player); } @Override - public FMLIndexedMessageToMessageCodec addDiscriminator(int discriminator, Class type) - { + public FMLIndexedMessageToMessageCodec addDiscriminator( + int discriminator, Class type) { // double check it has an empty constructor. or fail early. // This is to guard myself against my own stupidity. - if (!hasEmptyContructor(type)) - { + if (!hasEmptyContructor(type)) { LogManager.getLogger().log(Level.FATAL, type.getName() + "does not have an empty constructor!"); } @@ -155,110 +143,100 @@ public class PacketManager } @SuppressWarnings("rawtypes") - private static boolean hasEmptyContructor(Class type) - { - try - { - for (Constructor c : type.getConstructors()) - { - if (c.getParameterTypes().length == 0) - { + private static boolean hasEmptyContructor(Class type) { + try { + for (Constructor c : type.getConstructors()) { + if (c.getParameterTypes().length == 0) { return true; } } - } - catch (SecurityException e) - { + } catch (SecurityException e) { // really? } return false; } - } - + } + @Sharable @SideOnly(Side.CLIENT) - private static final class HandlerClient extends SimpleChannelInboundHandler - { + private static final class HandlerClient extends SimpleChannelInboundHandler { @Override - protected void channelRead0(ChannelHandlerContext ctx, PacketBase packet) throws Exception - { + protected void channelRead0(ChannelHandlerContext ctx, PacketBase packet) throws Exception { Minecraft mc = Minecraft.getMinecraft(); packet.actionClient(mc.theWorld, mc.thePlayer); } } @Sharable - private static final class HandlerServer extends SimpleChannelInboundHandler - { + private static final class HandlerServer extends SimpleChannelInboundHandler { @Override - protected void channelRead0(ChannelHandlerContext ctx, PacketBase packet) throws Exception - { - EntityPlayerMP player = ((NetHandlerPlayServer) ctx.channel().attr(NetworkRegistry.NET_HANDLER).get()).playerEntity; + protected void channelRead0(ChannelHandlerContext ctx, PacketBase packet) throws Exception { + EntityPlayerMP player = ((NetHandlerPlayServer) + ctx.channel().attr(NetworkRegistry.NET_HANDLER).get()) + .playerEntity; packet.actionServer(player.worldObj, player); } - } - + } + // UTIL SENDING METHODS - - public static void sendToServer(PacketBase packet) - { + + public static void sendToServer(PacketBase packet) { channels.get(CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER); channels.get(CLIENT).writeAndFlush(packet); } - - public static void sendToPlayer(PacketBase packet, EntityPlayer player) - { - if ((player instanceof FakePlayer) && (RConHandler.fakePlayersRcon.containsKey(player))){ - RConHandler.sendToPlayerRCon(packet, (FakePlayer)player); - } else if ((player instanceof FakePlayer) && (RConHandler.fakePlayersNexus.containsKey(player))){ - RConHandler.sendToPlayerNexus(packet, (FakePlayer)player); - } - else { - channels.get(SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER); - channels.get(SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player); - channels.get(SERVER).writeAndFlush(packet); - } + + public static void sendToPlayer(PacketBase packet, EntityPlayer player) { + if ((player instanceof FakePlayer) && (RConHandler.fakePlayersRcon.containsKey(player))) { + RConHandler.sendToPlayerRCon(packet, (FakePlayer) player); + } else if ((player instanceof FakePlayer) && (RConHandler.fakePlayersNexus.containsKey(player))) { + RConHandler.sendToPlayerNexus(packet, (FakePlayer) player); + } else { + channels.get(SERVER) + .attr(FMLOutboundHandler.FML_MESSAGETARGET) + .set(FMLOutboundHandler.OutboundTarget.PLAYER); + channels.get(SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player); + channels.get(SERVER).writeAndFlush(packet); + } } - public static void sendToPlayer(Packet packet, EntityPlayerMP player) - { - player.playerNetServerHandler.sendPacket(packet); + public static void sendToPlayer(Packet packet, EntityPlayerMP player) { + player.playerNetServerHandler.sendPacket(packet); } - - public static void sendToAllAround(PacketBase packet, NetworkRegistry.TargetPoint point) - { - channels.get(SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT); + + public static void sendToAllAround(PacketBase packet, NetworkRegistry.TargetPoint point) { + channels.get(SERVER) + .attr(FMLOutboundHandler.FML_MESSAGETARGET) + .set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT); channels.get(SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point); channels.get(SERVER).writeAndFlush(packet); } - public static void sendToDimension(PacketBase packet, int dimension) - { - channels.get(SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION); + public static void sendToDimension(PacketBase packet, int dimension) { + channels.get(SERVER) + .attr(FMLOutboundHandler.FML_MESSAGETARGET) + .set(FMLOutboundHandler.OutboundTarget.DIMENSION); channels.get(SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(dimension); channels.get(SERVER).writeAndFlush(packet); } - - public static void sendToAll(PacketBase packet) - { - channels.get(SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL); - channels.get(SERVER).writeAndFlush(packet); - - for (Object fakePlayer : RConHandler.fakePlayersRcon.keySet().toArray()){ - RConHandler.sendToPlayerRCon(packet, (FakePlayer)fakePlayer); - } - - for (Object fakePlayer : RConHandler.fakePlayersNexus.keySet().toArray()){ - RConHandler.sendToPlayerNexus(packet, (FakePlayer)fakePlayer); - } + + public static void sendToAll(PacketBase packet) { + channels.get(SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL); + channels.get(SERVER).writeAndFlush(packet); + + for (Object fakePlayer : RConHandler.fakePlayersRcon.keySet().toArray()) { + RConHandler.sendToPlayerRCon(packet, (FakePlayer) fakePlayer); + } + + for (Object fakePlayer : RConHandler.fakePlayersNexus.keySet().toArray()) { + RConHandler.sendToPlayerNexus(packet, (FakePlayer) fakePlayer); + } } - - public static Packet toMcPacket(PacketBase packet) - { + + public static Packet toMcPacket(PacketBase packet) { return channels.get(FMLCommonHandler.instance().getEffectiveSide()).generatePacketFrom(packet); } - + /* public void writeString(ByteArrayDataOutput buffer, String data) throws IOException { @@ -266,96 +244,110 @@ public class PacketManager buffer.writeShort(abyte.length); buffer.writeBytes(abyte); } - + public String readString(ByteArrayDataInput buffer) throws IOException { int j = buffer.readShort(); String s = new String(buffer.readBytes(j).array(), Charsets.UTF_8); return s; - } + } */ - - public static void validateAndSend(PacketBase capsule, EntityPlayerMP player){ - if (!capsule.msg.isDisplayActive(PlayerTracker.INSTANCE.getPlayerSelectedTab(player))) return; - - if (capsule.msg.canPlayerUseCommand(player)) - PacketManager.sendToPlayer(capsule, player); - } - - public static void sendPacketToAllSwing(PacketBase capsule){ - for (EntityPlayerMP player : PlayerTracker.INSTANCE.playersSwing) - PacketManager.validateAndSend(capsule, player); - } - - public static void sendChatMsg(String msg, EntityPlayerMP player){ - PacketManager.sendToPlayer(new S02PacketChat(new ChatComponentText(msg)), player); - } - - public static void splitAndSend(Message msg, ArrayList data, EntityPlayerMP player){ - int i = 0; - while (i < data.size()){ - validateAndSend(new NetDataList(msg, data.subList(i, Math.min(i + 500, data.size()))), player); - i += 500; - } - } - - public static void sendFullUpdate(EntityPlayerMP player){ - ArrayList timingEntities = EntityManager.INSTANCE.getWorses(100); - ArrayList timingTileEnts = TileEntityManager.INSTANCE.getWorses(100); - //ArrayList timingHandlers = TickHandlerManager.getCumulatedStatsServer(); - ArrayList timingChunks = ChunkManager.INSTANCE.getTopChunks(100); - ArrayList timingEntsClass = EntityManager.INSTANCE.getTotalPerClass(); - ArrayList timingTEsClass = TileEntityManager.INSTANCE.getCumulativeTimingTileEntities(); - - DataTiming totalTimeTE = TileEntityManager.INSTANCE.getTotalUpdateTime(); - DataTiming totalTimeEnt = EntityManager.INSTANCE.getTotalUpdateTime(); - //DataTiming totalTimeHandler = TickHandlerManager.getTotalUpdateTime(); - DataNetworkTick totalNetwork = new DataNetworkTick().fill(); - DataBlockTick totalWorldTick = new DataBlockTick().fill(); - ArrayList timingEvents = new ArrayList(); - HashBasedTable eventData = ((ProfilerEvent)ProfilerSection.EVENT_INVOKE.getProfiler()).data; - HashBasedTable eventMod = ((ProfilerEvent)ProfilerSection.EVENT_INVOKE.getProfiler()).dataMod; - for (Cell cell : eventData.cellSet()){ - timingEvents.add(new DataEvent().fill(cell, eventMod.get(cell.getRowKey(), cell.getColumnKey()))); - } + public static void validateAndSend(PacketBase capsule, EntityPlayerMP player) { + if (!capsule.msg.isDisplayActive(PlayerTracker.INSTANCE.getPlayerSelectedTab(player))) return; - ArrayList timingTicks = new ArrayList(); - HashBasedTable eventTickData = ((ProfilerEvent)ProfilerSection.EVENT_INVOKE.getProfiler()).dataTick; - HashBasedTable eventTickMod = ((ProfilerEvent)ProfilerSection.EVENT_INVOKE.getProfiler()).dataModTick; - for (Cell cell : eventTickData.cellSet()){ - timingTicks.add(new DataEvent().fill(cell, eventTickMod.get(cell.getRowKey(), cell.getColumnKey()))); - } - - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_HANDLERS, timingTicks), player); - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_ENTITIES, timingEntities), player); - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_TILEENTS, timingTileEnts), player); - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_TILEENTS_PER_CLASS, timingTEsClass), player); - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_CHUNK, timingChunks), player); - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_EVENTS, timingEvents), player); - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_ENTITIES_PER_CLASS, timingEntsClass), player); - PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_TILEENTS, totalTimeTE), player); - PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_ENTITIES, totalTimeEnt), player); - //PacketManager.validateAndSend(NetDataValue_OLD.create(Message.VALUE_TIMING_HANDLERS, totalTimeHandler), player); - PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_WORLDTICK, totalWorldTick), player); - PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_NETWORK, totalNetwork), player); - - //PacketManager.validateAndSend(NetDataValue_OLD.create(Message.VALUE_AMOUNT_HANDLERS, new SerialInt(timingHandlers.size())), player); - - PacketManager.validateAndSend(new NetDataValue(Message.STATUS_TIME_LAST_RUN, new SerialLong(ProfilerSection.timeStampLastRun)), player); - - PacketManager.validateAndSend(new NetDataValue(Message.STATUS_ACCESS_LEVEL, new SerialInt(PlayerTracker.INSTANCE.getPlayerAccessLevel(player).ordinal())), player); - - // This portion is to get the proper filtered amounts depending on the player preferences. - String name = player.getGameProfile().getName(); - boolean filtered = false; - if (PlayerTracker.INSTANCE.filteredAmount.containsKey(name)) - filtered = PlayerTracker.INSTANCE.filteredAmount.get(name); - ArrayList amountEntities = EntityManager.INSTANCE.getCumulativeEntities(filtered); + if (capsule.msg.canPlayerUseCommand(player)) PacketManager.sendToPlayer(capsule, player); + } - // Here we send a full update to the player - //OpisPacketHandler.validateAndSend(Packet_DataList.create(DataReq.LIST_AMOUNT_ENTITIES, amountEntities), player); - PacketManager.validateAndSend(new NetDataList(Message.LIST_AMOUNT_ENTITIES, amountEntities), player); - - } -} \ No newline at end of file + public static void sendPacketToAllSwing(PacketBase capsule) { + for (EntityPlayerMP player : PlayerTracker.INSTANCE.playersSwing) + PacketManager.validateAndSend(capsule, player); + } + + public static void sendChatMsg(String msg, EntityPlayerMP player) { + PacketManager.sendToPlayer(new S02PacketChat(new ChatComponentText(msg)), player); + } + + public static void splitAndSend(Message msg, ArrayList data, EntityPlayerMP player) { + int i = 0; + while (i < data.size()) { + validateAndSend(new NetDataList(msg, data.subList(i, Math.min(i + 500, data.size()))), player); + i += 500; + } + } + + public static void sendFullUpdate(EntityPlayerMP player) { + ArrayList timingEntities = EntityManager.INSTANCE.getWorses(100); + ArrayList timingTileEnts = TileEntityManager.INSTANCE.getWorses(100); + // ArrayList timingHandlers = TickHandlerManager.getCumulatedStatsServer(); + ArrayList timingChunks = ChunkManager.INSTANCE.getTopChunks(100); + ArrayList timingEntsClass = EntityManager.INSTANCE.getTotalPerClass(); + ArrayList timingTEsClass = + TileEntityManager.INSTANCE.getCumulativeTimingTileEntities(); + + DataTiming totalTimeTE = TileEntityManager.INSTANCE.getTotalUpdateTime(); + DataTiming totalTimeEnt = EntityManager.INSTANCE.getTotalUpdateTime(); + // DataTiming totalTimeHandler = TickHandlerManager.getTotalUpdateTime(); + DataNetworkTick totalNetwork = new DataNetworkTick().fill(); + DataBlockTick totalWorldTick = new DataBlockTick().fill(); + + ArrayList timingEvents = new ArrayList(); + HashBasedTable eventData = + ((ProfilerEvent) ProfilerSection.EVENT_INVOKE.getProfiler()).data; + HashBasedTable eventMod = + ((ProfilerEvent) ProfilerSection.EVENT_INVOKE.getProfiler()).dataMod; + for (Cell cell : eventData.cellSet()) { + timingEvents.add(new DataEvent().fill(cell, eventMod.get(cell.getRowKey(), cell.getColumnKey()))); + } + + ArrayList timingTicks = new ArrayList(); + HashBasedTable eventTickData = + ((ProfilerEvent) ProfilerSection.EVENT_INVOKE.getProfiler()).dataTick; + HashBasedTable eventTickMod = + ((ProfilerEvent) ProfilerSection.EVENT_INVOKE.getProfiler()).dataModTick; + for (Cell cell : eventTickData.cellSet()) { + timingTicks.add(new DataEvent().fill(cell, eventTickMod.get(cell.getRowKey(), cell.getColumnKey()))); + } + + PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_HANDLERS, timingTicks), player); + PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_ENTITIES, timingEntities), player); + PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_TILEENTS, timingTileEnts), player); + PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_TILEENTS_PER_CLASS, timingTEsClass), player); + PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_CHUNK, timingChunks), player); + PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_EVENTS, timingEvents), player); + PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_ENTITIES_PER_CLASS, timingEntsClass), player); + PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_TILEENTS, totalTimeTE), player); + PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_ENTITIES, totalTimeEnt), player); + // PacketManager.validateAndSend(NetDataValue_OLD.create(Message.VALUE_TIMING_HANDLERS, totalTimeHandler), + // player); + PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_WORLDTICK, totalWorldTick), player); + PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_NETWORK, totalNetwork), player); + + // PacketManager.validateAndSend(NetDataValue_OLD.create(Message.VALUE_AMOUNT_HANDLERS, new + // SerialInt(timingHandlers.size())), player); + + PacketManager.validateAndSend( + new NetDataValue(Message.STATUS_TIME_LAST_RUN, new SerialLong(ProfilerSection.timeStampLastRun)), + player); + + PacketManager.validateAndSend( + new NetDataValue( + Message.STATUS_ACCESS_LEVEL, + new SerialInt(PlayerTracker.INSTANCE + .getPlayerAccessLevel(player) + .ordinal())), + player); + + // This portion is to get the proper filtered amounts depending on the player preferences. + String name = player.getGameProfile().getName(); + boolean filtered = false; + if (PlayerTracker.INSTANCE.filteredAmount.containsKey(name)) + filtered = PlayerTracker.INSTANCE.filteredAmount.get(name); + ArrayList amountEntities = EntityManager.INSTANCE.getCumulativeEntities(filtered); + + // Here we send a full update to the player + // OpisPacketHandler.validateAndSend(Packet_DataList.create(DataReq.LIST_AMOUNT_ENTITIES, amountEntities), + // player); + PacketManager.validateAndSend(new NetDataList(Message.LIST_AMOUNT_ENTITIES, amountEntities), player); + } +} diff --git a/src/main/java/mcp/mobius/opis/network/ServerMessageHandler.java b/src/main/java/mcp/mobius/opis/network/ServerMessageHandler.java index 90f07ff..d1a8945 100644 --- a/src/main/java/mcp/mobius/opis/network/ServerMessageHandler.java +++ b/src/main/java/mcp/mobius/opis/network/ServerMessageHandler.java @@ -1,6 +1,7 @@ package mcp.mobius.opis.network; import cpw.mods.fml.relauncher.Side; +import java.util.ArrayList; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.data.holders.basetypes.*; @@ -24,179 +25,134 @@ import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import org.apache.logging.log4j.Level; -import java.util.ArrayList; - public class ServerMessageHandler { - private static ServerMessageHandler _instance; - private ServerMessageHandler(){} - - public static ServerMessageHandler instance(){ - if(_instance == null) - _instance = new ServerMessageHandler(); - return _instance; - } + private static ServerMessageHandler _instance; - public void handle(Message maintype, ISerializable param1, ISerializable param2, EntityPlayerMP player){ - String name = player.getGameProfile().getName(); + private ServerMessageHandler() {} - if (maintype == Message.LIST_CHUNK_LOADED){ - PlayerTracker.INSTANCE.playerDimension.put(player, ((SerialInt)param1).value); - PacketManager.validateAndSend(new NetDataCommand(Message.LIST_CHUNK_LOADED_CLEAR), player); - PacketManager.splitAndSend(Message.LIST_CHUNK_LOADED, ChunkManager.INSTANCE.getLoadedChunks(((SerialInt)param1).value), player); - } - - else if (maintype == Message.LIST_TIMING_TILEENTS){ - ArrayList timingTileEnts = TileEntityManager.INSTANCE.getWorses(100); - DataTiming totalTime = TileEntityManager.INSTANCE.getTotalUpdateTime(); - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_TILEENTS, timingTileEnts), player); - PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_TILEENTS, totalTime), player); - } - - else if (maintype == Message.LIST_TIMING_ENTITIES){ - ArrayList timingEntities = EntityManager.INSTANCE.getWorses(100); - DataTiming totalTime = EntityManager.INSTANCE.getTotalUpdateTime(); - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_ENTITIES, timingEntities), player); - PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_ENTITIES, totalTime), player); - } - - else if (maintype == Message.LIST_TIMING_HANDLERS){ - //ArrayList timingHandlers = TickHandlerManager.getCumulatedStatsServer(); - //DataTiming totalTime = TickHandlerManager.getTotalUpdateTime(); - //OpisPacketHandler_OLD.validateAndSend(NetDataList_OLD.create(Message.LIST_TIMING_HANDLERS, timingHandlers), player); - //OpisPacketHandler_OLD.validateAndSend(NetDataValue_OLD.create(Message.VALUE_TIMING_HANDLERS, totalTime), player); - } - - else if (maintype == Message.LIST_TIMING_CHUNK){ - ArrayList timingChunks = ChunkManager.INSTANCE.getTopChunks(100); - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_CHUNK, timingChunks), player); - } + public static ServerMessageHandler instance() { + if (_instance == null) _instance = new ServerMessageHandler(); + return _instance; + } - else if (maintype == Message.VALUE_TIMING_WORLDTICK){ - PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_WORLDTICK, new DataBlockTick().fill()), player); - } + public void handle(Message maintype, ISerializable param1, ISerializable param2, EntityPlayerMP player) { + String name = player.getGameProfile().getName(); - else if (maintype == Message.VALUE_TIMING_ENTUPDATE){ - } - - else if (maintype == Message.LIST_AMOUNT_ENTITIES){ - boolean filtered = false; - if (PlayerTracker.INSTANCE.filteredAmount.containsKey(name)) - filtered = PlayerTracker.INSTANCE.filteredAmount.get(name); - - ArrayList ents = EntityManager.INSTANCE.getCumulativeEntities(filtered); - PacketManager.validateAndSend(new NetDataList(Message.LIST_AMOUNT_ENTITIES, ents), player); - } - - else if (maintype == Message.LIST_AMOUNT_TILEENTS){ - PacketManager.validateAndSend(new NetDataList(Message.LIST_AMOUNT_TILEENTS, TileEntityManager.INSTANCE.getCumulativeAmountTileEntities()), player); - } - - else if (maintype == Message.COMMAND_FILTERING_TRUE){ - PlayerTracker.INSTANCE.filteredAmount.put(name, true); - } + if (maintype == Message.LIST_CHUNK_LOADED) { + PlayerTracker.INSTANCE.playerDimension.put(player, ((SerialInt) param1).value); + PacketManager.validateAndSend(new NetDataCommand(Message.LIST_CHUNK_LOADED_CLEAR), player); + PacketManager.splitAndSend( + Message.LIST_CHUNK_LOADED, + ChunkManager.INSTANCE.getLoadedChunks(((SerialInt) param1).value), + player); + } else if (maintype == Message.LIST_TIMING_TILEENTS) { + ArrayList timingTileEnts = TileEntityManager.INSTANCE.getWorses(100); + DataTiming totalTime = TileEntityManager.INSTANCE.getTotalUpdateTime(); + PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_TILEENTS, timingTileEnts), player); + PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_TILEENTS, totalTime), player); + } else if (maintype == Message.LIST_TIMING_ENTITIES) { + ArrayList timingEntities = EntityManager.INSTANCE.getWorses(100); + DataTiming totalTime = EntityManager.INSTANCE.getTotalUpdateTime(); + PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_ENTITIES, timingEntities), player); + PacketManager.validateAndSend(new NetDataValue(Message.VALUE_TIMING_ENTITIES, totalTime), player); + } else if (maintype == Message.LIST_TIMING_HANDLERS) { + // ArrayList timingHandlers = TickHandlerManager.getCumulatedStatsServer(); + // DataTiming totalTime = TickHandlerManager.getTotalUpdateTime(); + // OpisPacketHandler_OLD.validateAndSend(NetDataList_OLD.create(Message.LIST_TIMING_HANDLERS, + // timingHandlers), player); + // OpisPacketHandler_OLD.validateAndSend(NetDataValue_OLD.create(Message.VALUE_TIMING_HANDLERS, totalTime), + // player); + } else if (maintype == Message.LIST_TIMING_CHUNK) { + ArrayList timingChunks = ChunkManager.INSTANCE.getTopChunks(100); + PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_CHUNK, timingChunks), player); + } else if (maintype == Message.VALUE_TIMING_WORLDTICK) { + PacketManager.validateAndSend( + new NetDataValue(Message.VALUE_TIMING_WORLDTICK, new DataBlockTick().fill()), player); + } else if (maintype == Message.VALUE_TIMING_ENTUPDATE) { + } else if (maintype == Message.LIST_AMOUNT_ENTITIES) { + boolean filtered = false; + if (PlayerTracker.INSTANCE.filteredAmount.containsKey(name)) + filtered = PlayerTracker.INSTANCE.filteredAmount.get(name); - else if (maintype == Message.COMMAND_FILTERING_FALSE){ - PlayerTracker.INSTANCE.filteredAmount.put(name, false); - } - - else if (maintype == Message.COMMAND_UNREGISTER){ - PlayerTracker.INSTANCE.playerDimension.remove(player); - } + ArrayList ents = EntityManager.INSTANCE.getCumulativeEntities(filtered); + PacketManager.validateAndSend(new NetDataList(Message.LIST_AMOUNT_ENTITIES, ents), player); + } else if (maintype == Message.LIST_AMOUNT_TILEENTS) { + PacketManager.validateAndSend( + new NetDataList( + Message.LIST_AMOUNT_TILEENTS, TileEntityManager.INSTANCE.getCumulativeAmountTileEntities()), + player); + } else if (maintype == Message.COMMAND_FILTERING_TRUE) { + PlayerTracker.INSTANCE.filteredAmount.put(name, true); + } else if (maintype == Message.COMMAND_FILTERING_FALSE) { + PlayerTracker.INSTANCE.filteredAmount.put(name, false); + } else if (maintype == Message.COMMAND_UNREGISTER) { + PlayerTracker.INSTANCE.playerDimension.remove(player); + } else if (maintype == Message.COMMAND_START) { + MetaManager.reset(); + modOpis.profilerRun = true; + ProfilerSection.activateAll(Side.SERVER); + PacketManager.sendPacketToAllSwing( + new NetDataValue(Message.STATUS_START, new SerialInt(modOpis.profilerMaxTicks))); + } else if (maintype == Message.COMMAND_TELEPORT_BLOCK) { + EntityManager.INSTANCE.teleportPlayer((CoordinatesBlock) param1, player); + PacketManager.validateAndSend(new NetDataValue(Message.CLIENT_HIGHLIGHT_BLOCK, param1), player); + } else if (maintype == Message.COMMAND_TELEPORT_TO_ENTITY) { + EntityManager.INSTANCE.teleportEntity( + player, + EntityManager.INSTANCE.getEntity(((TargetEntity) param1).entityID, ((TargetEntity) param1).dim), + player); + } else if (maintype == Message.COMMAND_TELEPORT_PULL_ENTITY) { + EntityManager.INSTANCE.teleportEntity( + EntityManager.INSTANCE.getEntity(((TargetEntity) param1).entityID, ((TargetEntity) param1).dim), + player, + player); + } else if (maintype == Message.COMMAND_TELEPORT_CHUNK) { + CoordinatesChunk chunkCoord = (CoordinatesChunk) param1; + World world = DimensionManager.getWorld(chunkCoord.dim); + if (world == null) return; - else if (maintype == Message.COMMAND_START){ - MetaManager.reset(); - modOpis.profilerRun = true; - ProfilerSection.activateAll(Side.SERVER); - PacketManager.sendPacketToAllSwing(new NetDataValue(Message.STATUS_START, new SerialInt(modOpis.profilerMaxTicks))); - } - - else if (maintype == Message.COMMAND_TELEPORT_BLOCK){ - EntityManager.INSTANCE.teleportPlayer((CoordinatesBlock)param1, player); - PacketManager.validateAndSend(new NetDataValue(Message.CLIENT_HIGHLIGHT_BLOCK, param1), player); - } - - else if (maintype == Message.COMMAND_TELEPORT_TO_ENTITY){ - EntityManager.INSTANCE.teleportEntity(player, EntityManager.INSTANCE.getEntity(((TargetEntity)param1).entityID, ((TargetEntity)param1).dim), player); - } - - else if (maintype == Message.COMMAND_TELEPORT_PULL_ENTITY){ - EntityManager.INSTANCE.teleportEntity(EntityManager.INSTANCE.getEntity(((TargetEntity)param1).entityID, ((TargetEntity)param1).dim), player, player); - } - - else if (maintype == Message.COMMAND_TELEPORT_CHUNK){ - CoordinatesChunk chunkCoord = (CoordinatesChunk)param1; - World world = DimensionManager.getWorld(chunkCoord.dim); - if (world == null) return; - - CoordinatesBlock blockCoord = new CoordinatesBlock(chunkCoord.dim, chunkCoord.x + 8, world.getTopSolidOrLiquidBlock(chunkCoord.x, chunkCoord.z), chunkCoord.z + 8); - - EntityManager.INSTANCE.teleportPlayer(blockCoord, player); - } - - - else if (maintype == Message.COMMAND_KILLALL){ - EntityManager.INSTANCE.killAll(((SerialString)param1).value); - //this.handle(Message.LIST_AMOUNT_ENTITIES, null, null, player); - } + CoordinatesBlock blockCoord = new CoordinatesBlock( + chunkCoord.dim, + chunkCoord.x + 8, + world.getTopSolidOrLiquidBlock(chunkCoord.x, chunkCoord.z), + chunkCoord.z + 8); - else if (maintype == Message.COMMAND_KILLALL_BYCACHEID){ - String entname = StringCache.INSTANCE.getString(((SerialInt)param1).value); - EntityManager.INSTANCE.killAll(entname); - } - - else if(maintype == Message.COMMAND_UNREGISTER_SWING){ - PlayerTracker.INSTANCE.playersSwing.remove(player); - } - - else if(maintype == Message.STATUS_TIME_LAST_RUN){ - PacketManager.validateAndSend(new NetDataValue(Message.STATUS_TIME_LAST_RUN, new SerialLong(ProfilerSection.timeStampLastRun)), player); - } - - else if(maintype == Message.COMMAND_KILL_HOSTILES_ALL){ - for (int dim : DimensionManager.getIDs()) - EntityManager.INSTANCE.killAllPerClass(dim, EntityMob.class); - } - - else if(maintype == Message.COMMAND_KILL_HOSTILES_DIM){ - EntityManager.INSTANCE.killAllPerClass(((SerialInt)param1).value, EntityMob.class); - } - - else if(maintype == Message.COMMAND_KILL_STACKS_ALL){ - for (int dim : DimensionManager.getIDs()) - EntityManager.INSTANCE.killAllPerClass(dim, EntityItem.class); - } - - else if(maintype == Message.COMMAND_KILL_STACKS_DIM){ - EntityManager.INSTANCE.killAllPerClass(((SerialInt)param1).value, EntityItem.class); - } - - else if(maintype == Message.COMMAND_PURGE_CHUNKS_ALL){ - for (int dim : DimensionManager.getIDs()) - ChunkManager.INSTANCE.purgeChunks(dim); - } - - else if(maintype == Message.COMMAND_PURGE_CHUNKS_DIM){ - ChunkManager.INSTANCE.purgeChunks(((SerialInt)param1).value); - } - - else if(maintype == Message.STATUS_PING){ - PacketManager.validateAndSend(new NetDataValue(Message.STATUS_PING, param1), player); - } - - else if(maintype == Message.SWING_TAB_CHANGED){ - SelectedTab tab = SelectedTab.values()[((SerialInt)param1).value]; - PlayerTracker.INSTANCE.playerTab.put(player, tab); - } - - else if(maintype == Message.LIST_ORPHAN_TILEENTS){ - PacketManager.validateAndSend(new NetDataCommand(Message.LIST_ORPHAN_TILEENTS_CLEAR), player); - PacketManager.splitAndSend(Message.LIST_ORPHAN_TILEENTS, TileEntityManager.INSTANCE.getOrphans(), player); - } - - else{ - modOpis.log.log(Level.WARN, String.format("Unknown data request : %s ", maintype)); - } - } - + EntityManager.INSTANCE.teleportPlayer(blockCoord, player); + } else if (maintype == Message.COMMAND_KILLALL) { + EntityManager.INSTANCE.killAll(((SerialString) param1).value); + // this.handle(Message.LIST_AMOUNT_ENTITIES, null, null, player); + } else if (maintype == Message.COMMAND_KILLALL_BYCACHEID) { + String entname = StringCache.INSTANCE.getString(((SerialInt) param1).value); + EntityManager.INSTANCE.killAll(entname); + } else if (maintype == Message.COMMAND_UNREGISTER_SWING) { + PlayerTracker.INSTANCE.playersSwing.remove(player); + } else if (maintype == Message.STATUS_TIME_LAST_RUN) { + PacketManager.validateAndSend( + new NetDataValue(Message.STATUS_TIME_LAST_RUN, new SerialLong(ProfilerSection.timeStampLastRun)), + player); + } else if (maintype == Message.COMMAND_KILL_HOSTILES_ALL) { + for (int dim : DimensionManager.getIDs()) EntityManager.INSTANCE.killAllPerClass(dim, EntityMob.class); + } else if (maintype == Message.COMMAND_KILL_HOSTILES_DIM) { + EntityManager.INSTANCE.killAllPerClass(((SerialInt) param1).value, EntityMob.class); + } else if (maintype == Message.COMMAND_KILL_STACKS_ALL) { + for (int dim : DimensionManager.getIDs()) EntityManager.INSTANCE.killAllPerClass(dim, EntityItem.class); + } else if (maintype == Message.COMMAND_KILL_STACKS_DIM) { + EntityManager.INSTANCE.killAllPerClass(((SerialInt) param1).value, EntityItem.class); + } else if (maintype == Message.COMMAND_PURGE_CHUNKS_ALL) { + for (int dim : DimensionManager.getIDs()) ChunkManager.INSTANCE.purgeChunks(dim); + } else if (maintype == Message.COMMAND_PURGE_CHUNKS_DIM) { + ChunkManager.INSTANCE.purgeChunks(((SerialInt) param1).value); + } else if (maintype == Message.STATUS_PING) { + PacketManager.validateAndSend(new NetDataValue(Message.STATUS_PING, param1), player); + } else if (maintype == Message.SWING_TAB_CHANGED) { + SelectedTab tab = SelectedTab.values()[((SerialInt) param1).value]; + PlayerTracker.INSTANCE.playerTab.put(player, tab); + } else if (maintype == Message.LIST_ORPHAN_TILEENTS) { + PacketManager.validateAndSend(new NetDataCommand(Message.LIST_ORPHAN_TILEENTS_CLEAR), player); + PacketManager.splitAndSend(Message.LIST_ORPHAN_TILEENTS, TileEntityManager.INSTANCE.getOrphans(), player); + } else { + modOpis.log.log(Level.WARN, String.format("Unknown data request : %s ", maintype)); + } + } } diff --git a/src/main/java/mcp/mobius/opis/network/enums/AccessLevel.java b/src/main/java/mcp/mobius/opis/network/enums/AccessLevel.java index c2bec0f..db46ffb 100644 --- a/src/main/java/mcp/mobius/opis/network/enums/AccessLevel.java +++ b/src/main/java/mcp/mobius/opis/network/enums/AccessLevel.java @@ -1,7 +1,7 @@ package mcp.mobius.opis.network.enums; public enum AccessLevel { - NONE, - PRIVILEGED, - ADMIN; + NONE, + PRIVILEGED, + ADMIN; } diff --git a/src/main/java/mcp/mobius/opis/network/enums/Message.java b/src/main/java/mcp/mobius/opis/network/enums/Message.java index 287a72a..ac3b30b 100644 --- a/src/main/java/mcp/mobius/opis/network/enums/Message.java +++ b/src/main/java/mcp/mobius/opis/network/enums/Message.java @@ -1,157 +1,154 @@ package mcp.mobius.opis.network.enums; +import static mcp.mobius.opis.network.enums.AccessLevel.PRIVILEGED; + +import java.util.EnumSet; import mcp.mobius.opis.events.PlayerTracker; import mcp.mobius.opis.swing.SelectedTab; import net.minecraft.entity.player.EntityPlayerMP; -import java.util.EnumSet; - -import static mcp.mobius.opis.network.enums.AccessLevel.PRIVILEGED; - public enum Message { + LIST_CHUNK_LOADED, + LIST_CHUNK_LOADED_CLEAR, + LIST_TIMING_TILEENTS, + LIST_TIMING_TILEENTS_PER_CLASS, + LIST_TIMING_ENTITIES, + LIST_TIMING_ENTITIES_PER_CLASS, + LIST_TIMING_HANDLERS, + LIST_TIMING_CHUNK, + LIST_TIMING_EVENTS, + LIST_AMOUNT_ENTITIES, + LIST_AMOUNT_TILEENTS, + LIST_PLAYERS(EnumSet.of(SelectedTab.PLAYERS)), + LIST_DIMENSION_DATA(EnumSet.of(SelectedTab.DIMENSIONS)), + LIST_PACKETS_OUTBOUND(EnumSet.of(SelectedTab.PACKETOUTBOUND)), + LIST_PACKETS_INBOUND(EnumSet.of(SelectedTab.PACKETINBOUND)), + LIST_PACKETS_OUTBOUND_250(EnumSet.of(SelectedTab.PACKETOUTBOUND250)), + LIST_PACKETS_INBOUND_250(EnumSet.of(SelectedTab.PACKETINBOUND250)), + LIST_ORPHAN_TILEENTS, + LIST_ORPHAN_TILEENTS_CLEAR, + LIST_THREADS(EnumSet.of(SelectedTab.THREADS)), - LIST_CHUNK_LOADED, - LIST_CHUNK_LOADED_CLEAR, - LIST_TIMING_TILEENTS, - LIST_TIMING_TILEENTS_PER_CLASS, - LIST_TIMING_ENTITIES, - LIST_TIMING_ENTITIES_PER_CLASS, - LIST_TIMING_HANDLERS, - LIST_TIMING_CHUNK, - LIST_TIMING_EVENTS, - LIST_AMOUNT_ENTITIES, - LIST_AMOUNT_TILEENTS, - LIST_PLAYERS (EnumSet.of(SelectedTab.PLAYERS)), - LIST_DIMENSION_DATA (EnumSet.of(SelectedTab.DIMENSIONS)), - LIST_PACKETS_OUTBOUND (EnumSet.of(SelectedTab.PACKETOUTBOUND)), - LIST_PACKETS_INBOUND (EnumSet.of(SelectedTab.PACKETINBOUND)), - LIST_PACKETS_OUTBOUND_250(EnumSet.of(SelectedTab.PACKETOUTBOUND250)), - LIST_PACKETS_INBOUND_250 (EnumSet.of(SelectedTab.PACKETINBOUND250)), - LIST_ORPHAN_TILEENTS, - LIST_ORPHAN_TILEENTS_CLEAR, - LIST_THREADS (EnumSet.of(SelectedTab.THREADS)), - - VALUE_TIMING_TILEENTS, - VALUE_TIMING_ENTITIES, - VALUE_TIMING_HANDLERS, - VALUE_TIMING_WORLDTICK, - VALUE_TIMING_ENTUPDATE, - VALUE_TIMING_NETWORK, - - STATUS_START, - STATUS_STOP, - STATUS_RUN_UPDATE, - STATUS_RUNNING, - STATUS_CURRENT_TIME, - STATUS_TIME_LAST_RUN, - STATUS_ACCESS_LEVEL, - STATUS_PING(EnumSet.of(SelectedTab.SUMMARY)), - STATUS_STRINGUPD, - STATUS_STRINGUPD_FULL, - - - COMMAND_TELEPORT_BLOCK(PRIVILEGED), - COMMAND_TELEPORT_CHUNK(PRIVILEGED), - COMMAND_TELEPORT_TO_ENTITY(PRIVILEGED), - COMMAND_TELEPORT_PULL_ENTITY(PRIVILEGED), - COMMAND_START(PRIVILEGED), - COMMAND_KILLALL(PRIVILEGED), - COMMAND_KILLALL_BYCACHEID(PRIVILEGED), - COMMAND_FILTERING_TRUE, - COMMAND_FILTERING_FALSE, - COMMAND_UNREGISTER, - COMMAND_UNREGISTER_SWING, - COMMAND_OPEN_SWING, - - COMMAND_KILL_HOSTILES_DIM(PRIVILEGED), // This will kill all hostile in the dim given as argument - COMMAND_KILL_HOSTILES_ALL(PRIVILEGED), // This will kill all hostile in all the dimensions - COMMAND_PURGE_CHUNKS_DIM(PRIVILEGED), // This will purge the chunks in the dim given as argument - COMMAND_PURGE_CHUNKS_ALL(PRIVILEGED), // This will purge the chunks in all dimensions - COMMAND_KILL_STACKS_DIM(PRIVILEGED), // This will kill all stacks in the dim given as argument - COMMAND_KILL_STACKS_ALL(PRIVILEGED), // This will kill all stacks in all the dimensions - - CLIENT_START_PROFILING, - CLIENT_STOP_PROFILING, - CLIENT_RESET_PROFILING, - CLIENT_SHOW_RENDER_TICK, - CLIENT_SHOW_SWING, - CLIENT_CLEAR_SELECTION, - CLIENT_HIGHLIGHT_BLOCK, - - SWING_TAB_CHANGED, - NEXUS_UUID, // Login data for the nexus system - NEXUS_DATA, // Data blob with everything needed to update the summary screen in realtime - PLAYER_STATUS_UPDATE, // Update for the players (name, position, offline/online, etc) - CONNECTION_STATUS, - - CHAT_MSG; - - private AccessLevel accessLevel = AccessLevel.NONE; - private EnumSet tabEnum; - - private Message(){ - accessLevel = AccessLevel.NONE; - tabEnum = EnumSet.of(SelectedTab.ANY); - } + VALUE_TIMING_TILEENTS, + VALUE_TIMING_ENTITIES, + VALUE_TIMING_HANDLERS, + VALUE_TIMING_WORLDTICK, + VALUE_TIMING_ENTUPDATE, + VALUE_TIMING_NETWORK, - private Message(AccessLevel level){ - accessLevel = level; - tabEnum = EnumSet.of(SelectedTab.ANY); - } + STATUS_START, + STATUS_STOP, + STATUS_RUN_UPDATE, + STATUS_RUNNING, + STATUS_CURRENT_TIME, + STATUS_TIME_LAST_RUN, + STATUS_ACCESS_LEVEL, + STATUS_PING(EnumSet.of(SelectedTab.SUMMARY)), + STATUS_STRINGUPD, + STATUS_STRINGUPD_FULL, - private Message(EnumSet _tabEnum){ - accessLevel = AccessLevel.NONE; - tabEnum = _tabEnum; - } + COMMAND_TELEPORT_BLOCK(PRIVILEGED), + COMMAND_TELEPORT_CHUNK(PRIVILEGED), + COMMAND_TELEPORT_TO_ENTITY(PRIVILEGED), + COMMAND_TELEPORT_PULL_ENTITY(PRIVILEGED), + COMMAND_START(PRIVILEGED), + COMMAND_KILLALL(PRIVILEGED), + COMMAND_KILLALL_BYCACHEID(PRIVILEGED), + COMMAND_FILTERING_TRUE, + COMMAND_FILTERING_FALSE, + COMMAND_UNREGISTER, + COMMAND_UNREGISTER_SWING, + COMMAND_OPEN_SWING, - private Message(AccessLevel level, EnumSet _tabEnum){ - accessLevel = level; - tabEnum = _tabEnum; - } - - public AccessLevel getAccessLevel(){ - return this.accessLevel; - } + COMMAND_KILL_HOSTILES_DIM(PRIVILEGED), // This will kill all hostile in the dim given as argument + COMMAND_KILL_HOSTILES_ALL(PRIVILEGED), // This will kill all hostile in all the dimensions + COMMAND_PURGE_CHUNKS_DIM(PRIVILEGED), // This will purge the chunks in the dim given as argument + COMMAND_PURGE_CHUNKS_ALL(PRIVILEGED), // This will purge the chunks in all dimensions + COMMAND_KILL_STACKS_DIM(PRIVILEGED), // This will kill all stacks in the dim given as argument + COMMAND_KILL_STACKS_ALL(PRIVILEGED), // This will kill all stacks in all the dimensions - public void setAccessLevel(AccessLevel level){ - this.accessLevel = level; - } - - public boolean canPlayerUseCommand(EntityPlayerMP player){ - return PlayerTracker.INSTANCE.getPlayerAccessLevel(player).ordinal() >= this.accessLevel.ordinal(); - } - - public boolean isDisplayActive(SelectedTab tab){ - if (tab == SelectedTab.ALL) return true; - if (this.tabEnum.contains(SelectedTab.ANY)) return true; - if (this.tabEnum.contains(SelectedTab.NONE)) return false; - if (this.tabEnum.contains(tab)) return true; - return false; - } - - public static void setTablesMinimumLevel(AccessLevel level){ - Message.LIST_CHUNK_LOADED.setAccessLevel(level); - Message.LIST_TIMING_TILEENTS.setAccessLevel(level); - Message.LIST_TIMING_ENTITIES.setAccessLevel(level); - Message.LIST_TIMING_HANDLERS.setAccessLevel(level); - Message.LIST_TIMING_CHUNK.setAccessLevel(level); - Message.LIST_TIMING_TILEENTS_PER_CLASS.setAccessLevel(level); - Message.LIST_TIMING_ENTITIES_PER_CLASS.setAccessLevel(level); - Message.LIST_TIMING_HANDLERS.setAccessLevel(level); - Message.LIST_TIMING_EVENTS.setAccessLevel(level); - Message.LIST_AMOUNT_ENTITIES.setAccessLevel(level); - Message.LIST_AMOUNT_TILEENTS.setAccessLevel(level); - Message.LIST_PLAYERS.setAccessLevel(level); - Message.LIST_DIMENSION_DATA.setAccessLevel(level); - Message.LIST_PACKETS_OUTBOUND.setAccessLevel(level); - Message.LIST_PACKETS_INBOUND.setAccessLevel(level); - Message.LIST_PACKETS_OUTBOUND_250.setAccessLevel(level); - Message.LIST_PACKETS_INBOUND_250.setAccessLevel(level); - Message.LIST_ORPHAN_TILEENTS.setAccessLevel(level); - Message.LIST_THREADS.setAccessLevel(level); - } + CLIENT_START_PROFILING, + CLIENT_STOP_PROFILING, + CLIENT_RESET_PROFILING, + CLIENT_SHOW_RENDER_TICK, + CLIENT_SHOW_SWING, + CLIENT_CLEAR_SELECTION, + CLIENT_HIGHLIGHT_BLOCK, - public static void setOpisMinimumLevel(AccessLevel level){ - Message.COMMAND_OPEN_SWING.setAccessLevel(level); - } + SWING_TAB_CHANGED, + NEXUS_UUID, // Login data for the nexus system + NEXUS_DATA, // Data blob with everything needed to update the summary screen in realtime + PLAYER_STATUS_UPDATE, // Update for the players (name, position, offline/online, etc) + CONNECTION_STATUS, + + CHAT_MSG; + + private AccessLevel accessLevel = AccessLevel.NONE; + private EnumSet tabEnum; + + private Message() { + accessLevel = AccessLevel.NONE; + tabEnum = EnumSet.of(SelectedTab.ANY); + } + + private Message(AccessLevel level) { + accessLevel = level; + tabEnum = EnumSet.of(SelectedTab.ANY); + } + + private Message(EnumSet _tabEnum) { + accessLevel = AccessLevel.NONE; + tabEnum = _tabEnum; + } + + private Message(AccessLevel level, EnumSet _tabEnum) { + accessLevel = level; + tabEnum = _tabEnum; + } + + public AccessLevel getAccessLevel() { + return this.accessLevel; + } + + public void setAccessLevel(AccessLevel level) { + this.accessLevel = level; + } + + public boolean canPlayerUseCommand(EntityPlayerMP player) { + return PlayerTracker.INSTANCE.getPlayerAccessLevel(player).ordinal() >= this.accessLevel.ordinal(); + } + + public boolean isDisplayActive(SelectedTab tab) { + if (tab == SelectedTab.ALL) return true; + if (this.tabEnum.contains(SelectedTab.ANY)) return true; + if (this.tabEnum.contains(SelectedTab.NONE)) return false; + if (this.tabEnum.contains(tab)) return true; + return false; + } + + public static void setTablesMinimumLevel(AccessLevel level) { + Message.LIST_CHUNK_LOADED.setAccessLevel(level); + Message.LIST_TIMING_TILEENTS.setAccessLevel(level); + Message.LIST_TIMING_ENTITIES.setAccessLevel(level); + Message.LIST_TIMING_HANDLERS.setAccessLevel(level); + Message.LIST_TIMING_CHUNK.setAccessLevel(level); + Message.LIST_TIMING_TILEENTS_PER_CLASS.setAccessLevel(level); + Message.LIST_TIMING_ENTITIES_PER_CLASS.setAccessLevel(level); + Message.LIST_TIMING_HANDLERS.setAccessLevel(level); + Message.LIST_TIMING_EVENTS.setAccessLevel(level); + Message.LIST_AMOUNT_ENTITIES.setAccessLevel(level); + Message.LIST_AMOUNT_TILEENTS.setAccessLevel(level); + Message.LIST_PLAYERS.setAccessLevel(level); + Message.LIST_DIMENSION_DATA.setAccessLevel(level); + Message.LIST_PACKETS_OUTBOUND.setAccessLevel(level); + Message.LIST_PACKETS_INBOUND.setAccessLevel(level); + Message.LIST_PACKETS_OUTBOUND_250.setAccessLevel(level); + Message.LIST_PACKETS_INBOUND_250.setAccessLevel(level); + Message.LIST_ORPHAN_TILEENTS.setAccessLevel(level); + Message.LIST_THREADS.setAccessLevel(level); + } + + public static void setOpisMinimumLevel(AccessLevel level) { + Message.COMMAND_OPEN_SWING.setAccessLevel(level); + } } diff --git a/src/main/java/mcp/mobius/opis/network/enums/PlayerEv.java b/src/main/java/mcp/mobius/opis/network/enums/PlayerEv.java index b181966..6d8fdd1 100644 --- a/src/main/java/mcp/mobius/opis/network/enums/PlayerEv.java +++ b/src/main/java/mcp/mobius/opis/network/enums/PlayerEv.java @@ -1,11 +1,11 @@ package mcp.mobius.opis.network.enums; public enum PlayerEv { - LOGOUT, - LOGIN, - DEATH, - ONLINE, + LOGOUT, + LOGIN, + DEATH, + ONLINE, SERVERSTART, - SERVERSTOP, - NONE; + SERVERSTOP, + NONE; } diff --git a/src/main/java/mcp/mobius/opis/network/packets/client/PacketReqChunks.java b/src/main/java/mcp/mobius/opis/network/packets/client/PacketReqChunks.java index c021f47..873c8cf 100644 --- a/src/main/java/mcp/mobius/opis/network/packets/client/PacketReqChunks.java +++ b/src/main/java/mcp/mobius/opis/network/packets/client/PacketReqChunks.java @@ -1,71 +1,61 @@ package mcp.mobius.opis.network.packets.client; -import java.util.ArrayList; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - +import java.util.ArrayList; import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; import mcp.mobius.opis.events.PlayerTracker; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.AccessLevel; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; -public class PacketReqChunks extends PacketBase{ +public class PacketReqChunks extends PacketBase { - public int dim; - public ArrayList chunks = new ArrayList(); - - public PacketReqChunks() - { + public int dim; + public ArrayList chunks = new ArrayList(); + + public PacketReqChunks() {} + + public PacketReqChunks(int dim, ArrayList chunks) { + this.dim = dim; + this.chunks = chunks; } - public PacketReqChunks(int dim, ArrayList chunks) - { - this.dim = dim; - this.chunks = chunks; - } - - @Override - public void encode(ByteArrayDataOutput output) { - output.writeInt(dim); - output.writeInt(chunks.size()); - for(CoordinatesChunk coord : chunks) - coord.writeToStream(output); - } + @Override + public void encode(ByteArrayDataOutput output) { + output.writeInt(dim); + output.writeInt(chunks.size()); + for (CoordinatesChunk coord : chunks) coord.writeToStream(output); + } - @Override - public void decode(ByteArrayDataInput input) { - dim = input.readInt(); - int nchunks = input.readInt(); - for (int i = 0; i < nchunks; i++) - chunks.add(CoordinatesChunk.readFromStream(input)); - } + @Override + public void decode(ByteArrayDataInput input) { + dim = input.readInt(); + int nchunks = input.readInt(); + for (int i = 0; i < nchunks; i++) chunks.add(CoordinatesChunk.readFromStream(input)); + } - @Override - public void actionServer(World world, EntityPlayerMP player) { - if (PlayerTracker.INSTANCE.getPlayerAccessLevel(player).ordinal() > AccessLevel.PRIVILEGED.ordinal()){ - ArrayList list = new ArrayList(); - - if (world != null){ - for (CoordinatesChunk chunk : chunks) - list.add(world.getChunkFromChunkCoords(chunk.chunkX, chunk.chunkZ)); - - //if (!list.isEmpty()){ - // Packet_Chunks.send(castedPacket.dim, !world.provider.hasNoSky, list, player); - - - /* - Packet250CustomPayload chunkPacket = Packet_Chunks.create(castedPacket.dim, !world.provider.hasNoSky, list); - if (chunkPacket != null) - PacketDispatcher.sendPacketToPlayer( chunkPacket, player); - */ - //} - } - } - - } + @Override + public void actionServer(World world, EntityPlayerMP player) { + if (PlayerTracker.INSTANCE.getPlayerAccessLevel(player).ordinal() > AccessLevel.PRIVILEGED.ordinal()) { + ArrayList list = new ArrayList(); + if (world != null) { + for (CoordinatesChunk chunk : chunks) + list.add(world.getChunkFromChunkCoords(chunk.chunkX, chunk.chunkZ)); + + // if (!list.isEmpty()){ + // Packet_Chunks.send(castedPacket.dim, !world.provider.hasNoSky, list, player); + + /* + Packet250CustomPayload chunkPacket = Packet_Chunks.create(castedPacket.dim, !world.provider.hasNoSky, list); + if (chunkPacket != null) + PacketDispatcher.sendPacketToPlayer( chunkPacket, player); + */ + // } + } + } + } } diff --git a/src/main/java/mcp/mobius/opis/network/packets/client/PacketReqData.java b/src/main/java/mcp/mobius/opis/network/packets/client/PacketReqData.java index 4cd19bb..be96e6a 100644 --- a/src/main/java/mcp/mobius/opis/network/packets/client/PacketReqData.java +++ b/src/main/java/mcp/mobius/opis/network/packets/client/PacketReqData.java @@ -1,6 +1,7 @@ package mcp.mobius.opis.network.packets.client; -import mcp.mobius.opis.modOpis; +import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteArrayDataOutput; import mcp.mobius.opis.data.holders.DataType; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.network.PacketBase; @@ -9,79 +10,77 @@ import mcp.mobius.opis.network.enums.Message; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.world.World; -import com.google.common.io.ByteArrayDataInput; -import com.google.common.io.ByteArrayDataOutput; +public class PacketReqData extends PacketBase { -public class PacketReqData extends PacketBase{ + public Message dataReq; + public ISerializable param1 = null; + public ISerializable param2 = null; - public Message dataReq; - public ISerializable param1 = null; - public ISerializable param2 = null; - - public PacketReqData(){} + public PacketReqData() {} public PacketReqData(Message dataReq) { - this(dataReq, null, null); - } - + this(dataReq, null, null); + } + public PacketReqData(Message dataReq, ISerializable param1) { - this(dataReq, param1, null); - } - + this(dataReq, param1, null); + } + public PacketReqData(Message dataReq, ISerializable param1, ISerializable param2) { - this.dataReq = dataReq; - this.param1 = param1; - this.param2 = param2; - } - - @Override - public void encode(ByteArrayDataOutput output) { - output.writeInt(dataReq.ordinal()); - - if (param1 != null){ - output.writeBoolean(true); - output.writeInt(DataType.getForClass(param1.getClass()).ordinal()); - param1.writeToStream(output); - } else { - output.writeBoolean(false); - } - - if (param2 != null){ - output.writeBoolean(true); - output.writeInt(DataType.getForClass(param2.getClass()).ordinal()); - param2.writeToStream(output); - } else { - output.writeBoolean(false); - } - } + this.dataReq = dataReq; + this.param1 = param1; + this.param2 = param2; + } - @Override - public void decode(ByteArrayDataInput input) { - this.dataReq = Message.values()[input.readInt()]; - - if (input.readBoolean()){ - Class datatype = DataType.getForOrdinal(input.readInt()); - this.param1 = dataRead(datatype, input); - } - - if (input.readBoolean()){ - Class datatype = DataType.getForOrdinal(input.readInt()); - this.param2 = dataRead(datatype, input); - } - - } + @Override + public void encode(ByteArrayDataOutput output) { + output.writeInt(dataReq.ordinal()); - @Override - public void actionServer(World world, EntityPlayerMP player) { - String logmsg = String.format("Received request %s from player %s ... ", this.dataReq, player.getGameProfile().getName()); - - if (this.dataReq.canPlayerUseCommand(player)){ - logmsg += "Accepted"; - ServerMessageHandler.instance().handle(this.dataReq, this.param1, this.param2, player); - } else { - logmsg += "Rejected"; - } - - //modOpis.log.info(logmsg); - } + if (param1 != null) { + output.writeBoolean(true); + output.writeInt(DataType.getForClass(param1.getClass()).ordinal()); + param1.writeToStream(output); + } else { + output.writeBoolean(false); + } + + if (param2 != null) { + output.writeBoolean(true); + output.writeInt(DataType.getForClass(param2.getClass()).ordinal()); + param2.writeToStream(output); + } else { + output.writeBoolean(false); + } + } + + @Override + public void decode(ByteArrayDataInput input) { + this.dataReq = Message.values()[input.readInt()]; + + if (input.readBoolean()) { + Class datatype = DataType.getForOrdinal(input.readInt()); + this.param1 = dataRead(datatype, input); + } + + if (input.readBoolean()) { + Class datatype = DataType.getForOrdinal(input.readInt()); + this.param2 = dataRead(datatype, input); + } + } + + @Override + public void actionServer(World world, EntityPlayerMP player) { + String logmsg = String.format( + "Received request %s from player %s ... ", + this.dataReq, player.getGameProfile().getName()); + + if (this.dataReq.canPlayerUseCommand(player)) { + logmsg += "Accepted"; + ServerMessageHandler.instance().handle(this.dataReq, this.param1, this.param2, player); + } else { + logmsg += "Rejected"; + } + + // modOpis.log.info(logmsg); + } } diff --git a/src/main/java/mcp/mobius/opis/network/packets/server/NetDataCommand.java b/src/main/java/mcp/mobius/opis/network/packets/server/NetDataCommand.java index 347e915..9e2a140 100644 --- a/src/main/java/mcp/mobius/opis/network/packets/server/NetDataCommand.java +++ b/src/main/java/mcp/mobius/opis/network/packets/server/NetDataCommand.java @@ -1,39 +1,38 @@ package mcp.mobius.opis.network.packets.server; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import mcp.mobius.opis.api.MessageHandlerRegistrar; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; public class NetDataCommand extends PacketBase { - public NetDataCommand(){}; - - public NetDataCommand(Message msg){ - this.msg = msg; - }; - - @Override - public void encode(ByteArrayDataOutput output) { - output.writeInt(this.msg.ordinal()); - } + public NetDataCommand() {} + ; - @Override - public void decode(ByteArrayDataInput input) { - this.msg = Message.values()[input.readInt()]; - } + public NetDataCommand(Message msg) { + this.msg = msg; + } + ; @Override - @SideOnly(Side.CLIENT) - public void actionClient(World world, EntityPlayer player){ - MessageHandlerRegistrar.INSTANCE.routeMessage(this.msg, this); - } - + public void encode(ByteArrayDataOutput output) { + output.writeInt(this.msg.ordinal()); + } + + @Override + public void decode(ByteArrayDataInput input) { + this.msg = Message.values()[input.readInt()]; + } + + @Override + @SideOnly(Side.CLIENT) + public void actionClient(World world, EntityPlayer player) { + MessageHandlerRegistrar.INSTANCE.routeMessage(this.msg, this); + } } diff --git a/src/main/java/mcp/mobius/opis/network/packets/server/NetDataList.java b/src/main/java/mcp/mobius/opis/network/packets/server/NetDataList.java index f9f5ea0..37236ca 100644 --- a/src/main/java/mcp/mobius/opis/network/packets/server/NetDataList.java +++ b/src/main/java/mcp/mobius/opis/network/packets/server/NetDataList.java @@ -1,63 +1,57 @@ package mcp.mobius.opis.network.packets.server; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import mcp.mobius.opis.api.MessageHandlerRegistrar; import mcp.mobius.opis.data.holders.DataType; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; public class NetDataList extends PacketBase { - public NetDataList(){} - - public NetDataList(Message msg, List data) { - this.msg = msg; - this.array = new ArrayList(data); - } - - @Override - public void encode(ByteArrayDataOutput output) { - output.writeInt(this.msg.ordinal()); - output.writeInt(this.array.size()); - - if (this.array.size() > 0) - //Packet.writeString(data.get(0).getClass().getCanonicalName(), ostream); - output.writeInt(DataType.getForClass(this.array.get(0).getClass()).ordinal()); - - for (ISerializable odata : this.array) - odata.writeToStream(output); - } + public NetDataList() {} - @Override - public void decode(ByteArrayDataInput input) { - this.msg = Message.values()[input.readInt()]; - int ndata = input.readInt(); - this.clazzStr = ""; - if (ndata > 0){ - this.clazz = DataType.getForOrdinal(input.readInt()); - } - - this.array = new ArrayList(); - - for (int i = 0; i < ndata; i++) - this.array.add(dataRead(this.clazz, input)); - } + public NetDataList(Message msg, List data) { + this.msg = msg; + this.array = new ArrayList(data); + } @Override - @SideOnly(Side.CLIENT) - public void actionClient(World world, EntityPlayer player){ - MessageHandlerRegistrar.INSTANCE.routeMessage(this.msg, this); - } - + public void encode(ByteArrayDataOutput output) { + output.writeInt(this.msg.ordinal()); + output.writeInt(this.array.size()); + + if (this.array.size() > 0) + // Packet.writeString(data.get(0).getClass().getCanonicalName(), ostream); + output.writeInt(DataType.getForClass(this.array.get(0).getClass()).ordinal()); + + for (ISerializable odata : this.array) odata.writeToStream(output); + } + + @Override + public void decode(ByteArrayDataInput input) { + this.msg = Message.values()[input.readInt()]; + int ndata = input.readInt(); + this.clazzStr = ""; + if (ndata > 0) { + this.clazz = DataType.getForOrdinal(input.readInt()); + } + + this.array = new ArrayList(); + + for (int i = 0; i < ndata; i++) this.array.add(dataRead(this.clazz, input)); + } + + @Override + @SideOnly(Side.CLIENT) + public void actionClient(World world, EntityPlayer player) { + MessageHandlerRegistrar.INSTANCE.routeMessage(this.msg, this); + } } diff --git a/src/main/java/mcp/mobius/opis/network/packets/server/NetDataValue.java b/src/main/java/mcp/mobius/opis/network/packets/server/NetDataValue.java index 495bb8b..91daa61 100644 --- a/src/main/java/mcp/mobius/opis/network/packets/server/NetDataValue.java +++ b/src/main/java/mcp/mobius/opis/network/packets/server/NetDataValue.java @@ -1,11 +1,7 @@ package mcp.mobius.opis.network.packets.server; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; - import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import mcp.mobius.opis.api.MessageHandlerRegistrar; @@ -13,35 +9,35 @@ import mcp.mobius.opis.data.holders.DataType; import mcp.mobius.opis.data.holders.ISerializable; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; public class NetDataValue extends PacketBase { - public NetDataValue(){} - - public NetDataValue(Message msg, ISerializable data) { - this.msg = msg; - this.value = data; - } - - @Override - public void encode(ByteArrayDataOutput output) { - output.writeInt(this.msg.ordinal()); - output.writeInt(DataType.getForClass(this.value.getClass()).ordinal()); - this.value.writeToStream(output); - } + public NetDataValue() {} - @Override - public void decode(ByteArrayDataInput input) { - this.msg = Message.values()[input.readInt()]; - this.clazz = DataType.getForOrdinal(input.readInt()); - this.value = dataRead(this.clazz, input); - - } + public NetDataValue(Message msg, ISerializable data) { + this.msg = msg; + this.value = data; + } @Override - @SideOnly(Side.CLIENT) - public void actionClient(World world, EntityPlayer player){ - MessageHandlerRegistrar.INSTANCE.routeMessage(this.msg, this); - } - + public void encode(ByteArrayDataOutput output) { + output.writeInt(this.msg.ordinal()); + output.writeInt(DataType.getForClass(this.value.getClass()).ordinal()); + this.value.writeToStream(output); + } + + @Override + public void decode(ByteArrayDataInput input) { + this.msg = Message.values()[input.readInt()]; + this.clazz = DataType.getForOrdinal(input.readInt()); + this.value = dataRead(this.clazz, input); + } + + @Override + @SideOnly(Side.CLIENT) + public void actionClient(World world, EntityPlayer player) { + MessageHandlerRegistrar.INSTANCE.routeMessage(this.msg, this); + } } diff --git a/src/main/java/mcp/mobius/opis/network/rcon/RConHandler.java b/src/main/java/mcp/mobius/opis/network/rcon/RConHandler.java index 0280a75..19b53e1 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/RConHandler.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/RConHandler.java @@ -8,6 +8,9 @@ import io.nettyopis.buffer.ByteBuf; import io.nettyopis.channel.ChannelFuture; import io.nettyopis.channel.ChannelFutureListener; import io.nettyopis.channel.ChannelHandlerContext; +import java.io.IOException; +import java.lang.ref.WeakReference; +import java.net.ConnectException; import mcp.mobius.opis.events.PlayerTracker; import mcp.mobius.opis.modOpis; import mcp.mobius.opis.network.PacketBase; @@ -20,120 +23,108 @@ import mcp.mobius.opis.network.rcon.nexus.NexusClient; import mcp.mobius.opis.network.rcon.nexus.NexusInboundHandler; import net.minecraftforge.common.util.FakePlayer; -import java.io.IOException; -import java.lang.ref.WeakReference; -import java.net.ConnectException; - public class RConHandler { - public static BiMap packetTypes = HashBiMap.create(); - public static BiMap fakePlayersRcon = HashBiMap.create(); - public static BiMap fakePlayersNexus = HashBiMap.create(); - - public static String lastError = null; - public static WeakReference lastContext = null; - - static { - packetTypes.put((byte)0, PacketReqChunks.class); - packetTypes.put((byte)1, PacketReqData.class); - packetTypes.put((byte)2, NetDataCommand.class); - packetTypes.put((byte)3, NetDataList.class); - packetTypes.put((byte)4, NetDataValue.class); - } + public static BiMap packetTypes = HashBiMap.create(); + public static BiMap fakePlayersRcon = HashBiMap.create(); + public static BiMap fakePlayersNexus = HashBiMap.create(); - public static void sendToAllNexus(PacketBase packet){ - for (FakePlayer player : fakePlayersNexus.keySet()) - sendToPlayerNexus(packet, player); - } - - public static void sendToAllRCon(PacketBase packet){ - for (FakePlayer player : fakePlayersRcon.keySet()) - sendToPlayerRCon(packet, player); - } - - public static void sendToPlayerNexus(PacketBase packet, FakePlayer player) - { - ChannelHandlerContext ctx = RConHandler.fakePlayersNexus.get(player); - NexusInboundHandler hnd = ctx.pipeline().get(NexusInboundHandler.class); + public static String lastError = null; + public static WeakReference lastContext = null; - if (hnd != null && hnd.timers.isDone(packet.msg)) - sendToContext(packet, ctx); - } - - public static void sendToPlayerRCon(PacketBase packet, FakePlayer player) - { - ChannelHandlerContext ctx = RConHandler.fakePlayersRcon.get(player); - sendToContext(packet, ctx); + static { + packetTypes.put((byte) 0, PacketReqChunks.class); + packetTypes.put((byte) 1, PacketReqData.class); + packetTypes.put((byte) 2, NetDataCommand.class); + packetTypes.put((byte) 3, NetDataList.class); + packetTypes.put((byte) 4, NetDataValue.class); } - - public static void sendToContext(PacketBase packet, final ChannelHandlerContext ctx){ - //modOpis.log.info(String.format("%s", packet.msg)); - - - ByteArrayDataOutput output = ByteStreams.newDataOutput(); - packet.encode(output); - byte[] data = output.toByteArray(); - - ByteBuf buf = ctx.alloc().buffer(data.length + 4 + 1); - buf.writeInt(data.length); - buf.writeByte(RConHandler.packetTypes.inverse().get(packet.getClass())); - buf.writeBytes(data); - ChannelFuture f = ctx.writeAndFlush(buf); - f.addListener(new ChannelFutureListener(){ - @Override - public void operationComplete(ChannelFuture arg0) throws Exception { - if (arg0.cause() != null){ - RConHandler.exceptionCaught(ctx, arg0.cause()); - } - } - }); - - //modOpis.log.info(String.format("%s", packet.msg)); - } - - public static boolean isPriviledge(FakePlayer player){ - return fakePlayersRcon.containsKey(player) || fakePlayersNexus.containsKey(player); + + public static void sendToAllNexus(PacketBase packet) { + for (FakePlayer player : fakePlayersNexus.keySet()) sendToPlayerNexus(packet, player); } - + + public static void sendToAllRCon(PacketBase packet) { + for (FakePlayer player : fakePlayersRcon.keySet()) sendToPlayerRCon(packet, player); + } + + public static void sendToPlayerNexus(PacketBase packet, FakePlayer player) { + ChannelHandlerContext ctx = RConHandler.fakePlayersNexus.get(player); + NexusInboundHandler hnd = ctx.pipeline().get(NexusInboundHandler.class); + + if (hnd != null && hnd.timers.isDone(packet.msg)) sendToContext(packet, ctx); + } + + public static void sendToPlayerRCon(PacketBase packet, FakePlayer player) { + ChannelHandlerContext ctx = RConHandler.fakePlayersRcon.get(player); + sendToContext(packet, ctx); + } + + public static void sendToContext(PacketBase packet, final ChannelHandlerContext ctx) { + // modOpis.log.info(String.format("%s", packet.msg)); + + ByteArrayDataOutput output = ByteStreams.newDataOutput(); + packet.encode(output); + byte[] data = output.toByteArray(); + + ByteBuf buf = ctx.alloc().buffer(data.length + 4 + 1); + buf.writeInt(data.length); + buf.writeByte(RConHandler.packetTypes.inverse().get(packet.getClass())); + buf.writeBytes(data); + ChannelFuture f = ctx.writeAndFlush(buf); + f.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture arg0) throws Exception { + if (arg0.cause() != null) { + RConHandler.exceptionCaught(ctx, arg0.cause()); + } + } + }); + + // modOpis.log.info(String.format("%s", packet.msg)); + } + + public static boolean isPriviledge(FakePlayer player) { + return fakePlayersRcon.containsKey(player) || fakePlayersNexus.containsKey(player); + } + public static void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - if (cause.getMessage().equals(RConHandler.lastError) && ctx.equals(RConHandler.lastContext.get())) - return; - - RConHandler.lastError = cause.getMessage(); - RConHandler.lastContext = new WeakReference(ctx); - - if (cause instanceof IOException && cause.getMessage().contains("Connection reset by peer")){ - modOpis.log.warn("HydraOpis : Connection reset by peer"); - } else if (cause instanceof ConnectException && cause.getMessage().contains("Connection refused")){ - modOpis.log.warn("HydraOpis : Connection refused by remote server. Server is down ?"); - } else { - modOpis.log.info(String.format("%s | %s", cause.getClass().getCanonicalName(), cause.getMessage())); - cause.printStackTrace(); - } - - FakePlayer fakePlayer = null; - - if (RConHandler.fakePlayersNexus.inverse().containsKey(ctx)){ - fakePlayer = RConHandler.fakePlayersNexus.inverse().get(ctx); - RConHandler.fakePlayersNexus.remove(fakePlayer); - } - - if (RConHandler.fakePlayersRcon.inverse().containsKey(ctx)){ - fakePlayer = RConHandler.fakePlayersRcon.inverse().get(ctx); - RConHandler.fakePlayersRcon.remove(fakePlayer); - } - - if (fakePlayer != null){ - PlayerTracker.INSTANCE.playersSwing.remove(fakePlayer); - modOpis.log.info(String.format("Lost connection from %s", fakePlayer.getDisplayName())); + if (cause.getMessage().equals(RConHandler.lastError) && ctx.equals(RConHandler.lastContext.get())) return; + + RConHandler.lastError = cause.getMessage(); + RConHandler.lastContext = new WeakReference(ctx); + + if (cause instanceof IOException && cause.getMessage().contains("Connection reset by peer")) { + modOpis.log.warn("HydraOpis : Connection reset by peer"); + } else if (cause instanceof ConnectException && cause.getMessage().contains("Connection refused")) { + modOpis.log.warn("HydraOpis : Connection refused by remote server. Server is down ?"); } else { - modOpis.log.info(String.format("Lost connection")); + modOpis.log.info(String.format("%s | %s", cause.getClass().getCanonicalName(), cause.getMessage())); + cause.printStackTrace(); } - - if (NexusClient.instance.ctx.get().equals(ctx)){ - NexusClient.instance.reconnect = true; + + FakePlayer fakePlayer = null; + + if (RConHandler.fakePlayersNexus.inverse().containsKey(ctx)) { + fakePlayer = RConHandler.fakePlayersNexus.inverse().get(ctx); + RConHandler.fakePlayersNexus.remove(fakePlayer); } - + + if (RConHandler.fakePlayersRcon.inverse().containsKey(ctx)) { + fakePlayer = RConHandler.fakePlayersRcon.inverse().get(ctx); + RConHandler.fakePlayersRcon.remove(fakePlayer); + } + + if (fakePlayer != null) { + PlayerTracker.INSTANCE.playersSwing.remove(fakePlayer); + modOpis.log.info(String.format("Lost connection from %s", fakePlayer.getDisplayName())); + } else { + modOpis.log.info(String.format("Lost connection")); + } + + if (NexusClient.instance.ctx.get().equals(ctx)) { + NexusClient.instance.reconnect = true; + } + ctx.close(); - } - + } } diff --git a/src/main/java/mcp/mobius/opis/network/rcon/nexus/EventTimerRing.java b/src/main/java/mcp/mobius/opis/network/rcon/nexus/EventTimerRing.java index 6e13050..82a099c 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/nexus/EventTimerRing.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/nexus/EventTimerRing.java @@ -7,7 +7,6 @@ import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; - import mcp.mobius.opis.events.EventTimer; import mcp.mobius.opis.network.enums.Message; @@ -15,38 +14,38 @@ public class EventTimerRing { Map ring = new HashMap(); Properties prop; - public EventTimerRing(){ - ring.put(Message.NEXUS_UUID, new EventTimer(0)); + public EventTimerRing() { + ring.put(Message.NEXUS_UUID, new EventTimer(0)); } - - public EventTimerRing(String config){ + + public EventTimerRing(String config) { this.prop = readConfig(config); for (Object o : prop.keySet()) { - String msg = (String)o; + String msg = (String) o; ring.put(Message.valueOf(msg), new EventTimer(Long.valueOf(prop.getProperty(msg)))); } } - public EventTimerRing(Properties prop){ + public EventTimerRing(Properties prop) { this.prop = prop; for (Object o : prop.keySet()) { - String msg = (String)o; + String msg = (String) o; ring.put(Message.valueOf(msg), new EventTimer(Long.valueOf(prop.getProperty(msg)))); } } - public boolean isDone(Message msg){ + public boolean isDone(Message msg) { if (!ring.containsKey(msg)) return false; return ring.get(msg).isDone(); } - public Properties getProp(){ + public Properties getProp() { return this.prop; } - private Properties readConfig(String filename){ + private Properties readConfig(String filename) { Properties prop = new Properties(); InputStream input = null; diff --git a/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusClient.java b/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusClient.java index bdda225..81ebb9d 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusClient.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusClient.java @@ -7,85 +7,84 @@ import io.nettyopis.channel.socket.SocketChannel; import io.nettyopis.channel.socket.nio.NioSocketChannel; import io.nettyopis.handler.ssl.SslContext; import io.nettyopis.handler.ssl.util.InsecureTrustManagerFactory; -import mcp.mobius.opis.modOpis; - -import javax.net.ssl.SSLException; import java.io.*; import java.lang.ref.WeakReference; import java.net.ConnectException; import java.util.Properties; +import javax.net.ssl.SSLException; +import mcp.mobius.opis.modOpis; public class NexusClient implements Runnable { - class ChannelInit extends ChannelInitializer{ + class ChannelInit extends ChannelInitializer { private final SslContext sslCtx; - public ChannelInit(SslContext sslCtx) { this.sslCtx = sslCtx; } + + public ChannelInit(SslContext sslCtx) { + this.sslCtx = sslCtx; + } @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), NexusClient.instance.host, NexusClient.instance.port)); - //ch.pipeline().addLast(new ReadTimeoutHandler(10)); + // ch.pipeline().addLast(new ReadTimeoutHandler(10)); ch.pipeline().addLast(new NexusHandshakeDecoder()); ch.pipeline().addLast(new NexusHandshakeHandler()); - //ch.pipeline().addLast(new JdkZlibDecoder()); - //ch.pipeline().addLast(new JdkZlibEncoder()); - //ch.pipeline().addLast(new WriteTimeoutHandler(5)); - - //ch.pipeline().addLast(new NexusMsgDecoder()); - //ch.pipeline().addLast(new NexusInboundHandler()); - } - } - - String reverseprop = "opis.properties"; - - String host = "localhost"; - String uuid = ""; - String pass = ""; - Integer port = 8013; - Boolean active = false; - public boolean reconnect = false; - public boolean shouldRetry = true; - public WeakReference ctx; - - public final static NexusClient instance = new NexusClient(); - - private NexusClient(){} - - @Override - public void run(){ - this.readConfig(this.reverseprop); - if (!this.active) return; - if (this.uuid.equals("")){ - modOpis.log.error("UUID not set properly."); - return; - } - - while (this.connect()){ - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }; - - - } + // ch.pipeline().addLast(new JdkZlibDecoder()); + // ch.pipeline().addLast(new JdkZlibEncoder()); + // ch.pipeline().addLast(new WriteTimeoutHandler(5)); + + // ch.pipeline().addLast(new NexusMsgDecoder()); + // ch.pipeline().addLast(new NexusInboundHandler()); + } + } + + String reverseprop = "opis.properties"; + + String host = "localhost"; + String uuid = ""; + String pass = ""; + Integer port = 8013; + Boolean active = false; + public boolean reconnect = false; + public boolean shouldRetry = true; + public WeakReference ctx; + + public static final NexusClient instance = new NexusClient(); + + private NexusClient() {} + + @Override + public void run() { + this.readConfig(this.reverseprop); + if (!this.active) return; + if (this.uuid.equals("")) { + modOpis.log.error("UUID not set properly."); + return; + } + + while (this.connect()) { + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + ; + } + + private boolean connect() { + if (this.reconnect) modOpis.log.info(String.format("Reconnecting to HydraOpis %s:%s", this.host, this.port)); + else modOpis.log.info(String.format("Connecting to HydraOpis %s:%s", this.host, this.port)); - private boolean connect(){ - if (this.reconnect) - modOpis.log.info(String.format("Reconnecting to HydraOpis %s:%s", this.host, this.port)); - else - modOpis.log.info(String.format("Connecting to HydraOpis %s:%s", this.host, this.port)); - SslContext sslCtx = null; try { - sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); + sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } catch (SSLException e) { - this.handleException(e); - } - + this.handleException(e); + } + EventLoopGroup workerGroup = new NioEventLoopGroup(); - + try { Bootstrap b = new Bootstrap(); // (1) b.group(workerGroup); // (2) @@ -96,27 +95,26 @@ public class NexusClient implements Runnable { // Wait until the connection is closed. f.channel().closeFuture().sync(); - } catch (Exception e){ - this.handleException(e); + } catch (Exception e) { + this.handleException(e); } finally { workerGroup.shutdownGracefully(); - } - + } + return this.shouldRetry; } - - private void handleException(Throwable cause){ - if (cause instanceof ConnectException && cause.getMessage().contains("Connection refused")){ - modOpis.log.warn("HydraOpis : Connection refused by remote server. Server is down ?"); - } else { - modOpis.log.error("Error while connecting to Nexus Server"); - cause.printStackTrace(); - } + + private void handleException(Throwable cause) { + if (cause instanceof ConnectException && cause.getMessage().contains("Connection refused")) { + modOpis.log.warn("HydraOpis : Connection refused by remote server. Server is down ?"); + } else { + modOpis.log.error("Error while connecting to Nexus Server"); + cause.printStackTrace(); + } } - - private void readConfig(String filename){ - if (!new File(filename).exists()) - writeConfig(filename); + + private void readConfig(String filename) { + if (!new File(filename).exists()) writeConfig(filename); Properties prop = new Properties(); InputStream input = null; @@ -131,26 +129,26 @@ public class NexusClient implements Runnable { } catch (IOException e) { e.printStackTrace(); } - - this.host = prop.getProperty("host"); - this.port = Integer.valueOf(prop.getProperty("port")); + + this.host = prop.getProperty("host"); + this.port = Integer.valueOf(prop.getProperty("port")); this.active = Boolean.valueOf(prop.getProperty("active")); - this.uuid = prop.getProperty("uuid"); - this.pass = prop.getProperty("passphrase"); + this.uuid = prop.getProperty("uuid"); + this.pass = prop.getProperty("passphrase"); } - - private void writeConfig(String filename){ - Properties prop = new Properties(); + + private void writeConfig(String filename) { + Properties prop = new Properties(); OutputStream output = null; try { output = new FileOutputStream(filename); - prop.setProperty("host", host); - prop.setProperty("port", this.port.toString()); + prop.setProperty("host", host); + prop.setProperty("port", this.port.toString()); prop.setProperty("active", this.active.toString()); - prop.setProperty("uuid", this.uuid); - prop.setProperty("passphrase", this.pass); + prop.setProperty("uuid", this.uuid); + prop.setProperty("passphrase", this.pass); prop.store(output, null); output.close(); @@ -160,6 +158,5 @@ public class NexusClient implements Runnable { } catch (IOException e) { e.printStackTrace(); } - } - + } } diff --git a/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusHandshakeDecoder.java b/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusHandshakeDecoder.java index 7388f5f..53f8455 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusHandshakeDecoder.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusHandshakeDecoder.java @@ -1,17 +1,17 @@ package mcp.mobius.opis.network.rcon.nexus; -import java.util.List; - import io.nettyopis.buffer.ByteBuf; import io.nettyopis.channel.ChannelHandlerContext; import io.nettyopis.handler.codec.ByteToMessageDecoder; +import java.util.List; public class NexusHandshakeDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { - if (in.readableBytes() < 1) { return; } + if (in.readableBytes() < 1) { + return; + } out.add(in.readBoolean()); } - } diff --git a/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusHandshakeHandler.java b/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusHandshakeHandler.java index 592e822..1134c29 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusHandshakeHandler.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusHandshakeHandler.java @@ -1,8 +1,6 @@ package mcp.mobius.opis.network.rcon.nexus; -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.network.rcon.RConHandler; -import io.nettyopis.buffer.ByteBuf; +import io.nettyopis.channel.Channel; import io.nettyopis.channel.ChannelHandlerContext; import io.nettyopis.channel.ChannelInboundHandlerAdapter; import io.nettyopis.handler.codec.compression.JdkZlibDecoder; @@ -11,32 +9,34 @@ import io.nettyopis.handler.ssl.SslHandler; import io.nettyopis.util.ReferenceCountUtil; import io.nettyopis.util.concurrent.Future; import io.nettyopis.util.concurrent.GenericFutureListener; -import io.nettyopis.channel.Channel; +import mcp.mobius.opis.modOpis; +import mcp.mobius.opis.network.rcon.RConHandler; public class NexusHandshakeHandler extends ChannelInboundHandlerAdapter { - + @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { - ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener( - - new GenericFutureListener>() { + ctx.pipeline() + .get(SslHandler.class) + .handshakeFuture() + .addListener(new GenericFutureListener>() { @Override public void operationComplete(Future future) throws Exception { - modOpis.log.info("SSL encryption activated."); + modOpis.log.info("SSL encryption activated."); ctx.pipeline().remove(NexusHandshakeDecoder.class); ctx.pipeline().remove(NexusHandshakeHandler.class); - ctx.pipeline().addLast(new JdkZlibDecoder()); - ctx.pipeline().addLast(new JdkZlibEncoder()); + ctx.pipeline().addLast(new JdkZlibDecoder()); + ctx.pipeline().addLast(new JdkZlibEncoder()); ctx.pipeline().addLast(new NexusMsgDecoder()); ctx.pipeline().addLast(new NexusInboundHandler()); } }); - } - - @Override + } + + @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { - try{ - modOpis.log.warn("You shouldn't see this. This handler is never supposed to be active !"); + try { + modOpis.log.warn("You shouldn't see this. This handler is never supposed to be active !"); } finally { ReferenceCountUtil.release(msg); } @@ -44,7 +44,6 @@ public class NexusHandshakeHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - RConHandler.exceptionCaught(ctx, cause); + RConHandler.exceptionCaught(ctx, cause); } - } diff --git a/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusInboundHandler.java b/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusInboundHandler.java index 89c834a..08fabd4 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusInboundHandler.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusInboundHandler.java @@ -1,101 +1,96 @@ package mcp.mobius.opis.network.rcon.nexus; -import java.lang.ref.WeakReference; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -import net.minecraftforge.common.DimensionManager; -import net.minecraftforge.common.util.FakePlayer; -import net.minecraftforge.common.util.FakePlayerFactory; - -import com.google.common.io.ByteStreams; import com.mojang.authlib.GameProfile; - -import mcp.mobius.opis.modOpis; +import io.nettyopis.channel.ChannelHandlerContext; +import io.nettyopis.channel.ChannelInboundHandlerAdapter; +import io.nettyopis.util.ReferenceCountUtil; +import java.lang.ref.WeakReference; +import java.util.UUID; import mcp.mobius.opis.data.holders.basetypes.SerialInt; import mcp.mobius.opis.data.holders.basetypes.SerialLong; -import mcp.mobius.opis.data.holders.basetypes.SerialString; import mcp.mobius.opis.data.holders.newtypes.ConnectionProperties; import mcp.mobius.opis.data.holders.newtypes.NexusAuth; import mcp.mobius.opis.data.managers.StringCache; import mcp.mobius.opis.events.PlayerTracker; +import mcp.mobius.opis.modOpis; import mcp.mobius.opis.network.PacketBase; -import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.network.packets.server.NetDataValue; import mcp.mobius.opis.network.rcon.RConHandler; -import mcp.mobius.opis.network.rcon.server.RConServer; import mcp.mobius.opis.swing.SelectedTab; -import io.nettyopis.buffer.ByteBuf; -import io.nettyopis.channel.ChannelHandlerContext; -import io.nettyopis.channel.ChannelInboundHandlerAdapter; -import io.nettyopis.handler.codec.ByteToMessageDecoder; -import io.nettyopis.util.ReferenceCountUtil; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.common.util.FakePlayer; +import net.minecraftforge.common.util.FakePlayerFactory; public class NexusInboundHandler extends ChannelInboundHandlerAdapter { - public EventTimerRing timers = new EventTimerRing(); - + public EventTimerRing timers = new EventTimerRing(); + @Override public void handlerAdded(final ChannelHandlerContext ctx) { - NexusClient.instance.ctx = new WeakReference(ctx); - RConHandler.sendToContext(new NetDataValue(Message.NEXUS_UUID, new NexusAuth(NexusClient.instance.uuid, NexusClient.instance.pass, NexusClient.instance.reconnect)), ctx); + NexusClient.instance.ctx = new WeakReference(ctx); + RConHandler.sendToContext( + new NetDataValue( + Message.NEXUS_UUID, + new NexusAuth( + NexusClient.instance.uuid, NexusClient.instance.pass, NexusClient.instance.reconnect)), + ctx); } - + @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try { - FakePlayer fakePlayer = RConHandler.fakePlayersNexus.inverse().get(ctx); - PacketBase packet = (PacketBase) msg; - if (packet instanceof PacketReqData && ((PacketReqData)packet).dataReq == Message.CONNECTION_STATUS){ - PacketReqData pck = (PacketReqData)packet; - int status = ((SerialInt)pck.param1).value; - if (status == 0){ - modOpis.log.error(String.format("Connection refused. Wrong uuid or pass.")); - NexusClient.instance.shouldRetry = false; - } else if (status == 1){ - this.registerFakePlayer(ctx); - this.timers = new EventTimerRing(((ConnectionProperties)pck.param2).prop); - } - + FakePlayer fakePlayer = RConHandler.fakePlayersNexus.inverse().get(ctx); + PacketBase packet = (PacketBase) msg; + if (packet instanceof PacketReqData && ((PacketReqData) packet).dataReq == Message.CONNECTION_STATUS) { + PacketReqData pck = (PacketReqData) packet; + int status = ((SerialInt) pck.param1).value; + if (status == 0) { + modOpis.log.error(String.format("Connection refused. Wrong uuid or pass.")); + NexusClient.instance.shouldRetry = false; + } else if (status == 1) { + this.registerFakePlayer(ctx); + this.timers = new EventTimerRing(((ConnectionProperties) pck.param2).prop); + } - }else{ - packet.actionServer(null, fakePlayer); - } + } else { + packet.actionServer(null, fakePlayer); + } } finally { ReferenceCountUtil.release(msg); - } - } - + } + } + @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - RConHandler.exceptionCaught(ctx, cause); + RConHandler.exceptionCaught(ctx, cause); } - - private void registerFakePlayer(ChannelHandlerContext ctx){ - UUID fakeUUID = UUID.randomUUID(); - - FakePlayer fakePlayer = FakePlayerFactory.get(DimensionManager.getWorld(0), new GameProfile(fakeUUID, ctx.name())); - RConHandler.fakePlayersNexus.put(fakePlayer, ctx); - - PlayerTracker.INSTANCE.playersSwing.add(fakePlayer); - PlayerTracker.INSTANCE.playerTab.put(fakePlayer, SelectedTab.ALL); - RConHandler.sendToContext(new NetDataValue(Message.STATUS_CURRENT_TIME, new SerialLong(System.currentTimeMillis())), ctx); - StringCache.INSTANCE.syncCache(fakePlayer); - modOpis.log.info(String.format("FakePlayer %s with uuid %s registered.", ctx.name(), fakeUUID)); + private void registerFakePlayer(ChannelHandlerContext ctx) { + UUID fakeUUID = UUID.randomUUID(); + + FakePlayer fakePlayer = + FakePlayerFactory.get(DimensionManager.getWorld(0), new GameProfile(fakeUUID, ctx.name())); + RConHandler.fakePlayersNexus.put(fakePlayer, ctx); + + PlayerTracker.INSTANCE.playersSwing.add(fakePlayer); + PlayerTracker.INSTANCE.playerTab.put(fakePlayer, SelectedTab.ALL); + RConHandler.sendToContext( + new NetDataValue(Message.STATUS_CURRENT_TIME, new SerialLong(System.currentTimeMillis())), ctx); + StringCache.INSTANCE.syncCache(fakePlayer); + + modOpis.log.info(String.format("FakePlayer %s with uuid %s registered.", ctx.name(), fakeUUID)); } /* - private void unregisterFakePlayer(ChannelHandlerContext ctx){ - FakePlayer fakePlayer = RConHandler.fakePlayersNexus.inverse().get(ctx); - RConHandler.fakePlayersNexus.remove(fakePlayer); - PlayerTracker.INSTANCE.playersSwing.remove(fakePlayer); - PlayerTracker.INSTANCE.playerTab.remove(fakePlayer); - modOpis.log.info(String.format("FakePlayer %s unregistered.", fakePlayer)); - } - */ + private void unregisterFakePlayer(ChannelHandlerContext ctx){ + FakePlayer fakePlayer = RConHandler.fakePlayersNexus.inverse().get(ctx); + RConHandler.fakePlayersNexus.remove(fakePlayer); + PlayerTracker.INSTANCE.playersSwing.remove(fakePlayer); + PlayerTracker.INSTANCE.playerTab.remove(fakePlayer); + modOpis.log.info(String.format("FakePlayer %s unregistered.", fakePlayer)); + } + */ } diff --git a/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusMsgDecoder.java b/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusMsgDecoder.java index 0d842ba..efc1638 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusMsgDecoder.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/nexus/NexusMsgDecoder.java @@ -1,27 +1,27 @@ package mcp.mobius.opis.network.rcon.nexus; +import com.google.common.io.ByteStreams; import io.nettyopis.buffer.ByteBuf; import io.nettyopis.channel.ChannelHandlerContext; import io.nettyopis.handler.codec.ByteToMessageDecoder; - import java.util.List; - import mcp.mobius.opis.network.PacketBase; -import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.network.rcon.RConHandler; -import com.google.common.io.ByteStreams; - public class NexusMsgDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { - if (in.readableBytes() < 4) { return; } // Packet starts with the size (int) - int packetSize = in.getInt(in.readerIndex()); // We read the packet size (not including the packet type byte) + if (in.readableBytes() < 4) { + return; + } // Packet starts with the size (int) + int packetSize = in.getInt(in.readerIndex()); // We read the packet size (not including the packet type byte) - if (in.readableBytes() < 4 + 1 + packetSize) { return ;} // We check if there is at least packet type + packetSize available bytes + if (in.readableBytes() < 4 + 1 + packetSize) { + return; + } // We check if there is at least packet type + packetSize available bytes in.readInt(); - byte packetType = in.readByte(); // We read the header + byte packetType = in.readByte(); // We read the header // Here we should get a list of potential packets and decode for the corresponding byte diff --git a/src/main/java/mcp/mobius/opis/network/rcon/server/RConHandshakeDecoder.java b/src/main/java/mcp/mobius/opis/network/rcon/server/RConHandshakeDecoder.java index c9cd9b7..f3235df 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/server/RConHandshakeDecoder.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/server/RConHandshakeDecoder.java @@ -3,30 +3,27 @@ package mcp.mobius.opis.network.rcon.server; import io.nettyopis.buffer.ByteBuf; import io.nettyopis.channel.ChannelHandlerContext; import io.nettyopis.handler.codec.ByteToMessageDecoder; - import java.util.List; -import mcp.mobius.opis.network.PacketBase; - -import com.google.common.io.ByteStreams; - public class RConHandshakeDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { - if (in.readableBytes() < 4) { return; } // Size of the password char array - int nChars = in.getInt(in.readerIndex()); - - if (in.readableBytes() < 4 + 2*nChars) { return; } // The total size of the packet is 4 (int) + 2 (char) * nChars - in.readInt(); - - char[] passchars = new char[nChars]; - for (int i = 0; i < nChars; i++){ - passchars[i] = in.readChar(); - } - - out.add(new String(passchars)); - - } + if (in.readableBytes() < 4) { + return; + } // Size of the password char array + int nChars = in.getInt(in.readerIndex()); + if (in.readableBytes() < 4 + 2 * nChars) { + return; + } // The total size of the packet is 4 (int) + 2 (char) * nChars + in.readInt(); + + char[] passchars = new char[nChars]; + for (int i = 0; i < nChars; i++) { + passchars[i] = in.readChar(); + } + + out.add(new String(passchars)); + } } diff --git a/src/main/java/mcp/mobius/opis/network/rcon/server/RConHandshakeHandler.java b/src/main/java/mcp/mobius/opis/network/rcon/server/RConHandshakeHandler.java index a661fe0..44646e3 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/server/RConHandshakeHandler.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/server/RConHandshakeHandler.java @@ -1,56 +1,44 @@ package mcp.mobius.opis.network.rcon.server; -import java.util.UUID; - -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.data.holders.basetypes.SerialLong; -import mcp.mobius.opis.data.managers.StringCache; -import mcp.mobius.opis.events.PlayerTracker; -import mcp.mobius.opis.network.PacketManager; -import mcp.mobius.opis.network.enums.Message; -import mcp.mobius.opis.network.packets.server.NetDataValue; -import net.minecraftforge.common.DimensionManager; -import net.minecraftforge.common.util.FakePlayer; -import net.minecraftforge.common.util.FakePlayerFactory; - -import com.mojang.authlib.GameProfile; - import io.nettyopis.buffer.ByteBuf; import io.nettyopis.channel.ChannelHandlerContext; import io.nettyopis.channel.ChannelInboundHandlerAdapter; import io.nettyopis.handler.codec.compression.JdkZlibDecoder; import io.nettyopis.handler.codec.compression.JdkZlibEncoder; import io.nettyopis.util.ReferenceCountUtil; +import mcp.mobius.opis.modOpis; public class RConHandshakeHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // Here we should check the password against what the client is sending and do all the user registration part - // if the password is valid. We should close the socket immediately otherwise. - - try{ - modOpis.log.info(String.format("Connection to rcon from %s detected", ctx.channel().remoteAddress().toString())); - - if (((String)msg).equals(modOpis.rconpass)){ - ByteBuf buf = ctx.alloc().buffer(); - buf.writeBoolean(true); - ctx.writeAndFlush(buf); - - ctx.pipeline().remove(RConHandshakeDecoder.class); - ctx.pipeline().remove(RConHandshakeHandler.class); - ctx.pipeline().addLast(new JdkZlibDecoder()); - ctx.pipeline().addLast(new JdkZlibEncoder()); - ctx.pipeline().addLast(new RConMsgDecoder()); - ctx.pipeline().addLast(new RConInboundHandler()); - - } else { - modOpis.log.info(String.format("Password error. Closing socket")); - ByteBuf buf = ctx.alloc().buffer(); - buf.writeBoolean(false); - ctx.writeAndFlush(buf); - ctx.close(); - } + // if the password is valid. We should close the socket immediately otherwise. + + try { + modOpis.log.info(String.format( + "Connection to rcon from %s detected", + ctx.channel().remoteAddress().toString())); + + if (((String) msg).equals(modOpis.rconpass)) { + ByteBuf buf = ctx.alloc().buffer(); + buf.writeBoolean(true); + ctx.writeAndFlush(buf); + + ctx.pipeline().remove(RConHandshakeDecoder.class); + ctx.pipeline().remove(RConHandshakeHandler.class); + ctx.pipeline().addLast(new JdkZlibDecoder()); + ctx.pipeline().addLast(new JdkZlibEncoder()); + ctx.pipeline().addLast(new RConMsgDecoder()); + ctx.pipeline().addLast(new RConInboundHandler()); + + } else { + modOpis.log.info(String.format("Password error. Closing socket")); + ByteBuf buf = ctx.alloc().buffer(); + buf.writeBoolean(false); + ctx.writeAndFlush(buf); + ctx.close(); + } } finally { ReferenceCountUtil.release(msg); diff --git a/src/main/java/mcp/mobius/opis/network/rcon/server/RConInboundHandler.java b/src/main/java/mcp/mobius/opis/network/rcon/server/RConInboundHandler.java index cd4233f..7056e1a 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/server/RConInboundHandler.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/server/RConInboundHandler.java @@ -1,65 +1,60 @@ package mcp.mobius.opis.network.rcon.server; -import java.util.UUID; - import com.mojang.authlib.GameProfile; - -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.data.holders.basetypes.SerialLong; -import mcp.mobius.opis.data.managers.StringCache; -import mcp.mobius.opis.events.PlayerTracker; -import mcp.mobius.opis.network.PacketBase; -import mcp.mobius.opis.network.PacketManager; -import mcp.mobius.opis.network.enums.Message; -import mcp.mobius.opis.network.packets.client.PacketReqData; -import mcp.mobius.opis.network.packets.server.NetDataValue; -import mcp.mobius.opis.network.rcon.RConHandler; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraftforge.common.DimensionManager; -import net.minecraftforge.common.util.FakePlayer; -import net.minecraftforge.common.util.FakePlayerFactory; -import io.nettyopis.buffer.ByteBuf; import io.nettyopis.channel.ChannelHandlerContext; import io.nettyopis.channel.ChannelInboundHandlerAdapter; import io.nettyopis.util.ReferenceCountUtil; +import java.util.UUID; +import mcp.mobius.opis.data.holders.basetypes.SerialLong; +import mcp.mobius.opis.data.managers.StringCache; +import mcp.mobius.opis.events.PlayerTracker; +import mcp.mobius.opis.modOpis; +import mcp.mobius.opis.network.PacketBase; +import mcp.mobius.opis.network.PacketManager; +import mcp.mobius.opis.network.enums.Message; +import mcp.mobius.opis.network.packets.server.NetDataValue; +import mcp.mobius.opis.network.rcon.RConHandler; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.common.util.FakePlayer; +import net.minecraftforge.common.util.FakePlayerFactory; -class RConInboundHandler extends ChannelInboundHandlerAdapter{ - // One object of this type is created by connection - // There is one permanent context per connection ! - +class RConInboundHandler extends ChannelInboundHandlerAdapter { + // One object of this type is created by connection + // There is one permanent context per connection ! @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { - UUID fakeUUID = UUID.randomUUID(); - FakePlayer fakePlayer = FakePlayerFactory.get(DimensionManager.getWorld(0), new GameProfile(fakeUUID, ctx.name())); - RConHandler.fakePlayersRcon.put(fakePlayer, ctx); - - PlayerTracker.INSTANCE.playersSwing.add(fakePlayer); - PacketManager.validateAndSend(new NetDataValue(Message.STATUS_CURRENT_TIME, new SerialLong(System.currentTimeMillis())), fakePlayer); - StringCache.INSTANCE.syncCache(fakePlayer); + UUID fakeUUID = UUID.randomUUID(); + FakePlayer fakePlayer = + FakePlayerFactory.get(DimensionManager.getWorld(0), new GameProfile(fakeUUID, ctx.name())); + RConHandler.fakePlayersRcon.put(fakePlayer, ctx); - modOpis.log.info(String.format("FakePlayer %s with uuid %s created.", ctx.name(), fakeUUID)); + PlayerTracker.INSTANCE.playersSwing.add(fakePlayer); + PacketManager.validateAndSend( + new NetDataValue(Message.STATUS_CURRENT_TIME, new SerialLong(System.currentTimeMillis())), fakePlayer); + StringCache.INSTANCE.syncCache(fakePlayer); + + modOpis.log.info(String.format("FakePlayer %s with uuid %s created.", ctx.name(), fakeUUID)); } - @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try { - FakePlayer fakePlayer = RConHandler.fakePlayersRcon.inverse().get(ctx); - PacketBase packet = (PacketBase) msg; - - //if (packet instanceof PacketReqData) - // modOpis.log.info(String.format("Received request %s from player %s", ((PacketReqData)packet).dataReq, fakePlayer.getDisplayName())); - - packet.actionServer(null, fakePlayer); + FakePlayer fakePlayer = RConHandler.fakePlayersRcon.inverse().get(ctx); + PacketBase packet = (PacketBase) msg; + + // if (packet instanceof PacketReqData) + // modOpis.log.info(String.format("Received request %s from player %s", ((PacketReqData)packet).dataReq, + // fakePlayer.getDisplayName())); + + packet.actionServer(null, fakePlayer); } finally { ReferenceCountUtil.release(msg); - } + } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - RConHandler.exceptionCaught(ctx, cause); - } + RConHandler.exceptionCaught(ctx, cause); + } } - diff --git a/src/main/java/mcp/mobius/opis/network/rcon/server/RConMsgDecoder.java b/src/main/java/mcp/mobius/opis/network/rcon/server/RConMsgDecoder.java index c43c420..0f93fed 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/server/RConMsgDecoder.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/server/RConMsgDecoder.java @@ -1,26 +1,27 @@ package mcp.mobius.opis.network.rcon.server; -import java.util.List; - import com.google.common.io.ByteStreams; - -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.network.PacketBase; -import mcp.mobius.opis.network.rcon.RConHandler; import io.nettyopis.buffer.ByteBuf; import io.nettyopis.channel.ChannelHandlerContext; import io.nettyopis.handler.codec.ByteToMessageDecoder; +import java.util.List; +import mcp.mobius.opis.network.PacketBase; +import mcp.mobius.opis.network.rcon.RConHandler; public class RConMsgDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { - if (in.readableBytes() < 4) { return; } // Packet starts with the size (int) - int packetSize = in.getInt(in.readerIndex()); // We read the packet size (not including the packet type byte) + if (in.readableBytes() < 4) { + return; + } // Packet starts with the size (int) + int packetSize = in.getInt(in.readerIndex()); // We read the packet size (not including the packet type byte) - if (in.readableBytes() < 4 + 1 + packetSize) { return ;} // We check if there is at least packet type + packetSize available bytes + if (in.readableBytes() < 4 + 1 + packetSize) { + return; + } // We check if there is at least packet type + packetSize available bytes in.readInt(); - byte packetType = in.readByte(); // We read the header + byte packetType = in.readByte(); // We read the header // Here we should get a list of potential packets and decode for the corresponding byte diff --git a/src/main/java/mcp/mobius/opis/network/rcon/server/RConServer.java b/src/main/java/mcp/mobius/opis/network/rcon/server/RConServer.java index d6bf0fb..2de44ee 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/server/RConServer.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/server/RConServer.java @@ -11,79 +11,80 @@ import io.nettyopis.channel.socket.nio.NioServerSocketChannel; import io.nettyopis.handler.ssl.SslContext; import io.nettyopis.handler.ssl.util.SelfSignedCertificate; import io.nettyopis.handler.timeout.ReadTimeoutHandler; -import mcp.mobius.opis.modOpis; - -import javax.net.ssl.SSLException; import java.security.cert.CertificateException; +import javax.net.ssl.SSLException; +import mcp.mobius.opis.modOpis; public class RConServer implements Runnable { - class ChannelInit extends ChannelInitializer{ - private final SslContext sslCtx; - - public ChannelInit(SslContext sslCtx) { - this.sslCtx = sslCtx; - } - - @Override - protected void initChannel(SocketChannel ch) throws Exception { - - ch.pipeline().addLast(sslCtx.newHandler(ch.alloc())); + class ChannelInit extends ChannelInitializer { + private final SslContext sslCtx; + + public ChannelInit(SslContext sslCtx) { + this.sslCtx = sslCtx; + } + + @Override + protected void initChannel(SocketChannel ch) throws Exception { + + ch.pipeline().addLast(sslCtx.newHandler(ch.alloc())); ch.pipeline().addLast(new ReadTimeoutHandler(10)); ch.pipeline().addLast(new RConHandshakeDecoder()); ch.pipeline().addLast(new RConHandshakeHandler()); - //ch.pipeline().addLast(new JdkZlibDecoder()); - //ch.pipeline().addLast(new JdkZlibEncoder()); - //ch.pipeline().addLast(new RconMsgDecoder()); - //ch.pipeline().addLast(new RConInboundHandler()); + // ch.pipeline().addLast(new JdkZlibDecoder()); + // ch.pipeline().addLast(new JdkZlibEncoder()); + // ch.pipeline().addLast(new RconMsgDecoder()); + // ch.pipeline().addLast(new RConInboundHandler()); + + } + } + + public static final RConServer instance = new RConServer(); + + private int port = -1; + + private RConServer() { + this.port = modOpis.rconport; + } - } - } - - public final static RConServer instance = new RConServer(); - - private int port = -1; - - private RConServer(){ - this.port = modOpis.rconport; - } - @Override - public void run(){ - if (!modOpis.rconactive) return; - - modOpis.log.info("Starting Opis remote control server."); - + public void run() { + if (!modOpis.rconactive) return; - SelfSignedCertificate ssc = null; - SslContext sslCtx = null; - try { - ssc = new SelfSignedCertificate(); - sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); - } catch (CertificateException e1) { e1.printStackTrace(); - } catch (SSLException e1) { e1.printStackTrace(); } - - EventLoopGroup bossGroup = new NioEventLoopGroup(); + modOpis.log.info("Starting Opis remote control server."); + + SelfSignedCertificate ssc = null; + SslContext sslCtx = null; + try { + ssc = new SelfSignedCertificate(); + sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); + } catch (CertificateException e1) { + e1.printStackTrace(); + } catch (SSLException e1) { + e1.printStackTrace(); + } + + EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); - + try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) - .childHandler(new ChannelInit(sslCtx)) - .option(ChannelOption.SO_BACKLOG, 128) - .childOption(ChannelOption.SO_KEEPALIVE, true); + .channel(NioServerSocketChannel.class) + .childHandler(new ChannelInit(sslCtx)) + .option(ChannelOption.SO_BACKLOG, 128) + .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); // (7) f.channel().closeFuture().sync(); - - } catch (Exception e){ - modOpis.log.error("Error in Opis remote control server."); - e.printStackTrace(); + + } catch (Exception e) { + modOpis.log.error("Error in Opis remote control server."); + e.printStackTrace(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } - } + } } diff --git a/src/main/java/mcp/mobius/opis/proxy/ProxyClient.java b/src/main/java/mcp/mobius/opis/proxy/ProxyClient.java index 4ea6732..a792643 100644 --- a/src/main/java/mcp/mobius/opis/proxy/ProxyClient.java +++ b/src/main/java/mcp/mobius/opis/proxy/ProxyClient.java @@ -34,161 +34,180 @@ import mcp.mobius.opis.swing.panels.tracking.PanelPlayers; import net.minecraft.util.ResourceLocation; import org.apache.logging.log4j.Level; -public class ProxyClient extends ProxyServer implements IMessageHandler{ - - public static TrueTypeFont fontMC8, fontMC12, fontMC16, fontMC18, fontMC24; - - @Override - public void init(){ - fontMC8 = Fonts.createFont(new ResourceLocation("opis", "fonts/LiberationMono-Bold.ttf"), 14, true); +public class ProxyClient extends ProxyServer implements IMessageHandler { - IMessageHandler panelSummary = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelSummary(), "Summary"); - - TabPanelRegistrar.INSTANCE.registerSection("Tracking"); - IMessageHandler panelPlayers = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelPlayers(), "Players", "Tracking"); - IMessageHandler panelAmountEntities = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelAmountEntities(),"Entities", "Tracking"); - IMessageHandler panelAmountTileEnts = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelAmountTileEnts(),"Tile Entities", "Tracking"); - IMessageHandler panelDimensions = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelDimensions(), "Dimensions", "Tracking"); - - TabPanelRegistrar.INSTANCE.registerSection("Server timing"); - IMessageHandler panelTimingTileEnts = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingTileEnts(),"Tile Entities", "Server timing"); - IMessageHandler panelTimingTileEntsPerClass = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingTileEntsPerClass(),"Tile Entities [Type]", "Server timing"); - IMessageHandler panelTimingEntities = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingEntities(),"Entities", "Server timing"); - IMessageHandler panelTimingEntPerClass = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingEntitiesPerClass(),"Entities [Type]", "Server timing"); - IMessageHandler panelTimingHandlers = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingHandlers(),"Handlers", "Server timing"); - IMessageHandler panelTimingChunks = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingChunks(), "Chunks", "Server timing"); - IMessageHandler panelTimingEvents = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingEvents(), "Events", "Server timing"); - - TabPanelRegistrar.INSTANCE.registerSection("Client timing"); - TabPanelRegistrar.INSTANCE.registerTab(new PanelRenderTileEnts(),"[Render] TileEnts", "Client timing"); - TabPanelRegistrar.INSTANCE.registerTab(new PanelRenderEntities(),"[Render] Entities", "Client timing"); - TabPanelRegistrar.INSTANCE.registerTab(new PanelRenderHandlers(),"[Render] Handlers", "Client timing"); - TabPanelRegistrar.INSTANCE.registerTab(new PanelEventClient(),"Events", "Client timing"); - - TabPanelRegistrar.INSTANCE.registerSection("Network"); - IMessageHandler panelPacketsOut = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelOutbound(), "Outbound", "Network"); - IMessageHandler panelPacketsIn = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelInbound(), "Inbound", "Network"); - IMessageHandler panelPacketsOut250 = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelOutbound250(),"Outbound 250", "Network"); - IMessageHandler panelPacketsIn250 = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelInbound250(), "Inbound 250", "Network"); + public static TrueTypeFont fontMC8, fontMC12, fontMC16, fontMC18, fontMC24; - TabPanelRegistrar.INSTANCE.registerSection("Debug"); - IMessageHandler panelOrphanTileEnts = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelOrphanTileEntities(), "Orphan TileEnts", "Debug"); - IMessageHandler panelThreads = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelThreads(), "Threads", "Debug"); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_PLAYERS, panelPlayers); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_AMOUNT_ENTITIES, panelAmountEntities); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_AMOUNT_TILEENTS, panelAmountTileEnts); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_TILEENTS, panelTimingTileEnts); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_TILEENTS, panelTimingTileEnts); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingTileEnts); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingTileEnts); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingTileEnts); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.CLIENT_HIGHLIGHT_BLOCK,panelTimingTileEnts); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_ENTITIES, panelTimingEntities); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_ENTITIES, panelTimingEntities); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingEntities); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingEntities); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingEntities); + @Override + public void init() { + fontMC8 = Fonts.createFont(new ResourceLocation("opis", "fonts/LiberationMono-Bold.ttf"), 14, true); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_ENTITIES_PER_CLASS, panelTimingEntPerClass); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingEntPerClass); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingEntPerClass); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingEntPerClass); + IMessageHandler panelSummary = + (IMessageHandler) TabPanelRegistrar.INSTANCE.registerTab(new PanelSummary(), "Summary"); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_TILEENTS_PER_CLASS, panelTimingTileEntsPerClass); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingTileEntsPerClass); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingTileEntsPerClass); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingTileEntsPerClass); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_HANDLERS, panelTimingHandlers); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_HANDLERS, panelTimingHandlers); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingHandlers); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingHandlers); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingHandlers); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_CHUNK, panelTimingChunks); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingChunks); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingChunks); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingChunks); + TabPanelRegistrar.INSTANCE.registerSection("Tracking"); + IMessageHandler panelPlayers = + (IMessageHandler) TabPanelRegistrar.INSTANCE.registerTab(new PanelPlayers(), "Players", "Tracking"); + IMessageHandler panelAmountEntities = (IMessageHandler) + TabPanelRegistrar.INSTANCE.registerTab(new PanelAmountEntities(), "Entities", "Tracking"); + IMessageHandler panelAmountTileEnts = (IMessageHandler) + TabPanelRegistrar.INSTANCE.registerTab(new PanelAmountTileEnts(), "Tile Entities", "Tracking"); + IMessageHandler panelDimensions = (IMessageHandler) + TabPanelRegistrar.INSTANCE.registerTab(new PanelDimensions(), "Dimensions", "Tracking"); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_EVENTS, panelTimingEvents); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingEvents); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingEvents); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingEvents); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_ACCESS_LEVEL, DataCache.instance()); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_CURRENT_TIME, DataCache.instance()); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_ACCESS_LEVEL, SwingUI.instance()); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.CLIENT_SHOW_SWING, SwingUI.instance()); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.NEXUS_DATA, panelSummary); - //MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_AMOUNT_HANDLERS, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_TILEENTS, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_ENTITIES, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_HANDLERS, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_WORLDTICK, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUN_UPDATE, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_TIME_LAST_RUN, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_ENTUPDATE, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_NETWORK, panelSummary); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_PING, panelSummary); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_DIMENSION_DATA, panelDimensions); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_PACKETS_OUTBOUND, panelPacketsOut); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_PACKETS_INBOUND, panelPacketsIn); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_PACKETS_OUTBOUND_250, panelPacketsOut250); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_PACKETS_INBOUND_250, panelPacketsIn250); + TabPanelRegistrar.INSTANCE.registerSection("Server timing"); + IMessageHandler panelTimingTileEnts = (IMessageHandler) + TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingTileEnts(), "Tile Entities", "Server timing"); + IMessageHandler panelTimingTileEntsPerClass = (IMessageHandler) TabPanelRegistrar.INSTANCE.registerTab( + new PanelTimingTileEntsPerClass(), "Tile Entities [Type]", "Server timing"); + IMessageHandler panelTimingEntities = (IMessageHandler) + TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingEntities(), "Entities", "Server timing"); + IMessageHandler panelTimingEntPerClass = (IMessageHandler) TabPanelRegistrar.INSTANCE.registerTab( + new PanelTimingEntitiesPerClass(), "Entities [Type]", "Server timing"); + IMessageHandler panelTimingHandlers = (IMessageHandler) + TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingHandlers(), "Handlers", "Server timing"); + IMessageHandler panelTimingChunks = (IMessageHandler) + TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingChunks(), "Chunks", "Server timing"); + IMessageHandler panelTimingEvents = (IMessageHandler) + TabPanelRegistrar.INSTANCE.registerTab(new PanelTimingEvents(), "Events", "Server timing"); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_ORPHAN_TILEENTS_CLEAR, panelOrphanTileEnts); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_ORPHAN_TILEENTS, panelOrphanTileEnts); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_THREADS, panelThreads); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.CLIENT_CLEAR_SELECTION, modOpis.proxy); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.CLIENT_START_PROFILING, modOpis.proxy); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.CLIENT_SHOW_RENDER_TICK, modOpis.proxy); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_CHUNK, ChunkManager.INSTANCE); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_CHUNK_LOADED, ChunkManager.INSTANCE); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_CHUNK_LOADED_CLEAR, ChunkManager.INSTANCE); - - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STRINGUPD, StringCache.INSTANCE); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STRINGUPD_FULL, StringCache.INSTANCE); - } + TabPanelRegistrar.INSTANCE.registerSection("Client timing"); + TabPanelRegistrar.INSTANCE.registerTab(new PanelRenderTileEnts(), "[Render] TileEnts", "Client timing"); + TabPanelRegistrar.INSTANCE.registerTab(new PanelRenderEntities(), "[Render] Entities", "Client timing"); + TabPanelRegistrar.INSTANCE.registerTab(new PanelRenderHandlers(), "[Render] Handlers", "Client timing"); + TabPanelRegistrar.INSTANCE.registerTab(new PanelEventClient(), "Events", "Client timing"); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case CLIENT_CLEAR_SELECTION:{ - modOpis.selectedBlock = null; - break; - } - case CLIENT_START_PROFILING:{ - modOpis.log.log(Level.INFO, "Started profiling"); - MetaManager.reset(); - modOpis.profilerRun = true; - ProfilerSection.activateAll(Side.CLIENT); - break; - } - case CLIENT_SHOW_RENDER_TICK:{ - modOpis.log.log(Level.INFO, "=== RENDER TICK ==="); - //ArrayList stats = TickHandlerManager.getCumulatedStatsServer(); - //for (DataHandler stat : stats){ - // System.out.printf("%s \n", stat); - //} - break; - } - default: - return false; - } - - - return true; - } + TabPanelRegistrar.INSTANCE.registerSection("Network"); + IMessageHandler panelPacketsOut = + (IMessageHandler) TabPanelRegistrar.INSTANCE.registerTab(new PanelOutbound(), "Outbound", "Network"); + IMessageHandler panelPacketsIn = + (IMessageHandler) TabPanelRegistrar.INSTANCE.registerTab(new PanelInbound(), "Inbound", "Network"); + IMessageHandler panelPacketsOut250 = (IMessageHandler) + TabPanelRegistrar.INSTANCE.registerTab(new PanelOutbound250(), "Outbound 250", "Network"); + IMessageHandler panelPacketsIn250 = (IMessageHandler) + TabPanelRegistrar.INSTANCE.registerTab(new PanelInbound250(), "Inbound 250", "Network"); + + TabPanelRegistrar.INSTANCE.registerSection("Debug"); + IMessageHandler panelOrphanTileEnts = (IMessageHandler) + TabPanelRegistrar.INSTANCE.registerTab(new PanelOrphanTileEntities(), "Orphan TileEnts", "Debug"); + IMessageHandler panelThreads = + (IMessageHandler) TabPanelRegistrar.INSTANCE.registerTab(new PanelThreads(), "Threads", "Debug"); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_PLAYERS, panelPlayers); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_AMOUNT_ENTITIES, panelAmountEntities); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_AMOUNT_TILEENTS, panelAmountTileEnts); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_TILEENTS, panelTimingTileEnts); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_TILEENTS, panelTimingTileEnts); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingTileEnts); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingTileEnts); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingTileEnts); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.CLIENT_HIGHLIGHT_BLOCK, panelTimingTileEnts); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_ENTITIES, panelTimingEntities); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_ENTITIES, panelTimingEntities); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingEntities); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingEntities); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingEntities); + + MessageHandlerRegistrar.INSTANCE.registerHandler( + Message.LIST_TIMING_ENTITIES_PER_CLASS, panelTimingEntPerClass); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingEntPerClass); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingEntPerClass); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingEntPerClass); + + MessageHandlerRegistrar.INSTANCE.registerHandler( + Message.LIST_TIMING_TILEENTS_PER_CLASS, panelTimingTileEntsPerClass); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingTileEntsPerClass); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingTileEntsPerClass); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingTileEntsPerClass); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_HANDLERS, panelTimingHandlers); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_HANDLERS, panelTimingHandlers); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingHandlers); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingHandlers); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingHandlers); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_CHUNK, panelTimingChunks); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingChunks); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingChunks); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingChunks); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_EVENTS, panelTimingEvents); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelTimingEvents); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelTimingEvents); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelTimingEvents); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_ACCESS_LEVEL, DataCache.instance()); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_CURRENT_TIME, DataCache.instance()); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_ACCESS_LEVEL, SwingUI.instance()); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.CLIENT_SHOW_SWING, SwingUI.instance()); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.NEXUS_DATA, panelSummary); + // MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_AMOUNT_HANDLERS, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_TILEENTS, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_ENTITIES, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_HANDLERS, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_WORLDTICK, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_START, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STOP, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUN_UPDATE, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_RUNNING, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_TIME_LAST_RUN, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_ENTUPDATE, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.VALUE_TIMING_NETWORK, panelSummary); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_PING, panelSummary); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_DIMENSION_DATA, panelDimensions); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_PACKETS_OUTBOUND, panelPacketsOut); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_PACKETS_INBOUND, panelPacketsIn); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_PACKETS_OUTBOUND_250, panelPacketsOut250); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_PACKETS_INBOUND_250, panelPacketsIn250); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_ORPHAN_TILEENTS_CLEAR, panelOrphanTileEnts); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_ORPHAN_TILEENTS, panelOrphanTileEnts); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_THREADS, panelThreads); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.CLIENT_CLEAR_SELECTION, modOpis.proxy); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.CLIENT_START_PROFILING, modOpis.proxy); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.CLIENT_SHOW_RENDER_TICK, modOpis.proxy); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_CHUNK, ChunkManager.INSTANCE); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_CHUNK_LOADED, ChunkManager.INSTANCE); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_CHUNK_LOADED_CLEAR, ChunkManager.INSTANCE); + + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STRINGUPD, StringCache.INSTANCE); + MessageHandlerRegistrar.INSTANCE.registerHandler(Message.STATUS_STRINGUPD_FULL, StringCache.INSTANCE); + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case CLIENT_CLEAR_SELECTION: { + modOpis.selectedBlock = null; + break; + } + case CLIENT_START_PROFILING: { + modOpis.log.log(Level.INFO, "Started profiling"); + MetaManager.reset(); + modOpis.profilerRun = true; + ProfilerSection.activateAll(Side.CLIENT); + break; + } + case CLIENT_SHOW_RENDER_TICK: { + modOpis.log.log(Level.INFO, "=== RENDER TICK ==="); + // ArrayList stats = TickHandlerManager.getCumulatedStatsServer(); + // for (DataHandler stat : stats){ + // System.out.printf("%s \n", stat); + // } + break; + } + default: + return false; + } + + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/proxy/ProxyServer.java b/src/main/java/mcp/mobius/opis/proxy/ProxyServer.java index 2a6139d..b738fa1 100644 --- a/src/main/java/mcp/mobius/opis/proxy/ProxyServer.java +++ b/src/main/java/mcp/mobius/opis/proxy/ProxyServer.java @@ -4,13 +4,12 @@ import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; -public class ProxyServer implements IMessageHandler{ - - public void init(){ - } +public class ProxyServer implements IMessageHandler { - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - return false; - } + public void init() {} + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + return false; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/SelectedTab.java b/src/main/java/mcp/mobius/opis/swing/SelectedTab.java index ac3682b..d84f678 100644 --- a/src/main/java/mcp/mobius/opis/swing/SelectedTab.java +++ b/src/main/java/mcp/mobius/opis/swing/SelectedTab.java @@ -1,30 +1,30 @@ package mcp.mobius.opis.swing; public enum SelectedTab { - AMOUNTENTS, - AMOUNTTES, - DIMENSIONS, - PACKETS, - PLAYERS, - RENDERENTITIES, - RENDERTILEENTS, - SUMMARY, - TIMINGCHUNKS, - TIMINGENTITES, - TIMINGENTITESPERCLASS, - TIMINGHANDLERS, - TIMINGTILEENTS, - TIMINGTILEENTSPERCLASS, - TIMINGEVENTS, - PACKETINBOUND, - PACKETOUTBOUND, - PACKETINBOUND250, - PACKETOUTBOUND250, - ORPHANTES, - RENDERHANDLERS, - CLIENTEVENTS, - THREADS, - ANY, - NONE, - ALL; + AMOUNTENTS, + AMOUNTTES, + DIMENSIONS, + PACKETS, + PLAYERS, + RENDERENTITIES, + RENDERTILEENTS, + SUMMARY, + TIMINGCHUNKS, + TIMINGENTITES, + TIMINGENTITESPERCLASS, + TIMINGHANDLERS, + TIMINGTILEENTS, + TIMINGTILEENTSPERCLASS, + TIMINGEVENTS, + PACKETINBOUND, + PACKETOUTBOUND, + PACKETINBOUND250, + PACKETOUTBOUND250, + ORPHANTES, + RENDERHANDLERS, + CLIENTEVENTS, + THREADS, + ANY, + NONE, + ALL; } diff --git a/src/main/java/mcp/mobius/opis/swing/SwingUI.java b/src/main/java/mcp/mobius/opis/swing/SwingUI.java index b6fa1c4..8eb3253 100644 --- a/src/main/java/mcp/mobius/opis/swing/SwingUI.java +++ b/src/main/java/mcp/mobius/opis/swing/SwingUI.java @@ -3,158 +3,158 @@ package mcp.mobius.opis.swing; import java.awt.BorderLayout; import java.awt.Component; import java.awt.EventQueue; - +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.util.HashSet; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; +import javax.swing.SwingConstants; import javax.swing.ToolTipManager; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; - -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.HashSet; - -import javax.swing.SwingConstants; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiChat; -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.basetypes.SerialInt; +import mcp.mobius.opis.modOpis; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.AccessLevel; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.widgets.JButtonAccess; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiChat; -public class SwingUI extends JFrame implements WindowListener, ChangeListener, IMessageHandler{ +public class SwingUI extends JFrame implements WindowListener, ChangeListener, IMessageHandler { - public static HashSet registeredButtons = new HashSet(); - - private static SwingUI _instance = new SwingUI(); - public static SwingUI instance(){ - return _instance; - } - - private JPanel contentPane; - private JTabbedPane tabbedPane; - - public void showUI(){ - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - try { - SwingUI.instance().setVisible(true); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - - /** - * Create the frame. - */ - private SwingUI() { - - setTitle("Opis Control Panel"); - setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); - setBounds(100, 100, 893, 455); - contentPane = new JPanel(); - contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); - contentPane.setLayout(new BorderLayout(0, 0)); - setContentPane(contentPane); - - tabbedPane = new JTabbedPane(SwingConstants.TOP); - tabbedPane.addChangeListener(this); - contentPane.add(tabbedPane, BorderLayout.CENTER); + public static HashSet registeredButtons = new HashSet(); - this.addWindowListener(this); - ToolTipManager.sharedInstance().setInitialDelay(500); - ToolTipManager.sharedInstance().setDismissDelay(60 * 1000); - - } + private static SwingUI _instance = new SwingUI(); - @Override - public void windowActivated(WindowEvent arg0) {} + public static SwingUI instance() { + return _instance; + } - @Override - public void windowClosed(WindowEvent arg0) { - modOpis.swingOpen = false; - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_UNREGISTER_SWING)); - } + private JPanel contentPane; + private JTabbedPane tabbedPane; - @Override - public void windowClosing(WindowEvent arg0) {} + public void showUI() { + EventQueue.invokeLater(new Runnable() { + @Override + public void run() { + try { + SwingUI.instance().setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } - @Override - public void windowDeactivated(WindowEvent arg0) {} + /** + * Create the frame. + */ + private SwingUI() { - @Override - public void windowDeiconified(WindowEvent arg0) {} + setTitle("Opis Control Panel"); + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + setBounds(100, 100, 893, 455); + contentPane = new JPanel(); + contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); + contentPane.setLayout(new BorderLayout(0, 0)); + setContentPane(contentPane); - @Override - public void windowIconified(WindowEvent arg0) {} + tabbedPane = new JTabbedPane(SwingConstants.TOP); + tabbedPane.addChangeListener(this); + contentPane.add(tabbedPane, BorderLayout.CENTER); - @Override - public void windowOpened(WindowEvent arg0) {} - - public JTabbedPane getTabbedPane() { - return tabbedPane; - } - - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case STATUS_ACCESS_LEVEL:{ - AccessLevel level = AccessLevel.values()[((SerialInt)rawdata.value).value]; - for (JButtonAccess button : SwingUI.registeredButtons){ - if (level.ordinal() < button.getAccessLevel().ordinal()){ - button.setEnabled(false); - } else { - button.setEnabled(true); - } - } - break; - } - case CLIENT_SHOW_SWING:{ - /* - try { - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } catch (Exception e) {} - */ - - modOpis.swingOpen = true; - this.showUI(); - Minecraft.getMinecraft().displayGuiScreen(new GuiChat()); - PacketManager.sendToServer(new PacketReqData(Message.SWING_TAB_CHANGED, new SerialInt(SelectedTab.SUMMARY.ordinal()))); - break; - } - default: - return false; - - } - return true; - } + this.addWindowListener(this); + ToolTipManager.sharedInstance().setInitialDelay(500); + ToolTipManager.sharedInstance().setDismissDelay(60 * 1000); + } - @Override - public void stateChanged(ChangeEvent e) { - Component source = ((JTabbedPane)e.getSource()).getSelectedComponent(); - - if (source instanceof ITabPanel){ - ITabPanel panel = (ITabPanel)source; - PacketManager.sendToServer(new PacketReqData(Message.SWING_TAB_CHANGED, new SerialInt(panel.getSelectedTab().ordinal()))); - } - - if (source instanceof JTabbedPane){ - JTabbedPane pane = (JTabbedPane)source; - ITabPanel panel = (ITabPanel)pane.getSelectedComponent(); - PacketManager.sendToServer(new PacketReqData(Message.SWING_TAB_CHANGED, new SerialInt(panel.getSelectedTab().ordinal()))); - } - } + @Override + public void windowActivated(WindowEvent arg0) {} + + @Override + public void windowClosed(WindowEvent arg0) { + modOpis.swingOpen = false; + PacketManager.sendToServer(new PacketReqData(Message.COMMAND_UNREGISTER_SWING)); + } + + @Override + public void windowClosing(WindowEvent arg0) {} + + @Override + public void windowDeactivated(WindowEvent arg0) {} + + @Override + public void windowDeiconified(WindowEvent arg0) {} + + @Override + public void windowIconified(WindowEvent arg0) {} + + @Override + public void windowOpened(WindowEvent arg0) {} + + public JTabbedPane getTabbedPane() { + return tabbedPane; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case STATUS_ACCESS_LEVEL: { + AccessLevel level = AccessLevel.values()[((SerialInt) rawdata.value).value]; + for (JButtonAccess button : SwingUI.registeredButtons) { + if (level.ordinal() < button.getAccessLevel().ordinal()) { + button.setEnabled(false); + } else { + button.setEnabled(true); + } + } + break; + } + case CLIENT_SHOW_SWING: { + /* + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception e) {} + */ + + modOpis.swingOpen = true; + this.showUI(); + Minecraft.getMinecraft().displayGuiScreen(new GuiChat()); + PacketManager.sendToServer( + new PacketReqData(Message.SWING_TAB_CHANGED, new SerialInt(SelectedTab.SUMMARY.ordinal()))); + break; + } + default: + return false; + } + return true; + } + + @Override + public void stateChanged(ChangeEvent e) { + Component source = ((JTabbedPane) e.getSource()).getSelectedComponent(); + + if (source instanceof ITabPanel) { + ITabPanel panel = (ITabPanel) source; + PacketManager.sendToServer(new PacketReqData( + Message.SWING_TAB_CHANGED, + new SerialInt(panel.getSelectedTab().ordinal()))); + } + + if (source instanceof JTabbedPane) { + JTabbedPane pane = (JTabbedPane) source; + ITabPanel panel = (ITabPanel) pane.getSelectedComponent(); + PacketManager.sendToServer(new PacketReqData( + Message.SWING_TAB_CHANGED, + new SerialInt(panel.getSelectedTab().ordinal()))); + } + } } diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountEntities.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountEntities.java index 990eb44..2370775 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountEntities.java @@ -4,7 +4,9 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; - +import mcp.mobius.opis.api.TabPanelRegistrar; +import mcp.mobius.opis.data.holders.basetypes.AmountHolder; +import mcp.mobius.opis.data.holders.basetypes.SerialString; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; @@ -12,42 +14,34 @@ import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.panels.tracking.PanelAmountEntities; import mcp.mobius.opis.swing.widgets.JTableStats; -import mcp.mobius.opis.api.TabPanelRegistrar; -import mcp.mobius.opis.data.holders.basetypes.AmountHolder; -import mcp.mobius.opis.data.holders.basetypes.SerialString; - public class ActionAmountEntities implements ActionListener, ItemListener { - @Override - public void actionPerformed(ActionEvent e) { - PanelAmountEntities panel = (PanelAmountEntities)TabPanelRegistrar.INSTANCE.getTab(SelectedTab.AMOUNTENTS); - - - JTableStats table = panel.getTable(); - if (table == null || table.getSelectedRow() == -1) return; - int indexData = table.convertRowIndexToModel(table.getSelectedRow()); - AmountHolder data = (AmountHolder)table.getTableData().get(indexData); - - if (e.getSource() == panel.getBtnKillAll()){ - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_KILLALL, new SerialString(data.key.str))); - PacketManager.sendToServer(new PacketReqData(Message.LIST_AMOUNT_ENTITIES)); - } - - if (e.getSource() == panel.getBtnRefresh()){ - PacketManager.sendToServer(new PacketReqData(Message.LIST_AMOUNT_ENTITIES)); - } - - } + @Override + public void actionPerformed(ActionEvent e) { + PanelAmountEntities panel = (PanelAmountEntities) TabPanelRegistrar.INSTANCE.getTab(SelectedTab.AMOUNTENTS); - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED){ - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_FILTERING_TRUE)); + JTableStats table = panel.getTable(); + if (table == null || table.getSelectedRow() == -1) return; + int indexData = table.convertRowIndexToModel(table.getSelectedRow()); + AmountHolder data = (AmountHolder) table.getTableData().get(indexData); + + if (e.getSource() == panel.getBtnKillAll()) { + PacketManager.sendToServer(new PacketReqData(Message.COMMAND_KILLALL, new SerialString(data.key.str))); + PacketManager.sendToServer(new PacketReqData(Message.LIST_AMOUNT_ENTITIES)); } - else if (e.getStateChange() == ItemEvent.DESELECTED){ - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_FILTERING_FALSE)); + + if (e.getSource() == panel.getBtnRefresh()) { + PacketManager.sendToServer(new PacketReqData(Message.LIST_AMOUNT_ENTITIES)); + } + } + + @Override + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + PacketManager.sendToServer(new PacketReqData(Message.COMMAND_FILTERING_TRUE)); + } else if (e.getStateChange() == ItemEvent.DESELECTED) { + PacketManager.sendToServer(new PacketReqData(Message.COMMAND_FILTERING_FALSE)); } PacketManager.sendToServer(new PacketReqData(Message.LIST_AMOUNT_ENTITIES)); - } - + } } diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountTileEnts.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountTileEnts.java index 3234bbc..541f690 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountTileEnts.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountTileEnts.java @@ -2,29 +2,28 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.panels.tracking.PanelAmountTileEnts; -import mcp.mobius.opis.api.TabPanelRegistrar; -public class ActionAmountTileEnts implements ActionListener{ +public class ActionAmountTileEnts implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - PanelAmountTileEnts panel = (PanelAmountTileEnts)TabPanelRegistrar.INSTANCE.getTab(SelectedTab.AMOUNTTES); + @Override + public void actionPerformed(ActionEvent e) { + PanelAmountTileEnts panel = (PanelAmountTileEnts) TabPanelRegistrar.INSTANCE.getTab(SelectedTab.AMOUNTTES); - /* - JTableStats table = panel.getTable(); - if (table == null || table.getSelectedRow() == -1) return; - int indexData = table.convertRowIndexToModel(table.getSelectedRow()); - DataBlockTileEntityPerClass data = (DataBlockTileEntityPerClass)table.getTableData().get(indexData); - */ - - if (e.getSource() == panel.getBtnRefresh()){ - PacketManager.sendToServer(new PacketReqData(Message.LIST_AMOUNT_TILEENTS)); - } - - } + /* + JTableStats table = panel.getTable(); + if (table == null || table.getSelectedRow() == -1) return; + int indexData = table.convertRowIndexToModel(table.getSelectedRow()); + DataBlockTileEntityPerClass data = (DataBlockTileEntityPerClass)table.getTableData().get(indexData); + */ + + if (e.getSource() == panel.getBtnRefresh()) { + PacketManager.sendToServer(new PacketReqData(Message.LIST_AMOUNT_TILEENTS)); + } + } } diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionDimensions.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionDimensions.java index 32a30f9..5168d91 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionDimensions.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionDimensions.java @@ -2,9 +2,7 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; - import javax.swing.JOptionPane; - import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.data.holders.basetypes.SerialInt; import mcp.mobius.opis.data.holders.newtypes.DataDimension; @@ -15,35 +13,46 @@ import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.panels.tracking.PanelDimensions; import mcp.mobius.opis.swing.widgets.JTableStats; -public class ActionDimensions implements ActionListener { +public class ActionDimensions implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - PanelDimensions panel = (PanelDimensions)TabPanelRegistrar.INSTANCE.getTab(SelectedTab.DIMENSIONS); - - if (e.getSource() == panel.getBtnPurgeAll()){ - if (JOptionPane.showConfirmDialog (null, "Do you want to kill all hostiles in game ?","Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_KILL_HOSTILES_ALL)); - if (JOptionPane.showConfirmDialog (null, "Do you want to remove all the dropped items ?","Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_KILL_STACKS_ALL)); - if (JOptionPane.showConfirmDialog (null, "Do you want to purge chunks ?","Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_PURGE_CHUNKS_ALL)); - - } else { - JTableStats table = panel.getTable(); - if (table == null || table.getSelectedRow() == -1) return; - int indexData = table.convertRowIndexToModel(table.getSelectedRow()); - DataDimension data = (DataDimension)table.getTableData().get(indexData); + @Override + public void actionPerformed(ActionEvent e) { + PanelDimensions panel = (PanelDimensions) TabPanelRegistrar.INSTANCE.getTab(SelectedTab.DIMENSIONS); - if (JOptionPane.showConfirmDialog (null, "Do you want to kill all hostiles ?","Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_KILL_HOSTILES_DIM, new SerialInt(data.dim))); - if (JOptionPane.showConfirmDialog (null, "Do you want to remove all the dropped items ?","Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_KILL_STACKS_DIM, new SerialInt(data.dim))); - if (JOptionPane.showConfirmDialog (null, "Do you want to purge chunks ?","Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_PURGE_CHUNKS_DIM, new SerialInt(data.dim))); - - } - - } + if (e.getSource() == panel.getBtnPurgeAll()) { + if (JOptionPane.showConfirmDialog( + null, "Do you want to kill all hostiles in game ?", "Warning", JOptionPane.YES_NO_OPTION) + == JOptionPane.YES_OPTION) + PacketManager.sendToServer(new PacketReqData(Message.COMMAND_KILL_HOSTILES_ALL)); + if (JOptionPane.showConfirmDialog( + null, "Do you want to remove all the dropped items ?", "Warning", JOptionPane.YES_NO_OPTION) + == JOptionPane.YES_OPTION) + PacketManager.sendToServer(new PacketReqData(Message.COMMAND_KILL_STACKS_ALL)); + if (JOptionPane.showConfirmDialog( + null, "Do you want to purge chunks ?", "Warning", JOptionPane.YES_NO_OPTION) + == JOptionPane.YES_OPTION) + PacketManager.sendToServer(new PacketReqData(Message.COMMAND_PURGE_CHUNKS_ALL)); + } else { + JTableStats table = panel.getTable(); + if (table == null || table.getSelectedRow() == -1) return; + int indexData = table.convertRowIndexToModel(table.getSelectedRow()); + DataDimension data = (DataDimension) table.getTableData().get(indexData); + + if (JOptionPane.showConfirmDialog( + null, "Do you want to kill all hostiles ?", "Warning", JOptionPane.YES_NO_OPTION) + == JOptionPane.YES_OPTION) + PacketManager.sendToServer( + new PacketReqData(Message.COMMAND_KILL_HOSTILES_DIM, new SerialInt(data.dim))); + if (JOptionPane.showConfirmDialog( + null, "Do you want to remove all the dropped items ?", "Warning", JOptionPane.YES_NO_OPTION) + == JOptionPane.YES_OPTION) + PacketManager.sendToServer(new PacketReqData(Message.COMMAND_KILL_STACKS_DIM, new SerialInt(data.dim))); + if (JOptionPane.showConfirmDialog( + null, "Do you want to purge chunks ?", "Warning", JOptionPane.YES_NO_OPTION) + == JOptionPane.YES_OPTION) + PacketManager.sendToServer( + new PacketReqData(Message.COMMAND_PURGE_CHUNKS_DIM, new SerialInt(data.dim))); + } + } } diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionOrphanTileEntities.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionOrphanTileEntities.java index bd2d4f9..853ccda 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionOrphanTileEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionOrphanTileEntities.java @@ -2,7 +2,6 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; - import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; @@ -12,14 +11,13 @@ import mcp.mobius.opis.swing.panels.debug.PanelOrphanTileEntities; public class ActionOrphanTileEntities implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - PanelOrphanTileEntities panel = (PanelOrphanTileEntities)TabPanelRegistrar.INSTANCE.getTab(SelectedTab.ORPHANTES); - - if (e.getSource() == panel.getBtnRefresh()){ - PacketManager.sendToServer(new PacketReqData(Message.LIST_ORPHAN_TILEENTS)); - } - - } - + @Override + public void actionPerformed(ActionEvent e) { + PanelOrphanTileEntities panel = + (PanelOrphanTileEntities) TabPanelRegistrar.INSTANCE.getTab(SelectedTab.ORPHANTES); + + if (e.getSource() == panel.getBtnRefresh()) { + PacketManager.sendToServer(new PacketReqData(Message.LIST_ORPHAN_TILEENTS)); + } + } } diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionPlayers.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionPlayers.java index d6e9162..bf6b276 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionPlayers.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionPlayers.java @@ -2,41 +2,41 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import mcp.mobius.opis.api.TabPanelRegistrar; +import mcp.mobius.opis.data.holders.basetypes.TargetEntity; +import mcp.mobius.opis.data.holders.newtypes.DataEntity; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.panels.tracking.PanelPlayers; import mcp.mobius.opis.swing.widgets.JTableStats; - -import mcp.mobius.opis.api.TabPanelRegistrar; -import mcp.mobius.opis.data.holders.basetypes.TargetEntity; -import mcp.mobius.opis.data.holders.newtypes.DataEntity; import net.minecraft.client.Minecraft; public class ActionPlayers implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - PanelPlayers panel = (PanelPlayers)TabPanelRegistrar.INSTANCE.getTab(SelectedTab.PLAYERS); - - JTableStats table = panel.getTable(); - if (table == null || table.getSelectedRow() == -1) return; - int indexData = table.convertRowIndexToModel(table.getSelectedRow()); - DataEntity data = (DataEntity)table.getTableData().get(indexData); - - if (e.getSource() == panel.getBtnTeleport()){ - int eid = data.eid; - int dim = data.pos.dim; - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_TELEPORT_TO_ENTITY, new TargetEntity(eid, dim))); - Minecraft.getMinecraft().setIngameFocus(); - } - - if (e.getSource() == panel.getBtnPull()){ - int eid = data.eid; - int dim = data.pos.dim; - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_TELEPORT_PULL_ENTITY, new TargetEntity(eid, dim))); - } - } + @Override + public void actionPerformed(ActionEvent e) { + PanelPlayers panel = (PanelPlayers) TabPanelRegistrar.INSTANCE.getTab(SelectedTab.PLAYERS); + JTableStats table = panel.getTable(); + if (table == null || table.getSelectedRow() == -1) return; + int indexData = table.convertRowIndexToModel(table.getSelectedRow()); + DataEntity data = (DataEntity) table.getTableData().get(indexData); + + if (e.getSource() == panel.getBtnTeleport()) { + int eid = data.eid; + int dim = data.pos.dim; + PacketManager.sendToServer( + new PacketReqData(Message.COMMAND_TELEPORT_TO_ENTITY, new TargetEntity(eid, dim))); + Minecraft.getMinecraft().setIngameFocus(); + } + + if (e.getSource() == panel.getBtnPull()) { + int eid = data.eid; + int dim = data.pos.dim; + PacketManager.sendToServer( + new PacketReqData(Message.COMMAND_TELEPORT_PULL_ENTITY, new TargetEntity(eid, dim))); + } + } } diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionRunOpis.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionRunOpis.java index 6e2bf51..a3de88c 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionRunOpis.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionRunOpis.java @@ -2,15 +2,14 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; - import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; public class ActionRunOpis implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_START)); - } + @Override + public void actionPerformed(ActionEvent e) { + PacketManager.sendToServer(new PacketReqData(Message.COMMAND_START)); + } } diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionRunOpisClient.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionRunOpisClient.java index 7b5be85..52d6df7 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionRunOpisClient.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionRunOpisClient.java @@ -1,18 +1,17 @@ package mcp.mobius.opis.swing.actions; +import cpw.mods.fml.relauncher.Side; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; - -import cpw.mods.fml.relauncher.Side; import mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.modOpis; public class ActionRunOpisClient implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - modOpis.profilerRunClient = true; - ProfilerSection.resetAll (Side.CLIENT); - ProfilerSection.activateAll(Side.CLIENT); - } + @Override + public void actionPerformed(ActionEvent e) { + modOpis.profilerRunClient = true; + ProfilerSection.resetAll(Side.CLIENT); + ProfilerSection.activateAll(Side.CLIENT); + } } diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingChunks.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingChunks.java index 39a6c27..48ef3cd 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingChunks.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingChunks.java @@ -2,6 +2,8 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import mcp.mobius.opis.api.TabPanelRegistrar; +import mcp.mobius.opis.data.holders.stats.StatsChunk; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; @@ -9,22 +11,19 @@ import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.panels.timingserver.PanelTimingChunks; import mcp.mobius.opis.swing.widgets.JTableStats; -import mcp.mobius.opis.api.TabPanelRegistrar; -import mcp.mobius.opis.data.holders.stats.StatsChunk; - public class ActionTimingChunks implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - PanelTimingChunks panel = (PanelTimingChunks)TabPanelRegistrar.INSTANCE.getTab(SelectedTab.TIMINGCHUNKS); - - JTableStats table = panel.getTable(); - if (table == null || table.getSelectedRow() == -1) return; - int indexData = table.convertRowIndexToModel(table.getSelectedRow()); - StatsChunk data = (StatsChunk)table.getTableData().get(indexData); - - if (e.getSource() == panel.getBtnTeleport()){ - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_TELEPORT_CHUNK, data.getChunk())); - } - } + @Override + public void actionPerformed(ActionEvent e) { + PanelTimingChunks panel = (PanelTimingChunks) TabPanelRegistrar.INSTANCE.getTab(SelectedTab.TIMINGCHUNKS); + + JTableStats table = panel.getTable(); + if (table == null || table.getSelectedRow() == -1) return; + int indexData = table.convertRowIndexToModel(table.getSelectedRow()); + StatsChunk data = (StatsChunk) table.getTableData().get(indexData); + + if (e.getSource() == panel.getBtnTeleport()) { + PacketManager.sendToServer(new PacketReqData(Message.COMMAND_TELEPORT_CHUNK, data.getChunk())); + } + } } diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingEntities.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingEntities.java index 34e7755..682d71e 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingEntities.java @@ -2,42 +2,41 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import mcp.mobius.opis.api.TabPanelRegistrar; +import mcp.mobius.opis.data.holders.basetypes.TargetEntity; +import mcp.mobius.opis.data.holders.newtypes.DataEntity; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.panels.timingserver.PanelTimingEntities; import mcp.mobius.opis.swing.widgets.JTableStats; - -import mcp.mobius.opis.api.TabPanelRegistrar; -import mcp.mobius.opis.data.holders.basetypes.TargetEntity; -import mcp.mobius.opis.data.holders.newtypes.DataEntity; import net.minecraft.client.Minecraft; public class ActionTimingEntities implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - PanelTimingEntities panel = (PanelTimingEntities)TabPanelRegistrar.INSTANCE.getTab(SelectedTab.TIMINGENTITES); - - JTableStats table = panel.getTable(); - if (table == null || table.getSelectedRow() == -1) return; - int indexData = table.convertRowIndexToModel(table.getSelectedRow()); - DataEntity data = (DataEntity)table.getTableData().get(indexData); + @Override + public void actionPerformed(ActionEvent e) { + PanelTimingEntities panel = (PanelTimingEntities) TabPanelRegistrar.INSTANCE.getTab(SelectedTab.TIMINGENTITES); - if (e.getSource() == panel.getBtnTeleport()){ + JTableStats table = panel.getTable(); + if (table == null || table.getSelectedRow() == -1) return; + int indexData = table.convertRowIndexToModel(table.getSelectedRow()); + DataEntity data = (DataEntity) table.getTableData().get(indexData); + + if (e.getSource() == panel.getBtnTeleport()) { int eid = data.eid; int dim = data.pos.dim; - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_TELEPORT_TO_ENTITY, new TargetEntity(eid, dim))); - Minecraft.getMinecraft().setIngameFocus(); - } - - if (e.getSource() == panel.getBtnPull()){ + PacketManager.sendToServer( + new PacketReqData(Message.COMMAND_TELEPORT_TO_ENTITY, new TargetEntity(eid, dim))); + Minecraft.getMinecraft().setIngameFocus(); + } + + if (e.getSource() == panel.getBtnPull()) { int eid = data.eid; int dim = data.pos.dim; - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_TELEPORT_PULL_ENTITY, new TargetEntity(eid, dim))); - } - - } - + PacketManager.sendToServer( + new PacketReqData(Message.COMMAND_TELEPORT_PULL_ENTITY, new TargetEntity(eid, dim))); + } + } } diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingTileEnts.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingTileEnts.java index 735d6e1..223a422 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingTileEnts.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingTileEnts.java @@ -2,6 +2,9 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import mcp.mobius.opis.api.TabPanelRegistrar; +import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; +import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; import mcp.mobius.opis.modOpis; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; @@ -9,33 +12,28 @@ import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.panels.timingserver.PanelTimingTileEnts; import mcp.mobius.opis.swing.widgets.JTableStats; - -import mcp.mobius.opis.api.TabPanelRegistrar; -import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; -import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; import net.minecraft.client.Minecraft; public class ActionTimingTileEnts implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - PanelTimingTileEnts panel = (PanelTimingTileEnts)TabPanelRegistrar.INSTANCE.getTab(SelectedTab.TIMINGTILEENTS); - - JTableStats table = panel.getTable(); - if (table == null || table.getSelectedRow() == -1) return; - int indexData = table.convertRowIndexToModel(table.getSelectedRow()); - DataBlockTileEntity data = (DataBlockTileEntity)table.getTableData().get(indexData); - - if (e.getSource() == panel.getBtnTeleport()){ + @Override + public void actionPerformed(ActionEvent e) { + PanelTimingTileEnts panel = (PanelTimingTileEnts) TabPanelRegistrar.INSTANCE.getTab(SelectedTab.TIMINGTILEENTS); + + JTableStats table = panel.getTable(); + if (table == null || table.getSelectedRow() == -1) return; + int indexData = table.convertRowIndexToModel(table.getSelectedRow()); + DataBlockTileEntity data = (DataBlockTileEntity) table.getTableData().get(indexData); + + if (e.getSource() == panel.getBtnTeleport()) { CoordinatesBlock coord = data.pos; modOpis.selectedBlock = coord; PacketManager.sendToServer(new PacketReqData(Message.COMMAND_TELEPORT_BLOCK, coord)); - Minecraft.getMinecraft().setIngameFocus(); - } - - if (e.getSource() == panel.getBtnReset()){ - modOpis.selectedBlock = null; - } - } + Minecraft.getMinecraft().setIngameFocus(); + } + if (e.getSource() == panel.getBtnReset()) { + modOpis.selectedBlock = null; + } + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/PanelSummary.java b/src/main/java/mcp/mobius/opis/swing/panels/PanelSummary.java index 255f185..0ab63d6 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/PanelSummary.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/PanelSummary.java @@ -4,9 +4,11 @@ import java.awt.Color; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; - +import javax.swing.JButton; +import javax.swing.JLabel; import javax.swing.JPanel; - +import javax.swing.JProgressBar; +import javax.swing.JTabbedPane; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.client.DataCache; import mcp.mobius.opis.data.holders.ISerializable; @@ -25,12 +27,6 @@ import mcp.mobius.opis.swing.widgets.JButtonAccess; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import net.miginfocom.swing.MigLayout; import net.minecraft.util.MathHelper; - -import javax.swing.JLabel; -import javax.swing.JButton; -import javax.swing.JProgressBar; -import javax.swing.JTabbedPane; - import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; @@ -42,420 +38,471 @@ import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; -public class PanelSummary extends JPanelMsgHandler implements ITabPanel{ - private JLabel lblTimingWorldTick; - private JLabel lblTimingTileEnts; - private JLabel lblTimingEntities; - //private JLabel lblTimingHandlers; - private JLabel lblTimingTotal; - private JLabel lblTickTime; - private JLabel lblAmountTileEnts; - private JLabel lblAmountEntities; - //private JLabel lblAmountHandlers; - private JLabel lblAmountUpload; - private JLabel lblAmountDownload; - private JLabel lblAmountForced; - private JLabel lblAmountLoaded; - private JButtonAccess btnRun; - private JProgressBar progressBarRun; - private JLabel lblTimeStamp; - private JTabbedPane tabGraphs; - - private DescriptiveStatistics pingData = new DescriptiveStatistics(5); - private long nPings = 0; - - /** - * Create the panel. - */ - public PanelSummary() { - setLayout(new MigLayout("", "[20px:20px:20px,grow][][20px:20px:20px][60px:60px:60px][][20px:20px:20px][50px:50px:50px][20px:20px:20px][][20px:20px:20px][50px:50px:50px][][20px:20px:20px][grow][]", "[20px:20px:20px][][][][][][][][][20px:20px:20px][][grow]")); - - JLabel lblNewLabel_5 = new JLabel("Update time"); - add(lblNewLabel_5, "cell 3 1 2 1,alignx right"); - - JLabel lblNewLabel_16 = new JLabel("Amount"); - add(lblNewLabel_16, "cell 6 1,alignx right"); - - JLabel lblNewLabel_24 = new JLabel("Amount"); - add(lblNewLabel_24, "cell 10 1 2 1,alignx right"); - - btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); - add(btnRun, "cell 14 1,alignx right"); - btnRun.addActionListener(new ActionRunOpis()); - - JLabel lblNewLabel = new JLabel("World tick"); - add(lblNewLabel, "cell 1 2"); - - lblTimingWorldTick = new JLabel("0"); - add(lblTimingWorldTick, "cell 3 2 2 1,alignx right"); - - JLabel lblNewLabel_20 = new JLabel("Upload"); - add(lblNewLabel_20, "cell 8 2"); - - lblAmountUpload = new JLabel("0"); - add(lblAmountUpload, "cell 10 2,alignx right"); - - JLabel lblNewLabel_30 = new JLabel("kB/s"); - add(lblNewLabel_30, "cell 11 2,alignx right"); - - progressBarRun = new JProgressBar(); - add(progressBarRun, "cell 13 2 2 1,growx"); - - JLabel lblNewLabel_1 = new JLabel("TileEntities"); - add(lblNewLabel_1, "cell 1 3"); - - lblTimingTileEnts = new JLabel("0"); - add(lblTimingTileEnts, "cell 3 3 2 1,alignx right"); - - lblAmountTileEnts = new JLabel("0"); - add(lblAmountTileEnts, "cell 6 3,alignx right"); - - JLabel lblNewLabel_21 = new JLabel("Download"); - add(lblNewLabel_21, "cell 8 3"); - - lblAmountDownload = new JLabel("0"); - add(lblAmountDownload, "cell 10 3,alignx right"); - - JLabel lblNewLabel_29 = new JLabel("kB/s"); - add(lblNewLabel_29, "cell 11 3,alignx right"); - - lblTimeStamp = new JLabel("Last run : Never"); - add(lblTimeStamp, "cell 13 3 2 1,alignx right"); - - JLabel lblNewLabel_2 = new JLabel("Entities"); - add(lblNewLabel_2, "cell 1 4"); - - lblTimingEntities = new JLabel("0"); - add(lblTimingEntities, "cell 3 4 2 1,alignx right"); - - lblAmountEntities = new JLabel("0"); - add(lblAmountEntities, "cell 6 4,alignx right"); - - JLabel lblNewLabel_6 = new JLabel("Ping"); - add(lblNewLabel_6, "cell 8 4"); - - lblTimingPing = new JLabel("0"); - add(lblTimingPing, "cell 10 4 2 1,alignx right"); - - //JLabel lblNewLabel_3 = new JLabel("Handlers"); - //add(lblNewLabel_3, "cell 1 5"); - - //lblTimingHandlers = new JLabel("0"); - //add(lblTimingHandlers, "cell 3 5 2 1,alignx right"); - - //lblAmountHandlers = new JLabel("0"); - //add(lblAmountHandlers, "cell 6 5,alignx right"); - - JLabel lblNewLabel_22 = new JLabel("Forced chunks"); - add(lblNewLabel_22, "cell 8 6"); - - lblAmountForced = new JLabel("0"); - add(lblAmountForced, "cell 10 6 2 1,alignx right"); - - JLabel lblNewLabel_23 = new JLabel("Loaded chunks"); - add(lblNewLabel_23, "cell 8 7"); - - lblAmountLoaded = new JLabel("0"); - add(lblAmountLoaded, "cell 10 7 2 1,alignx right"); +public class PanelSummary extends JPanelMsgHandler implements ITabPanel { + private JLabel lblTimingWorldTick; + private JLabel lblTimingTileEnts; + private JLabel lblTimingEntities; + // private JLabel lblTimingHandlers; + private JLabel lblTimingTotal; + private JLabel lblTickTime; + private JLabel lblAmountTileEnts; + private JLabel lblAmountEntities; + // private JLabel lblAmountHandlers; + private JLabel lblAmountUpload; + private JLabel lblAmountDownload; + private JLabel lblAmountForced; + private JLabel lblAmountLoaded; + private JButtonAccess btnRun; + private JProgressBar progressBarRun; + private JLabel lblTimeStamp; + private JTabbedPane tabGraphs; - JLabel lblNewLabel_4 = new JLabel("Total"); - add(lblNewLabel_4, "cell 1 6"); - - lblTimingTotal = new JLabel("0"); - add(lblTimingTotal, "cell 3 6 2 1,alignx right"); - - JLabel lblNewLabel_31 = new JLabel("Tick Time"); - add(lblNewLabel_31, "cell 1 10"); - - lblTickTime = new JLabel("0"); - add(lblTickTime, "cell 3 10 2 1,alignx right"); - - - tabGraphs = new JTabbedPane(); - add(tabGraphs, "cell 0 11 15 1,grow"); - - JPanel panelTick = this.createTickGraph(); - tabGraphs.addTab("Tick time", panelTick); - - JPanel panelPing = this.createPingGraph(); - tabGraphs.addTab("Ping", panelPing); + private DescriptiveStatistics pingData = new DescriptiveStatistics(5); + private long nPings = 0; - } - //JLabel lblNewLabel_32 = new JLabel("Network"); - //add(lblNewLabel_32, "cell 1 6"); - - //lblTimingNetwork = new JLabel("0"); - //add(lblTimingNetwork, "cell 3 6 2 1,alignx right"); - - //JLabel lblNewLabel_4 = new JLabel("Total"); - //add(lblNewLabel_4, "cell 1 8"); - - //lblTimingTotal = new JLabel("0"); - //add(lblTimingTotal, "cell 3 8 2 1,alignx right"); - - public JLabel getLblTimingWorldTick() {return lblTimingWorldTick;} - public JLabel getLblTimingTileEnts() {return lblTimingTileEnts;} - public JLabel getLblTimingEntities() {return lblTimingEntities;} - //public JLabel getLblTimingHandlers() {return lblTimingHandlers;} - public JLabel getLblTimingTotal() {return lblTimingTotal;} - public JLabel getLblTickTime() {return lblTickTime;} - public JLabel getLblAmountTileEnts() {return lblAmountTileEnts;} - public JLabel getLblAmountEntities() {return lblAmountEntities;} - //public JLabel getLblAmountHandlers() {return lblAmountHandlers;} - public JLabel getLblAmountUpload() {return lblAmountUpload;} - public JLabel getLblAmountDownload() {return lblAmountDownload;} - public JLabel getLblAmountForced() {return lblAmountForced;} - public JLabel getLblAmountLoaded() {return lblAmountLoaded;} - public JButton getBtnRun() {return btnRun;} - public JProgressBar getProgressBarRun() {return progressBarRun;} - public JLabel getLblTimeStamp() {return lblTimeStamp;} + /** + * Create the panel. + */ + public PanelSummary() { + setLayout(new MigLayout( + "", + "[20px:20px:20px,grow][][20px:20px:20px][60px:60px:60px][][20px:20px:20px][50px:50px:50px][20px:20px:20px][][20px:20px:20px][50px:50px:50px][][20px:20px:20px][grow][]", + "[20px:20px:20px][][][][][][][][][20px:20px:20px][][grow]")); - public void setProgressBar(int min, int max, int value){ - if (min != -1) - this.getProgressBarRun().setMinimum(min); - - if (max != -1) - this.getProgressBarRun().setMaximum(max); - - if (value != -1) - this.getProgressBarRun().setValue(value); - } - - private DataTimingMillisecond timingWorldTickTotal = new DataTimingMillisecond(); - private DataTimingMillisecond timingHandlersTotal = new DataTimingMillisecond(); - private DataTimingMillisecond timingTileEntsTotal = new DataTimingMillisecond(); - private DataTimingMillisecond timingEntitiesTotal = new DataTimingMillisecond(); - private DataTimingMillisecond timingNetworkTotal = new DataTimingMillisecond(); - - public void setTimingEntUpdateTotal(double value){ - } - - ArrayList datapointsTick = new ArrayList(); - ArrayList datapointsPing = new ArrayList(); - XYSeries xydataTick = new XYSeries("Update time"); - XYSeries xydataPing = new XYSeries("Ping"); - XYSeriesCollection datasetTick = new XYSeriesCollection(); - XYSeriesCollection datasetPing = new XYSeriesCollection(); - XYPlot xyPlotTick; - XYPlot xyPlotPing; - private JLabel lblTimingNetwork; - private JLabel lblTimingPing; - - private JPanel createTickGraph(){ - JFreeChart chart = ChartFactory.createXYAreaChart("", "Seconds", "Update Time [ms]", datasetTick, PlotOrientation.VERTICAL, false, false, false); - chart.setBackgroundPaint(new Color(255,255,255,0)); - xyPlotTick = chart.getXYPlot(); - xyPlotTick.getRendererForDataset(datasetTick).setSeriesPaint(0, Color.BLUE); - - for (double y = 25.0; y < 500.0; y += 25.0){ - ValueMarker marker = new ValueMarker(y); - marker.setPaint(Color.black); - xyPlotTick.addRangeMarker(marker); - } + JLabel lblNewLabel_5 = new JLabel("Update time"); + add(lblNewLabel_5, "cell 3 1 2 1,alignx right"); - //ValueMarker marker = new ValueMarker(50.0); - //marker.setPaint(Color.red); - //xyPlot.addRangeMarker(marker); - - return new ChartPanel(chart); - } - - private JPanel createPingGraph(){ - JFreeChart chart = ChartFactory.createXYAreaChart("", "Seconds", "Ping Time [ms]", datasetPing, PlotOrientation.VERTICAL, false, false, false); - chart.setBackgroundPaint(new Color(255,255,255,0)); - xyPlotPing = chart.getXYPlot(); - xyPlotPing.getRendererForDataset(datasetPing).setSeriesPaint(0, Color.BLUE); - - for (double y = 200.0; y < 10000.0; y += 200.0){ - ValueMarker marker = new ValueMarker(y); - marker.setPaint(Color.black); - xyPlotPing.addRangeMarker(marker); - } + JLabel lblNewLabel_16 = new JLabel("Amount"); + add(lblNewLabel_16, "cell 6 1,alignx right"); - //ValueMarker marker = new ValueMarker(50.0); - //marker.setPaint(Color.red); - //xyPlot.addRangeMarker(marker); - - return new ChartPanel(chart); - } - - public void setTimingTick(ISerializable tickStat){ - DataTimingMillisecond ticktime = ((DataTiming)tickStat).asMillisecond(); - - this.getLblTickTime().setText(ticktime.toString()); + JLabel lblNewLabel_24 = new JLabel("Amount"); + add(lblNewLabel_24, "cell 10 1 2 1,alignx right"); - datapointsTick.add(ticktime.timing/1000./1000.); - if (datapointsTick.size() > 101) - datapointsTick.remove(0); - - xydataTick.clear(); - for (int i = 0; i < datapointsTick.size(); i++) - xydataTick.add(i, datapointsTick.get(i)); + btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); + add(btnRun, "cell 14 1,alignx right"); + btnRun.addActionListener(new ActionRunOpis()); - datasetTick.removeAllSeries(); - datasetTick.addSeries(xydataTick); - - Double verticalScale = 50.0 * (MathHelper.floor_double(xydataTick.getMaxY() / 50.0D) + 1); - ((NumberAxis)xyPlotTick.getRangeAxis()).setRange(0.0, verticalScale); - ((NumberAxis)xyPlotTick.getDomainAxis()).setRange(0.0, 100.0); - } + JLabel lblNewLabel = new JLabel("World tick"); + add(lblNewLabel, "cell 1 2"); - public void setTimingPing(ISerializable pingStat){ - DataTimingMillisecond pingtime = ((DataTiming)pingStat).asMillisecond(); - - //this.getLblTickTime().setText(pingtime.toString()); + lblTimingWorldTick = new JLabel("0"); + add(lblTimingWorldTick, "cell 3 2 2 1,alignx right"); - datapointsPing.add(pingtime.timing/1000./1000.); - if (datapointsPing.size() > 101) - datapointsPing.remove(0); - - xydataPing.clear(); - for (int i = 0; i < datapointsPing.size(); i++) - xydataPing.add(i, datapointsPing.get(i)); + JLabel lblNewLabel_20 = new JLabel("Upload"); + add(lblNewLabel_20, "cell 8 2"); - datasetPing.removeAllSeries(); - datasetPing.addSeries(xydataPing); - - Double verticalScale = 500.0 * (MathHelper.floor_double(xydataPing.getMaxY() / 500.0D) + 1); - ((NumberAxis)xyPlotPing.getRangeAxis()).setRange(0.0, verticalScale); - ((NumberAxis)xyPlotPing.getDomainAxis()).setRange(0.0, 100.0); - } - - private DataTimingMillisecond getProfiledTickTotalTime(){ - //return new DataTimingMillisecond(timingWorldTickTotal.timing + timingTileEntsTotal.timing + timingEntitiesTotal.timing + timingHandlersTotal.timing + timingNetworkTotal.timing); - return new DataTimingMillisecond(timingWorldTickTotal.timing + timingTileEntsTotal.timing + timingEntitiesTotal.timing + timingHandlersTotal.timing); - } + lblAmountUpload = new JLabel("0"); + add(lblAmountUpload, "cell 10 2,alignx right"); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - - case NEXUS_DATA:{ - NexusData data = (NexusData)rawdata.value; - - this.getLblAmountTileEnts().setText(String.valueOf(data.amountTileEnts.value)); - this.getLblAmountEntities().setText(String.valueOf(data.amountEntities.value)); - double uploadKB = data.packetOutbound.value / 1024.0; - this.getLblAmountUpload().setText(String.format("%.3f", uploadKB)); - double downloadKB = data.packetInbound.value / 1024.0; - this.getLblAmountDownload().setText(String.format("%.3f", downloadKB)); - this.setTimingTick(data.timingTick); - this.getLblAmountForced().setText(String.valueOf(data.chunkForced.value)); - this.getLblAmountLoaded().setText(String.valueOf(data.chunkLoaded.value)); - break; - } - - case VALUE_TIMING_NETWORK:{ - //this.timingNetworkTotal = ((DataNetworkTick)rawdata.value).update.asMillisecond(); - //this.getLblTimingNetwork().setText(this.timingNetworkTotal.toString()); - break; - } - case VALUE_TIMING_TILEENTS:{ - this.timingTileEntsTotal = ((DataTiming)rawdata.value).asMillisecond(); - this.getLblTimingTileEnts().setText(this.timingTileEntsTotal.toString()); - this.getLblTimingTotal().setText(String.format("%s", this.getProfiledTickTotalTime().toString() )); - break; - } - case VALUE_TIMING_ENTITIES:{ - this.timingEntitiesTotal = ((DataTiming)rawdata.value).asMillisecond(); - this.getLblTimingEntities().setText(this.timingEntitiesTotal.toString()); - this.getLblTimingTotal().setText(String.format("%s", this.getProfiledTickTotalTime().toString() )); - break; - } - //case VALUE_TIMING_HANDLERS:{ - // this.timingHandlersTotal = ((DataTiming)rawdata.value).asMillisecond(); - // this.getLblTimingHandlers().setText(this.timingHandlersTotal.toString()); - // this.getLblTimingTotal().setText(String.format("%s", this.getProfiledTickTotalTime().toString() )); - // break; - //} - case VALUE_TIMING_WORLDTICK:{ - this.timingWorldTickTotal = ((DataBlockTick)rawdata.value).total.asMillisecond(); - this.getLblTimingWorldTick().setText(this.timingWorldTickTotal.toString()); - this.getLblTimingTotal().setText(String.format("%s", this.getProfiledTickTotalTime().toString() )); - - String tooltip = "
";
-			
-			for (Integer indim : ((DataBlockTick)rawdata.value).perdim.keySet()){
-				//System.out.printf("WorldTick [ %4d ] %s\n", indim, ((DataBlockTick)rawdata.value).perdim.get(indim).asMillisecond().toString());
-				tooltip += String.format("[ %4d ] %s
", indim, ((DataBlockTick)rawdata.value).perdim.get(indim).asMillisecond().toString()); - } - - tooltip += "
"; - - this.getLblTimingWorldTick().setToolTipText(tooltip); - - break; - } - case STATUS_START:{ - this.getBtnRun().setText("Running..."); - this.setProgressBar(0, ((SerialInt)rawdata.value).value, 0); - break; - } - case STATUS_STOP:{ - this.getBtnRun().setText("Run Opis"); - this.setProgressBar(0, ((SerialInt)rawdata.value).value, ((SerialInt)rawdata.value).value); - break; - } - case STATUS_RUN_UPDATE:{ - this.setProgressBar(-1, -1, ((SerialInt)rawdata.value).value); - break; - } - case STATUS_RUNNING:{ - this.getBtnRun().setText("Running..."); - this.setProgressBar(-1, -1, ((SerialInt)rawdata.value).value); - break; - } - case STATUS_TIME_LAST_RUN:{ - long serverLastRun = ((SerialLong)rawdata.value).value; - if (serverLastRun == 0){ - this.getLblTimeStamp().setText("Last run : "); - } else { - long clientLastRun = serverLastRun + DataCache.instance().getClockScrew(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date resultdate = new Date(clientLastRun); - - this.getLblTimeStamp().setText(String.format("Last run : %s", sdf.format(resultdate))); - } - break; - } - - case VALUE_TIMING_ENTUPDATE:{ - break; - } - - case STATUS_PING:{ - this.pingData.addValue(System.nanoTime() - ((SerialLong)rawdata.value).value); - this.nPings += 1; - - //if (this.nPings % 2 == 0){ - DataTiming timing = new DataTiming(this.pingData.getGeometricMean()); - this.setTimingPing(timing); - this.getLblTimingPing().setText(timing.asMillisecond().toString()); - //} - break; - } - - default: - return false; - - } - return true; - } + JLabel lblNewLabel_30 = new JLabel("kB/s"); + add(lblNewLabel_30, "cell 11 2,alignx right"); - public JLabel getLblTimingNetwork() { - return lblTimingNetwork; - } - public JLabel getLblTimingPing() { - return lblTimingPing; - } - - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.SUMMARY; - } - - @Override - public boolean refreshOnString(){ - return false; - } + progressBarRun = new JProgressBar(); + add(progressBarRun, "cell 13 2 2 1,growx"); + + JLabel lblNewLabel_1 = new JLabel("TileEntities"); + add(lblNewLabel_1, "cell 1 3"); + + lblTimingTileEnts = new JLabel("0"); + add(lblTimingTileEnts, "cell 3 3 2 1,alignx right"); + + lblAmountTileEnts = new JLabel("0"); + add(lblAmountTileEnts, "cell 6 3,alignx right"); + + JLabel lblNewLabel_21 = new JLabel("Download"); + add(lblNewLabel_21, "cell 8 3"); + + lblAmountDownload = new JLabel("0"); + add(lblAmountDownload, "cell 10 3,alignx right"); + + JLabel lblNewLabel_29 = new JLabel("kB/s"); + add(lblNewLabel_29, "cell 11 3,alignx right"); + + lblTimeStamp = new JLabel("Last run : Never"); + add(lblTimeStamp, "cell 13 3 2 1,alignx right"); + + JLabel lblNewLabel_2 = new JLabel("Entities"); + add(lblNewLabel_2, "cell 1 4"); + + lblTimingEntities = new JLabel("0"); + add(lblTimingEntities, "cell 3 4 2 1,alignx right"); + + lblAmountEntities = new JLabel("0"); + add(lblAmountEntities, "cell 6 4,alignx right"); + + JLabel lblNewLabel_6 = new JLabel("Ping"); + add(lblNewLabel_6, "cell 8 4"); + + lblTimingPing = new JLabel("0"); + add(lblTimingPing, "cell 10 4 2 1,alignx right"); + + // JLabel lblNewLabel_3 = new JLabel("Handlers"); + // add(lblNewLabel_3, "cell 1 5"); + + // lblTimingHandlers = new JLabel("0"); + // add(lblTimingHandlers, "cell 3 5 2 1,alignx right"); + + // lblAmountHandlers = new JLabel("0"); + // add(lblAmountHandlers, "cell 6 5,alignx right"); + + JLabel lblNewLabel_22 = new JLabel("Forced chunks"); + add(lblNewLabel_22, "cell 8 6"); + + lblAmountForced = new JLabel("0"); + add(lblAmountForced, "cell 10 6 2 1,alignx right"); + + JLabel lblNewLabel_23 = new JLabel("Loaded chunks"); + add(lblNewLabel_23, "cell 8 7"); + + lblAmountLoaded = new JLabel("0"); + add(lblAmountLoaded, "cell 10 7 2 1,alignx right"); + + JLabel lblNewLabel_4 = new JLabel("Total"); + add(lblNewLabel_4, "cell 1 6"); + + lblTimingTotal = new JLabel("0"); + add(lblTimingTotal, "cell 3 6 2 1,alignx right"); + + JLabel lblNewLabel_31 = new JLabel("Tick Time"); + add(lblNewLabel_31, "cell 1 10"); + + lblTickTime = new JLabel("0"); + add(lblTickTime, "cell 3 10 2 1,alignx right"); + + tabGraphs = new JTabbedPane(); + add(tabGraphs, "cell 0 11 15 1,grow"); + + JPanel panelTick = this.createTickGraph(); + tabGraphs.addTab("Tick time", panelTick); + + JPanel panelPing = this.createPingGraph(); + tabGraphs.addTab("Ping", panelPing); + } + // JLabel lblNewLabel_32 = new JLabel("Network"); + // add(lblNewLabel_32, "cell 1 6"); + + // lblTimingNetwork = new JLabel("0"); + // add(lblTimingNetwork, "cell 3 6 2 1,alignx right"); + + // JLabel lblNewLabel_4 = new JLabel("Total"); + // add(lblNewLabel_4, "cell 1 8"); + + // lblTimingTotal = new JLabel("0"); + // add(lblTimingTotal, "cell 3 8 2 1,alignx right"); + + public JLabel getLblTimingWorldTick() { + return lblTimingWorldTick; + } + + public JLabel getLblTimingTileEnts() { + return lblTimingTileEnts; + } + + public JLabel getLblTimingEntities() { + return lblTimingEntities; + } + // public JLabel getLblTimingHandlers() {return lblTimingHandlers;} + public JLabel getLblTimingTotal() { + return lblTimingTotal; + } + + public JLabel getLblTickTime() { + return lblTickTime; + } + + public JLabel getLblAmountTileEnts() { + return lblAmountTileEnts; + } + + public JLabel getLblAmountEntities() { + return lblAmountEntities; + } + // public JLabel getLblAmountHandlers() {return lblAmountHandlers;} + public JLabel getLblAmountUpload() { + return lblAmountUpload; + } + + public JLabel getLblAmountDownload() { + return lblAmountDownload; + } + + public JLabel getLblAmountForced() { + return lblAmountForced; + } + + public JLabel getLblAmountLoaded() { + return lblAmountLoaded; + } + + public JButton getBtnRun() { + return btnRun; + } + + public JProgressBar getProgressBarRun() { + return progressBarRun; + } + + public JLabel getLblTimeStamp() { + return lblTimeStamp; + } + + public void setProgressBar(int min, int max, int value) { + if (min != -1) this.getProgressBarRun().setMinimum(min); + + if (max != -1) this.getProgressBarRun().setMaximum(max); + + if (value != -1) this.getProgressBarRun().setValue(value); + } + + private DataTimingMillisecond timingWorldTickTotal = new DataTimingMillisecond(); + private DataTimingMillisecond timingHandlersTotal = new DataTimingMillisecond(); + private DataTimingMillisecond timingTileEntsTotal = new DataTimingMillisecond(); + private DataTimingMillisecond timingEntitiesTotal = new DataTimingMillisecond(); + private DataTimingMillisecond timingNetworkTotal = new DataTimingMillisecond(); + + public void setTimingEntUpdateTotal(double value) {} + + ArrayList datapointsTick = new ArrayList(); + ArrayList datapointsPing = new ArrayList(); + XYSeries xydataTick = new XYSeries("Update time"); + XYSeries xydataPing = new XYSeries("Ping"); + XYSeriesCollection datasetTick = new XYSeriesCollection(); + XYSeriesCollection datasetPing = new XYSeriesCollection(); + XYPlot xyPlotTick; + XYPlot xyPlotPing; + private JLabel lblTimingNetwork; + private JLabel lblTimingPing; + + private JPanel createTickGraph() { + JFreeChart chart = ChartFactory.createXYAreaChart( + "", "Seconds", "Update Time [ms]", datasetTick, PlotOrientation.VERTICAL, false, false, false); + chart.setBackgroundPaint(new Color(255, 255, 255, 0)); + xyPlotTick = chart.getXYPlot(); + xyPlotTick.getRendererForDataset(datasetTick).setSeriesPaint(0, Color.BLUE); + + for (double y = 25.0; y < 500.0; y += 25.0) { + ValueMarker marker = new ValueMarker(y); + marker.setPaint(Color.black); + xyPlotTick.addRangeMarker(marker); + } + + // ValueMarker marker = new ValueMarker(50.0); + // marker.setPaint(Color.red); + // xyPlot.addRangeMarker(marker); + + return new ChartPanel(chart); + } + + private JPanel createPingGraph() { + JFreeChart chart = ChartFactory.createXYAreaChart( + "", "Seconds", "Ping Time [ms]", datasetPing, PlotOrientation.VERTICAL, false, false, false); + chart.setBackgroundPaint(new Color(255, 255, 255, 0)); + xyPlotPing = chart.getXYPlot(); + xyPlotPing.getRendererForDataset(datasetPing).setSeriesPaint(0, Color.BLUE); + + for (double y = 200.0; y < 10000.0; y += 200.0) { + ValueMarker marker = new ValueMarker(y); + marker.setPaint(Color.black); + xyPlotPing.addRangeMarker(marker); + } + + // ValueMarker marker = new ValueMarker(50.0); + // marker.setPaint(Color.red); + // xyPlot.addRangeMarker(marker); + + return new ChartPanel(chart); + } + + public void setTimingTick(ISerializable tickStat) { + DataTimingMillisecond ticktime = ((DataTiming) tickStat).asMillisecond(); + + this.getLblTickTime().setText(ticktime.toString()); + + datapointsTick.add(ticktime.timing / 1000. / 1000.); + if (datapointsTick.size() > 101) datapointsTick.remove(0); + + xydataTick.clear(); + for (int i = 0; i < datapointsTick.size(); i++) xydataTick.add(i, datapointsTick.get(i)); + + datasetTick.removeAllSeries(); + datasetTick.addSeries(xydataTick); + + Double verticalScale = 50.0 * (MathHelper.floor_double(xydataTick.getMaxY() / 50.0D) + 1); + ((NumberAxis) xyPlotTick.getRangeAxis()).setRange(0.0, verticalScale); + ((NumberAxis) xyPlotTick.getDomainAxis()).setRange(0.0, 100.0); + } + + public void setTimingPing(ISerializable pingStat) { + DataTimingMillisecond pingtime = ((DataTiming) pingStat).asMillisecond(); + + // this.getLblTickTime().setText(pingtime.toString()); + + datapointsPing.add(pingtime.timing / 1000. / 1000.); + if (datapointsPing.size() > 101) datapointsPing.remove(0); + + xydataPing.clear(); + for (int i = 0; i < datapointsPing.size(); i++) xydataPing.add(i, datapointsPing.get(i)); + + datasetPing.removeAllSeries(); + datasetPing.addSeries(xydataPing); + + Double verticalScale = 500.0 * (MathHelper.floor_double(xydataPing.getMaxY() / 500.0D) + 1); + ((NumberAxis) xyPlotPing.getRangeAxis()).setRange(0.0, verticalScale); + ((NumberAxis) xyPlotPing.getDomainAxis()).setRange(0.0, 100.0); + } + + private DataTimingMillisecond getProfiledTickTotalTime() { + // return new DataTimingMillisecond(timingWorldTickTotal.timing + timingTileEntsTotal.timing + + // timingEntitiesTotal.timing + timingHandlersTotal.timing + timingNetworkTotal.timing); + return new DataTimingMillisecond(timingWorldTickTotal.timing + + timingTileEntsTotal.timing + + timingEntitiesTotal.timing + + timingHandlersTotal.timing); + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case NEXUS_DATA: { + NexusData data = (NexusData) rawdata.value; + + this.getLblAmountTileEnts().setText(String.valueOf(data.amountTileEnts.value)); + this.getLblAmountEntities().setText(String.valueOf(data.amountEntities.value)); + double uploadKB = data.packetOutbound.value / 1024.0; + this.getLblAmountUpload().setText(String.format("%.3f", uploadKB)); + double downloadKB = data.packetInbound.value / 1024.0; + this.getLblAmountDownload().setText(String.format("%.3f", downloadKB)); + this.setTimingTick(data.timingTick); + this.getLblAmountForced().setText(String.valueOf(data.chunkForced.value)); + this.getLblAmountLoaded().setText(String.valueOf(data.chunkLoaded.value)); + break; + } + + case VALUE_TIMING_NETWORK: { + // this.timingNetworkTotal = ((DataNetworkTick)rawdata.value).update.asMillisecond(); + // this.getLblTimingNetwork().setText(this.timingNetworkTotal.toString()); + break; + } + case VALUE_TIMING_TILEENTS: { + this.timingTileEntsTotal = ((DataTiming) rawdata.value).asMillisecond(); + this.getLblTimingTileEnts().setText(this.timingTileEntsTotal.toString()); + this.getLblTimingTotal() + .setText(String.format( + "%s", this.getProfiledTickTotalTime().toString())); + break; + } + case VALUE_TIMING_ENTITIES: { + this.timingEntitiesTotal = ((DataTiming) rawdata.value).asMillisecond(); + this.getLblTimingEntities().setText(this.timingEntitiesTotal.toString()); + this.getLblTimingTotal() + .setText(String.format( + "%s", this.getProfiledTickTotalTime().toString())); + break; + } + // case VALUE_TIMING_HANDLERS:{ + // this.timingHandlersTotal = ((DataTiming)rawdata.value).asMillisecond(); + // this.getLblTimingHandlers().setText(this.timingHandlersTotal.toString()); + // this.getLblTimingTotal().setText(String.format("%s", this.getProfiledTickTotalTime().toString() )); + // break; + // } + case VALUE_TIMING_WORLDTICK: { + this.timingWorldTickTotal = ((DataBlockTick) rawdata.value).total.asMillisecond(); + this.getLblTimingWorldTick().setText(this.timingWorldTickTotal.toString()); + this.getLblTimingTotal() + .setText(String.format( + "%s", this.getProfiledTickTotalTime().toString())); + + String tooltip = "
";
+
+                for (Integer indim : ((DataBlockTick) rawdata.value).perdim.keySet()) {
+                    // System.out.printf("WorldTick [ %4d ] %s\n", indim,
+                    // ((DataBlockTick)rawdata.value).perdim.get(indim).asMillisecond().toString());
+                    tooltip += String.format(
+                            "[ %4d ] %s
", + indim, + ((DataBlockTick) rawdata.value) + .perdim + .get(indim) + .asMillisecond() + .toString()); + } + + tooltip += "
"; + + this.getLblTimingWorldTick().setToolTipText(tooltip); + + break; + } + case STATUS_START: { + this.getBtnRun().setText("Running..."); + this.setProgressBar(0, ((SerialInt) rawdata.value).value, 0); + break; + } + case STATUS_STOP: { + this.getBtnRun().setText("Run Opis"); + this.setProgressBar(0, ((SerialInt) rawdata.value).value, ((SerialInt) rawdata.value).value); + break; + } + case STATUS_RUN_UPDATE: { + this.setProgressBar(-1, -1, ((SerialInt) rawdata.value).value); + break; + } + case STATUS_RUNNING: { + this.getBtnRun().setText("Running..."); + this.setProgressBar(-1, -1, ((SerialInt) rawdata.value).value); + break; + } + case STATUS_TIME_LAST_RUN: { + long serverLastRun = ((SerialLong) rawdata.value).value; + if (serverLastRun == 0) { + this.getLblTimeStamp().setText("Last run : "); + } else { + long clientLastRun = serverLastRun + DataCache.instance().getClockScrew(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date resultdate = new Date(clientLastRun); + + this.getLblTimeStamp().setText(String.format("Last run : %s", sdf.format(resultdate))); + } + break; + } + + case VALUE_TIMING_ENTUPDATE: { + break; + } + + case STATUS_PING: { + this.pingData.addValue(System.nanoTime() - ((SerialLong) rawdata.value).value); + this.nPings += 1; + + // if (this.nPings % 2 == 0){ + DataTiming timing = new DataTiming(this.pingData.getGeometricMean()); + this.setTimingPing(timing); + this.getLblTimingPing().setText(timing.asMillisecond().toString()); + // } + break; + } + + default: + return false; + } + return true; + } + + public JLabel getLblTimingNetwork() { + return lblTimingNetwork; + } + + public JLabel getLblTimingPing() { + return lblTimingPing; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.SUMMARY; + } + + @Override + public boolean refreshOnString() { + return false; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelOrphanTileEntities.java b/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelOrphanTileEntities.java index 1c3bff6..d439a82 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelOrphanTileEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelOrphanTileEntities.java @@ -1,5 +1,9 @@ package mcp.mobius.opis.swing.panels.debug; +import javax.swing.JButton; +import javax.swing.JScrollPane; +import javax.swing.SwingConstants; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataTileEntity; @@ -13,84 +17,84 @@ import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JButton; -import javax.swing.JScrollPane; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableModel; - public class PanelOrphanTileEntities extends JPanelMsgHandler implements ITabPanel { - private JButtonAccess btnRefresh; - public PanelOrphanTileEntities() { - setLayout(new MigLayout("", "[grow][]", "[][grow]")); - - btnRefresh = new JButtonAccess("Refresh", AccessLevel.PRIVILEGED); - add(btnRefresh, "cell 1 0"); - btnRefresh.addActionListener(new ActionOrphanTileEntities()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 2 1,grow"); - - table = new JTableStats( - new String[] {"Class", "Hash", "Type", "Dimension", "Coordinates"}, - new Class[] {CachedString.class, String.class, CachedString.class, Integer.class, String.class}, - new int[] {SwingConstants.LEFT, SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER} - ); - scrollPane.setViewportView(table); - } + private JButtonAccess btnRefresh; - int row; - - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_ORPHAN_TILEENTS:{ - this.cacheData(msg, rawdata); - - this.getTable().addTableData(rawdata.array); - DefaultTableModel model = this.getTable().getModel(); - //int row = this.updateData(table, model, DataTileEntity.class); + public PanelOrphanTileEntities() { + setLayout(new MigLayout("", "[grow][]", "[][grow]")); - for (Object o : rawdata.array){ - DataTileEntity data = (DataTileEntity)o; - model.addRow(new Object[] { - data.clazz, - String.format("0x%x", data.hashCode), - data.cause, - data.pos.dim, - String.format("[ %4d %4d %4d ]", data.pos.x, data.pos.y, data.pos.z), - }); - } - - this.getTable().dataUpdated(row); - - break; - } - - case LIST_ORPHAN_TILEENTS_CLEAR:{ - this.getTable().clearTableData(); - DefaultTableModel model = this.getTable().getModel(); - row = this.getTable().clearTable(DataTileEntity.class); - } - - default: - return false; - - } - return true; - } + btnRefresh = new JButtonAccess("Refresh", AccessLevel.PRIVILEGED); + add(btnRefresh, "cell 1 0"); + btnRefresh.addActionListener(new ActionOrphanTileEntities()); - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.ORPHANTES; - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 2 1,grow"); - public JButton getBtnRefresh() { - return btnRefresh; - } + table = new JTableStats( + new String[] {"Class", "Hash", "Type", "Dimension", "Coordinates"}, + new Class[] {CachedString.class, String.class, CachedString.class, Integer.class, String.class}, + new int[] { + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER + }); + scrollPane.setViewportView(table); + } - @Override - public boolean refreshOnString(){ - return true; - } + int row; + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_ORPHAN_TILEENTS: { + this.cacheData(msg, rawdata); + + this.getTable().addTableData(rawdata.array); + DefaultTableModel model = this.getTable().getModel(); + // int row = this.updateData(table, model, DataTileEntity.class); + + for (Object o : rawdata.array) { + DataTileEntity data = (DataTileEntity) o; + model.addRow(new Object[] { + data.clazz, + String.format("0x%x", data.hashCode), + data.cause, + data.pos.dim, + String.format("[ %4d %4d %4d ]", data.pos.x, data.pos.y, data.pos.z), + }); + } + + this.getTable().dataUpdated(row); + + break; + } + + case LIST_ORPHAN_TILEENTS_CLEAR: { + this.getTable().clearTableData(); + DefaultTableModel model = this.getTable().getModel(); + row = this.getTable().clearTable(DataTileEntity.class); + } + + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.ORPHANTES; + } + + public JButton getBtnRefresh() { + return btnRefresh; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelThreads.java b/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelThreads.java index 28d3b70..e68475c 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelThreads.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelThreads.java @@ -1,5 +1,8 @@ package mcp.mobius.opis.swing.panels.debug; +import javax.swing.JScrollPane; +import javax.swing.SwingConstants; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataThread; @@ -10,61 +13,55 @@ import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JScrollPane; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableModel; - public class PanelThreads extends JPanelMsgHandler implements ITabPanel { - public PanelThreads() { - setLayout(new MigLayout("", "[grow]", "[grow]")); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 0,grow"); - - table = new JTableStats( - new String[] {"Name", "Class"}, - new Class[] {CachedString.class, CachedString.class}, - new int[] {SwingConstants.LEFT, SwingConstants.LEFT} - ); - scrollPane.setViewportView(table); - } + public PanelThreads() { + setLayout(new MigLayout("", "[grow]", "[grow]")); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_THREADS:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = this.getTable().getModel(); - int row = this.getTable().clearTable(DataThread.class); + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 0,grow"); - for (Object o : rawdata.array){ - DataThread data = (DataThread)o; - model.addRow(new Object[] { data.name, data.clzz }); - } - - this.getTable().dataUpdated(row); - - break; - } - - default: - return false; - - } - return true; - } + table = new JTableStats( + new String[] {"Name", "Class"}, + new Class[] {CachedString.class, CachedString.class}, + new int[] {SwingConstants.LEFT, SwingConstants.LEFT}); + scrollPane.setViewportView(table); + } - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.THREADS; - } - - @Override - public boolean refreshOnString(){ - return true; - } + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_THREADS: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = this.getTable().getModel(); + int row = this.getTable().clearTable(DataThread.class); + + for (Object o : rawdata.array) { + DataThread data = (DataThread) o; + model.addRow(new Object[] {data.name, data.clzz}); + } + + this.getTable().dataUpdated(row); + + break; + } + + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.THREADS; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound.java b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound.java index c36f7bc..4e42f06 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound.java @@ -2,8 +2,7 @@ package mcp.mobius.opis.swing.panels.network; import javax.swing.JScrollPane; import javax.swing.SwingConstants; - -import net.miginfocom.swing.MigLayout; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.DataAmountRate; import mcp.mobius.opis.data.holders.newtypes.DataByteRate; @@ -14,67 +13,64 @@ import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; - -import javax.swing.table.DefaultTableModel; +import net.miginfocom.swing.MigLayout; public class PanelInbound extends JPanelMsgHandler implements ITabPanel { - public PanelInbound() { - setLayout(new MigLayout("", "[grow]", "[grow]")); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 0,grow"); - - table = new JTableStats( - new String[] {"Type", "ID", "Amount", "Rate", "Total Size"}, - new Class[] {String.class, Integer.class, DataAmountRate.class, DataByteRate.class, DataByteSize.class}, - new int[] {SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.RIGHT, SwingConstants.RIGHT, SwingConstants.RIGHT} - ); - scrollPane.setViewportView(table); - } + public PanelInbound() { + setLayout(new MigLayout("", "[grow]", "[grow]")); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_PACKETS_INBOUND:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = this.getTable().getModel(); - int row = this.getTable().clearTable(DataPacket.class); + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 0,grow"); - for (Object o : rawdata.array){ - DataPacket packet = (DataPacket)o; - if (packet.type.equals("")) continue; - model.addRow(new Object[] { - packet.type, - packet.id, - packet.amount, - packet.rate, - packet.size - }); - } - - this.getTable().dataUpdated(row); - - break; - } - - default: - return false; - - } - return true; - } + table = new JTableStats( + new String[] {"Type", "ID", "Amount", "Rate", "Total Size"}, + new Class[] {String.class, Integer.class, DataAmountRate.class, DataByteRate.class, DataByteSize.class}, + new int[] { + SwingConstants.LEFT, + SwingConstants.CENTER, + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.RIGHT + }); + scrollPane.setViewportView(table); + } - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.PACKETINBOUND; - } + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_PACKETS_INBOUND: { + this.cacheData(msg, rawdata); - @Override - public boolean refreshOnString(){ - return false; - } + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = this.getTable().getModel(); + int row = this.getTable().clearTable(DataPacket.class); + + for (Object o : rawdata.array) { + DataPacket packet = (DataPacket) o; + if (packet.type.equals("")) continue; + model.addRow(new Object[] {packet.type, packet.id, packet.amount, packet.rate, packet.size}); + } + + this.getTable().dataUpdated(row); + + break; + } + + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.PACKETINBOUND; + } + + @Override + public boolean refreshOnString() { + return false; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound250.java b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound250.java index f52dff4..dfbf197 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound250.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound250.java @@ -2,8 +2,7 @@ package mcp.mobius.opis.swing.panels.network; import javax.swing.JScrollPane; import javax.swing.SwingConstants; - -import net.miginfocom.swing.MigLayout; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataAmountRate; @@ -15,65 +14,57 @@ import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; - -import javax.swing.table.DefaultTableModel; +import net.miginfocom.swing.MigLayout; public class PanelInbound250 extends JPanelMsgHandler implements ITabPanel { - public PanelInbound250() { - setLayout(new MigLayout("", "[grow]", "[grow]")); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 0,grow"); - - table = new JTableStats( - new String[] {"Channel", "Amount", "Rate", "Total Size"}, - new Class[] {CachedString.class, DataAmountRate.class, DataByteRate.class, DataByteSize.class}, - new int[] {SwingConstants.LEFT, SwingConstants.RIGHT, SwingConstants.RIGHT, SwingConstants.RIGHT} - ); - scrollPane.setViewportView(table); - } + public PanelInbound250() { + setLayout(new MigLayout("", "[grow]", "[grow]")); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_PACKETS_INBOUND_250:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = this.getTable().getModel(); - int row = this.getTable().clearTable(DataPacket250.class); + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 0,grow"); - for (Object o : rawdata.array){ - DataPacket250 packet = (DataPacket250)o; - model.addRow(new Object[] { - packet.channel, - packet.amount, - packet.rate, - packet.size - }); - } - - this.getTable().dataUpdated(row); - - break; - } - - default: - return false; - - } - return true; - } + table = new JTableStats( + new String[] {"Channel", "Amount", "Rate", "Total Size"}, + new Class[] {CachedString.class, DataAmountRate.class, DataByteRate.class, DataByteSize.class}, + new int[] {SwingConstants.LEFT, SwingConstants.RIGHT, SwingConstants.RIGHT, SwingConstants.RIGHT}); + scrollPane.setViewportView(table); + } - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.PACKETINBOUND250; - } - - @Override - public boolean refreshOnString(){ - return false; - } + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_PACKETS_INBOUND_250: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = this.getTable().getModel(); + int row = this.getTable().clearTable(DataPacket250.class); + + for (Object o : rawdata.array) { + DataPacket250 packet = (DataPacket250) o; + model.addRow(new Object[] {packet.channel, packet.amount, packet.rate, packet.size}); + } + + this.getTable().dataUpdated(row); + + break; + } + + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.PACKETINBOUND250; + } + + @Override + public boolean refreshOnString() { + return false; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound.java b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound.java index c6bf141..c6a44e0 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound.java @@ -2,8 +2,7 @@ package mcp.mobius.opis.swing.panels.network; import javax.swing.JScrollPane; import javax.swing.SwingConstants; - -import net.miginfocom.swing.MigLayout; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.DataAmountRate; import mcp.mobius.opis.data.holders.newtypes.DataByteRate; @@ -14,67 +13,58 @@ import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; - -import javax.swing.table.DefaultTableModel; +import net.miginfocom.swing.MigLayout; public class PanelOutbound extends JPanelMsgHandler implements ITabPanel { - public PanelOutbound() { - setLayout(new MigLayout("", "[grow]", "[grow]")); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 0,grow"); - - table = new JTableStats( - new String[] {"Type", "Amount", "Rate", "Total Size"}, - new Class[] {String.class, DataAmountRate.class, DataByteRate.class, DataByteSize.class}, - new int[] {SwingConstants.LEFT, SwingConstants.RIGHT, SwingConstants.RIGHT, SwingConstants.RIGHT} - ); - scrollPane.setViewportView(table); - - } + public PanelOutbound() { + setLayout(new MigLayout("", "[grow]", "[grow]")); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_PACKETS_OUTBOUND:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = this.getTable().getModel(); - int row = this.getTable().clearTable(DataPacket.class); + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 0,grow"); - for (Object o : rawdata.array){ - DataPacket packet = (DataPacket)o; - if (packet.type.equals("")) continue; - model.addRow(new Object[] { - packet.type, - packet.amount, - packet.rate, - packet.size - }); - } - - this.getTable().dataUpdated(row); - - break; - } - - default: - return false; - - } - return true; - } + table = new JTableStats( + new String[] {"Type", "Amount", "Rate", "Total Size"}, + new Class[] {String.class, DataAmountRate.class, DataByteRate.class, DataByteSize.class}, + new int[] {SwingConstants.LEFT, SwingConstants.RIGHT, SwingConstants.RIGHT, SwingConstants.RIGHT}); + scrollPane.setViewportView(table); + } - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.PACKETOUTBOUND; - } + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_PACKETS_OUTBOUND: { + this.cacheData(msg, rawdata); - @Override - public boolean refreshOnString(){ - return false; - } -} \ No newline at end of file + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = this.getTable().getModel(); + int row = this.getTable().clearTable(DataPacket.class); + + for (Object o : rawdata.array) { + DataPacket packet = (DataPacket) o; + if (packet.type.equals("")) continue; + model.addRow(new Object[] {packet.type, packet.amount, packet.rate, packet.size}); + } + + this.getTable().dataUpdated(row); + + break; + } + + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.PACKETOUTBOUND; + } + + @Override + public boolean refreshOnString() { + return false; + } +} diff --git a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound250.java b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound250.java index e4a4b8c..4762262 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound250.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound250.java @@ -2,8 +2,7 @@ package mcp.mobius.opis.swing.panels.network; import javax.swing.JScrollPane; import javax.swing.SwingConstants; - -import net.miginfocom.swing.MigLayout; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataAmountRate; @@ -15,66 +14,57 @@ import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; - -import javax.swing.table.DefaultTableModel; +import net.miginfocom.swing.MigLayout; public class PanelOutbound250 extends JPanelMsgHandler implements ITabPanel { - public PanelOutbound250() { - setLayout(new MigLayout("", "[grow]", "[grow]")); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 0,grow"); - - table = new JTableStats( - new String[] {"Channel", "Amount", "Rate", "Total Size"}, - new Class[] {CachedString.class, DataAmountRate.class, DataByteRate.class, DataByteSize.class}, - new int[] {SwingConstants.LEFT, SwingConstants.RIGHT, SwingConstants.RIGHT, SwingConstants.RIGHT} - ); - scrollPane.setViewportView(table); - - } + public PanelOutbound250() { + setLayout(new MigLayout("", "[grow]", "[grow]")); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_PACKETS_OUTBOUND_250:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = this.getTable().getModel(); - int row = this.getTable().clearTable(DataPacket250.class); + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 0,grow"); - for (Object o : rawdata.array){ - DataPacket250 packet = (DataPacket250)o; - model.addRow(new Object[] { - packet.channel, - packet.amount, - packet.rate, - packet.size - }); - } - - this.getTable().dataUpdated(row); - - break; - } - - default: - return false; - - } - return true; - } + table = new JTableStats( + new String[] {"Channel", "Amount", "Rate", "Total Size"}, + new Class[] {CachedString.class, DataAmountRate.class, DataByteRate.class, DataByteSize.class}, + new int[] {SwingConstants.LEFT, SwingConstants.RIGHT, SwingConstants.RIGHT, SwingConstants.RIGHT}); + scrollPane.setViewportView(table); + } - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.PACKETOUTBOUND250; - } + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_PACKETS_OUTBOUND_250: { + this.cacheData(msg, rawdata); - @Override - public boolean refreshOnString(){ - return false; - } -} \ No newline at end of file + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = this.getTable().getModel(); + int row = this.getTable().clearTable(DataPacket250.class); + + for (Object o : rawdata.array) { + DataPacket250 packet = (DataPacket250) o; + model.addRow(new Object[] {packet.channel, packet.amount, packet.rate, packet.size}); + } + + this.getTable().dataUpdated(row); + + break; + } + + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.PACKETOUTBOUND250; + } + + @Override + public boolean refreshOnString() { + return false; + } +} diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelEventClient.java b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelEventClient.java index 996712a..05d206c 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelEventClient.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelEventClient.java @@ -1,6 +1,8 @@ package mcp.mobius.opis.swing.panels.timingclient; - +import java.util.ArrayList; +import javax.swing.*; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.clienttypes.DataRenderEvent; @@ -14,93 +16,101 @@ import mcp.mobius.opis.swing.actions.ActionRunOpisClient; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.*; -import javax.swing.table.DefaultTableModel; -import java.util.ArrayList; +public class PanelEventClient extends JPanel implements ITabPanel, IMessageHandler { + private JTableStats table; + private JButton btnRunRender; -public class PanelEventClient extends JPanel implements ITabPanel, IMessageHandler{ - private JTableStats table; - private JButton btnRunRender; + /** + * Create the panel. + */ + public PanelEventClient() { + setLayout(new MigLayout("", "[grow][grow][]", "[][grow][]")); - /** - * Create the panel. - */ - public PanelEventClient() { - setLayout(new MigLayout("", "[grow][grow][]", "[][grow][]")); - - btnRunRender = new JButton("Run Render"); - add(btnRunRender, "cell 2 0"); - btnRunRender.addActionListener(new ActionRunOpisClient()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 3 1,grow"); - - table = new JTableStats( - new String[] {"Event", "Mod", "Class", "Handler", "Calls", "Timing"}, - new Class[] {CachedString.class, CachedString.class, CachedString.class, CachedString.class, Long.class, DataTiming.class}, - new int[] {SwingConstants.LEFT, SwingConstants.LEFT, SwingConstants.LEFT, SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.CENTER} - ); - - scrollPane.setViewportView(table); - } + btnRunRender = new JButton("Run Render"); + add(btnRunRender, "cell 2 0"); + btnRunRender.addActionListener(new ActionRunOpisClient()); - public void setTable(ArrayList data){ - - DefaultTableModel model = table.getModel(); - int row = this.updateData(table, model, DataEvent.class); - - for (DataRenderEvent o : data){ - model.addRow(new Object[] {o.event, o.mod, o.package_, o.handler, o.nCalls, o.update}); - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 3 1,grow"); - this.dataUpdated(table, model, row); - } - - public JTableStats getTable() { - return table; - } - - public int updateData(JTable table, DefaultTableModel model, Class datatype){ - int row = table.getSelectedRow(); - - if (model.getRowCount() > 0) - for (int i = model.getRowCount() - 1; i >= 0; i--) - model.removeRow(i); - - return row; - } - - public void dataUpdated(JTable table, DefaultTableModel model, int row){ - model.fireTableDataChanged(); - - try{ - table.setRowSelectionInterval(row, row); - } catch (IllegalArgumentException e ){ - - } - } - public JButton getBtnRunRender() { - return btnRunRender; - } + table = new JTableStats( + new String[] {"Event", "Mod", "Class", "Handler", "Calls", "Timing"}, + new Class[] { + CachedString.class, + CachedString.class, + CachedString.class, + CachedString.class, + Long.class, + DataTiming.class + }, + new int[] { + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.CENTER, + SwingConstants.CENTER + }); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - // TODO Auto-generated method stub - return false; - } - - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.CLIENTEVENTS; - } - - @Override - public boolean refreshOnString(){ - return false; - } - - @Override - public boolean refresh(){ - return false; - } -} \ No newline at end of file + scrollPane.setViewportView(table); + } + + public void setTable(ArrayList data) { + + DefaultTableModel model = table.getModel(); + int row = this.updateData(table, model, DataEvent.class); + + for (DataRenderEvent o : data) { + model.addRow(new Object[] {o.event, o.mod, o.package_, o.handler, o.nCalls, o.update}); + } + + this.dataUpdated(table, model, row); + } + + public JTableStats getTable() { + return table; + } + + public int updateData(JTable table, DefaultTableModel model, Class datatype) { + int row = table.getSelectedRow(); + + if (model.getRowCount() > 0) for (int i = model.getRowCount() - 1; i >= 0; i--) model.removeRow(i); + + return row; + } + + public void dataUpdated(JTable table, DefaultTableModel model, int row) { + model.fireTableDataChanged(); + + try { + table.setRowSelectionInterval(row, row); + } catch (IllegalArgumentException e) { + + } + } + + public JButton getBtnRunRender() { + return btnRunRender; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + // TODO Auto-generated method stub + return false; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.CLIENTEVENTS; + } + + @Override + public boolean refreshOnString() { + return false; + } + + @Override + public boolean refresh() { + return false; + } +} diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderEntities.java b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderEntities.java index 6cf5e58..7988dbc 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderEntities.java @@ -1,9 +1,12 @@ package mcp.mobius.opis.swing.panels.timingclient; +import java.util.ArrayList; +import javax.swing.*; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.ITabPanel; -import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.clienttypes.DataEntityRender; +import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataTiming; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; @@ -12,103 +15,94 @@ import mcp.mobius.opis.swing.actions.ActionRunOpisClient; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.*; -import javax.swing.table.DefaultTableModel; -import java.util.ArrayList; +public class PanelRenderEntities extends JPanel implements ITabPanel, IMessageHandler { + private JTableStats table; + private JButton btnRunRender; + private JLabel lblTotal; -public class PanelRenderEntities extends JPanel implements ITabPanel, IMessageHandler{ - private JTableStats table; - private JButton btnRunRender; - private JLabel lblTotal; + /** + * Create the panel. + */ + public PanelRenderEntities() { + setLayout(new MigLayout("", "[grow][grow][]", "[][grow][]")); - /** - * Create the panel. - */ - public PanelRenderEntities() { - setLayout(new MigLayout("", "[grow][grow][]", "[][grow][]")); - - btnRunRender = new JButton("Run Render"); - add(btnRunRender, "cell 2 0"); - btnRunRender.addActionListener(new ActionRunOpisClient()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 3 1,grow"); - - table = new JTableStats( - new String[] {"Name", "Coordinates", "Timing"}, - new Class[] {CachedString.class, Object.class, DataTiming.class} - ); - scrollPane.setViewportView(table); - - lblTotal = new JLabel("Total : 0 µs"); - add(lblTotal, "cell 0 2 3 1,alignx center"); - } + btnRunRender = new JButton("Run Render"); + add(btnRunRender, "cell 2 0"); + btnRunRender.addActionListener(new ActionRunOpisClient()); - public void setTable(ArrayList data){ - - DefaultTableModel model = table.getModel(); - int row = this.updateData(table, model, DataEntityRender.class); - - for (DataEntityRender o : data){ - - model.addRow(new Object[] { - o.name, - String.format("[ %4d %4d %4d ]", o.pos.x, o.pos.y, o.pos.z), - o.update - }); - } - - this.dataUpdated(table, model, row); - } - - public JTableStats getTable() { - return table; - } - - public int updateData(JTable table, DefaultTableModel model, Class datatype){ - int row = table.getSelectedRow(); - - if (model.getRowCount() > 0) - for (int i = model.getRowCount() - 1; i >= 0; i--) - model.removeRow(i); - - return row; - } - - public void dataUpdated(JTable table, DefaultTableModel model, int row){ - model.fireTableDataChanged(); - - try{ - table.setRowSelectionInterval(row, row); - } catch (IllegalArgumentException e ){ - - } - } - public JButton getBtnRunRender() { - return btnRunRender; - } - public JLabel getLblTotal() { - return lblTotal; - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 3 1,grow"); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - // TODO Auto-generated method stub - return false; - } - - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.RENDERENTITIES; - } - - @Override - public boolean refreshOnString(){ - return false; - } - - @Override - public boolean refresh(){ - return false; - } + table = new JTableStats( + new String[] {"Name", "Coordinates", "Timing"}, + new Class[] {CachedString.class, Object.class, DataTiming.class}); + scrollPane.setViewportView(table); + + lblTotal = new JLabel("Total : 0 µs"); + add(lblTotal, "cell 0 2 3 1,alignx center"); + } + + public void setTable(ArrayList data) { + + DefaultTableModel model = table.getModel(); + int row = this.updateData(table, model, DataEntityRender.class); + + for (DataEntityRender o : data) { + + model.addRow(new Object[] {o.name, String.format("[ %4d %4d %4d ]", o.pos.x, o.pos.y, o.pos.z), o.update}); + } + + this.dataUpdated(table, model, row); + } + + public JTableStats getTable() { + return table; + } + + public int updateData(JTable table, DefaultTableModel model, Class datatype) { + int row = table.getSelectedRow(); + + if (model.getRowCount() > 0) for (int i = model.getRowCount() - 1; i >= 0; i--) model.removeRow(i); + + return row; + } + + public void dataUpdated(JTable table, DefaultTableModel model, int row) { + model.fireTableDataChanged(); + + try { + table.setRowSelectionInterval(row, row); + } catch (IllegalArgumentException e) { + + } + } + + public JButton getBtnRunRender() { + return btnRunRender; + } + + public JLabel getLblTotal() { + return lblTotal; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + // TODO Auto-generated method stub + return false; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.RENDERENTITIES; + } + + @Override + public boolean refreshOnString() { + return false; + } + + @Override + public boolean refresh() { + return false; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderHandlers.java b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderHandlers.java index 1004aa0..14a07c2 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderHandlers.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderHandlers.java @@ -1,14 +1,11 @@ package mcp.mobius.opis.swing.panels.timingclient; import java.util.ArrayList; - import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; - -import net.miginfocom.swing.MigLayout; import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; @@ -19,88 +16,87 @@ import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.actions.ActionRunOpisClient; import mcp.mobius.opis.swing.widgets.JTableStats; +import net.miginfocom.swing.MigLayout; -public class PanelRenderHandlers extends JPanel implements ITabPanel, IMessageHandler{ - private JTableStats table; - private JButton btnRunRender; +public class PanelRenderHandlers extends JPanel implements ITabPanel, IMessageHandler { + private JTableStats table; + private JButton btnRunRender; - /** - * Create the panel. - */ - public PanelRenderHandlers() { - setLayout(new MigLayout("", "[grow][grow][]", "[][grow][]")); - - btnRunRender = new JButton("Run Render"); - add(btnRunRender, "cell 2 0"); - btnRunRender.addActionListener(new ActionRunOpisClient()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 3 1,grow"); - - table = new JTableStats( - new String[] {"Mod", "Tick", "Update Time"}, - new Class[] {CachedString.class, String.class, DataTiming.class} - ); - scrollPane.setViewportView(table); - } + /** + * Create the panel. + */ + public PanelRenderHandlers() { + setLayout(new MigLayout("", "[grow][grow][]", "[][grow][]")); - public void setTable(ArrayList data){ - - DefaultTableModel model = table.getModel(); - int row = this.updateData(table, model, DataEvent.class); - - for (DataEvent o : data){ - model.addRow(new Object[] {o.mod, o.event.toString().split("\\$")[1], o.update}); - } + btnRunRender = new JButton("Run Render"); + add(btnRunRender, "cell 2 0"); + btnRunRender.addActionListener(new ActionRunOpisClient()); - this.dataUpdated(table, model, row); - } - - public JTableStats getTable() { - return table; - } - - public int updateData(JTable table, DefaultTableModel model, Class datatype){ - int row = table.getSelectedRow(); - - if (model.getRowCount() > 0) - for (int i = model.getRowCount() - 1; i >= 0; i--) - model.removeRow(i); - - return row; - } - - public void dataUpdated(JTable table, DefaultTableModel model, int row){ - model.fireTableDataChanged(); - - try{ - table.setRowSelectionInterval(row, row); - } catch (IllegalArgumentException e ){ - - } - } - public JButton getBtnRunRender() { - return btnRunRender; - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 3 1,grow"); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - // TODO Auto-generated method stub - return false; - } - - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.RENDERHANDLERS; - } - - @Override - public boolean refreshOnString(){ - return false; - } - - @Override - public boolean refresh(){ - return false; - } -} \ No newline at end of file + table = new JTableStats( + new String[] {"Mod", "Tick", "Update Time"}, + new Class[] {CachedString.class, String.class, DataTiming.class}); + scrollPane.setViewportView(table); + } + + public void setTable(ArrayList data) { + + DefaultTableModel model = table.getModel(); + int row = this.updateData(table, model, DataEvent.class); + + for (DataEvent o : data) { + model.addRow(new Object[] {o.mod, o.event.toString().split("\\$")[1], o.update}); + } + + this.dataUpdated(table, model, row); + } + + public JTableStats getTable() { + return table; + } + + public int updateData(JTable table, DefaultTableModel model, Class datatype) { + int row = table.getSelectedRow(); + + if (model.getRowCount() > 0) for (int i = model.getRowCount() - 1; i >= 0; i--) model.removeRow(i); + + return row; + } + + public void dataUpdated(JTable table, DefaultTableModel model, int row) { + model.fireTableDataChanged(); + + try { + table.setRowSelectionInterval(row, row); + } catch (IllegalArgumentException e) { + + } + } + + public JButton getBtnRunRender() { + return btnRunRender; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + // TODO Auto-generated method stub + return false; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.RENDERHANDLERS; + } + + @Override + public boolean refreshOnString() { + return false; + } + + @Override + public boolean refresh() { + return false; + } +} diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderTileEnts.java b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderTileEnts.java index bddc357..3c75c47 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderTileEnts.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderTileEnts.java @@ -1,9 +1,12 @@ package mcp.mobius.opis.swing.panels.timingclient; import java.util.ArrayList; - +import javax.swing.JButton; +import javax.swing.JLabel; import javax.swing.JPanel; - +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.DataTileEntityRender; @@ -17,113 +20,103 @@ import net.miginfocom.swing.MigLayout; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; -import javax.swing.JButton; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.table.DefaultTableModel; -import javax.swing.JLabel; +public class PanelRenderTileEnts extends JPanel implements ITabPanel, IMessageHandler { + private JTableStats table; + private JButton btnRunRender; + private JLabel lblTotal; -public class PanelRenderTileEnts extends JPanel implements ITabPanel, IMessageHandler{ - private JTableStats table; - private JButton btnRunRender; - private JLabel lblTotal; + /** + * Create the panel. + */ + public PanelRenderTileEnts() { + setLayout(new MigLayout("", "[grow][grow][]", "[][grow][]")); - /** - * Create the panel. - */ - public PanelRenderTileEnts() { - setLayout(new MigLayout("", "[grow][grow][]", "[][grow][]")); - - btnRunRender = new JButton("Run Render"); - add(btnRunRender, "cell 2 0"); - btnRunRender.addActionListener(new ActionRunOpisClient()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 3 1,grow"); - - table = new JTableStats( - new String[] {"Name", "Coordinates", "Timing"}, - new Class[] {String.class, Object.class, DataTiming.class} - ); - scrollPane.setViewportView(table); - - lblTotal = new JLabel("Total : 0 µs"); - add(lblTotal, "cell 0 2 3 1,alignx center"); - } + btnRunRender = new JButton("Run Render"); + add(btnRunRender, "cell 2 0"); + btnRunRender.addActionListener(new ActionRunOpisClient()); - public void setTable(ArrayList data){ - - DefaultTableModel model = table.getModel(); - int row = this.updateData(table, model, DataTileEntityRender.class); - - for (DataTileEntityRender o : data){ - - ItemStack is; - String name = String.format("te.%d.%d", o.id, o.meta); - - try{ - is = new ItemStack(Block.getBlockById(o.id), 1, o.meta); - name = is.getDisplayName(); - } catch (Exception e) { } - - model.addRow(new Object[] { - name, - String.format("[ %4d %4d %4d ]", o.pos.x, o.pos.y, o.pos.z), - o.update - }); - } - - this.dataUpdated(table, model, row); - } - - public JTableStats getTable() { - return table; - } - - public int updateData(JTable table, DefaultTableModel model, Class datatype){ - int row = table.getSelectedRow(); - - if (model.getRowCount() > 0) - for (int i = model.getRowCount() - 1; i >= 0; i--) - model.removeRow(i); - - return row; - } - - public void dataUpdated(JTable table, DefaultTableModel model, int row){ - model.fireTableDataChanged(); - - try{ - table.setRowSelectionInterval(row, row); - } catch (IllegalArgumentException e ){ - - } - } - public JButton getBtnRunRender() { - return btnRunRender; - } - public JLabel getLblTotal() { - return lblTotal; - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 3 1,grow"); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - // TODO Auto-generated method stub - return false; - } - - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.RENDERTILEENTS; - } + table = new JTableStats( + new String[] {"Name", "Coordinates", "Timing"}, + new Class[] {String.class, Object.class, DataTiming.class}); + scrollPane.setViewportView(table); - @Override - public boolean refreshOnString(){ - return false; - } - - @Override - public boolean refresh(){ - return false; - } + lblTotal = new JLabel("Total : 0 µs"); + add(lblTotal, "cell 0 2 3 1,alignx center"); + } + + public void setTable(ArrayList data) { + + DefaultTableModel model = table.getModel(); + int row = this.updateData(table, model, DataTileEntityRender.class); + + for (DataTileEntityRender o : data) { + + ItemStack is; + String name = String.format("te.%d.%d", o.id, o.meta); + + try { + is = new ItemStack(Block.getBlockById(o.id), 1, o.meta); + name = is.getDisplayName(); + } catch (Exception e) { + } + + model.addRow(new Object[] {name, String.format("[ %4d %4d %4d ]", o.pos.x, o.pos.y, o.pos.z), o.update}); + } + + this.dataUpdated(table, model, row); + } + + public JTableStats getTable() { + return table; + } + + public int updateData(JTable table, DefaultTableModel model, Class datatype) { + int row = table.getSelectedRow(); + + if (model.getRowCount() > 0) for (int i = model.getRowCount() - 1; i >= 0; i--) model.removeRow(i); + + return row; + } + + public void dataUpdated(JTable table, DefaultTableModel model, int row) { + model.fireTableDataChanged(); + + try { + table.setRowSelectionInterval(row, row); + } catch (IllegalArgumentException e) { + + } + } + + public JButton getBtnRunRender() { + return btnRunRender; + } + + public JLabel getLblTotal() { + return lblTotal; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + // TODO Auto-generated method stub + return false; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.RENDERTILEENTS; + } + + @Override + public boolean refreshOnString() { + return false; + } + + @Override + public boolean refresh() { + return false; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingChunks.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingChunks.java index 2b4e129..82dc1e6 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingChunks.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingChunks.java @@ -1,5 +1,8 @@ package mcp.mobius.opis.swing.panels.timingserver; +import javax.swing.JButton; +import javax.swing.JScrollPane; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.stats.StatAbstract; import mcp.mobius.opis.data.holders.stats.StatsChunk; @@ -14,92 +17,92 @@ import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JButton; -import javax.swing.JScrollPane; -import javax.swing.table.DefaultTableModel; +public class PanelTimingChunks extends JPanelMsgHandler implements ITabPanel { + private JButtonAccess btnRun; + private JButtonAccess btnTeleport; -public class PanelTimingChunks extends JPanelMsgHandler implements ITabPanel{ - private JButtonAccess btnRun; - private JButtonAccess btnTeleport; + /** + * Create the panel. + */ + public PanelTimingChunks() { + setLayout(new MigLayout("", "[][grow][]", "[][grow]")); - /** - * Create the panel. - */ - public PanelTimingChunks() { - setLayout(new MigLayout("", "[][grow][]", "[][grow]")); - - btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); - add(btnTeleport, "cell 0 0"); - btnTeleport.addActionListener(new ActionTimingChunks()); - - btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); - add(btnRun, "cell 3 0"); - btnRun.addActionListener(new ActionRunOpis()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 4 1,grow"); - - table = new JTableStats( - new String[] {"Dimension", "Position", "TileEntities", "Entities", "Update Time"}, - new Class[] {Integer.class, String.class, Integer.class, Integer.class, StatAbstract.class} - ); - scrollPane.setViewportView(table); - } + btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); + add(btnTeleport, "cell 0 0"); + btnTeleport.addActionListener(new ActionTimingChunks()); - public JButton getBtnRun() {return btnRun;} - public JButton getBtnTeleport() {return btnTeleport;} + btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); + add(btnRun, "cell 3 0"); + btnRun.addActionListener(new ActionRunOpis()); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_TIMING_CHUNK:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = table.getModel(); - int row = this.getTable().clearTable(StatsChunk.class); - - for (Object o : rawdata.array){ - StatsChunk stat = (StatsChunk)o; - model.addRow(new Object[] { - stat.getChunk().dim, - String.format("[ %4d %4d ]", stat.getChunk().chunkX, stat.getChunk().chunkZ), - stat.tileEntities, - stat.entities, - stat}); - } - - this.getTable().dataUpdated(row); - - break; - } - case STATUS_START:{ - this.getBtnRun().setText("Running..."); - break; - } - case STATUS_STOP:{ - this.getBtnRun().setText("Run Opis"); - break; - } - case STATUS_RUNNING:{ - this.getBtnRun().setText("Running..."); - break; - } - default: - return false; - - } - return true; - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 4 1,grow"); - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.TIMINGCHUNKS; - } - - @Override - public boolean refreshOnString(){ - return true; - } + table = new JTableStats( + new String[] {"Dimension", "Position", "TileEntities", "Entities", "Update Time"}, + new Class[] {Integer.class, String.class, Integer.class, Integer.class, StatAbstract.class}); + scrollPane.setViewportView(table); + } + + public JButton getBtnRun() { + return btnRun; + } + + public JButton getBtnTeleport() { + return btnTeleport; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_TIMING_CHUNK: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = table.getModel(); + int row = this.getTable().clearTable(StatsChunk.class); + + for (Object o : rawdata.array) { + StatsChunk stat = (StatsChunk) o; + model.addRow(new Object[] { + stat.getChunk().dim, + String.format("[ %4d %4d ]", stat.getChunk().chunkX, stat.getChunk().chunkZ), + stat.tileEntities, + stat.entities, + stat + }); + } + + this.getTable().dataUpdated(row); + + break; + } + case STATUS_START: { + this.getBtnRun().setText("Running..."); + break; + } + case STATUS_STOP: { + this.getBtnRun().setText("Run Opis"); + break; + } + case STATUS_RUNNING: { + this.getBtnRun().setText("Running..."); + break; + } + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.TIMINGCHUNKS; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntities.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntities.java index 5b5c82c..9033786 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntities.java @@ -1,5 +1,9 @@ package mcp.mobius.opis.swing.panels.timingserver; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.DataEntity; import mcp.mobius.opis.data.holders.newtypes.DataTiming; @@ -14,108 +18,115 @@ import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JButton; -import javax.swing.JScrollPane; -import javax.swing.JLabel; -import javax.swing.table.DefaultTableModel; +public class PanelTimingEntities extends JPanelMsgHandler implements ITabPanel { + private JButtonAccess btnRun; + private JButtonAccess btnPull; + private JButtonAccess btnTeleport; + private JLabel lblSummary; -public class PanelTimingEntities extends JPanelMsgHandler implements ITabPanel{ - private JButtonAccess btnRun; - private JButtonAccess btnPull; - private JButtonAccess btnTeleport; - private JLabel lblSummary; + /** + * Create the panel. + */ + public PanelTimingEntities() { + setLayout(new MigLayout("", "[][][grow][]", "[][grow][]")); - /** - * Create the panel. - */ - public PanelTimingEntities() { - setLayout(new MigLayout("", "[][][grow][]", "[][grow][]")); - - btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); - add(btnTeleport, "cell 0 0"); - btnTeleport.addActionListener(new ActionTimingEntities()); - - btnPull = new JButtonAccess("Pull", AccessLevel.PRIVILEGED); - add(btnPull, "cell 1 0"); - btnPull.addActionListener(new ActionTimingEntities()); - - btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); - add(btnRun, "cell 4 0"); - btnRun.addActionListener(new ActionRunOpis()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 5 1,grow"); - - table = new JTableStats( - new String[] {"Type", "ID", "Dim", "Pos", "Update Time", "Data"}, - new Class[] {String.class, Integer.class, Integer.class, Object.class, DataTiming.class, Integer.class} - ); - scrollPane.setViewportView(table); - - lblSummary = new JLabel("New label"); - add(lblSummary, "cell 0 2 5 1,alignx center"); - } + btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); + add(btnTeleport, "cell 0 0"); + btnTeleport.addActionListener(new ActionTimingEntities()); - public JButton getBtnRun() {return btnRun;} - public JButton getBtnPull() {return btnPull;} - public JButton getBtnTeleport() {return btnTeleport;} - public JLabel getLblSummary() {return lblSummary;} + btnPull = new JButtonAccess("Pull", AccessLevel.PRIVILEGED); + add(btnPull, "cell 1 0"); + btnPull.addActionListener(new ActionTimingEntities()); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_TIMING_ENTITIES:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = table.getModel(); - int row = this.getTable().clearTable(DataEntity.class); - - for (Object o : rawdata.array){ - DataEntity data = (DataEntity)o; - model.addRow(new Object[] {data.name, - data.eid, - data.pos.dim, - String.format("[ %4d %4d %4d ]",data.pos.x,data.pos.y,data.pos.z), - data.update, - data.npoints}); - } - - this.getTable().dataUpdated(row); - - break; - } - case VALUE_TIMING_ENTITIES:{ - this.getLblSummary().setText(String.format("Total update time : %s", ((DataTiming)rawdata.value).toString())); - break; - } - case STATUS_START:{ - this.getBtnRun().setText("Running..."); - break; - } - case STATUS_STOP:{ - this.getBtnRun().setText("Run Opis"); - break; - } - case STATUS_RUNNING:{ - this.getBtnRun().setText("Running..."); - break; - } - default: - return false; - - } - return true; - } + btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); + add(btnRun, "cell 4 0"); + btnRun.addActionListener(new ActionRunOpis()); - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.TIMINGENTITES; - } - - @Override - public boolean refreshOnString(){ - return true; - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 5 1,grow"); + + table = new JTableStats(new String[] {"Type", "ID", "Dim", "Pos", "Update Time", "Data"}, new Class[] { + String.class, Integer.class, Integer.class, Object.class, DataTiming.class, Integer.class + }); + scrollPane.setViewportView(table); + + lblSummary = new JLabel("New label"); + add(lblSummary, "cell 0 2 5 1,alignx center"); + } + + public JButton getBtnRun() { + return btnRun; + } + + public JButton getBtnPull() { + return btnPull; + } + + public JButton getBtnTeleport() { + return btnTeleport; + } + + public JLabel getLblSummary() { + return lblSummary; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_TIMING_ENTITIES: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = table.getModel(); + int row = this.getTable().clearTable(DataEntity.class); + + for (Object o : rawdata.array) { + DataEntity data = (DataEntity) o; + model.addRow(new Object[] { + data.name, + data.eid, + data.pos.dim, + String.format("[ %4d %4d %4d ]", data.pos.x, data.pos.y, data.pos.z), + data.update, + data.npoints + }); + } + + this.getTable().dataUpdated(row); + + break; + } + case VALUE_TIMING_ENTITIES: { + this.getLblSummary() + .setText(String.format("Total update time : %s", ((DataTiming) rawdata.value).toString())); + break; + } + case STATUS_START: { + this.getBtnRun().setText("Running..."); + break; + } + case STATUS_STOP: { + this.getBtnRun().setText("Run Opis"); + break; + } + case STATUS_RUNNING: { + this.getBtnRun().setText("Running..."); + break; + } + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.TIMINGENTITES; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntitiesPerClass.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntitiesPerClass.java index 408c50b..9abbac9 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntitiesPerClass.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntitiesPerClass.java @@ -4,8 +4,6 @@ import javax.swing.JButton; import javax.swing.JScrollPane; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableModel; - -import net.miginfocom.swing.MigLayout; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataEntityPerClass; @@ -18,80 +16,80 @@ import mcp.mobius.opis.swing.actions.ActionRunOpis; import mcp.mobius.opis.swing.widgets.JButtonAccess; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; +import net.miginfocom.swing.MigLayout; public class PanelTimingEntitiesPerClass extends JPanelMsgHandler implements ITabPanel { - private JButtonAccess btnRun; + private JButtonAccess btnRun; - public PanelTimingEntitiesPerClass() { - setLayout(new MigLayout("", "[grow][]", "[][grow]")); - - btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); - add(btnRun, "cell 1 0"); - btnRun.addActionListener(new ActionRunOpis()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 2 1,grow"); - - table = new JTableStats( - new String[] {"Name", "Amount", "Timing", "Mean value"}, - new Class[] {CachedString.class, Integer.class, DataTiming.class, DataTiming.class}, - new int[] {SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER} - ); - scrollPane.setViewportView(table); - } + public PanelTimingEntitiesPerClass() { + setLayout(new MigLayout("", "[grow][]", "[][grow]")); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - - case LIST_TIMING_ENTITIES_PER_CLASS:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = table.getModel(); - int row = this.getTable().clearTable(DataEntityPerClass.class); - - for (Object o : rawdata.array){ - DataEntityPerClass data = (DataEntityPerClass)o; - model.addRow(new Object[] {data.name, data.nents, data.update, new DataTiming(data.update.timing / data.nents)}); - } + btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); + add(btnRun, "cell 1 0"); + btnRun.addActionListener(new ActionRunOpis()); - this.getTable().dataUpdated(row); - - break; - } - - case STATUS_START:{ - this.getBtnRun().setText("Running..."); - break; - } - case STATUS_STOP:{ - this.getBtnRun().setText("Run Opis"); - break; - } - case STATUS_RUNNING:{ - this.getBtnRun().setText("Running..."); - break; - } - default: - return false; - - } - return true; - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 2 1,grow"); - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.TIMINGENTITESPERCLASS; - } + table = new JTableStats( + new String[] {"Name", "Amount", "Timing", "Mean value"}, + new Class[] {CachedString.class, Integer.class, DataTiming.class, DataTiming.class}, + new int[] {SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER}); + scrollPane.setViewportView(table); + } - public JButton getBtnRun() { - return btnRun; - } - - @Override - public boolean refreshOnString(){ - return true; - } + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_TIMING_ENTITIES_PER_CLASS: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = table.getModel(); + int row = this.getTable().clearTable(DataEntityPerClass.class); + + for (Object o : rawdata.array) { + DataEntityPerClass data = (DataEntityPerClass) o; + model.addRow(new Object[] { + data.name, data.nents, data.update, new DataTiming(data.update.timing / data.nents) + }); + } + + this.getTable().dataUpdated(row); + + break; + } + + case STATUS_START: { + this.getBtnRun().setText("Running..."); + break; + } + case STATUS_STOP: { + this.getBtnRun().setText("Run Opis"); + break; + } + case STATUS_RUNNING: { + this.getBtnRun().setText("Running..."); + break; + } + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.TIMINGENTITESPERCLASS; + } + + public JButton getBtnRun() { + return btnRun; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEvents.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEvents.java index bebd500..e20f3ab 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEvents.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEvents.java @@ -1,5 +1,9 @@ package mcp.mobius.opis.swing.panels.timingserver; +import javax.swing.JButton; +import javax.swing.JScrollPane; +import javax.swing.SwingConstants; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataEvent; @@ -14,84 +18,91 @@ import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JButton; -import javax.swing.JScrollPane; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableModel; - public class PanelTimingEvents extends JPanelMsgHandler implements ITabPanel { - private JButtonAccess btnRun; + private JButtonAccess btnRun; - public PanelTimingEvents() { - setLayout(new MigLayout("", "[grow][]", "[][grow]")); - - btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); - add(btnRun, "cell 1 0"); - btnRun.addActionListener(new ActionRunOpis()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 2 1,grow"); - - table = new JTableStats( - new String[] {"Event", "Mod", "Class", "Handler", "Calls", "Timing"}, - new Class[] {CachedString.class, CachedString.class, CachedString.class, CachedString.class, Long.class, DataTiming.class}, - new int[] {SwingConstants.LEFT, SwingConstants.LEFT, SwingConstants.LEFT, SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.CENTER} - ); - scrollPane.setViewportView(table); - } + public PanelTimingEvents() { + setLayout(new MigLayout("", "[grow][]", "[][grow]")); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - - case LIST_TIMING_EVENTS:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = table.getModel(); - int row = this.getTable().clearTable(DataEvent.class); - - for (Object o : rawdata.array){ - DataEvent data = (DataEvent)o; - model.addRow(new Object[] {data.event, data.mod, data.package_, data.handler, data.nCalls, data.update}); - } + btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); + add(btnRun, "cell 1 0"); + btnRun.addActionListener(new ActionRunOpis()); - this.getTable().dataUpdated(row); - - break; - } - - case STATUS_START:{ - this.getBtnRun().setText("Running..."); - break; - } - case STATUS_STOP:{ - this.getBtnRun().setText("Run Opis"); - break; - } - case STATUS_RUNNING:{ - this.getBtnRun().setText("Running..."); - break; - } - default: - return false; - - } - return true; - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 2 1,grow"); - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.TIMINGEVENTS; - } + table = new JTableStats( + new String[] {"Event", "Mod", "Class", "Handler", "Calls", "Timing"}, + new Class[] { + CachedString.class, + CachedString.class, + CachedString.class, + CachedString.class, + Long.class, + DataTiming.class + }, + new int[] { + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.CENTER, + SwingConstants.CENTER + }); + scrollPane.setViewportView(table); + } - public JButton getBtnRun() { - return btnRun; - } - - @Override - public boolean refreshOnString(){ - return true; - } + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_TIMING_EVENTS: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = table.getModel(); + int row = this.getTable().clearTable(DataEvent.class); + + for (Object o : rawdata.array) { + DataEvent data = (DataEvent) o; + model.addRow( + new Object[] {data.event, data.mod, data.package_, data.handler, data.nCalls, data.update}); + } + + this.getTable().dataUpdated(row); + + break; + } + + case STATUS_START: { + this.getBtnRun().setText("Running..."); + break; + } + case STATUS_STOP: { + this.getBtnRun().setText("Run Opis"); + break; + } + case STATUS_RUNNING: { + this.getBtnRun().setText("Running..."); + break; + } + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.TIMINGEVENTS; + } + + public JButton getBtnRun() { + return btnRun; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingHandlers.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingHandlers.java index c8e1878..0a279ee 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingHandlers.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingHandlers.java @@ -1,5 +1,9 @@ package mcp.mobius.opis.swing.panels.timingserver; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataEvent; @@ -14,98 +18,97 @@ import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JButton; -import javax.swing.JScrollPane; -import javax.swing.JLabel; -import javax.swing.table.DefaultTableModel; +public class PanelTimingHandlers extends JPanelMsgHandler implements ITabPanel { + private JButtonAccess btnRun; + private JLabel lblSummary; + /** + * Create the panel. + */ + public PanelTimingHandlers() { + setLayout(new MigLayout("", "[grow][]", "[][grow][]")); -public class PanelTimingHandlers extends JPanelMsgHandler implements ITabPanel{ - private JButtonAccess btnRun; - private JLabel lblSummary; - - /** - * Create the panel. - */ - public PanelTimingHandlers() { - setLayout(new MigLayout("", "[grow][]", "[][grow][]")); - - btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); - add(btnRun, "cell 1 0"); - btnRun.addActionListener(new ActionRunOpis()); - - JScrollPane scrollPane = new JScrollPane(); - - add(scrollPane, "cell 0 1 2 1,grow"); - - table = new JTableStats( - new String[] {"Mod", "Tick", "Update Time"}, - new Class[] {CachedString.class, String.class, DataTiming.class} - ); - scrollPane.setViewportView(table); - - lblSummary = new JLabel("TmpText"); - add(lblSummary, "cell 0 2 2 1,alignx center"); - } + btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); + add(btnRun, "cell 1 0"); + btnRun.addActionListener(new ActionRunOpis()); - public JButton getBtnRun() {return btnRun;} - public JLabel getLblSummary(){return lblSummary;} + JScrollPane scrollPane = new JScrollPane(); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_TIMING_HANDLERS:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = table.getModel(); - int row = this.getTable().clearTable(DataEvent.class); - - for (Object o : rawdata.array){ - DataEvent data = (DataEvent)o; - try{ - model.addRow(new Object[] {data.mod, data.event.toString().split("\\$")[1], data.update}); - } catch (ArrayIndexOutOfBoundsException e){ - //System.out.printf("AIOOB : %s %s\n", data.event.index, data.event.toString()); - model.addRow(new Object[] {data.mod, data.event.toString(), data.update}); - } - } + add(scrollPane, "cell 0 1 2 1,grow"); - this.getTable().dataUpdated(row); - - break; - } - case VALUE_TIMING_HANDLERS:{ - this.getLblSummary().setText(String.format("Total update time : %s", ((DataTiming)rawdata.value).toString())); - break; - } - case STATUS_START:{ - this.getBtnRun().setText("Running..."); - break; - } - case STATUS_STOP:{ - this.getBtnRun().setText("Run Opis"); - break; - } - case STATUS_RUNNING:{ - this.getBtnRun().setText("Running..."); - break; - } - default: - return false; - - } - return true; - } + table = new JTableStats( + new String[] {"Mod", "Tick", "Update Time"}, + new Class[] {CachedString.class, String.class, DataTiming.class}); + scrollPane.setViewportView(table); - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.TIMINGHANDLERS; - } - - @Override - public boolean refreshOnString(){ - return true; - } + lblSummary = new JLabel("TmpText"); + add(lblSummary, "cell 0 2 2 1,alignx center"); + } + + public JButton getBtnRun() { + return btnRun; + } + + public JLabel getLblSummary() { + return lblSummary; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_TIMING_HANDLERS: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = table.getModel(); + int row = this.getTable().clearTable(DataEvent.class); + + for (Object o : rawdata.array) { + DataEvent data = (DataEvent) o; + try { + model.addRow( + new Object[] {data.mod, data.event.toString().split("\\$")[1], data.update}); + } catch (ArrayIndexOutOfBoundsException e) { + // System.out.printf("AIOOB : %s %s\n", data.event.index, data.event.toString()); + model.addRow(new Object[] {data.mod, data.event.toString(), data.update}); + } + } + + this.getTable().dataUpdated(row); + + break; + } + case VALUE_TIMING_HANDLERS: { + this.getLblSummary() + .setText(String.format("Total update time : %s", ((DataTiming) rawdata.value).toString())); + break; + } + case STATUS_START: { + this.getBtnRun().setText("Running..."); + break; + } + case STATUS_STOP: { + this.getBtnRun().setText("Run Opis"); + break; + } + case STATUS_RUNNING: { + this.getBtnRun().setText("Running..."); + break; + } + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.TIMINGHANDLERS; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEnts.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEnts.java index f97a888..271bf9b 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEnts.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEnts.java @@ -1,11 +1,15 @@ package mcp.mobius.opis.swing.panels.timingserver; -import mcp.mobius.opis.modOpis; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; import mcp.mobius.opis.data.holders.newtypes.DataTiming; import mcp.mobius.opis.helpers.ModIdentification; +import mcp.mobius.opis.modOpis; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.AccessLevel; import mcp.mobius.opis.network.enums.Message; @@ -17,116 +21,122 @@ import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JButton; -import javax.swing.JScrollPane; -import javax.swing.JLabel; -import javax.swing.table.DefaultTableModel; +public class PanelTimingTileEnts extends JPanelMsgHandler implements ITabPanel { + private JButtonAccess btnTeleport; + private JButtonAccess btnReset; + private JButtonAccess btnRun; + private JLabel lblSummary; -public class PanelTimingTileEnts extends JPanelMsgHandler implements ITabPanel{ - private JButtonAccess btnTeleport; - private JButtonAccess btnReset; - private JButtonAccess btnRun; - private JLabel lblSummary; + /** + * Create the panel. + */ + public PanelTimingTileEnts() { + setLayout(new MigLayout("", "[][][grow][]", "[][grow][]")); - /** - * Create the panel. - */ - public PanelTimingTileEnts() { - setLayout(new MigLayout("", "[][][grow][]", "[][grow][]")); - - btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); - add(btnTeleport, "cell 0 0"); - btnTeleport.addActionListener(new ActionTimingTileEnts()); - - btnReset = new JButtonAccess("Reset Highlight", AccessLevel.PRIVILEGED); - btnReset.setEnabled(false); - add(btnReset, "cell 1 0"); - btnReset.addActionListener(new ActionTimingTileEnts()); - - btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); - add(btnRun, "cell 4 0"); - btnRun.addActionListener(new ActionRunOpis()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 5 1,grow"); - - table = new JTableStats( - new String[] {"Type", "Mod", "Dim", "Pos", "Update Time"}, - new Class[] {String.class, String.class, Integer.class, Object.class, DataTiming.class} - ); - scrollPane.setViewportView(table); - - lblSummary = new JLabel("New label"); - add(lblSummary, "cell 0 2 5 1,alignx center"); - } + btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); + add(btnTeleport, "cell 0 0"); + btnTeleport.addActionListener(new ActionTimingTileEnts()); - public JButton getBtnTeleport(){return btnTeleport;} - public JButton getBtnReset() {return btnReset;} - public JButton getBtnRun() {return btnRun;} - public JLabel getLblSummary() {return lblSummary;} + btnReset = new JButtonAccess("Reset Highlight", AccessLevel.PRIVILEGED); + btnReset.setEnabled(false); + add(btnReset, "cell 1 0"); + btnReset.addActionListener(new ActionTimingTileEnts()); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_TIMING_TILEENTS:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = table.getModel(); - int row = this.getTable().clearTable(DataBlockTileEntity.class); + btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); + add(btnRun, "cell 4 0"); + btnRun.addActionListener(new ActionRunOpis()); - for (Object o : rawdata.array){ - DataBlockTileEntity data = (DataBlockTileEntity)o; - String name = ModIdentification.getStackName(data.id, data.meta); - String modID = ModIdentification.getModStackName(data.id, data.meta); - model.addRow(new Object[] { - name, - modID, - data.pos.dim, - String.format("[ %4d %4d %4d ]", data.pos.x, data.pos.y, data.pos.z), - data.update}); - } - - this.getTable().dataUpdated(row); - - break; - } - case VALUE_TIMING_TILEENTS:{ - this.getLblSummary().setText(String.format("Total update time : %s", ((DataTiming)rawdata.value).toString())); - break; - } - case STATUS_START:{ - this.getBtnRun().setText("Running..."); - break; - } - case STATUS_STOP:{ - this.getBtnRun().setText("Run Opis"); - break; - } - case STATUS_RUNNING:{ - this.getBtnRun().setText("Running..."); - break; - } - case CLIENT_HIGHLIGHT_BLOCK:{ - modOpis.selectedBlock = (CoordinatesBlock)rawdata.value; - this.getBtnReset().setEnabled(true); - break; - } - default: - return false; - - } - return true; - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 5 1,grow"); - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.TIMINGTILEENTS; - } - - @Override - public boolean refreshOnString(){ - return true; - } + table = new JTableStats( + new String[] {"Type", "Mod", "Dim", "Pos", "Update Time"}, + new Class[] {String.class, String.class, Integer.class, Object.class, DataTiming.class}); + scrollPane.setViewportView(table); + + lblSummary = new JLabel("New label"); + add(lblSummary, "cell 0 2 5 1,alignx center"); + } + + public JButton getBtnTeleport() { + return btnTeleport; + } + + public JButton getBtnReset() { + return btnReset; + } + + public JButton getBtnRun() { + return btnRun; + } + + public JLabel getLblSummary() { + return lblSummary; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_TIMING_TILEENTS: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = table.getModel(); + int row = this.getTable().clearTable(DataBlockTileEntity.class); + + for (Object o : rawdata.array) { + DataBlockTileEntity data = (DataBlockTileEntity) o; + String name = ModIdentification.getStackName(data.id, data.meta); + String modID = ModIdentification.getModStackName(data.id, data.meta); + model.addRow(new Object[] { + name, + modID, + data.pos.dim, + String.format("[ %4d %4d %4d ]", data.pos.x, data.pos.y, data.pos.z), + data.update + }); + } + + this.getTable().dataUpdated(row); + + break; + } + case VALUE_TIMING_TILEENTS: { + this.getLblSummary() + .setText(String.format("Total update time : %s", ((DataTiming) rawdata.value).toString())); + break; + } + case STATUS_START: { + this.getBtnRun().setText("Running..."); + break; + } + case STATUS_STOP: { + this.getBtnRun().setText("Run Opis"); + break; + } + case STATUS_RUNNING: { + this.getBtnRun().setText("Running..."); + break; + } + case CLIENT_HIGHLIGHT_BLOCK: { + modOpis.selectedBlock = (CoordinatesBlock) rawdata.value; + this.getBtnReset().setEnabled(true); + break; + } + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.TIMINGTILEENTS; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEntsPerClass.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEntsPerClass.java index da00d46..70939cb 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEntsPerClass.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEntsPerClass.java @@ -1,13 +1,10 @@ package mcp.mobius.opis.swing.panels.timingserver; import java.util.HashMap; - import javax.swing.JButton; import javax.swing.JScrollPane; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableModel; - -import net.miginfocom.swing.MigLayout; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntityPerClass; import mcp.mobius.opis.data.holders.newtypes.DataTiming; @@ -20,93 +17,104 @@ import mcp.mobius.opis.swing.actions.ActionRunOpis; import mcp.mobius.opis.swing.widgets.JButtonAccess; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; +import net.miginfocom.swing.MigLayout; public class PanelTimingTileEntsPerClass extends JPanelMsgHandler implements ITabPanel { - private JButtonAccess btnRun; + private JButtonAccess btnRun; - public PanelTimingTileEntsPerClass() { - setLayout(new MigLayout("", "[grow][]", "[][grow]")); - - btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); - add(btnRun, "cell 1 0"); - btnRun.addActionListener(new ActionRunOpis()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 2 1,grow"); - - table = new JTableStats( - new String[] {"Name", "Mod", "Amount", "Timing", "Mean value"}, - new Class[] {String.class, String.class, Integer.class, DataTiming.class, DataTiming.class}, - new int[] {SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER} - ); - scrollPane.setViewportView(table); - } + public PanelTimingTileEntsPerClass() { + setLayout(new MigLayout("", "[grow][]", "[][grow]")); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - - case LIST_TIMING_TILEENTS_PER_CLASS:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = table.getModel(); - int row = this.getTable().clearTable(DataBlockTileEntityPerClass.class); - - HashMap cumData = new HashMap(); + btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); + add(btnRun, "cell 1 0"); + btnRun.addActionListener(new ActionRunOpis()); - for (Object o : rawdata.array){ - DataBlockTileEntityPerClass data = (DataBlockTileEntityPerClass)o; - String name = ModIdentification.getStackName(data.id, data.meta); - - if (!cumData.containsKey(name)) - cumData.put(name, new DataBlockTileEntityPerClass(data.id, data.meta)); - - cumData.get(name).add(data.amount, data.update.timing); - } - - for (String s : cumData.keySet()){ - String name = s; - String modID = ModIdentification.getModStackName(cumData.get(s).id, cumData.get(s).meta); - model.addRow(new Object[] {name, modID, cumData.get(s).amount, cumData.get(s).update, new DataTiming(cumData.get(s).update.timing / cumData.get(s).amount)}); - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 2 1,grow"); - this.getTable().dataUpdated(row); - - break; - } - - case STATUS_START:{ - this.getBtnRun().setText("Running..."); - break; - } - case STATUS_STOP:{ - this.getBtnRun().setText("Run Opis"); - break; - } - case STATUS_RUNNING:{ - this.getBtnRun().setText("Running..."); - break; - } - default: - return false; - - } - return true; - } + table = new JTableStats( + new String[] {"Name", "Mod", "Amount", "Timing", "Mean value"}, + new Class[] {String.class, String.class, Integer.class, DataTiming.class, DataTiming.class}, + new int[] { + SwingConstants.LEFT, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER + }); + scrollPane.setViewportView(table); + } - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.TIMINGTILEENTSPERCLASS; - } + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_TIMING_TILEENTS_PER_CLASS: { + this.cacheData(msg, rawdata); - public JButton getBtnRun() { - return btnRun; - } - - @Override - public boolean refreshOnString(){ - return true; - } + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = table.getModel(); + int row = this.getTable().clearTable(DataBlockTileEntityPerClass.class); + + HashMap cumData = + new HashMap(); + + for (Object o : rawdata.array) { + DataBlockTileEntityPerClass data = (DataBlockTileEntityPerClass) o; + String name = ModIdentification.getStackName(data.id, data.meta); + + if (!cumData.containsKey(name)) + cumData.put(name, new DataBlockTileEntityPerClass(data.id, data.meta)); + + cumData.get(name).add(data.amount, data.update.timing); + } + + for (String s : cumData.keySet()) { + String name = s; + String modID = ModIdentification.getModStackName(cumData.get(s).id, cumData.get(s).meta); + model.addRow(new Object[] { + name, + modID, + cumData.get(s).amount, + cumData.get(s).update, + new DataTiming(cumData.get(s).update.timing / cumData.get(s).amount) + }); + } + + this.getTable().dataUpdated(row); + + break; + } + + case STATUS_START: { + this.getBtnRun().setText("Running..."); + break; + } + case STATUS_STOP: { + this.getBtnRun().setText("Run Opis"); + break; + } + case STATUS_RUNNING: { + this.getBtnRun().setText("Running..."); + break; + } + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.TIMINGTILEENTSPERCLASS; + } + + public JButton getBtnRun() { + return btnRun; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountEntities.java b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountEntities.java index b250d06..81922ba 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountEntities.java @@ -1,5 +1,10 @@ package mcp.mobius.opis.swing.panels.tracking; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.basetypes.AmountHolder; import mcp.mobius.opis.network.PacketBase; @@ -12,90 +17,91 @@ import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JCheckBox; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JScrollPane; -import javax.swing.table.DefaultTableModel; +public class PanelAmountEntities extends JPanelMsgHandler implements ITabPanel { + private JCheckBox chckbxFilter; + private JButtonAccess btnKillAll; + private JButtonAccess btnRefresh; + private JLabel lblSummary; -public class PanelAmountEntities extends JPanelMsgHandler implements ITabPanel{ - private JCheckBox chckbxFilter; - private JButtonAccess btnKillAll; - private JButtonAccess btnRefresh; - private JLabel lblSummary; + /** + * Create the panel. + */ + public PanelAmountEntities() { + setLayout(new MigLayout("", "[][][grow][]", "[][grow][]")); - /** - * Create the panel. - */ - public PanelAmountEntities() { - setLayout(new MigLayout("", "[][][grow][]", "[][grow][]")); - - chckbxFilter = new JCheckBox("Filter Entities"); - add(chckbxFilter, "cell 0 0"); - chckbxFilter.addItemListener(new ActionAmountEntities()); - - btnKillAll = new JButtonAccess("Kill All", AccessLevel.PRIVILEGED); - add(btnKillAll, "cell 1 0"); - btnKillAll.addActionListener(new ActionAmountEntities()); - - btnRefresh = new JButtonAccess("Refresh", AccessLevel.NONE); - add(btnRefresh, "cell 3 0"); - btnRefresh.addActionListener(new ActionAmountEntities()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 4 1,grow"); - - table = new JTableStats( - new String[] {"Type", "Amount"}, - new Class[] {String.class, Integer.class} - ); - scrollPane.setViewportView(table); - - lblSummary = new JLabel("New label"); - add(lblSummary, "cell 0 2 4 1,alignx center"); - } + chckbxFilter = new JCheckBox("Filter Entities"); + add(chckbxFilter, "cell 0 0"); + chckbxFilter.addItemListener(new ActionAmountEntities()); - public JCheckBox getChckbxFilter() {return chckbxFilter;} - public JButton getBtnKillAll() {return btnKillAll;} - public JButton getBtnRefresh() {return btnRefresh;} - public JLabel getLblSummary() {return lblSummary;} - - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_AMOUNT_ENTITIES:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = this.getTable().getModel(); - int row = this.getTable().clearTable(AmountHolder.class); - int totalEntities = 0; + btnKillAll = new JButtonAccess("Kill All", AccessLevel.PRIVILEGED); + add(btnKillAll, "cell 1 0"); + btnKillAll.addActionListener(new ActionAmountEntities()); - for (Object o : rawdata.array){ - AmountHolder entity = (AmountHolder)o; - model.addRow(new Object[] {entity.key, entity.value}); - totalEntities += entity.value; - } - - this.getLblSummary().setText("Total : " + String.valueOf(totalEntities)); - this.getTable().dataUpdated(row); - break; - } - default: - return false; - - } - return true; - } + btnRefresh = new JButtonAccess("Refresh", AccessLevel.NONE); + add(btnRefresh, "cell 3 0"); + btnRefresh.addActionListener(new ActionAmountEntities()); - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.AMOUNTENTS; - } - - @Override - public boolean refreshOnString(){ - return true; - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 4 1,grow"); + + table = new JTableStats(new String[] {"Type", "Amount"}, new Class[] {String.class, Integer.class}); + scrollPane.setViewportView(table); + + lblSummary = new JLabel("New label"); + add(lblSummary, "cell 0 2 4 1,alignx center"); + } + + public JCheckBox getChckbxFilter() { + return chckbxFilter; + } + + public JButton getBtnKillAll() { + return btnKillAll; + } + + public JButton getBtnRefresh() { + return btnRefresh; + } + + public JLabel getLblSummary() { + return lblSummary; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_AMOUNT_ENTITIES: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = this.getTable().getModel(); + int row = this.getTable().clearTable(AmountHolder.class); + int totalEntities = 0; + + for (Object o : rawdata.array) { + AmountHolder entity = (AmountHolder) o; + model.addRow(new Object[] {entity.key, entity.value}); + totalEntities += entity.value; + } + + this.getLblSummary().setText("Total : " + String.valueOf(totalEntities)); + this.getTable().dataUpdated(row); + break; + } + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.AMOUNTENTS; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountTileEnts.java b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountTileEnts.java index 0021ae2..e2b751b 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountTileEnts.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountTileEnts.java @@ -1,11 +1,11 @@ package mcp.mobius.opis.swing.panels.tracking; -import java.util.HashMap; - +import javax.swing.JButton; +import javax.swing.JScrollPane; +import javax.swing.SwingConstants; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.basetypes.AmountHolder; -import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntityPerClass; -import mcp.mobius.opis.helpers.ModIdentification; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.AccessLevel; import mcp.mobius.opis.network.enums.Message; @@ -16,71 +16,65 @@ import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JButton; -import javax.swing.JScrollPane; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableModel; +public class PanelAmountTileEnts extends JPanelMsgHandler implements ITabPanel { + private JButtonAccess btnRefresh; -public class PanelAmountTileEnts extends JPanelMsgHandler implements ITabPanel{ - private JButtonAccess btnRefresh; + /** + * Create the panel. + */ + public PanelAmountTileEnts() { + setLayout(new MigLayout("", "[][][grow][]", "[][grow][]")); + btnRefresh = new JButtonAccess("Refresh", AccessLevel.NONE); + add(btnRefresh, "cell 3 0"); + btnRefresh.addActionListener(new ActionAmountTileEnts()); - /** - * Create the panel. - */ - public PanelAmountTileEnts() { - setLayout(new MigLayout("", "[][][grow][]", "[][grow][]")); - - btnRefresh = new JButtonAccess("Refresh", AccessLevel.NONE); - add(btnRefresh, "cell 3 0"); - btnRefresh.addActionListener(new ActionAmountTileEnts()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 4 1,grow"); - - table = new JTableStats( - new String[] {"Name", "Mod", "Amount"}, - new Class[] {String.class, String.class, Integer.class}, - new int[] {SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.CENTER} - ); - scrollPane.setViewportView(table); - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 4 1,grow"); - public JButton getBtnRefresh() {return btnRefresh;} - - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_AMOUNT_TILEENTS:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = this.getTable().getModel(); - int row = this.getTable().clearTable(AmountHolder.class); + table = new JTableStats( + new String[] {"Name", "Mod", "Amount"}, + new Class[] {String.class, String.class, Integer.class}, + new int[] {SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.CENTER}); + scrollPane.setViewportView(table); + } - for (Object o : rawdata.array){ - AmountHolder entity = (AmountHolder)o; - model.addRow(new Object[] {entity.key, entity.data, entity.value}); - } - - this.getTable().dataUpdated(row); - break; - } - default: - return false; - - } - return true; - } + public JButton getBtnRefresh() { + return btnRefresh; + } - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.AMOUNTTES; - } - - @Override - public boolean refreshOnString(){ - return true; - } + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_AMOUNT_TILEENTS: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = this.getTable().getModel(); + int row = this.getTable().clearTable(AmountHolder.class); + + for (Object o : rawdata.array) { + AmountHolder entity = (AmountHolder) o; + model.addRow(new Object[] {entity.key, entity.data, entity.value}); + } + + this.getTable().dataUpdated(row); + break; + } + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.AMOUNTTES; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelDimensions.java b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelDimensions.java index a2502aa..8444cfc 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelDimensions.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelDimensions.java @@ -1,5 +1,8 @@ package mcp.mobius.opis.swing.panels.tracking; +import javax.swing.JButton; +import javax.swing.JScrollPane; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.DataDimension; @@ -15,82 +18,99 @@ import mcp.mobius.opis.swing.widgets.JTableButton; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JScrollPane; -import javax.swing.table.DefaultTableModel; -import javax.swing.JButton; +public class PanelDimensions extends JPanelMsgHandler implements IMessageHandler, ITabPanel { + private JButtonAccess btnPurgeAll; -public class PanelDimensions extends JPanelMsgHandler implements IMessageHandler, ITabPanel { - private JButtonAccess btnPurgeAll; - - public PanelDimensions() { - setLayout(new MigLayout("", "[grow]", "[][grow]")); - - btnPurgeAll = new JButtonAccess("Purge All", AccessLevel.PRIVILEGED); - add(btnPurgeAll, "cell 0 0"); - btnPurgeAll.addActionListener(new ActionDimensions()); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1,grow"); - - table = new JTableStats( - new String[] {"Dim", "Name", "Players", "Forced chunks", "Loaded chunks", "Monsters", "Animals", "Stacks", "Update time", "Purge"}, - new Class[] {Integer.class, String.class, Integer.class, Integer.class, Integer.class, Integer.class, Integer.class, Integer.class, DataTimingMillisecond.class, JTableButton.class}, - new boolean[]{false, false, false, false, false,false,false,false, false, true} - ); - table.setBackground(this.getBackground()); - table.setAutoCreateRowSorter(true); - table.setShowGrid(false); - scrollPane.setViewportView(table); - - JTableButton buttonColumn = new JTableButton(table, new ActionDimensions(), 9, AccessLevel.PRIVILEGED); - } + public PanelDimensions() { + setLayout(new MigLayout("", "[grow]", "[][grow]")); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_DIMENSION_DATA:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = this.getTable().getModel(); - int row = this.getTable().clearTable(DataDimension.class); + btnPurgeAll = new JButtonAccess("Purge All", AccessLevel.PRIVILEGED); + add(btnPurgeAll, "cell 0 0"); + btnPurgeAll.addActionListener(new ActionDimensions()); - for (Object o : rawdata.array){ - DataDimension data = (DataDimension)o; - model.addRow(new Object[] { - data.dim, - data.name, - data.players, - data.forced, - data.loaded, - data.mobs, - data.neutral, - data.itemstacks, - data.update.asMillisecond(), - "Purge" - }); - } - this.getTable().dataUpdated(row); - break; - } - default: - return false; - - } - return true; - } - public JButton getBtnPurgeAll() { - return btnPurgeAll; - } - - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.DIMENSIONS; - } - - @Override - public boolean refreshOnString(){ - return true; - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1,grow"); + + table = new JTableStats( + new String[] { + "Dim", + "Name", + "Players", + "Forced chunks", + "Loaded chunks", + "Monsters", + "Animals", + "Stacks", + "Update time", + "Purge" + }, + new Class[] { + Integer.class, + String.class, + Integer.class, + Integer.class, + Integer.class, + Integer.class, + Integer.class, + Integer.class, + DataTimingMillisecond.class, + JTableButton.class + }, + new boolean[] {false, false, false, false, false, false, false, false, false, true}); + table.setBackground(this.getBackground()); + table.setAutoCreateRowSorter(true); + table.setShowGrid(false); + scrollPane.setViewportView(table); + + JTableButton buttonColumn = new JTableButton(table, new ActionDimensions(), 9, AccessLevel.PRIVILEGED); + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_DIMENSION_DATA: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = this.getTable().getModel(); + int row = this.getTable().clearTable(DataDimension.class); + + for (Object o : rawdata.array) { + DataDimension data = (DataDimension) o; + model.addRow(new Object[] { + data.dim, + data.name, + data.players, + data.forced, + data.loaded, + data.mobs, + data.neutral, + data.itemstacks, + data.update.asMillisecond(), + "Purge" + }); + } + this.getTable().dataUpdated(row); + break; + } + default: + return false; + } + return true; + } + + public JButton getBtnPurgeAll() { + return btnPurgeAll; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.DIMENSIONS; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelPlayers.java b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelPlayers.java index 952d686..5056b85 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelPlayers.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelPlayers.java @@ -1,5 +1,8 @@ package mcp.mobius.opis.swing.panels.tracking; +import javax.swing.JButton; +import javax.swing.JScrollPane; +import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.DataEntity; import mcp.mobius.opis.data.holders.newtypes.PlayerStatus; @@ -13,89 +16,85 @@ import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JButton; -import javax.swing.JScrollPane; -import javax.swing.table.DefaultTableModel; +public class PanelPlayers extends JPanelMsgHandler implements ITabPanel { + private JButtonAccess btnTeleport; + private JButtonAccess btnPull; -public class PanelPlayers extends JPanelMsgHandler implements ITabPanel{ - private JButtonAccess btnTeleport; - private JButtonAccess btnPull; + /** + * Create the panel. + */ + public PanelPlayers() { + setLayout(new MigLayout("", "[][][][][grow]", "[][grow]")); - /** - * Create the panel. - */ - public PanelPlayers() { - setLayout(new MigLayout("", "[][][][][grow]", "[][grow]")); - - btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); - add(btnTeleport, "cell 0 0"); - btnTeleport.addActionListener(new ActionPlayers()); - - btnPull = new JButtonAccess("Pull", AccessLevel.PRIVILEGED); - add(btnPull, "cell 1 0"); - btnPull.addActionListener(new ActionPlayers()); - - JButton btnKill = new JButton("Kill"); - btnKill.setEnabled(false); - add(btnKill, "cell 2 0"); - - JButton btnMorph = new JButton("Morph"); - btnMorph.setEnabled(false); - add(btnMorph, "cell 3 0"); - - JScrollPane scrollPane = new JScrollPane(); - add(scrollPane, "cell 0 1 6 1,grow"); - - table = new JTableStats( - new String[] {"Name", "Dimension", "Coordinates"}, - new Class[] {String.class, Integer.class, Object.class} - ); - scrollPane.setViewportView(table); - } + btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); + add(btnTeleport, "cell 0 0"); + btnTeleport.addActionListener(new ActionPlayers()); - public JButton getBtnTeleport() {return btnTeleport;} - public JButton getBtnPull() {return btnPull;} + btnPull = new JButtonAccess("Pull", AccessLevel.PRIVILEGED); + add(btnPull, "cell 1 0"); + btnPull.addActionListener(new ActionPlayers()); - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_PLAYERS:{ - this.cacheData(msg, rawdata); - - this.getTable().setTableData(rawdata.array); - - DefaultTableModel model = this.getTable().getModel(); - int row = this.getTable().clearTable(DataEntity.class); + JButton btnKill = new JButton("Kill"); + btnKill.setEnabled(false); + add(btnKill, "cell 2 0"); - for (Object o : rawdata.array){ - PlayerStatus player = (PlayerStatus)o; - model.addRow(new Object[] { - player.name, - player.dim, - String.format("[ %4d %4d %4d ]", player.x, player.y, player.z), - }); - } - - this.getTable().dataUpdated(row); - - break; - } - - default: - return false; - - } - return true; + JButton btnMorph = new JButton("Morph"); + btnMorph.setEnabled(false); + add(btnMorph, "cell 3 0"); - } + JScrollPane scrollPane = new JScrollPane(); + add(scrollPane, "cell 0 1 6 1,grow"); - @Override - public SelectedTab getSelectedTab() { - return SelectedTab.PLAYERS; - } - - @Override - public boolean refreshOnString(){ - return true; - } + table = new JTableStats( + new String[] {"Name", "Dimension", "Coordinates"}, + new Class[] {String.class, Integer.class, Object.class}); + scrollPane.setViewportView(table); + } + + public JButton getBtnTeleport() { + return btnTeleport; + } + + public JButton getBtnPull() { + return btnPull; + } + + @Override + public boolean handleMessage(Message msg, PacketBase rawdata) { + switch (msg) { + case LIST_PLAYERS: { + this.cacheData(msg, rawdata); + + this.getTable().setTableData(rawdata.array); + + DefaultTableModel model = this.getTable().getModel(); + int row = this.getTable().clearTable(DataEntity.class); + + for (Object o : rawdata.array) { + PlayerStatus player = (PlayerStatus) o; + model.addRow(new Object[] { + player.name, player.dim, String.format("[ %4d %4d %4d ]", player.x, player.y, player.z), + }); + } + + this.getTable().dataUpdated(row); + + break; + } + + default: + return false; + } + return true; + } + + @Override + public SelectedTab getSelectedTab() { + return SelectedTab.PLAYERS; + } + + @Override + public boolean refreshOnString() { + return true; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/widgets/JButtonAccess.java b/src/main/java/mcp/mobius/opis/swing/widgets/JButtonAccess.java index 4e0501f..e5269f6 100644 --- a/src/main/java/mcp/mobius/opis/swing/widgets/JButtonAccess.java +++ b/src/main/java/mcp/mobius/opis/swing/widgets/JButtonAccess.java @@ -1,35 +1,34 @@ package mcp.mobius.opis.swing.widgets; import javax.swing.JButton; - import mcp.mobius.opis.network.enums.AccessLevel; import mcp.mobius.opis.swing.SwingUI; public class JButtonAccess extends JButton { - private AccessLevel al = AccessLevel.NONE; + private AccessLevel al = AccessLevel.NONE; - public JButtonAccess(AccessLevel level){ - super(); - this.al = level; - SwingUI.registeredButtons.add(this); - } - - public JButtonAccess(String label){ - super(label); - SwingUI.registeredButtons.add(this); - } - - public JButtonAccess(String label, AccessLevel level){ - super(label); - this.al = level; - SwingUI.registeredButtons.add(this); - } - - public void setAccessLevel(AccessLevel level){ - this.al = level; - } - - public AccessLevel getAccessLevel(){ - return this.al; - } + public JButtonAccess(AccessLevel level) { + super(); + this.al = level; + SwingUI.registeredButtons.add(this); + } + + public JButtonAccess(String label) { + super(label); + SwingUI.registeredButtons.add(this); + } + + public JButtonAccess(String label, AccessLevel level) { + super(label); + this.al = level; + SwingUI.registeredButtons.add(this); + } + + public void setAccessLevel(AccessLevel level) { + this.al = level; + } + + public AccessLevel getAccessLevel() { + return this.al; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/widgets/JPanelMsgHandler.java b/src/main/java/mcp/mobius/opis/swing/widgets/JPanelMsgHandler.java index 612a899..f960ea7 100644 --- a/src/main/java/mcp/mobius/opis/swing/widgets/JPanelMsgHandler.java +++ b/src/main/java/mcp/mobius/opis/swing/widgets/JPanelMsgHandler.java @@ -1,33 +1,29 @@ package mcp.mobius.opis.swing.widgets; import javax.swing.JPanel; - import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; public abstract class JPanelMsgHandler extends JPanel implements IMessageHandler { - - public JTableStats table; - public Message cachedmsg; - public PacketBase cachedrawdata; - - - public JTableStats getTable(){ - return this.table; - } - - public boolean cacheData(Message msg, PacketBase rawdata) { - this.cachedmsg = msg; - this.cachedrawdata = rawdata; - return true; - } - - public boolean refresh(){ - if (this.cachedmsg != null && this.cachedrawdata != null) - return this.handleMessage(this.cachedmsg, this.cachedrawdata); - else - return false; - } - + + public JTableStats table; + public Message cachedmsg; + public PacketBase cachedrawdata; + + public JTableStats getTable() { + return this.table; + } + + public boolean cacheData(Message msg, PacketBase rawdata) { + this.cachedmsg = msg; + this.cachedrawdata = rawdata; + return true; + } + + public boolean refresh() { + if (this.cachedmsg != null && this.cachedrawdata != null) + return this.handleMessage(this.cachedmsg, this.cachedrawdata); + else return false; + } } diff --git a/src/main/java/mcp/mobius/opis/swing/widgets/JTableButton.java b/src/main/java/mcp/mobius/opis/swing/widgets/JTableButton.java index ba5ce5d..45ecce9 100644 --- a/src/main/java/mcp/mobius/opis/swing/widgets/JTableButton.java +++ b/src/main/java/mcp/mobius/opis/swing/widgets/JTableButton.java @@ -2,15 +2,11 @@ package mcp.mobius.opis.swing.widgets; import java.awt.*; import java.awt.event.*; - import javax.swing.*; import javax.swing.border.*; import javax.swing.table.*; - import mcp.mobius.opis.network.enums.AccessLevel; - - /** * The ButtonColumn class provides a renderer and an editor that looks like a * JButton. The renderer and editor will then be used for a specified column @@ -25,210 +21,178 @@ import mcp.mobius.opis.network.enums.AccessLevel; * */ public class JTableButton extends AbstractCellEditor - implements TableCellRenderer, TableCellEditor, ActionListener, MouseListener -{ - private JTable table; - private ActionListener action; - private int mnemonic; - private Border originalBorder; - private Border focusBorder; + implements TableCellRenderer, TableCellEditor, ActionListener, MouseListener { + private JTable table; + private ActionListener action; + private int mnemonic; + private Border originalBorder; + private Border focusBorder; - private JButtonAccess renderButton; - private JButtonAccess editButton; - private Object editorValue; - private boolean isButtonColumnEditor; + private JButtonAccess renderButton; + private JButtonAccess editButton; + private Object editorValue; + private boolean isButtonColumnEditor; - private AccessLevel level; - - /** - * Create the ButtonColumn to be used as a renderer and editor. The - * renderer and editor will automatically be installed on the TableColumn - * of the specified column. - * - * @param table the table containing the button renderer/editor - * @param action the Action to be invoked when the button is invoked - * @param column the column to which the button renderer/editor is added - */ - public JTableButton(JTable table, ActionListener action, int column, AccessLevel level) - { - this.table = table; - this.action = action; - this.level = level; - - renderButton = new JButtonAccess(level); - editButton = new JButtonAccess(level); - editButton.setFocusPainted( false ); - editButton.addActionListener( this ); - originalBorder = editButton.getBorder(); - setFocusBorder( new LineBorder(Color.BLUE) ); + private AccessLevel level; - TableColumnModel columnModel = table.getColumnModel(); - columnModel.getColumn(column).setCellRenderer( this ); - columnModel.getColumn(column).setCellEditor( this ); - table.addMouseListener( this ); - } + /** + * Create the ButtonColumn to be used as a renderer and editor. The + * renderer and editor will automatically be installed on the TableColumn + * of the specified column. + * + * @param table the table containing the button renderer/editor + * @param action the Action to be invoked when the button is invoked + * @param column the column to which the button renderer/editor is added + */ + public JTableButton(JTable table, ActionListener action, int column, AccessLevel level) { + this.table = table; + this.action = action; + this.level = level; + renderButton = new JButtonAccess(level); + editButton = new JButtonAccess(level); + editButton.setFocusPainted(false); + editButton.addActionListener(this); + originalBorder = editButton.getBorder(); + setFocusBorder(new LineBorder(Color.BLUE)); - /** - * Get foreground color of the button when the cell has focus - * - * @return the foreground color - */ - public Border getFocusBorder() - { - return focusBorder; - } + TableColumnModel columnModel = table.getColumnModel(); + columnModel.getColumn(column).setCellRenderer(this); + columnModel.getColumn(column).setCellEditor(this); + table.addMouseListener(this); + } - /** - * The foreground color of the button when the cell has focus - * - * @param focusBorder the foreground color - */ - public void setFocusBorder(Border focusBorder) - { - this.focusBorder = focusBorder; - editButton.setBorder( focusBorder ); - } + /** + * Get foreground color of the button when the cell has focus + * + * @return the foreground color + */ + public Border getFocusBorder() { + return focusBorder; + } - public int getMnemonic() - { - return mnemonic; - } + /** + * The foreground color of the button when the cell has focus + * + * @param focusBorder the foreground color + */ + public void setFocusBorder(Border focusBorder) { + this.focusBorder = focusBorder; + editButton.setBorder(focusBorder); + } - /** - * The mnemonic to activate the button when the cell has focus - * - * @param mnemonic the mnemonic - */ - public void setMnemonic(int mnemonic) - { - this.mnemonic = mnemonic; - renderButton.setMnemonic(mnemonic); - editButton.setMnemonic(mnemonic); - } + public int getMnemonic() { + return mnemonic; + } - @Override - public Component getTableCellEditorComponent( - JTable table, Object value, boolean isSelected, int row, int column) - { - if (value == null) - { - editButton.setText( "" ); - editButton.setIcon( null ); - } - else if (value instanceof Icon) - { - editButton.setText( "" ); - editButton.setIcon( (Icon)value ); - } - else - { - editButton.setText( value.toString() ); - editButton.setIcon( null ); - } - - this.editorValue = value; - return editButton; - } - - @Override - public Object getCellEditorValue() - { - return editorValue; - } - -// -// Implement TableCellRenderer interface -// - @Override - public Component getTableCellRendererComponent( - JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) - { - if (isSelected) - { - renderButton.setForeground(table.getSelectionForeground()); - renderButton.setBackground(table.getSelectionBackground()); - } - else - { - renderButton.setForeground(table.getForeground()); - renderButton.setBackground(UIManager.getColor("Button.background")); - } - - if (hasFocus) - { - renderButton.setBorder( focusBorder ); - } - else - { - renderButton.setBorder( originalBorder ); - } - -// renderButton.setText( (value == null) ? "" : value.toString() ); - if (value == null) - { - renderButton.setText( "" ); - renderButton.setIcon( null ); - } - else if (value instanceof Icon) - { - renderButton.setText( "" ); - renderButton.setIcon( (Icon)value ); - } - else - { - renderButton.setText( value.toString() ); - renderButton.setIcon( null ); - } - - return renderButton; - } - -// -// Implement ActionListener interface -// - /* - * The button has been pressed. Stop editing and invoke the custom Action - */ - @Override - public void actionPerformed(ActionEvent e) - { - int row = table.convertRowIndexToModel( table.getEditingRow() ); - fireEditingStopped(); - - action.actionPerformed(e); - } - -// -// Implement MouseListener interface -// - /* - * When the mouse is pressed the editor is invoked. If you then then drag - * the mouse to another cell before releasing it, the editor is still - * active. Make sure editing is stopped when the mouse is released. - */ - @Override - public void mousePressed(MouseEvent e) - { - if (table.isEditing() - && table.getCellEditor() == this) - isButtonColumnEditor = true; + /** + * The mnemonic to activate the button when the cell has focus + * + * @param mnemonic the mnemonic + */ + public void setMnemonic(int mnemonic) { + this.mnemonic = mnemonic; + renderButton.setMnemonic(mnemonic); + editButton.setMnemonic(mnemonic); } @Override - public void mouseReleased(MouseEvent e) - { - if (isButtonColumnEditor - && table.isEditing()) - table.getCellEditor().stopCellEditing(); + public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { + if (value == null) { + editButton.setText(""); + editButton.setIcon(null); + } else if (value instanceof Icon) { + editButton.setText(""); + editButton.setIcon((Icon) value); + } else { + editButton.setText(value.toString()); + editButton.setIcon(null); + } - isButtonColumnEditor = false; + this.editorValue = value; + return editButton; } @Override - public void mouseClicked(MouseEvent e) {} - @Override - public void mouseEntered(MouseEvent e) {} + public Object getCellEditorValue() { + return editorValue; + } + + // + // Implement TableCellRenderer interface + // @Override - public void mouseExited(MouseEvent e) {} -} \ No newline at end of file + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + if (isSelected) { + renderButton.setForeground(table.getSelectionForeground()); + renderButton.setBackground(table.getSelectionBackground()); + } else { + renderButton.setForeground(table.getForeground()); + renderButton.setBackground(UIManager.getColor("Button.background")); + } + + if (hasFocus) { + renderButton.setBorder(focusBorder); + } else { + renderButton.setBorder(originalBorder); + } + + // renderButton.setText( (value == null) ? "" : value.toString() ); + if (value == null) { + renderButton.setText(""); + renderButton.setIcon(null); + } else if (value instanceof Icon) { + renderButton.setText(""); + renderButton.setIcon((Icon) value); + } else { + renderButton.setText(value.toString()); + renderButton.setIcon(null); + } + + return renderButton; + } + + // + // Implement ActionListener interface + // + /* + * The button has been pressed. Stop editing and invoke the custom Action + */ + @Override + public void actionPerformed(ActionEvent e) { + int row = table.convertRowIndexToModel(table.getEditingRow()); + fireEditingStopped(); + + action.actionPerformed(e); + } + + // + // Implement MouseListener interface + // + /* + * When the mouse is pressed the editor is invoked. If you then then drag + * the mouse to another cell before releasing it, the editor is still + * active. Make sure editing is stopped when the mouse is released. + */ + @Override + public void mousePressed(MouseEvent e) { + if (table.isEditing() && table.getCellEditor() == this) isButtonColumnEditor = true; + } + + @Override + public void mouseReleased(MouseEvent e) { + if (isButtonColumnEditor && table.isEditing()) table.getCellEditor().stopCellEditing(); + + isButtonColumnEditor = false; + } + + @Override + public void mouseClicked(MouseEvent e) {} + + @Override + public void mouseEntered(MouseEvent e) {} + + @Override + public void mouseExited(MouseEvent e) {} +} diff --git a/src/main/java/mcp/mobius/opis/swing/widgets/JTableStats.java b/src/main/java/mcp/mobius/opis/swing/widgets/JTableStats.java index f74bb90..fa55802 100644 --- a/src/main/java/mcp/mobius/opis/swing/widgets/JTableStats.java +++ b/src/main/java/mcp/mobius/opis/swing/widgets/JTableStats.java @@ -2,135 +2,158 @@ package mcp.mobius.opis.swing.widgets; import java.util.ArrayList; import java.util.HashMap; - import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; - import mcp.mobius.opis.data.holders.ISerializable; public class JTableStats extends JTable { - public class OpisTableModel extends DefaultTableModel{ - String[] headers; - Class[] columnTypes; - boolean[] columnEditables; - - public OpisTableModel(String[] headers, Class[] columnTypes, boolean[] columnEditables){ - super(new Object[][]{}, headers); - this.headers = headers; - this.columnTypes = columnTypes; - this.columnEditables = columnEditables; - } - - @Override - public Class getColumnClass(int columnIndex) { - return columnTypes[columnIndex]; - } - - @Override - public boolean isCellEditable(int row, int column) { - return columnEditables[column]; - } - } - - protected ArrayList statistics; - protected int[] alignList; - - public JTableStats(String[] headers, Class[] columnTypes){ - this(headers, columnTypes, - new int[] {SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER}, - new boolean[] {false, false, false, false, false, false, false, false, false, false} - ); - } + public class OpisTableModel extends DefaultTableModel { + String[] headers; + Class[] columnTypes; + boolean[] columnEditables; - public JTableStats(String[] headers, Class[] columnTypes, boolean[] editable){ - this(headers, columnTypes, - new int[] {SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER}, - editable - ); - } - - public JTableStats(String[] headers, Class[] columnTypes, int[] align){ - this(headers, columnTypes, align, - new boolean[] {false, false, false, false, false, false, false, false, false, false} - ); - } - - public JTableStats(String[] headers, Class[] columnTypes, int[] align, boolean[] editable){ - - super(); - this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - this.setAutoCreateRowSorter(true); - this.alignList = align; - this.setModel(new OpisTableModel(headers, columnTypes, editable)); - - HashMap hashAlign = new HashMap(); - - DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(); - centerRenderer.setHorizontalAlignment( SwingConstants.CENTER ); - hashAlign.put(SwingConstants.CENTER, centerRenderer); - - DefaultTableCellRenderer leftRenderer = new DefaultTableCellRenderer(); - leftRenderer.setHorizontalAlignment( SwingConstants.LEFT ); - hashAlign.put(SwingConstants.LEFT, leftRenderer); - - DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer(); - rightRenderer.setHorizontalAlignment( SwingConstants.RIGHT ); - hashAlign.put(SwingConstants.RIGHT, rightRenderer); - - for (int i = 0; i < this.getColumnCount(); i++) - this.getColumnModel().getColumn(i).setCellRenderer(hashAlign.get(align[i])); - } - - public ArrayList getTableData(){ - return this.statistics; - } - - public void setTableData(ArrayList statistics){ - this.statistics = statistics; - } - - public void clearTableData(){ - this.statistics = new ArrayList(); - } + public OpisTableModel(String[] headers, Class[] columnTypes, boolean[] columnEditables) { + super(new Object[][] {}, headers); + this.headers = headers; + this.columnTypes = columnTypes; + this.columnEditables = columnEditables; + } + + @Override + public Class getColumnClass(int columnIndex) { + return columnTypes[columnIndex]; + } + + @Override + public boolean isCellEditable(int row, int column) { + return columnEditables[column]; + } + } + + protected ArrayList statistics; + protected int[] alignList; + + public JTableStats(String[] headers, Class[] columnTypes) { + this( + headers, + columnTypes, + new int[] { + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER + }, + new boolean[] {false, false, false, false, false, false, false, false, false, false}); + } + + public JTableStats(String[] headers, Class[] columnTypes, boolean[] editable) { + this( + headers, + columnTypes, + new int[] { + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER, + SwingConstants.CENTER + }, + editable); + } + + public JTableStats(String[] headers, Class[] columnTypes, int[] align) { + this(headers, columnTypes, align, new boolean[] { + false, false, false, false, false, false, false, false, false, false + }); + } + + public JTableStats(String[] headers, Class[] columnTypes, int[] align, boolean[] editable) { + + super(); + this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + this.setAutoCreateRowSorter(true); + this.alignList = align; + this.setModel(new OpisTableModel(headers, columnTypes, editable)); + + HashMap hashAlign = new HashMap(); + + DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(); + centerRenderer.setHorizontalAlignment(SwingConstants.CENTER); + hashAlign.put(SwingConstants.CENTER, centerRenderer); + + DefaultTableCellRenderer leftRenderer = new DefaultTableCellRenderer(); + leftRenderer.setHorizontalAlignment(SwingConstants.LEFT); + hashAlign.put(SwingConstants.LEFT, leftRenderer); + + DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer(); + rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT); + hashAlign.put(SwingConstants.RIGHT, rightRenderer); + + for (int i = 0; i < this.getColumnCount(); i++) + this.getColumnModel().getColumn(i).setCellRenderer(hashAlign.get(align[i])); + } + + public ArrayList getTableData() { + return this.statistics; + } + + public void setTableData(ArrayList statistics) { + this.statistics = statistics; + } + + public void clearTableData() { + this.statistics = new ArrayList(); + } + + public void addTableData(ArrayList statistics) { + this.statistics.addAll(statistics); + } + + @Override + public DefaultTableModel getModel() { + return (DefaultTableModel) super.getModel(); + } + + public int clearTable(Class datatype) { + int row = this.getSelectedRow(); + try { + this.getModel().setRowCount(0); + } catch (NullPointerException e) { + } + return row; + } + + public void dataUpdated(int row) { + this.getModel().fireTableDataChanged(); + + try { + this.setRowSelectionInterval(row, row); + } catch (IllegalArgumentException e) { + + } + } + + /* + public void setStatistics(ArrayList statistics){ + this.statistics = new ArrayList(); + for (Object o : statistics){ + this.statistics.add((StatAbstract)o); + } + } + */ - public void addTableData(ArrayList statistics){ - this.statistics.addAll(statistics); - } - - @Override - public DefaultTableModel getModel(){ - return (DefaultTableModel)super.getModel(); - } - - public int clearTable(Class datatype){ - int row = this.getSelectedRow(); - try{ - this.getModel().setRowCount(0); - } catch (NullPointerException e){} - return row; - } - - public void dataUpdated(int row){ - this.getModel().fireTableDataChanged(); - - try{ - this.setRowSelectionInterval(row, row); - } catch (IllegalArgumentException e ){ - - } - } - - /* - public void setStatistics(ArrayList statistics){ - this.statistics = new ArrayList(); - for (Object o : statistics){ - this.statistics.add((StatAbstract)o); - } - } - */ - } diff --git a/src/main/java/mcp/mobius/opis/tools/BlockDebug.java b/src/main/java/mcp/mobius/opis/tools/BlockDebug.java index bc13c28..00b98a6 100644 --- a/src/main/java/mcp/mobius/opis/tools/BlockDebug.java +++ b/src/main/java/mcp/mobius/opis/tools/BlockDebug.java @@ -9,12 +9,11 @@ public class BlockDebug extends BlockContainer { public BlockDebug(Material par2Material) { super(par2Material); - //this.setUnlocalizedName("Debug Companion Cube"); - } - - @Override - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileDebug(); - } + // this.setUnlocalizedName("Debug Companion Cube"); + } + @Override + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileDebug(); + } } diff --git a/src/main/java/mcp/mobius/opis/tools/BlockLag.java b/src/main/java/mcp/mobius/opis/tools/BlockLag.java index f836329..ed5407d 100644 --- a/src/main/java/mcp/mobius/opis/tools/BlockLag.java +++ b/src/main/java/mcp/mobius/opis/tools/BlockLag.java @@ -9,12 +9,11 @@ public class BlockLag extends BlockContainer { public BlockLag(Material par2Material) { super(par2Material); - //this.setUnlocalizedName("Lag Generator"); - } - - @Override - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileLag(); - } + // this.setUnlocalizedName("Lag Generator"); + } + @Override + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileLag(); + } } diff --git a/src/main/java/mcp/mobius/opis/tools/TileDebug.java b/src/main/java/mcp/mobius/opis/tools/TileDebug.java index 8aeff26..d0487d9 100644 --- a/src/main/java/mcp/mobius/opis/tools/TileDebug.java +++ b/src/main/java/mcp/mobius/opis/tools/TileDebug.java @@ -5,20 +5,21 @@ import net.minecraft.tileentity.TileEntity; public class TileDebug extends TileEntity { - public TileDebug(){ - modOpis.log.info("============================="); - modOpis.log.info(String.format("Hello, I will be your companion debug block for the day. My ID is 0x%s", System.identityHashCode(this))); - modOpis.log.info("For a starter, let me show you who created me :"); - StackTraceElement[] cause = Thread.currentThread().getStackTrace(); - - for (StackTraceElement elem : cause){ - modOpis.log.info(String.format("%s.%s:%s", elem.getClassName(), elem.getMethodName(), elem.getLineNumber())); - } - modOpis.log.info("============================="); - - } - - @Override - public void updateEntity(){ - } + public TileDebug() { + modOpis.log.info("============================="); + modOpis.log.info(String.format( + "Hello, I will be your companion debug block for the day. My ID is 0x%s", + System.identityHashCode(this))); + modOpis.log.info("For a starter, let me show you who created me :"); + StackTraceElement[] cause = Thread.currentThread().getStackTrace(); + + for (StackTraceElement elem : cause) { + modOpis.log.info( + String.format("%s.%s:%s", elem.getClassName(), elem.getMethodName(), elem.getLineNumber())); + } + modOpis.log.info("============================="); + } + + @Override + public void updateEntity() {} } diff --git a/src/main/java/mcp/mobius/opis/tools/TileLag.java b/src/main/java/mcp/mobius/opis/tools/TileLag.java index 54f5f9d..d888df1 100644 --- a/src/main/java/mcp/mobius/opis/tools/TileLag.java +++ b/src/main/java/mcp/mobius/opis/tools/TileLag.java @@ -4,14 +4,14 @@ import net.minecraft.tileentity.TileEntity; public class TileLag extends TileEntity { - @Override - public void updateEntity(){ - if (this.worldObj.isRemote) return; - - try { - Thread.sleep(5); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + @Override + public void updateEntity() { + if (this.worldObj.isRemote) return; + + try { + Thread.sleep(5); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } }